The Open Framework for Building Agents
feat(eve)!: unify public session operation APIs (#1597)
Casey Gowrie40b09e60d920
diff --git a/.changeset/unified-session-operation-surfaces.md b/.changeset/unified-session-operation-surfaces.mdnew file mode 100644index 000000000..23cacdb26--- /dev/null+++ b/.changeset/unified-session-operation-surfaces.md@@ -0,0 +1,15 @@+---+"eve": minor+---++Replace continuation-token session APIs with fixed, ID-addressed handles and consistent channel-local operations. This is a breaking migration across the following public surfaces:++- TypeScript clients now use `client.sessions.create(input)` to start a session and `client.sessions.attach(sessionId)` to obtain a fixed handle; `client.session(...)` and continuation-token client state are removed.+- Client, eval, frontend, fixed-session, and Slack message delivery now use positional `send(message, options)`. HITL replies use the separate `respond(inputResponses, options)` method, and `message` and `inputResponses` are mutually exclusive.+- Custom channels use `from(address)` for channel-local operations, top-level `resolveSession(address)` to resolve the current owner, `attachSession(sessionId)` for an immutable session handle, and `to(channel, target)` for cross-channel delivery.+- Slack message and interaction hooks expose `ctx.send`, `ctx.respond`, `ctx.cancel`, `ctx.compact`, `ctx.clear`, `ctx.reset`, and `ctx.resolveSession`. For generic events, the target is passed in each operation's options; `ctx.receive` and `resolveActiveSession` are removed.+- Schedule handlers replace `receive(channel, { message, target, auth })` with `to(channel, target).send(message, { auth })`.+- Channel event session identity moves to `ctx.session.id`, while `session.failed` includes `sessionId` in its event data.+- The eve HTTP API keeps `POST /eve/v1/session` for creation and `POST /eve/v1/session/:sessionId` for follow-ups. Clear, compact, and reset move from continuation-token body routes to `POST /eve/v1/session/:sessionId/{clear,compact,reset}`; cancel and streaming remain ID-addressed.+- Session message and control bodies no longer accept or return continuation tokens. Accepted asynchronous work returns HTTP `202`; no-active operation results omit `sessionId`, and inactive follow-ups return HTTP `409` with `code: "session_not_active"`, available as `ClientError.code`.+- Canonical eve `onMessage` hooks can no longer drop an otherwise authorized delivery by returning `null`.diff --git a/apps/docs/registry/channel/web/app/_components/agent-chat.tsx b/apps/docs/registry/channel/web/app/_components/agent-chat.tsxindex c13a477f7..290469b52 100644--- a/apps/docs/registry/channel/web/app/_components/agent-chat.tsx+++ b/apps/docs/registry/channel/web/app/_components/agent-chat.tsx@@ -31,9 +31,8 @@ type Cancellation = {};export function AgentChat() {- const [session] = useState(() =>- new Client({ host: "", preserveCompletedSessions: true }).session(),- );+ const [client] = useState(() => new Client({ host: "" }));+ const sessionIdRef = useRef<string | undefined>(undefined);const cancellationRef = useRef<Cancellation>({ requested: false });const [cancellationError, setCancellationError] = useState<string>();const [cancellationState, setCancellationState] = useState<CancellationState>("idle");@@ -48,18 +47,26 @@ export function AgentChat() {cancellation.sentTurnId = turnId;setCancellationState("cancelling");- void session.cancel({ turnId }).catch((error: unknown) => {- if (cancellationRef.current !== cancellation) {- return;- }+ const sessionId = sessionIdRef.current;+ if (sessionId === undefined) {+ return;+ }- cancellation.requested = false;- cancellation.sentTurnId = undefined;- setCancellationError(toErrorMessage(error));- setCancellationState("idle");- });+ void client.sessions+ .attach(sessionId)+ .cancel({ turnId })+ .catch((error: unknown) => {+ if (cancellationRef.current !== cancellation) {+ return;+ }++ cancellation.requested = false;+ cancellation.sentTurnId = undefined;+ setCancellationError(toErrorMessage(error));+ setCancellationState("idle");+ });},- [session],+ [client],);const handleEvent = useCallback(@@ -75,7 +82,12 @@ export function AgentChat() {[cancelTurn],);- const agent = useEveAgent({ onEvent: handleEvent, session });+ const agent = useEveAgent({+ onEvent: handleEvent,+ onSessionChange(session) {+ sessionIdRef.current = session?.sessionId;+ },+ });const isBusy = agent.status === "submitted" || agent.status === "streaming";const isEmpty = agent.data.messages.length === 0;const errorMessage = cancellationError ?? agent.error?.message;@@ -109,7 +121,7 @@ export function AgentChat() {prepareTurn();if (message.files.length === 0) {- await agent.send({ message: text });+ await agent.send(text);return;}@@ -126,7 +138,7 @@ export function AgentChat() {});}- await agent.send({ message: parts });+ await agent.send(parts);};const composer = (@@ -172,7 +184,7 @@ export function AgentChat() {message={message}onInputResponses={(inputResponses) => {prepareTurn();- return agent.send({ inputResponses });+ return agent.respond(inputResponses);}}/>))}diff --git a/apps/fixtures/agent-tui-client/agent/channels/anchored.ts b/apps/fixtures/agent-tui-client/agent/channels/anchored.tsindex 01b6f97dc..85a156eeb 100644--- a/apps/fixtures/agent-tui-client/agent/channels/anchored.ts+++ b/apps/fixtures/agent-tui-client/agent/channels/anchored.ts@@ -51,12 +51,11 @@ export default defineChannel({};},routes: [- POST<AnchorState>("/anchor/start", async (request, { send }) => {+ POST<AnchorState>("/anchor/start", async (request, { from }) => {const body = readBody(await request.json().catch(() => ({})));const anchorToken = `thread:${body.threadId}`;- const session = await send(body.message, {+ const session = await from(`pending:${body.threadId}`).send(body.message, {auth: authFor("start", body.marker),- continuationToken: `pending:${body.threadId}`,state: initialState(anchorToken),});@@ -68,12 +67,11 @@ export default defineChannel({});}),- POST<AnchorState>("/anchor/reply", async (request, { send }) => {+ POST<AnchorState>("/anchor/reply", async (request, { from }) => {const body = readBody(await request.json().catch(() => ({})));const anchorToken = `thread:${body.threadId}`;- const session = await send(body.message, {+ const session = await from(anchorToken).send(body.message, {auth: authFor("reply", body.marker),- continuationToken: anchorToken,state: initialState(anchorToken),});@@ -89,8 +87,13 @@ export default defineChannel({channel.state.completedMessages.push(event.message ?? "");const anchorToken = channel.state.anchorToken;- if (anchorToken !== null && !channel.continuationToken.endsWith(`:${anchorToken}`)) {- channel.setContinuationToken(anchorToken);+ const continuation = channel.continuation;+ if (+ anchorToken !== null &&+ continuation !== undefined &&+ !continuation.token.endsWith(`:${anchorToken}`)+ ) {+ continuation.rekey(anchorToken);}},},diff --git a/apps/frameworks/next-multi-agent/app/page.tsx b/apps/frameworks/next-multi-agent/app/page.tsxindex 009fba6df..7bc0c3985 100644--- a/apps/frameworks/next-multi-agent/app/page.tsx+++ b/apps/frameworks/next-multi-agent/app/page.tsx@@ -57,7 +57,7 @@ function AgentPanel({const trimmed = message.trim();if (trimmed.length === 0 || isBusy) return;setMessage("");- await eve.send({ message: trimmed });+ await eve.send(trimmed);};return (diff --git a/apps/frameworks/next/app/_chat/App.tsx b/apps/frameworks/next/app/_chat/App.tsxindex fee46a885..489e4601f 100644--- a/apps/frameworks/next/app/_chat/App.tsx+++ b/apps/frameworks/next/app/_chat/App.tsx@@ -67,8 +67,8 @@ export function App() {const hasComposerText = composerInput.trim().length > 0;const hasConversation = turns.length > 0 || isComposeInProgress;const conversationActivityKey = [- agent.session.sessionId ?? "new-thread",- String(agent.session.streamIndex),+ agent.session?.sessionId ?? "new-thread",+ String(agent.session?.streamIndex ?? 0),String(agent.events.length),agent.status,].join(":");@@ -107,10 +107,10 @@ export function App() {setComposerError(undefined);setComposerInput("");- if (agent.session.sessionId === undefined && agent.data.turns.length > 0) {+ if (agent.session?.sessionId === undefined && agent.data.turns.length > 0) {agent.reset();}- await agent.send({ message });+ await agent.send(message);};const isSendable = !isComposeInProgress && hasComposerText;diff --git a/apps/frameworks/next/app/_chat/thread-state.ts b/apps/frameworks/next/app/_chat/thread-state.tsdeleted file mode 100644index 900afceb1..000000000--- a/apps/frameworks/next/app/_chat/thread-state.ts+++ /dev/null@@ -1,269 +0,0 @@-import { buildTraceTurnsFromTranscript } from "./trace";-import type { ChatSessionCursor, ThreadState, TranscriptStreamEvent } from "./types";--const SESSION_STREAM_CONTENT_TYPE = "application/x-ndjson; charset=utf-8";-const SESSION_STREAM_INITIAL_TIMEOUT_MS = 5_000;-const SESSION_STREAM_REPLAY_IDLE_TIMEOUT_MS = 300;--export const EMPTY_CHAT_SESSION: ChatSessionCursor = {- streamIndex: 0,-};--function createSessionTranscriptPath(sessionId: string): string {- return `/eve/v1/session/${encodeURIComponent(sessionId)}/stream`;-}--function parseTranscriptStreamEvent(line: string): TranscriptStreamEvent {- const parsed = JSON.parse(line) as unknown;-- if (- parsed === null ||- typeof parsed !== "object" ||- !("type" in parsed) ||- typeof parsed.type !== "string"- ) {- throw new Error("Received an invalid transcript event.");- }-- return parsed as TranscriptStreamEvent;-}--function createIdleTimeout(timeoutMs: number): {- readonly cancel: () => void;- readonly promise: Promise<"timeout">;-} {- let timeoutId: ReturnType<typeof globalThis.setTimeout> | undefined;-- return {- cancel: () => {- if (timeoutId !== undefined) {- globalThis.clearTimeout(timeoutId);- }- },- promise: new Promise((resolve) => {- timeoutId = globalThis.setTimeout(() => {- resolve("timeout");- }, timeoutMs);- }),- };-}--async function readTranscriptEvents(sessionId: string): Promise<{- readonly events: readonly TranscriptStreamEvent[];- readonly eventsRead: number;-}> {- const response = await fetch(createSessionTranscriptPath(sessionId), {- headers: {- accept: SESSION_STREAM_CONTENT_TYPE,- },- });-- if (!response.ok) {- const body = await response.text();- throw new Error(body.length > 0 ? body : `Request failed (${response.status}).`);- }-- if (response.body === null) {- throw new Error("Transcript response did not include a readable body.");- }-- const reader = response.body.getReader();- const decoder = new TextDecoder();- const events: TranscriptStreamEvent[] = [];- let buffer = "";- let reachedStreamEnd = false;- let sawEvent = false;-- const pushLine = (line: string): void => {- events.push(parseTranscriptStreamEvent(line));- sawEvent = true;- };-- try {- while (true) {- const timeoutMs = sawEvent- ? SESSION_STREAM_REPLAY_IDLE_TIMEOUT_MS- : SESSION_STREAM_INITIAL_TIMEOUT_MS;- const idleTimeout = createIdleTimeout(timeoutMs);- const result = await Promise.race([reader.read(), idleTimeout.promise]);- idleTimeout.cancel();-- if (result === "timeout") {- break;- }-- const { done, value } = result;-- if (done) {- buffer += decoder.decode();- reachedStreamEnd = true;- break;- }-- buffer += decoder.decode(value, {- stream: true,- });-- while (true) {- const newlineIndex = buffer.indexOf("\n");- if (newlineIndex === -1) {- break;- }-- const line = buffer.slice(0, newlineIndex).trim();- buffer = buffer.slice(newlineIndex + 1);-- if (line.length === 0) {- continue;- }-- pushLine(line);- }- }-- if (reachedStreamEnd) {- const trailingLine = buffer.trim();- if (trailingLine.length > 0) {- pushLine(trailingLine);- }- }- } finally {- await reader.cancel().catch(() => undefined);- reader.releaseLock();- }-- return {- events,- eventsRead: events.length,- };-}--/**- * Loads the transcript-derived thread state from the persisted session stream.- */-export async function loadThreadViewFromTranscript(sessionId: string): Promise<{- readonly eventsRead: number;- readonly thread: ThreadState;-}> {- const transcript = await readTranscriptEvents(sessionId);- const turns = buildTraceTurnsFromTranscript(transcript.events);-- return {- eventsRead: transcript.eventsRead,- thread: {- sessionId,- streamIndex: transcript.eventsRead,- turns,- },- };-}--/**- * Rebuilds one thread from the already-rendered transcript prefix plus the- * newest streamed events for the active turn.- */-export function mergeThreadStreamEvents(input: {- readonly baseThread?: ThreadState;- readonly sessionId: string;- readonly startIndex: number;- readonly streamEvents: readonly TranscriptStreamEvent[];-}): ThreadState {- const existingEvents = input.baseThread?.turns.flatMap((turn) => turn.events) ?? [];- const transcriptEvents = [- ...existingEvents.slice(0, Math.min(input.startIndex, existingEvents.length)),- ...input.streamEvents,- ];-- return {- continuationToken: input.baseThread?.continuationToken,- sessionId: input.sessionId,- streamIndex: input.startIndex + input.streamEvents.length,- turns: buildTraceTurnsFromTranscript(transcriptEvents),- };-}--/**- * Returns the continuation token that should stay attached to the active- * thread while a turn is streaming.- */-export function resolveContinuationToken(input: {- readonly currentContinuationToken?: string;- readonly nextContinuationToken?: string;-}): string | undefined {- if (typeof input.nextContinuationToken === "string" && input.nextContinuationToken.length > 0) {- return input.nextContinuationToken;- }-- return input.currentContinuationToken;-}--/**- * Seeds the in-memory streaming thread with the live continuation token so the- * active session does not briefly look replay-only while events are arriving.- */-export function createStreamingThreadBase(input: {- readonly baseThread?: ThreadState;- readonly continuationToken?: string;- readonly sessionId: string;- readonly startIndex: number;-}): ThreadState | undefined {- if (input.baseThread !== undefined) {- if (- input.continuationToken === undefined ||- input.baseThread.continuationToken === input.continuationToken- ) {- return input.baseThread;- }-- return {- continuationToken: input.continuationToken,- sessionId: input.baseThread.sessionId,- streamIndex: input.baseThread.streamIndex,- turns: input.baseThread.turns,- };- }-- if (input.continuationToken === undefined) {- return undefined;- }-- return {- continuationToken: input.continuationToken,- sessionId: input.sessionId,- streamIndex: input.startIndex,- turns: [],- };-}--/**- * Returns whether the selected thread should be hydrated from cached or- * persisted history for the current render pass.- */-export function shouldHydrateSelectedThread(input: {- readonly isComposeInProgress: boolean;- readonly lastHydratedSessionId: string | null;- readonly selectedSessionId: string | null;-}): boolean {- return (- input.selectedSessionId !== null &&- input.selectedSessionId !== input.lastHydratedSessionId &&- !input.isComposeInProgress- );-}--/**- * Returns whether the selected thread is a history-only replay that cannot- * accept a follow-up message.- */-export function isReplayOnlyThread(input: {- readonly isComposeInProgress: boolean;- readonly selectedSessionId: string | null;- readonly selectedThreadState?: ThreadState;-}): boolean {- return (- input.selectedSessionId !== null &&- input.selectedThreadState !== undefined &&- input.selectedThreadState.continuationToken === undefined &&- !input.isComposeInProgress- );-}diff --git a/apps/frameworks/next/app/_chat/types.ts b/apps/frameworks/next/app/_chat/types.tsindex 991f56067..9a914ca95 100644--- a/apps/frameworks/next/app/_chat/types.ts+++ b/apps/frameworks/next/app/_chat/types.ts@@ -1,43 +1,3 @@-import type { AgentInformation } from "./workflow-api";--export type ComposeState =- | {- readonly status: "idle";- }- | {- readonly status: "sending";- }- | {- readonly status: "streaming";- }- | {- readonly message: string;- readonly status: "error";- };--export type AgentInfoState =- | {- readonly status: "idle";- }- | {- readonly status: "loading";- }- | {- readonly message: string;- readonly status: "error";- }- | {- readonly info: AgentInformation;- readonly status: "ready";- readonly updatedAt: number;- };--export interface ChatSessionCursor {- readonly continuationToken?: string;- readonly sessionId?: string;- readonly streamIndex: number;-}-export interface TranscriptMessageReceivedEvent {readonly data: {readonly message: string;@@ -176,14 +136,3 @@ export interface TraceTurn {readonly turnId: string;readonly userMessage?: string;}--/**- * One restored thread in the local web UI, expressed directly in reconstructed- * transcript turns so chat and debugger can render from the same source.- */-export interface ThreadState {- readonly continuationToken?: string;- readonly sessionId: string;- readonly streamIndex: number;- readonly turns: readonly TraceTurn[];-}diff --git a/apps/frameworks/next/app/_chat/workflow-api.ts b/apps/frameworks/next/app/_chat/workflow-api.tsdeleted file mode 100644index ca646b1c7..000000000--- a/apps/frameworks/next/app/_chat/workflow-api.ts+++ /dev/null@@ -1,804 +0,0 @@-const SESSION_API_PATH = "/eve/v1/session";-const SESSION_STREAM_ROUTE_PREFIX = "/eve/v1/session";-const INFO_API_PATH = "/eve/v1/info";--function createSessionContinuePath(sessionId: string): string {- return `${SESSION_API_PATH}/${encodeURIComponent(sessionId)}`;-}--const EVE_SESSION_ID_HEADER = "x-eve-session-id";-const MESSAGE_STREAM_CONTENT_TYPE = "application/x-ndjson; charset=utf-8";-const DEFAULT_SESSION_TURN_TIMEOUT_MS = 60_000;--export interface SendMessageInput {- readonly continuationToken?: string;- readonly message: string;- readonly sessionId?: string;-}--export interface SentMessageResult {- readonly continuationToken?: string;- readonly sessionId?: string;-}--export interface AgentInfoSource {- readonly exportName?: string;- readonly logicalPath: string;- readonly sourceId?: string;- readonly sourceKind: string;-}--export interface AgentInfoToolEntry extends AgentInfoSource {- readonly description: string;- readonly hasAuth: boolean;- readonly hasExecute: boolean;- readonly hasModelOutputProjection: boolean;- readonly hasOutputSchema: boolean;- readonly inputSchema: unknown;- readonly name: string;- readonly origin: "authored" | "framework";- readonly outputSchema: unknown;- readonly replacesFrameworkTool: boolean;- readonly requiresApproval: boolean;-}--export interface AgentInfoFrameworkToolEntry extends AgentInfoToolEntry {- readonly disabledByAuthor: boolean;- readonly replacedByAuthoredTool: boolean;- readonly status: "active" | "disabled" | "replaced";-}--export interface AgentInfoDynamicResolverEntry extends AgentInfoSource {- readonly eventNames: readonly string[];- readonly origin: "authored" | "framework";- readonly slug: string;-}--export interface AgentInfoSkillEntry extends AgentInfoSource {- readonly description: string;- readonly license?: string;- readonly markdown: string;- readonly metadata?: Readonly<Record<string, string>>;- readonly name: string;-}--export interface AgentInfoInstructionsEntry extends AgentInfoSource {- readonly markdown: string;- readonly name: string;-}--export interface AgentInfoScheduleEntry extends AgentInfoSource {- readonly cron: string;- readonly hasRun: boolean;- readonly markdown?: string;- readonly name: string;-}--export interface AgentInfoSubagentEntry extends AgentInfoSource {- readonly description: string;- readonly entryPath: string;- readonly name: string;- readonly nodeId: string;- readonly rootPath: string;- readonly summary: {- readonly channels: number;- readonly connections: number;- readonly hooks: number;- readonly instructions: boolean;- readonly schedules: number;- readonly skills: number;- readonly tools: number;- };-}--export interface AgentInfoChannelEntry extends AgentInfoSource {- readonly adapterKind?: string;- readonly method: string;- readonly name: string;- readonly origin: "authored" | "framework";- readonly urlPath: string;-}--export interface AgentInfoFrameworkChannelEntry extends AgentInfoChannelEntry {- readonly disabledByAuthor: boolean;- readonly replacedByAuthoredChannel: boolean;- readonly status: "active" | "disabled" | "replaced";-}--export interface AgentInfoConnectionEntry extends AgentInfoSource {- readonly connectionName: string;- readonly description: string;- readonly hasApproval: boolean;- readonly hasAuthorization: boolean;- readonly hasHeaders: boolean;- readonly protocol: string;- readonly toolFilter?: unknown;- readonly url: string;-}--export interface AgentInfoHookEntry extends AgentInfoSource {- readonly eventNames: readonly string[];- readonly slug: string;-}--export interface AgentInfoSandboxEntry extends AgentInfoSource {- readonly backendKind?: string;- readonly description?: string;- readonly hasBootstrap: boolean;- readonly hasOnSession: boolean;- readonly revalidationKey?: string;- readonly sourceHash?: string;-}--export interface AgentInformation {- readonly agent: {- readonly agentRoot: string;- readonly appRoot: string;- readonly configSource?: AgentInfoSource;- readonly description?: string;- readonly model: {- readonly contextWindowTokens?: number;- readonly id: string;- readonly providerOptions?: unknown;- readonly source?: AgentInfoSource;- };- readonly name: string;- readonly outputSchema?: unknown;- };- readonly channels: {- readonly authored: readonly AgentInfoChannelEntry[];- readonly available: readonly AgentInfoChannelEntry[];- readonly disabledFramework: readonly string[];- readonly framework: readonly AgentInfoFrameworkChannelEntry[];- };- readonly connections: readonly AgentInfoConnectionEntry[];- readonly diagnostics: {- readonly discoveryErrors: number;- readonly discoveryWarnings: number;- };- readonly hooks: readonly AgentInfoHookEntry[];- readonly instructions: {- readonly dynamic: readonly AgentInfoDynamicResolverEntry[];- readonly static: AgentInfoInstructionsEntry | null;- };- readonly kind: "eve-agent-info";- readonly mode: "development" | "production";- readonly sandbox: AgentInfoSandboxEntry | null;- readonly schedules: readonly AgentInfoScheduleEntry[];- readonly skills: {- readonly dynamic: readonly AgentInfoDynamicResolverEntry[];- readonly static: readonly AgentInfoSkillEntry[];- };- readonly subagents: {- readonly local: readonly AgentInfoSubagentEntry[];- readonly total: number;- };- readonly tools: {- readonly authored: readonly AgentInfoToolEntry[];- readonly available: readonly AgentInfoToolEntry[];- readonly disabledFramework: readonly string[];- readonly dynamic: readonly AgentInfoDynamicResolverEntry[];- readonly framework: readonly AgentInfoFrameworkToolEntry[];- readonly reserved: readonly string[];- };- readonly version: 1;- readonly workflow: {- readonly enabled: boolean;- readonly toolName: string;- };- readonly workspace: {- readonly resourceRoot: unknown;- readonly rootEntries: readonly string[];- };-}--export type MessageTurnStatus = "completed" | "failed" | "waiting";--export interface MessageTurnResult {- readonly eventsRead: number;- readonly failureMessage?: string;- readonly message?: string;- readonly status: MessageTurnStatus;-}--interface ApiErrorPayload {- readonly error?: string;-}--interface MessageCompletedStreamEvent {- readonly data: {- readonly finishReason?: string;- readonly message: string | null;- };- readonly type: "message.completed";-}--interface SessionFailedStreamEvent {- readonly data: {- readonly message: string;- };- readonly type: "session.failed";-}--interface SessionCompletedStreamEvent {- readonly type: "session.completed";-}--interface SessionWaitingStreamEvent {- readonly type: "session.waiting";-}--type MessageStreamEvent =- | MessageCompletedStreamEvent- | SessionCompletedStreamEvent- | SessionFailedStreamEvent- | SessionWaitingStreamEvent- | {- readonly data?: unknown;- readonly type: string;- };--function isRecord(value: unknown): value is Record<string, unknown> {- return value !== null && typeof value === "object";-}--function stringifyError(error: unknown): string {- if (error instanceof Error) {- return error.message;- }-- return String(error);-}--function parseApiError(statusCode: number, body: unknown): Error {- if (isRecord(body)) {- const payload = body as ApiErrorPayload;- if (typeof payload.error === "string" && payload.error.length > 0) {- return new Error(payload.error);- }- }-- return new Error(`Request failed (${statusCode}).`);-}--function parseResponseTextAsJson(value: string): unknown {- try {- return JSON.parse(value) as unknown;- } catch {- return undefined;- }-}--async function requestJson<T>(path: string, init?: RequestInit): Promise<T> {- const response = await fetch(path, {- ...init,- headers: {- accept: "application/json",- ...init?.headers,- },- });-- const body = (await response.json()) as unknown;-- if (!response.ok) {- throw parseApiError(response.status, body);- }-- return body as T;-}--function expectString(value: unknown, path: string): string {- if (typeof value !== "string") {- throw new Error(`Invalid JSON response for ${path}.`);- }-- return value;-}--function expectNumber(value: unknown, path: string): number {- if (typeof value !== "number") {- throw new Error(`Invalid JSON response for ${path}.`);- }-- return value;-}--function expectBoolean(value: unknown, path: string): boolean {- if (typeof value !== "boolean") {- throw new Error(`Invalid JSON response for ${path}.`);- }-- return value;-}--function expectRecord(value: unknown, path: string): Record<string, unknown> {- if (!isRecord(value)) {- throw new Error(`Invalid JSON response for ${path}.`);- }-- return value;-}--function expectOptionalString(value: unknown, path: string): void {- if (value !== undefined && typeof value !== "string") {- throw new Error(`Invalid JSON response for ${path}.`);- }-}--function expectOrigin(value: unknown): "authored" | "framework" {- if (value !== "authored" && value !== "framework") {- throw new Error(`Invalid JSON response for ${INFO_API_PATH}.`);- }-- return value;-}--function expectArray(value: unknown, path: string): readonly unknown[] {- if (!Array.isArray(value)) {- throw new Error(`Invalid JSON response for ${path}.`);- }-- return value;-}--function assertSource(value: unknown): Record<string, unknown> {- const source = expectRecord(value, INFO_API_PATH);- expectOptionalString(source.exportName, INFO_API_PATH);- expectString(source.logicalPath, INFO_API_PATH);- expectOptionalString(source.sourceId, INFO_API_PATH);- expectString(source.sourceKind, INFO_API_PATH);- return source;-}--function assertNamedSource(value: unknown): Record<string, unknown> {- const source = assertSource(value);- expectString(source.name, INFO_API_PATH);- return source;-}--function assertDynamicResolvers(value: unknown): void {- for (const entry of expectArray(value, INFO_API_PATH)) {- const resolver = assertSource(entry);- expectArray(resolver.eventNames, INFO_API_PATH).forEach((eventName) => {- expectString(eventName, INFO_API_PATH);- });- expectOrigin(resolver.origin);- expectString(resolver.slug, INFO_API_PATH);- }-}--function assertToolEntries(value: unknown): void {- for (const entry of expectArray(value, INFO_API_PATH)) {- const tool = assertNamedSource(entry);- expectString(tool.description, INFO_API_PATH);- expectBoolean(tool.hasAuth, INFO_API_PATH);- expectBoolean(tool.hasExecute, INFO_API_PATH);- expectBoolean(tool.hasModelOutputProjection, INFO_API_PATH);- expectBoolean(tool.hasOutputSchema, INFO_API_PATH);- expectOrigin(tool.origin);- expectBoolean(tool.replacesFrameworkTool, INFO_API_PATH);- expectBoolean(tool.requiresApproval, INFO_API_PATH);- }-}--function assertChannelEntries(value: unknown): void {- for (const entry of expectArray(value, INFO_API_PATH)) {- const channel = assertNamedSource(entry);- expectOptionalString(channel.adapterKind, INFO_API_PATH);- expectString(channel.method, INFO_API_PATH);- expectOrigin(channel.origin);- expectString(channel.urlPath, INFO_API_PATH);- }-}--function ensureAgentInformation(value: unknown): AgentInformation {- const payload = expectRecord(value, INFO_API_PATH);- if (- expectString(payload.kind, INFO_API_PATH) !== "eve-agent-info" ||- expectNumber(payload.version, INFO_API_PATH) !== 1- ) {- throw new Error(`Invalid JSON response for ${INFO_API_PATH}.`);- }- const mode = expectString(payload.mode, INFO_API_PATH);- if (mode !== "development" && mode !== "production") {- throw new Error(`Invalid JSON response for ${INFO_API_PATH}.`);- }-- const agent = expectRecord(payload.agent, INFO_API_PATH);- expectString(agent.agentRoot, INFO_API_PATH);- expectString(agent.appRoot, INFO_API_PATH);- expectOptionalString(agent.description, INFO_API_PATH);- if (agent.configSource !== undefined) {- assertSource(agent.configSource);- }-- const model = expectRecord(agent.model, INFO_API_PATH);- expectString(model.id, INFO_API_PATH);- if (model.contextWindowTokens !== undefined) {- expectNumber(model.contextWindowTokens, INFO_API_PATH);- }- if (model.source !== undefined) {- assertSource(model.source);- }- expectString(agent.name, INFO_API_PATH);-- const channels = expectRecord(payload.channels, INFO_API_PATH);- assertChannelEntries(channels.authored);- assertChannelEntries(channels.available);- expectArray(channels.disabledFramework, INFO_API_PATH).forEach((name) => {- expectString(name, INFO_API_PATH);- });- assertChannelEntries(channels.framework);-- expectArray(payload.connections, INFO_API_PATH).forEach((entry) => {- const connection = assertSource(entry);- expectString(connection.connectionName, INFO_API_PATH);- expectString(connection.description, INFO_API_PATH);- expectBoolean(connection.hasApproval, INFO_API_PATH);- expectBoolean(connection.hasAuthorization, INFO_API_PATH);- expectBoolean(connection.hasHeaders, INFO_API_PATH);- expectString(connection.protocol, INFO_API_PATH);- expectString(connection.url, INFO_API_PATH);- });-- const diagnostics = expectRecord(payload.diagnostics, INFO_API_PATH);- expectNumber(diagnostics.discoveryErrors, INFO_API_PATH);- expectNumber(diagnostics.discoveryWarnings, INFO_API_PATH);-- expectArray(payload.hooks, INFO_API_PATH).forEach((entry) => {- const hook = assertSource(entry);- expectArray(hook.eventNames, INFO_API_PATH);- expectString(hook.slug, INFO_API_PATH);- });-- const instructions = expectRecord(payload.instructions, INFO_API_PATH);- assertDynamicResolvers(instructions.dynamic);- if (instructions.static !== null) {- const staticInstructions = assertNamedSource(instructions.static);- expectString(staticInstructions.markdown, INFO_API_PATH);- }-- if (payload.sandbox !== null) {- const sandbox = assertSource(payload.sandbox);- expectOptionalString(sandbox.backendKind, INFO_API_PATH);- expectOptionalString(sandbox.description, INFO_API_PATH);- expectBoolean(sandbox.hasBootstrap, INFO_API_PATH);- expectBoolean(sandbox.hasOnSession, INFO_API_PATH);- }-- expectArray(payload.schedules, INFO_API_PATH).forEach((entry) => {- const schedule = assertNamedSource(entry);- expectString(schedule.cron, INFO_API_PATH);- expectBoolean(schedule.hasRun, INFO_API_PATH);- expectOptionalString(schedule.markdown, INFO_API_PATH);- });-- const skills = expectRecord(payload.skills, INFO_API_PATH);- expectArray(skills.static, INFO_API_PATH).forEach((entry) => {- const skill = assertNamedSource(entry);- expectString(skill.description, INFO_API_PATH);- expectString(skill.markdown, INFO_API_PATH);- });- assertDynamicResolvers(skills.dynamic);-- const subagents = expectRecord(payload.subagents, INFO_API_PATH);- expectArray(subagents.local, INFO_API_PATH).forEach((entry) => {- const subagent = assertNamedSource(entry);- expectString(subagent.description, INFO_API_PATH);- expectString(subagent.entryPath, INFO_API_PATH);- expectString(subagent.nodeId, INFO_API_PATH);- expectString(subagent.rootPath, INFO_API_PATH);- });- expectNumber(subagents.total, INFO_API_PATH);-- const tools = expectRecord(payload.tools, INFO_API_PATH);- assertToolEntries(tools.authored);- assertToolEntries(tools.available);- expectArray(tools.disabledFramework, INFO_API_PATH).forEach((name) => {- expectString(name, INFO_API_PATH);- });- assertDynamicResolvers(tools.dynamic);- assertToolEntries(tools.framework);- expectArray(tools.reserved, INFO_API_PATH).forEach((name) => {- expectString(name, INFO_API_PATH);- });-- const workflow = expectRecord(payload.workflow, INFO_API_PATH);- expectBoolean(workflow.enabled, INFO_API_PATH);- expectString(workflow.toolName, INFO_API_PATH);-- const workspace = expectRecord(payload.workspace, INFO_API_PATH);- expectArray(workspace.rootEntries, INFO_API_PATH).forEach((entry) => {- expectString(entry, INFO_API_PATH);- });-- return value as AgentInformation;-}--function createSessionMessageStreamPath(sessionId: string): string {- return `${SESSION_STREAM_ROUTE_PREFIX}/${encodeURIComponent(sessionId)}/stream`;-}--function resolveRuntimeOrigin(): string {- const location = globalThis.location;-- if (location && typeof location.origin === "string" && location.origin.length > 0) {- return location.origin;- }-- return "http://localhost";-}--function resolveSessionMessageStreamUrl(input: {- readonly sessionId: string;- readonly startIndex?: number;-}): string {- const path = createSessionMessageStreamPath(input.sessionId);- const url = new URL(path, resolveRuntimeOrigin());-- if (typeof input.startIndex === "number" && Number.isInteger(input.startIndex)) {- if (input.startIndex > 0) {- url.searchParams.set("startIndex", String(input.startIndex));- }- }-- return url.toString();-}--function parseMessageStreamEvent(line: string): MessageStreamEvent {- const parsed = JSON.parse(line) as unknown;-- if (!isRecord(parsed) || typeof parsed.type !== "string") {- throw new Error("Received an invalid message stream event.");- }-- return parsed as MessageStreamEvent;-}--function isMessageCompletedEvent(event: MessageStreamEvent): event is MessageCompletedStreamEvent {- if (event.type !== "message.completed") {- return false;- }-- return isRecord(event.data) && "message" in event.data;-}--function isSessionFailedEvent(event: MessageStreamEvent): event is SessionFailedStreamEvent {- if (event.type !== "session.failed") {- return false;- }-- return isRecord(event.data) && "message" in event.data;-}--/**- * Loads the package-owned agent inspection payload.- */-export async function loadAgentInformation(): Promise<AgentInformation> {- return ensureAgentInformation(await requestJson<unknown>(INFO_API_PATH));-}--/**- * Starts or resumes one message turn. When `sessionId` and- * `continuationToken` are both present the call resumes that session via- * `POST /eve/v1/session/:sessionId`; otherwise it opens a new session via- * `POST /eve/v1/session`.- */-export async function sendMessage(input: SendMessageInput): Promise<SentMessageResult> {- const isContinue =- typeof input.sessionId === "string" &&- input.sessionId.length > 0 &&- typeof input.continuationToken === "string" &&- input.continuationToken.length > 0;-- const path = isContinue ? createSessionContinuePath(input.sessionId as string) : SESSION_API_PATH;-- const body: {- continuationToken?: string;- message: string;- } = {- message: input.message,- };-- if (isContinue) {- body.continuationToken = input.continuationToken as string;- }-- const response = await fetch(path, {- body: JSON.stringify(body),- headers: {- accept: "application/json",- "content-type": "application/json",- },- method: "POST",- });-- const payload = (await response.json()) as unknown;-- if (!response.ok) {- throw parseApiError(response.status, payload);- }-- if (!isRecord(payload)) {- throw new Error(`Invalid JSON response for ${path}.`);- }-- const sessionIdHeader = response.headers.get(EVE_SESSION_ID_HEADER);- const continuationToken = payload.continuationToken;- const sessionId = payload.sessionId;-- const result: {- continuationToken?: string;- sessionId?: string;- } = {};-- if (typeof sessionIdHeader === "string" && sessionIdHeader.length > 0) {- result.sessionId = sessionIdHeader;- } else if (typeof sessionId === "string" && sessionId.length > 0) {- result.sessionId = sessionId;- }-- if (typeof continuationToken === "string" && continuationToken.length > 0) {- result.continuationToken = continuationToken;- }-- return result;-}--/**- * Reads one session stream until the current turn reaches a boundary event.- */-export async function readSessionTurn(input: {- readonly onEvent?: (- event: MessageStreamEvent,- info: {- readonly eventsRead: number;- },- ) => void;- readonly sessionId: string;- readonly startIndex?: number;- readonly timeoutMs?: number;-}): Promise<MessageTurnResult> {- const controller = new AbortController();- const timeoutMs = input.timeoutMs ?? DEFAULT_SESSION_TURN_TIMEOUT_MS;- const timeoutId = globalThis.setTimeout(() => {- controller.abort();- }, timeoutMs);-- try {- const streamUrl = resolveSessionMessageStreamUrl({- sessionId: input.sessionId,- startIndex: input.startIndex,- });- const response = await fetch(streamUrl, {- headers: {- accept: MESSAGE_STREAM_CONTENT_TYPE,- },- signal: controller.signal,- });-- if (!response.ok) {- const body = await response.text();- const parsedBody = parseResponseTextAsJson(body);- if (parsedBody !== undefined) {- throw parseApiError(response.status, parsedBody);- }- throw new Error(body.length > 0 ? body : `Request failed (${response.status}).`);- }-- if (response.body === null) {- throw new Error("Message stream response did not include a readable body.");- }-- const reader = response.body.getReader();- const decoder = new TextDecoder();- let buffer = "";- let eventsRead = 0;- let failureMessage: string | undefined;- let message: string | undefined;- let status: MessageTurnStatus | null = null;-- const pushLine = (line: string): void => {- const event = parseMessageStreamEvent(line);- eventsRead += 1;- input.onEvent?.(event, { eventsRead });-- if (isMessageCompletedEvent(event)) {- const finishReason = event.data.finishReason;- if (finishReason !== "tool-calls") {- const completedMessage = event.data.message;- if (typeof completedMessage === "string" && completedMessage.length > 0) {- message = completedMessage;- }- }- return;- }-- if (isSessionFailedEvent(event)) {- if (typeof event.data.message === "string" && event.data.message.length > 0) {- failureMessage = event.data.message;- }- status = "failed";- return;- }-- if (event.type === "session.completed") {- status = "completed";- return;- }-- if (event.type === "session.waiting") {- status = "waiting";- }- };-- try {- while (status === null) {- const { done, value } = await reader.read();-- if (done) {- buffer += decoder.decode();- break;- }-- if (value !== undefined) {- buffer += decoder.decode(value, {- stream: true,- });- }-- while (status === null) {- const newlineIndex = buffer.indexOf("\n");- if (newlineIndex === -1) {- break;- }-- const line = buffer.slice(0, newlineIndex).trim();- buffer = buffer.slice(newlineIndex + 1);-- if (line.length === 0) {- continue;- }-- pushLine(line);- }- }-- if (status === null) {- const trailingLine = buffer.trim();- if (trailingLine.length > 0) {- pushLine(trailingLine);- }- }- } finally {- await reader.cancel().catch(() => undefined);- reader.releaseLock();- }-- if (status === null) {- throw new Error("Message stream ended before a turn boundary event was received.");- }-- return {- eventsRead,- failureMessage,- message,- status,- };- } catch (error) {- if (error instanceof DOMException && error.name === "AbortError") {- throw new Error(`Timed out after waiting ${timeoutMs}ms for a session response.`);- }-- throw error;- } finally {- globalThis.clearTimeout(timeoutId);- }-}--/**- * Returns a stable, user-facing error string for UI surfaces.- */-export function toErrorMessage(error: unknown): string {- return stringifyError(error);-}diff --git a/apps/frameworks/nuxt/app/components/EveAgentConsole.vue b/apps/frameworks/nuxt/app/components/EveAgentConsole.vueindex 67befc0c3..56764b015 100644--- a/apps/frameworks/nuxt/app/components/EveAgentConsole.vue+++ b/apps/frameworks/nuxt/app/components/EveAgentConsole.vue@@ -1,7 +1,7 @@<script setup lang="ts">import type { EveDynamicToolPart, EveMessagePart } from "eve/vue";-const { data, status, error, send, stop } = useEveAgent();+const { data, status, error, respond, send, stop } = useEveAgent();type EveFilePart = Extract<EveMessagePart, { type: "file" }>;@@ -37,7 +37,7 @@ function submitMessage() {const text = messageText.value.trim();if (!text || isBusy.value) return;messageText.value = "";- void send({ message: text });+ void send(text);}function onKeydown(e: KeyboardEvent) {@@ -54,7 +54,7 @@ function handleInputResponses(readonly text?: string;}[],) {- void send({ inputResponses: responses });+ void respond(responses);}function partKey(part: EveMessagePart, index: number): string {diff --git a/apps/frameworks/sveltekit/src/lib/EveAgentConsole.svelte b/apps/frameworks/sveltekit/src/lib/EveAgentConsole.svelteindex 2d30b6e15..547e49e96 100644--- a/apps/frameworks/sveltekit/src/lib/EveAgentConsole.svelte+++ b/apps/frameworks/sveltekit/src/lib/EveAgentConsole.svelte@@ -45,7 +45,7 @@const text = messageText.trim();if (!text || isBusy) return;messageText = "";- void agent.send({ message: text });+ void agent.send(text);}function onKeydown(e: KeyboardEvent) {@@ -62,7 +62,7 @@readonly text?: string;}[],) {- void agent.send({ inputResponses: responses });+ void agent.respond(responses);}function partKey(part: EveMessagePart, index: number): string {diff --git a/docs/README.md b/docs/README.mdindex cfe9ca7ef..194af436a 100644--- a/docs/README.md+++ b/docs/README.md@@ -86,21 +86,21 @@ eve then gives you:The public surface stays filesystem-first, but the implementation model underneath is still useful toknow:-- channels normalize inbound transport input and define the `continuationToken`+- channels normalize inbound transport input and map platform addresses to sessions- the harness does one unit of AI work and decides whether to continue, wait, or finish- the runtime persists session state, streams events, and owns workflow orchestration-That is why eve exposes two identifiers:--- `continuationToken` for the next user message-- `sessionId` for streaming and inspection+The default HTTP API exposes one durable `sessionId` for messages, controls, and+streaming. Platform channels additionally own channel-local continuation+addresses so a Slack thread or custom conversation ID can point at its current+session without leaking that routing identity into the HTTP client contract.## How to use these docs- Start with the authored filesystem shape and `agent.ts`.- Then add runtime surfaces in this order: skills, tools, workspace, sandbox, channels.- Then learn the durable runtime model: HITL, session context, sessions, streaming, and- continuation-token follow-ups.+ ID-addressed follow-ups and channel address routing.- Then add advanced features: subagents, schedules, route protection, deployment.## Good companions in this repodiff --git a/docs/channels/chat-sdk.mdx b/docs/channels/chat-sdk.mdxindex 79799d8c9..f63b25327 100644--- a/docs/channels/chat-sdk.mdx+++ b/docs/channels/chat-sdk.mdx@@ -177,14 +177,13 @@ chatSdkChannel({### Proactive sessions-Start a session without an inbound webhook through `channel.receive({ message, target, auth })` — from a schedule `run` handler, or `args.receive(channel, ...)` from another channel. The target is a serialized Chat SDK thread, or `{ threadId, adapterName }` when you only have a provider-native thread id:+Start a session without an inbound webhook through `to(channel, target).send(message, { auth })` from a schedule `run` handler, or `ctx.to(channel, target).send(message, { auth })` from another channel. The target is a serialized Chat SDK thread, or `{ threadId, adapterName }` when you only have a provider-native thread id:```ts-await channel.receive({- message: "Your weekly digest is ready.",- target: { adapterName: "resend", threadId: "resend:[email protected]" },- auth: null,-});+await to(channel, { adapterName: "resend", threadId: "resend:[email protected]" }).send(+ "Your weekly digest is ready.",+ { auth: null },+);```### Attachmentsdiff --git a/docs/channels/custom.mdx b/docs/channels/custom.mdxindex f9e048fcf..46429f624 100644--- a/docs/channels/custom.mdx+++ b/docs/channels/custom.mdx@@ -13,152 +13,120 @@ The channel file stem becomes the channel id, so `agent/channels/internal-webhoo## Define a channel-```ts+Pass the platform's conversation identity to each operation:++```ts title="agent/channels/support.ts"import { defineChannel, GET, POST } from "eve/channels";export default defineChannel({routes: [- POST("/message", async (req, { send }) => {- const body = await req.json();- const session = await send(body.message, {- auth: null,- continuationToken: body.token,- });+ POST("/threads/:threadId/messages", async (request, { from, params }) => {+ const body = await request.json();+ const source = from(params.threadId);++ if (body.message === "/new") {+ return Response.json(await source.reset({ reason: "User requested /new" }));+ }+ const session = await source.send(body.message, { auth: null });return Response.json({ sessionId: session.id });}),- GET("/sessions/:sessionId/stream", async (_req, { getSession, params }) => {- const session = getSession(params.sessionId);- const stream = await session.getEventStream();+ POST("/threads/:threadId/cancel", async (_request, { from, params }) =>+ Response.json(await from(params.threadId).cancel()),+ ),+ POST("/threads/:threadId/compact", async (_request, { from, params }) =>+ Response.json(await from(params.threadId).compact()),+ ),+ POST("/threads/:threadId/clear", async (_request, { from, params }) =>+ Response.json(await from(params.threadId).clear()),+ ),++ GET("/sessions/:sessionId/stream", async (_request, { attachSession, params }) => {+ const stream = await attachSession(params.sessionId).getEventStream();return new Response(stream, {headers: { "content-type": "application/x-ndjson; charset=utf-8" },});}),],+events: {- "message.completed"(event, channel, ctx) {- // deliver completed messages back to the surface that owns this channel+ "message.completed"(event, _channel, ctx) {+ console.log(ctx.session.id, event.message);},},});```-Declare routes with the `POST()` and `GET()` helpers. Each route handler receives the raw `Request` and a helpers object:--- `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.-- `receive(channel, ...)` hands inbound work to a different channel for cross-channel hand-off.-- `params` holds route parameters extracted from the path pattern.-- `waitUntil(promise)` extends the request lifetime for background work.-- `requestIp` is the client IP, or `null` when the host cannot provide it.--Event handlers like `"message.completed"` are declared under the `events` key. They receive `(eventData, channel, ctx)`, where `eventData` is the event payload, `channel` carries platform handles and session continuation operations, and `ctx` is the eve `SessionContext`. Every channel kind shares this signature. The one exception is `session.failed`, which receives only `(eventData, channel)` with no `ctx`.--## Cancel a turn--A stop route cancels a session's in-flight turn with the `cancel` helper, addressed by the same channel-local continuation token used with `send()`:--```ts-import { defineChannel, POST } from "eve/channels";--export default defineChannel({- routes: [- POST("/threads/:threadId/stop", async (_req, { cancel, params }) => {- const result = await cancel({ continuationToken: params.threadId });- return Response.json(result);- }),- ],-});-```--Both result statuses are successful. `"accepted"` means the cancellation request was consumed, not that the observed turn will cancel; confirmation is `turn.cancelled` followed by `session.waiting` on the event stream. `"no_active_turn"` covers an unknown token and a session with nothing to cancel — idle, parked, or already completed.+Each route receives these operation surfaces:-Semantics:+- `from(address)` binds `send`, `respond`, `cancel`, `compact`, `clear`, and `reset` to a channel-local continuation address.+- `resolveSession(address)` snapshots the session currently owning a channel-local continuation address.+- `attachSession(sessionId)` creates an I/O-free handle pinned to one durable session ID.+- `to(channel, target).send(message, options)` hands work to another authored channel.+- `params`, `waitUntil`, and `requestIp` provide request metadata and lifetime control.-- `cancel` never starts a session, sends input, or clears history. The session parks and accepts the next message normally.-- Pass `turnId` (stamped on every turn-scoped stream event) to guard against stale stop requests. A mismatched guard is consumed as a benign no-op and cannot cancel a newer turn.-- The helper addresses only this channel's sessions; it cannot cancel a session owned by another channel.-- Cancellation stops work without replacement input. Partial streamed output and completed side effects remain observable, and active local or remote subagents receive cancellation recursively.-- The route owns authentication of the inbound stop request, exactly as for `send()`.+Event handlers receive `(eventData, channel, ctx)`. `ctx.session.id` identifies+the exact session, while `channel.continuation` exposes the current address and+`rekey()` when this channel needs to move it. `session.failed` receives only+`(eventData, channel)` because it runs outside session context; its event data+contains `sessionId` directly.-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.+`channel.continuation.token` is always the channel-local address accepted by+`from()`, `resolveSession()`, and `rekey()`. Framework namespace prefixes are not+part of the authored channel API.-## Clear session context+## Channel operations and session handles-Call `clear` with the channel-local continuation token to remove a session's durable model-message history without replacing the session:+Channel operations are dynamic: every call targets whichever session currently+owns the address. Only `send()` can create a session when the address is unowned.```ts-import { defineChannel, POST } from "eve/channels";+const source = from(threadId);-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 session--Call `compact` with the channel-local continuation token to summarize durable conversation history without delivering a command to the model:--```ts-import { defineChannel, POST } from "eve/channels";+const session = await source.send("Hello", { auth });+await source.respond(inputResponses, { auth });+await source.cancel({ turnId });+await source.compact();+await source.clear();+await source.reset({ reason: "Start over" });-export default defineChannel({- routes: [- POST("/threads/:threadId/compact", async (_req, { compact, params }) => {- const result = await compact({ continuationToken: params.threadId });- return Response.json(result);- }),- ],-});+const currentSession = await resolveSession(threadId);```-`"accepted"` means the durable session queued the operation. A successful compaction emits `compaction.requested` followed by `compaction.completed`, then the operation returns through `session.waiting`. If summarization fails, the stream returns through `session.waiting` without `compaction.completed` and preserves the previous history. If a turn is active, eve runs the compaction after that turn settles; it does not cancel the turn. `"no_active_session"` means the token has no current owner. Both outcomes are successful, and compaction never starts a session or appends a synthetic user message.--## Reset a session--Identity-addressed channels can consume commands such as `/new` in their route, without sending the command to the model. Call `reset` with the same channel-local continuation token used by `send()`:+`Session` is fixed: every call targets exactly one durable ID. It never creates,+follows, or resolves a replacement.```ts-import { defineChannel, POST } from "eve/channels";--export default defineChannel({- routes: [- POST("/messages", async (request, { reset, send }) => {- const body = await request.json();+const session = attachSession(sessionId);++await session.send("Follow up", { auth });+await session.respond(inputResponses, { auth });+await session.cancel({ turnId });+await session.compact();+await session.clear();+await session.reset({ reason: "Retire this session" });+await session.getEventStream({ startIndex: 12 });+```- if (body.message.trim().toLowerCase() === "/new") {- await reset({- continuationToken: body.conversationId,- reason: "User requested /new",- });- return Response.json({ message: "Started a new conversation." });- }+Attaching does no lookup. The first operation reports whether the ID is active.+Call `resolveSession(address)` only when you explicitly need to snapshot an+address's current owner as a fixed handle.- const session = await send(body.message, {- auth: null,- continuationToken: body.conversationId,- });- return Response.json({ sessionId: session.id });- }),- ],-});-```+## Operation semantics-`reset` returns `{ status: "reset", previousSessionId }` when it observed an owner, or `{ status: "no_active_session" }` when the token was already free. Both outcomes are successful. It terminally cancels the observed workflow run and waits until its non-retained continuation hook no longer blocks reuse, so the next `send()` using the same token creates a new session with fresh history and state.+- `cancel` cooperatively stops the active turn. Confirm it with `turn.cancelled`+ followed by `session.waiting`; the session accepts another message afterward.+- `compact` summarizes model context without adding a synthetic user message. A+ success emits `compaction.requested`, `compaction.completed`, then `session.waiting`.+- `clear` removes model-message history in place. It preserves the system prompt,+ skills, tools, durable state, limits, address ownership, and session sandbox.+- `reset` terminally retires the current session. A later address `send()` creates+ a fresh session; a fixed `Session` handle remains pinned to the retired ID.-The replacement session owns a new session-scoped sandbox. eve initializes it lazily on that session's first sandbox use, so it never reuses the prior session's workspace or sandbox state. Resetting does not clear history in place, roll back tool calls, or delete the previous run or its sandbox; normal retention and backend cleanup policies still apply. Side effects or partial output that were already committed remain committed. Authenticate and deduplicate inbound command webhooks before calling this helper: a delayed duplicate `/new` can otherwise reset a newer session that has already reclaimed the same token.+Control operations never create a session. Unknown or inactive targets return a+benign no-active status. Authenticate and deduplicate command webhooks before+calling `reset`, because a delayed duplicate can retire a newer address owner.## CORS@@ -188,19 +156,19 @@ import { defineChannel, WS } from "eve/channels";export default defineChannel({routes: [- WS("/voice/ws", async (_req, { send }) => ({+ WS("/voice/ws", async (_req, { from }) => ({async message(_peer, message) {- await send(message.text(), {- auth: null,- continuationToken: "voice-demo",- });+ await from("voice-demo").send(message.text(), { auth: null });},})),],});```-`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`.+`WS()` handlers receive the same `from`, `to`, and `attachSession` operations,+`params`, `waitUntil`, and `requestIp` arguments as HTTP route handlers. 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 hatch@@ -222,7 +190,7 @@ The bridge server does not listen on its own port. It receives only upgrade even## Cross-channel hand-off-Route handlers can start a session on a different channel via `args.receive(channel, ...)`. Use this when an inbound request on one channel should pivot the conversation onto another, such as an incident webhook that opens an investigation thread in Slack.+Route handlers can start a session on a different channel via `ctx.to(channel, target).send(message, options)`. Use this when an inbound request on one channel should pivot the conversation onto another, such as an incident webhook that opens an investigation thread in Slack.```tsimport { defineChannel, POST } from "eve/channels";@@ -230,20 +198,20 @@ import slack from "./slack";export default defineChannel({routes: [- POST("/incident", async (req, args) => {+ POST("/incident", async (req, ctx) => {const incident = await req.json();- args.waitUntil(- args.receive(slack, {- message: `Investigate ${incident.reference}: ${incident.title}`,- target: { channelId: "C0123ABC" },- auth: {- authenticator: "incidentio",- principalType: "service",- principalId: incident.actor.id,- attributes: { reference: incident.reference, severity: incident.severity },- },- }),+ ctx.waitUntil(+ ctx+ .to(slack, { channelId: "C0123ABC" })+ .send(`Investigate ${incident.reference}: ${incident.title}`, {+ auth: {+ authenticator: "incidentio",+ principalType: "service",+ principalId: incident.actor.id,+ attributes: { reference: incident.reference, severity: incident.severity },+ },+ }),);return new Response("ok");@@ -254,9 +222,9 @@ export default defineChannel({Semantics:-- The target channel's authored `receive(input, { send })` hook owns the continuation-token format and initial state. Callers supply only `{ message, target, auth }`.+- The target channel's authored `receive(input, { from })` hook owns the continuation-token format and initial state. Callers supply the target to `to(...)`, then the message and auth to `send(...)`.- `auth` flows through to `session.auth.initiator` so the target's event handlers and the agent's tools can read who started the session.-- Calling `args.receive(...)` does not also start a session on the current channel. The inbound channel's response is whatever the route handler returns explicitly.+- Calling `ctx.to(...).send(...)` does not also start a session on the current channel. The inbound channel's response is whatever the route handler returns explicitly.- The first argument is the target channel module's default export. Import it directly from `agent/channels/<name>.ts`. Identity is matched by reference.## Channel metadata@@ -281,11 +249,10 @@ export default defineChannel({},routes: [- POST("/start", async (req, { send }) => {+ POST("/start", async (req, { from }) => {const body = await req.json();- await send(body.message, {+ await from(body.token).send(body.message, {auth: null,- continuationToken: body.token,state: { topic: body.topic, contextMessages: body.context, internalCounter: 0 },});@@ -306,7 +273,7 @@ When a parent agent dispatches a subagent, the framework forwards the parent's c## Continuation tokens-Each call to `send(message, { auth, continuationToken, state?, title? })` from a channel route addresses a session by its channel-local raw token. The framework prepends the channel name, derived from the file stem under `agent/channels/`, before handing the token to the runtime.+Each channel operation accepts a channel-local token. The framework prepends the channel name, derived from the file stem under `agent/channels/`, before handing the token to the runtime.```tsimport { slackContinuationToken } from "eve/channels/slack";@@ -318,11 +285,11 @@ twilioContinuationToken("+15551234567", "+15557654321"); // "+15551234567:+15557Custom channels write their own function that joins the identity fields. The framework derives nothing for you; the channel owns its token format.-When the identity that should address a session is not known until later, the channel can re-key the parked session by calling `session.setContinuationToken(...)`. Pass the channel-local raw token; the runtime preserves the current channel namespace.+When the identity that should address a session is not known until later, re-key the live address with `channel.continuation?.rekey(rawToken)`. The runtime preserves the current channel namespace.Re-keying changes the address of the current session. `reset` is different: it terminally retires the current session and makes its existing address available to a later `send()`. `cancel` is narrower still: it stops only the active turn and leaves the session, history, and continuation-token ownership intact.-The `context(state, session)` config option builds the per-step `channel` argument handed to every event handler. It receives the channel's live adapter `state` and a `SessionHandle`, and returns the channel-owned context (thread handles, API clients, late-bound callbacks). The framework injects [`ChannelSessionOps`](#define-a-channel) and passes the result as the second positional argument to each handler. Closing over `session` lets the factory register callbacks that re-key the session later. State mutations made through the returned context are written back to adapter state.+The `context(state, session)` config option builds the per-step `channel` argument handed to every event handler. It receives the channel's live adapter `state` and a `SessionHandle`, and returns the channel-owned context (thread handles, API clients, late-bound callbacks). The framework injects [`ChannelContinuationOps`](#define-a-channel) and passes the result as the second positional argument to each handler. Closing over `session` lets the factory register callbacks that re-key the address later. State mutations made through the returned context are written back to adapter state.```tsimport { defineChannel } from "eve/channels";@@ -336,7 +303,7 @@ defineChannel<{ ref: string | null }>({state,registerAnchor(ref: string) {state.ref = ref;- session.setContinuationToken(ref);+ session.continuation?.rekey(ref);},};},@@ -353,15 +320,17 @@ At the next workflow boundary, the runtime claims the new park hook before relea## File uploads-`send()` accepts `string | UserContent`. To include file attachments, pass a `UserContent` array mixing text and file parts:+`from(address).send()` accepts a `message` containing `string | UserContent`, while+`Session.send()` accepts `string | UserContent` directly. To include file+attachments, pass a `UserContent` array mixing text and file parts:```ts-await send(+await from(continuationToken).send([{ type: "text", text: body.message },{ type: "file", data: imageBytes, mediaType: "image/png" },],- { auth, continuationToken },+ { auth },);```@@ -377,8 +346,8 @@ defineChannel({},routes: [- POST("/webhook", async (req, { send }) => {- await send(+ POST("/webhook", async (req, { from }) => {+ await from(continuationToken).send([{ type: "text", text: message.text },...message.attachments.map((a) => ({@@ -387,7 +356,10 @@ defineChannel({mediaType: a.mediaType,})),],- { auth, continuationToken, state },+ {+ auth,+ state,+ },);}),],diff --git a/docs/channels/discord.mdx b/docs/channels/discord.mdxindex 6697ed15a..1376f429e 100644--- a/docs/channels/discord.mdx+++ b/docs/channels/discord.mdx@@ -90,7 +90,7 @@ HITL renders as Discord components. Confirmations and options become buttons, `d### Proactive sessions-Start a session without an inbound interaction through `receive(discord, { message, target, auth })` from a schedule `run` handler, or `args.receive(discord, ...)` from another channel. The proactive target shape is `{ channelId, conversationId?, initialMessage? }`. Either path needs a bot token, supplied by Connect or `DISCORD_BOT_TOKEN`.+Start a session without an inbound interaction through `to(discord, target).send(message, { auth })` from a schedule `run` handler, or `ctx.to(discord, target).send(message, { auth })` from another channel. The proactive target shape is `{ channelId, conversationId?, initialMessage? }`. Either path needs a bot token, supplied by Connect or `DISCORD_BOT_TOKEN`.### Attachmentsdiff --git a/docs/channels/eve.mdx b/docs/channels/eve.mdxindex 25e9fe8b2..863c6ea39 100644--- a/docs/channels/eve.mdx+++ b/docs/channels/eve.mdx@@ -20,68 +20,112 @@ export default eveChannel({## Routes-The application exposes a health route plus eve channel routes that inspect the agent, create sessions, send follow-ups, cancel turns, compact or reset sessions, and stream events:+The application exposes a health route plus eve channel routes that inspect the agent, create sessions, send follow-ups, control sessions, and stream events:-- `GET /eve/v1/health`-- `GET /eve/v1/info`-- `POST /eve/v1/session` (start a session)+- `GET /eve/v1/health` (check whether the application is reachable)+- `GET /eve/v1/info` (inspect the agent)+- `POST /eve/v1/session` (start a session and send its first message)- `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)+- `POST /eve/v1/session/:sessionId/clear` (clear the session's model history)+- `POST /eve/v1/session/:sessionId/compact` (compact the session's context)+- `POST /eve/v1/session/:sessionId/reset` (retire the session)+- `GET /eve/v1/session/:sessionId/stream` (stream events as NDJSON)-Start a session with a minimal body. The response returns `sessionId` and the `continuationToken` you reuse for follow-ups:+The session routes use only durable session IDs. Create a session explicitly, then put its returned ID in every follow-up, control, and stream path.++### Start and continue a session```bashcurl -X POST https://<deployment>/eve/v1/session \-H "Content-Type: application/json" \-d '{"message":"What is the weather in Paris?"}'-# {"continuationToken":"eve:7f3c...","ok":true,"sessionId":"ses_01h..."}+# {"ok":true,"sessionId":"wrun_A","status":"accepted"}++curl -X POST https://<deployment>/eve/v1/session/wrun_A \+ -H "Content-Type: application/json" \+ -d '{"message":"How about tomorrow?"}'+```++The first request requires `message`. A follow-up request accepts exactly one of+`message` or `inputResponses`; use the latter to answer a pending HITL request:++```bash+curl -X POST https://<deployment>/eve/v1/session/wrun_A \+ -H "Content-Type: application/json" \+ -d '{"inputResponses":[{"requestId":"req_A","optionId":"approve"}]}'```-Stream that session's events as newline-delimited JSON (`application/x-ndjson; charset=utf-8`), one event object per line:+Sending 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}`.+TypeScript clients expose the stable code as `ClientError.code`. The route never+creates or follows a replacement session.++### Stream events++Stream responses are newline-delimited JSON (`application/x-ndjson; charset=utf-8`), one event object per line:```bash-curl -N https://<deployment>/eve/v1/session/ses_01h.../stream+curl -N https://<deployment>/eve/v1/session/wrun_A/stream# {"type":"turn.started",...}# {"type":"message.appended","data":{"messageDelta":"It is ",...}}# {"type":"message.completed",...}```+### Cancel a turn+Cancel a session's in-flight turn with an empty body, or scope the cancel to the turn you observed by passing the `turnId` stamped on that turn's stream events:```bash-curl -X POST https://<deployment>/eve/v1/session/ses_01h.../cancel-# {"ok":true,"sessionId":"ses_01h...","status":"accepted"}+curl -X POST https://<deployment>/eve/v1/session/wrun_A/cancel+# {"ok":true,"sessionId":"wrun_A","status":"accepted"}+```++Cancellation is asynchronous: `"accepted"` means the live session durably queued the request. Confirm an actual cancellation 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. Content emitted before cancellation stays on the event stream, while durable model history keeps only content that had already settled. The session accepts the next message normally.++An accepted cancellation returns HTTP `202` with `sessionId`. An inactive target+returns HTTP `200` with `{"ok":true,"status":"no_active_turn"}`.++A live session also returns `"accepted"` when it is already parked; the driver consumes that late or duplicate cancel as a no-op. An unknown or terminal session returns `"no_active_turn"`. A `turnId` naming any other turn is likewise accepted and consumed as a no-op, so a guarded cancel racing a turn boundary cannot stop a turn the caller never saw.++### Clear context++Clear one session's model-message history without replacing the session:++```bash+curl -X POST https://<deployment>/eve/v1/session/wrun_A/clear+# {"ok":true,"sessionId":"wrun_A","status":"accepted"}```-Cancellation 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.+An accepted clear emits `context.cleared` followed by `session.waiting`. The next message uses the same session without prior model messages; the system prompt, tools, skills, durable state, limits, and session-scoped sandbox remain.++### Compact context-Clear the model-message history of the session that owns a continuation token:+Compact one session's context without sending a message:```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"}+curl -X POST https://<deployment>/eve/v1/session/wrun_A/compact+# {"ok":true,"sessionId":"wrun_A","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.+Compaction is asynchronous. A successful operation emits `compaction.requested` and `compaction.completed`, then returns through `session.waiting`. When a turn is active, compaction waits for it to settle. If summarization fails, the session still returns to `session.waiting` with its previous history.-Compact the session that owns a continuation token without sending a message:+### Reset a session++Reset terminally retires the exact session ID:```bash-curl -X POST https://<deployment>/eve/v1/session/compact \+curl -X POST https://<deployment>/eve/v1/session/wrun_A/reset \-H "Content-Type: application/json" \- -d '{"continuationToken":"eve:7f3c..."}'-# {"ok":true,"sessionId":"ses_01h...","status":"accepted"}+ -d '{"reason":"Start over"}'+# {"ok":true,"previousSessionId":"wrun_A","status":"reset"}```-Compaction is asynchronous. A successful operation emits `compaction.requested` and `compaction.completed`, then returns through `session.waiting`; when a turn is active, the operation waits for it to settle. If summarization fails, the session still returns to `session.waiting` with its previous history. `"no_active_session"` is the successful no-op response when the token has no owner.+After reset, the old ID cannot accept another message. Start a replacement explicitly with `POST /eve/v1/session`.++The control routes never create sessions. `compact`, `clear`, and `reset` return `"no_active_session"` when the ID is already inactive. Session message and control request/response bodies do not accept or return continuation tokens. For compatibility, the streamed `session.waiting` event retains `data.continuationToken`: it is the channel-local token for a channel-addressed session and the immutable session ID for an ID-only session. New clients should continue through their fixed session handle instead of reading this field.-See [Sessions, runs & streaming](../concepts/sessions-runs-and-streaming) for the full request and stream flow, including the complete event set.+See [Sessions, runs & streaming](../concepts/sessions-runs-and-streaming) for the complete event set, operation results, and cursor behavior.## CORS@@ -137,9 +181,8 @@ export default eveChannel({};},events: {- "message.completed"(eventData, channel, ctx) {+ "message.completed"(eventData, _channel, ctx) {console.log("eve response completed", {- continuationToken: channel.continuationToken,sessionId: ctx.session.id,});},@@ -147,11 +190,14 @@ export default eveChannel({});```+`onMessage` must return an auth result. A successful canonical eve HTTP message+always dispatches and therefore always produces or continues a session.+## ClientsThe browser side of this API lives in the [Frontend](../guides/frontend/overview) docs, where `useEveAgent` drives the eve channel from React UI.-For scripts, server-to-server calls, evals, tests, and custom clients, use the [TypeScript SDK](../guides/client/overview). It wraps the session routes, continuation token, stream cursor, and reconnect loop.+For scripts, server-to-server calls, evals, tests, and custom clients, use the [TypeScript SDK](../guides/client/overview). It wraps the ID-addressed session routes, stream cursor, and reconnect loop.## What to read nextdiff --git a/docs/channels/github.mdx b/docs/channels/github.mdxindex de0400160..7ab3c0441 100644--- a/docs/channels/github.mdx+++ b/docs/channels/github.mdx@@ -103,7 +103,7 @@ GitHub comments have no interactive button or card affordance. A human-in-the-lo### Proactive sessions-Start a session without an inbound comment invocation through `receive(github, { message, target, auth })` from a schedule `run` handler, or `args.receive(github, ...)` from another channel. The target requires `owner`, `repo`, and exactly one of `issueNumber` or `pullRequestNumber`.+Start a session without an inbound comment invocation through `to(github, target).send(message, { auth })` from a schedule `run` handler, or `ctx.to(github, target).send(message, { auth })` from another channel. The target requires `owner`, `repo`, and exactly one of `issueNumber` or `pullRequestNumber`.### Attachmentsdiff --git a/docs/channels/linear.mdx b/docs/channels/linear.mdxindex ed10c536e..ff6038905 100644--- a/docs/channels/linear.mdx+++ b/docs/channels/linear.mdx@@ -160,7 +160,7 @@ await channel.linear.updateSession({## Proactive sessions-Use the channel's `receive` target to continue an existing Agent Session or create one from a Linear issue or root comment. The target accepts an existing `agentSessionId`, or an `issueId` or root `commentId` to create a new session before sending the message. The example below runs from a schedule; a route handler uses the same target shape through its own `receive` helper.+Use the channel's proactive target to continue an existing Agent Session or create one from a Linear issue or root comment. The target accepts an existing `agentSessionId`, or an `issueId` or root `commentId` to create a new session before sending the message. The example below runs from a schedule; a route handler uses the same target shape through `ctx.to(...)`.```tsimport { defineSchedule } from "eve/schedules";@@ -169,15 +169,13 @@ import linear from "../channels/linear";export default defineSchedule({cron: "0 14 * * 1",- async run({ receive, waitUntil, appAuth }) {+ async run({ to, waitUntil, appAuth }) {waitUntil(- receive(linear, {+ to(linear, {+ issueId: "EVE-123",+ initialActivity: "Preparing the status update.",+ }).send("Post a concise status update with blockers and next actions.", {auth: appAuth,- message: "Post a concise status update with blockers and next actions.",- target: {- issueId: "EVE-123",- initialActivity: "Preparing the status update.",- },}),);},diff --git a/docs/channels/overview.mdx b/docs/channels/overview.mdxindex ecea35864..33603f572 100644--- a/docs/channels/overview.mdx+++ b/docs/channels/overview.mdx@@ -6,7 +6,7 @@ description: "How users reach your agent: the channel contract, the base eve HTTA channel is the edge adapter between a platform and your agent. It does three things:- Normalizes platform input into a user message.-- Owns the `continuationToken`, the resume handle for a conversation on that surface.+- Owns the channel-local address that maps a platform conversation to its current durable session.- Decides delivery, meaning how, where, and whether a response goes back.eve ships a base HTTP channel plus first-class platform channels, and you can author your own. Browse the full set in the [Integrations](/integrations) gallery and choose the Channels filter.@@ -36,7 +36,7 @@ The eve channel is the framework's default HTTP session API, the routes the term## Custom channels-When eve doesn't ship a channel for your surface, build one with `defineChannel` from `eve/channels`. A custom channel declares route handlers (`GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `WS`), an `events` map, and a `send` call inside a handler to start or resume a session. See [Custom channels](./custom) for the full walkthrough, including WebSocket routes, cross-channel hand-off, channel metadata, continuation tokens, and file uploads.+When eve doesn't ship a channel for your surface, build one with `defineChannel` from `eve/channels`. A custom channel declares route handlers (`GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `WS`), an `events` map, and uses `send(address, input)` to start or resume a session. See [Custom channels](./custom) for the full walkthrough, including WebSocket routes, cross-channel hand-off, channel metadata, address tokens, and file uploads.## Relationship to the Chat SDKdiff --git a/docs/channels/slack.mdx b/docs/channels/slack.mdxindex 0c5ed1933..31e357d71 100644--- a/docs/channels/slack.mdx+++ b/docs/channels/slack.mdx@@ -108,7 +108,7 @@ Like `threadContext`, this helper calls `conversations.replies` and requires the#### Cancel an active turn-Message hooks (`onMessage`, `onAppMention`, and `onDirectMessage`) receive a thread-bound `ctx.cancel({ turnId? })` helper. Call it before returning `{ auth }` to stop the current turn and queue the new Slack message as replacement input, producing a debounce-like experience:+Message hooks (`onMessage`, `onAppMention`, and `onDirectMessage`) receive thread-bound session operations directly on `ctx`. Call `ctx.cancel({ turnId? })` before returning `{ auth }` to stop the current turn and queue the new Slack message as replacement input, producing a debounce-like experience:```ts title="agent/channels/slack.ts"export default slackChannel({@@ -123,11 +123,28 @@ export default slackChannel({});```-`"accepted"` means the cancellation request was consumed; `"no_active_turn"` means the thread had no cancellable turn. Both are successful outcomes, so the hook can still return `{ auth }` to deliver the replacement message. Cancellation never sends input itself. A custom `onInteraction` handler receives the same bound helper, which is useful for a Stop button that should cancel without replacement input.+`"accepted"` means the live thread session durably queued the cancellation request. A parked session consumes it as a no-op; `"no_active_turn"` means the thread has no active session owner. Both are successful outcomes, so the hook can still return `{ auth }` to deliver the replacement message. Cancellation never sends input itself. A custom `onInteraction` handler receives the same flat operations, which is useful for a Stop button that should cancel without replacement input.++Message and interaction hooks expose every current-owner operation directly on `ctx`:++```ts+async onAppMention(ctx) {+ await ctx.send("Run a separate turn.");+ await ctx.respond(inputResponses);+ await ctx.cancel();+ await ctx.compact();+ await ctx.clear();+ await ctx.reset({ reason: "Start over" });+ const session = await ctx.resolveSession();+ return { auth: null };+}+```++These calls are independent examples; a handler normally chooses one. `ctx.send()` is the only method that can create a session when the thread is unowned. It derives Slack auth from the inbound user unless `auth` is supplied explicitly. Use `await ctx.resolveSession()` only when later work must stay pinned to the currently owning durable session ID.#### Reset a conversation-Use the thread-bound `ctx.reset({ reason? })` helper when the conversation should start over instead. Reset terminally retires the session that currently owns the thread, including any in-flight turn. The next delivered message starts a new session with fresh history, state, and a new session-scoped sandbox:+Use the thread-bound `ctx.reset({ reason? })` method when the conversation should start over instead. Reset terminally retires the session that currently owns the thread, including any in-flight turn. The next delivered message starts a new session with fresh history, state, and a new session-scoped sandbox:```ts title="agent/channels/slack.ts"export default slackChannel({@@ -142,11 +159,11 @@ export default slackChannel({});```-Reset returns `{ status: "reset", previousSessionId }` when the thread had a session, or `{ status: "no_active_session" }` when it was already free. Both outcomes are successful. Returning `null` after reset consumes the triggering message as a command; return `{ auth }` instead to deliver that message as the first turn of the fresh session. Custom `onInteraction` handlers receive the same bound reset helper, which is useful for a New conversation button.+Reset returns `{ status: "reset", previousSessionId }` when the thread had a session, or `{ status: "no_active_session" }` when it was already free. Both outcomes are successful. Returning `null` after reset consumes the triggering message as a command; return `{ auth }` instead to deliver that message as the first turn of the fresh session. Custom `onInteraction` handlers receive the same flat operations, which is useful for a New conversation button.### Other Events API callbacks-Use `onEvent` for subscribed events such as `reaction_added`, `team_join`, or `channel_created`. It receives the raw, open-ended Slack event and owns control flow. `ctx.receive(options)` is the current Slack channel's pre-bound form of the schedule API's `receive(slack, options)`: call it zero, one, or many times to start turns. Each call accepts `message`, `target`, and `auth`, and returns the resulting session.+Use `onEvent` for subscribed events such as `reaction_added`, `team_join`, or `channel_created`. It receives the raw, open-ended Slack event and owns control flow. Call `ctx.send(message, { target, auth })` zero, one, or many times to start turns. Each call returns the resulting session.```ts title="agent/channels/slack.ts"import { connectSlackCredentials } from "@vercel/connect/eve";@@ -156,25 +173,39 @@ const onboardingChannels = ["C0123ABC", "C0456DEF"];export default slackChannel({credentials: connectSlackCredentials("slack/my-agent"),- async onEvent({ receive }, event) {+ async onEvent(ctx, event) {if (event.type !== "team_join") return;await Promise.all(onboardingChannels.map((channelId) =>- receive({- message: `A user joined the Slack workspace. Onboard them from this event:\n${JSON.stringify(event)}`,- target: { channelId },- auth: null,- }),+ ctx.send(+ `A user joined the Slack workspace. Onboard them from this event:\n${JSON.stringify(event)}`,+ {+ target: { channelId },+ auth: null,+ },+ ),),);},});```-The webhook invocation already keeps an awaited `onEvent` handler alive. Use `ctx.waitUntil(promise)` for deliberately detached work, matching a handler-form schedule. `ctx.slack.request(operation, body)` provides workspace-scoped Slack Web API access, while `ctx.envelope` carries delivery metadata such as `team_id`, `event_id`, and `event_time`. Calls to `ctx.receive` automatically seed the callback's team id into Slack session state.+The webhook invocation already keeps an awaited `onEvent` handler alive. Use `ctx.waitUntil(promise)` for deliberately detached work, matching a handler-form schedule. `ctx.slack.request(operation, body)` provides workspace-scoped Slack Web API access, while `ctx.envelope` carries delivery metadata such as `team_id`, `event_id`, and `event_time`. Calls to `ctx.send` automatically seed the callback's team id into Slack session state.++Because a generic event is not necessarily tied to one thread, put the target in each operation's input:-Because a generic event is not necessarily tied to one thread, its session helpers take the target explicitly: `ctx.cancel({ channelId, threadTs, turnId? })` stops in-flight work while retaining the session, and `ctx.reset({ channelId, threadTs, reason? })` retires the session. Pair either one with `ctx.receive(...)` when an event should deliver replacement input, or call it alone to stop or reset the thread.+```ts+const target = { channelId, threadTs };++await ctx.send("Follow up", { auth: null, target });+await ctx.respond(inputResponses, { auth: null, target });+await ctx.cancel({ target, turnId });+await ctx.compact({ target });+await ctx.clear({ target });+await ctx.reset({ reason: "Start over", target });+const session = await ctx.resolveSession({ target });+````onEvent` is the raw fallback after the message hooks. If an event is not claimed by `onAppMention`, `onDirectMessage`, or `onMessage`, an authored `onEvent` receives it; otherwise eve applies the built-in mention/DM default or ignores it.@@ -233,7 +264,7 @@ The default handlers reply in-thread and show progress. Typing indicators post aOutbound text preserves bare `@` tokens as literal text. To mention a user, embed Slack's `<@USER_ID>` syntax directly or use `channel.thread.mentionUser(userId)`.-When a session starts without a `threadTs` (say, from a schedule or `receive(slack, ...)`), eve gives it a unique temporary continuation token. The first agent post anchors the session to the Slack message timestamp, and later posts and mentions resume that same session. Pass `initialMessage` with a `Card` to land a structured anchor first instead. `threadTs` and `initialMessage` are mutually exclusive.+When a session starts without a `threadTs` (say, from a schedule's `to(slack, target).send(...)`), eve gives it a unique temporary continuation token. The first agent post anchors the session to the Slack message timestamp, and later posts and mentions resume that same session. Pass `initialMessage` with a `Card` to land a structured anchor first instead. `threadTs` and `initialMessage` are mutually exclusive.The example below overrides `onAppMention` to gate on an authored message and posts the completed reply to the thread. Event handlers receive `(eventData, channel, ctx)`, with Slack platform handles on `channel.thread` and `channel.slack`:@@ -272,7 +303,7 @@ events: {### Proactive sessions-Start a session without an inbound message through `receive(slack, { message, target, auth })` from a schedule `run` handler, or `args.receive(slack, ...)` from another channel. The proactive target shape is `{ channelId }`.+Start a session without an inbound message through `ctx.to(slack, target).send(message, { auth })` from another channel, or `to(slack, target).send(message, { auth })` from a schedule `run` handler. The proactive target shape is `{ channelId, threadTs?, initialMessage? }`.### Attachmentsdiff --git a/docs/channels/telegram.mdx b/docs/channels/telegram.mdxindex 036e2238c..7de9aab67 100644--- a/docs/channels/telegram.mdx+++ b/docs/channels/telegram.mdx@@ -51,7 +51,7 @@ Human-in-the-loop (HITL) turns option requests into inline-keyboard buttons and### Proactive sessions-Start a session without an inbound message through `receive(telegram, { message, target, auth })` from a schedule `run` handler, or `args.receive(telegram, ...)` from another channel. `target.chatId` is required. Add `messageThreadId` to land in a specific forum topic.+Start a session without an inbound message through `to(telegram, target).send(message, { auth })` from a schedule `run` handler, or `ctx.to(telegram, target).send(message, { auth })` from another channel. `target.chatId` is required. Add `messageThreadId` to land in a specific forum topic.Private proactive chats stay keyed to the chat, or to the chat plus `messageThreadId` when you target a topic. Group and supergroup proactive sends anchor to the bot message id returned by Telegram, so replies to different bot messages can resume different sessions in the same chat. If Telegram does not return a recognized chat type for an outbound send, eve keeps the session unanchored instead of guessing.diff --git a/docs/channels/twilio.mdx b/docs/channels/twilio.mdxindex 3a44b1813..54ec1e690 100644--- a/docs/channels/twilio.mdx+++ b/docs/channels/twilio.mdx@@ -66,7 +66,7 @@ SMS and voice have no native button or card affordance, so HITL prompts do not r### Proactive sessions-Start a session without an inbound message through `receive(twilio, { message, target, auth })` from a schedule `run` handler, or `args.receive(twilio, ...)` from another channel. `target.phoneNumber` is required, and the channel needs `messaging.from` or `messaging.messagingServiceSid` for the outbound sender.+Start a session without an inbound message through `to(twilio, target).send(message, { auth })` from a schedule `run` handler, or `ctx.to(twilio, target).send(message, { auth })` from another channel. `target.phoneNumber` is required, and the channel needs `messaging.from` or `messaging.messagingServiceSid` for the outbound sender.### Attachmentsdiff --git a/docs/concepts/default-harness.md b/docs/concepts/default-harness.mdindex 90744b704..a5b0df902 100644--- a/docs/concepts/default-harness.md+++ b/docs/concepts/default-harness.md@@ -20,9 +20,17 @@ export default defineAgent({Compaction also preserves the framework's own tool state automatically. It resets read-before-write tracking (so a write afterward re-reads the file whose read evidence was summarized away) and re-injects the active todo list, so the model keeps its task list across the summary. There is no per-tool hook to configure.-Clients and channels can also request compaction between turns. Call `ClientSession.compact()` or a custom route's `compact({ continuationToken })` helper. The request does not append a user message; if a turn is running, eve queues it until that turn settles. A successful manual compaction emits the same `compaction.requested` and `compaction.completed` events as automatic compaction, followed by `session.waiting`.--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`.+Clients and channels can also request compaction between turns. Call+`ClientSession.compact()`, a channel route's `compact(address)`, or+`attachSession(sessionId).compact()`. 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 the corresponding+`clear()` method on any of those handles. 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 toolsdiff --git a/docs/concepts/execution-model-and-durability.mdx b/docs/concepts/execution-model-and-durability.mdxindex 7b2e28f8b..d2eb75c5e 100644--- a/docs/concepts/execution-model-and-durability.mdx+++ b/docs/concepts/execution-model-and-durability.mdx@@ -68,11 +68,23 @@ Some work has to wait, including a human approving a [tool](../tools), an intera## Message delivery and queueing-eve does not maintain a durable FIFO queue of user messages for a session. The `continuationToken` is a resume handle for the session's current workflow hook, not a general message-queue address.--Only one active session can own a continuation token. When a session starts with a token, eve commits the park hook before processing its first turn and fails a competing session if another run already owns that token. A tokenless session claims its token after the first turn establishes one. Competing input is not forwarded to the owner.--When a session is waiting, a delivery to the current continuation token wakes the session and starts the next turn. When a turn is already active, the hook may accept additional deliveries, but the runtime only drains them at specific workflow boundaries. If more than one delivery is ready when the driver checks, eve may fold them into the next turn; that drain is best-effort and depends on workflow and transport timing.+eve does not maintain a durable FIFO queue of user messages for a session. An+ID-addressed HTTP delivery and a channel-address delivery both target the+session's current command inbox; neither is a general message queue.++Only one active session can own a channel continuation token. A channel-created+session commits both its stable session-ID alias and its channel alias before+processing the first turn, and fails creation if another run already owns the+channel alias. Rekeying replaces only that channel alias. An HTTP-created+session has the stable ID alias and no channel continuation token. Competing+channel input is not forwarded to the owner.++When a session is waiting, a delivery through its ID or current channel address+wakes the session and starts the next turn. When a turn is already active, the+inbox may accept additional deliveries, but the runtime only drains them at+specific workflow boundaries. If more than one delivery is ready when the driver+checks, eve may fold them into the next turn; that drain is best-effort and+depends on workflow and transport timing.So don't rely on concurrent sends to the same session behaving like a typical ordered chat queue. For deterministic behavior, send one user turn at a time and wait for `session.waiting` before sending the next message to the same session. If your channel can receive bursts while the agent is working, keep your own per-session queue in the channel or app layer, then deliver the next message after the session parks again. Separate sessions still run independently.diff --git a/docs/concepts/sessions-runs-and-streaming.md b/docs/concepts/sessions-runs-and-streaming.mdindex 762b4fcb0..e0934e0c2 100644--- a/docs/concepts/sessions-runs-and-streaming.md+++ b/docs/concepts/sessions-runs-and-streaming.md@@ -1,18 +1,20 @@---title: "Sessions, Runs & Streaming"-description: "The session and run contract you touch: continuation tokens, stream handles, the NDJSON event stream, and reconnecting."+description: "The ID-addressed session contract: messages, controls, the NDJSON event stream, and reconnecting."---Every eve app speaks the same stable HTTP API to a [durable session](./execution-model-and-durability). This page is the contract you hold: the handles you get back, the events you stream, and how to reconnect.-## The two handles+## Identity by surface-Two handles do two jobs, and mixing them up is the most common mistake. One handle creates and resumes a session; a different one streams and inspects it.+The HTTP API and TypeScript client use one durable `sessionId` for messages,+controls, and streams. Every operation targets that exact session; none follows+or creates a replacement implicitly.-- **`continuationToken`**: the resume handle. Use it to send a follow-up message to the same conversation. Owned by the channel.-- **`sessionId` / `runId`**: the stream-and-inspect handle. Use it to attach to the event stream and watch a run. Owned by the runtime.--A session has one active continuation at a time: each follow-up uses the current `continuationToken`, and a stale one is rejected.+Authored channels also have channel-local continuation tokens. A token addresses+whichever session currently owns a platform conversation, such as a Slack thread.+That identity stays behind the channel boundary and is never accepted or returned+by the eve HTTP session API. See [Custom channels](../channels/custom#address-and-session-handles).Sessions last 30 days by default; configure `limits.sessionTimeoutMs` in`agent.ts`, or set it to `false` to disable the deadline. At expiration, eve@@ -30,7 +32,8 @@ curl -X POST http://127.0.0.1:2000/eve/v1/session \-d '{"message":"Summarize the latest forecast."}'```-eve responds right away. The JSON body carries a `sessionId` and a `continuationToken`, and the `x-eve-session-id` header names the durable session to stream.+eve responds right away with the durable `sessionId` in the JSON body and+`x-eve-session-id` header.## Stream a session@@ -66,7 +69,7 @@ The stream is newline-delimited JSON (NDJSON), one event per line:| `turn.completed` | The turn finished. || `turn.failed` | The turn failed; carries `{ code, message, details? }`. || `turn.cancelled` | The turn was cancelled before finishing; always followed by `session.waiting`. |-| `session.waiting` | The session parked for the next input; carries the current channel-owned `continuationToken`. |+| `session.waiting` | The session parked and is ready for the next message. || `session.failed` | The session failed. || `session.completed` | The session reached a terminal end. |@@ -137,12 +140,12 @@ Authored [hooks](../guides/hooks) receive the same envelope, but observe each ev## Send a follow-up message-Once the session is waiting (you'll see `session.waiting`), POST your follow-up to the session endpoint with `event.data.continuationToken`:+Once the session is waiting (you'll see `session.waiting`), POST your follow-up to its ID-addressed messages endpoint:```bashcurl -X POST http://127.0.0.1:2000/eve/v1/session/<sessionId> \-H 'content-type: application/json' \- -d '{"continuationToken":"<token>","message":"Now send the short version."}'+ -d '{"message":"Now send the short version."}'```The follow-up reuses the same durable session: same history, same state.@@ -166,9 +169,30 @@ curl -X POST http://127.0.0.1:2000/eve/v1/session/<sessionId>/cancel# {"ok":true,"sessionId":"<sessionId>","status":"accepted"}```-`"accepted"` means a cancellation hook accepted the request. Confirm cancellation on the stream as `turn.cancelled` followed by `session.waiting`; the session then accepts the next message normally. If the turn is waiting on active local or remote subagents, eve also requests cancellation of every adopted child, recursively, before settling the parent. Each child reports its own cancellation boundary on its child-session stream; the parent does not emit `subagent.completed` for cancelled work. `"no_active_turn"` means no resumable cancellation target exists, including an unknown session or an already-settled turn. Both statuses are success, so clients can fire and forget. See the [eve channel](../channels/eve) for the full route contract.+`"accepted"` means the live session durably queued the request. Confirm an actual cancellation on the stream as `turn.cancelled` followed by `session.waiting`; the session then accepts the next message normally. If the turn is waiting on active local or remote subagents, eve also requests cancellation of every adopted child, recursively, before settling the parent. Each child reports its own cancellation boundary on its child-session stream; the parent does not emit `subagent.completed` for cancelled work. A live but already-parked session also returns `"accepted"` and consumes the command as a no-op. `"no_active_turn"` means the session or channel address is unknown or terminal. Both statuses are success, so clients can fire and forget. See the [eve channel](../channels/eve) for the full route contract.++The HTTP route returns `202` for `"accepted"` and `200` for+`"no_active_turn"`. Only the accepted result includes `sessionId`.++Custom channel routes request the same cancellation through+`from(address).cancel()` or `attachSession(sessionId).cancel()`. See+[custom channels](../channels/custom#channel-operations-and-session-handles).++## Compact, clear, and reset++All session controls are ID-addressed and accept no continuation token:++```bash+curl -X POST http://127.0.0.1:2000/eve/v1/session/<sessionId>/compact+curl -X POST http://127.0.0.1:2000/eve/v1/session/<sessionId>/clear+curl -X POST http://127.0.0.1:2000/eve/v1/session/<sessionId>/reset \+ -H 'content-type: application/json' \+ -d '{"reason":"Start over"}'+```-Custom channel routes request the same cancellation without knowing the session id: the `cancel` route helper is addressed by the channel-local continuation token, and `Session.cancel()` by session id. See [custom channels](../channels/custom#cancel-a-turn).+Compaction summarizes context, clear removes model-message history in place,+and reset terminally retires the session. A reset ID never becomes a new session;+create another session explicitly for a fresh conversation.## Reconnect and rewind@@ -186,7 +210,9 @@ A negative `startIndex` reads relative to the stream's current tail. For examplecurl "http://127.0.0.1:2000/eve/v1/session/<sessionId>/stream?startIndex=-1"```-This gives a consumer that only persisted `sessionId` a lightweight way to recover the current `continuationToken`. Because a tail-relative position does not resolve to an absolute consumed-event count, client tail reads do not automatically reconnect or advance the stored cursor.+Because a tail-relative position does not resolve to an absolute consumed-event+count, client tail reads do not automatically reconnect or advance the stored+cursor.For a catch-up read that stops instead of following the live stream, pass `includeTailIndex=1`. The response then carries the `x-eve-stream-tail-index` header: the zero-based index of the last durably recorded event, or `-1` before the first. Read from your cursor until it passes that tail, then disconnect — reconnecting from the updated cursor if the connection drops first:@@ -201,7 +227,7 @@ The lookup is opt-in; requests without the parameter get no header. The TypeScriFor scripts, server-to-server calls, tests, evals, and custom UIs, `eve/client` wraps these routes in a typed client so you don't hand-roll the POST and NDJSON stream loop.-Start with the [TypeScript SDK](../guides/client/overview) guide. It covers basic usage, sending messages, continuations, streaming, and per-turn `outputSchema` results.+Start with the [TypeScript SDK](../guides/client/overview) guide. It covers basic usage, sending messages, session state, streaming, and per-turn `outputSchema` results.## Inspect the agent over HTTP@@ -227,6 +253,6 @@ The order is structural, not incidental. By the time a resolver or hook reads ch## What to read next- [Execution model & durability](./execution-model-and-durability): what makes a session durable and how parked work resumes.-- [Channels](../channels/overview): what owns the continuation token and delivery.+- [Channels](../channels/overview): how platform addresses map to durable sessions.- [TypeScript SDK](../guides/client/overview): call these routes from scripts and server-side code.- [Frontend](../guides/frontend/overview): `useEveAgent` instead of raw routes.diff --git a/docs/evals/cases.mdx b/docs/evals/cases.mdxindex 22821be54..237dcaed1 100644--- a/docs/evals/cases.mdx+++ b/docs/evals/cases.mdx@@ -101,12 +101,12 @@ export default defineEval({`t` drives the primary session; `t.newSession()` returns an independent `EveEvalSession` against the same target, whose events feed the same run-level assertions.-- `t.send(input)` sends a turn and waits for it to settle. It accepts the same input as `ClientSession.send()` (a string or a structured message) and resolves to a turn carrying `.message` and `.expectOk()`.-- `t.start(input)` starts a turn but returns as soon as the server accepts it. The returned live turn exposes `.sessionId`, `.waitForEvent(...)`, `.cancel()`, and `.result()` for coordinating with work that is still running.+- `t.send(message, options?)` sends a turn and waits for it to settle. It matches `ClientSession.send()` and resolves to a turn carrying `.message` and `.expectOk()`.+- `t.start(message)` starts a text turn but returns as soon as the server accepts it. The returned live turn exposes `.sessionId`, `.waitForEvent(...)`, `.cancel()`, and `.result()` for coordinating with work that is still running.- `t.cancel()` requests cooperative cancellation of the primary session's active turn. Both `accepted` and `no_active_turn` are successful outcomes.- `t.sendFile(text, path, mediaType?)` attaches a local file as a data URL.- `t.requireInputRequest(filter?)` records a gate, requires exactly one pending request, and returns it. Filters match tool name, action input, prompt, display, and option ids.-- `t.respond(...responses)` answers specific pending input requests and sends them as the next turn.+- `t.respond(responses, options?)` answers specific pending input requests and sends them as the next turn.- `t.respondAll(optionId)` answers every pending input request with the same option and sends the responses as the next turn.- `t.reply` is the last assistant message (or `null`); `t.sessionId` is the current session id; `t.events` is the full typed event stream captured so far.diff --git a/docs/evals/targets.mdx b/docs/evals/targets.mdxindex e740b3d97..b671e3782 100644--- a/docs/evals/targets.mdx+++ b/docs/evals/targets.mdx@@ -24,7 +24,7 @@ export default defineEval({- `t.target.fetch(path, init)` performs an authenticated fetch against the target, useful for channel and webhook ingress. See [Authentication](#authentication) for how the runner authenticates.- `t.target.dispatchSchedule(id)` triggers a [schedule](../schedules) through the dev-only schedule route and returns the session ids it created. It works only against a target with dev routes enabled (the local `eve eval` dev server, or a deployment running in development mode), and throws otherwise.-- `t.target.attachSession(sessionId, { startIndex? })` consumes one turn from a session created outside the eval, by a channel or a schedule, so its events feed the run-level assertions. `startIndex` skips events before that position, so a session already partway through its stream resumes from where you left off rather than replaying from the start. When the consumed turn parks (`session.waiting`), the attached session recovers the current continuation token from the stream, so `session.send(...)` and `session.respond(...)` continue the same durable session.+- `t.target.attachSession(sessionId, { startIndex? })` consumes one turn from a session created outside the eval, by a channel or a schedule, so its events feed the run-level assertions. `startIndex` skips events before that position, so a session already partway through its stream resumes from where you left off rather than replaying from the start. The attached session stays bound to that exact ID, so `session.send(...)` and `session.respond(...)` continue it after the turn parks (`session.waiting`).- `t.target.watchTurn(sessionId, { startIndex? })` starts consuming an externally-created turn immediately and returns a live-turn handle. Use `waitForEvent(...)` to coordinate with mid-turn work, `cancel()` to request cancellation, and `result()` to consume through the boundary. The live turn's `.session` is the attached `EveEvalSession` for follow-up sends after settlement.Sessions attached this way are full `EveEvalSession`s: you can keep driving them and assert directly on that session (`session.succeeded()`, `session.calledTool(...)`). Aggregate assertions on `t` continue to read the whole run, including every attached session.diff --git a/docs/guides/auth-and-route-protection.md b/docs/guides/auth-and-route-protection.mdindex 87023f5ff..d7975bb71 100644--- a/docs/guides/auth-and-route-protection.md+++ b/docs/guides/auth-and-route-protection.md@@ -16,6 +16,7 @@ The route-auth policy lives on the HTTP channel factory (`agent/channels/eve.ts`- `POST /eve/v1/session`- `POST /eve/v1/session/:sessionId`+- `POST /eve/v1/session/:sessionId/{cancel,compact,clear,reset}`- `GET /eve/v1/session/:sessionId/stream`These routes are protected by the channel's auth policy. eve fails closed by default: production traffic is rejected unless you configure an authenticator that accepts it, and anonymous access requires an explicit `none()`.@@ -181,7 +182,7 @@ import { createUnauthorizedResponse } from "eve/channels/auth";export default defineChannel({routes: [- POST("/message", async (req, { send }) => {+ POST("/message", async (req) => {if (!isAllowed(req)) {return createUnauthorizedResponse({status: 403, // defaults to 401; code defaults to "forbidden" / "unauthorized"diff --git a/docs/guides/client/continuations.mdx b/docs/guides/client/continuations.mdxindex 18f26eece..8859c67ab 100644--- a/docs/guides/client/continuations.mdx+++ b/docs/guides/client/continuations.mdx@@ -1,137 +1,110 @@----title: "Continuations"-description: "Persist and resume eve client sessions with continuation tokens, session IDs, and stream cursors."+title: "Session State"+description: "Persist and resume eve client sessions with durable session IDs and stream cursors."----Every eve client turn returns two handles, and mixing them up is a common mistake. The TypeScript client tracks both for you:--- `continuationToken`: the resume handle. Use it to send the next user turn.-- `sessionId`: the stream-and-inspect handle. Use it to attach to event history.--`ClientSession` also tracks `streamIndex`, the count of events already consumed. Together these three fields make a `SessionState`.+The TypeScript client uses one durable session ID for messages, controls, and+streams. A `ClientSession` adds a local `streamIndex` cursor so reconnects do not+replay events already consumed by that handle.## Read and persist state-After a streamed turn finishes, read `session.state`:+Create the session with its first turn, then persist `session.state` after+consuming the response:```ts-const session = client.session();+const { session, response } = await client.sessions.create({+ message: "Create a launch checklist.",+});-const response = await session.send("Create a launch checklist.");await response.result();-await saveSessionState(session.state);```-As soon as `send()` returns, `session.state.sessionId` identifies the accepted in-flight turn for cancellation or stream reconnection. Consume the response before saving a fully advanced cursor: the continuation token and `streamIndex` update as events reach the turn boundary.--Store the full state object:+The state is deliberately small:```ts-interface SessionState {- continuationToken?: string;- sessionId?: string;+interface ClientSessionState {+ sessionId: string;streamIndex: number;}```-The continuation token resumes the conversation. The session ID and stream index let the client reconnect to the right stream position without replaying events it already consumed.--`SessionState` is a cursor, not a chat transcript. If your app shows historical messages, persist the stream events separately and store them under your own chat or thread ID. On reload, pass the saved `SessionState` back to `client.session(savedState)` or `useEveAgent({ initialSession })`, and pass the saved events to your renderer or `useEveAgent({ initialEvents })`.+It is a remote stream cursor, not a transcript. Persist events separately when+your application renders chat history.## Resume a saved session-Pass the saved state back into `client.session()`:+Attach a fixed handle to the saved ID and restore its cursor:```ts-import type { SessionState } from "eve/client";+import type { ClientSessionState } from "eve/client";-const saved = (await loadSessionState()) as SessionState;-const session = client.session(saved);+const saved = (await loadSessionState()) as ClientSessionState;+const session = client.sessions.attach(saved.sessionId, {+ streamIndex: saved.streamIndex,+});const response = await session.send("Now shorten it.");-const result = await response.result();-console.log(result.message);-```--If all you have is a continuation token, pass it as shorthand:--```ts-const session = client.session(continuationToken);-const response = await session.send("Continue where we left off.");-await response.result();+console.log((await response.result()).message);```-The shorthand can send a follow-up, but it doesn't know the previous stream cursor. Prefer full `SessionState` when you control persistence.--## Waiting, completed, and failed sessions+`attach()` performs no request. Every later operation targets exactly+`saved.sessionId`; it never follows or creates a replacement.-When a turn ends with `session.waiting`, the event carries the current channel-owned `data.continuationToken` and the client preserves the state so the next send continues the conversation.+## Waiting, completed, and reset sessions-When a turn ends with `session.completed` or `session.failed`, the client resets its local state. The next send starts a fresh durable session:+A session that emits `session.waiting` accepts another message through the same+handle. A terminal or reset session does not. Start a fresh conversation+explicitly with another `client.sessions.create(firstTurn)` call.```ts-const response = await session.send("Do this one-shot task.");-const result = await response.result();--if (result.status === "completed") {- // session.state is now a fresh cursor: { streamIndex: 0 }-}+const reset = await session.reset({ reason: "Start over" });+const { session: fresh, response } = await client.sessions.create({ message: "Begin again." });```-This matches the runtime contract, where only waiting sessions can accept the next user input.+The old `session` remains pinned to its retired ID; `fresh` owns a different ID.## Multiple sessions-Create a separate `ClientSession` per conversation:+Create one handle per conversation:```ts-const research = client.session();-const support = client.session();--const researchResponse = await research.send("Research competitors.");-await researchResponse.result();--const supportResponse = await support.send("Draft a support reply.");-await supportResponse.result();-+const { session: research, response: researchResponse } = await client.sessions.create({+ message: "Research competitors.",+});+const { session: support, response: supportResponse } = await client.sessions.create({+ message: "Draft a support reply.",+});++await Promise.all([researchResponse.result(), supportResponse.result()]);await save("research", research.state);await save("support", support.state);```-The shared `Client` only owns host, auth, headers, and reconnect settings. Conversation state lives on each `ClientSession`.--For a multi-chat UI, this usually means one application row per chat with two eve fields: the latest `SessionState` and the ordered event log for rendering. Do not reuse one `ClientSession` across sidebar conversations, and do not treat `streamIndex` as your database row index; it is only the remote stream cursor for that eve session.+The shared `Client` owns host, auth, headers, and redirect policy. Each+`ClientSession` owns its fixed ID and stream cursor.## Reconnect an existing stream-When a session already has a `sessionId`, `session.stream()` reattaches to its stream from the saved cursor. Resuming a saved `SessionState` after a restart is the common reason to do this:+`stream()` starts from the handle's saved cursor and advances it as events are+read:```ts-const session = client.session(savedState);+const session = client.sessions.attach(saved.sessionId, {+ streamIndex: saved.streamIndex,+});for await (const event of session.stream()) {console.log(event.type);}```-`stream()` attaches to an existing run; to send new user input, use `send()`. For overriding the cursor with `startIndex` and the full reconnection model, see [Streaming](./streaming#open-a-stream-manually).--If you only persisted `sessionId`, read the latest durable event to recover the current token from a waiting session:--```ts-const session = client.session({ sessionId, streamIndex: 0 });--for await (const event of session.stream({ startIndex: -1 })) {- if (event.type === "session.waiting") {- await saveContinuationToken(event.data.continuationToken);- }- break;-}-```+Use `send()` for new input. For explicit cursors, tail-relative reads, and+bounded catch-up, see [Streaming](./streaming#open-a-stream-manually).## What to read next- [Streaming](./streaming): stream events and reconnect by index- [Sessions, runs & streaming](../../concepts/sessions-runs-and-streaming): the raw HTTP contract-- [eve channel](../../channels/eve): where continuation tokens come from+- [eve channel](../../channels/eve): the ID-addressed routesdiff --git a/docs/guides/client/messages.mdx b/docs/guides/client/messages.mdxindex b9e732447..079b8f067 100644--- a/docs/guides/client/messages.mdx+++ b/docs/guides/client/messages.mdx@@ -3,7 +3,7 @@ title: "Messages"description: "Send text, full turn payloads, client context, attachments, and HITL responses with eve/client."----`ClientSession` sends one turn at a time. A fresh session starts on the first send; later sends continue the same conversation as long as the previous turn left the session waiting.+Create a session with its first turn, then use the returned `ClientSession` for follow-ups. Each handle targets one durable session ID.## Send text@@ -13,12 +13,12 @@ Pass a string to `send()` for plain text:import { Client } from "eve/client";const client = new Client({ host: "http://127.0.0.1:2000" });-const session = client.session();--const response = await session.send("What is the weather in Brooklyn?");+const { session, response } = await client.sessions.create({+ message: "What is the weather in Brooklyn?",+});// Metadata is available as soon as the POST succeeds.-console.log(response.sessionId, response.continuationToken);+console.log(response.sessionId);const result = await response.result();console.log(result.status, result.message);@@ -38,10 +38,10 @@ When the stream includes `session.failed`, the turn returns `status: "failed"` r## Send a full turn payload-Use `send()` when you need more than plain text:+Pass the full payload to `create()` for the first turn or `send()` for a follow-up:```ts-const response = await session.send({+const { session, response } = await client.sessions.create({message: "What should I do on this screen?",clientContext: {route: "/billing",@@ -60,17 +60,15 @@ await response.result();`send()` accepts AI SDK `UserContent`, so a message can mix text and file parts:```ts-const response = await session.send({- message: [- { type: "text", text: "Summarize this report." },- {- type: "file",- data: reportDataUrl,- mediaType: "application/pdf",- filename: "report.pdf",- },- ],-});+const response = await session.send([+ { type: "text", text: "Summarize this report." },+ {+ type: "file",+ data: reportDataUrl,+ mediaType: "application/pdf",+ filename: "report.pdf",+ },+]);await response.result();```@@ -83,17 +81,15 @@ import { readFile } from "node:fs/promises";const bytes = await readFile("report.pdf");const reportDataUrl = `data:application/pdf;base64,${bytes.toString("base64")}`;-const response = await session.send({- message: [- { type: "text", text: "Summarize this report." },- {- type: "file",- data: reportDataUrl,- mediaType: "application/pdf",- filename: "report.pdf",- },- ],-});+const response = await session.send([+ { type: "text", text: "Summarize this report." },+ {+ type: "file",+ data: reportDataUrl,+ mediaType: "application/pdf",+ filename: "report.pdf",+ },+]);await response.result();```@@ -119,17 +115,17 @@ for await (const event of response) {}}-const resumed = await session.send({- inputResponses: pendingRequests.map((request) => ({+const resumed = await session.respond(+ pendingRequests.map((request) => ({requestId: request.requestId,optionId: "approve",})),-});+);await resumed.result();```-You can send `message`, `inputResponses`, and `clientContext` together when the resumed turn needs both a human answer and follow-up text.+`send(message, options)` and `respond(inputResponses, options)` are separate operations. Put `clientContext`, `outputSchema`, headers, or stream options in the second argument to either method.## Single-use responsesdiff --git a/docs/guides/client/output-schema.mdx b/docs/guides/client/output-schema.mdxindex 4e04f0635..5253a0e47 100644--- a/docs/guides/client/output-schema.mdx+++ b/docs/guides/client/output-schema.mdx@@ -27,9 +27,7 @@ const outputSchema = {} as const;const client = new Client({ host: "http://127.0.0.1:2000" });-const session = client.session();--const response = await session.send<Summary>({+const { session, response } = await client.sessions.create<Summary>({message: "Summarize this turn.",outputSchema,});@@ -56,8 +54,7 @@ const summarySchema = z.object({type Summary = z.infer<typeof summarySchema>;-const response = await session.send<Summary>({- message: "Summarize this turn.",+const response = await session.send<Summary>("Summarize this turn.", {outputSchema: summarySchema,});@@ -71,8 +68,7 @@ The server is authoritative for validation. The client types `MessageResult.dataIf you consume events manually, read `result.completed`:```ts-const response = await session.send<Summary>({- message: "Summarize this turn.",+const response = await session.send<Summary>("Summarize this turn.", {outputSchema,});@@ -88,11 +84,10 @@ If more than one `result.completed` appears in the consumed event list, `result(## Send payloads with output schema-`outputSchema` works with string shorthand and object-form sends. Use object form when you need schema, headers, signal, context, attachments, or HITL responses:+Pass `outputSchema` in the second argument to `send()` or `respond()` alongside headers, signal, or client context:```ts-const response = await session.send<Summary>({- message: "Summarize this PDF.",+const response = await session.send<Summary>("Summarize this PDF.", {clientContext: { reportId: "rpt_123" },outputSchema,});@@ -103,9 +98,7 @@ const result = await response.result();It also works on follow-up turns and HITL response turns:```ts-const response = await session.send({- inputResponses: [{ requestId, optionId: "approve" }],- message: "Return the approved action as structured output.",+const response = await session.respond([{ requestId, optionId: "approve" }], {outputSchema,});@@ -117,7 +110,7 @@ const result = await response.result();Client `outputSchema` is scoped to the turn that sends it. It doesn't become a permanent setting for the conversation:```ts-const response = await session.send({ message: "Return a structured summary.", outputSchema });+const response = await session.send("Return a structured summary.", { outputSchema });await response.result();const followUpResponse = await session.send("Now answer normally.");diff --git a/docs/guides/client/overview.mdx b/docs/guides/client/overview.mdxindex ef314141d..5683233b1 100644--- a/docs/guides/client/overview.mdx+++ b/docs/guides/client/overview.mdx@@ -100,8 +100,7 @@ Set `redirect` to `"manual"` or `"error"` on credential-bearing clients so fetchPer-request headers can be attached to an individual turn:```ts-const response = await session.send({- message: "Run the check.",+const response = await session.send("Run the check.", {headers: { "x-request-id": requestId },});@@ -112,23 +111,53 @@ Per-request headers override client-level values with the same name. For example## Sessions-Create a `ClientSession` for each conversation:+For an ID-addressed session, create it explicitly with the first message:```ts-const session = client.session();+const { session, response } = await client.sessions.create({ message: "Summarize account A." });+await response.result();++await (await session.send("Now list the risks.")).result();+await session.compact();+await session.clear();+```++If you already know the durable ID, attach a fixed handle without performing I/O:++```ts+const session = client.sessions.attach("wrun_A");```-A client can own many sessions at once. Each session tracks its own `sessionId`, `continuationToken`, and stream cursor:+The fixed client handle exposes the full lifecycle around that ID. The calls below show the available shapes independently:```ts-const alice = client.session();-const bob = client.session();+const response = await session.send("Continue the analysis.");+await response.result();++await session.cancel({ turnId: "turn_123" });+await session.compact();+await session.clear();-const aliceResponse = await alice.send("Summarize account A.");-await aliceResponse.result();+for await (const event of session.stream({ follow: false })) {+ console.log(event.type);+}++await session.reset({ reason: "User requested a fresh session" });+```++`client.sessions` stores only the session ID and stream cursor. Every method calls an ID-addressed `/eve/v1/session/:sessionId/...` route. Sending through a handle for an unknown or terminal ID fails instead of creating a replacement, and reset leaves the handle pinned to the retired ID.++A client can own many independent fixed sessions at once:++```ts+const { session: alice, response: aliceResponse } = await client.sessions.create({+ message: "Summarize account A.",+});+const { session: bob, response: bobResponse } = await client.sessions.create({+ message: "Summarize account B.",+});-const bobResponse = await bob.send("Summarize account B.");-await bobResponse.result();+await Promise.all([aliceResponse.result(), bobResponse.result()]);```The next pages cover the session lifecycle:diff --git a/docs/guides/client/streaming.mdx b/docs/guides/client/streaming.mdxindex 915ec0432..836d13c02 100644--- a/docs/guides/client/streaming.mdx+++ b/docs/guides/client/streaming.mdx@@ -5,18 +5,22 @@ description: "Consume eve client stream events live, reconnect by event index, aEvery `ClientSession.send()` call posts the turn, then reads the session's NDJSON (newline-delimited JSON) event stream. `MessageResponse` gives you two ways to consume that stream, aggregating it with `result()` or iterating it live.-Once `send()` is accepted, the session exposes its assigned `sessionId` and can request cooperative cancellation with `session.cancel()`, even while the response stream is still running. The result status is `accepted` when the active turn accepted the signal or `no_active_turn` when it already settled:+Once `send()` is accepted, the session exposes its assigned `sessionId` and can request cooperative cancellation with `session.cancel()`, even while the response stream is still running. The result status is `accepted` when the live session durably queued the command, including when a parked session consumes it as a no-op. An unknown or terminal session returns `no_active_turn`:```ts-const session = client.session();-const response = await session.send("Run the long operation.");+const { session, response } = await client.sessions.create({ message: "Run the long operation." });const cancellation = await session.cancel();-console.log(cancellation.status);+if (cancellation.status === "accepted") {+ console.log(cancellation.sessionId);+}const result = await response.result();```+The cancellation result is discriminated by `status`: only `accepted` includes+`sessionId`; `no_active_turn` has no session identity field.+Cancellation does not replace stream consumption. Continue reading the response to observe its terminal `turn.cancelled` and `session.waiting` boundary and to advance the client session cursor normally.Between turns, `session.compact()` queues context compaction without sending model input. An accepted request reports the session id; consume the durable stream through the following `session.waiting` boundary before sending the next turn. `compaction.completed` confirms that summarization succeeded; without it, eve preserves the previous history. A never-started session returns `no_active_session` as a successful no-op.@@ -103,7 +107,7 @@ The most common UI events are:| `action.result` | Show tool call results. || `input.requested` | Pause the UI for approval or a question answer. || `result.completed` | Read structured output from an [output schema](./output-schema). |-| `session.waiting` | Enable the composer and read the current `data.continuationToken`. |+| `session.waiting` | Enable the composer; the same fixed session handle accepts the next message. || `session.completed` | Mark the conversation terminal. || `session.failed` | Mark the conversation failed. |@@ -129,8 +133,7 @@ If your consumer persists events, key on `event.meta.id`. It is stable across reSet `streamReconnectPolicy: { reconnect: false }` when a relay or proxy owns the cursor and reconnection policy. This makes a single stream GET attempt and returns when that connection ends; it does not stop the server-side turn:```ts-const response = await session.send({- message: "Run the long operation.",+const response = await session.send("Run the long operation.", {streamReconnectPolicy: { reconnect: false },});@@ -146,9 +149,7 @@ The same option is available on manual attachments as `session.stream({ streamReUse `session.stream()` when you already have a session cursor and only need to attach to the existing stream:```ts-const session = client.session({- continuationToken: "eve:6c8b1f2e-3d4a-4b9c-8e21-9f0a1b2c3d4e",- sessionId: "wrun_01ARYZ6S41TSV4RRFFQ69G5FAV",+const session = client.sessions.attach("wrun_01ARYZ6S41TSV4RRFFQ69G5FAV", {streamIndex: 10,});@@ -169,9 +170,7 @@ Nonnegative values are absolute event indexes. Negative values read relative to```tsfor await (const event of session.stream({ startIndex: -1 })) {- if (event.type === "session.waiting") {- console.log(event.data.continuationToken);- }+ console.log(event.type);break;}```@@ -193,15 +192,13 @@ The first connection pins the bound to the tail the server reports at open time;Because a tail-relative cursor cannot be bounded, `follow: false` throws when combined with a negative `startIndex`. It also fails if the server does not report the durable tail (an agent running an older eve version).-`stream()` throws if the session has no `sessionId`, because there's no stream to attach to before the first send.-## Snapshot a sessionUse `snapshot()` when you need the complete event prefix and its matching cursoras one value, such as when hydrating a server-rendered chat:```ts-const session = client.session({ sessionId, streamIndex: 0 });+const session = client.sessions.attach(sessionId);const snapshot = await session.snapshot();// snapshot.events contains event indexes 0 through snapshot.session.streamIndex - 1.@@ -213,11 +210,9 @@ The read pins the durable tail when it opens, just likecontinue. `snapshot()` always reads from index `0`; use a bounded stream directlywhen you only need the unread suffix from an existing cursor.-Unlike `stream()`, `snapshot()` does not advance or reset the originating-`ClientSession`. Its returned session includes a continuation token only when-the captured prefix ends in `session.waiting`, or when completed sessions are-explicitly preserved by the client. Active and terminal snapshots remain-inspectable at their returned stream cursor but cannot accept another turn.+Unlike `stream()`, `snapshot()` does not advance the originating+`ClientSession`. Its returned cursor contains the fixed session ID and the exact+stream index after the captured prefix.## Abort a request@@ -229,8 +224,7 @@ Arm the timeout before awaiting `send()` so it covers the POST as well as the stconst controller = new AbortController();const timeout = setTimeout(() => controller.abort(), 10_000);-const response = await session.send({- message: "Run a long analysis.",+const response = await session.send("Run a long analysis.", {signal: controller.signal,});diff --git a/docs/guides/frontend/nuxt.mdx b/docs/guides/frontend/nuxt.mdxindex 40b058bbb..725e4f9ab 100644--- a/docs/guides/frontend/nuxt.mdx+++ b/docs/guides/frontend/nuxt.mdx@@ -48,7 +48,7 @@ async function handleSubmit() {const text = message.value.trim();if (!text || isBusy.value) return;message.value = "";- await send({ message: text });+ await send(text);}</script>diff --git a/docs/guides/frontend/overview.mdx b/docs/guides/frontend/overview.mdxindex 209339c20..d49a6d81d 100644--- a/docs/guides/frontend/overview.mdx+++ b/docs/guides/frontend/overview.mdx@@ -36,7 +36,7 @@ export function Chat() {const form = new FormData(event.currentTarget);const message = String(form.get("message") ?? "").trim();if (message.length > 0) {- void agent.send({ message });+ void agent.send(message);}}}>@@ -61,16 +61,17 @@ export function Chat() {`useEveAgent()` returns the current UI state plus commands:-| Field | What it is |-| --------- | ------------------------------------------------------------------------------ |-| `data` | Projected UI state from the reducer. Defaults to `{ messages }`. |-| `status` | `"ready"`, `"submitted"`, `"streaming"`, or `"error"`. Drives the composer. |-| `error` | The last `Error` thrown, if any. |-| `events` | Raw eve stream events for this session. |-| `session` | Serializable session cursor (`sessionId`, `continuationToken`, `streamIndex`). |-| `send` | Send text or the full turn payload (multi-part messages, HITL responses). |-| `stop` | Abort the client's in-flight stream. The server-side turn keeps running. |-| `reset` | Clear local events, data, errors, and the local session cursor. |+| Field | What it is |+| --------- | --------------------------------------------------------------------------- |+| `data` | Projected UI state from the reducer. Defaults to `{ messages }`. |+| `status` | `"ready"`, `"submitted"`, `"streaming"`, or `"error"`. Drives the composer. |+| `error` | The last `Error` thrown, if any. |+| `events` | Raw eve stream events for this session. |+| `session` | Serializable fixed session cursor (`sessionId`, `streamIndex`). |+| `send` | Send text or a multi-part message, with per-turn options. |+| `respond` | Answer pending HITL input requests, with per-turn options. |+| `stop` | Abort the client's in-flight stream. The server-side turn keeps running. |+| `reset` | Clear local events, data, errors, and the local session cursor. |Most chat UIs only need `data.messages` and `status`. Drop down to `events` when you need the authoritative wire events directly, for example to persist an audit log or build a custom projection.@@ -78,29 +79,31 @@ Most chat UIs only need `data.messages` and `status`. Drop down to `events` when## Sending and streaming-Pass an object to `send()` for text, multi-part messages, attachments, HITL responses, and per-turn context:+Pass the message first and optional per-turn settings second. Use `respond()` for HITL answers:```tsx-await agent.send({ message: "Summarize this session." });--await agent.send({- message: [- { type: "text", text: "What is in this file?" },- {- type: "file",- data: fileDataUrl, // base64 data URL- mediaType: "application/pdf",- filename: "report.pdf",- },- ],-});+await agent.send("Summarize this session.");++await agent.send([+ { type: "text", text: "What is in this file?" },+ {+ type: "file",+ data: fileDataUrl, // base64 data URL+ mediaType: "application/pdf",+ filename: "report.pdf",+ },+]);```Assistant text, reasoning, tool calls, and tool results stream into `data` as they arrive, and `status` moves from `ready` to `submitted` to `streaming` and back. Call `stop()` to abort the client's in-flight stream, and `reset()` to clear local state so the next send starts a fresh durable session.`stop()` is local: turns are resumable across disconnects, so detaching the stream never cancels the work — the turn keeps running and billing on the server. To stop the turn itself, POST the session's [cancel route](../../channels/eve#routes); the turn then settles on the stream as `turn.cancelled` followed by `session.waiting`.-A chat UI with a Stop button should own the `ClientSession` passed to `useEveAgent`, create it with `preserveCompletedSessions: true`, and call `session.cancel({ turnId })` after observing that turn's `turn.started` event. The `turnId` guard makes a late click a harmless no-op instead of cancelling a newer turn. Keep the stream open until the cancellation boundary arrives; do not use `stop()` for this interaction.+A chat UI with a server-side Cancel button can use the `sessionId` exposed by the+hook, attach a fixed `ClientSession`, and call `session.cancel({ turnId })` after+observing that turn's `turn.started` event. The `turnId` guard makes a late click+a harmless no-op instead of cancelling a newer turn. Keep the stream open until+the cancellation boundary arrives; do not use `stop()` for this interaction.After eve confirms an attachment turn with `message.received`, the default reducer projects eachreceived attachment as a `file` part on the user message. The part includes `mediaType`, optional@@ -108,7 +111,7 @@ received attachment as a `file` part on the user message. The part includes `med## Human-in-the-loop prompts-Tools opt into approval with `approval`, and the model can also ask a question with `ask_question` — see [Human-in-the-loop](/docs/human-in-the-loop) for the server-side model. Either way the stream emits an `input.requested` event, and the pending request rides on a `dynamic-tool` part of the latest message at `part.toolMetadata?.eve?.inputRequest`. Read it, then answer through the same session with `send()`:+Tools opt into approval with `approval`, and the model can also ask a question with `ask_question` — see [Human-in-the-loop](/docs/human-in-the-loop) for the server-side model. Either way the stream emits an `input.requested` event, and the pending request rides on a `dynamic-tool` part of the latest message at `part.toolMetadata?.eve?.inputRequest`. Read it, then answer through the same session with `respond()`:```tsxconst request = agent.data.messages@@ -117,9 +120,7 @@ const request = agent.data.messages?.toolMetadata?.eve?.inputRequest;if (request) {- await agent.send({- inputResponses: [{ requestId: request.requestId, optionId: "approve" }],- });+ await agent.respond([{ requestId: request.requestId, optionId: "approve" }]);}```@@ -159,11 +160,10 @@ For fully custom state machines, `authorization.required` and `authorization.com## Attach page context per turn-`clientContext` adds ephemeral context for the next model call only. Strings (or an array of strings) become user-role context messages; an object is JSON-serialized into one. It rides along with a message or HITL response, so it never dispatches a turn on its own and never lands in durable session history. Pass it directly to `send()`:+`clientContext` adds ephemeral context for the next model call only. Strings (or an array of strings) become user-role context messages; an object is JSON-serialized into one. It rides along with a message or HITL response, so it never dispatches a turn on its own and never lands in durable session history. Pass it in the second argument to `send()` or `respond()`:```tsx-await agent.send({- message: "What should I do on this screen?",+await agent.send("What should I do on this screen?", {clientContext: { route: "/billing", plan: "pro", seatsUsed: 4 },});```@@ -226,11 +226,11 @@ const agent = useEveAgent({ reducer: toolCounter });The browser conversation lives durably on the server. Persist both the rendered event log and the `session` cursor to pick it back up after a reload:```tsx-import type { SessionState, MessageStreamEvent } from "eve/client";+import type { ClientSessionState, MessageStreamEvent } from "eve/client";type SavedEveChat = {events?: readonly MessageStreamEvent[];- session?: SessionState;+ session?: ClientSessionState;};const [saved] = useState<SavedEveChat>(() => {@@ -253,7 +253,11 @@ const agent = useEveAgent({});```-Store the full `session` object (`sessionId`, `continuationToken`, `streamIndex`), not a single field. The session cursor lets eve continue the durable conversation; the event log lets your UI render historical messages without replaying the whole stream. A database-backed chat app should usually persist stream events as they arrive with `onEvent` and then save a final snapshot in `onFinish`.+Store the full `session` object (`sessionId`, `streamIndex`). The session cursor+lets eve continue the exact durable conversation; the event log lets your UI+render historical messages without replaying the whole stream. A database-backed+chat app should usually persist stream events as they arrive with `onEvent` and+then save a final snapshot in `onFinish`.`initialEvents` must be an ordered prefix of the same session's stream, but its endpoint does not have to line up exactly with where the stream resumes. Every event carries a stable [`meta.id`](/docs/concepts/sessions-runs-and-streaming#the-event-envelope), and the store drops any event whose id it has already applied — so a saved log that overlaps the replayed prefix renders once, and `onEvent` only fires for events your UI has not seen.diff --git a/docs/guides/frontend/sveltekit.mdx b/docs/guides/frontend/sveltekit.mdxindex b51f870de..1805240d3 100644--- a/docs/guides/frontend/sveltekit.mdx+++ b/docs/guides/frontend/sveltekit.mdx@@ -56,7 +56,7 @@ With the plugin in `vite.config.ts`, components call [`useEveAgent`](./use-eve-aconst text = message.trim();if (!text || isBusy) return;message = "";- await agent.send({ message: text });+ await agent.send(text);}</script>diff --git a/docs/guides/frontend/use-eve-agent-svelte.mdx b/docs/guides/frontend/use-eve-agent-svelte.mdxindex 6e78c1d3d..b7cb1972e 100644--- a/docs/guides/frontend/use-eve-agent-svelte.mdx+++ b/docs/guides/frontend/use-eve-agent-svelte.mdx@@ -23,16 +23,17 @@ Import from `eve/svelte` and read the reactive getters directly. No `$` prefix:## What it returns-| Property | Type | Description |-| --------- | ------------------------------------------- | ------------------------------------------------------------------------- |-| `data` | `TData` | Projected state. With the default reducer, `EveMessageData` (`messages`). |-| `status` | `UseEveAgentStatus` | `"ready"`, `"submitted"`, `"streaming"`, or `"error"`. |-| `error` | `Error \| undefined` | Last transport-level error. |-| `events` | `readonly MessageStreamEvent[]` | Raw server events for this session. |-| `session` | `SessionState` | Snapshot of session state. |-| `send` | `(input: SendTurnPayload) => Promise<void>` | Send text or a full turn (multi-part, attachments, HITL responses). |-| `stop` | `() => void` | Abort the client's in-flight stream. |-| `reset` | `() => void` | Clear state and start a new session. |+| Property | Type | Description |+| --------- | --------------------------------------------- | ------------------------------------------------------------------------- |+| `data` | `TData` | Projected state. With the default reducer, `EveMessageData` (`messages`). |+| `status` | `UseEveAgentStatus` | `"ready"`, `"submitted"`, `"streaming"`, or `"error"`. |+| `error` | `Error \| undefined` | Last transport-level error. |+| `events` | `readonly MessageStreamEvent[]` | Raw server events for this session. |+| `session` | `ClientSessionState \| undefined` | Fixed session ID and stream cursor. |+| `send` | `(message, options?) => Promise<void>` | Send text or a multi-part message. |+| `respond` | `(inputResponses, options?) => Promise<void>` | Answer pending HITL input requests. |+| `stop` | `() => void` | Abort the client's in-flight stream. |+| `reset` | `() => void` | Clear state and start a new session. |These state fields are reactive getters, so read them straight from templates, `$derived`, or `$effect`. They are not stores, so don't prefix them with `$`.@@ -49,7 +50,7 @@ These state fields are reactive getters, so read them straight from templates, `const text = message.trim();if (!text) return;message = "";- await agent.send({ message: text });+ await agent.send(text);}</script>@@ -68,17 +69,15 @@ When a turn is more than plain text, reach for `send()`. Attachments follow theconst bytes = new Uint8Array(await file.arrayBuffer());const base64 = btoa(String.fromCodePoint(...bytes));-await agent.send({- message: [- { type: "text", text: "Describe this image." },- { type: "file", data: `data:${file.type};base64,${base64}`, mediaType: file.type },- ],-});+await agent.send([+ { type: "text", text: "Describe this image." },+ { type: "file", data: `data:${file.type};base64,${base64}`, mediaType: file.type },+]);```## Human-in-the-loop prompts-A tool opts into approval with `approval` ([Tools](../../tools)). When one fires, the pending request rides along on a `dynamic-tool` part of the latest message at `part.toolMetadata?.eve?.inputRequest`. Read it, then answer through the same session with `agent.send({ inputResponses })`:+A tool opts into approval with `approval` ([Tools](../../tools)). When one fires, the pending request rides along on a `dynamic-tool` part of the latest message at `part.toolMetadata?.eve?.inputRequest`. Read it, then answer through the same session with `agent.respond(inputResponses)`:```tsimport type { EveDynamicToolPart, EveMessagePart } from "eve/svelte";@@ -93,9 +92,7 @@ const request = agent.data.messages.find((value) => value !== undefined);if (request) {- await agent.send({- inputResponses: [{ requestId: request.requestId, optionId: "approve" }],- });+ await agent.respond([{ requestId: request.requestId, optionId: "approve" }]);}```@@ -133,8 +130,7 @@ const agent = useEveAgent({`clientContext` adds ephemeral context for the next model call and nothing more. Strings (or an array of strings) become user-role context messages; an object is JSON-serialized into one. It rides along with a message or HITL response, never dispatches a turn on its own, and never lands in durable session history. Pass it to `send()`:```ts-await agent.send({- message: "What should I do on this screen?",+await agent.send("What should I do on this screen?", {clientContext: { route: "/billing", plan: "pro", seatsUsed: 4 },});```diff --git a/docs/guides/frontend/use-eve-agent-vue.mdx b/docs/guides/frontend/use-eve-agent-vue.mdxindex a6332efe5..55053ec29 100644--- a/docs/guides/frontend/use-eve-agent-vue.mdx+++ b/docs/guides/frontend/use-eve-agent-vue.mdx@@ -25,16 +25,17 @@ const { data } = useEveAgent();## What it returns-| Property | Type | Description |-| --------- | -------------------------------------------- | ------------------------------------------------------------------------- |-| `data` | `ComputedRef<TData>` | Projected state. With the default reducer, `EveMessageData` (`messages`). |-| `status` | `ComputedRef<UseEveAgentStatus>` | `"ready"`, `"submitted"`, `"streaming"`, or `"error"`. |-| `error` | `ComputedRef<Error \| undefined>` | Last transport-level error. |-| `events` | `ComputedRef<readonly MessageStreamEvent[]>` | Raw server events for this session. |-| `session` | `ComputedRef<SessionState>` | Snapshot of session state. |-| `send` | `(input: SendTurnPayload) => Promise<void>` | Send text or a full turn (multi-part, attachments, HITL responses). |-| `stop` | `() => void` | Abort the client's in-flight stream. |-| `reset` | `() => void` | Clear state and start a new session. |+| Property | Type | Description |+| --------- | ---------------------------------------------- | ------------------------------------------------------------------------- |+| `data` | `ComputedRef<TData>` | Projected state. With the default reducer, `EveMessageData` (`messages`). |+| `status` | `ComputedRef<UseEveAgentStatus>` | `"ready"`, `"submitted"`, `"streaming"`, or `"error"`. |+| `error` | `ComputedRef<Error \| undefined>` | Last transport-level error. |+| `events` | `ComputedRef<readonly MessageStreamEvent[]>` | Raw server events for this session. |+| `session` | `ComputedRef<ClientSessionState \| undefined>` | Fixed session ID and stream cursor. |+| `send` | `(message, options?) => Promise<void>` | Send text or a multi-part message. |+| `respond` | `(inputResponses, options?) => Promise<void>` | Answer pending HITL input requests. |+| `stop` | `() => void` | Abort the client's in-flight stream. |+| `reset` | `() => void` | Clear state and start a new session. |The first five are `ComputedRef`s; the rest are methods. Destructure whatever you need, since refs keep their reactivity through destructuring. Read them with `.value` in `<script>`, and unwrapped in `<template>`.@@ -52,7 +53,7 @@ async function handleSubmit() {const text = message.value.trim();if (!text) return;message.value = "";- await send({ message: text });+ await send(text);}</script>@@ -77,24 +78,22 @@ async function onFileChange(event: Event) {if (!file) return;const bytes = new Uint8Array(await file.arrayBuffer());const base64 = btoa(String.fromCodePoint(...bytes));- await send({- message: [- { type: "text", text: "Describe this image." },- { type: "file", data: `data:${file.type};base64,${base64}`, mediaType: file.type },- ],- });+ await send([+ { type: "text", text: "Describe this image." },+ { type: "file", data: `data:${file.type};base64,${base64}`, mediaType: file.type },+ ]);}</script>```## Human-in-the-loop prompts-A tool opts into approval with `approval` ([Tools](../../tools)). When it triggers, the pending request shows up as a `dynamic-tool` part on the latest message at `part.toolMetadata?.eve?.inputRequest`. Read it, then answer through the same session with `send({ inputResponses })`:+A tool opts into approval with `approval` ([Tools](../../tools)). When it triggers, the pending request shows up as a `dynamic-tool` part on the latest message at `part.toolMetadata?.eve?.inputRequest`. Read it, then answer through the same session with `respond(inputResponses)`:```tsimport type { EveDynamicToolPart, EveMessagePart } from "eve/vue";-const { data, send } = useEveAgent();+const { data, respond } = useEveAgent();const isDynamicToolPart = (part: EveMessagePart): part is EveDynamicToolPart =>part.type === "dynamic-tool";@@ -106,9 +105,7 @@ const request = data.value.messages.find((value) => value !== undefined);if (request) {- await send({- inputResponses: [{ requestId: request.requestId, optionId: "approve" }],- });+ await respond([{ requestId: request.requestId, optionId: "approve" }]);}```@@ -143,11 +140,10 @@ const agent = useEveAgent({## Attach page context per turn-`clientContext` adds ephemeral context for the next model call and nothing more. Strings (or an array of strings) become user-role context messages; an object is JSON-serialized into one. It rides along with a message or HITL response, never dispatches a turn on its own, and never lands in durable session history. Pass it to `send()`:+`clientContext` adds ephemeral context for the next model call and nothing more. Strings (or an array of strings) become user-role context messages; an object is JSON-serialized into one. It rides along with a message or HITL response, never dispatches a turn on its own, and never lands in durable session history. Pass it in the second argument to `send()` or `respond()`:```ts-await send({- message: "What should I do on this screen?",+await send("What should I do on this screen?", {clientContext: { route: "/billing", plan: "pro", seatsUsed: 4 },});```diff --git a/docs/guides/instrumentation.md b/docs/guides/instrumentation.mdindex be2ede235..92dc48b4e 100644--- a/docs/guides/instrumentation.md+++ b/docs/guides/instrumentation.md@@ -181,7 +181,7 @@ When `eve build` fails on discovery errors, the CLI prints the full diagnostics| --------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- || Tool not discovered (the model never sees it) | Run `eve info`. Confirm the file is in the right slot (`agent/tools/<name>.ts`) and default-exports `defineTool(...)`, and check `.eve/diagnostics.json` for shape errors. `schedules/` are root-only. || Model won't call a tool it should | Tighten the tool `description` and `inputSchema`; put procedural guidance in a [skill](../skills), not the description. Confirm it's in the active set with `eve info`. |-| Stuck on `session.waiting` | The turn is parked on an approval, a question, or a connection sign-in. Answer it, or POST a follow-up with the `continuationToken` (a stale token is rejected). |+| Stuck on `session.waiting` | The turn is parked for input. Answer the pending approval or question, or POST a follow-up to `/eve/v1/session/:sessionId`. || 401 on production routes | Expected: auth fails closed. Replace `placeholderAuth()` with your route policy. Use `vercelOidc()` only for Vercel-issued tokens; otherwise configure `httpBasic()`, JWT/OIDC helpers, or a custom `AuthFn`. See [Auth and route protection](./auth-and-route-protection). || Build fails with discovery errors | Read the printed diagnostics and `.eve/diagnostics.json`; confirm the root-vs-subagent boundary is valid and secrets come from env vars. |diff --git a/docs/patterns/dynamic-scheduling.md b/docs/patterns/dynamic-scheduling.mdindex 76ab441c3..ab208edfb 100644--- a/docs/patterns/dynamic-scheduling.md+++ b/docs/patterns/dynamic-scheduling.md@@ -35,7 +35,7 @@ import { scheduleStore } from "../lib/schedule-store";export default defineSchedule({cron: "* * * * *",- run({ receive, waitUntil }) {+ run({ to, waitUntil }) {waitUntil((async () => {const jobs = await scheduleStore.claimDue({@@ -47,25 +47,26 @@ export default defineSchedule({await Promise.all(jobs.map(async (job) => {try {- await receive(slack, {- message: [+ await to(slack, { channelId: job.channelId }).send(+ [`Run dynamic schedule ${job.id}.`,"Complete this tenant-owned task:",job.prompt,].join("\n\n"),- target: { channelId: job.channelId },- auth: {- attributes: {- tenantId: job.tenantId,- role: job.ownerRole,- scheduleId: job.id,+ {+ auth: {+ attributes: {+ tenantId: job.tenantId,+ role: job.ownerRole,+ scheduleId: job.id,+ },+ authenticator: job.authenticator,+ ...(job.issuer ? { issuer: job.issuer } : {}),+ principalId: job.ownerId,+ principalType: "user",},- authenticator: job.authenticator,- ...(job.issuer ? { issuer: job.issuer } : {}),- principalId: job.ownerId,- principalType: "user",},- });+ );await scheduleStore.complete(job);} catch (error) {await scheduleStore.release(job, { error, retryAt: new Date(Date.now() + 300_000) });@@ -78,7 +79,7 @@ export default defineSchedule({});```-`waitUntil` keeps the cron invocation alive until claiming and handoff settle. `receive` starts the same durable runtime used by inbound channel messages.+`waitUntil` keeps the cron invocation alive until claiming and handoff settle. `to(...).send(...)` starts the same durable runtime used by inbound channel messages.This example uses Slack because it has a proactive target of `{ channelId }`. Any channel that implements `receive` can replace it.diff --git a/docs/schedules.mdx b/docs/schedules.mdxindex 59e126cfe..f10a69763 100644--- a/docs/schedules.mdx+++ b/docs/schedules.mdx@@ -19,7 +19,7 @@ interface ScheduleDefinition {}interface ScheduleHandlerArgs {- receive: CrossChannelReceiveFn; // hand the work off to a channel+ to: ScheduleToFn; // select a channel target, then sendwaitUntil: (task: Promise<unknown>) => void; // keep the cron task alive past returnappAuth: SessionAuthContext; // pre-built app principal}@@ -56,7 +56,7 @@ Sweep stale workflow state.## Handler form (`run`)-Use a handler when the schedule needs to deliver to a channel, branch on conditions, or compute its arguments at fire time. The handler is in full control. It has no channel of its own, so it passes the work to one with `receive`.+Use a handler when the schedule needs to deliver to a channel, branch on conditions, or compute its arguments at fire time. The handler is in full control. It has no channel of its own, so it selects a channel target with `to(...)` and sends through the returned handle.```ts title="agent/schedules/critical-alerts.ts"import { defineSchedule } from "eve/schedules";@@ -65,13 +65,12 @@ import slack from "../channels/slack";export default defineSchedule({cron: "* * * * *",- async run({ receive, waitUntil, appAuth }) {+ async run({ to, waitUntil, appAuth }) {waitUntil(- receive(slack, {- message: "Check for new critical alerts. Report only when there are any.",- target: { channelId: "C0123ABC" },- auth: appAuth,- }),+ to(slack, { channelId: "C0123ABC" }).send(+ "Check for new critical alerts. Report only when there are any.",+ { auth: appAuth },+ ),);},});@@ -79,9 +78,9 @@ export default defineSchedule({The agent does not have to deliver a message on every run. When a prompt makes delivery conditional, as in the alert check above, eve tells the agent how to finish successfully without sending anything to the channel. Frequent polling schedules do not need a separate filter or delivery setting.-- `receive(channel, { message, target, auth })`: starts a session on another channel. Same contract as a route handler's `args.receive`.-- `waitUntil(promise)`: extends the cron task's lifetime so the parked session and any in-flight fetches settle before the task ends. Wrap the `receive` call in it.-- `appAuth`: the app principal (`{ authenticator: "app", principalId: "eve:app", principalType: "runtime" }`). Pass it as `receive(..., { auth: appAuth })` for work the agent does on its own behalf.+- `to(channel, target).send(message, { auth })`: starts a session on another channel. It has the same contract as a route handler's `ctx.to(...)` handle.+- `waitUntil(promise)`: extends the cron task's lifetime so the parked session and any in-flight fetches settle before the task ends. Wrap the `send` call in it.+- `appAuth`: the app principal (`{ authenticator: "app", principalId: "eve:app", principalType: "runtime" }`). Pass it as `to(...).send(..., { auth: appAuth })` for work the agent does on its own behalf.A handler-form session runs on the same durable runtime engine as any other session, so it can park (durably suspend), for instance when the channel handoff is waiting for a Slack reply. Only markdown task mode is barred from waiting.diff --git a/docs/tools/human-in-the-loop.md b/docs/tools/human-in-the-loop.mdindex d48d20edc..4fb31c87d 100644--- a/docs/tools/human-in-the-loop.md+++ b/docs/tools/human-in-the-loop.md@@ -58,7 +58,7 @@ Gating a side effect on approval is also how you make non-idempotent work safe a### Skipping approval for schedule-dispatched turns-`session.auth.current` identifies the caller of this turn. Markdown schedules use the app principal (`authenticator: "app"`, `principalId: "eve:app"`, `principalType: "runtime"`) automatically. A `run` schedule must pass its `appAuth` to `receive(...)` for the child session to use that principal. Match all three fields to skip approval for automated turns while still prompting when a person calls the same tool:+`session.auth.current` identifies the caller of this turn. Markdown schedules use the app principal (`authenticator: "app"`, `principalId: "eve:app"`, `principalType: "runtime"`) automatically. A `run` schedule must pass its `appAuth` to `send(...)` for the child session to use that principal. Match all three fields to skip approval for automated turns while still prompting when a person calls the same tool:```ts title="agent/tools/refund_charge.ts"import { defineTool } from "eve/tools";diff --git a/docs/tutorial/ship-it.mdx b/docs/tutorial/ship-it.mdxindex 6f6fd36a9..b2cb27381 100644--- a/docs/tutorial/ship-it.mdx+++ b/docs/tutorial/ship-it.mdx@@ -43,7 +43,7 @@ export function AgentChat() {event.preventDefault();const data = new FormData(event.currentTarget);const message = String(data.get("q") ?? "").trim();- if (message) void agent.send({ message });+ if (message) void agent.send(message);}}>{agent.data.messages.map((message) => (diff --git a/e2e/fixtures/agent-basic-runtime/evals/runtime/client-context.eval.ts b/e2e/fixtures/agent-basic-runtime/evals/runtime/client-context.eval.tsindex a3c0c64e7..f6598aab7 100644--- a/e2e/fixtures/agent-basic-runtime/evals/runtime/client-context.eval.ts+++ b/e2e/fixtures/agent-basic-runtime/evals/runtime/client-context.eval.ts@@ -14,9 +14,8 @@ export default defineEval({description: "Session runtime smoke: client context.",async test(t) {- await t.send({+ await t.send("Say hello.", {clientContext: [`include the exact token ${CLIENT_CONTEXT_TOKEN} verbatim`],- message: "Say hello.",});t.succeeded();diff --git a/e2e/fixtures/agent-basic-runtime/evals/runtime/output-schema-turn.eval.ts b/e2e/fixtures/agent-basic-runtime/evals/runtime/output-schema-turn.eval.tsindex 565cd5afb..0d1b1d3ec 100644--- a/e2e/fixtures/agent-basic-runtime/evals/runtime/output-schema-turn.eval.ts+++ b/e2e/fixtures/agent-basic-runtime/evals/runtime/output-schema-turn.eval.ts@@ -14,8 +14,7 @@ export default defineEval({description: "Session runtime smoke: output schema.",async test(t) {- const structured = await t.send({- message: "Summarize this turn as structured output.",+ const structured = await t.send("Summarize this turn as structured output.", {outputSchema: {properties: { count: { type: "integer" }, title: { type: "string" } },required: ["title", "count"],diff --git a/e2e/fixtures/agent-cancellation/agent/channels/threads.ts b/e2e/fixtures/agent-cancellation/agent/channels/threads.tsindex 1908f9c20..74e585fb5 100644--- a/e2e/fixtures/agent-cancellation/agent/channels/threads.ts+++ b/e2e/fixtures/agent-cancellation/agent/channels/threads.ts@@ -11,41 +11,39 @@ const AUTH = {* Chat-style channel for continuation-addressed session-control evals.** Messages address a thread by channel-local continuation token. The stop- * and session-control routes act through public channel helpers without+ * and session-control routes act through channel operations without* knowing the runtime session id.*/export default defineChannel({routes: [- POST("/threads/:threadId/messages", async (request, { params, send }) => {+ POST("/threads/:threadId/messages", async (request, { from, params }) => {const body = (await request.json().catch(() => ({}))) as { message?: string };- const session = await send(body.message ?? "", {+ const session = await from(params.threadId ?? "").send(body.message ?? "", {auth: AUTH,- continuationToken: params.threadId ?? "",});return Response.json({ ok: true, sessionId: session.id });}),- POST("/threads/:threadId/stop", async (_request, { params, cancel }) => {- const result = await cancel({ continuationToken: params.threadId ?? "" });+ POST("/threads/:threadId/stop", async (_request, { from, params }) => {+ const result = await from(params.threadId ?? "").cancel();return Response.json(result);}),- POST("/threads/:threadId/new", async (_request, { params, reset }) => {- const result = await reset({- continuationToken: params.threadId ?? "",+ POST("/threads/:threadId/new", async (_request, { from, params }) => {+ const result = await from(params.threadId ?? "").reset({reason: "E2E user requested /new",});return Response.json({ acknowledgement: "Started a new conversation.", ...result });}),- POST("/threads/:threadId/compact", async (_request, { compact, params }) => {- const result = await compact({ continuationToken: params.threadId ?? "" });+ POST("/threads/:threadId/compact", async (_request, { from, params }) => {+ const result = await from(params.threadId ?? "").compact();return Response.json(result);}),- POST("/threads/:threadId/clear", async (_request, { clear, params }) => {- const result = await clear({ continuationToken: params.threadId ?? "" });+ POST("/threads/:threadId/clear", async (_request, { from, params }) => {+ const result = await from(params.threadId ?? "").clear();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 });+ POST("/threads/:threadId/owner", async (_request, { params, resolveSession }) => {+ const session = await resolveSession(params.threadId ?? "");+ return Response.json({ sessionId: session?.id ?? null });}),],});diff --git a/e2e/fixtures/agent-cancellation/evals/cancellation/cancel-turn.eval.ts b/e2e/fixtures/agent-cancellation/evals/cancellation/cancel-turn.eval.tsindex e35c42def..617e146fb 100644--- a/e2e/fixtures/agent-cancellation/evals/cancellation/cancel-turn.eval.ts+++ b/e2e/fixtures/agent-cancellation/evals/cancellation/cancel-turn.eval.ts@@ -9,7 +9,7 @@ const TOOL_NAME = "wait-for-cancellation";* Flow: start a turn that hangs mid-tool, request cooperative cancellation,* and assert the turn settles as `turn.cancelled` followed by* `session.waiting` with zero failure events. Then prove the session accepts a- * follow-up normally and a late duplicate cancel is a benign no-op.+ * follow-up normally and a late duplicate cancel is accepted as a benign no-op.*/export default defineEval({tags: ["real-model"],@@ -31,7 +31,7 @@ export default defineEval({cancelled,satisfies((value: typeof cancelled) =>- value.sessionId === live.sessionId && value.status === "accepted",+ value.status === "accepted" && value.sessionId === live.sessionId,"cancel request is accepted with status 'accepted'",),);@@ -50,15 +50,22 @@ export default defineEval({followUp.notEvent("session.failed");followUp.messageIncludes(/CANCELLATION-FOLLOW-UP-OK/i);- const lateStatus = (await t.cancel()).status;+ const late = await t.cancel();await t.require(- lateStatus,+ late,satisfies(- (value: typeof lateStatus) => value === "accepted" || value === "no_active_turn",- "a late cancel is accepted as a no-op or reports no_active_turn",+ (value: typeof late) => value.status === "accepted" && value.sessionId === live.sessionId,+ "a live parked session accepts a late cancel as a no-op",),);+ const afterLateCancel = await t.send("Reply with exactly CANCELLATION-LATE-NOOP-OK.");+ afterLateCancel.expectOk();+ afterLateCancel.notEvent("turn.cancelled");+ afterLateCancel.notEvent("turn.failed");+ afterLateCancel.notEvent("session.failed");+ afterLateCancel.messageIncludes(/CANCELLATION-LATE-NOOP-OK/i);+t.event("turn.cancelled", { count: 1 });},});diff --git a/e2e/fixtures/agent-cancellation/evals/cancellation/unified-http-session-operations.eval.ts b/e2e/fixtures/agent-cancellation/evals/cancellation/unified-http-session-operations.eval.tsnew file mode 100644index 000000000..a0d33d22f--- /dev/null+++ b/e2e/fixtures/agent-cancellation/evals/cancellation/unified-http-session-operations.eval.ts@@ -0,0 +1,225 @@+import { defineEval, type EveEvalTargetHandle } from "eve/evals";+import { satisfies } from "eve/evals/expect";++const TOOL_NAME = "wait-for-cancellation";++interface AcceptedResponse {+ readonly ok?: boolean;+ readonly sessionId?: string;+ readonly status?: string;+}++interface ResetResponse {+ readonly ok?: boolean;+ readonly previousSessionId?: string;+ readonly status?: string;+}++async function postJson<T>(+ target: EveEvalTargetHandle,+ path: string,+ body: unknown,+ expectedStatus: number,+): 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.status !== expectedStatus) {+ throw new Error(+ `POST ${path} returned ${response.status}, expected ${expectedStatus}: ${text}`,+ );+ }+ return JSON.parse(text) as T;+}++/** Exercises every ID-only eve HTTP session operation as one lifecycle. */+export default defineEval({+ tags: ["real-model"],+ description: "Keep HTTP session operations pinned to one immutable session ID.",+ timeoutMs: 240_000,++ async test(t) {+ const created = await postJson<AcceptedResponse>(+ t.target,+ "/eve/v1/session",+ { message: "Reply with exactly HTTP-SESSION-INITIAL-OK." },+ 202,+ );+ await t.require(+ created,+ satisfies(+ (value: AcceptedResponse) =>+ value.ok === true && value.status === "accepted" && typeof value.sessionId === "string",+ "the HTTP session route creates a session without a continuation token",+ ),+ );+ const sessionId = created.sessionId!;++ const initial = await t.target.watchTurn(sessionId).result();+ initial.notEvent("turn.failed");+ initial.notEvent("session.failed");+ initial.messageIncludes(/HTTP-SESSION-INITIAL-OK/i);++ const liveCancellation = t.target.watchTurn(sessionId, {+ startIndex: initial.events.length,+ });+ const sent = await postJson<AcceptedResponse>(+ t.target,+ `/eve/v1/session/${sessionId}`,+ { message: "Please wait for cancellation." },+ 202,+ );+ await t.require(+ sent,+ satisfies(+ (value: AcceptedResponse) => value.status === "accepted" && value.sessionId === sessionId,+ "the message route sends to the exact session ID",+ ),+ );++ await liveCancellation.waitForEvent("actions.requested", {+ data: {+ actions: (actions) =>+ actions.some((action) => action.kind === "tool-call" && action.toolName === TOOL_NAME),+ },+ });+ const cancelled = await postJson<AcceptedResponse>(+ t.target,+ `/eve/v1/session/${sessionId}/cancel`,+ {},+ 202,+ );+ await t.require(+ cancelled,+ satisfies(+ (value: AcceptedResponse) => value.status === "accepted" && value.sessionId === sessionId,+ "cancel targets the exact session ID",+ ),+ );++ const cancelledTurn = await liveCancellation.result();+ cancelledTurn.event("turn.cancelled", { count: 1 });+ cancelledTurn.eventOrder([{ type: "turn.cancelled" }, { type: "session.waiting" }]);+ cancelledTurn.notEvent("turn.failed");+ cancelledTurn.notEvent("session.failed");++ let eventIndex = initial.events.length + cancelledTurn.events.length;+ const liveCompaction = t.target.watchTurn(sessionId, { startIndex: eventIndex });+ const compacted = await postJson<AcceptedResponse>(+ t.target,+ `/eve/v1/session/${sessionId}/compact`,+ {},+ 202,+ );+ await t.require(+ compacted,+ satisfies(+ (value: AcceptedResponse) => value.status === "accepted" && value.sessionId === sessionId,+ "compact targets the exact session ID",+ ),+ );+ const compactedEvents = await liveCompaction.result();+ compactedEvents.eventOrder([+ { type: "compaction.requested" },+ { type: "compaction.completed" },+ { type: "session.waiting" },+ ]);+ compactedEvents.notEvent("turn.started");+ eventIndex += compactedEvents.events.length;++ const liveClear = t.target.watchTurn(sessionId, { startIndex: eventIndex });+ const cleared = await postJson<AcceptedResponse>(+ t.target,+ `/eve/v1/session/${sessionId}/clear`,+ {},+ 202,+ );+ await t.require(+ cleared,+ satisfies(+ (value: AcceptedResponse) => value.status === "accepted" && value.sessionId === sessionId,+ "clear targets the exact session ID",+ ),+ );+ const clearedEvents = await liveClear.result();+ clearedEvents.event("context.cleared", { count: 1 });+ clearedEvents.eventOrder([{ type: "context.cleared" }, { type: "session.waiting" }]);+ clearedEvents.notEvent("turn.started");+ eventIndex += clearedEvents.events.length;++ const liveFollowUp = t.target.watchTurn(sessionId, { startIndex: eventIndex });+ const followUpResponse = await postJson<AcceptedResponse>(+ t.target,+ `/eve/v1/session/${sessionId}`,+ { message: "Reply with exactly HTTP-SESSION-FOLLOW-UP-OK." },+ 202,+ );+ await t.require(+ followUpResponse,+ satisfies(+ (value: AcceptedResponse) => value.status === "accepted" && value.sessionId === sessionId,+ "the same session accepts a message after compact and clear",+ ),+ );+ const followUp = await liveFollowUp.result();+ followUp.notEvent("turn.failed");+ followUp.notEvent("session.failed");+ followUp.messageIncludes(/HTTP-SESSION-FOLLOW-UP-OK/i);++ const reset = await postJson<ResetResponse>(+ t.target,+ `/eve/v1/session/${sessionId}/reset`,+ { reason: "Verify immutable HTTP session identity" },+ 200,+ );+ await t.require(+ reset,+ satisfies(+ (value: ResetResponse) => value.status === "reset" && value.previousSessionId === sessionId,+ "reset terminally retires the exact session ID",+ ),+ );++ const rejected = await postJson<{ readonly code?: string; readonly ok?: boolean }>(+ t.target,+ `/eve/v1/session/${sessionId}`,+ { message: "This must not create or follow a replacement." },+ 409,+ );+ await t.require(+ rejected,+ satisfies(+ (value: { readonly code?: string; readonly ok?: boolean }) =>+ value.ok === false && value.code === "session_not_active",+ "a reset session ID cannot send or create a replacement",+ ),+ );++ const replacement = await postJson<AcceptedResponse>(+ t.target,+ "/eve/v1/session",+ { message: "Reply with exactly HTTP-SESSION-REPLACEMENT-OK." },+ 202,+ );+ await t.require(+ replacement,+ satisfies(+ (value: AcceptedResponse) =>+ value.status === "accepted" &&+ typeof value.sessionId === "string" &&+ value.sessionId !== sessionId,+ "a replacement session requires explicit creation",+ ),+ );++ const replacementTurn = await t.target.watchTurn(replacement.sessionId!).result();+ replacementTurn.notEvent("turn.failed");+ replacementTurn.notEvent("session.failed");+ replacementTurn.messageIncludes(/HTTP-SESSION-REPLACEMENT-OK/i);++ t.succeeded();+ },+});diff --git a/e2e/fixtures/agent-channels/agent/channels/target.ts b/e2e/fixtures/agent-channels/agent/channels/target.tsindex fa096e96c..cb72e08b8 100644--- a/e2e/fixtures/agent-channels/agent/channels/target.ts+++ b/e2e/fixtures/agent-channels/agent/channels/target.ts@@ -7,12 +7,11 @@ import { defineChannel, POST } from "eve/channels";*/export default defineChannel({routes: [POST("/target", async () => new Response("ok"))],- async receive(input, { send }) {+ async receive(input, { from }) {const sessionRef =typeof input.target.sessionRef === "string" ? input.target.sessionRef : "default";- return send(input.message, {+ return from(`target:${sessionRef}`).send(input.message, {auth: input.auth,- continuationToken: `target:${sessionRef}`,});},});diff --git a/e2e/fixtures/agent-channels/agent/channels/webhook.ts b/e2e/fixtures/agent-channels/agent/channels/webhook.tsindex 2076ff24f..d000e7c32 100644--- a/e2e/fixtures/agent-channels/agent/channels/webhook.ts+++ b/e2e/fixtures/agent-channels/agent/channels/webhook.ts@@ -2,28 +2,28 @@ import { defineChannel, POST } from "eve/channels";import target from "./target";/**- * Exercises the cross-channel `args.receive(channel, …)` path: the+ * Exercises the cross-channel `ctx.to(channel, target).send(...)` path: the* webhook handler does not start a session of its own; it hands the* message off to the target channel and returns the new session id so* the smoke test client can stream the resulting turn.*/export default defineChannel({routes: [- POST("/webhook", async (req, args) => {+ POST("/webhook", async (req, ctx) => {const body = (await req.json().catch(() => ({}))) as {message?: string;sessionRef?: string;};- const session = await args.receive(target, {- message: body.message ?? "Reply with the single word: hello.",- target: { sessionRef: body.sessionRef ?? crypto.randomUUID() },- auth: {- attributes: { source: "smoke-test" },- authenticator: "webhook",- principalId: "smoke-test",- principalType: "service",- },- });+ const session = await ctx+ .to(target, { sessionRef: body.sessionRef ?? crypto.randomUUID() })+ .send(body.message ?? "Reply with the single word: hello.", {+ auth: {+ attributes: { source: "smoke-test" },+ authenticator: "webhook",+ principalId: "smoke-test",+ principalType: "service",+ },+ });return Response.json({ ok: true, sessionId: session.id });}),],diff --git a/e2e/fixtures/agent-channels/evals/custom-channels/cross-channel-receive.eval.ts b/e2e/fixtures/agent-channels/evals/custom-channels/cross-channel-receive.eval.tsindex 4beaab683..7e746d13b 100644--- a/e2e/fixtures/agent-channels/evals/custom-channels/cross-channel-receive.eval.ts+++ b/e2e/fixtures/agent-channels/evals/custom-channels/cross-channel-receive.eval.ts@@ -4,10 +4,10 @@ import { satisfies } from "eve/evals/expect";import { postChannel } from "./shared";/**- * Custom-channel eval for cross-channel `args.receive` handoff.+ * Custom-channel eval for cross-channel `ctx.to(...).send(...)` handoff.** The `/webhook` route does not start a session itself; it hands the- * message to the target channel via `args.receive` and returns the new+ * message to the target channel via `ctx.to(...).send(...)` and returns the new* session id, which we attach to and drive to a turn boundary.*/export default defineEval({diff --git a/e2e/fixtures/agent-schedules/agent/channels/quiet-sink.ts b/e2e/fixtures/agent-schedules/agent/channels/quiet-sink.tsindex 715d9777f..334dd2874 100644--- a/e2e/fixtures/agent-schedules/agent/channels/quiet-sink.ts+++ b/e2e/fixtures/agent-schedules/agent/channels/quiet-sink.ts@@ -2,10 +2,9 @@ import { defineChannel, POST } from "eve/channels";export default defineChannel<undefined, void, { id: string }>({routes: [POST("/quiet-sink", async () => new Response("ok"))],- receive(input, { send }) {- return send(input.message, {+ receive(input, { from }) {+ return from(input.target.id).send(input.message, {auth: input.auth,- continuationToken: input.target.id,});},events: {diff --git a/e2e/fixtures/agent-schedules/agent/schedules/quiet-alerts.ts b/e2e/fixtures/agent-schedules/agent/schedules/quiet-alerts.tsindex cdaf0c64a..e5c4d2262 100644--- a/e2e/fixtures/agent-schedules/agent/schedules/quiet-alerts.ts+++ b/e2e/fixtures/agent-schedules/agent/schedules/quiet-alerts.ts@@ -4,17 +4,18 @@ import quietSink from "../channels/quiet-sink";export default defineSchedule({cron: "* * * * *",- run({ receive, waitUntil, appAuth }) {+ run({ to, waitUntil, appAuth }) {waitUntil(- receive(quietSink, {- auth: appAuth,- message: [+ to(quietSink, { id: "quiet-alerts" }).send(+ ["Call the `check-alerts` tool exactly once with an empty object.","Report the critical alerts only when the returned `alerts` list is non-empty.","Do not send a message when the list is empty.",].join("\n"),- target: { id: "quiet-alerts" },- }),+ {+ auth: appAuth,+ },+ ),);},});diff --git a/e2e/fixtures/agent-session-limits/evals/limits/session-token-limit-approve.eval.ts b/e2e/fixtures/agent-session-limits/evals/limits/session-token-limit-approve.eval.tsindex 6395440d7..a2904f97d 100644--- a/e2e/fixtures/agent-session-limits/evals/limits/session-token-limit-approve.eval.ts+++ b/e2e/fixtures/agent-session-limits/evals/limits/session-token-limit-approve.eval.ts@@ -16,16 +16,11 @@ export default defineEval({);await active.waitForEvent("actions.requested");- const continuationToken = t.state.continuationToken;- if (continuationToken === undefined) {- throw new Error("The active session did not expose a continuation token.");- }-const deliverWhileActive = async (message: string): Promise<void> => {const response = await t.target.fetch(`/eve/v1/session/${encodeURIComponent(active.sessionId)}`,{- body: JSON.stringify({ continuationToken, message }),+ body: JSON.stringify({ message }),headers: { "content-type": "application/json" },method: "POST",},@@ -46,8 +41,12 @@ export default defineEval({toolName: "session_limit_continuation",});+ const activeState = t.state;+ if (activeState === undefined) {+ throw new Error("The active eval session did not expose client state.");+ }const queuedSession = t.target.watchTurn(active.sessionId, {- startIndex: t.state.streamIndex,+ startIndex: activeState.streamIndex,});const queuedA = await queuedSession.result();queuedA.event("message.received", { count: 1 });@@ -56,8 +55,12 @@ export default defineEval({const received = events.find((event) => event.type === "message.received");return received !== undefined && received.data.message.includes("Queued message A");});+ const queuedState = queuedSession.session.state;+ if (queuedState === undefined) {+ throw new Error("The attached eval session did not expose client state.");+ }const queuedBSession = t.target.watchTurn(active.sessionId, {- startIndex: queuedSession.session.state.streamIndex,+ startIndex: queuedState.streamIndex,});const queuedB = await queuedBSession.result();queuedB.event("message.received", { count: 1 });@@ -73,16 +76,18 @@ export default defineEval({equals(1),);- const resumed = await queuedBSession.session.respond({- optionId: "continue",- requestId: request.requestId,- });+ const resumed = await queuedBSession.session.respond([+ {+ optionId: "continue",+ requestId: request.requestId,+ },+ ]);resumed.expectOk();resumed.event("step.started");resumed.notEvent("input.requested");resumed.messageIncludes("approved");t.check(resumed.sessionId, equals(active.sessionId));- t.check(queuedBSession.session.state.sessionId, equals(active.sessionId));+ t.check(queuedBSession.session.sessionId, equals(active.sessionId));const nextPrompt = await queuedBSession.session.send('Post-approval probe: reply with exactly "same session".',@@ -91,7 +96,7 @@ export default defineEval({nextPrompt.notEvent("message.completed");t.check(nextPrompt.sessionId, equals(active.sessionId));t.check(nextPrompt.status, equals("waiting"));- t.check(queuedBSession.session.state.sessionId, equals(active.sessionId));+ t.check(queuedBSession.session.sessionId, equals(active.sessionId));const nextRequest = queuedBSession.session.requireInputRequest({display: "confirmation",diff --git a/e2e/fixtures/agent-session-limits/evals/limits/session-token-limit-continuation.eval.ts b/e2e/fixtures/agent-session-limits/evals/limits/session-token-limit-continuation.eval.tsindex 10968625a..0f00b44e5 100644--- a/e2e/fixtures/agent-session-limits/evals/limits/session-token-limit-continuation.eval.ts+++ b/e2e/fixtures/agent-session-limits/evals/limits/session-token-limit-continuation.eval.ts@@ -27,7 +27,7 @@ export default defineEval({toolName: "session_limit_continuation",});- const resumed = await t.respond({ optionId: "continue", requestId: request.requestId });+ const resumed = await t.respond([{ optionId: "continue", requestId: request.requestId }]);resumed.expectOk();t.succeeded();t.messageIncludes("limit pong");@@ -45,10 +45,12 @@ export default defineEval({toolName: "session_limit_continuation",});- const stopped = await stopSession.respond({- optionId: "stop",- requestId: stopRequest.requestId,- });+ const stopped = await stopSession.respond([+ {+ optionId: "stop",+ requestId: stopRequest.requestId,+ },+ ]);stopped.expectOk();stopSession.notEvent("turn.failed");stopSession.notEvent("session.failed");diff --git a/e2e/fixtures/agent-session-timeout/agent/channels/threads.ts b/e2e/fixtures/agent-session-timeout/agent/channels/threads.tsindex 90d400c6e..5820a212f 100644--- a/e2e/fixtures/agent-session-timeout/agent/channels/threads.ts+++ b/e2e/fixtures/agent-session-timeout/agent/channels/threads.ts@@ -9,17 +9,16 @@ const AUTH = {export default defineChannel({routes: [- POST("/threads/:threadId/messages", async (request, { params, send }) => {+ POST("/threads/:threadId/messages", async (request, { from, params }) => {const body = (await request.json().catch(() => ({}))) as { message?: string };- const session = await send(body.message ?? "", {+ const session = await from(params.threadId ?? "").send(body.message ?? "", {auth: AUTH,- continuationToken: params.threadId ?? "",});return Response.json({ sessionId: session.id });}),- POST("/threads/:threadId/owner", async (_request, { params, resolveActiveSession }) => {- const owner = await resolveActiveSession({ continuationToken: params.threadId ?? "" });- return Response.json({ sessionId: owner?.sessionId ?? null });+ POST("/threads/:threadId/owner", async (_request, { params, resolveSession }) => {+ const session = await resolveSession(params.threadId ?? "");+ return Response.json({ sessionId: session?.id ?? null });}),],});diff --git a/e2e/fixtures/agent-subagents/evals/descendant-session-limit.eval.ts b/e2e/fixtures/agent-subagents/evals/descendant-session-limit.eval.tsindex d6e60be67..12df7aea6 100644--- a/e2e/fixtures/agent-subagents/evals/descendant-session-limit.eval.ts+++ b/e2e/fixtures/agent-subagents/evals/descendant-session-limit.eval.ts@@ -39,10 +39,12 @@ export default defineEval({),);- const resumed = await t.respond({- optionId: "continue",- requestId: continueRequest.requestId,- });+ const resumed = await t.respond([+ {+ optionId: "continue",+ requestId: continueRequest.requestId,+ },+ ]);resumed.expectOk();t.succeeded();t.calledSubagent("limited-worker", { count: 1, output: CHILD_TOKEN });@@ -57,10 +59,12 @@ export default defineEval({toolName: "session_limit_continuation",});- const stopped = await stopSession.respond({- optionId: "stop",- requestId: stopRequest.requestId,- });+ const stopped = await stopSession.respond([+ {+ optionId: "stop",+ requestId: stopRequest.requestId,+ },+ ]);stopped.expectOk();stopSession.notEvent("turn.failed");stopSession.notEvent("session.failed");diff --git a/e2e/fixtures/agent-subagents/evals/remote-principal-forwarding.eval.ts b/e2e/fixtures/agent-subagents/evals/remote-principal-forwarding.eval.tsindex 1a74da5b0..65b37797b 100644--- a/e2e/fixtures/agent-subagents/evals/remote-principal-forwarding.eval.ts+++ b/e2e/fixtures/agent-subagents/evals/remote-principal-forwarding.eval.ts@@ -28,11 +28,10 @@ export default defineEval({async test(t) {await t.send("Reply with the single word: ready.");- await t.send({- headers: { authorization: "Bearer e2e-principal-forwarding-second-user" },- message:- "Use the remote-loopback agent with this exact message and nothing else (no outputSchema): 'Run the whoami tool and reply with only its marker string, verbatim.' When it returns, reply with the agent's exact output included verbatim.",- });+ await t.send(+ "Use the remote-loopback agent with this exact message and nothing else (no outputSchema): 'Run the whoami tool and reply with only its marker string, verbatim.' When it returns, reply with the agent's exact output included verbatim.",+ { headers: { authorization: "Bearer e2e-principal-forwarding-second-user" } },+ );t.succeeded();t.calledSubagent("remote-loopback", {diff --git a/e2e/fixtures/agent-tools-hitl-openai/evals/hitl/approve-resume.eval.ts b/e2e/fixtures/agent-tools-hitl-openai/evals/hitl/approve-resume.eval.tsindex 19838cb88..725129118 100644--- a/e2e/fixtures/agent-tools-hitl-openai/evals/hitl/approve-resume.eval.ts+++ b/e2e/fixtures/agent-tools-hitl-openai/evals/hitl/approve-resume.eval.ts@@ -23,10 +23,12 @@ export default defineEval({toolName: "guarded-echo",});- const approved = await t.respond({- requestId: request.requestId,- optionId: "approve",- });+ const approved = await t.respond([+ {+ requestId: request.requestId,+ optionId: "approve",+ },+ ]);approved.expectOk();approved.event("action.result", {data: {diff --git a/e2e/fixtures/agent-tools-hitl/evals/hitl/authored-always-approve-resume.eval.ts b/e2e/fixtures/agent-tools-hitl/evals/hitl/authored-always-approve-resume.eval.tsindex 31acbfa2c..fc7bbd1f3 100644--- a/e2e/fixtures/agent-tools-hitl/evals/hitl/authored-always-approve-resume.eval.ts+++ b/e2e/fixtures/agent-tools-hitl/evals/hitl/authored-always-approve-resume.eval.ts@@ -18,10 +18,12 @@ export default defineEval({// This sends only `inputResponses` in a separate turn. No user message or// channel context follows the tool approval response in the model input.- const approved = await t.respond({- optionId: "approve",- requestId: approval.requestId,- });+ const approved = await t.respond([+ {+ optionId: "approve",+ requestId: approval.requestId,+ },+ ]);approved.expectOk();approved.event("action.result", {diff --git a/e2e/fixtures/agent-tools-hitl/evals/hitl/authored-always-unrelated-input.eval.ts b/e2e/fixtures/agent-tools-hitl/evals/hitl/authored-always-unrelated-input.eval.tsindex 696955dda..f4e8ce1c2 100644--- a/e2e/fixtures/agent-tools-hitl/evals/hitl/authored-always-unrelated-input.eval.ts+++ b/e2e/fixtures/agent-tools-hitl/evals/hitl/authored-always-unrelated-input.eval.ts@@ -25,10 +25,12 @@ export default defineEval({unrelated.notEvent("step.started");unrelated.event("session.waiting", { count: 1 });- const approved = await t.respond({- optionId: "approve",- requestId: approval.requestId,- });+ const approved = await t.respond([+ {+ optionId: "approve",+ requestId: approval.requestId,+ },+ ]);approved.expectOk();approved.event("action.result", {diff --git a/e2e/fixtures/agent-tools-hitl/evals/hitl/slow-once-approve-replay.eval.ts b/e2e/fixtures/agent-tools-hitl/evals/hitl/slow-once-approve-replay.eval.tsindex 787bb86b0..993b35530 100644--- a/e2e/fixtures/agent-tools-hitl/evals/hitl/slow-once-approve-replay.eval.ts+++ b/e2e/fixtures/agent-tools-hitl/evals/hitl/slow-once-approve-replay.eval.ts@@ -27,10 +27,12 @@ export default defineEval({toolName: TOOL_NAME,});- const approved = await t.respond({- requestId: request.requestId,- optionId: "approve",- });+ const approved = await t.respond([+ {+ requestId: request.requestId,+ optionId: "approve",+ },+ ]);approved.expectOk();t.calledTool(TOOL_NAME, {diff --git a/e2e/fixtures/agent-tools-hitl/evals/hitl/stale-ask-question-selection-idle.eval.ts b/e2e/fixtures/agent-tools-hitl/evals/hitl/stale-ask-question-selection-idle.eval.tsindex 16fc7b947..6e6ce5540 100644--- a/e2e/fixtures/agent-tools-hitl/evals/hitl/stale-ask-question-selection-idle.eval.ts+++ b/e2e/fixtures/agent-tools-hitl/evals/hitl/stale-ask-question-selection-idle.eval.ts@@ -35,10 +35,12 @@ export default defineEval({intervening.notEvent("input.requested");intervening.messageIncludes(/INTERVENING-HITL-OK/i);- const staleSelection = await t.respond({- requestId: request.requestId,- optionId: "candidate",- });+ const staleSelection = await t.respond([+ {+ requestId: request.requestId,+ optionId: "candidate",+ },+ ]);staleSelection.expectOk();staleSelection.notEvent("input.requested");staleSelection.event("message.received", {diff --git a/e2e/fixtures/agent-tools-hitl/evals/hitl/stale-ask-question-selection.eval.ts b/e2e/fixtures/agent-tools-hitl/evals/hitl/stale-ask-question-selection.eval.tsindex 78d1372a5..c509aa20c 100644--- a/e2e/fixtures/agent-tools-hitl/evals/hitl/stale-ask-question-selection.eval.ts+++ b/e2e/fixtures/agent-tools-hitl/evals/hitl/stale-ask-question-selection.eval.ts@@ -56,10 +56,12 @@ export default defineEval({throw new Error("The second ask_question call reused the stale request ID.");}- const staleSelection = await t.respond({- requestId: request.requestId,- optionId: "candidate",- });+ const staleSelection = await t.respond([+ {+ requestId: request.requestId,+ optionId: "candidate",+ },+ ]);staleSelection.expectOk();staleSelection.event("message.received", {count: 1,diff --git a/e2e/fixtures/agent-tools-hitl/evals/hitl/unrelated-message-queued.eval.ts b/e2e/fixtures/agent-tools-hitl/evals/hitl/unrelated-message-queued.eval.tsindex 74ff12b74..9570bf232 100644--- a/e2e/fixtures/agent-tools-hitl/evals/hitl/unrelated-message-queued.eval.ts+++ b/e2e/fixtures/agent-tools-hitl/evals/hitl/unrelated-message-queued.eval.ts@@ -27,10 +27,12 @@ export default defineEval({});queued.event("session.waiting", { count: 1 });- const approved = await t.respond({- requestId: request.requestId,- optionId: "approve",- });+ const approved = await t.respond([+ {+ requestId: request.requestId,+ optionId: "approve",+ },+ ]);approved.expectOk();approved.event("action.result", {data: {diff --git a/e2e/fixtures/agent-tools/agent/channels/action-narration.ts b/e2e/fixtures/agent-tools/agent/channels/action-narration.tsindex 3b4c8ed76..4272b1b3b 100644--- a/e2e/fixtures/agent-tools/agent/channels/action-narration.ts+++ b/e2e/fixtures/agent-tools/agent/channels/action-narration.ts@@ -65,11 +65,10 @@ export default defineChannel({},routes: [- POST<ActionNarrationState>("/action-narration/start", async (request, { send }) => {+ POST<ActionNarrationState>("/action-narration/start", async (request, { from }) => {const input = await readRequest(request);- const session = await send(input.message, {+ const session = await from(continuationToken(input.token)).send(input.message, {auth: null,- continuationToken: continuationToken(input.token),state: initialState(),});return Response.json({ sessionId: session.id });diff --git a/e2e/fixtures/agent-tools/agent/channels/anchored.ts b/e2e/fixtures/agent-tools/agent/channels/anchored.tsindex 01b6f97dc..85a156eeb 100644--- a/e2e/fixtures/agent-tools/agent/channels/anchored.ts+++ b/e2e/fixtures/agent-tools/agent/channels/anchored.ts@@ -51,12 +51,11 @@ export default defineChannel({};},routes: [- POST<AnchorState>("/anchor/start", async (request, { send }) => {+ POST<AnchorState>("/anchor/start", async (request, { from }) => {const body = readBody(await request.json().catch(() => ({})));const anchorToken = `thread:${body.threadId}`;- const session = await send(body.message, {+ const session = await from(`pending:${body.threadId}`).send(body.message, {auth: authFor("start", body.marker),- continuationToken: `pending:${body.threadId}`,state: initialState(anchorToken),});@@ -68,12 +67,11 @@ export default defineChannel({});}),- POST<AnchorState>("/anchor/reply", async (request, { send }) => {+ POST<AnchorState>("/anchor/reply", async (request, { from }) => {const body = readBody(await request.json().catch(() => ({})));const anchorToken = `thread:${body.threadId}`;- const session = await send(body.message, {+ const session = await from(anchorToken).send(body.message, {auth: authFor("reply", body.marker),- continuationToken: anchorToken,state: initialState(anchorToken),});@@ -89,8 +87,13 @@ export default defineChannel({channel.state.completedMessages.push(event.message ?? "");const anchorToken = channel.state.anchorToken;- if (anchorToken !== null && !channel.continuationToken.endsWith(`:${anchorToken}`)) {- channel.setContinuationToken(anchorToken);+ const continuation = channel.continuation;+ if (+ anchorToken !== null &&+ continuation !== undefined &&+ !continuation.token.endsWith(`:${anchorToken}`)+ ) {+ continuation.rekey(anchorToken);}},},diff --git a/e2e/fixtures/agent-tools/agent/channels/metadata-provider.ts b/e2e/fixtures/agent-tools/agent/channels/metadata-provider.tsindex 6c94ae145..df4faed77 100644--- a/e2e/fixtures/agent-tools/agent/channels/metadata-provider.ts+++ b/e2e/fixtures/agent-tools/agent/channels/metadata-provider.ts@@ -16,21 +16,23 @@ export default defineChannel({},routes: [- POST<MetadataProviderState>("/metadata-provider/start", async (request, { send }) => {+ POST<MetadataProviderState>("/metadata-provider/start", async (request, { from }) => {const body = (await request.json().catch(() => ({}))) as {message?: string;topic?: string;contextMessages?: string[];};- const session = await send(body.message ?? "hello", {- auth: null,- continuationToken: `mp:${crypto.randomUUID().slice(0, 8)}`,- state: {- topic: body.topic ?? null,- contextMessages: body.contextMessages ?? [],+ const session = await from(`mp:${crypto.randomUUID().slice(0, 8)}`).send(+ body.message ?? "hello",+ {+ auth: null,+ state: {+ topic: body.topic ?? null,+ contextMessages: body.contextMessages ?? [],+ },},- });+ );return Response.json({ ok: true, sessionId: session.id });}),diff --git a/packages/eve/README.md b/packages/eve/README.mdindex da4c30f95..c1099e1ba 100644--- a/packages/eve/README.md+++ b/packages/eve/README.md@@ -27,7 +27,7 @@ Unless you configure stricter controls, eve agents may operate with permissive s- Durable message runs and follow-up turns- Inspectable compiled artifacts under `.eve/`- Per-agent sandbox with optional authored overrides-- A stable HTTP protocol with explicit `continuationToken` and `sessionId` contracts+- A stable HTTP protocol built around immutable session IDs- A runtime model that keeps channels, harnesses, and workflow execution separate## Authored Directory@@ -163,14 +163,13 @@ You do not need this section to author an eve agent — it documents the publiceve's internal split is:-- the **channel** normalizes inbound transport, applies auth and delivery policy, and owns `continuationToken`+- the **channel** normalizes inbound transport, applies auth and delivery policy, and owns channel-local addresses- the **harness** does one unit of AI work and returns `{ session, next }`- the **runtime** persists state, follows `next`, streams events, and owns workflow primitives (`start()`, `resumeHook()`, `createHook()`, `getWritable()`)-That split is why the public HTTP protocol separates two distinct identifiers:--- `continuationToken` — channel-owned handle the caller uses to start the next user turn-- `sessionId` — runtime-owned handle for streaming and inspection+The public HTTP protocol exposes one immutable identifier: `sessionId`. Create a+session explicitly, then use that ID for follow-up messages, controls, streaming,+and inspection. Channel-local addresses remain behind authored channel APIs.## Changelogdiff --git a/packages/eve/src/acp/adapter.test.ts b/packages/eve/src/acp/adapter.test.tsindex 74525a93d..f7cb2fd5c 100644--- a/packages/eve/src/acp/adapter.test.ts+++ b/packages/eve/src/acp/adapter.test.ts@@ -3,25 +3,33 @@ import { describe, expect, it, vi } from "vitest";import { EveAcpAdapter } from "#acp/adapter.js";import { ClientError } from "#client/client-error.js";-import type { SendTurnInput, SessionState } from "#client/types.js";+import type { SendTurnInput, SendTurnPayload } from "#client/types.js";import type { HandleMessageStreamEvent } from "#protocol/message.js";type TestStreamEvent<T = HandleMessageStreamEvent> = T extends unknown ? Omit<T, "meta"> : never;class FakeClientSession {- readonly cancel = vi.fn(async () => ({ status: "accepted" }));+ readonly cancel = vi.fn(async () => ({ sessionId: "session_test", status: "accepted" }));readonly reset = vi.fn(async () => ({ status: "reset" }));- readonly sends: SendTurnInput[] = [];- state: SessionState = { streamIndex: 0 };+ readonly sends: SendTurnPayload[] = [];readonly #turns: Array<readonly TestStreamEvent[]>;constructor(turns: Array<readonly TestStreamEvent[]>) {this.#turns = turns;}- async send(input: SendTurnInput): Promise<AsyncIterable<HandleMessageStreamEvent>> {+ async send(message: SendTurnInput["message"]): Promise<AsyncIterable<HandleMessageStreamEvent>> {+ return await this.#next({ message });+ }++ async respond(+ inputResponses: NonNullable<SendTurnPayload["inputResponses"]>,+ ): Promise<AsyncIterable<HandleMessageStreamEvent>> {+ return await this.#next({ inputResponses });+ }++ async #next(input: SendTurnPayload): Promise<AsyncIterable<HandleMessageStreamEvent>> {this.sends.push(input);- this.state = { ...this.state, sessionId: "eve-session" };const events = this.#turns.shift() ?? [];return (async function* () {for (const [index, event] of events.entries()) {@@ -34,10 +42,20 @@ class FakeClientSession {}}+function fakeClient(session: FakeClientSession) {+ return {+ sessions: {+ async create(input: SendTurnInput) {+ return { response: await session.send(input.message), session };+ },+ },+ };+}+function adapterWith(turns: Array<readonly TestStreamEvent[]> = []) {const session = new FakeClientSession(turns);const adapter = new EveAcpAdapter({- client: { session: () => session },+ client: fakeClient(session),eveVersion: "1.2.3",serverUrl: "http://127.0.0.1:2000",workspaceRoot: process.cwd(),@@ -105,7 +123,7 @@ describe("EveAcpAdapter", () => {it("does not treat a remote ACP client's cwd as a deployment workspace", async () => {const session = new FakeClientSession([]);const adapter = new EveAcpAdapter({- client: { session: () => session },+ client: fakeClient(session),eveVersion: "1.2.3",serverUrl: "https://agent.example.com",});@@ -157,7 +175,10 @@ describe("EveAcpAdapter", () => {turnId: "t1",},},- { type: "session.waiting", data: { continuationToken: "secret", wait: "next-user-message" } },+ {+ type: "session.waiting",+ data: { continuationToken: "session-id", wait: "next-user-message" },+ },];const { adapter, session } = adapterWith([events]);const sessionId = await createSession(adapter);@@ -215,9 +236,17 @@ describe("EveAcpAdapter", () => {turnId: "t1",},},- { type: "session.waiting", data: { continuationToken: "one", wait: "next-user-message" } },+ {+ type: "session.waiting",+ data: { continuationToken: "session-id", wait: "next-user-message" },+ },+ ],+ [+ {+ type: "session.waiting",+ data: { continuationToken: "session-id", wait: "next-user-message" },+ },],- [{ type: "session.waiting", data: { continuationToken: "two", wait: "next-user-message" } }],]);const request = vi.fn(async (_method: string, params: any) => ({outcome: { outcome: "selected", optionId: params.options[0].optionId },@@ -276,9 +305,17 @@ describe("EveAcpAdapter", () => {turnId: "turn-1",},},- { type: "session.waiting", data: { continuationToken: "one", wait: "next-user-message" } },+ {+ type: "session.waiting",+ data: { continuationToken: "session-id", wait: "next-user-message" },+ },+ ],+ [+ {+ type: "session.waiting",+ data: { continuationToken: "session-id", wait: "next-user-message" },+ },],- [{ type: "session.waiting", data: { continuationToken: "two", wait: "next-user-message" } }],]);adapter.initialize({clientCapabilities: { elicitation: { form: {} } },@@ -337,7 +374,10 @@ describe("EveAcpAdapter", () => {turnId: "turn-1",},},- { type: "session.waiting", data: { continuationToken: "one", wait: "next-user-message" } },+ {+ type: "session.waiting",+ data: { continuationToken: "session-id", wait: "next-user-message" },+ },],]);let requestStarted!: () => void;@@ -389,7 +429,6 @@ describe("EveAcpAdapter", () => {session.send = vi.fn(async () => {sendStarted();await released;- session.state = { sessionId: "eve-session", streamIndex: 0 };return (async function* () {yield {type: "turn.cancelled",@@ -397,12 +436,12 @@ describe("EveAcpAdapter", () => {} as HandleMessageStreamEvent;yield {type: "session.waiting",- data: { continuationToken: "next", wait: "next-user-message" },+ data: { continuationToken: "session-id", wait: "next-user-message" },} as HandleMessageStreamEvent;})();});const adapter = new EveAcpAdapter({- client: { session: () => session },+ client: fakeClient(session),eveVersion: "1.2.3",serverUrl: "http://127.0.0.1:2000",workspaceRoot: process.cwd(),@@ -430,7 +469,6 @@ describe("EveAcpAdapter", () => {const turnObserved = new Promise<void>((resolve) => (observeTurn = resolve));const session = new FakeClientSession([]);session.send = vi.fn(async () => {- session.state = { sessionId: "eve-session", streamIndex: 0 };return (async function* () {observeTurn();yield {@@ -444,12 +482,12 @@ describe("EveAcpAdapter", () => {} as HandleMessageStreamEvent;yield {type: "session.waiting",- data: { continuationToken: "next", wait: "next-user-message" },+ data: { continuationToken: "session-id", wait: "next-user-message" },} as HandleMessageStreamEvent;})();});const adapter = new EveAcpAdapter({- client: { session: () => session },+ client: fakeClient(session),eveVersion: "1.2.3",serverUrl: "http://127.0.0.1:2000",workspaceRoot: process.cwd(),@@ -475,7 +513,7 @@ describe("EveAcpAdapter", () => {throw new ClientError(401, JSON.stringify({ error: "Unauthorized" }));});const adapter = new EveAcpAdapter({- client: { session: () => session },+ client: fakeClient(session),eveVersion: "1.2.3",serverUrl: "https://agent.example.com",});@@ -507,7 +545,10 @@ describe("EveAcpAdapter", () => {turnId: "turn-1",},},- { type: "session.waiting", data: { continuationToken: "next", wait: "next-user-message" } },+ {+ type: "session.waiting",+ data: { continuationToken: "session-id", wait: "next-user-message" },+ },],]);const sessionId = await createSession(adapter);@@ -532,7 +573,10 @@ describe("EveAcpAdapter", () => {turnId: "turn-1",},},- { type: "session.waiting", data: { continuationToken: "next", wait: "next-user-message" } },+ {+ type: "session.waiting",+ data: { continuationToken: "session-id", wait: "next-user-message" },+ },],]);const sessionId = await createSession(adapter);@@ -563,8 +607,15 @@ describe("EveAcpAdapter", () => {});it("resets owned eve sessions when an ACP session or connection closes", async () => {- const { adapter, session } = adapterWith();+ const waitingTurn = [+ {+ type: "session.waiting",+ data: { continuationToken: "session-id", wait: "next-user-message" },+ },+ ] as const;+ const { adapter, session } = adapterWith([waitingTurn, waitingTurn]);const first = await createSession(adapter);+ await adapter.prompt(textPrompt(first), acpClient().client, new AbortController().signal);await adapter.closeSession(first);expect(session.reset).toHaveBeenCalledOnce();@@ -572,14 +623,23 @@ describe("EveAcpAdapter", () => {adapter.prompt(textPrompt(first), acpClient().client, new AbortController().signal),).rejects.toThrow("Unknown or closed");- await createSession(adapter);+ const second = await createSession(adapter);+ await adapter.prompt(textPrompt(second), acpClient().client, new AbortController().signal);await adapter.close();expect(session.reset).toHaveBeenCalledTimes(2);});it("keeps whole-connection cleanup best-effort when reset fails", async () => {- const { adapter, session } = adapterWith();- await createSession(adapter);+ const { adapter, session } = adapterWith([+ [+ {+ type: "session.waiting",+ data: { continuationToken: "session-id", wait: "next-user-message" },+ },+ ],+ ]);+ const sessionId = await createSession(adapter);+ await adapter.prompt(textPrompt(sessionId), acpClient().client, new AbortController().signal);session.reset.mockRejectedValueOnce(new Error("server already stopped"));await expect(adapter.close()).resolves.toBeUndefined();diff --git a/packages/eve/src/acp/adapter.ts b/packages/eve/src/acp/adapter.tsindex adedb416b..2dc2d388d 100644--- a/packages/eve/src/acp/adapter.ts+++ b/packages/eve/src/acp/adapter.ts@@ -16,7 +16,7 @@ import {type ToolCall,} from "#compiled/@agentclientprotocol/sdk/index.js";import { Client, ClientError } from "#client/index.js";-import type { ClientOptions, SendTurnInput, SessionState } from "#client/types.js";+import type { ClientOptions, SendTurnInput, SendTurnPayload } from "#client/types.js";import type { HandleMessageStreamEvent } from "#protocol/message.js";import type { RuntimeActionRequest, RuntimeActionResult } from "#runtime/actions/types.js";import type { InputRequest, InputResponse } from "#runtime/input/types.js";@@ -36,18 +36,25 @@ interface ActivePrompt {}interface AdapterClientSession {- readonly state: SessionState;- send(input: SendTurnInput): Promise<AsyncIterable<HandleMessageStreamEvent>>;+ send(message: SendTurnInput["message"]): Promise<AsyncIterable<HandleMessageStreamEvent>>;+ respond(+ inputResponses: readonly InputResponse[],+ ): Promise<AsyncIterable<HandleMessageStreamEvent>>;cancel(options?: { turnId?: string }): Promise<unknown>;reset(): Promise<unknown>;}interface AdapterClient {- session(): AdapterClientSession;+ readonly sessions: {+ create(input: SendTurnInput): Promise<{+ readonly response: AsyncIterable<HandleMessageStreamEvent>;+ readonly session: AdapterClientSession;+ }>;+ };}interface AcpSession {- readonly client: AdapterClientSession;+ client?: AdapterClientSession;active?: ActivePrompt;readonly tools: Map<string, ToolCall>;}@@ -87,7 +94,6 @@ export class EveAcpAdapter {auth: options.auth,headers: options.headers,host: options.serverUrl,- preserveCompletedSessions: true,redirect: "manual",});}@@ -134,7 +140,6 @@ export class EveAcpAdapter {const sessionId = randomUUID();this.#sessions.set(sessionId, {- client: this.#client.session(),tools: new Map(),});return { sessionId };@@ -178,9 +183,22 @@ export class EveAcpAdapter {if (active.protocolCancelled) {throw RequestError.requestCancelled({ sessionId: params.sessionId });}- let input: SendTurnInput = { message };+ let input: SendTurnPayload = { message };for (;;) {- const response = await session.client.send(input);+ let response: AsyncIterable<HandleMessageStreamEvent>;+ if (session.client === undefined) {+ if (input.message === undefined) {+ throw new Error("ACP session has not started.");+ }+ const created = await this.#client.sessions.create({ ...input, message: input.message });+ session.client = created.session;+ response = created.response;+ } else {+ response =+ input.inputResponses === undefined+ ? await session.client.send(input.message!)+ : await session.client.respond(input.inputResponses);+ }if (active.cancelRequested || active.protocolCancelled) {await this.#cancelActive(session);}@@ -278,7 +296,7 @@ export class EveAcpAdapter {}try {- await session.client.reset();+ await session.client?.reset();} catch (resetError) {if (cancellationError !== undefined) {throw new AggregateError(@@ -293,7 +311,7 @@ export class EveAcpAdapter {async #cancelActive(session: AcpSession): Promise<void> {session.active?.outboundController.abort();- if (session.client.state.sessionId === undefined) return;+ if (session.client === undefined) return;await session.client.cancel(session.active?.turnId === undefined ? undefined : { turnId: session.active.turnId },);diff --git a/packages/eve/src/acp/server.test.ts b/packages/eve/src/acp/server.test.tsindex 6524f2a86..a4da96b4e 100644--- a/packages/eve/src/acp/server.test.ts+++ b/packages/eve/src/acp/server.test.ts@@ -4,7 +4,7 @@ import { describe, expect, it, vi } from "vitest";import { ACP_MAX_LINE_BYTES } from "#acp/line-limit.js";import { runAcpServerOnStreams } from "#acp/server.js";-import type { SendTurnInput, SessionState } from "#client/types.js";+import type { SendTurnInput } from "#client/types.js";import type { HandleMessageStreamEvent } from "#protocol/message.js";function streams() {@@ -26,15 +26,20 @@ describe("runAcpServerOnStreams", () => {await expect(server).resolves.toBeUndefined();});- it("closes the transport and resets sessions when shutdown is requested", async () => {+ it("closes the transport without creating an eve session before the first prompt", async () => {const reset = vi.fn(async () => ({ status: "reset" }));+ const session = {+ cancel: vi.fn(async () => ({ sessionId: "session_test", status: "accepted" })),+ reset,+ respond: vi.fn(async () => emptyEvents()),+ send: vi.fn(async (_message: SendTurnInput["message"]) => emptyEvents()),+ };const client = {- session: () => ({- cancel: vi.fn(async () => ({ status: "accepted" })),- reset,- send: vi.fn(async (_input: SendTurnInput) => emptyEvents()),- state: { streamIndex: 0 } satisfies SessionState,- }),+ sessions: {+ async create(input: SendTurnInput) {+ return { response: await session.send(input.message), session };+ },+ },};const controller = new AbortController();const transport = streams();@@ -65,7 +70,7 @@ describe("runAcpServerOnStreams", () => {controller.abort();await expect(server).resolves.toBeUndefined();- expect(reset).toHaveBeenCalledOnce();+ expect(reset).not.toHaveBeenCalled();});});diff --git a/packages/eve/src/channel/adapter-context.ts b/packages/eve/src/channel/adapter-context.tsindex 3747d7bc8..a4221422e 100644--- a/packages/eve/src/channel/adapter-context.ts+++ b/packages/eve/src/channel/adapter-context.ts@@ -8,7 +8,7 @@ import { buildSessionHandle } from "#channel/session.js";** Populates `session` with a live {@link SessionHandle} backed by the* supplied accessor so handlers can read identity / auth and call- * `setContinuationToken(...)` to re-key the parked session.+ * `session.continuation.rekey(...)` to re-key the parked session.*/export function buildAdapterContext<TCtx extends ChannelAdapterContext<any> = ChannelAdapterContext,diff --git a/packages/eve/src/channel/adapter.test.ts b/packages/eve/src/channel/adapter.test.tsindex 32f0ff165..e1a9e2810 100644--- a/packages/eve/src/channel/adapter.test.ts+++ b/packages/eve/src/channel/adapter.test.ts@@ -101,37 +101,61 @@ describe("ChannelAdapter helpers", () => {expect(defaultDeliverResult({})).toBeUndefined();});- it("publishes a continuation token re-keyed by the waiting handler", async () => {+ it("publishes a waiting handler's re-keyed channel address", async () => {let continuationToken = "slack:temporary";+ let observedToken: string | undefined;const context: ChannelAdapterContext = {ctx: {} as ChannelAdapterContext["ctx"],session: {auth: { current: null, initiator: null },- get continuationToken() {- return continuationToken;- },id: "session-1",- setContinuationToken(token) {- continuationToken = `slack:${token}`;+ continuation: {+ get token() {+ return continuationToken.slice("slack:".length);+ },+ rekey(token: string) {+ continuationToken = `slack:${token}`;+ },},},state: {},};const adapter: ChannelAdapter = {kind: "slack",- "session.waiting"(_data, ctx) {- ctx.session.setContinuationToken("C1:T1");+ "session.waiting"(data, ctx) {+ observedToken = data.continuationToken;+ ctx.session.continuation?.rekey("C1:T1");+ },+ };++ const event = await callAdapterEventHandler(adapter, createSessionWaitingEvent(), context);++ expect(event).toEqual({+ data: { continuationToken: "C1:T1", wait: "next-user-message" },+ type: "session.waiting",+ });+ expect(observedToken).toBe("temporary");+ expect(continuationToken).toBe("slack:C1:T1");+ });++ it("publishes the session ID for an ID-only waiting session", async () => {+ const context: ChannelAdapterContext = {+ ctx: {} as ChannelAdapterContext["ctx"],+ session: {+ auth: { current: null, initiator: null },+ id: "session-1",},+ state: {},};const event = await callAdapterEventHandler(- adapter,- createSessionWaitingEvent("slack:temporary"),+ { kind: "http" },+ createSessionWaitingEvent(),context,);expect(event).toEqual({- data: { continuationToken: "C1:T1", wait: "next-user-message" },+ data: { continuationToken: "session-1", wait: "next-user-message" },type: "session.waiting",});});diff --git a/packages/eve/src/channel/adapter.ts b/packages/eve/src/channel/adapter.tsindex 8cb3ca96d..aa9ad1765 100644--- a/packages/eve/src/channel/adapter.ts+++ b/packages/eve/src/channel/adapter.ts@@ -5,7 +5,6 @@ import type { UnstampedMessageStreamEvent } from "#protocol/message.js";import type { SessionHandle } from "#channel/session.js";import type { DeliverPayload } from "#channel/types.js";import type { FetchFileResult, FetchFileFunction } from "#shared/channel-definition.js";-import { toChannelLocalContinuationToken } from "#shared/continuation-token.js";const log = createLogger("channel.adapter");@@ -23,7 +22,7 @@ const log = createLogger("channel.adapter");* {@link ContextAccessor} that tools and providers use).** `session` is a live handle to the current session — id, auth,- * continuation token, plus an imperative {@link SessionHandle.setContinuationToken}+ * optional channel continuation address, including an imperative `rekey()`* for channels that need to re-key the session mid-turn (e.g. Slack's* auto-anchor on first post).*/@@ -223,9 +222,7 @@ export function getAdapterKind(adapter: ChannelAdapter): string {/*** Calls an adapter's event handler for a given event. Adapters perform side- * effects rather than transforming events; after the handler runs, the- * runtime refreshes `session.waiting` with the live continuation token so a- * handler that re-keyed the session publishes the new resume handle.+ * effects rather than transforming events.** Throwing handlers are logged and swallowed so a downstream delivery* failure does not corrupt the event stream write path.@@ -235,13 +232,14 @@ export async function callAdapterEventHandler(event: UnstampedMessageStreamEvent,ctx: ChannelAdapterContext,): Promise<UnstampedMessageStreamEvent> {+ const eventForHandler = withWaitingContinuationToken(event, ctx);const handler = adapter[event.type] as| ((data: unknown, ctx: ChannelAdapterContext) => void | Promise<void>)| undefined;if (handler !== undefined) {try {- await handler("data" in event ? event.data : undefined, ctx);+ await handler("data" in eventForHandler ? eventForHandler.data : undefined, ctx);} catch (error) {log.error("adapter event handler threw — event swallowed", {adapterKind: getAdapterKind(adapter),@@ -251,15 +249,19 @@ export async function callAdapterEventHandler(}}- if (event.type === "session.waiting") {- return {- ...event,- data: {- ...event.data,- continuationToken: toChannelLocalContinuationToken(ctx.session.continuationToken),- },- };- }+ return withWaitingContinuationToken(eventForHandler, ctx);+}- return event;+function withWaitingContinuationToken(+ event: UnstampedMessageStreamEvent,+ ctx: ChannelAdapterContext,+): UnstampedMessageStreamEvent {+ if (event.type !== "session.waiting") return event;+ return {+ ...event,+ data: {+ ...event.data,+ continuationToken: ctx.session.continuation?.token ?? ctx.session.id,+ },+ };}diff --git a/packages/eve/src/channel/cancel.test.ts b/packages/eve/src/channel/cancel.test.tsdeleted file mode 100644index ae2b033de..000000000--- a/packages/eve/src/channel/cancel.test.ts+++ /dev/null@@ -1,50 +0,0 @@-import { describe, expect, it, vi } from "vitest";--import { createCancelFn } from "#channel/cancel.js";-import type { Runtime } from "#channel/types.js";--function createRuntime(): Runtime {- return {- createSession: vi.fn(),- dispatchContinuation: vi.fn().mockResolvedValue({ status: "accepted" }),- dispatchSession: vi.fn(),- getEventStream: vi.fn(),- getStreamTailIndex: vi.fn(),- resolveContinuation: vi.fn(),- };-}--describe("createCancelFn", () => {- it("dispatches directly through the namespaced channel address", async () => {- const runtime = createRuntime();-- await expect(- createCancelFn(runtime, "slack")({ continuationToken: "C1:T1", turnId: "turn_3" }),- ).resolves.toEqual({ status: "accepted" });- expect(runtime.dispatchContinuation).toHaveBeenCalledWith({- command: { kind: "cancel", turnId: "turn_3" },- continuationToken: "slack:C1:T1",- });- expect(runtime.resolveContinuation).not.toHaveBeenCalled();- });-- it("passes through no_active_turn", async () => {- const runtime = createRuntime();- vi.mocked(runtime.dispatchContinuation).mockResolvedValue({ status: "no_active_turn" });-- await expect(- createCancelFn(runtime, "slack")({ continuationToken: "unknown" }),- ).resolves.toEqual({ status: "no_active_turn" });- });-- it("propagates dispatch failures without creating a session", async () => {- const failure = new Error("transient backing-store outage");- const runtime = createRuntime();- vi.mocked(runtime.dispatchContinuation).mockRejectedValue(failure);-- await expect(createCancelFn(runtime, "slack")({ continuationToken: "C1:T1" })).rejects.toBe(- failure,- );- expect(runtime.createSession).not.toHaveBeenCalled();- });-});diff --git a/packages/eve/src/channel/cancel.ts b/packages/eve/src/channel/cancel.tsdeleted file mode 100644index c77729250..000000000--- a/packages/eve/src/channel/cancel.ts+++ /dev/null@@ -1,14 +0,0 @@-import type { CancelFn, CancelOptions } from "#channel/routes.js";-import type { CancelTurnResult, Runtime } from "#channel/types.js";--/**- * Builds the route-handler `cancel` helper for one channel.- */-export function createCancelFn(runtime: Runtime, channelName: string): CancelFn {- return async (options: CancelOptions): Promise<CancelTurnResult> => {- return await runtime.dispatchContinuation({- command: { kind: "cancel", turnId: options.turnId },- continuationToken: `${channelName}:${options.continuationToken}`,- });- };-}diff --git a/packages/eve/src/channel/channel-address.test.ts b/packages/eve/src/channel/channel-address.test.tsnew file mode 100644index 000000000..f52348257--- /dev/null+++ b/packages/eve/src/channel/channel-address.test.ts@@ -0,0 +1,110 @@+import { describe, expect, it, vi } from "vitest";++import { createChannelAddress } from "#channel/channel-address.js";+import type { Runtime } from "#channel/types.js";++function createRuntime(): Runtime {+ return {+ createSession: vi.fn(),+ dispatchContinuation: vi.fn().mockResolvedValue({ sessionId: "sess_1", status: "accepted" }),+ dispatchSession: vi.fn(),+ getEventStream: vi.fn(),+ getStreamTailIndex: vi.fn(),+ resolveContinuation: vi.fn(),+ };+}++describe("createChannelAddress", () => {+ it("rejects channel addresses in the framework-reserved session namespace", () => {+ expect(() =>+ createChannelAddress({+ adapter: { kind: "http" },+ channelName: "eve",+ continuationToken: "session:wrun_1:inbox",+ runtime: createRuntime(),+ }),+ ).toThrow("reserved session namespace");+ });++ it("sends directly through the address and returns a fixed session handle", async () => {+ const runtime = createRuntime();+ const address = createChannelAddress({+ adapter: { kind: "slack" },+ channelName: "slack",+ continuationToken: "C1:T1",+ runtime,+ });++ const session = await address.send("hello", { auth: null });+ await session.clear();++ expect(runtime.dispatchContinuation).toHaveBeenCalledWith({+ command: {+ auth: null,+ kind: "send",+ payload: { message: "hello" },+ requestId: undefined,+ },+ continuationToken: "slack:C1:T1",+ });+ expect(runtime.resolveContinuation).not.toHaveBeenCalled();+ expect(runtime.createSession).not.toHaveBeenCalled();+ expect(runtime.dispatchSession).toHaveBeenCalledWith({+ command: { kind: "clear" },+ sessionId: "sess_1",+ });+ });++ it("binds every control directly to the namespaced continuation token", async () => {+ const runtime = createRuntime();+ const address = createChannelAddress({+ adapter: { kind: "slack" },+ channelName: "slack",+ continuationToken: "C1:T1",+ runtime,+ });++ await address.cancel({ turnId: "turn_1" });+ await address.compact();+ await address.clear();+ await address.reset({ reason: "fresh start" });++ expect(runtime.dispatchContinuation).toHaveBeenNthCalledWith(1, {+ command: { kind: "cancel", turnId: "turn_1" },+ continuationToken: "slack:C1:T1",+ });+ expect(runtime.dispatchContinuation).toHaveBeenNthCalledWith(2, {+ command: { kind: "compact" },+ continuationToken: "slack:C1:T1",+ });+ expect(runtime.dispatchContinuation).toHaveBeenNthCalledWith(3, {+ command: { kind: "clear" },+ continuationToken: "slack:C1:T1",+ });+ expect(runtime.dispatchContinuation).toHaveBeenNthCalledWith(4, {+ command: { kind: "reset", reason: "fresh start" },+ continuationToken: "slack:C1:T1",+ });+ expect(runtime.resolveContinuation).not.toHaveBeenCalled();+ });++ it("resolves explicitly to a fixed session handle", async () => {+ const runtime = createRuntime();+ vi.mocked(runtime.resolveContinuation).mockResolvedValue({ sessionId: "sess_2" });+ const address = createChannelAddress({+ adapter: { kind: "slack" },+ channelName: "slack",+ continuationToken: "C1:T1",+ runtime,+ });++ const session = await address.resolveSession();+ await session?.clear();++ expect(runtime.resolveContinuation).toHaveBeenCalledWith("slack:C1:T1");+ expect(runtime.dispatchSession).toHaveBeenCalledWith({+ command: { kind: "clear" },+ sessionId: "sess_2",+ });+ });+});diff --git a/packages/eve/src/channel/channel-address.ts b/packages/eve/src/channel/channel-address.tsnew file mode 100644index 000000000..e7834c754--- /dev/null+++ b/packages/eve/src/channel/channel-address.ts@@ -0,0 +1,195 @@+import type { UserContent } from "ai";++import type { ChannelAdapter } from "#channel/adapter.js";+import type { SendPayload } from "#channel/routes.js";+import { normalizeSendInput, serializeUrlFilePartsInMessage } from "#channel/send-input.js";+import { createSession, sessionCallbackToTurnCaller, type Session } from "#channel/session.js";+import type {+ CancelTurnResult,+ ClearSessionResult,+ CompactSessionResult,+ ResetSessionResult,+ RunInput,+ Runtime,+ SessionAuthContext,+ SessionCallback,+ SessionCommand,+} from "#channel/types.js";+import { isRuntimeSessionOwnershipConflictError } from "#execution/runtime-errors.js";+import { isReservedSessionCommandToken } from "#execution/session-command-token.js";+import type { RunMode } from "#shared/run-mode.js";++interface BaseChannelAddressDeliveryOptions {+ readonly auth: SessionAuthContext | null;+ readonly callback?: SessionCallback;+ readonly initiatorAuth?: SessionAuthContext | null;+ readonly mode?: RunMode;+ readonly title?: string;+}++/** Delivery options for a channel address whose continuation token is already bound. */+export type ChannelAddressDeliveryOptions<TState = undefined> = [TState] extends [undefined]+ ? BaseChannelAddressDeliveryOptions+ : BaseChannelAddressDeliveryOptions & { readonly state?: TState };++/**+ * Dynamic handle for whichever durable session currently owns one channel-local address.+ * Only {@link send} may create a session when the address is unowned.+ */+export interface ChannelAddress<TState = undefined> {+ readonly continuationToken: string;+ deliver(input: SendPayload, options: ChannelAddressDeliveryOptions<TState>): Promise<Session>;+ send(+ message: string | UserContent,+ options: ChannelAddressDeliveryOptions<TState>,+ ): Promise<Session>;+ respond(+ inputResponses: SendPayload["inputResponses"],+ options: ChannelAddressDeliveryOptions<TState>,+ ): Promise<Session>;+ cancel(options?: { readonly turnId?: string }): Promise<CancelTurnResult>;+ compact(): Promise<CompactSessionResult>;+ clear(): Promise<ClearSessionResult>;+ reset(options?: { readonly reason?: string }): Promise<ResetSessionResult>;+ resolveSession(): Promise<Session | undefined>;+}++/** Factory for binding a route-local continuation token to a {@link ChannelAddress}. */+export type ChannelAddressFn<TState = undefined> = (+ continuationToken: string,+) => ChannelAddress<TState>;++/** Creates one channel address backed by the runtime's continuation dispatch primitive. */+export function createChannelAddress<TState = undefined>(input: {+ readonly adapter: ChannelAdapter<any>;+ readonly channelName: string;+ readonly continuationToken: string;+ readonly metadata?: { readonly requestId?: string };+ readonly runtime: Runtime;+}): ChannelAddress<TState> {+ const metadata = input.metadata ?? {};+ const namespacedToken = `${input.channelName}:${input.continuationToken}`;+ if (isReservedSessionCommandToken(namespacedToken)) {+ throw new Error(`Channel address "${namespacedToken}" uses eve's reserved session namespace.`);+ }++ return {+ continuationToken: input.continuationToken,+ async deliver(sendInput, options) {+ const payload = normalizeSendInput(sendInput);+ const caller = sessionCallbackToTurnCaller(options.callback);+ const commandWithoutCaller = {+ auth: options.auth,+ kind: "send" as const,+ payload: {+ ...payload,+ message: serializeUrlFilePartsInMessage(payload.message),+ },+ requestId: metadata.requestId,+ };+ const command: Extract<SessionCommand, { readonly kind: "send" }> =+ caller === undefined ? commandWithoutCaller : { ...commandWithoutCaller, caller };+ const dispatch = async (): Promise<Session | undefined> => {+ const result = await input.runtime.dispatchContinuation({+ command,+ continuationToken: namespacedToken,+ });+ return result.status === "accepted"+ ? createSession(result.sessionId, input.runtime, metadata)+ : undefined;+ };++ const existing = await dispatch();+ if (existing !== undefined) return existing;+ if (payload.inputResponses && payload.inputResponses.length > 0) {+ throw new Error(+ "Cannot deliver inputResponses — the target session was not found via continuation token.",+ );+ }++ const state = (options as { readonly state?: TState }).state;+ const adapter =+ state === undefined+ ? input.adapter+ : {+ ...input.adapter,+ state: { ...input.adapter.state, ...(state as Record<string, unknown>) },+ };+ const runInput: RunInput = {+ adapter,+ auth: options.auth,+ capabilities: options.mode === "task" ? undefined : { requestInput: true },+ callback: options.callback,+ channelName: input.channelName,+ continuationToken: namespacedToken,+ initiatorAuth: options.initiatorAuth,+ input: {+ context: payload.context,+ message: serializeUrlFilePartsInMessage(payload.message) ?? "",+ outputSchema: payload.outputSchema,+ },+ mode: options.mode ?? "conversation",+ requestId: metadata.requestId,+ title: options.title,+ };+ try {+ const handle = await input.runtime.createSession(runInput);+ return createSession(handle.sessionId, input.runtime, metadata);+ } catch (error) {+ if (!isRuntimeSessionOwnershipConflictError(error)) throw error;+ const winner = await dispatch();+ if (winner !== undefined) return winner;+ throw error;+ }+ },+ async send(message, options) {+ return await this.deliver({ message }, options);+ },+ async respond(inputResponses, options) {+ if (inputResponses === undefined || inputResponses.length === 0) {+ throw new Error("respond() requires at least one input response.");+ }+ return await this.deliver({ inputResponses }, options);+ },+ async cancel(options) {+ return await input.runtime.dispatchContinuation({+ command: { kind: "cancel", turnId: options?.turnId },+ continuationToken: namespacedToken,+ });+ },+ async compact() {+ return await input.runtime.dispatchContinuation({+ command: { kind: "compact" },+ continuationToken: namespacedToken,+ });+ },+ async clear() {+ return await input.runtime.dispatchContinuation({+ command: { kind: "clear" },+ continuationToken: namespacedToken,+ });+ },+ async reset(options) {+ return await input.runtime.dispatchContinuation({+ command: { kind: "reset", reason: options?.reason },+ continuationToken: namespacedToken,+ });+ },+ async resolveSession() {+ const owner = await input.runtime.resolveContinuation(namespacedToken);+ return owner === undefined+ ? undefined+ : createSession(owner.sessionId, input.runtime, metadata);+ },+ };+}++/** Builds a request-scoped factory for channel addresses on one authored channel. */+export function createChannelAddressFn<TState = undefined>(input: {+ readonly adapter: ChannelAdapter<any>;+ readonly channelName: string;+ readonly metadata?: { readonly requestId?: string };+ readonly runtime: Runtime;+}): ChannelAddressFn<TState> {+ return (continuationToken) => createChannelAddress({ ...input, continuationToken });+}diff --git a/packages/eve/src/channel/channel-operations.test.ts b/packages/eve/src/channel/channel-operations.test.tsnew file mode 100644index 000000000..387062cb0--- /dev/null+++ b/packages/eve/src/channel/channel-operations.test.ts@@ -0,0 +1,100 @@+import { describe, expect, it, vi } from "vitest";++import { createChannelOperations } from "#channel/channel-operations.js";+import type { Runtime } from "#channel/types.js";++function createRuntime(): Runtime {+ return {+ createSession: vi.fn(),+ dispatchContinuation: vi.fn().mockResolvedValue({+ sessionId: "sess_1",+ status: "accepted",+ }),+ dispatchSession: vi.fn(),+ getEventStream: vi.fn(),+ getStreamTailIndex: vi.fn(),+ resolveContinuation: vi.fn(),+ };+}++describe("createChannelOperations", () => {+ it("sends through a channel-local address without serializing operation options", async () => {+ const runtime = createRuntime();+ const { from } = createChannelOperations({+ adapter: { kind: "slack" },+ channelName: "slack",+ runtime,+ });++ const session = await from("C1:T1").send("hello", {+ auth: null,+ title: "Support thread",+ });+ await session.clear();++ expect(runtime.dispatchContinuation).toHaveBeenCalledWith({+ command: {+ auth: null,+ kind: "send",+ payload: { message: "hello" },+ requestId: undefined,+ },+ continuationToken: "slack:C1:T1",+ });+ expect(runtime.dispatchSession).toHaveBeenCalledWith({+ command: { kind: "clear" },+ sessionId: "sess_1",+ });+ });++ it("targets every control operation by raw channel-local address", async () => {+ const runtime = createRuntime();+ const { from } = createChannelOperations({+ adapter: { kind: "slack" },+ channelName: "slack",+ runtime,+ });++ const source = from("C1:T1");+ await source.cancel({ turnId: "turn_1" });+ await source.compact();+ await source.clear();+ await source.reset({ reason: "fresh start" });++ expect(runtime.dispatchContinuation).toHaveBeenNthCalledWith(1, {+ command: { kind: "cancel", turnId: "turn_1" },+ continuationToken: "slack:C1:T1",+ });+ expect(runtime.dispatchContinuation).toHaveBeenNthCalledWith(2, {+ command: { kind: "compact" },+ continuationToken: "slack:C1:T1",+ });+ expect(runtime.dispatchContinuation).toHaveBeenNthCalledWith(3, {+ command: { kind: "clear" },+ continuationToken: "slack:C1:T1",+ });+ expect(runtime.dispatchContinuation).toHaveBeenNthCalledWith(4, {+ command: { kind: "reset", reason: "fresh start" },+ continuationToken: "slack:C1:T1",+ });+ });++ it("resolves an address owner only when explicitly requested", async () => {+ const runtime = createRuntime();+ vi.mocked(runtime.resolveContinuation).mockResolvedValue({ sessionId: "sess_2" });+ const { resolveSession } = createChannelOperations({+ adapter: { kind: "slack" },+ channelName: "slack",+ runtime,+ });++ const session = await resolveSession("C1:T1");+ await session?.clear();++ expect(runtime.resolveContinuation).toHaveBeenCalledWith("slack:C1:T1");+ expect(runtime.dispatchSession).toHaveBeenCalledWith({+ command: { kind: "clear" },+ sessionId: "sess_2",+ });+ });+});diff --git a/packages/eve/src/channel/channel-operations.ts b/packages/eve/src/channel/channel-operations.tsnew file mode 100644index 000000000..c62528194--- /dev/null+++ b/packages/eve/src/channel/channel-operations.ts@@ -0,0 +1,146 @@+import type { UserContent } from "ai";++import type { ChannelAdapter } from "#channel/adapter.js";+import {+ createChannelAddressFn,+ type ChannelAddressDeliveryOptions,+} from "#channel/channel-address.js";+import type { SendPayload } from "#channel/routes.js";+import type { Session } from "#channel/session.js";+import type {+ CancelTurnResult,+ ClearSessionResult,+ CompactSessionResult,+ ResetSessionResult,+ Runtime,+ SessionAuthContext,+ SessionCallback,+} from "#channel/types.js";+import type { InputResponse } from "#runtime/input/types.js";+import type { JsonObject } from "#shared/json.js";+import type { RunMode } from "#shared/run-mode.js";++interface BaseChannelSendOptions {+ readonly auth: SessionAuthContext | null;+ readonly callback?: SessionCallback;+ readonly context?: readonly string[];+ readonly initiatorAuth?: SessionAuthContext | null;+ readonly mode?: RunMode;+ readonly outputSchema?: JsonObject;+ readonly title?: string;+}++/** Options for sending a message from a channel-local continuation address. */+export type ChannelSendOptions<TState = undefined> = [TState] extends [undefined]+ ? BaseChannelSendOptions+ : BaseChannelSendOptions & { readonly state: TState };++interface BaseChannelRespondOptions {+ readonly auth: SessionAuthContext | null;+ readonly context?: readonly string[];+ readonly outputSchema?: JsonObject;+}++/** Options for answering pending input requests at an existing continuation address. */+export type ChannelRespondOptions = BaseChannelRespondOptions;++/** Dynamic handle for whichever session currently owns one channel-local address. */+export interface ChannelSource<TState = undefined> {+ /** Starts or resumes a turn with a user message. May create a session. */+ send(message: string | UserContent, options: ChannelSendOptions<TState>): Promise<Session>;+ /** Answers pending input requests. Never creates a session. */+ respond(+ inputResponses: readonly InputResponse[],+ options: ChannelRespondOptions,+ ): Promise<Session>;+ /** Cooperatively cancels the active turn without creating a session. */+ cancel(options?: { readonly turnId?: string }): Promise<CancelTurnResult>;+ /** Queues context compaction without creating a session. */+ compact(): Promise<CompactSessionResult>;+ /** Clears model-message history without creating a session. */+ clear(): Promise<ClearSessionResult>;+ /** Retires the current owner without creating a replacement. */+ reset(options?: { readonly reason?: string }): Promise<ResetSessionResult>;+}++/** Binds a raw channel-local continuation address to its current-owner operations. */+export type ChannelFrom<TState = undefined> = (address: string) => ChannelSource<TState>;++/** Snapshots the session currently owning a channel-local continuation address. */+export type ChannelResolveSession = (address: string) => Promise<Session | undefined>;++/** Continuation operations passed to an authored channel's proactive `receive` hook. */+export interface ChannelReceiveContext<TState = undefined> {+ readonly from: ChannelFrom<TState>;+ readonly resolveSession: ChannelResolveSession;+}++export const INTERNAL_CHANNEL_DELIVER = Symbol("eve.internal.channel-deliver");++/** @internal Permissive transport delivery retained below public authoring surfaces. */+export interface InternalChannelSource<TState = undefined> extends ChannelSource<TState> {+ [INTERNAL_CHANNEL_DELIVER](+ payload: SendPayload,+ options: ChannelAddressDeliveryOptions<TState>,+ ): Promise<Session>;+}++/** Creates request-scoped channel operations backed by continuation dispatch. */+export function createChannelOperations<TState = undefined>(input: {+ readonly adapter: ChannelAdapter<any>;+ readonly channelName: string;+ readonly metadata?: { readonly requestId?: string };+ readonly runtime: Runtime;+}): ChannelReceiveContext<TState> {+ const channelAddress = createChannelAddressFn<TState>(input);++ return {+ from(address) {+ const bound = channelAddress(address);+ const source: InternalChannelSource<TState> = {+ async send(message, options) {+ return await bound.deliver(+ {+ context: options.context,+ message,+ outputSchema: options.outputSchema,+ },+ options,+ );+ },+ async respond(inputResponses, options) {+ if (inputResponses.length === 0) {+ throw new Error("respond() requires at least one input response.");+ }+ return await bound.deliver(+ {+ context: options.context,+ inputResponses,+ outputSchema: options.outputSchema,+ },+ options,+ );+ },+ async cancel(options) {+ return await bound.cancel(options);+ },+ async compact() {+ return await bound.compact();+ },+ async clear() {+ return await bound.clear();+ },+ async reset(options) {+ return await bound.reset(options);+ },+ async [INTERNAL_CHANNEL_DELIVER](payload, options) {+ return await bound.deliver(payload, options);+ },+ };+ return source;+ },+ async resolveSession(address) {+ return await channelAddress(address).resolveSession();+ },+ };+}diff --git a/packages/eve/src/channel/clear-session.test.ts b/packages/eve/src/channel/clear-session.test.tsdeleted file mode 100644index be62f3608..000000000--- a/packages/eve/src/channel/clear-session.test.ts+++ /dev/null@@ -1,26 +0,0 @@-import { describe, expect, it, vi } from "vitest";--import { createClearFn } from "#channel/clear-session.js";-import type { Runtime } from "#channel/types.js";--describe("createClearFn", () => {- it("dispatches clear through the namespaced channel address", async () => {- const runtime = {- createSession: vi.fn(),- dispatchContinuation: vi.fn().mockResolvedValue({ sessionId: "sess_1", status: "accepted" }),- dispatchSession: vi.fn(),- getEventStream: vi.fn(),- getStreamTailIndex: vi.fn(),- resolveContinuation: vi.fn(),- } satisfies Runtime;-- await expect(createClearFn(runtime, "slack")({ continuationToken: "C1:T1" })).resolves.toEqual({- sessionId: "sess_1",- status: "accepted",- });- expect(runtime.dispatchContinuation).toHaveBeenCalledWith({- command: { kind: "clear" },- continuationToken: "slack:C1:T1",- });- });-});diff --git a/packages/eve/src/channel/clear-session.ts b/packages/eve/src/channel/clear-session.tsdeleted file mode 100644index b7004e363..000000000--- a/packages/eve/src/channel/clear-session.ts+++ /dev/null@@ -1,11 +0,0 @@-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.dispatchContinuation({- command: { kind: "clear" },- continuationToken: `${channelName}:${options.continuationToken}`,- });-}diff --git a/packages/eve/src/channel/compact-session.test.ts b/packages/eve/src/channel/compact-session.test.tsdeleted file mode 100644index b55829b4d..000000000--- a/packages/eve/src/channel/compact-session.test.ts+++ /dev/null@@ -1,25 +0,0 @@-import { describe, expect, it, vi } from "vitest";--import { createCompactFn } from "#channel/compact-session.js";-import type { Runtime } from "#channel/types.js";--describe("createCompactFn", () => {- it("dispatches compact through the namespaced channel address", async () => {- const runtime = {- createSession: vi.fn(),- dispatchContinuation: vi.fn().mockResolvedValue({ sessionId: "sess_1", status: "accepted" }),- dispatchSession: vi.fn(),- getEventStream: vi.fn(),- getStreamTailIndex: vi.fn(),- resolveContinuation: vi.fn(),- } satisfies Runtime;-- await expect(- createCompactFn(runtime, "slack")({ continuationToken: "C1:T1" }),- ).resolves.toEqual({ sessionId: "sess_1", status: "accepted" });- expect(runtime.dispatchContinuation).toHaveBeenCalledWith({- command: { kind: "compact" },- continuationToken: "slack:C1:T1",- });- });-});diff --git a/packages/eve/src/channel/compact-session.ts b/packages/eve/src/channel/compact-session.tsdeleted file mode 100644index 8f31da14e..000000000--- a/packages/eve/src/channel/compact-session.ts+++ /dev/null@@ -1,11 +0,0 @@-import type { CompactFn, CompactOptions } from "#channel/routes.js";-import type { CompactSessionResult, Runtime } from "#channel/types.js";--/** Builds a channel-scoped manual compaction helper. */-export function createCompactFn(runtime: Runtime, channelName: string): CompactFn {- return async (options: CompactOptions): Promise<CompactSessionResult> =>- await runtime.dispatchContinuation({- command: { kind: "compact" },- continuationToken: `${channelName}:${options.continuationToken}`,- });-}diff --git a/packages/eve/src/channel/compiled-channel.ts b/packages/eve/src/channel/compiled-channel.tsindex fba8bda54..1b6fd49e9 100644--- a/packages/eve/src/channel/compiled-channel.ts+++ b/packages/eve/src/channel/compiled-channel.ts@@ -1,6 +1,9 @@import type { ChannelAdapter } from "#channel/adapter.js";+import type { UserContent } from "ai";+import type { ChannelReceiveContext } from "#channel/channel-operations.js";import type { NormalizedChannelCorsOptions } from "#channel/cors.js";-import type { RouteDefinition, SendFn } from "#channel/routes.js";+import type { TypedReceiveTarget } from "#channel/receive-target.js";+import type { RouteDefinition } from "#channel/routes.js";import type { Session } from "#channel/session.js";import type { SessionAuthContext } from "#channel/types.js";@@ -18,23 +21,29 @@ const channelInstrumentationKindGlobal = globalThis as ChannelInstrumentationKinchannelInstrumentationKindGlobal[CHANNEL_INSTRUMENTATION_KINDS] ??= new Map();const channelInstrumentationKinds = channelInstrumentationKindGlobal[CHANNEL_INSTRUMENTATION_KINDS];+/** Structural identity shared by public authored channels and compiled channels. */+export interface ChannelReference<+ TReceiveTarget = Record<string, unknown>,+> extends TypedReceiveTarget<TReceiveTarget> {+ readonly __kind: typeof CHANNEL_SENTINEL;+}+export interface CompiledChannel<TState = undefined,TReceiveTarget = Record<string, unknown>,TMetadata extends Record<string, unknown> = Record<string, unknown>,-> {- readonly __kind: typeof CHANNEL_SENTINEL;+> extends ChannelReference<TReceiveTarget> {readonly routes: readonly RouteDefinition<TState>[];readonly adapter: ChannelAdapter<any>;readonly cors?: NormalizedChannelCorsOptions;readonly __metadata?: TMetadata;readonly receive?: (input: {- readonly message: string;+ readonly message: string | UserContent;readonly target: Readonly<TReceiveTarget>;readonly auth: SessionAuthContext | null;},- args: { send: SendFn<TState> },+ ctx: ChannelReceiveContext<TState>,) => Promise<Session>;}diff --git a/packages/eve/src/channel/cross-channel-receive.test.ts b/packages/eve/src/channel/cross-channel-receive.test.tsindex 2f9d608c3..4a4f29838 100644--- a/packages/eve/src/channel/cross-channel-receive.test.ts+++ b/packages/eve/src/channel/cross-channel-receive.test.ts@@ -1,10 +1,7 @@import { describe, expect, it, vi } from "vitest";import { CHANNEL_SENTINEL, type CompiledChannel } from "#channel/compiled-channel.js";-import {- createCrossChannelReceiveFn,- type CrossChannelTarget,-} from "#channel/cross-channel-receive.js";+import { createCrossChannelToFn, type CrossChannelTarget } from "#channel/cross-channel-receive.js";import type { Session } from "#channel/session.js";import type { Runtime } from "#channel/types.js";@@ -22,7 +19,6 @@ function makeRuntime(): Runtime {function makeSession(): Session {return {id: "sess_1",- continuationToken: "tok",async cancel() {return { status: "no_active_turn" };},@@ -32,6 +28,21 @@ function makeSession(): Session {async getStreamTailIndex() {return -1;},+ async send() {+ return { sessionId: "sess_1", status: "accepted" };+ },+ async respond() {+ return { sessionId: "sess_1", status: "accepted" };+ },+ async compact() {+ return { status: "no_active_session" };+ },+ async clear() {+ return { status: "no_active_session" };+ },+ async reset() {+ return { status: "no_active_session" };+ },};}@@ -59,14 +70,23 @@ function makeChannel(name: string): {};}-describe("createCrossChannelReceiveFn", () => {+describe("createCrossChannelToFn", () => {+ it("requires an eve channel reference at compile time", () => {+ const fn = createCrossChannelToFn(makeRuntime(), []);+ const invalidCalls = () => {+ // @ts-expect-error arbitrary strings are not authored channel references.+ fn("slack", {});+ // @ts-expect-error arbitrary objects are not authored channel references.+ fn({}, {});+ };+ expect(invalidCalls).toBeTypeOf("function");+ });+it("delegates to the target channel's receive with a per-target send", async () => {const slack = makeChannel("slack");- const fn = createCrossChannelReceiveFn(makeRuntime(), [slack.target]);+ const fn = createCrossChannelToFn(makeRuntime(), [slack.target]);- const session = await fn(slack.definition, {- message: "hello",- target: { channelId: "C1" },+ const session = await fn(slack.definition, { channelId: "C1" }).send("hello", {auth: { attributes: {}, authenticator: "app", principalId: "u", principalType: "user" },});@@ -78,15 +98,15 @@ describe("createCrossChannelReceiveFn", () => {target: { channelId: "C1" },auth: expect.objectContaining({ principalId: "u" }),});- expect(typeof ctx.send).toBe("function");+ expect(typeof ctx.from).toBe("function");});it("resolves the target by reference identity even when multiple channels are registered", async () => {const slack = makeChannel("slack");const twilio = makeChannel("twilio");- const fn = createCrossChannelReceiveFn(makeRuntime(), [slack.target, twilio.target]);+ const fn = createCrossChannelToFn(makeRuntime(), [slack.target, twilio.target]);- await fn(twilio.definition, { message: "ping", target: {}, auth: null });+ await fn(twilio.definition, {}).send("ping", { auth: null });expect(twilio.receive).toHaveBeenCalledTimes(1);expect(slack.receive).not.toHaveBeenCalled();@@ -100,9 +120,9 @@ describe("createCrossChannelReceiveFn", () => {adapter: target.definition.adapter,receive: target.definition.receive,};- const fn = createCrossChannelReceiveFn(makeRuntime(), [target.target]);+ const fn = createCrossChannelToFn(makeRuntime(), [target.target]);- await fn(duplicateDefinition, { message: "ping", target: {}, auth: null });+ await fn(duplicateDefinition, {}).send("ping", { auth: null });expect(target.receive).toHaveBeenCalledTimes(1);});@@ -118,29 +138,27 @@ describe("createCrossChannelReceiveFn", () => {};first.target = { ...first.target, definition: duplicateDefinition };second.target = { ...second.target, definition: duplicateDefinition };- const fn = createCrossChannelReceiveFn(makeRuntime(), [first.target, second.target]);+ const fn = createCrossChannelToFn(makeRuntime(), [first.target, second.target]);- await expect(- fn({ ...duplicateDefinition }, { message: "ping", target: {}, auth: null }),- ).rejects.toThrow(/matches multiple registered channels by route shape/);+ expect(() => fn({ ...duplicateDefinition }, {})).toThrow(+ /matches multiple registered channels by route shape/,+ );});it("throws when the passed channel is not registered in this agent", async () => {const slack = makeChannel("slack");const stranger = makeChannel("stranger");- const fn = createCrossChannelReceiveFn(makeRuntime(), [slack.target]);+ const fn = createCrossChannelToFn(makeRuntime(), [slack.target]);- await expect(fn(stranger.definition, { message: "x", target: {}, auth: null })).rejects.toThrow(- /not registered in this agent's channels/,- );+ expect(() => fn(stranger.definition, {})).toThrow(/not registered in this agent's channels/);});it("throws when the target channel has no receive()", async () => {const slack = makeChannel("slack");slack.target = { ...slack.target, receive: undefined };- const fn = createCrossChannelReceiveFn(makeRuntime(), [slack.target]);+ const fn = createCrossChannelToFn(makeRuntime(), [slack.target]);- await expect(fn(slack.definition, { message: "x", target: {}, auth: null })).rejects.toThrow(+ await expect(fn(slack.definition, {}).send("x", { auth: null })).rejects.toThrow(/does not implement receive/,);});@@ -148,16 +166,14 @@ describe("createCrossChannelReceiveFn", () => {it("throws when the target channel has no adapter", async () => {const slack = makeChannel("slack");slack.target = { ...slack.target, adapter: undefined };- const fn = createCrossChannelReceiveFn(makeRuntime(), [slack.target]);+ const fn = createCrossChannelToFn(makeRuntime(), [slack.target]);- await expect(fn(slack.definition, { message: "x", target: {}, auth: null })).rejects.toThrow(- /no adapter/,- );+ await expect(fn(slack.definition, {}).send("x", { auth: null })).rejects.toThrow(/no adapter/);});it("forwards auth to the target receive verbatim", async () => {const slack = makeChannel("slack");- const fn = createCrossChannelReceiveFn(makeRuntime(), [slack.target]);+ const fn = createCrossChannelToFn(makeRuntime(), [slack.target]);const auth = {attributes: { incidentReference: "INC-42" },authenticator: "incidentio",@@ -165,7 +181,7 @@ describe("createCrossChannelReceiveFn", () => {principalType: "service" as const,};- await fn(slack.definition, { message: "go", target: {}, auth });+ await fn(slack.definition, {}).send("go", { auth });expect(slack.receive.mock.calls[0]![0]).toEqual(expect.objectContaining({ auth }));});diff --git a/packages/eve/src/channel/cross-channel-receive.ts b/packages/eve/src/channel/cross-channel-receive.tsindex f64f20e39..319fa1704 100644--- a/packages/eve/src/channel/cross-channel-receive.ts+++ b/packages/eve/src/channel/cross-channel-receive.ts@@ -1,35 +1,34 @@import type { UserContent } from "ai";import type { ChannelAdapter } from "#channel/adapter.js";-import { isCompiledChannel, type CompiledChannel } from "#channel/compiled-channel.js";+import { createChannelOperations } from "#channel/channel-operations.js";+import {+ isCompiledChannel,+ type ChannelReference,+ type CompiledChannel,+} from "#channel/compiled-channel.js";import type { InferReceiveTarget } from "#channel/receive-target.js";-import { createSendFn } from "#channel/send.js";import type { Session } from "#channel/session.js";import type { Runtime, SessionAuthContext } from "#channel/types.js";import type { ResolvedChannelDefinition } from "#runtime/types.js";/**- * Options accepted by {@link CrossChannelReceiveFn}. Mirrors the input- * argument of a channel's authored `receive(input, { send })` hook —- * the runtime constructs `send` internally so route-handler callers- * only supply the platform target, payload, and auth.+ * Options for sending a message to a channel selected with `ctx.to(...)`.*/-export interface CrossChannelReceiveOptions<TTarget = Record<string, unknown>> {- readonly message: string | UserContent;- readonly target: TTarget;+export interface CrossChannelSendOptions {readonly auth: SessionAuthContext | null;}-/**- * Starts a session on a different channel from inside a route handler.- * The target channel's authored `receive` hook owns continuation-token- * format and initial state; `auth` is forwarded verbatim and becomes- * `session.initiatorAuth`.- */-export type CrossChannelReceiveFn = <TChannel>(+/** Message delivery bound to one channel-specific proactive target. */+export interface CrossChannelTargetHandle {+ send(message: string | UserContent, options: CrossChannelSendOptions): Promise<Session>;+}++/** Selects another authored channel and one of its proactive targets. */+export type CrossChannelToFn = <TChannel extends ChannelReference>(channel: TChannel,- options: CrossChannelReceiveOptions<InferReceiveTarget<TChannel>>,-) => Promise<Session>;+ target: InferReceiveTarget<TChannel>,+) => CrossChannelTargetHandle;/*** Channel record consumed by the receiver — keeps the public-facing@@ -68,31 +67,32 @@ export function toCrossChannelTargets(}/**- * Builds the `args.receive` closure used by every route handler. The- * closure resolves the target channel by reference identity against- * the request-scoped channel bundle, then delegates to the target's- * authored `receive` hook with a per-target `send` factory.+ * Builds the `ctx.to(channel, target)` closure used by route and schedule handlers.*/-export function createCrossChannelReceiveFn(+export function createCrossChannelToFn(runtime: Runtime,channels: readonly CrossChannelTarget[],-): CrossChannelReceiveFn {- return async (channel, options) => {+): CrossChannelToFn {+ return (channel, target) => {const targetChannel = resolveTargetByReference(channel, channels);- return await invokeChannelReceive({- runtime,- target: targetChannel,- input: {- message: options.message as string,- target: options.target as Readonly<Record<string, unknown>>,- auth: options.auth,+ return {+ async send(message, options) {+ return await invokeChannelReceive({+ runtime,+ target: targetChannel,+ input: {+ message,+ target: target as Readonly<Record<string, unknown>>,+ auth: options.auth,+ },+ describeMissingReceive: () =>+ `ctx.to(): channel "${targetChannel.name}" does not implement receive(). ` ++ `Declare a receive hook on the channel to accept cross-channel sessions.`,+ describeMissingAdapter: () =>+ `ctx.to(): channel "${targetChannel.name}" has no adapter — cannot build ctx.from().`,+ });},- describeMissingReceive: () =>- `args.receive(): channel "${targetChannel.name}" does not implement receive(). ` +- `Declare a receive hook on the channel to accept cross-channel sessions.`,- describeMissingAdapter: () =>- `args.receive(): channel "${targetChannel.name}" has no adapter — cannot build send().`,- });+ };};}@@ -100,7 +100,7 @@ interface InvokeChannelReceiveInput {readonly runtime: Runtime;readonly target: Pick<CrossChannelTarget, "name" | "receive" | "adapter">;readonly input: {- readonly message: string;+ readonly message: string | UserContent;readonly target: Readonly<Record<string, unknown>>;readonly auth: SessionAuthContext | null;};@@ -109,10 +109,7 @@ interface InvokeChannelReceiveInput {}/**- * Shared `receive(input, { send })` invocation used by both the route-- * handler cross-channel surface and the schedule dispatcher. Owns the- * receive/adapter precondition checks and the per-target `send`- * factory so both call sites stay byte-identical.+ * Shared authored `receive(input, ctx)` invocation used by route and schedule delivery.*/export async function invokeChannelReceive(args: InvokeChannelReceiveInput): Promise<Session> {if (!args.target.receive) {@@ -121,8 +118,12 @@ export async function invokeChannelReceive(args: InvokeChannelReceiveInput): Proif (!args.target.adapter) {throw new Error(args.describeMissingAdapter());}- const send = createSendFn(args.runtime, args.target.adapter, args.target.name);- return await args.target.receive(args.input, { send });+ const channelOperations = createChannelOperations({+ adapter: args.target.adapter,+ channelName: args.target.name,+ runtime: args.runtime,+ });+ return await args.target.receive(args.input, channelOperations);}function resolveTargetByReference(@@ -139,7 +140,7 @@ function resolveTargetByReference(return structurallyMatchedTarget;}throw new Error(- "args.receive(): the channel passed as the first argument is not registered " ++ "ctx.to(): the channel passed as the first argument is not registered " +"in this agent's channels/. Import the channel module's default export from " +"agent/channels/<name>.ts and pass that value.",);@@ -172,9 +173,9 @@ function resolveTargetByRouteFingerprint(}if (matches.size > 1) {throw new Error(- "args.receive(): the channel passed as the first argument matches multiple " ++ "ctx.to(): the channel passed as the first argument matches multiple " +"registered channels by route shape. Import a channel with a unique route set " +- "from agent/channels/<name>.ts before passing it to args.receive().",+ "from agent/channels/<name>.ts before passing it to ctx.to().",);}diff --git a/packages/eve/src/channel/receive-target.ts b/packages/eve/src/channel/receive-target.tsindex 62fca24d7..26dc174ef 100644--- a/packages/eve/src/channel/receive-target.ts+++ b/packages/eve/src/channel/receive-target.ts@@ -3,8 +3,7 @@ declare const receiveTargetMarker: unique symbol;/*** Structural marker that channel factories (e.g. `slackChannel`,* `twilioChannel`) add to declare the target type their `receive()` accepts.- * `receive(channel, { target })` helpers and the route-handler- * `args.receive(channel, ...)` read this marker to infer typed targets+ * `ctx.to(channel, target)` helpers read this marker to infer typed targets* from a plain channel import.*/export interface TypedReceiveTarget<TTarget = Record<string, unknown>> {diff --git a/packages/eve/src/channel/reset-session.test.ts b/packages/eve/src/channel/reset-session.test.tsdeleted file mode 100644index a35134036..000000000--- a/packages/eve/src/channel/reset-session.test.ts+++ /dev/null@@ -1,57 +0,0 @@-import { describe, expect, it, vi } from "vitest";--import { createResetFn } from "#channel/reset-session.js";-import type { Runtime } from "#channel/types.js";--function createRuntime(): Runtime {- return {- createSession: vi.fn(),- dispatchContinuation: vi- .fn()- .mockResolvedValue({ previousSessionId: "sess_1", status: "reset" }),- dispatchSession: vi.fn(),- getEventStream: vi.fn(),- getStreamTailIndex: vi.fn().mockResolvedValue(-1),- resolveContinuation: vi.fn(),- };-}--describe("createResetFn", () => {- it("dispatches reset directly through the namespaced channel address", async () => {- const runtime = createRuntime();-- await expect(- createResetFn(- runtime,- "imessage",- )({- continuationToken: "direct:+1:+2",- reason: "User requested /new",- }),- ).resolves.toEqual({ previousSessionId: "sess_1", status: "reset" });- expect(runtime.dispatchContinuation).toHaveBeenCalledWith({- command: { kind: "reset", reason: "User requested /new" },- continuationToken: "imessage:direct:+1:+2",- });- expect(runtime.resolveContinuation).not.toHaveBeenCalled();- });-- it("passes through no_active_session", async () => {- const runtime = createRuntime();- vi.mocked(runtime.dispatchContinuation).mockResolvedValue({ status: "no_active_session" });-- await expect(- createResetFn(runtime, "imessage")({ continuationToken: "direct:+1:+2" }),- ).resolves.toEqual({ status: "no_active_session" });- });-- it("propagates dispatch failures", async () => {- const failure = new Error("World unavailable");- const runtime = createRuntime();- vi.mocked(runtime.dispatchContinuation).mockRejectedValue(failure);-- await expect(- createResetFn(runtime, "imessage")({ continuationToken: "direct:+1:+2" }),- ).rejects.toBe(failure);- });-});diff --git a/packages/eve/src/channel/reset-session.ts b/packages/eve/src/channel/reset-session.tsdeleted file mode 100644index 9e615e5d2..000000000--- a/packages/eve/src/channel/reset-session.ts+++ /dev/null@@ -1,15 +0,0 @@-import type { ResetFn, ResetOptions, ResetResult } from "#channel/routes.js";-import type { Runtime } from "#channel/types.js";--/**- * Builds a channel-scoped session reset helper.- */-export function createResetFn(runtime: Runtime, channelName: string): ResetFn {- return async (options: ResetOptions): Promise<ResetResult> => {- const continuationToken = `${channelName}:${options.continuationToken}`;- return await runtime.dispatchContinuation({- command: { kind: "reset", reason: options.reason },- continuationToken,- });- };-}diff --git a/packages/eve/src/channel/resolve-active-session.test.ts b/packages/eve/src/channel/resolve-active-session.test.tsdeleted file mode 100644index 5bd1f2d2c..000000000--- a/packages/eve/src/channel/resolve-active-session.test.ts+++ /dev/null@@ -1,36 +0,0 @@-import { describe, expect, it, vi } from "vitest";--import { createResolveActiveSessionFn } from "#channel/resolve-active-session.js";-import type { Runtime } from "#channel/types.js";--function runtime(): Runtime {- return {- createSession: vi.fn(),- dispatchContinuation: vi.fn(),- dispatchSession: vi.fn(),- getEventStream: vi.fn().mockResolvedValue(new ReadableStream()),- getStreamTailIndex: vi.fn().mockResolvedValue(-1),- resolveContinuation: vi.fn(),- };-}--describe("createResolveActiveSessionFn", () => {- it("resolves a channel-local continuation using the authored channel name", async () => {- const mockRuntime = runtime();- vi.mocked(mockRuntime.resolveContinuation).mockResolvedValue({ sessionId: "session-1" });-- await expect(- createResolveActiveSessionFn(mockRuntime, "support")({ continuationToken: "C1:T1" }),- ).resolves.toEqual({ sessionId: "session-1" });- expect(mockRuntime.resolveContinuation).toHaveBeenCalledWith("support:C1:T1");- });-- it("returns undefined for an inactive continuation", async () => {- const mockRuntime = runtime();- vi.mocked(mockRuntime.resolveContinuation).mockResolvedValue(undefined);-- await expect(- createResolveActiveSessionFn(mockRuntime, "support")({ continuationToken: "C1:T1" }),- ).resolves.toBeUndefined();- });-});diff --git a/packages/eve/src/channel/resolve-active-session.ts b/packages/eve/src/channel/resolve-active-session.tsdeleted file mode 100644index 42dce629b..000000000--- a/packages/eve/src/channel/resolve-active-session.ts+++ /dev/null@@ -1,11 +0,0 @@-import type { ResolveActiveSessionFn } from "#channel/routes.js";-import type { Runtime } from "#channel/types.js";--/** Builds a channel-scoped lookup for the active owner of a continuation token. */-export function createResolveActiveSessionFn(- runtime: Runtime,- channelName: string,-): ResolveActiveSessionFn {- return ({ continuationToken }) =>- runtime.resolveContinuation(`${channelName}:${continuationToken}`);-}diff --git a/packages/eve/src/channel/routes.ts b/packages/eve/src/channel/routes.tsindex f853c9866..304a73506 100644--- a/packages/eve/src/channel/routes.ts+++ b/packages/eve/src/channel/routes.ts@@ -1,55 +1,36 @@import type { UserContent } from "ai";-import type { CrossChannelReceiveFn } from "#channel/cross-channel-receive.js";-import type {- CancelTurnResult,- ClearSessionResult,- CompactSessionResult,- SessionAuthContext,- SessionCallback,- SessionCapabilities,- TurnCaller,-} from "#channel/types.js";+import type { CrossChannelToFn } from "#channel/cross-channel-receive.js";+import type { ChannelFrom, ChannelResolveSession } from "#channel/channel-operations.js";import type { InputResponse } from "#runtime/input/types.js";import type { Session } from "#channel/session.js";-import type { RunMode } from "#shared/run-mode.js";import type { JsonObject } from "#shared/json.js";import type { ChannelMethod } from "#public/definitions/channel.js";type WebSocketHeaders = Headers | readonly (readonly [string, string])[] | Record<string, string>;/**- * 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; `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.+ * Second argument passed to every route handler. `from` binds local operations,+ * `resolveSession` snapshots the current owner, `to` selects a proactive target+ * on another channel, and `attachSession` binds an immutable-ID handle.*/export interface RouteHandlerArgs<TState = undefined> {- send: SendFn<TState>;+ /** Binds a raw channel-local address to its current-owner operations. */+ readonly from: ChannelFrom<TState>;+ /** Snapshots the session currently owning a raw channel-local address. */+ readonly resolveSession: ChannelResolveSession;+ /** Attaches a fixed operation handle to one exact durable session ID without performing I/O. */+ attachSession: AttachSessionFn;/**- * Resolves the session currently owning a channel-local continuation token.- * This point-in-time lookup does not reserve the continuation.+ * Selects a proactive target on another channel. Call `.send(message, options)`+ * on the returned handle; the target channel owns its address and initial state.*/- resolveActiveSession: ResolveActiveSessionFn;- cancel: CancelFn;- clear: ClearFn;- compact: CompactFn;- reset: ResetFn;- getSession: GetSessionFn;- /**- * Starts a session on a different channel to hand off inbound work (e.g. an- * HTTP webhook routing the conversation onto Slack). The target's authored- * `receive` hook owns continuation-token format and initial state; the caller- * supplies the payload, channel-specific args, and auth.- */- receive: CrossChannelReceiveFn;+ readonly to: CrossChannelToFn;+ /** Path parameters matched for the current route. */params: Readonly<Record<string, string>>;+ /** Keeps background work alive after the route returns its response. */waitUntil: (task: Promise<unknown>) => void;+ /** Best-effort client IP reported by the host, or `null` when unavailable. */requestIp: string | null;}@@ -63,142 +44,14 @@ export interface SendPayload {*/readonly context?: readonly string[];/**- * Run-scoped JSON schema the turn's result must match. Orthogonal to- * {@link BaseSendOptions.mode}: eve enforces the schema in either mode; mode- * only decides the failure behavior. A conversation run parks recoverably and- * waits for more input; a task run (which cannot wait) finishes as an error.+ * Run-scoped JSON schema the turn's result must match. eve enforces the+ * schema in conversation and task mode; mode only decides failure behavior.*/readonly outputSchema?: JsonObject;}-/**- * Starts or continues a session on this channel. Accepts a plain string,- * `UserContent`, or a {@link SendPayload}, plus {@link SendOptions}. Resolves- * to the resulting {@link Session}.- */-export type SendFn<TState = undefined> = (- input: string | UserContent | SendPayload,- options: SendOptions<TState>,-) => Promise<Session>;--/** Resolves the active owner of a channel-local continuation token. */-export type ResolveActiveSessionFn = (options: {- readonly continuationToken: string;-}) => Promise<{ readonly sessionId: string } | undefined>;--type BaseSendOptions = {- auth: SessionAuthContext | null;- callback?: SessionCallback;- /** Framework-internal delegated caller waiting on this turn's settled result. */- caller?: TurnCaller;- capabilities?: SessionCapabilities;- continuationToken: string;- /**- * `"resume"` requires an active session and propagates a typed no-active-session- * error. `"resume-or-start"` preserves the default channel behavior.- */- intent?: "resume" | "resume-or-start";- /**- * The original (top-level) caller's auth for a newly started session,- * becoming `session.auth.initiator`. Defaults to {@link auth} when omitted- * (root session behavior). Ignored when the send resolves to an existing- * session, whose initiator never changes after start.- */- initiatorAuth?: SessionAuthContext | null;- mode?: RunMode;- /**- * Human-readable title for a newly started workflow session. Defaults to- * the first user message and is ignored when resuming an existing session.- */- title?: string;-};--/**- * Options for {@link SendFn}. The channel owns its continuation-token- * format: pass the channel-local raw token (the framework prepends- * the channel name). Stateful channels also seed initial adapter- * state via {@link state}, which becomes the new session's `state`- * on first `runtime.run()` and is ignored on subsequent `deliver`s.- */-export type SendOptions<TState = undefined> = [TState] extends [undefined]- ? BaseSendOptions- : BaseSendOptions & { state: TState };--/**- * Resolves an existing {@link Session} by id, for example to read its event- * stream from within a route handler.- */-export type GetSessionFn = (sessionId: string) => Session;--/**- * Options for {@link CancelFn}. `continuationToken` is the channel-local raw- * token, exactly as passed to {@link SendFn}. `turnId` limits the request to- * the turn the caller observed; a stale guard is consumed as a benign no-op.- */-export interface CancelOptions {- readonly continuationToken: string;- readonly turnId?: string;-}--/**- * Requests cancellation of the active turn on the session that owns the- * continuation token. Never starts a session, sends input, or clears history.- *- * Both statuses are successful: `"accepted"` means the request was consumed,- * and `"no_active_turn"` covers an unknown token and a session with nothing- * to cancel. Confirmation is `turn.cancelled` followed by `session.waiting`- * on the event stream.- */-export type CancelFn = (options: CancelOptions) => Promise<CancelTurnResult>;--/** Options for {@link CompactFn}. */-export interface CompactOptions {- /** Channel-local raw token, in the same format accepted by {@link SendFn}. */- readonly continuationToken: string;-}--/**- * Queues context compaction for the session owning a continuation token.- * Never sends model input or starts a new session. An accepted request returns- * to `session.waiting`; successful compaction emits `compaction.requested`- * followed by `compaction.completed` on the session stream.- */-export type CompactFn = (options: CompactOptions) => Promise<CompactSessionResult>;--/** Options for {@link 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}. */- readonly continuationToken: string;- /** Human-readable terminal reason. Do not include credentials or message contents. */- readonly reason?: string;-}--/** Result of resetting the session that owned a continuation token. */-export type ResetResult =- | { readonly status: "reset"; readonly previousSessionId: string }- | { readonly status: "no_active_session" };--/**- * Terminally retires the session currently owning a continuation token.- * The token is available for the next {@link SendFn} after this resolves;- * that send starts with fresh history and state, and initializes a new- * session-scoped sandbox on first sandbox use.- */-export type ResetFn = (options: ResetOptions) => Promise<ResetResult>;+/** Attaches an I/O-free handle to one exact durable session ID. */+export type AttachSessionFn = (sessionId: string) => Session;export type RouteHandler<TState = undefined> = (req: Request,diff --git a/packages/eve/src/channel/schedule.test.ts b/packages/eve/src/channel/schedule.test.tsindex 4a9d7e6ab..687d6b94a 100644--- a/packages/eve/src/channel/schedule.test.ts+++ b/packages/eve/src/channel/schedule.test.ts@@ -15,7 +15,6 @@ import type { ResolvedChannelDefinition } from "#runtime/types.js";function createMockRunHandle(): RunHandle {return {- continuationToken: "slack:C0123ABC:",events: new ReadableStream<MessageStreamEvent>(),sessionId: "mock-session-id",};@@ -94,7 +93,7 @@ describe("ScheduleDispatcher", () => {});describe("run handler form", () => {- it("invokes the author's run() with { receive, waitUntil, appAuth }", async () => {+ it("invokes the author's run() with { to, waitUntil, appAuth }", async () => {const runtime = createMockRuntime();vi.stubEnv("SLACK_BOT_TOKEN", "xoxb-test");vi.stubEnv("SLACK_SIGNING_SECRET", "test-secret");@@ -109,12 +108,10 @@ describe("ScheduleDispatcher", () => {const result = await dispatcher.trigger({scheduleId: "daily-digest",- async run({ receive, waitUntil, appAuth }) {+ async run({ to, waitUntil, appAuth }) {observed.hasAppAuth = appAuth.principalId === "eve:app";observed.hasWaitUntil = typeof waitUntil === "function";- await receive(definition, {- message: "post the digest",- target: { channelId: "C0123ABC" },+ await to(definition, { channelId: "C0123ABC" }).send("post the digest", {auth: appAuth,});},@@ -152,7 +149,7 @@ describe("ScheduleDispatcher", () => {expect(result.sessions).toHaveLength(0);});- it("throws when args.receive(channel) is called with an unregistered channel", async () => {+ it("throws when ctx.to(channel) is called with an unregistered channel", async () => {const runtime = createMockRuntime();const dispatcher = new ScheduleDispatcher({ runtime, channels: [] });const stranger = {@@ -164,8 +161,8 @@ describe("ScheduleDispatcher", () => {await expect(dispatcher.trigger({scheduleId: "stranger",- async run({ receive }) {- await receive(stranger, { message: "x", target: {}, auth: null });+ async run({ to }) {+ await to(stranger, {}).send("x", { auth: null });},}),).rejects.toThrow(/not registered in this agent/);diff --git a/packages/eve/src/channel/schedule.ts b/packages/eve/src/channel/schedule.tsindex 6794875e3..163c2e321 100644--- a/packages/eve/src/channel/schedule.ts+++ b/packages/eve/src/channel/schedule.ts@@ -1,9 +1,6 @@import type { ChannelAdapter } from "#channel/adapter.js";import { SCHEDULE_APP_AUTH } from "#channel/schedule-auth.js";-import {- createCrossChannelReceiveFn,- toCrossChannelTargets,-} from "#channel/cross-channel-receive.js";+import { createCrossChannelToFn, toCrossChannelTargets } from "#channel/cross-channel-receive.js";import { createSession, type Session } from "#channel/session.js";import type { Runtime } from "#channel/types.js";import { expectFunction } from "#internal/authored-module.js";@@ -45,7 +42,7 @@ export interface ScheduleDispatchInput {** For handler schedules: builds {@link ScheduleHandlerArgs} against the* request-scoped channel bundle and invokes the author's `run`. The- * author owns control flow — `args.receive(channel, …)` hands work off+ * author owns control flow — `args.to(channel, target).send(…)` hands work off* to a channel; `args.waitUntil(promise)` extends the task lifetime* so the dispatcher awaits in-flight work before settling.*@@ -77,14 +74,19 @@ export class ScheduleDispatcher {async trigger(input: ScheduleDispatchInput): Promise<ScheduleDispatchResult> {const sessions: Session[] = [];const waitUntilTasks: Promise<unknown>[] = [];- const receive = createCrossChannelReceiveFn(this.runtime, toCrossChannelTargets(this.channels));+ const toChannel = createCrossChannelToFn(this.runtime, toCrossChannelTargets(this.channels));const args: ScheduleHandlerArgs = {appAuth: SCHEDULE_APP_AUTH,- receive: async (channel, options) => {- const session = await receive(channel, options);- sessions.push(session);- return session;+ to(channel, target) {+ const destination = toChannel(channel, target);+ return {+ async send(message, options) {+ const session = await destination.send(message, options);+ sessions.push(session);+ return session;+ },+ };},waitUntil(task) {waitUntilTasks.push(task);@@ -112,7 +114,7 @@ export class ScheduleDispatcher {input: { message: markdown },mode: "task",});- return createSession(handle.sessionId, handle.continuationToken, this.runtime);+ return createSession(handle.sessionId, this.runtime);}}diff --git a/packages/eve/src/channel/send-input.ts b/packages/eve/src/channel/send-input.tsnew file mode 100644index 000000000..a7962483f--- /dev/null+++ b/packages/eve/src/channel/send-input.ts@@ -0,0 +1,28 @@+import type { FilePart, UserContent } from "ai";++import type { SendPayload } from "#channel/routes.js";+import { serializeUrlFilePart } from "#internal/attachments/url-refs.js";++/** Normalizes the shorthand input forms accepted by channel and session sends. */+export function normalizeSendInput(input: string | UserContent | SendPayload): SendPayload {+ if (typeof input === "string") return { message: input };+ if (Array.isArray(input)) return { message: input };+ return input;+}++/** Serializes non-data URL file parts before input crosses the durable boundary. */+export function serializeUrlFilePartsInMessage(+ message: string | UserContent | undefined,+): string | UserContent | undefined {+ if (message === undefined || typeof message === "string") return message;++ let changed = false;+ const result = message.map((part): FilePart | typeof part => {+ if (part.type === "file" && part.data instanceof URL && part.data.protocol !== "data:") {+ changed = true;+ return { ...part, data: serializeUrlFilePart(part.data) };+ }+ return part;+ });+ return changed ? result : message;+}diff --git a/packages/eve/src/channel/send.test.ts b/packages/eve/src/channel/send.test.tsdeleted file mode 100644index 124a25084..000000000--- a/packages/eve/src/channel/send.test.ts+++ /dev/null@@ -1,251 +0,0 @@-import { describe, expect, it, vi } from "vitest";--import type { ChannelAdapter } from "#channel/adapter.js";-import { createSendFn } from "#channel/send.js";-import type { RunHandle, Runtime, SessionSendCommandResult } from "#channel/types.js";-import {- RuntimeNoActiveSessionError,- RuntimeSessionOwnershipConflictError,-} from "#execution/runtime-errors.js";-import type { MessageStreamEvent } from "#protocol/message.js";--function createMockRunHandle(): RunHandle {- return {- continuationToken: "test:token",- events: new ReadableStream<MessageStreamEvent>(),- sessionId: "mock-session-id",- };-}--function createRuntime(- dispatchResult: SessionSendCommandResult = { status: "session_not_active" },-): Runtime {- return {- createSession: vi.fn().mockResolvedValue(createMockRunHandle()),- dispatchContinuation: vi.fn().mockResolvedValue(dispatchResult),- dispatchSession: vi.fn(),- getEventStream: vi.fn().mockResolvedValue(new ReadableStream<MessageStreamEvent>()),- getStreamTailIndex: vi.fn().mockResolvedValue(-1),- resolveContinuation: vi.fn(),- };-}--const ADAPTER: ChannelAdapter = { kind: "channel:test" };--describe("createSendFn", () => {- it("creates a session when the channel address is unowned", async () => {- const runtime = createRuntime();- const send = createSendFn(runtime, ADAPTER, "test");-- const session = await send("hello", { auth: null, continuationToken: "token" });-- expect(session.id).toBe("mock-session-id");- expect(runtime.dispatchContinuation).toHaveBeenCalledWith({- command: {- auth: null,- caller: undefined,- kind: "send",- payload: {- context: undefined,- inputResponses: undefined,- message: "hello",- outputSchema: undefined,- },- requestId: undefined,- },- continuationToken: "test:token",- });- expect(runtime.createSession).toHaveBeenCalledOnce();- });-- it("rethrows a typed no-active-session error when resume intent forbids fallback", async () => {- const runtime = createRuntime();-- const send = createSendFn(runtime, ADAPTER, "test");- await expect(- send("hello", {- auth: null,- continuationToken: "token",- intent: "resume",- }),- ).rejects.toEqual(new RuntimeNoActiveSessionError("test:token"));-- expect(runtime.createSession).not.toHaveBeenCalled();- });-- it("returns the existing session without creating", async () => {- const runtime = createRuntime({ sessionId: "existing-session-id", status: "accepted" });- const send = createSendFn(runtime, ADAPTER, "test");-- await expect(send("hello", { auth: null, continuationToken: "token" })).resolves.toMatchObject({- id: "existing-session-id",- continuationToken: "token",- });- expect(runtime.createSession).not.toHaveBeenCalled();- });-- it("propagates unexpected dispatch failures without creating", async () => {- const failure = new Error("boom");- const runtime = createRuntime();- vi.mocked(runtime.dispatchContinuation).mockRejectedValue(failure);-- await expect(- createSendFn(- runtime,- ADAPTER,- "test",- )("hello", {- auth: null,- continuationToken: "token",- }),- ).rejects.toBe(failure);- expect(runtime.createSession).not.toHaveBeenCalled();- });-- it("rejects inputResponses when the channel address is unowned", async () => {- const runtime = createRuntime();-- await expect(- createSendFn(- runtime,- ADAPTER,- "test",- )(- { inputResponses: [{ requestId: "req-1", text: "yes" }] },- { auth: null, continuationToken: "token" },- ),- ).rejects.toThrow(/Cannot deliver inputResponses/);- expect(runtime.createSession).not.toHaveBeenCalled();- });-- it("re-dispatches to the winner of a concurrent first-send claim", async () => {- const runtime = createRuntime();- vi.mocked(runtime.createSession).mockRejectedValue(- new RuntimeSessionOwnershipConflictError({- continuationToken: "test:token",- ownerSessionId: "winner",- sessionId: "loser",- }),- );- vi.mocked(runtime.dispatchContinuation)- .mockResolvedValueOnce({ status: "session_not_active" })- .mockResolvedValueOnce({ sessionId: "winner", status: "accepted" });-- await expect(- createSendFn(- runtime,- ADAPTER,- "test",- )("hello", {- auth: null,- continuationToken: "token",- }),- ).resolves.toMatchObject({ id: "winner" });- expect(runtime.dispatchContinuation).toHaveBeenCalledTimes(2);- });-- it("forwards the turn caller on the session command", async () => {- const runtime = createRuntime({ sessionId: "existing-session-id", status: "accepted" });- const caller = {- callId: "call-1",- replyTo: { kind: "hook" as const, token: "parent-turn" },- subagentName: "research",- };-- await createSendFn(- runtime,- ADAPTER,- "test",- )({ message: "follow up" }, { auth: null, caller, continuationToken: "token" });-- expect(runtime.dispatchContinuation).toHaveBeenCalledWith({- command: expect.objectContaining({- caller,- payload: expect.not.objectContaining({ caller: expect.anything() }),- }),- continuationToken: "test:token",- });- });-- it("forwards context, output schema, and request id through dispatch and creation", async () => {- const runtime = createRuntime();- const outputSchema = {- properties: { title: { type: "string" } },- required: ["title"],- type: "object",- } as const;- const send = createSendFn(runtime, ADAPTER, "test", { requestId: "req_send" });-- await send(- { context: ["thread background"], message: "hello", outputSchema },- { auth: null, continuationToken: "token" },- );-- expect(runtime.dispatchContinuation).toHaveBeenCalledWith({- command: expect.objectContaining({- payload: expect.objectContaining({- context: ["thread background"],- message: "hello",- outputSchema,- }),- requestId: "req_send",- }),- continuationToken: "test:token",- });- expect(vi.mocked(runtime.createSession).mock.calls[0]![0]).toEqual(- expect.objectContaining({- input: {- context: ["thread background"],- message: "hello",- outputSchema,- },- requestId: "req_send",- }),- );- });-- it("namespaces the raw token and seeds state for a new session", async () => {- interface State {- channelId: string;- threadTs: string;- }- const runtime = createRuntime();- const adapter: ChannelAdapter = {- kind: "channel:stateful",- state: { channelId: null, threadTs: null },- };-- await createSendFn<State>(- runtime,- adapter,- "stateful",- )("hello", {- auth: null,- continuationToken: "C1:T1",- state: { channelId: "C1", threadTs: "T1" },- });-- const runInput = vi.mocked(runtime.createSession).mock.calls[0]![0];- expect(runInput.continuationToken).toBe("stateful:C1:T1");- expect(runInput.adapter.state).toEqual({ channelId: "C1", threadTs: "T1" });- });-- it("keeps an explicit workflow title separate from the model message", async () => {- const runtime = createRuntime();- const message = "<slack_message>ship it</slack_message>";-- await createSendFn(- runtime,- ADAPTER,- "test",- )(message, {- auth: null,- continuationToken: "token",- title: "ship it",- });-- const runInput = vi.mocked(runtime.createSession).mock.calls[0]![0];- expect(runInput.input.message).toBe(message);- expect(runInput.title).toBe("ship it");- });-});diff --git a/packages/eve/src/channel/send.ts b/packages/eve/src/channel/send.tsdeleted file mode 100644index c4cdfcb26..000000000--- a/packages/eve/src/channel/send.ts+++ /dev/null@@ -1,133 +0,0 @@-import type { FilePart, UserContent } from "ai";--import type { ChannelAdapter } from "#channel/adapter.js";-import type { RunInput, Runtime, SessionCommand } from "#channel/types.js";-import { createSession, type Session } from "#channel/session.js";-import type { SendFn, SendOptions, SendPayload } from "#channel/routes.js";-import {- isRuntimeSessionOwnershipConflictError,- RuntimeNoActiveSessionError,-} from "#execution/runtime-errors.js";-import { serializeUrlFilePart } from "#internal/attachments/url-refs.js";--export function createSendFn<TState = undefined>(- runtime: Runtime,- adapter: ChannelAdapter<any>,- channelName: string,- metadata: { readonly requestId?: string } = {},-): SendFn<TState> {- return async (- input: string | UserContent | SendPayload,- options: SendOptions<TState>,- ): Promise<Session> => {- // `SendOptions<TState>` is conditional on `TState`, so its properties are- // not accessible until the generic resolves; widen once to the base shape.- const opts = options as SendOptions<undefined> & { readonly state?: TState };- const { auth, callback, caller, capabilities, initiatorAuth, state, title } = opts;- const intent = opts.intent ?? "resume-or-start";- const mode = opts.mode ?? "conversation";- const rawToken = opts.continuationToken;- const continuationToken = `${channelName}:${rawToken}`;-- const {- message: rawMessage,- inputResponses,- context,- outputSchema,- } = normalizeSendInput(input);- const message = serializeUrlFilePartsInMessage(rawMessage);-- const command: Extract<SessionCommand, { readonly kind: "send" }> = {- auth,- caller,- kind: "send",- payload: { inputResponses, message, context, outputSchema },- requestId: metadata.requestId,- };-- const dispatch = async (): Promise<Session | undefined> => {- const result = await runtime.dispatchContinuation({- command,- continuationToken,- });- return result.status === "accepted"- ? createSession(result.sessionId, rawToken, runtime)- : undefined;- };-- const existing = await dispatch();- if (existing !== undefined) return existing;- if (intent === "resume") throw new RuntimeNoActiveSessionError(continuationToken);-- if (inputResponses && inputResponses.length > 0) {- throw new Error(- "Cannot deliver inputResponses — the target session was not found via continuation token.",- );- }-- const sessionAdapter = state- ? { ...adapter, state: { ...adapter.state, ...(state as Record<string, unknown>) } }- : adapter;-- const runInput: {- -readonly [K in keyof RunInput]: RunInput[K];- } = {- adapter: sessionAdapter,- auth,- capabilities: capabilities ?? (mode === "conversation" ? { requestInput: true } : undefined),- channelName,- callback,- continuationToken,- input: { message: message ?? "", context, outputSchema },- mode,- requestId: metadata.requestId,- title,- };- if (initiatorAuth !== undefined) {- runInput.initiatorAuth = initiatorAuth;- }- try {- const handle = await runtime.createSession(runInput);- return createSession(handle.sessionId, rawToken, runtime);- } catch (error) {- if (!isRuntimeSessionOwnershipConflictError(error)) throw error;- const winner = await dispatch();- if (winner !== undefined) return winner;- throw error;- }- };-}--/**- * Serializes `URL` objects in `FilePart.data` to `eve-url:` strings- * before the message crosses the queue boundary. The staging pipeline- * reconstitutes them on the other side.- */-function serializeUrlFilePartsInMessage(- message: string | UserContent | undefined,-): string | UserContent | undefined {- if (message === undefined || typeof message === "string") {- return message;- }- let changed = false;- const result = message.map((part): FilePart | typeof part => {- if (part.type === "file" && part.data instanceof URL && part.data.protocol !== "data:") {- changed = true;- return { ...part, data: serializeUrlFilePart(part.data) };- }- return part;- });- return changed ? result : message;-}--function normalizeSendInput(input: string | UserContent | SendPayload): SendPayload {- if (typeof input === "string") {- return { message: input };- }-- if (Array.isArray(input)) {- return { message: input };- }-- return input;-}diff --git a/packages/eve/src/channel/session.test.ts b/packages/eve/src/channel/session.test.tsindex d77b6ac67..408be8300 100644--- a/packages/eve/src/channel/session.test.ts+++ b/packages/eve/src/channel/session.test.ts@@ -1,6 +1,6 @@import { describe, expect, it, vi } from "vitest";-import { buildSessionHandle, createGetSessionFn, createSession } from "#channel/session.js";+import { buildSessionHandle, createAttachSessionFn, createSession } from "#channel/session.js";import type { Runtime } from "#channel/types.js";import { ContextContainer } from "#context/container.js";import { AuthKey, ContinuationTokenKey, InitiatorAuthKey, SessionIdKey } from "#context/keys.js";@@ -9,7 +9,12 @@ function createRuntime(): Runtime {return {createSession: vi.fn(),dispatchContinuation: vi.fn(),- dispatchSession: vi.fn().mockResolvedValue({ status: "accepted" }),+ dispatchSession: vi+ .fn()+ .mockImplementation(async ({ sessionId }: { readonly sessionId: string }) => ({+ sessionId,+ status: "accepted",+ })),getEventStream: vi.fn(),getStreamTailIndex: vi.fn(),resolveContinuation: vi.fn(),@@ -19,9 +24,9 @@ function createRuntime(): Runtime {describe("createSession#cancel", () => {it("cancels this session's turn by session id", async () => {const runtime = createRuntime();- const session = createSession("sess_1", "C1:T1", runtime);+ const session = createSession("sess_1", runtime);- await expect(session.cancel()).resolves.toEqual({ status: "accepted" });+ await expect(session.cancel()).resolves.toEqual({ sessionId: "sess_1", status: "accepted" });expect(runtime.dispatchSession).toHaveBeenCalledWith({command: { kind: "cancel", turnId: undefined },sessionId: "sess_1",@@ -30,7 +35,7 @@ describe("createSession#cancel", () => {it("forwards the turn guard", async () => {const runtime = createRuntime();- const session = createSession("sess_1", "C1:T1", runtime);+ const session = createSession("sess_1", runtime);await session.cancel({ turnId: "turn_2" });@@ -40,11 +45,11 @@ describe("createSession#cancel", () => {});});- it("is available on sessions returned by getSession", async () => {+ it("is available on sessions returned by attachSession", async () => {const runtime = createRuntime();- const session = createGetSessionFn(runtime)("sess_2");+ const session = createAttachSessionFn(runtime)("sess_2");- await expect(session.cancel()).resolves.toEqual({ status: "accepted" });+ await expect(session.cancel()).resolves.toEqual({ sessionId: "sess_2", status: "accepted" });expect(runtime.dispatchSession).toHaveBeenCalledWith({command: { kind: "cancel", turnId: undefined },sessionId: "sess_2",@@ -52,6 +57,83 @@ describe("createSession#cancel", () => {});});+describe("fixed session operations", () => {+ it("dispatches every operation through the stable session id", async () => {+ const runtime = createRuntime();+ const session = createAttachSessionFn(runtime, { requestId: "req_1" })("sess_1");++ await session.send("hello", { auth: null });+ await session.respond([{ optionId: "approve", requestId: "request_1" }], { auth: null });+ await session.compact();+ await session.clear();+ await session.reset({ reason: "fresh start" });++ expect(runtime.dispatchSession).toHaveBeenNthCalledWith(1, {+ command: {+ auth: null,+ kind: "send",+ payload: { message: "hello" },+ requestId: "req_1",+ },+ sessionId: "sess_1",+ });+ expect(runtime.dispatchSession).toHaveBeenNthCalledWith(2, {+ command: {+ auth: null,+ kind: "send",+ payload: { inputResponses: [{ optionId: "approve", requestId: "request_1" }] },+ requestId: "req_1",+ },+ sessionId: "sess_1",+ });+ expect(runtime.dispatchSession).toHaveBeenNthCalledWith(3, {+ command: { kind: "compact" },+ sessionId: "sess_1",+ });+ expect(runtime.dispatchSession).toHaveBeenNthCalledWith(4, {+ command: { kind: "clear" },+ sessionId: "sess_1",+ });+ expect(runtime.dispatchSession).toHaveBeenNthCalledWith(5, {+ command: { kind: "reset", reason: "fresh start" },+ sessionId: "sess_1",+ });+ });++ it("maps the public callback abstraction onto internal turn routing", async () => {+ const runtime = createRuntime();+ const session = createSession("sess_1", runtime);+ const callback = {+ callId: "call_1",+ subagentName: "research",+ token: "callback-token",+ url: "https://caller.example.com/eve/v1/callback/callback-token",+ };++ await session.send("continue", { auth: null, callback });+ const invalidSend = async () => {+ // @ts-expect-error runtime TurnCaller routing is not public session input.+ await session.send("continue", { auth: null, caller: {} });+ };+ expect(invalidSend).toBeTypeOf("function");++ expect(runtime.dispatchSession).toHaveBeenCalledWith({+ command: {+ auth: null,+ caller: {+ callId: "call_1",+ replyTo: { kind: "callback", url: callback.url },+ subagentName: "research",+ },+ kind: "send",+ payload: { message: "continue" },+ requestId: undefined,+ },+ sessionId: "sess_1",+ });+ });+});+describe("buildSessionHandle", () => {it("exposes sessionId / continuationToken / auth from the live accessor", () => {const ctx = new ContextContainer();@@ -73,7 +155,7 @@ describe("buildSessionHandle", () => {const session = buildSessionHandle(ctx);expect(session.id).toBe("sess-123");- expect(session.continuationToken).toBe("slack:C1:T1");+ expect(session.continuation?.token).toBe("C1:T1");expect(session.auth.current?.principalId).toBe("U1");expect(session.auth.initiator?.principalId).toBe("eve:app");});@@ -82,23 +164,33 @@ describe("buildSessionHandle", () => {const ctx = new ContextContainer();const session = buildSessionHandle(ctx);- expect(session.continuationToken).toBe("");+ expect(session.continuation).toBeUndefined();ctx.set(ContinuationTokenKey, "slack:C1:T1");- expect(session.continuationToken).toBe("slack:C1:T1");+ expect(session.continuation?.token).toBe("C1:T1");});- it("namespaces the channel-local token on setContinuationToken", () => {+ it("namespaces the channel-local token on continuation.rekey", () => {const ctx = new ContextContainer();ctx.set(ContinuationTokenKey, "slack:C1:");const session = buildSessionHandle(ctx);- session.setContinuationToken("C1:T1");+ session.continuation?.rekey("C1:T1");++ expect(ctx.get(ContinuationTokenKey)).toBe("slack:C1:T1");+ });++ it("round-trips the exposed channel-local token through continuation.rekey", () => {+ const ctx = new ContextContainer();+ ctx.set(ContinuationTokenKey, "slack:C1:T1");+ const session = buildSessionHandle(ctx);++ session.continuation?.rekey(session.continuation.token);expect(ctx.get(ContinuationTokenKey)).toBe("slack:C1:T1");});- it("is idempotent: a redundant setContinuationToken does not write", () => {- // Authors call setContinuationToken from hot-path event handlers+ it("is idempotent: a redundant continuation.rekey does not write", () => {+ // Authors call continuation.rekey from hot-path event handlers// (e.g. Slack's `message.completed`). The handler can't always// know whether the token has actually changed, so the SessionHandle// itself short-circuits redundant writes — the workflow body@@ -122,11 +214,11 @@ describe("buildSessionHandle", () => {const session = buildSessionHandle(observed);- session.setContinuationToken("C1:T1");+ session.continuation?.rekey("C1:T1");expect(writeCount).toBe(0);expect(ctx.get(ContinuationTokenKey)).toBe("slack:C1:T1");- session.setContinuationToken("C1:T2");+ session.continuation?.rekey("C1:T2");expect(writeCount).toBe(1);expect(ctx.get(ContinuationTokenKey)).toBe("slack:C1:T2");});@@ -135,6 +227,6 @@ describe("buildSessionHandle", () => {const ctx = new ContextContainer();const session = buildSessionHandle(ctx);- expect(() => session.setContinuationToken("C1:T1")).toThrow(/placeholder continuationToken/);+ expect(session.continuation).toBeUndefined();});});diff --git a/packages/eve/src/channel/session.ts b/packages/eve/src/channel/session.tsindex d7d0f3e16..0f66c2501 100644--- a/packages/eve/src/channel/session.ts+++ b/packages/eve/src/channel/session.ts@@ -1,64 +1,147 @@import type { ContextAccessor } from "#context/key.js";import type { MessageStreamEvent } from "#protocol/message.js";-import type { CancelTurnResult, Runtime } from "#channel/types.js";+import type { UserContent } from "ai";+import type {+ CancelTurnResult,+ ClearSessionResult,+ CompactSessionResult,+ ResetSessionResult,+ Runtime,+ SessionAuthContext,+ SessionCallback,+ SessionSendCommandResult,+ TurnCaller,+} from "#channel/types.js";+import { serializeUrlFilePartsInMessage } from "#channel/send-input.js";import type { SessionAuth } from "#context/keys.js";import { AuthKey, ContinuationTokenKey, InitiatorAuthKey, SessionIdKey } from "#context/keys.js";+import type { InputResponse } from "#runtime/input/types.js";+import type { JsonObject } from "#shared/json.js";+import { toChannelLocalContinuationToken } from "#shared/continuation-token.js";-/**- * Result of starting or delivering to a session. Exposes the session- * `id`, its channel-local `continuationToken`, and `getEventStream`, which- * resolves to a `ReadableStream` of the session's harness events- * (optionally from `startIndex`). Returned by {@link SendFn},- * {@link GetSessionFn}, and a channel's `receive` hook. Unlike the live- * {@link SessionHandle} on `ctx.session`, this is an inert result value:- * its fields are snapshots and it cannot mutate the continuation token.- */+/** Immutable-ID handle for one exact durable session. */export interface Session {readonly id: string;- readonly continuationToken: string;- /**- * Requests cancellation of this session's in-flight turn. `turnId` limits- * the request to the turn the caller observed. Both statuses are- * successful; confirmation is `turn.cancelled` followed by- * `session.waiting` on the event stream.- */+ /** Sends a message to this exact session ID without creating or following a replacement. */+ send(+ message: string | UserContent,+ options: SessionSendOptions,+ ): Promise<SessionSendCommandResult>;+ /** Answers pending input requests on this exact session ID. */+ respond(+ inputResponses: readonly InputResponse[],+ options: SessionRespondOptions,+ ): Promise<SessionSendCommandResult>;+ /** Requests cancellation of this exact session's active turn. */cancel(options?: { turnId?: string }): Promise<CancelTurnResult>;- /**- * Opens the durable event stream. Negative start indexes read relative to- * the current tail (`-1` starts at the latest event).- */+ /** Queues compaction on this exact session ID. */+ compact(): Promise<CompactSessionResult>;+ /** Queues a context clear on this exact session ID. */+ clear(): Promise<ClearSessionResult>;+ /** Terminally retires this exact session ID. */+ reset(options?: { reason?: string }): Promise<ResetSessionResult>;getEventStream(options?: { startIndex?: number }): Promise<ReadableStream<MessageStreamEvent>>;- /**- * Resolves the durable tail of the event stream: the zero-based index of- * the last recorded event, or `-1` before the first.- */getStreamTailIndex(): Promise<number>;}+interface SessionDeliveryOptions {+ readonly auth: SessionAuthContext | null;+ /** Public callback destination for a delegated continuation turn. */+ readonly callback?: SessionCallback;+ readonly context?: readonly string[];+ readonly outputSchema?: JsonObject;+}++/** Options for sending a message through a fixed session handle. */+export type SessionSendOptions = SessionDeliveryOptions;++/** Options for answering pending input requests through a fixed session handle. */+export type SessionRespondOptions = SessionDeliveryOptions;+/*** Live handle to the current session, exposed on `ctx.session` to* `deliver` and event handlers. The framework hydrates the read-only* fields from the active context at step start. A write through- * {@link SessionHandle.setContinuationToken} updates the context so the+ * `continuation.rekey()` updates the context so the* runtime can re-key the parked workflow hook at the next step boundary.*/export interface SessionHandle {readonly id: string;- readonly continuationToken: string;readonly auth: SessionAuth;- setContinuationToken(rawToken: string): void;+ readonly continuation?: {+ readonly token: string;+ rekey(rawToken: string): void;+ };}-export function createSession(id: string, continuationToken: string, runtime: Runtime): Session {+export function createSession(+ id: string,+ runtime: Runtime,+ metadata: { readonly requestId?: string } = {},+): Session {return {id,- continuationToken,+ async send(message, options) {+ const caller = sessionCallbackToTurnCaller(options.callback);+ const payload: {+ context?: readonly string[];+ message: string | UserContent | undefined;+ outputSchema?: JsonObject;+ } = { message: serializeUrlFilePartsInMessage(message) };+ if (options.context !== undefined) payload.context = options.context;+ if (options.outputSchema !== undefined) payload.outputSchema = options.outputSchema;+ const commandWithoutCaller = {+ auth: options.auth,+ kind: "send" as const,+ payload,+ requestId: metadata.requestId,+ };+ return await runtime.dispatchSession({+ command: caller === undefined ? commandWithoutCaller : { ...commandWithoutCaller, caller },+ sessionId: id,+ });+ },+ async respond(inputResponses, options) {+ if (inputResponses.length === 0) {+ throw new Error("respond() requires at least one input response.");+ }+ const caller = sessionCallbackToTurnCaller(options.callback);+ const payload: {+ context?: readonly string[];+ inputResponses: readonly InputResponse[];+ outputSchema?: JsonObject;+ } = { inputResponses };+ if (options.context !== undefined) payload.context = options.context;+ if (options.outputSchema !== undefined) payload.outputSchema = options.outputSchema;+ const commandWithoutCaller = {+ auth: options.auth,+ kind: "send" as const,+ payload,+ requestId: metadata.requestId,+ };+ return await runtime.dispatchSession({+ command: caller === undefined ? commandWithoutCaller : { ...commandWithoutCaller, caller },+ sessionId: id,+ });+ },async cancel(options?: { turnId?: string }) {- return runtime.dispatchSession({+ return await runtime.dispatchSession({command: { kind: "cancel", turnId: options?.turnId },sessionId: id,});},+ async compact() {+ return await runtime.dispatchSession({ command: { kind: "compact" }, sessionId: id });+ },+ async clear() {+ return await runtime.dispatchSession({ command: { kind: "clear" }, sessionId: id });+ },+ async reset(options) {+ return await runtime.dispatchSession({+ command: { kind: "reset", reason: options?.reason },+ sessionId: id,+ });+ },async getEventStream(options?: { startIndex?: number }) {return runtime.getEventStream(id, options);},@@ -68,8 +151,12 @@ export function createSession(id: string, continuationToken: string, runtime: Ru};}-export function createGetSessionFn(runtime: Runtime): (sessionId: string) => Session {- return (sessionId: string) => createSession(sessionId, "", runtime);+/** Builds an I/O-free factory for fixed session-ID handles. */+export function createAttachSessionFn(+ runtime: Runtime,+ metadata: { readonly requestId?: string } = {},+): (sessionId: string) => Session {+ return (sessionId) => createSession(sessionId, runtime, metadata);}/**@@ -87,25 +174,23 @@ export function buildSessionHandle(accessor: ContextAccessor): SessionHandle {get id() {return accessor.get(SessionIdKey) ?? "";},- get continuationToken() {- return accessor.get(ContinuationTokenKey) ?? "";- },get auth(): SessionAuth {return {current: accessor.get(AuthKey) ?? null,initiator: accessor.get(InitiatorAuthKey) ?? null,};},- setContinuationToken(rawToken: string): void {- const currentToken = accessor.get(ContinuationTokenKey) ?? "";- const token = namespaceContinuationToken(currentToken, rawToken);-- // Idempotent: a redundant write would push the workflow body- // through a hook dispose / recreate cycle for no reason. The- // call must remain cheap so channels can call it from- // hot-path event handlers without measuring first.- if (currentToken === token) return;- accessor.set(ContinuationTokenKey, token);+ get continuation() {+ const currentToken = accessor.get(ContinuationTokenKey);+ if (currentToken === undefined || currentToken.length === 0) return undefined;+ return {+ token: toChannelLocalContinuationToken(currentToken),+ rekey(rawToken: string): void {+ const token = namespaceContinuationToken(currentToken, rawToken);+ if (currentToken === token) return;+ accessor.set(ContinuationTokenKey, token);+ },+ };},};}@@ -120,3 +205,16 @@ function namespaceContinuationToken(currentToken: string, rawToken: string): str}return `${currentToken.slice(0, separatorIndex + 1)}${rawToken}`;}++/** @internal Converts validated public callback metadata into runtime turn routing. */+export function sessionCallbackToTurnCaller(+ callback: SessionCallback | undefined,+): TurnCaller | undefined {+ return callback === undefined+ ? undefined+ : {+ callId: callback.callId,+ replyTo: { kind: "callback", url: callback.url },+ subagentName: callback.subagentName,+ };+}diff --git a/packages/eve/src/channel/types.ts b/packages/eve/src/channel/types.tsindex 3b8abac3f..0488d044b 100644--- a/packages/eve/src/channel/types.ts+++ b/packages/eve/src/channel/types.ts@@ -1,7 +1,7 @@import type { UserContent } from "ai";import type { UnstampedMessageStreamEvent, MessageStreamEvent } from "#protocol/message.js";-import type { CancelTurnStatus } from "#protocol/cancel-turn.js";+import type { CancelTurnResult as ProtocolCancelTurnResult } from "#protocol/cancel-turn.js";import type { RunMode } from "#shared/run-mode.js";import type { RuntimeSubagentChildResult } from "#runtime/actions/types.js";import type { InputRequest, InputResponse } from "#runtime/input/types.js";@@ -27,48 +27,18 @@ export interface CancelTurnInput {}/** Result of requesting turn cancellation. Both statuses are successful. */-export interface CancelTurnResult {- readonly status: CancelTurnStatus;- /**- * For `no_active_turn`: the error class that classified the target as- * inactive, distinguishing "already finished" (`HookNotFoundError`) from a- * transiently unreachable cancel hook (`EntityConflictError`).- */- readonly reason?: string;-}--/** Identifies the continuation hook whose durable session should compact. */-export interface CompactSessionInput {- readonly continuationToken: string;-}+export type CancelTurnResult = ProtocolCancelTurnResult;/** Result of queueing manual context compaction for a session. */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. */- readonly reason?: string;- readonly sessionId: string;-}--/** Result of attempting to terminally retire a session. */-export type TerminateSessionResult =- | { readonly status: "terminated" }- | { readonly status: "already_terminal" };-// ---------------------------------------------------------------------------// Lineage// ---------------------------------------------------------------------------@@ -194,7 +164,8 @@ export type SessionSendCommandResult =| { readonly status: "accepted"; readonly sessionId: string }| { readonly status: "session_not_active" };-export type ResetSessionCommandResult =+/** Result of terminally resetting a session. */+export type ResetSessionResult =| { readonly status: "reset"; readonly previousSessionId: string }| { readonly status: "no_active_session" };@@ -207,7 +178,7 @@ export type SessionCommandResult<TCommand extends SessionCommand = SessionComman? CompactSessionResult: TCommand extends { readonly kind: "clear" }? ClearSessionResult- : ResetSessionCommandResult;+ : ResetSessionResult;export interface DispatchContinuationInput<TCommand extends SessionCommand = SessionCommand> {readonly command: TCommand;@@ -419,9 +390,10 @@ export interface RunInput {/*** Session continuation token for delivery and hook creation. Channels can* re-key the session during the first turn via- * `ctx.session.setContinuationToken(...)` (e.g. Slack adopts its first+ * `ctx.session.continuation.rekey(...)` (e.g. Slack adopts its first* post's `ts` as the thread root), so an initial placeholder token is- * acceptable when full identity isn't known until the first message.+ * acceptable when full identity isn't known until the first message. ID-only+ * transports omit this field.*/readonly continuationToken?: string;/**@@ -491,7 +463,6 @@ export type RunResult =* Carries the identifiers needed for stream endpoints.*/export interface RunHandle {- readonly continuationToken: string;readonly events: ReadableStream<MessageStreamEvent>;/*** Runtime-owned identifier for this session. Stream and inspection APIsdiff --git a/packages/eve/src/cli/commands/agent-prompt/build-and-verify.md b/packages/eve/src/cli/commands/agent-prompt/build-and-verify.mdindex 7b3e42984..5774051af 100644--- a/packages/eve/src/cli/commands/agent-prompt/build-and-verify.md+++ b/packages/eve/src/cli/commands/agent-prompt/build-and-verify.md@@ -28,8 +28,7 @@ terminal UI in a controllable background process instead:Wait for the server URL, then exercise the HTTP API: create a session with`POST /eve/v1/session`, attach to `GET /eve/v1/session/:id/stream`, and send a-follow-up with the returned `continuationToken`. Stop the dev process after-verification.+follow-up to `POST /eve/v1/session/:id`. Stop the dev process after verification.When the user is ready to use their agent's REPL, give them the interactivecommand to run from the project directory:diff --git a/packages/eve/src/cli/commands/channel-add-conflicts.ts b/packages/eve/src/cli/commands/channel-add-conflicts.tsindex dd6b6d53d..bb136cef4 100644--- a/packages/eve/src/cli/commands/channel-add-conflicts.ts+++ b/packages/eve/src/cli/commands/channel-add-conflicts.ts@@ -5,7 +5,7 @@ import type { DisabledChannelReasons } from "#setup/cli/index.js";import { compileChannelDefinition } from "#compiler/normalize-channel.js";import { discoverAgent } from "#discover/discover-agent.js";-import { EVE_CREATE_SESSION_ROUTE_PATH } from "#protocol/routes.js";+import { EVE_SESSION_ROUTE_PATH } from "#protocol/routes.js";const SCAFFOLDED_WEB_CHANNEL_LOGICAL_PATH = "channels/eve.ts";const SCAFFOLDED_SLACK_CHANNEL_LOGICAL_PATH = "channels/slack.ts";@@ -39,7 +39,7 @@ export async function inspectExistingChannelRegistrations(if (definition.kind !== "channel") {continue;}- if (definition.method === "POST" && definition.urlPath === EVE_CREATE_SESSION_ROUTE_PATH) {+ if (definition.method === "POST" && definition.urlPath === EVE_SESSION_ROUTE_PATH) {webRouteOwners.add(source.logicalPath);}if (definition.adapterKind === "slack") {@@ -52,7 +52,7 @@ export async function inspectExistingChannelRegistrations(if ([...webRouteOwners].some((logicalPath) => logicalPath !== SCAFFOLDED_WEB_CHANNEL_LOGICAL_PATH)) {- disabledChannelReasons.web = `POST ${EVE_CREATE_SESSION_ROUTE_PATH} already registered`;+ disabledChannelReasons.web = `POST ${EVE_SESSION_ROUTE_PATH} already registered`;}if (slackOwners.size > 0) {disabledChannelReasons.slack = "Slack channel already registered";@@ -79,7 +79,7 @@ export function assertCanAddSelectedChannels();if (conflictingOwner !== undefined) {throw new Error(- `Cannot scaffold Web Chat because agent/${conflictingOwner} already defines POST ${EVE_CREATE_SESSION_ROUTE_PATH}. Web Chat scaffolds the same eve session routes.`,+ `Cannot scaffold Web Chat because agent/${conflictingOwner} already defines POST ${EVE_SESSION_ROUTE_PATH}. Web Chat scaffolds the same eve session routes.`,);}}diff --git a/packages/eve/src/cli/commands/info.test.ts b/packages/eve/src/cli/commands/info.test.tsindex 58e642271..ee5848f5f 100644--- a/packages/eve/src/cli/commands/info.test.ts+++ b/packages/eve/src/cli/commands/info.test.ts@@ -19,8 +19,8 @@ vi.mock("#services/inspect-application.js", () => ({ inspectApplication: vi.fn()const MESSAGING = {createSessionRoutePath: "/eve/v1/session",- continueSessionRoutePattern: "/eve/v1/session/:id",- streamRoutePattern: "/eve/v1/session/:id/stream",+ sessionMessagesRoutePattern: "/eve/v1/session/:sessionId",+ streamRoutePattern: "/eve/v1/session/:sessionId/stream",};const APP_ROOT = "/virtual/app";@@ -201,7 +201,7 @@ describe("buildApplicationInfoJson", () => {expect(json.subagents).toEqual([]);expect(json.schedules).toEqual([]);expect(json.appRoot).toBe(APP_ROOT);- expect(json.messaging.stream).toBe("/eve/v1/session/:id/stream");+ expect(json.messaging.stream).toBe("/eve/v1/session/:sessionId/stream");});});diff --git a/packages/eve/src/cli/commands/info.ts b/packages/eve/src/cli/commands/info.tsindex f4241a9af..3bff489c9 100644--- a/packages/eve/src/cli/commands/info.ts+++ b/packages/eve/src/cli/commands/info.ts@@ -25,7 +25,7 @@ export interface ApplicationInfoJson {subagents: string[];schedules: string[];channels: { name: string; kind: string | null; method: string | null; urlPath: string | null }[];- messaging: { create: string; continue: string; stream: string };+ messaging: { create: string; messages: string; stream: string };artifacts: {compiledManifest: string;discoveryManifest: string;@@ -71,7 +71,7 @@ export function buildApplicationInfoJson(inspection: ApplicationInspection): App),messaging: {create: messaging.createSessionRoutePath,- continue: messaging.continueSessionRoutePattern,+ messages: messaging.sessionMessagesRoutePattern,stream: messaging.streamRoutePattern,},artifacts: compiledState@@ -273,9 +273,9 @@ export async function printApplicationInfo(value: `POST ${inspection.messaging.createSessionRoutePath}`,},{- label: "Continue",+ label: "Messages",tone: "info",- value: `POST ${inspection.messaging.continueSessionRoutePattern}`,+ value: `POST ${inspection.messaging.sessionMessagesRoutePattern}`,},{label: "Stream",diff --git a/packages/eve/src/cli/dev/tui/runner.test.ts b/packages/eve/src/cli/dev/tui/runner.test.tsindex 194b276b5..b5421bd5d 100644--- a/packages/eve/src/cli/dev/tui/runner.test.ts+++ b/packages/eve/src/cli/dev/tui/runner.test.ts@@ -53,7 +53,14 @@ function stubClient(): Client {/** Real `ClientSession` handle; harmless until `send`/`stream` are spied. */function stubSession(): ClientSession {- return stubClient().session();+ return stubClient().sessions.attach("session_test");+}++function mockSessionCreation(client: Client, session: ClientSession) {+ return vi.spyOn(client.sessions, "create").mockImplementation(async (input) => ({+ response: await session.send(input.message, input),+ session,+ }));}/**@@ -66,7 +73,6 @@ function messageResponseOf(events: readonly unknown[]): MessageResponse {isStamped(event) ? event : stampTestEvent(event as UnstampedMessageStreamEvent, index),);return new MessageResponse({- continuationToken: "eve:test",createStream: async function* () {for (const event of stamped) yield event;},@@ -523,17 +529,20 @@ describe("EveTUIRunner agent header", () => {function sessionYielding(events: readonly unknown[]): ClientSession {const session = stubSession();vi.spyOn(session, "send").mockImplementation(async () => messageResponseOf(events));+ vi.spyOn(session, "respond").mockImplementation(async () => messageResponseOf(events));return session;}function sessionYieldingTurns(turns: ReadonlyArray<readonly unknown[]>): ClientSession {const session = stubSession();let index = 0;- vi.spyOn(session, "send").mockImplementation(async () => {+ const nextResponse = async () => {const events = turns[index] ?? [];index += 1;return messageResponseOf(events);- });+ };+ vi.spyOn(session, "send").mockImplementation(nextResponse);+ vi.spyOn(session, "respond").mockImplementation(nextResponse);return session;}@@ -563,11 +572,8 @@ describe("EveTUIRunner development session continuity", () => {const sessionId =url.pathname === "/eve/v1/session"? `session-${String(++nextSession)}`- : (url.pathname.split("/").at(-1) ?? `session-${String(++nextSession)}`);- return Response.json({- continuationToken: `token-${sessionId}`,- sessionId,- });+ : (url.pathname.split("/")[4] ?? `session-${String(++nextSession)}`);+ return Response.json({ sessionId });}return new Response(@@ -578,10 +584,7 @@ describe("EveTUIRunner development session continuity", () => {`${JSON.stringify(stampTestEvent({type: "session.waiting",- data: {- continuationToken: "token-session-1",- wait: "next-user-message",- },+ data: { continuationToken: "session-id", wait: "next-user-message" },} as UnstampedMessageStreamEvent),)}\n`,),@@ -595,8 +598,8 @@ describe("EveTUIRunner development session continuity", () => {const client = stubClient();vi.spyOn(client, "info").mockResolvedValue(AGENT_INFO);- const session = client.session();- const createSession = vi.spyOn(client, "session");+ const session = client.sessions.attach("session-1");+ const createSession = vi.spyOn(client.sessions, "create");const prompts: Array<string | undefined> = ["first", "second", undefined];const runner = new EveTUIRunner({client,@@ -624,7 +627,7 @@ describe("EveTUIRunner development session continuity", () => {request.method === "POST" && request.url.pathname.startsWith("/eve/v1/session"),).map((request) => request.url.pathname),- ).toEqual(["/eve/v1/session", "/eve/v1/session/session-1"]);+ ).toEqual(["/eve/v1/session/session-1", "/eve/v1/session/session-1"]);});it("starts a fresh session only after an explicit /reset command", async () => {@@ -634,7 +637,7 @@ describe("EveTUIRunner development session continuity", () => {.mockResolvedValue({ previousSessionId: "session_1", status: "reset" });const newSession = sessionYielding([{ type: "session.waiting" }]);const client = stubClient();- const createSession = vi.spyOn(client, "session").mockReturnValue(newSession);+ const createSession = mockSessionCreation(client, newSession);const prompts: Array<string | undefined> = ["first", "/reset", "second", undefined];const runner = new EveTUIRunner({client,@@ -667,7 +670,7 @@ describe("EveTUIRunner development session continuity", () => {(async function* () {yield stampTestEvent({- data: { continuationToken: "eve:test", wait: "next-user-message" },+ data: { continuationToken: "session-id", wait: "next-user-message" },type: "session.waiting",},0,@@ -709,7 +712,7 @@ describe("EveTUIRunner development session continuity", () => {(async function* () {yield stampTestEvent({- data: { continuationToken: "eve:test", wait: "next-user-message" },+ data: { continuationToken: "session-id", wait: "next-user-message" },type: "session.waiting",},0,@@ -742,11 +745,7 @@ describe("EveTUIRunner development session continuity", () => {);it("cancels an active turn without sending a prompt", async () => {- const session = stubClient().session({- continuationToken: "eve:test",- sessionId: "session_1",- streamIndex: 0,- });+ const session = stubClient().sessions.attach("session_1");const cancel = vi.spyOn(session, "cancel").mockResolvedValue({ sessionId: "session_1", status: "accepted" });@@ -755,7 +754,7 @@ describe("EveTUIRunner development session continuity", () => {(async function* () {yield stampTestEvent({- data: { continuationToken: "eve:test", wait: "next-user-message" },+ data: { continuationToken: "session-id", wait: "next-user-message" },type: "session.waiting",},0,@@ -787,8 +786,6 @@ describe("EveTUIRunner development session continuity", () => {});it("does not call the cancel API before a session has started", async () => {- const session = stubSession();- const cancel = vi.spyOn(session, "cancel");const results: string[] = [];const prompts: Array<string | undefined> = ["/cancel", undefined];const runner = new EveTUIRunner({@@ -797,12 +794,10 @@ describe("EveTUIRunner development session continuity", () => {readPrompt: vi.fn(async () => prompts.shift()),renderCommandResult: (message) => results.push(message),}),- session,});await runner.run();- expect(cancel).not.toHaveBeenCalled();expect(results).toEqual(["No active turn to cancel."]);});@@ -836,7 +831,7 @@ describe("EveTUIRunner development session continuity", () => {.mockResolvedValue({ previousSessionId: "session_1", status: "reset" });const newSession = sessionYielding([]);const client = stubClient();- const createSession = vi.spyOn(client, "session").mockReturnValue(newSession);+ const createSession = mockSessionCreation(client, newSession);const prompts: Array<string | undefined> = ["first", undefined];const renderer = fakeRenderer({readPrompt: vi.fn(async () => prompts.shift()),@@ -857,7 +852,7 @@ describe("EveTUIRunner development session continuity", () => {await runner.run();expect(reset).toHaveBeenCalledOnce();- expect(createSession).toHaveBeenCalledOnce();+ expect(createSession).not.toHaveBeenCalled();expect(initialSession.send).toHaveBeenCalledOnce();expect(newSession.send).not.toHaveBeenCalled();});@@ -876,7 +871,7 @@ describe("EveTUIRunner terminal-failure recovery", () => {]);const recoveredSession = sessionYielding([]);const client = stubClient();- const sessionFactory = vi.spyOn(client, "session").mockImplementation(() => recoveredSession);+ const sessionFactory = mockSessionCreation(client, recoveredSession);const renderer: AgentTUIRenderer = {readPrompt: vi.fn(async () => prompts.shift()),@@ -901,7 +896,7 @@ describe("EveTUIRunner terminal-failure recovery", () => {// Exactly one recovery session was created, and the failed session was// only used for the one (failing) turn.- expect(sessionFactory).toHaveBeenCalledTimes(1);+ expect(sessionFactory).not.toHaveBeenCalled();expect(failingSession.send).toHaveBeenCalledTimes(1);expect(recoveredSession.send).not.toHaveBeenCalled();expect(notices).toHaveLength(1);@@ -914,7 +909,7 @@ describe("EveTUIRunner terminal-failure recovery", () => {const strandedSession = sessionYielding([{ type: "turn.started", data: {} }]);const client = stubClient();- const sessionFactory = vi.spyOn(client, "session");+ const sessionFactory = vi.spyOn(client.sessions, "create");const runner = new EveTUIRunner({client,@@ -946,7 +941,7 @@ describe("EveTUIRunner terminal-failure recovery", () => {const interruptedSession = sessionYielding([{ type: "turn.started", data: {} }]);const replacementSession = sessionYielding([]);const client = stubClient();- const sessionFactory = vi.spyOn(client, "session").mockReturnValue(replacementSession);+ const sessionFactory = mockSessionCreation(client, replacementSession);const runner = new EveTUIRunner({client,@@ -967,7 +962,7 @@ describe("EveTUIRunner terminal-failure recovery", () => {await runner.run();- expect(sessionFactory).toHaveBeenCalledTimes(1);+ expect(sessionFactory).not.toHaveBeenCalled();expect(notices).toHaveLength(1);expect(notices[0]).toContain("new session");expect(notices[0]).toContain("may still be running");@@ -1042,12 +1037,12 @@ describe("EveTUIRunner /traces", () => {expect(open).toHaveBeenCalledTimes(2);expect(open).toHaveBeenNthCalledWith(1, {appRoot: "/tmp/weather-agent",- sessionId: undefined,+ sessionId: "session_test",reference: "abc123",});expect(open).toHaveBeenNthCalledWith(2, {appRoot: "/tmp/weather-agent",- sessionId: undefined,+ sessionId: "session_test",reference: undefined,});});@@ -1107,8 +1102,7 @@ describe("EveTUIRunner initial input", () => {// The seed is a draft, not an auto-submit: the turn carries the text the// user actually sent, not the seeded value.expect(session.send).toHaveBeenCalledTimes(1);- expect(session.send).toHaveBeenNthCalledWith(1, {- message: "edited and sent",+ expect(session.send).toHaveBeenNthCalledWith(1, "edited and sent", {signal: expect.any(AbortSignal),});});@@ -1142,9 +1136,17 @@ describe("EveTUIRunner native continuation state", () => {],},},- { type: "session.waiting", data: { wait: "next-user-message" } },+ {+ type: "session.waiting",+ data: { continuationToken: "session-id", wait: "next-user-message" },+ },+ ],+ [+ {+ type: "session.waiting",+ data: { continuationToken: "session-id", wait: "next-user-message" },+ },],- [{ type: "session.waiting", data: { wait: "next-user-message" } }],]);const renderer: AgentTUIRenderer = {readPrompt: vi.fn(async () => prompts.shift()),@@ -1164,15 +1166,14 @@ describe("EveTUIRunner native continuation state", () => {await runner.run();- expect(session.send).toHaveBeenCalledTimes(2);- expect(session.send).toHaveBeenNthCalledWith(1, {- message: "approve this",- signal: expect.any(AbortSignal),- });- expect(session.send).toHaveBeenNthCalledWith(2, {- inputResponses: [{ requestId: "request-1", optionId: "approve" }],+ expect(session.send).toHaveBeenCalledTimes(1);+ expect(session.send).toHaveBeenNthCalledWith(1, "approve this", {signal: expect.any(AbortSignal),});+ expect(session.respond).toHaveBeenCalledWith(+ [{ requestId: "request-1", optionId: "approve" }],+ { signal: expect.any(AbortSignal) },+ );});it.each([{ chosenOptionId: "continue" }, { chosenOptionId: "stop" }])(@@ -1205,9 +1206,17 @@ describe("EveTUIRunner native continuation state", () => {],},},- { type: "session.waiting", data: { wait: "next-user-message" } },+ {+ type: "session.waiting",+ data: { continuationToken: "session-id", wait: "next-user-message" },+ },+ ],+ [+ {+ type: "session.waiting",+ data: { continuationToken: "session-id", wait: "next-user-message" },+ },],- [{ type: "session.waiting", data: { wait: "next-user-message" } }],]);const readToolApproval = vi.fn(async () => ({ approved: true }));const readInputQuestion = vi.fn(async () => ({ optionId: chosenOptionId }));@@ -1244,10 +1253,10 @@ describe("EveTUIRunner native continuation state", () => {}),expect.anything(),);- expect(session.send).toHaveBeenNthCalledWith(2, {- inputResponses: [{ requestId: "wrun_1:limit:input:19093", optionId: chosenOptionId }],- signal: expect.any(AbortSignal),- });+ expect(session.respond).toHaveBeenCalledWith(+ [{ requestId: "wrun_1:limit:input:19093", optionId: chosenOptionId }],+ { signal: expect.any(AbortSignal) },+ );},);});@@ -1276,7 +1285,7 @@ describe("EveTUIRunner connection authorization", () => {} as UnstampedMessageStreamEvent);yield stampTestEvent({type: "session.waiting",- data: { wait: "next-user-message" },+ data: { continuationToken: "session-id", wait: "next-user-message" },} as UnstampedMessageStreamEvent);});const renderer: AgentTUIRenderer = {@@ -1322,7 +1331,10 @@ describe("EveTUIRunner failure rendering", () => {{ type: "session.failed", data: { ...failureData, sessionId: "s0" } },]);const client = stubClient();- vi.spyOn(client, "session").mockImplementation(() => sessionYielding([]));+ vi.spyOn(client.sessions, "create").mockImplementation(async (input) => {+ const session = sessionYielding([]);+ return { response: await session.send(input.message, input), session };+ });const renderer: AgentTUIRenderer = {readPrompt: vi.fn(async () => prompts.shift()),@@ -1359,7 +1371,10 @@ describe("EveTUIRunner failure rendering", () => {turnId: "t0",},},- { type: "session.waiting", data: { wait: "next-user-message" } },+ {+ type: "session.waiting",+ data: { continuationToken: "session-id", wait: "next-user-message" },+ },]);const renderer: AgentTUIRenderer = {@@ -1437,7 +1452,10 @@ describe("EveTUIRunner reused step indexes", () => {},},{ type: "turn.completed", data: { sequence: 0, turnId: "t0" } },- { type: "session.waiting", data: { wait: "next-user-message" } },+ {+ type: "session.waiting",+ data: { continuationToken: "session-id", wait: "next-user-message" },+ },]);const renderer: AgentTUIRenderer = {@@ -1497,7 +1515,10 @@ describe("EveTUIRunner replay guards", () => {},{ type: "step.started", data: { sequence: 1, stepIndex: 0, turnId: "turn_0" } },appended,- { type: "session.waiting", data: { wait: "next-user-message" } },+ {+ type: "session.waiting",+ data: { continuationToken: "session-id", wait: "next-user-message" },+ },]);const renderer: AgentTUIRenderer = {readPrompt: vi.fn(async () => prompts.shift()),@@ -1668,7 +1689,10 @@ describe("EveTUIRunner replay guards", () => {turnId: "turn_0",},},- { type: "session.waiting", data: { wait: "next-user-message" } },+ {+ type: "session.waiting",+ data: { continuationToken: "session-id", wait: "next-user-message" },+ },]);const renderer: AgentTUIRenderer = {@@ -1724,7 +1748,10 @@ describe("EveTUIRunner replay guards", () => {turnId: "turn_0",},})),- { type: "session.waiting", data: { wait: "next-user-message" } },+ {+ type: "session.waiting",+ data: { continuationToken: "session-id", wait: "next-user-message" },+ },]);const renderer: AgentTUIRenderer = {@@ -1787,7 +1814,10 @@ describe("EveTUIRunner replay guards", () => {turnId: "turn_0",},},- { type: "session.waiting", data: { wait: "next-user-message" } },+ {+ type: "session.waiting",+ data: { continuationToken: "session-id", wait: "next-user-message" },+ },]);const renderer: AgentTUIRenderer = {@@ -1852,7 +1882,10 @@ describe("EveTUIRunner replay guards", () => {turnId: "turn_0",},},- { type: "session.waiting", data: { wait: "next-user-message" } },+ {+ type: "session.waiting",+ data: { continuationToken: "session-id", wait: "next-user-message" },+ },]);const renderer: AgentTUIRenderer = {readPrompt: vi.fn(async () => prompts.shift()),@@ -1994,7 +2027,7 @@ describe("EveTUIRunner remote authentication", () => {resolveDeployment?: NonNullable<RemoteConnectionControllerOptions["resolveDeployment"]>;}): Promise<void> {await new EveTUIRunner({- session: input.client.session(),+ session: input.client.sessions.attach("session_test"),client: input.client,renderer: fakeRenderer({ setupFlow: idleSetupFlow(), ...input.renderer }),serverUrl: target.serverUrl,@@ -2123,7 +2156,7 @@ describe("EveTUIRunner remote authentication", () => {it("demotes a ready remote after turn dispatch fails", async () => {const client = stubClient();vi.spyOn(client, "info").mockResolvedValue(AGENT_INFO);- const session = client.session();+ const session = client.sessions.attach("session_test");vi.spyOn(session, "send").mockRejectedValue(new Error("socket down"));const statuses: string[] = [];const readPrompt = vi.fn().mockResolvedValueOnce("hello").mockResolvedValueOnce(undefined);@@ -2244,8 +2277,8 @@ describe("EveTUIRunner renderer teardown", () => {it("finishes the section on the child's own turn boundary, before subagent.completed", async () => {const client = stubClient();- const childSession = client.session({ sessionId: "child-session", streamIndex: 0 });- vi.spyOn(client, "session").mockReturnValue(childSession);+ const childSession = client.sessions.attach("child-session");+ vi.spyOn(client.sessions, "attach").mockReturnValue(childSession);vi.spyOn(childSession, "stream").mockImplementation(() => ({async *[Symbol.asyncIterator]() {yield stampTestEvent(@@ -2264,7 +2297,7 @@ describe("EveTUIRunner renderer teardown", () => {yield stampTestEvent({type: "session.waiting",- data: { wait: "next-user-message" },+ data: { continuationToken: "session-id", wait: "next-user-message" },} as UnstampedMessageStreamEvent,1,);@@ -2318,7 +2351,10 @@ describe("EveTUIRunner renderer teardown", () => {// The parent stream never reports subagent.completed — the child's// own boundary must finish the section.{ type: "turn.completed", data: { sequence: 0, turnId: "turn-parent" } },- { type: "session.waiting", data: { wait: "next-user-message" } },+ {+ type: "session.waiting",+ data: { continuationToken: "session-id", wait: "next-user-message" },+ },]),});@@ -2330,9 +2366,9 @@ describe("EveTUIRunner renderer teardown", () => {it("aborts child-session streams when Ctrl-C exits the runner", async () => {const client = stubClient();- const childSession = client.session({ sessionId: "child-session", streamIndex: 0 });+ const childSession = client.sessions.attach("child-session");let childSignal: AbortSignal | undefined;- vi.spyOn(client, "session").mockReturnValue(childSession);+ vi.spyOn(client.sessions, "attach").mockReturnValue(childSession);vi.spyOn(childSession, "stream").mockImplementation((options) => {const signal = options?.signal;if (signal === undefined) {@@ -2347,7 +2383,7 @@ describe("EveTUIRunner renderer teardown", () => {yield stampTestEvent({type: "session.waiting",- data: { wait: "next-user-message" },+ data: { continuationToken: "session-id", wait: "next-user-message" },} as UnstampedMessageStreamEvent,1,);@@ -2382,7 +2418,10 @@ describe("EveTUIRunner renderer teardown", () => {},},{ type: "turn.completed", data: { sequence: 0, turnId: "turn-parent" } },- { type: "session.waiting", data: { wait: "next-user-message" } },+ {+ type: "session.waiting",+ data: { continuationToken: "session-id", wait: "next-user-message" },+ },]),});@@ -2543,7 +2582,10 @@ describe("EveTUIRunner gateway-auth failure rendering", () => {const emitted: AgentTUIStreamEvent[] = [];const session = sessionYielding([{ type: "step.failed", data: { ...gatewayFailure, sequence: 0, stepIndex: 0, turnId: "t0" } },- { type: "session.waiting", data: { wait: "next-user-message" } },+ {+ type: "session.waiting",+ data: { continuationToken: "session-id", wait: "next-user-message" },+ },]);const renderer: AgentTUIRenderer = {@@ -3047,11 +3089,8 @@ describe("EveTUIRunner mid-turn message queue", () => {await runner.run();expect(session.send).toHaveBeenCalledTimes(2);- expect(session.send).toHaveBeenNthCalledWith(1, expect.objectContaining({ message: "hello" }));- expect(session.send).toHaveBeenNthCalledWith(- 2,- expect.objectContaining({ message: "queued follow-up" }),- );+ expect(session.send).toHaveBeenNthCalledWith(1, "hello", expect.any(Object));+ expect(session.send).toHaveBeenNthCalledWith(2, "queued follow-up", expect.any(Object));// The drained prompt bypasses the interactive prompt read entirely.expect(renderer.readPrompt).toHaveBeenCalledTimes(2);});@@ -3084,7 +3123,6 @@ describe("EveTUIRunner mid-turn message queue", () => {vi.spyOn(session, "send").mockImplementation(async () =>new MessageResponse({- continuationToken: "eve:test",createStream: async function* () {yield stampTestEvent({@@ -3117,7 +3155,7 @@ describe("EveTUIRunner mid-turn message queue", () => {}// The first request raced the dispatch window: the turn workflow has// not claimed its cancel hook yet, so the server reports no turn.- return { sessionId: "session_test", status: "no_active_turn" as const };+ return { status: "no_active_turn" as const };});const prompts: Array<string | undefined> = ["hello", undefined];const seen: string[] = [];@@ -3208,7 +3246,6 @@ describe("EveTUIRunner session id reporting", () => {vi.spyOn(session, "send").mockImplementation(async () =>new MessageResponse({- continuationToken: "eve:test",createStream: async function* () {yield { type: "turn.started", data: { turnId: "turn-1", sequence: 1 } } as never;await gate.promise;@@ -3263,7 +3300,7 @@ describe("EveTUIRunner cancelled-turn subagent settling", () => {},});const client = stubClient();- vi.spyOn(client, "session").mockReturnValue({+ vi.spyOn(client.sessions, "attach").mockReturnValue({stream: (options?: { signal?: AbortSignal }) => childStream(options),} as never);diff --git a/packages/eve/src/cli/dev/tui/runner.ts b/packages/eve/src/cli/dev/tui/runner.tsindex 15861d772..862da7ed0 100644--- a/packages/eve/src/cli/dev/tui/runner.ts+++ b/packages/eve/src/cli/dev/tui/runner.ts@@ -390,7 +390,7 @@ export interface PromptCommandHandler {}export type EveTUIRunnerOptions = TuiDisplayOptions & {- session: ClientSession;+ session?: ClientSession;/** Production TUI probe injected by the launcher; omitted in hermetic runners. */probeMcpConnection?: McpConnectionProbe;/**@@ -460,7 +460,7 @@ function authIssueForStatus(status: VercelAuthStatus): SetupIssue | undefined {}export class EveTUIRunner {- #session: ClientSession;+ #session: ClientSession | undefined;readonly #client?: Client;readonly #renderer: AgentTUIRenderer;readonly #name: string;@@ -790,7 +790,7 @@ export class EveTUIRunner {}if (command?.type === "cancel") {- if (this.#session.state.sessionId === undefined) {+ if (this.#session === undefined) {this.#renderCommandOutcome("No active turn to cancel.");pendingInputResponses = undefined;followCurrentSession = false;@@ -840,6 +840,14 @@ export class EveTUIRunner {}if (command?.type === "compact") {+ if (this.#session === undefined) {+ this.#renderCommandOutcome("No active session to compact.");+ pendingInputResponses = undefined;+ followCurrentSession = false;+ streamWithoutPrompt = false;+ prompt = undefined;+ continue;+ }try {const result = await this.#session.compact();this.#renderCommandOutcome(@@ -869,6 +877,14 @@ export class EveTUIRunner {}if (command?.type === "clear") {+ if (this.#session === undefined) {+ this.#renderCommandOutcome("No active session to clear.");+ pendingInputResponses = undefined;+ followCurrentSession = false;+ streamWithoutPrompt = false;+ prompt = undefined;+ continue;+ }try {const result = await this.#session.clear();this.#renderCommandOutcome(@@ -951,7 +967,7 @@ export class EveTUIRunner {});// The session id becomes known once the send is accepted; keep the// renderer's copy fresh so the parting line can name the session.- const acceptedSessionId = this.#session.state.sessionId;+ const acceptedSessionId = this.#session?.state.sessionId;if (acceptedSessionId !== undefined) {this.#renderer.setSessionId?.(acceptedSessionId);}@@ -1042,7 +1058,7 @@ export class EveTUIRunner {if (result.turnState.aborted) {this.#sessionFailed = true;} else {- const strandedSessionId = this.#session.state.sessionId;+ const strandedSessionId = this.#session?.state.sessionId;this.#renderer.renderNotice?.(strandedSessionId? `Lost the event stream — the turn may still be running on the server (session ${strandedSessionId}). Your next message resumes this session; use /cancel to stop the turn.`@@ -1119,14 +1135,17 @@ export class EveTUIRunner {this.#pendingConnectionAuths.clear();this.#renderer.setConnectionAuthPendingCount?.(0);- if (this.#client) {- this.#session = this.#client.session();- }+ this.#session = undefined;this.#runtimeArtifacts?.clear();}/** Resets the durable owner before clearing the local conversation view. */async #resetCurrentSession(): Promise<boolean> {+ if (this.#session === undefined) {+ this.#startNewSession();+ this.#renderer.reset?.();+ return true;+ }try {await this.#session.reset();} catch (error) {@@ -1228,7 +1247,25 @@ export class EveTUIRunner {this.#renderer.flushDelayedDevBuildErrors?.();}- response = await this.#session.send(sendInput);+ if (this.#session === undefined) {+ if (this.#client === undefined) {+ throw new Error("Cannot create a session without an eve client.");+ }+ if (sendInput.message === undefined) {+ throw new Error("Cannot answer an input request before the session starts.");+ }+ const created = await this.#client.sessions.create({+ ...sendInput,+ message: sendInput.message,+ });+ this.#session = created.session;+ response = created.response;+ } else {+ response =+ sendInput.inputResponses === undefined+ ? await this.#session.send(sendInput.message!, { signal: sendInput.signal })+ : await this.#session.respond(sendInput.inputResponses, { signal: sendInput.signal });+ }} catch (error) {if (isInterruptedError(error)) throw error;// Dispatching the turn failed before any stream opened (transport@@ -1277,10 +1314,10 @@ export class EveTUIRunner {if (turnState.boundaryEvent !== undefined || turnState.aborted === true) return;const turnId = turnState.turnId;try {- const result = await this.#session.cancel(turnId === undefined ? undefined : { turnId });+ const result = await this.#session?.cancel(turnId === undefined ? undefined : { turnId });// Accepted means the turn's cancellation hook consumed the// request; the turn settles at its next safe boundary.- if (result.status === "accepted") return;+ if (result?.status === "accepted") return;} catch {// No accepted session yet or a transport failure — retry below;// lifecycle interruption remains the hard client-side escape hatch.@@ -1294,6 +1331,9 @@ export class EveTUIRunner {/** Follows the current session without dispatching another turn. */#streamCurrentSession(): AgentTUIStreamResult {+ if (this.#session === undefined) {+ throw new Error("Cannot stream a session before its first turn is accepted.");+ }const abortController = new AbortController();return this.#createTUIStreamResult(this.#session.stream({ signal: abortController.signal }),@@ -1577,7 +1617,7 @@ export class EveTUIRunner {try {await this.#renderer.traceViewer.open({appRoot: this.#appRoot,- sessionId: this.#session.state.sessionId,+ sessionId: this.#session?.state.sessionId,reference: argument === "" ? undefined : argument,});} catch (error) {diff --git a/packages/eve/src/cli/dev/tui/setup-issues.integration.test.ts b/packages/eve/src/cli/dev/tui/setup-issues.integration.test.tsindex c5cbc85c3..fbd59cf30 100644--- a/packages/eve/src/cli/dev/tui/setup-issues.integration.test.ts+++ b/packages/eve/src/cli/dev/tui/setup-issues.integration.test.ts@@ -123,7 +123,7 @@ describe("BOOT_DETECTIONS against a real directory", () => {promptCommandHandler: { handle },renderer,serverUrl: "http://localhost:3000",- session: client.session(),+ session: client.sessions.attach("session_test"),initialInput: "/model",});diff --git a/packages/eve/src/cli/dev/tui/subagent-pump.test.ts b/packages/eve/src/cli/dev/tui/subagent-pump.test.tsindex 169551f09..ae369ceb9 100644--- a/packages/eve/src/cli/dev/tui/subagent-pump.test.ts+++ b/packages/eve/src/cli/dev/tui/subagent-pump.test.ts@@ -91,7 +91,10 @@ function reasoningEvent(delta: string, index = 0): MessageStreamEvent {function boundaryEvent(index: number): MessageStreamEvent {return stampTestEvent(- { type: "session.waiting", data: { wait: "next-user-message" } } as UnstampedMessageStreamEvent,+ {+ type: "session.waiting",+ data: { continuationToken: "session-id", wait: "next-user-message" },+ } as UnstampedMessageStreamEvent,index,);}@@ -104,7 +107,7 @@ describe("SubagentPump.settleAll", () => {it("closes live sections and stops stale child output after a cancelled turn", async () => {const child = pushableChildStream();const client = new Client({ host: "http://localhost:3000" });- vi.spyOn(client, "session").mockReturnValue({+ vi.spyOn(client.sessions, "attach").mockReturnValue({stream: (options?: { signal?: AbortSignal }) => child.stream(options),} as never);const view = fakeView();@@ -142,7 +145,7 @@ describe("SubagentPump child stream replay", () => {const transcript = [reasoningEvent("looked up the forecast", 0), boundaryEvent(1)];let opened = 0;const client = new Client({ host: "http://localhost:3000" });- vi.spyOn(client, "session").mockReturnValue({+ vi.spyOn(client.sessions, "attach").mockReturnValue({stream: () => {opened += 1;return {diff --git a/packages/eve/src/cli/dev/tui/subagent-pump.ts b/packages/eve/src/cli/dev/tui/subagent-pump.tsindex 20a54dce0..38e2fc73e 100644--- a/packages/eve/src/cli/dev/tui/subagent-pump.ts+++ b/packages/eve/src/cli/dev/tui/subagent-pump.ts@@ -227,10 +227,7 @@ export class SubagentPump {void (async () => {let boundaryReached = false;try {- const childSession = client.session({- sessionId: called.data.childSessionId,- streamIndex: 0,- });+ const childSession = client.sessions.attach(called.data.childSessionId);const stream = childSession.stream({ signal: controller.signal });for await (const event of stream) {if (controller.signal.aborted) break;diff --git a/packages/eve/src/cli/dev/tui/tui.test.ts b/packages/eve/src/cli/dev/tui/tui.test.tsindex 59904c180..ded6898e9 100644--- a/packages/eve/src/cli/dev/tui/tui.test.ts+++ b/packages/eve/src/cli/dev/tui/tui.test.ts@@ -24,7 +24,7 @@ describe("runDevelopmentTui", () => {mocks.runnerOptions.length = 0;});- it("creates a fresh client session for every TUI attached to the same server", async () => {+ it("creates a fresh client and defers session creation until the first prompt", async () => {const target = {kind: "local",serverUrl: "http://127.0.0.1:4321/",@@ -39,7 +39,8 @@ describe("runDevelopmentTui", () => {throw new Error("Expected two TUI runner invocations.");}expect(first.client).not.toBe(second.client);- expect(first.session).not.toBe(second.session);+ expect(first.session).toBeUndefined();+ expect(second.session).toBeUndefined();});it.each([diff --git a/packages/eve/src/cli/dev/tui/tui.ts b/packages/eve/src/cli/dev/tui/tui.tsindex b68db93bc..29e69a480 100644--- a/packages/eve/src/cli/dev/tui/tui.ts+++ b/packages/eve/src/cli/dev/tui/tui.ts@@ -113,7 +113,6 @@ export async function runDevelopmentTui(input: RunDevelopmentTuiInput): Promise<const options: EveTUIRunnerOptions = {...display,- session: client.session(),client,serverUrl,promptCommandHandler: createPromptCommandHandler({ target }),diff --git a/packages/eve/src/cli/invoke/invoke.test.ts b/packages/eve/src/cli/invoke/invoke.test.tsindex ea98c5811..7b12c3568 100644--- a/packages/eve/src/cli/invoke/invoke.test.ts+++ b/packages/eve/src/cli/invoke/invoke.test.ts@@ -4,7 +4,6 @@ import { resolveInvokeOperation, runInvoke, type RunInvokeInput } from "./invokeimport { parseInvokeResumeInput } from "./result.js";const cursor = {- continuationToken: "eve:test",sessionId: "ses_1",streamIndex: 3,};@@ -51,9 +50,7 @@ describe("parseInvokeResumeInput", () => {describe("runInvoke", () => {it("preserves an accepted session when its stream later rejects authorization", async () => {vi.spyOn(globalThis, "fetch")- .mockResolvedValueOnce(- Response.json({ continuationToken: "eve:test", sessionId: "ses_1" }, { status: 202 }),- )+ .mockResolvedValueOnce(Response.json({ sessionId: "ses_1" }, { status: 202 })).mockResolvedValueOnce(Response.json({@@ -82,7 +79,7 @@ describe("runInvoke", () => {{ type: "input.requested", data: { requests: [request] } },{type: "session.waiting",- data: { continuationToken: "eve:rekeyed", wait: "next-user-message" },+ data: { continuationToken: "session-id", wait: "next-user-message" },},]);@@ -96,7 +93,7 @@ describe("runInvoke", () => {},],resume: {- session: { continuationToken: "eve:rekeyed", sessionId: "ses_1", streamIndex: 2 },+ session: { sessionId: "ses_1", streamIndex: 2 },},});if (result.status !== "input-required") throw new Error("Expected input-required result.");@@ -113,14 +110,14 @@ describe("runInvoke", () => {},{type: "session.waiting",- data: { continuationToken: "eve:retry", wait: "next-user-message" },+ data: { continuationToken: "session-id", wait: "next-user-message" },},]),).resolves.toMatchObject({status: "ready",outcome: { status: "failed", message: "Model unavailable" },resume: {- session: { continuationToken: "eve:retry", sessionId: "ses_1", streamIndex: 2 },+ session: { sessionId: "ses_1", streamIndex: 2 },},});});@@ -135,7 +132,7 @@ describe("runInvoke", () => {},{type: "session.waiting",- data: { continuationToken: "eve:authorized", wait: "next-user-message" },+ data: { continuationToken: "session-id", wait: "next-user-message" },},],{@@ -146,7 +143,7 @@ describe("runInvoke", () => {).resolves.toMatchObject({status: "authorization-required",authorizations: [{ name: "linear" }],- resume: { session: { continuationToken: "eve:authorized", streamIndex: 2 } },+ resume: { session: { sessionId: "ses_1", streamIndex: 2 } },});});@@ -164,7 +161,7 @@ describe("runInvoke", () => {},{type: "session.waiting",- data: { continuationToken: "eve:authorized", wait: "next-user-message" },+ data: { continuationToken: "session-id", wait: "next-user-message" },},],{@@ -191,7 +188,7 @@ describe("runInvoke", () => {},{type: "session.waiting",- data: { continuationToken: "eve:authorized", wait: "next-user-message" },+ data: { continuationToken: "session-id", wait: "next-user-message" },},]),).resolves.toEqual({@@ -211,7 +208,7 @@ describe("runInvoke", () => {},{type: "session.waiting",- data: { continuationToken: "eve:next", wait: "next-user-message" },+ data: { continuationToken: "session-id", wait: "next-user-message" },},]),);@@ -304,9 +301,7 @@ async function runStreamedInvocation(overrides: Partial<RunInvokeInput> = {},): Promise<Awaited<ReturnType<typeof runInvoke>>> {vi.spyOn(globalThis, "fetch")- .mockResolvedValueOnce(- Response.json({ continuationToken: "eve:test", sessionId: "ses_1" }, { status: 202 }),- )+ .mockResolvedValueOnce(Response.json({ sessionId: "ses_1" }, { status: 202 })).mockResolvedValueOnce(streamResponse(events));return runInvoke({operation: { kind: "send", payload: { message: "do foo" } },diff --git a/packages/eve/src/cli/invoke/invoke.ts b/packages/eve/src/cli/invoke/invoke.tsindex b784275ce..1b2341f28 100644--- a/packages/eve/src/cli/invoke/invoke.ts+++ b/packages/eve/src/cli/invoke/invoke.ts@@ -3,9 +3,9 @@ import {ClientError,type ClientSession,type MessageStreamEvent,- type SendTurnPayload,- type SessionState,+ type ClientSessionState,} from "#client/index.js";+import type { SendTurnPayload } from "#client/types.js";import { collectTurnEvents, summarizeTurnEvents } from "#client/session-utils.js";import { resolveLocalDevelopmentClientOptions } from "#services/dev-client/client-options.js";import { resolveLinkedDevelopmentOidcToken } from "#services/dev-client/request-headers.js";@@ -41,9 +41,11 @@ export interface RunInvokeInput {export async function runInvoke(input: RunInvokeInput): Promise<InvokeResult> {const { client, deploymentResolution } = await createInvokeClient(input);const resume = input.operation.resume;- const session = client.session(resume?.session);if (input.operation.kind === "follow") {+ const session = client.sessions.attach(resume!.session.sessionId, {+ streamIndex: resume!.session.streamIndex,+ });return observeSafely(input,session,@@ -53,8 +55,26 @@ export async function runInvoke(input: RunInvokeInput): Promise<InvokeResult> {}let response: Awaited<ReturnType<ClientSession["send"]>>;+ let session: ClientSession;try {- response = await session.send({ ...input.operation.payload, signal: input.signal });+ const payload = { ...input.operation.payload, signal: input.signal };+ if (resume === undefined) {+ if (payload.message === undefined) {+ throw new Error("Cannot answer an input request before the session starts.");+ }+ const created = await client.sessions.create({ ...payload, message: payload.message });+ session = created.session;+ response = created.response;+ } else {+ session = client.sessions.attach(resume.session.sessionId, {+ streamIndex: resume.session.streamIndex,+ });+ const { inputResponses, message, ...options } = payload;+ response =+ inputResponses === undefined+ ? await session.send(message!, options)+ : await session.respond(inputResponses, options);+ }} catch (error) {const authentication = authenticationFailure(error, undefined, deploymentResolution);if (authentication !== undefined) return authentication;@@ -115,7 +135,6 @@ async function createInvokeClient(input: RunInvokeInput): Promise<{serverUrl: input.target.serverUrl,token: () => resolveLinkedDevelopmentOidcToken(input.target.workspaceRoot),}),- preserveCompletedSessions: true,}),};}@@ -128,7 +147,7 @@ async function createInvokeClient(input: RunInvokeInput): Promise<{workspaceRoot: input.target.workspaceRoot,});return {- client: new Client({ ...options, preserveCompletedSessions: true }),+ client: new Client(options),deploymentResolution,};}@@ -202,22 +221,13 @@ async function observeInvocation(return { status: "ready", outcome, resume };}-function runningResult(target: DevelopmentTarget, state: SessionState): InvokeResult {+function runningResult(target: DevelopmentTarget, state: ClientSessionState): InvokeResult {return { status: "running", resume: createResume(target, state) };}-function createResume(target: DevelopmentTarget, session: SessionState): InvokeResume {- if (session.sessionId === undefined) throw new Error("Invocation has no resumable session ID.");- const cursor =- session.continuationToken === undefined- ? { sessionId: session.sessionId, streamIndex: session.streamIndex }- : {- continuationToken: session.continuationToken,- sessionId: session.sessionId,- streamIndex: session.streamIndex,- };+function createResume(target: DevelopmentTarget, session: ClientSessionState): InvokeResume {return {- session: cursor,+ session,target:target.kind === "local" ? { kind: "local" } : { kind: "remote", serverUrl: target.serverUrl },};diff --git a/packages/eve/src/cli/invoke/result.ts b/packages/eve/src/cli/invoke/result.tsindex 623998d31..fbce831cd 100644--- a/packages/eve/src/cli/invoke/result.ts+++ b/packages/eve/src/cli/invoke/result.ts@@ -4,7 +4,6 @@ import type { ConnectionAuthorizationChallenge } from "#public/connections/errorconst sessionCursorSchema = z.object({- continuationToken: z.string().optional(),sessionId: z.string().min(1),streamIndex: z.number().int().nonnegative(),})diff --git a/packages/eve/src/client/client-error.test.ts b/packages/eve/src/client/client-error.test.tsindex 86d8632fc..2356acbb3 100644--- a/packages/eve/src/client/client-error.test.ts+++ b/packages/eve/src/client/client-error.test.ts@@ -14,6 +14,7 @@ describe("ClientError", () => {);expect(error.message).toBe("Production auth is not configured.");+ expect(error.code).toBe("eve_production_auth_not_configured");expect(error.status).toBe(401);});diff --git a/packages/eve/src/client/client-error.ts b/packages/eve/src/client/client-error.tsindex fb438d3d7..363309c59 100644--- a/packages/eve/src/client/client-error.ts+++ b/packages/eve/src/client/client-error.ts@@ -4,6 +4,8 @@ import { isObject } from "#shared/guards.js";* Error thrown when the eve server returns a non-successful HTTP response.*/export class ClientError extends Error {+ /** Stable eve error code when the response body provides one. */+ readonly code: string | undefined;/*** HTTP status code returned by the server.*/@@ -21,15 +23,18 @@ export class ClientError extends Error {constructor(status: number, body: string, headers?: ConstructorParameters<typeof Headers>[0]) {let message = body || `Server returned ${status}.`;+ let code: string | undefined;try {const parsed: unknown = JSON.parse(body);- if (isObject(parsed) && typeof parsed.error === "string") {- message = parsed.error;+ if (isObject(parsed)) {+ if (typeof parsed.error === "string") message = parsed.error;+ if (typeof parsed.code === "string") code = parsed.code;}} catch {}super(message);this.name = "ClientError";+ this.code = code;this.status = status;this.body = body;this.headers = Object.freeze(Object.fromEntries(new Headers(headers).entries()));diff --git a/packages/eve/src/client/client.test.ts b/packages/eve/src/client/client.test.tsindex edb75edaa..227d95371 100644--- a/packages/eve/src/client/client.test.ts+++ b/packages/eve/src/client/client.test.ts@@ -53,7 +53,7 @@ describe("Client request policy", () => {.mockResolvedValueOnce(Response.json({ ok: true, status: "ready", workflowId: "wf" })).mockResolvedValueOnce(new Response(null, { status: 204 })).mockResolvedValueOnce(- Response.json({ continuationToken: "eve:test", sessionId: "session_1" }, { status: 202 }),+ Response.json({ sessionId: "session_1", status: "accepted" }, { status: 202 }),).mockResolvedValueOnce(new Response(`${JSON.stringify({ data: {}, type: "session.completed" })}\n`),@@ -65,7 +65,7 @@ describe("Client request policy", () => {await client.info();await client.health();await client.fetch("/custom");- await (await client.session().send("hello")).result();+ await (await client.sessions.create({ message: "hello" })).response.result();expect(fetchMock.mock.calls).toHaveLength(5);for (const [request] of fetchMock.mock.calls) {@@ -82,7 +82,7 @@ describe("Client request policy", () => {.mockResolvedValueOnce(Response.json({ ok: true, status: "ready", workflowId: "wf" })).mockResolvedValueOnce(new Response(null, { status: 204 })).mockResolvedValueOnce(- Response.json({ continuationToken: "eve:test", sessionId: "session_1" }, { status: 202 }),+ Response.json({ sessionId: "session_1", status: "accepted" }, { status: 202 }),).mockResolvedValueOnce(new Response(`${JSON.stringify({ data: {}, type: "session.completed" })}\n`),@@ -92,7 +92,7 @@ describe("Client request policy", () => {await client.info();await client.health();await client.fetch("/custom", { redirect: "follow" });- await (await client.session().send("hello")).result();+ await (await client.sessions.create({ message: "hello" })).response.result();expect(fetchMock.mock.calls).toHaveLength(5);for (const [, init] of fetchMock.mock.calls) {@@ -120,7 +120,7 @@ describe("Client request policy", () => {const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValueOnce(- Response.json({ continuationToken: "eve:test", sessionId: "session_1" }, { status: 202 }),+ Response.json({ sessionId: "session_1", status: "accepted" }, { status: 202 }),).mockResolvedValueOnce(new Response(`${JSON.stringify({ data: {}, type: "session.completed" })}\n`),@@ -131,11 +131,11 @@ describe("Client request policy", () => {});await (- await client.session().send({+ await client.sessions.create({headers: { authorization: "Bearer application-user" },message: "hello",})- ).result();+ ).response.result();expect(fetchMock.mock.calls).toHaveLength(2);for (const [, init] of fetchMock.mock.calls) {diff --git a/packages/eve/src/client/client.ts b/packages/eve/src/client/client.tsindex a6ad00696..ae178dc35 100644--- a/packages/eve/src/client/client.ts+++ b/packages/eve/src/client/client.ts@@ -3,8 +3,7 @@ import { AgentInfoResponseError } from "#client/agent-info-error.js";import { encodeBasicCredentials } from "#internal/http/basic-auth.js";import { AgentInfoResultSchema } from "#client/agent-info-schema.js";import { ClientError } from "#client/client-error.js";-import { ClientSession } from "#client/session.js";-import { createInitialSessionState } from "#client/session-utils.js";+import { ClientSessions } from "#client/sessions.js";import { createClientUrl } from "#client/url.js";import type {AgentInfoResult,@@ -13,7 +12,6 @@ import type {ClientRedirectPolicy,HeadersValue,HealthResult,- SessionState,TokenValue,} from "#client/types.js";import { VERCEL_TRUSTED_OIDC_IDP_TOKEN_HEADER } from "#client/types.js";@@ -21,23 +19,28 @@ import { VERCEL_TRUSTED_OIDC_IDP_TOKEN_HEADER } from "#client/types.js";/*** HTTP client for talking to a deployed eve agent.*- * A single client is bound to one host and auth configuration. It can create- * many concurrent {@link ClientSession | sessions}, each tracking their own- * conversation state independently.+ * A single client is bound to one host and auth configuration. Its+ * `sessions` collection can create or attach many independent fixed session+ * handles.*/export class Client {readonly #auth: ClientAuth | undefined;readonly #headers: HeadersValue | undefined;readonly #host: string;- readonly #preserveCompletedSessions: boolean;readonly #redirect: ClientRedirectPolicy | undefined;+ /** Explicit create/attach surface for ID-addressed sessions. */+ readonly sessions: ClientSessions;constructor(options: ClientOptions) {this.#host = options.host;this.#auth = options.auth;this.#headers = options.headers;- this.#preserveCompletedSessions = options.preserveCompletedSessions ?? false;this.#redirect = options.redirect;+ this.sessions = new ClientSessions({+ host: this.#host,+ redirect: this.#redirect,+ resolveHeaders: (perRequest) => this.#resolveHeaders(perRequest),+ });}/**@@ -112,36 +115,6 @@ export class Client {return await fetch(url, withRedirectPolicy({ ...init, headers }, this.#redirect));}- /**- * Creates a {@link ClientSession} handle for one conversation.- *- * - **No arguments**: starts a fresh conversation. The first- * `session.send()` call creates the run on the server.- * - **{@link SessionState}**: resumes a previously serialized session.- * - **string**: shorthand for resuming with a continuation token alone.- */- session(state?: SessionState | string): ClientSession {- let resolved: SessionState;-- if (typeof state === "string") {- resolved = { continuationToken: state, streamIndex: 0 };- } else if (state) {- resolved = state;- } else {- resolved = createInitialSessionState();- }-- return new ClientSession(- {- host: this.#host,- preserveCompletedSessions: this.#preserveCompletedSessions,- redirect: this.#redirect,- resolveHeaders: (perRequest) => this.#resolveHeaders(perRequest),- },- resolved,- );- }-// ---------------------------------------------------------------------------// Internal// ---------------------------------------------------------------------------diff --git a/packages/eve/src/client/eve-agent-store.test.ts b/packages/eve/src/client/eve-agent-store.test.tsindex 60d5fd711..6487389b3 100644--- a/packages/eve/src/client/eve-agent-store.test.ts+++ b/packages/eve/src/client/eve-agent-store.test.ts@@ -22,18 +22,15 @@ function turnEvents(): MessageStreamEvent[] {stepIndex: 0,turnId: "turn_1",}),- createSessionWaitingEvent("http:session_1"),+ createSessionWaitingEvent(),] as UnstampedMessageStreamEvent[]);}function startedResponse(): Response {- return new Response(- JSON.stringify({ continuationToken: "http:session_1", ok: true, sessionId: "session_1" }),- {- headers: { "content-type": "application/json", [EVE_SESSION_ID_HEADER]: "session_1" },- status: 202,- },- );+ return new Response(JSON.stringify({ ok: true, sessionId: "session_1", status: "accepted" }), {+ headers: { "content-type": "application/json", [EVE_SESSION_ID_HEADER]: "session_1" },+ status: 202,+ });}function streamResponse(events: readonly MessageStreamEvent[]): Response {@@ -69,6 +66,33 @@ afterEach(() => {});describe("EveAgentStore stream overlap", () => {+ it("rejects a prepared turn containing both a message and input responses", async () => {+ const fetchMock = vi.spyOn(globalThis, "fetch");+ const store = new EveAgentStore({ reducer: defaultMessageReducer() });+ store.setCallbacks({+ prepareSend: () =>+ ({+ inputResponses: [{ optionId: "approve", requestId: "request_1" }],+ message: "also send this",+ }) as never,+ });+ const invalidSend = () => {+ // @ts-expect-error message and inputResponses are mutually exclusive.+ void store.send({+ inputResponses: [{ optionId: "approve", requestId: "request_1" }],+ message: "also send this",+ });+ };+ expect(invalidSend).toBeTypeOf("function");++ await store.send({ message: "hello" });++ expect(store.snapshot.error?.message).toBe(+ "A turn requires exactly one of message or inputResponses.",+ );+ expect(fetchMock).not.toHaveBeenCalled();+ });+it("folds an initialEvents prefix that the live stream re-delivers in once", async () => {const events = turnEvents();vi.spyOn(globalThis, "fetch")@@ -104,7 +128,7 @@ describe("EveAgentStore stream overlap", () => {it("applies a pre-v20 event whose envelope has no id", async () => {const legacy = preV20MessageCompletedEvent();- const boundary = stampTestEvents([createSessionWaitingEvent("http:session_1")])[0]!;+ const boundary = stampTestEvents([createSessionWaitingEvent()])[0]!;vi.spyOn(globalThis, "fetch").mockResolvedValueOnce(startedResponse()).mockResolvedValueOnce(streamResponse([legacy, boundary]));diff --git a/packages/eve/src/client/eve-agent-store.ts b/packages/eve/src/client/eve-agent-store.tsindex 9e3e30b86..afaba6bcb 100644--- a/packages/eve/src/client/eve-agent-store.ts+++ b/packages/eve/src/client/eve-agent-store.ts@@ -4,7 +4,12 @@ import type { ClientSession } from "#client/session.js";import { createEventDeduper } from "#protocol/event-dedupe.js";import type { MessageStreamEvent } from "#protocol/message.js";import { toError } from "#shared/errors.js";-import type { ClientAuth, HeadersValue, SendTurnPayload, SessionState } from "#client/types.js";+import type {+ ClientAuth,+ HeadersValue,+ SendTurnPayload,+ ClientSessionState,+} from "#client/types.js";import type { UserContent } from "ai";/**@@ -32,7 +37,7 @@ export interface EveAgentStoreSnapshot<TData> {readonly data: TData;readonly error: Error | undefined;readonly events: readonly MessageStreamEvent[];- readonly session: SessionState;+ readonly session: ClientSessionState | undefined;readonly status: EveAgentStoreStatus;}@@ -47,7 +52,7 @@ export interface EveAgentStoreCallbacks<TData> {readonly onError?: (error: Error) => void;readonly onEvent?: (event: MessageStreamEvent) => void;readonly onFinish?: (snapshot: EveAgentStoreSnapshot<TData>) => void;- readonly onSessionChange?: (session: SessionState) => void;+ readonly onSessionChange?: (session: ClientSessionState | undefined) => void;readonly prepareSend?: PrepareSend;}@@ -71,7 +76,7 @@ export interface EveAgentStoreInit<TData> {readonly host?: string;/** Ordered prefix of the session stream used to rehydrate projected state. */readonly initialEvents?: readonly MessageStreamEvent[];- readonly initialSession?: SessionState;+ readonly initialSession?: ClientSessionState;readonly optimistic?: boolean;readonly reducer: EveAgentReducer<TData>;readonly session?: ClientSession;@@ -96,7 +101,8 @@ interface PendingMessageSubmission {* abort the in-flight turn with `stop`, and discard all state with `reset`.*/export class EveAgentStore<TData> {- readonly #createSession: (() => ClientSession) | undefined;+ readonly #client: Client | undefined;+ readonly #externalSession: boolean;readonly #optimistic: boolean;readonly #reducer: EveAgentReducer<TData>;readonly #subscribers = new Set<() => void>();@@ -112,19 +118,19 @@ export class EveAgentStore<TData> {#operationId = 0;#pendingMessageSubmission: PendingMessageSubmission | undefined;#projectionEvents: readonly EveAgentReducerEvent[];- #session: ClientSession;+ #session: ClientSession | undefined;#snapshot: EveAgentStoreSnapshot<TData>;#status: EveAgentStoreStatus = "ready";constructor(init: EveAgentStoreInit<TData>) {- this.#createSession = init.session+ this.#externalSession = init.session !== undefined;+ this.#client = this.#externalSession? undefined- : () =>- new Client({- auth: init.auth,- headers: init.headers,- host: init.host ?? "",- }).session(init.initialSession);+ : new Client({+ auth: init.auth,+ headers: init.headers,+ host: init.host ?? "",+ });// Seed the deduper from the saved log so a live stream that replays the// same prefix does not double-apply it.const initialEvents: MessageStreamEvent[] = [];@@ -135,7 +141,13 @@ export class EveAgentStore<TData> {this.#projectionEvents = [...this.#events];this.#optimistic = init.optimistic ?? true;this.#reducer = init.reducer;- this.#session = init.session ?? this.#createOwnedSession();+ this.#session =+ init.session ??+ (init.initialSession === undefined+ ? undefined+ : this.#client?.sessions.attach(init.initialSession.sessionId, {+ streamIndex: init.initialSession.streamIndex,+ }));this.#data = this.#reduceProjectionEvents(this.#projectionEvents);this.#snapshot = this.#createSnapshot();@@ -170,6 +182,7 @@ export class EveAgentStore<TData> {try {const preparedInput = (await this.#callbacks.prepareSend?.(input)) ?? input;+ assertExclusiveTurnInput(preparedInput);if (!this.#isCurrentOperation(operationId)) {return;@@ -179,10 +192,11 @@ export class EveAgentStore<TData> {this.#projectInputResponses(preparedInput);this.#publish();- const response = await this.#session.send({+ const turnInput = {...preparedInput,signal: createAbortSignal(preparedInput.signal, abortController.signal),- });+ };+ const response = await this.#dispatchTurn(turnInput);let sawEvent = false;for await (const event of response) {@@ -228,7 +242,7 @@ export class EveAgentStore<TData> {} finally {if (this.#isCurrentOperation(operationId)) {this.#abortController = undefined;- this.#callbacks.onSessionChange?.(this.#session.state);+ this.#callbacks.onSessionChange?.(this.#session?.state);this.#publish();this.#callbacks.onFinish?.(this.#snapshot);}@@ -243,7 +257,7 @@ export class EveAgentStore<TData> {this.#invalidateOperation();this.stop();this.#abortController = undefined;- this.#session = this.#createSession?.() ?? this.#session;+ if (!this.#externalSession) this.#session = undefined;this.#events = [];this.#seenEvents = createEventDeduper();this.#pendingMessageSubmission = undefined;@@ -251,15 +265,36 @@ export class EveAgentStore<TData> {this.#data = this.#reducer.initial();this.#error = undefined;this.#status = "ready";- this.#callbacks.onSessionChange?.(this.#session.state);+ this.#callbacks.onSessionChange?.(this.#session?.state);this.#publish();}- #createOwnedSession(): ClientSession {- if (!this.#createSession) {- throw new Error("Cannot create an owned eve session from an external session.");+ async #createFirstTurn<TOutput>(+ input: SendTurnPayload<TOutput>,+ ): Promise<Awaited<ReturnType<ClientSession["send"]>>> {+ if (this.#client === undefined) {+ throw new Error("An external eve session is required before sending.");}- return this.#createSession();+ if (input.message === undefined) {+ throw new Error("Cannot answer an input request before the session starts.");+ }+ const created = await this.#client.sessions.create({ ...input, message: input.message });+ this.#session = created.session;+ this.#callbacks.onSessionChange?.(created.session.state);+ this.#publish();+ return created.response;+ }++ async #dispatchTurn<TOutput>(+ input: SendTurnPayload<TOutput>,+ ): Promise<Awaited<ReturnType<ClientSession["send"]>>> {+ if (this.#session === undefined) return await this.#createFirstTurn(input);+ if (input.inputResponses === undefined) {+ const { message, ...options } = input;+ return await this.#session.send(message, options);+ }+ const { inputResponses, ...options } = input;+ return await this.#session.respond(inputResponses, options);}#startOperation(): number {@@ -404,7 +439,7 @@ export class EveAgentStore<TData> {data: this.#data,error: this.#error,events: this.#events,- session: this.#session.state,+ session: this.#session?.state,status: this.#status,};}@@ -417,6 +452,14 @@ export class EveAgentStore<TData> {}}+function assertExclusiveTurnInput(input: SendTurnPayload): void {+ const hasMessage = input.message !== undefined;+ const hasResponses = input.inputResponses !== undefined;+ if (hasMessage === hasResponses) {+ throw new Error("A turn requires exactly one of message or inputResponses.");+ }+}+let submissionSequence = 0;function createSubmissionId(): string {diff --git a/packages/eve/src/client/index.ts b/packages/eve/src/client/index.tsindex 9b3fa995d..8ac0815fa 100644--- a/packages/eve/src/client/index.ts+++ b/packages/eve/src/client/index.ts@@ -10,6 +10,7 @@ export { defaultMessageReducer } from "#client/message-reducer.js";export { createDataUrlFilePart, createTextWithFileContent } from "#client/file-parts.js";export { MessageResponse } from "#client/message-response.js";export { ClientSession } from "#client/session.js";+export { ClientSessions, type CreatedClientSession } from "#client/sessions.js";// ---------------------------------------------------------------------------// Client types@@ -51,12 +52,13 @@ export type {HeadersValue,HealthResult,MessageResult,+ RespondTurnOptions,ResetResult,ResolvedStreamReconnectPolicy,SendTurnInput,- SendTurnPayload,+ SendTurnOptions,SessionSnapshot,- SessionState,+ ClientSessionState,StreamOptions,StreamReconnectPolicy,StreamReconnectRetryPolicy,diff --git a/packages/eve/src/client/message-response.ts b/packages/eve/src/client/message-response.tsindex f8c68392c..3b22bbf0f 100644--- a/packages/eve/src/client/message-response.ts+++ b/packages/eve/src/client/message-response.ts@@ -7,7 +7,6 @@ import type { MessageResult } from "#client/types.js";* Internal configuration passed to construct a {@link MessageResponse}.*/interface MessageResponseInput {- readonly continuationToken?: string;readonly createStream: () => AsyncGenerator<MessageStreamEvent>;readonly sessionId: string;}@@ -15,16 +14,11 @@ interface MessageResponseInput {/*** The response from {@link ClientSession.send}.*- * Like `fetch()`, the response exposes metadata (session ID, continuation- * token) as soon as the POST completes. Collect the event stream via+ * Like `fetch()`, the response exposes its session ID as soon as the POST+ * completes. Collect the event stream via* {@link result} or iterate it with `for await...of`.*/export class MessageResponse<TOutput = unknown> implements AsyncIterable<MessageStreamEvent> {- /**- * Continuation token returned by the server for follow-up messages.- */- readonly continuationToken: string | undefined;-/*** Session ID assigned by the server.*/@@ -35,7 +29,6 @@ export class MessageResponse<TOutput = unknown> implements AsyncIterable<Message/** @internal */constructor(input: MessageResponseInput) {- this.continuationToken = input.continuationToken;this.sessionId = input.sessionId;this.#createStream = input.createStream;}diff --git a/packages/eve/src/client/open-stream.ts b/packages/eve/src/client/open-stream.tsindex 19ccaaa0b..b0d8007d5 100644--- a/packages/eve/src/client/open-stream.ts+++ b/packages/eve/src/client/open-stream.ts@@ -1,6 +1,6 @@import type { MessageStreamEvent } from "#protocol/message.js";import { EVE_STREAM_TAIL_INDEX_HEADER } from "#protocol/message.js";-import { createEveMessageStreamRoutePath } from "#protocol/routes.js";+import { createEveSessionStreamRoutePath } from "#protocol/routes.js";import { ClientError } from "#client/client-error.js";import { isStreamDisconnectError, readNdjsonStream } from "#client/ndjson.js";import type {@@ -226,7 +226,7 @@ export async function openStreamBody(for (let attempt = 0; attempt < openRetryPolicy.maxAttempts; attempt += 1) {const url = createClientUrl(input.host,- createEveMessageStreamRoutePath(input.sessionId),+ createEveSessionStreamRoutePath(input.sessionId),Object.keys(searchParams).length > 0 ? searchParams : undefined,);diff --git a/packages/eve/src/client/session-controls.ts b/packages/eve/src/client/session-controls.tsnew file mode 100644index 000000000..4fe4f6b2d--- /dev/null+++ b/packages/eve/src/client/session-controls.ts@@ -0,0 +1,145 @@+import { ClientError } from "#client/client-error.js";+import type {+ CancelSessionResult,+ ClearResult,+ ClientRedirectPolicy,+ CompactResult,+ ResetResult,+} from "#client/types.js";+import { createClientUrl } from "#client/url.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 {+ createEveSessionCancelRoutePath,+ createEveSessionClearRoutePath,+ createEveSessionCompactRoutePath,+ createEveSessionResetRoutePath,+} from "#protocol/routes.js";++interface SessionControlContext {+ readonly host: string;+ readonly redirect?: ClientRedirectPolicy;+ resolveHeaders(): Promise<Headers>;+}++export async function cancelClientSession(input: {+ readonly context: SessionControlContext;+ readonly options?: { readonly turnId?: string };+ readonly sessionId: string;+}): Promise<CancelSessionResult> {+ const { payload, response } = await postJson({+ body: input.options,+ context: input.context,+ operation: "Cancel",+ path: createEveSessionCancelRoutePath(input.sessionId),+ });+ const result = CancelTurnResponseSchema.safeParse(payload);+ if (+ !result.success ||+ (result.data.status === "accepted" && result.data.sessionId !== input.sessionId)+ ) {+ throw new Error(`Cancel route returned an invalid response (${response.status}).`);+ }+ return result.data.status === "accepted"+ ? { sessionId: result.data.sessionId, status: "accepted" }+ : { status: "no_active_turn" };+}++export async function clearClientSession(input: {+ readonly context: SessionControlContext;+ readonly sessionId: string;+}): Promise<ClearResult> {+ const { payload } = await postJson({+ context: input.context,+ operation: "Clear",+ path: createEveSessionClearRoutePath(input.sessionId),+ });+ const result = ClearResponseSchema.safeParse(payload);+ if (+ !result.success ||+ (result.data.status === "accepted" && result.data.sessionId !== input.sessionId)+ ) {+ throw new Error("Clear route returned an invalid response.");+ }+ return result.data.status === "accepted"+ ? { sessionId: result.data.sessionId, status: "accepted" }+ : { status: "no_active_session" };+}++export async function compactClientSession(input: {+ readonly context: SessionControlContext;+ readonly sessionId: string;+}): Promise<CompactResult> {+ const { payload } = await postJson({+ context: input.context,+ operation: "Compact",+ path: createEveSessionCompactRoutePath(input.sessionId),+ });+ const result = CompactResponseSchema.safeParse(payload);+ if (+ !result.success ||+ (result.data.status === "accepted" && result.data.sessionId !== input.sessionId)+ ) {+ throw new Error("Compact route returned an invalid response.");+ }+ return result.data.status === "accepted"+ ? { sessionId: result.data.sessionId, status: "accepted" }+ : { status: "no_active_session" };+}++export async function resetClientSession(input: {+ readonly context: SessionControlContext;+ readonly options?: { readonly reason?: string };+ readonly sessionId: string;+}): Promise<ResetResult> {+ const { payload } = await postJson({+ body: input.options,+ context: input.context,+ operation: "Reset",+ path: createEveSessionResetRoutePath(input.sessionId),+ });+ const result = ResetResponseSchema.safeParse(payload);+ if (+ !result.success ||+ (result.data.status === "reset" && result.data.previousSessionId !== input.sessionId)+ ) {+ throw new Error("Reset route returned an invalid response.");+ }+ return result.data.status === "reset"+ ? { previousSessionId: result.data.previousSessionId, status: "reset" }+ : { status: "no_active_session" };+}++async function postJson(input: {+ readonly body?: object;+ readonly context: SessionControlContext;+ readonly operation: string;+ readonly path: string;+}): Promise<{ readonly payload: unknown; readonly response: Response }> {+ const headers = await input.context.resolveHeaders();+ headers.set("content-type", "application/json");+ const response = await fetch(+ createClientUrl(input.context.host, input.path),+ withRedirectPolicy(+ {+ body: input.body === undefined ? undefined : JSON.stringify(input.body),+ headers,+ method: "POST",+ },+ input.context.redirect,+ ),+ );+ const text = await response.text();+ if (!response.ok) throw new ClientError(response.status, text, response.headers);+ try {+ return { payload: JSON.parse(text) as unknown, response };+ } catch {+ throw new Error(`${input.operation} route returned invalid JSON (${response.status}).`);+ }+}++function withRedirectPolicy(init: RequestInit, redirect?: ClientRedirectPolicy): RequestInit {+ return redirect === undefined ? init : { ...init, redirect };+}diff --git a/packages/eve/src/client/session-utils.test.ts b/packages/eve/src/client/session-utils.test.tsindex e39a253e4..99b00dfe4 100644--- a/packages/eve/src/client/session-utils.test.ts+++ b/packages/eve/src/client/session-utils.test.ts@@ -34,7 +34,7 @@ describe("summarizeTurnEvents", () => {},{type: "session.waiting",- data: { continuationToken: "eve:next", wait: "next-user-message" },+ data: { continuationToken: "session-id", wait: "next-user-message" },},] satisfies UnstampedMessageStreamEvent[];@@ -65,7 +65,7 @@ describe("summarizeTurnEvents", () => {},{type: "session.waiting",- data: { continuationToken: "eve:next", wait: "next-user-message" },+ data: { continuationToken: "session-id", wait: "next-user-message" },},] satisfies UnstampedMessageStreamEvent[];@@ -82,7 +82,7 @@ describe("collectTurnEvents", () => {async function* stream(): AsyncGenerator<UnstampedMessageStreamEvent> {yield {type: "session.waiting",- data: { continuationToken: "eve:next", wait: "next-user-message" },+ data: { continuationToken: "session-id", wait: "next-user-message" },};yield { type: "session.completed" };}@@ -90,7 +90,7 @@ describe("collectTurnEvents", () => {await expect(collectTurnEvents(stream())).resolves.toEqual([{type: "session.waiting",- data: { continuationToken: "eve:next", wait: "next-user-message" },+ data: { continuationToken: "session-id", wait: "next-user-message" },},]);});diff --git a/packages/eve/src/client/session-utils.ts b/packages/eve/src/client/session-utils.tsindex 708a36d6f..7878003e6 100644--- a/packages/eve/src/client/session-utils.ts+++ b/packages/eve/src/client/session-utils.ts@@ -5,59 +5,8 @@ import type {UnstampedMessageStreamEvent,} from "#protocol/message.js";import { isCurrentTurnBoundaryEvent, isTurnFailureEvent } from "#protocol/message.js";-import type { SessionState } from "#client/types.js";import type { InputRequest } from "#runtime/input/types.js";-/**- * Returns a fresh session state with no active run.- */-export function createInitialSessionState(): SessionState {- return { streamIndex: 0 };-}--/**- * Advances the session cursor after one streamed turn completes.- *- * When the boundary event is `session.waiting`, the session is preserved for- * the next message. For `session.completed` and `session.failed`, the session- * resets so the next call starts a new conversation. Without a boundary, the- * session stays resumable from its advanced cursor.- */-export function advanceSession(input: {- readonly continuationToken?: string;- readonly events: readonly UnstampedMessageStreamEvent[];- readonly preserveCompletedSessions?: boolean;- readonly sessionId: string;- readonly session: SessionState;-}): SessionState {- const boundaryEvent = findBoundaryEvent(input.events);- const streamIndex = input.session.streamIndex + input.events.length;-- if (- boundaryEvent?.type === "session.waiting" ||- (input.preserveCompletedSessions === true && boundaryEvent?.type === "session.completed")- ) {- return {- continuationToken:- boundaryEvent?.type === "session.waiting"- ? boundaryEvent.data.continuationToken- : (input.continuationToken ?? input.session.continuationToken),- sessionId: input.sessionId,- streamIndex,- };- }-- if (boundaryEvent === undefined) {- return {- continuationToken: input.continuationToken ?? input.session.continuationToken,- sessionId: input.sessionId,- streamIndex,- };- }-- return createInitialSessionState();-}-/** A connection authorization challenge that remains unresolved at a turn boundary. */export interface PendingAuthorization {readonly authorization?: AuthorizationRequiredStreamEvent["data"]["authorization"];@@ -126,16 +75,6 @@ export async function collectTurnEvents(return events;}-function findBoundaryEvent(- events: readonly UnstampedMessageStreamEvent[],-): UnstampedMessageStreamEvent | undefined {- for (let i = events.length - 1; i >= 0; i--) {- const event = events[i];- if (event !== undefined && isCurrentTurnBoundaryEvent(event)) return event;- }- return undefined;-}-function isFinalMessageCompleted(event: UnstampedMessageStreamEvent,): event is MessageCompletedStreamEvent {diff --git a/packages/eve/src/client/session.test.ts b/packages/eve/src/client/session.test.tsindex 425a47f10..c0818ca50 100644--- a/packages/eve/src/client/session.test.ts+++ b/packages/eve/src/client/session.test.ts@@ -1,23 +1,22 @@import { afterEach, describe, expect, it, vi } from "vitest";+import { ClientError } from "#client/client-error.js";import { ClientSession } from "#client/session.js";-import type { SessionState } from "#client/types.js";+import type { ClientSessionState } from "#client/types.js";afterEach(() => {vi.restoreAllMocks();});function createSession(- state: SessionState = { streamIndex: 0 },+ state: ClientSessionState = { sessionId: "session_1", streamIndex: 0 },options: {- readonly preserveCompletedSessions?: boolean;readonly redirect?: "error" | "follow" | "manual";readonly resolveHeaders?: () => Promise<Headers>;} = {},) {const context: ConstructorParameters<typeof ClientSession>[0] = {host: "https://eve.test",- preserveCompletedSessions: options.preserveCompletedSessions ?? false,redirect: options.redirect,resolveHeaders: options.resolveHeaders ?? (async () => new Headers()),};@@ -50,7 +49,6 @@ async function collectEventTypes(events: AsyncIterable<{ type: string }>): Promifunction createAcceptedResponse() {return Response.json({- continuationToken: "eve:test",ok: true,sessionId: "session_1",},@@ -99,7 +97,7 @@ describe("ClientSession", () => {return createAcceptedResponse();});const session = createSession(- { streamIndex: 0 },+ { sessionId: "session_1", streamIndex: 0 },{redirect: "error",resolveHeaders: async () => {@@ -121,10 +119,6 @@ describe("ClientSession", () => {expect(requests[1]!.headers.get("authorization")).toBe("Bearer token-2");});- it("rejects cancellation before a session has started", async () => {- await expect(createSession().cancel()).rejects.toThrow("Session has no session ID");- });-it("snapshots the session from the start through one pinned durable tail", async () => {const requests: string[] = [];vi.spyOn(globalThis, "fetch").mockImplementation(async (request, init) => {@@ -136,13 +130,12 @@ describe("ClientSession", () => {{ type: "turn.started", data: { turnId: "turn_1" } },{type: "session.waiting",- data: { continuationToken: "eve:current", wait: "next-user-message" },+ data: { continuationToken: "session-id", wait: "next-user-message" },},];return createBoundedStreamResponse(events);});const initialState = {- continuationToken: "eve:stale",sessionId: "session_1",streamIndex: 9,};@@ -155,7 +148,6 @@ describe("ClientSession", () => {expect(requestUrl.searchParams.get("includeTailIndex")).toBe("1");expect(snapshot.events.map((event) => event.type)).toEqual(["turn.started", "session.waiting"]);expect(snapshot.session).toEqual({- continuationToken: "eve:current",sessionId: "session_1",streamIndex: 2,});@@ -190,7 +182,6 @@ describe("ClientSession", () => {]),);const initialState = {- continuationToken: "eve:stale",sessionId: "session_1",streamIndex: 4,};@@ -202,12 +193,11 @@ describe("ClientSession", () => {expect(session.state).toBe(initialState);});- it("omits the continuation token while the snapshotted turn is active", async () => {+ it("snapshots an active turn without changing the fixed handle", async () => {vi.spyOn(globalThis, "fetch").mockResolvedValue(createBoundedStreamResponse([{ type: "turn.started", data: { turnId: "turn_1" } }]),);const initialState = {- continuationToken: "eve:previous",sessionId: "session_1",streamIndex: 4,};@@ -222,7 +212,6 @@ describe("ClientSession", () => {it("preserves an empty session without mutating its handle", async () => {vi.spyOn(globalThis, "fetch").mockResolvedValue(createBoundedStreamResponse([]));const initialState = {- continuationToken: "eve:pending",sessionId: "session_1",streamIndex: 0,};@@ -245,7 +234,6 @@ describe("ClientSession", () => {return createBoundedStreamResponse([]);});const initialState = {- continuationToken: "eve:current",sessionId: "session_1",streamIndex: 3,};@@ -257,46 +245,43 @@ describe("ClientSession", () => {expect(session.state).toBe(initialState);});- it("preserves completed-session continuation when configured", async () => {+ it("rejects a cancel response for a different session", async () => {vi.spyOn(globalThis, "fetch").mockResolvedValue(- createBoundedStreamResponse([- {- type: "session.completed",- data: { reason: "completed" },- },- ]),+ Response.json(+ { ok: true, sessionId: "another-session", status: "accepted" },+ { status: 202 },+ ),);- const initialState = {- continuationToken: "eve:current",- sessionId: "session_1",- streamIndex: 3,- };- const session = createSession(initialState, { preserveCompletedSessions: true });-- const snapshot = await session.snapshot();+ const session = createSession({ sessionId: "session_1", streamIndex: 0 });- expect(snapshot.session).toEqual({- continuationToken: "eve:current",- sessionId: "session_1",- streamIndex: 1,- });- expect(session.state).toBe(initialState);+ await expect(session.cancel()).rejects.toThrow("Cancel route returned an invalid response");});- it("rejects a cancel response for a different session", async () => {+ it("exposes a typed session_not_active conflict", async () => {vi.spyOn(globalThis, "fetch").mockResolvedValue(Response.json(- { ok: true, sessionId: "another-session", status: "accepted" },- { status: 202 },+ {+ code: "session_not_active",+ error: "The session is no longer active.",+ ok: false,+ },+ { status: 409 },),);const session = createSession({ sessionId: "session_1", streamIndex: 0 });- await expect(session.cancel()).rejects.toThrow("Cancel route returned an invalid response");+ const error = await session.send("too late").catch((cause: unknown) => cause);++ expect(error).toBeInstanceOf(ClientError);+ expect(error).toMatchObject({+ code: "session_not_active",+ message: "The session is no longer active.",+ status: 409,+ });});it("queues a context clear without clearing the local session cursor", async () => {- const state = { continuationToken: "eve:test", sessionId: "session_1", streamIndex: 4 };+ const state = { sessionId: "session_1", streamIndex: 4 };const requests: Array<{ body?: string; method: string; url: string }> = [];vi.spyOn(globalThis, "fetch").mockImplementation(async (request, init) => {const url =@@ -319,20 +304,13 @@ describe("ClientSession", () => {});expect(session.state).toEqual(state);- expect(new URL(requests[0]!.url).pathname).toBe("/eve/v1/session/clear");+ expect(new URL(requests[0]!.url).pathname).toBe("/eve/v1/session/session_1/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();+ expect(JSON.parse(requests[0]!.body ?? "{}")).toEqual({});});it("queues compaction without clearing the local session cursor", async () => {- const state = { continuationToken: "eve:test", sessionId: "session_1", streamIndex: 4 };+ const state = { sessionId: "session_1", streamIndex: 4 };const requests: Array<{ body?: string; method: string; url: string }> = [];vi.spyOn(globalThis, "fetch").mockImplementation(async (request, init) => {const url =@@ -355,19 +333,12 @@ describe("ClientSession", () => {});expect(session.state).toEqual(state);- expect(new URL(requests[0]!.url).pathname).toBe("/eve/v1/session/compact");+ expect(new URL(requests[0]!.url).pathname).toBe("/eve/v1/session/session_1/compact");expect(requests[0]!.method).toBe("POST");- expect(JSON.parse(requests[0]!.body ?? "{}")).toEqual({ continuationToken: "eve:test" });+ expect(JSON.parse(requests[0]!.body ?? "{}")).toEqual({});});- it("treats compacting a never-started session as a successful no-op", async () => {- const fetchMock = vi.spyOn(globalThis, "fetch");-- await expect(createSession().compact()).resolves.toEqual({ status: "no_active_session" });- expect(fetchMock).not.toHaveBeenCalled();- });-- it("resets the continuation owner and clears the local session state", async () => {+ it("resets the exact session while keeping the handle pinned to its ID", async () => {let headerResolution = 0;const requests: Array<{ headers: Headers; method: string; url: string; body?: string }> = [];vi.spyOn(globalThis, "fetch").mockImplementation(async (request, init) => {@@ -386,7 +357,7 @@ describe("ClientSession", () => {});});const session = createSession(- { continuationToken: "eve:test", sessionId: "session_1", streamIndex: 4 },+ { sessionId: "session_1", streamIndex: 4 },{redirect: "error",resolveHeaders: async () => {@@ -401,29 +372,12 @@ describe("ClientSession", () => {status: "reset",});- expect(session.state).toEqual({ streamIndex: 0 });+ expect(session.state).toEqual({ sessionId: "session_1", streamIndex: 4 });expect(requests).toHaveLength(1);- expect(new URL(requests[0]!.url).pathname).toBe("/eve/v1/session/reset");+ expect(new URL(requests[0]!.url).pathname).toBe("/eve/v1/session/session_1/reset");expect(requests[0]!.method).toBe("POST");expect(requests[0]!.headers.get("authorization")).toBe("Bearer token-1");- expect(JSON.parse(requests[0]!.body ?? "{}")).toEqual({ continuationToken: "eve:test" });- });-- it("treats a never-started session as already reset", async () => {- const fetchMock = vi.spyOn(globalThis, "fetch");- const session = createSession();-- await expect(session.reset()).resolves.toEqual({ status: "no_active_session" });-- expect(fetchMock).not.toHaveBeenCalled();- expect(session.state).toEqual({ streamIndex: 0 });- });-- it("refuses to discard a session that has no continuation token", async () => {- const session = createSession({ sessionId: "session_1", streamIndex: 4 });-- await expect(session.reset()).rejects.toThrow("Consume its event stream before resetting");- expect(session.state).toEqual({ sessionId: "session_1", streamIndex: 4 });+ expect(JSON.parse(requests[0]!.body ?? "{}")).toEqual({});});it("preserves the local session when the reset response names another owner", async () => {@@ -434,21 +388,18 @@ describe("ClientSession", () => {status: "reset",}),);- const state = { continuationToken: "eve:test", sessionId: "session_1", streamIndex: 4 };+ const state = { sessionId: "session_1", streamIndex: 4 };const session = createSession(state);await expect(session.reset()).rejects.toThrow("Reset route returned an invalid response");expect(session.state).toEqual(state);});- it("serializes clientContext when sending a create-session message", async () => {+ it("serializes clientContext with a fixed-session message", async () => {const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValueOnce(createAcceptedResponse());const session = createSession();- await session.send({- clientContext: { selectedWord: "jazz" },- message: "What word is selected?",- });+ await session.send("What word is selected?", { clientContext: { selectedWord: "jazz" } });expect(fetchMock).toHaveBeenCalledTimes(1);const init = fetchMock.mock.calls[0]?.[1] as RequestInit;@@ -461,38 +412,32 @@ describe("ClientSession", () => {it("serializes clientContext when continuing a session", async () => {const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValueOnce(createAcceptedResponse());const session = createSession({- continuationToken: "eve:test",sessionId: "session_1",streamIndex: 0,});- await session.send({+ await session.respond([{ requestId: "approval_1", optionId: "approve" }], {clientContext: "approve button visible",- inputResponses: [{ requestId: "approval_1", optionId: "approve" }],});expect(fetchMock).toHaveBeenCalledTimes(1);const init = fetchMock.mock.calls[0]?.[1] as RequestInit;expect(JSON.parse(String(init.body))).toEqual({clientContext: "approve button visible",- continuationToken: "eve:test",inputResponses: [{ requestId: "approval_1", optionId: "approve" }],});});- it("rejects clientContext-only sends", async () => {+ it("rejects empty input responses", async () => {const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValueOnce(createAcceptedResponse());const session = createSession({- continuationToken: "eve:test",sessionId: "session_1",streamIndex: 0,});- await expect(- session.send({- clientContext: { selectedWord: "jazz" },- }),- ).rejects.toThrow("Session.send requires a non-empty message, inputResponses, or both.");+ await expect(session.respond([], { clientContext: { selectedWord: "jazz" } })).rejects.toThrow(+ "ClientSession.respond() requires at least one input response.",+ );expect(fetchMock).not.toHaveBeenCalled();});@@ -515,7 +460,7 @@ describe("ClientSession", () => {return createStreamResponse([{type: "session.waiting",- data: { continuationToken: "eve:rekeyed", wait: "next-user-message" },+ data: { continuationToken: "session-id", wait: "next-user-message" },},]);});@@ -531,7 +476,6 @@ describe("ClientSession", () => {const postRequests = requests.filter((request) => request.method === "POST");expect(new URL(postRequests[1]!.url).pathname).toBe("/eve/v1/session/session_1");expect(postRequests[1]!.body).toEqual({- continuationToken: "eve:rekeyed",message: "second",});});@@ -545,7 +489,7 @@ describe("ClientSession", () => {encoder.encode(`${JSON.stringify({type: "session.waiting",- data: { continuationToken: "eve:test", wait: "next-user-message" },+ data: { continuationToken: "session-id", wait: "next-user-message" },})}\n`,),);@@ -569,7 +513,7 @@ describe("ClientSession", () => {expect(cancelled).toBe(true);});- it("resets the session by default after consuming through session.completed", async () => {+ it("keeps the fixed session ID after consuming through session.completed", async () => {const requests: Array<{ body?: unknown; method: string; url: string }> = [];const fetchMock = vi.spyOn(globalThis, "fetch").mockImplementation(async (request, init) => {const url =@@ -592,42 +536,10 @@ describe("ClientSession", () => {await (await session.send("first")).result();await session.send("second");- expect(fetchMock).toHaveBeenCalledTimes(3);- const postRequests = requests.filter((request) => request.method === "POST");- expect(new URL(postRequests[1]!.url).pathname).toBe("/eve/v1/session");- expect(postRequests[1]!.body).toEqual({- message: "second",- });- });-- it("continues the session after session.completed when configured", async () => {- const requests: Array<{ body?: unknown; method: string; url: string }> = [];- const fetchMock = vi.spyOn(globalThis, "fetch").mockImplementation(async (request, init) => {- const url =- typeof request === "string" ? request : request instanceof URL ? request.href : request.url;- const method = init?.method ?? "GET";- requests.push({- body: init?.body === undefined ? undefined : JSON.parse(String(init.body)),- method,- url,- });-- if (method === "POST") {- return createAcceptedResponse();- }-- return createStreamResponse([{ type: "session.completed", data: {} }]);- });- const session = createSession({ streamIndex: 0 }, { preserveCompletedSessions: true });-- await (await session.send("first")).result();- await session.send("second");-expect(fetchMock).toHaveBeenCalledTimes(3);const postRequests = requests.filter((request) => request.method === "POST");expect(new URL(postRequests[1]!.url).pathname).toBe("/eve/v1/session/session_1");expect(postRequests[1]!.body).toEqual({- continuationToken: "eve:test",message: "second",});});@@ -656,7 +568,7 @@ describe("ClientSession", () => {},{type: "session.waiting",- data: { continuationToken: "eve:test", wait: "next-user-message" },+ data: { continuationToken: "session-id", wait: "next-user-message" },},]);});@@ -676,12 +588,11 @@ describe("ClientSession", () => {return createStreamResponse([{type: "session.waiting",- data: { continuationToken: "eve:test", wait: "next-user-message" },+ data: { continuationToken: "session-id", wait: "next-user-message" },},]);});const initialState = {- continuationToken: "eve:test",sessionId: "session_1",streamIndex: 7,};@@ -716,7 +627,7 @@ describe("ClientSession", () => {encoder.encode(`${JSON.stringify({type: "session.waiting",- data: { continuationToken: "eve:test", wait: "next-user-message" },+ data: { continuationToken: "session-id", wait: "next-user-message" },})}\n`,),);@@ -763,8 +674,7 @@ describe("ClientSession", () => {const session = createSession();const eventTypes: string[] = [];- for await (const event of await session.send({- message: "first",+ for await (const event of await session.send("first", {streamReconnectPolicy: { reconnect: false },})) {eventTypes.push(event.type);@@ -855,7 +765,7 @@ describe("ClientSession", () => {return createStreamResponse([{type: "session.waiting",- data: { continuationToken: "eve:test", wait: "next-user-message" },+ data: { continuationToken: "session-id", wait: "next-user-message" },},]);});@@ -902,17 +812,13 @@ describe("ClientSession", () => {const session = createSession();const eventTypes: string[] = [];- for await (const event of await session.send({- message: "first",- signal: abortController.signal,- })) {+ for await (const event of await session.send("first", { signal: abortController.signal })) {eventTypes.push(event.type);abortController.abort();}expect(eventTypes).toEqual(["turn.started"]);expect(session.state).toEqual({- continuationToken: "eve:test",sessionId: "session_1",streamIndex: 1,});@@ -931,7 +837,7 @@ describe("ClientSession", () => {return createStreamResponse([{type: "session.waiting",- data: { continuationToken: "eve:first", wait: "next-user-message" },+ data: { continuationToken: "session-id", wait: "next-user-message" },},]);}@@ -962,7 +868,6 @@ describe("ClientSession", () => {expect(streamStartIndices).toEqual([null, "1"]);expect(session.state).toEqual({- continuationToken: "eve:first",sessionId: "session_1",streamIndex: 2,});diff --git a/packages/eve/src/client/session.ts b/packages/eve/src/client/session.tsindex fbcbcc287..e1f80317c 100644--- a/packages/eve/src/client/session.ts+++ b/packages/eve/src/client/session.ts@@ -1,101 +1,81 @@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,- createEveContinueSessionRoutePath,-} from "#protocol/routes.js";+import { EVE_SESSION_ROUTE_PATH, createEveSessionRoutePath } from "#protocol/routes.js";import { ClientError } from "#client/client-error.js";import { MessageResponse } from "#client/message-response.js";import { followStreamIterable } from "#client/open-stream.js";-import { advanceSession, createInitialSessionState } from "#client/session-utils.js";+import {+ cancelClientSession,+ clearClientSession,+ compactClientSession,+ resetClientSession,+} from "#client/session-controls.js";import { serializeOutputSchema } from "#shared/tool-schema.js";import { createClientUrl } from "#client/url.js";+import type { InputResponse } from "#runtime/input/types.js";import type {CancelSessionResult,ClearResult,+ ClientSessionState,CompactResult,ClientRedirectPolicy,+ RespondTurnOptions,ResetResult,SendTurnInput,+ SendTurnOptions,SendTurnPayload,SessionSnapshot,- SessionState,StreamOptions,} from "#client/types.js";-const DELIVER_RETRY_ATTEMPTS = 10;-const DELIVER_RETRY_DELAY_MS = 200;-/*** Internal interface that a {@link ClientSession} uses to access client-level* configuration without depending on the full {@link Client} class.*/-interface SessionContext {+export interface ClientSessionContext {readonly host: string;- readonly preserveCompletedSessions: boolean;readonly redirect?: ClientRedirectPolicy;resolveHeaders(perRequest?: Readonly<Record<string, string>>): Promise<Headers>;}-/**- * One conversation with an eve agent.- *- * A session tracks conversation state (continuation token, session ID, stream- * cursor) automatically across {@link send} calls. Read the state from- * the {@link state} getter and serialize it to persist a session.- */+/** One fixed, ID-addressed conversation with an eve agent. */export class ClientSession {- readonly #context: SessionContext;- #state: SessionState;+ readonly #context: ClientSessionContext;+ #state: ClientSessionState;/** @internal */- constructor(context: SessionContext, state: SessionState) {+ constructor(context: ClientSessionContext, state: ClientSessionState) {this.#context = context;this.#state = state;}- /**- * Current session cursor. The assigned session ID appears as soon as a send- * is accepted; the continuation token and stream index advance as its event- * stream is consumed. Serialize this to persist and resume later.- */- get state(): SessionState {+ /** @internal */+ static async create<TOutput = unknown>(+ context: ClientSessionContext,+ input: SendTurnInput<TOutput>,+ ): Promise<{ readonly response: MessageResponse<TOutput>; readonly session: ClientSession }> {+ const response = await postTurn(context, EVE_SESSION_ROUTE_PATH, input, true);+ const sessionId = await readSessionId(response);+ const session = new ClientSession(context, { sessionId, streamIndex: 0 });++ return {+ response: session.#messageResponse<TOutput>(response, input, 0),+ session,+ };+ }++ /** Current fixed session identity and durable stream cursor. */+ get state(): ClientSessionState {return this.#state;}- /**- * Reads a finite, point-in-time prefix of this session's durable event stream.- *- * The read starts at the beginning of the session and stops at the durable- * tail observed when it opens. The returned cursor points exactly after the- * returned events, so it can hydrate a UI and resume without a gap.- * Reading a snapshot does not advance or reset this handle's state.- *- * @throws {Error} If the session has no session ID (no message has been sent- * yet).- */+ /** Reads a finite prefix through the durable tail without advancing this handle. */async snapshot(options?: { readonly signal?: AbortSignal }): Promise<SessionSnapshot> {options?.signal?.throwIfAborted();-- const initialState = this.#state;- const sessionId = initialState.sessionId;- if (!sessionId) {- throw new Error("Session has no session ID. Send a message first.");- }-const events: MessageStreamEvent[] = [];for await (const event of this.#readStream({follow: false,- sessionId,signal: options?.signal,startIndex: 0,})) {@@ -103,451 +83,141 @@ export class ClientSession {}options?.signal?.throwIfAborted();-- const lastEvent = events.at(-1);- const continuationToken =- lastEvent?.type === "session.waiting"- ? lastEvent.data.continuationToken- : lastEvent?.type === "session.completed" && this.#context.preserveCompletedSessions- ? initialState.continuationToken- : undefined;- const session: SessionState =- continuationToken === undefined- ? { sessionId, streamIndex: events.length }- : { continuationToken, sessionId, streamIndex: events.length };-- return { events, session };+ return {+ events,+ session: { sessionId: this.#state.sessionId, streamIndex: events.length },+ };}- /**- * Sends one turn payload to the agent.- *- * Pass a string as shorthand for `{ message }`, or pass an object to submit- * follow-up text, HITL results, client context, output schema, signal, and- * headers in a single request.- */- async send<TOutput = unknown>(input: SendTurnInput<TOutput>): Promise<MessageResponse<TOutput>> {- const payload = normalizeSendTurnInput(input);- const state = this.#state;- const postResult = await this.#postTurn(payload, state);- const { continuationToken, sessionId } = postResult;-- // Cancellation and observation can begin as soon as the POST is accepted,- // before the response stream reaches a turn boundary.- if (this.#state === state) {- const nextState = { ...state, sessionId };- if (continuationToken !== undefined) nextState.continuationToken = continuationToken;- this.#state = nextState;- }-- return new MessageResponse<TOutput>({- continuationToken,- createStream: () => this.#createEventStream(sessionId, continuationToken, state, payload),- sessionId,- });+ /** Sends a message to this exact session ID. */+ async send<TOutput = unknown>(+ message: SendTurnInput<TOutput>["message"],+ options: SendTurnOptions<TOutput> = {},+ ): Promise<MessageResponse<TOutput>> {+ return await this.#send({ ...options, message });}- /**- * Requests cooperative cancellation of this session's active turn.- *- * Both `accepted` and `no_active_turn` are successful outcomes. The latter- * means the active turn settled before the request arrived or the session is- * already parked. `turnId` limits the request to the turn the caller- * observed; a stale guard is consumed as a benign no-op. Credentials are- * resolved immediately before the request.- *- * @throws {Error} If this handle has not started or attached to a session.- * @throws {ClientError} If the cancel route returns a non-successful status.- */- async cancel(options?: { turnId?: string }): Promise<CancelSessionResult> {- const sessionId = this.#state.sessionId;- if (!sessionId) {- throw new Error("Session has no session ID. Send a message first.");+ /** Answers pending input requests on this exact session ID. */+ async respond<TOutput = unknown>(+ inputResponses: readonly InputResponse[],+ options: RespondTurnOptions<TOutput> = {},+ ): Promise<MessageResponse<TOutput>> {+ if (inputResponses.length === 0) {+ throw new Error("ClientSession.respond() requires at least one input response.");}+ return await this.#send({ ...options, inputResponses });+ }- const url = createClientUrl(this.#context.host, createEveCancelTurnRoutePath(sessionId));- const headers = await this.#context.resolveHeaders();- headers.set("content-type", "application/json");-- const response = await fetch(- url,- withRedirectPolicy(- {- headers,- method: "POST",- body: options ? JSON.stringify(options) : undefined,- },- this.#context.redirect,- ),+ async #send<TOutput = unknown>(+ input: SendTurnPayload<TOutput>,+ ): Promise<MessageResponse<TOutput>> {+ const initialStreamIndex = this.#state.streamIndex;+ const response = await postTurn(+ this.#context,+ createEveSessionRoutePath(this.#state.sessionId),+ input,+ false,);- 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(`Cancel route returned invalid JSON (${response.status}).`);- }-- const result = CancelTurnResponseSchema.safeParse(payload);- if (!result.success || result.data.sessionId !== sessionId) {- throw new Error(`Cancel route returned an invalid response (${response.status}).`);+ const responseSessionId = await readSessionId(response, this.#state.sessionId);+ if (responseSessionId !== this.#state.sessionId) {+ throw new Error("Message route returned a different session id.");}+ return this.#messageResponse<TOutput>(response, input, initialStreamIndex);+ }- return { sessionId: result.data.sessionId, status: result.data.status };+ /** Requests cooperative cancellation of this session's active turn. */+ async cancel(options?: { readonly turnId?: string }): Promise<CancelSessionResult> {+ return await cancelClientSession({+ context: this.#context,+ options,+ sessionId: this.#state.sessionId,+ });}- /**- * 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.- */+ /** Queues removal of this session's durable model-message history. */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" };+ return await clearClientSession({ context: this.#context, sessionId: this.#state.sessionId });}- /**- * Queues context compaction without sending model input. The request is- * asynchronous; consume the durable event stream through its next session- * boundary before sending another turn. `compaction.completed` confirms that- * summarization succeeded. A never-started handle is a successful no-op.- */+ /** Queues context compaction without sending model input. */async compact(): Promise<CompactResult> {- const state = this.#state;- const continuationToken = state.continuationToken;-- if (continuationToken === undefined) {- if (state.sessionId !== undefined) {- throw new Error(- "Session has no continuation token. Consume its event stream before compacting.",- );- }- return { status: "no_active_session" };- }-- const url = createClientUrl(this.#context.host, EVE_COMPACT_SESSION_ROUTE_PATH);- const headers = await this.#context.resolveHeaders();- headers.set("content-type", "application/json");-- const response = await fetch(- url,- withRedirectPolicy(- {- body: JSON.stringify({ continuationToken }),- headers,- method: "POST",- },- this.#context.redirect,- ),- );- const body = await response.text();-- if (!response.ok) {- throw new ClientError(response.status, body, response.headers);- }-- let payload: unknown;- try {- payload = JSON.parse(body);- } catch {- throw new Error(`Compact route returned invalid JSON (${response.status}).`);- }-- const result = CompactResponseSchema.safeParse(payload);- if (- !result.success ||- (result.data.status === "accepted" &&- state.sessionId !== undefined &&- result.data.sessionId !== state.sessionId)- ) {- throw new Error(`Compact route returned an invalid response (${response.status}).`);- }-- return result.data.status === "accepted"- ? { sessionId: result.data.sessionId, status: "accepted" }- : { status: "no_active_session" };+ return await compactClientSession({ context: this.#context, sessionId: this.#state.sessionId });}- /**- * Terminally retires the session that owns this handle's continuation token.- *- * Unlike {@link cancel}, reset does not merely stop an active turn: it- * releases the durable workflow owner so the next {@link send} creates a- * fresh conversation and initializes a new session-scoped sandbox on first- * sandbox use. Resetting a never-started handle is a successful no-op. After- * a successful reset, this handle has no session state.- *- * @throws {ClientError} If the reset route returns a non-successful status.- */- async reset(): Promise<ResetResult> {- 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 resetting.",- );- }- this.#state = createInitialSessionState();- return { status: "no_active_session" };- }-- const url = createClientUrl(this.#context.host, EVE_RESET_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(`Reset route returned invalid JSON (${response.status}).`);- }-- const result = ResetResponseSchema.safeParse(payload);- if (!result.success) {- throw new Error(`Reset route returned an invalid response (${response.status}).`);- }- if (- result.data.status === "reset" &&- state.sessionId !== undefined &&- result.data.previousSessionId !== state.sessionId- ) {- throw new Error(`Reset route returned an invalid response (${response.status}).`);- }-- if (this.#state === state) {- this.#state = createInitialSessionState();- }-- return result.data.status === "reset"- ? { previousSessionId: result.data.previousSessionId, status: "reset" }- : { status: "no_active_session" };+ /** Terminally retires this exact session ID. The handle remains pinned to it. */+ async reset(options?: { readonly reason?: string }): Promise<ResetResult> {+ return await resetClientSession({+ context: this.#context,+ options,+ sessionId: this.#state.sessionId,+ });}- /**- * Opens this session's event stream for the current session ID.- *- * Resumes from the session's stored stream cursor unless `options.startIndex`- * overrides it. By default, the stream reconnects from its cursor when the- * connection ends; pass `streamReconnectPolicy: { reconnect: false }` to use- * one connection. Negative indices read relative to the current tail on one connection- * and do not advance the stored absolute cursor.- *- * Pass `follow: false` for a bounded read: yields events up to the durable- * tail observed when the stream opens, then returns instead of following.- * The stored cursor still advances past the consumed events.- *- * @throws {Error} If the session has no session ID (no message has been sent- * yet), or if `follow: false` is combined with a negative `startIndex`.- */+ /** Opens this session's durable event stream from its stored cursor. */stream(options?: StreamOptions): AsyncIterable<MessageStreamEvent> {- const sessionId = this.#state.sessionId;-- if (!sessionId) {- throw new Error("Session has no session ID. Send a message first.");- }-if (options?.follow === false && (options.startIndex ?? this.#state.streamIndex) < 0) {throw new Error("stream({ follow: false }) requires a nonnegative startIndex; a tail-relative cursor cannot be bounded.",);}-- return this.#streamAndAdvance(sessionId, options);+ return this.#streamAndAdvance(options);}- // ---------------------------------------------------------------------------- // Internal: POST to message route- // ----------------------------------------------------------------------------- async #postTurn(+ #messageResponse<TOutput>(+ response: Response,input: SendTurnPayload,- session: SessionState,- ): Promise<{ continuationToken?: string; sessionId: string }> {- const routePath = session.sessionId- ? createEveContinueSessionRoutePath(session.sessionId)- : EVE_CREATE_SESSION_ROUTE_PATH;- const url = createClientUrl(this.#context.host, routePath);- const headers = await this.#context.resolveHeaders(input.headers);- headers.set("content-type", "application/json");-- const body = createHandleMessageBody({- input,- outputSchema: serializeOutputSchema(input.outputSchema),- session,- });-- if (body === null) {- throw new Error("Session.send requires a non-empty message, inputResponses, or both.");- }-- const response = await postTurnWithRetry({- body: JSON.stringify(body),- headers,- mustDeliver: (input.inputResponses?.length ?? 0) > 0,- redirect: this.#context.redirect,- signal: input.signal,- url,+ initialStreamIndex: number,+ ): MessageResponse<TOutput> {+ response.body?.cancel().catch(() => {});+ return new MessageResponse<TOutput>({+ createStream: () => this.#createEventStream(initialStreamIndex, input),+ sessionId: this.#state.sessionId,});-- const payload = (await response.json()) as Record<string, unknown>;-- const sessionId =- (typeof payload.sessionId === "string" ? payload.sessionId : undefined) ??- response.headers.get(EVE_SESSION_ID_HEADER)?.trim() ??- session.sessionId;-- if (!sessionId) {- throw new Error("Message route did not return a session id.");- }-- const continuationToken =- typeof payload.continuationToken === "string" ? payload.continuationToken : undefined;-- return { continuationToken, sessionId };}- // ---------------------------------------------------------------------------- // Internal: event stream consumption- // ----------------------------------------------------------------------------async *#createEventStream(- sessionId: string,- continuationToken: string | undefined,- initialState: SessionState,+ initialStreamIndex: number,input: SendTurnPayload,): AsyncGenerator<MessageStreamEvent> {- const events: MessageStreamEvent[] = [];-+ let eventCount = 0;try {for await (const event of this.#readStream({headers: input.headers,- streamReconnectPolicy: input.streamReconnectPolicy,- sessionId,signal: input.signal,- startIndex: initialState.sessionId === sessionId ? initialState.streamIndex : 0,+ startIndex: initialStreamIndex,+ streamReconnectPolicy: input.streamReconnectPolicy,})) {- events.push(event);+ eventCount += 1;yield event;-- if (isCurrentTurnBoundaryEvent(event)) {- break;- }+ if (isCurrentTurnBoundaryEvent(event)) break;}} finally {- this.#state = advanceSession({- continuationToken,- events,- preserveCompletedSessions: this.#context.preserveCompletedSessions,- sessionId,- session: initialState,- });+ this.#state = {+ sessionId: this.#state.sessionId,+ streamIndex: initialStreamIndex + eventCount,+ };}}- async *#streamAndAdvance(- sessionId: string,- options?: StreamOptions,- ): AsyncGenerator<MessageStreamEvent> {- const initialState = this.#state;- const streamIndex = options?.startIndex ?? initialState.streamIndex;- const events: MessageStreamEvent[] = [];-+ async *#streamAndAdvance(options?: StreamOptions): AsyncGenerator<MessageStreamEvent> {+ const startIndex = options?.startIndex ?? this.#state.streamIndex;+ let eventCount = 0;try {for await (const event of this.#readStream({follow: options?.follow,- sessionId,signal: options?.signal,- startIndex: streamIndex,+ startIndex,streamReconnectPolicy: options?.streamReconnectPolicy,})) {- events.push(event);+ eventCount += 1;yield event;}} finally {- if (streamIndex >= 0) {- this.#state = advanceSession({- continuationToken: initialState.continuationToken,- events,- preserveCompletedSessions: this.#context.preserveCompletedSessions,- session: { ...initialState, sessionId, streamIndex },- sessionId,- });+ if (startIndex >= 0) {+ this.#state = {+ sessionId: this.#state.sessionId,+ streamIndex: startIndex + eventCount,+ };}}}@@ -555,7 +225,6 @@ export class ClientSession {#readStream(input: {readonly follow?: boolean;readonly headers?: Readonly<Record<string, string>>;- readonly sessionId: string;readonly signal?: AbortSignal;readonly startIndex: number;readonly streamReconnectPolicy?: StreamOptions["streamReconnectPolicy"];@@ -565,116 +234,69 @@ export class ClientSession {host: this.#context.host,resolveHeaders: () => this.#context.resolveHeaders(input.headers),redirect: this.#context.redirect,- streamReconnectPolicy: input.streamReconnectPolicy,- sessionId: input.sessionId,+ sessionId: this.#state.sessionId,signal: input.signal,startIndex: input.startIndex,+ streamReconnectPolicy: input.streamReconnectPolicy,});}}-async function postTurnWithRetry(input: {- readonly body: string;- readonly headers: Headers;- readonly mustDeliver: boolean;- readonly redirect?: ClientRedirectPolicy;- readonly signal?: AbortSignal;- readonly url: string;-}): Promise<Response> {- const attempts = input.mustDeliver ? DELIVER_RETRY_ATTEMPTS : 1;- let lastStatus: number | undefined;- let lastBody: string | undefined;- let lastHeaders: Headers | undefined;-- for (let attempt = 0; attempt < attempts; attempt += 1) {- const response = await fetch(input.url, {- body: input.body,- headers: input.headers,- method: "POST",- redirect: input.redirect,- signal: input.signal ?? null,- });-- if (response.ok) return response;-- lastStatus = response.status;- lastBody = await response.text();- lastHeaders = response.headers;-- if (!isRetryableDeliveryFailure(response.status, lastBody)) {- throw new ClientError(response.status, lastBody, response.headers);- }-- if (attempt < attempts - 1) {- await sleep(DELIVER_RETRY_DELAY_MS);- }+async function postTurn(+ context: ClientSessionContext,+ path: string,+ input: SendTurnPayload,+ requireMessage: boolean,+): Promise<Response> {+ const body = createMessageBody(input, requireMessage);+ if (body === null) {+ throw new Error(+ requireMessage+ ? "Creating a session requires a non-empty message."+ : "A session turn requires a non-empty message or inputResponses.",+ );}- throw new ClientError(- lastStatus ?? 0,- lastBody ?? "Failed to deliver session turn.",- lastHeaders,- );-}--function isRetryableDeliveryFailure(status: number, body: string): boolean {- return status === 500 && /target session was not found/i.test(body);-}--async function sleep(ms: number): Promise<void> {- await new Promise((resolve) => setTimeout(resolve, ms));+ const headers = await context.resolveHeaders(input.headers);+ headers.set("content-type", "application/json");+ const response = await fetch(createClientUrl(context.host, path), {+ body: JSON.stringify(body),+ headers,+ method: "POST",+ redirect: context.redirect,+ signal: input.signal ?? null,+ });+ if (!response.ok) {+ const responseBody = await response.text();+ throw new ClientError(response.status, responseBody, response.headers);+ }+ return response;}-function normalizeSendTurnInput<TOutput>(input: SendTurnInput<TOutput>): SendTurnPayload<TOutput> {- return typeof input === "string" ? { message: input } : input;+async function readSessionId(response: Response, expected?: string): Promise<string> {+ const payload = (await response.json()) as Record<string, unknown>;+ const sessionId =+ (typeof payload.sessionId === "string" ? payload.sessionId : undefined) ??+ response.headers.get(EVE_SESSION_ID_HEADER)?.trim() ??+ expected;+ if (!sessionId) throw new Error("Message route did not return a session id.");+ return sessionId;}-function createHandleMessageBody(input: {- readonly input: SendTurnPayload;- readonly outputSchema?: Record<string, unknown>;- readonly session: SessionState;-}): Record<string, unknown> | null {+function createMessageBody(+ input: SendTurnPayload,+ requireMessage: boolean,+): Record<string, unknown> | null {const body: Record<string, unknown> = {};-- if (input.input.message !== undefined) {- body.message = input.input.message;- }-- if (input.input.inputResponses !== undefined && input.input.inputResponses.length > 0) {- body.inputResponses = input.input.inputResponses;- }-- if (input.input.clientContext !== undefined) {- body.clientContext = input.input.clientContext;- }-- if (input.outputSchema !== undefined) {- body.outputSchema = input.outputSchema;- }-- if (input.session.continuationToken !== undefined) {- body.continuationToken = input.session.continuationToken;- }-- if (Object.keys(body).length === 0) {- return null;- }-- if (input.session.continuationToken === undefined && body.message === undefined) {- return null;- }-- if (- input.session.continuationToken !== undefined &&- body.message === undefined &&- body.inputResponses === undefined- ) {- return null;+ if (input.message !== undefined) body.message = input.message;+ if (input.inputResponses !== undefined && input.inputResponses.length > 0) {+ body.inputResponses = input.inputResponses;}+ if (input.clientContext !== undefined) body.clientContext = input.clientContext;+ const outputSchema = serializeOutputSchema(input.outputSchema);+ if (outputSchema !== undefined) body.outputSchema = outputSchema;+ if (requireMessage && body.message === undefined) return null;+ if (body.message === undefined && body.inputResponses === undefined) return null;return body;}--function withRedirectPolicy(init: RequestInit, redirect?: ClientRedirectPolicy): RequestInit {- return redirect === undefined ? init : { ...init, redirect };-}diff --git a/packages/eve/src/client/sessions.test.ts b/packages/eve/src/client/sessions.test.tsnew file mode 100644index 000000000..d150031fc--- /dev/null+++ b/packages/eve/src/client/sessions.test.ts@@ -0,0 +1,81 @@+import { afterEach, describe, expect, it, vi } from "vitest";++import { Client } from "#client/client.js";++afterEach(() => {+ vi.restoreAllMocks();+});++describe("Client.sessions", () => {+ it("creates explicitly, streams by ID, and keeps the fixed session state", async () => {+ const requests: Array<{ readonly body?: string; readonly url: string }> = [];+ vi.spyOn(globalThis, "fetch")+ .mockImplementationOnce(async (request, init) => {+ requests.push({ body: init?.body as string | undefined, url: String(request) });+ return Response.json(+ { ok: true, sessionId: "wrun_A", status: "accepted" },+ { status: 202 },+ );+ })+ .mockImplementationOnce(async (request) => {+ requests.push({ url: String(request) });+ return new Response(+ `${JSON.stringify({ data: { reason: "completed" }, type: "session.completed" })}\n`,+ );+ });+ const client = new Client({ host: "https://eve.test" });++ const { response, session } = await client.sessions.create({ message: "hello" });+ await response.result();++ expect(new URL(requests[0]!.url).pathname).toBe("/eve/v1/session");+ expect(JSON.parse(requests[0]!.body!)).toEqual({ message: "hello" });+ expect(new URL(requests[1]!.url).pathname).toBe("/eve/v1/session/wrun_A/stream");+ expect(session.state).toEqual({ sessionId: "wrun_A", streamIndex: 1 });+ });++ it("attaches without I/O and sends every operation through ID-only routes", async () => {+ const requests: Array<{ readonly body?: string; readonly url: string }> = [];+ vi.spyOn(globalThis, "fetch").mockImplementation(async (request, init) => {+ const url = String(request);+ requests.push({ body: init?.body as string | undefined, url });+ const path = new URL(url).pathname;+ if (path === "/eve/v1/session/wrun_A") {+ return Response.json(+ { ok: true, sessionId: "wrun_A", status: "accepted" },+ { status: 202 },+ );+ }+ if (path.endsWith("/cancel")) {+ return Response.json({ ok: true, sessionId: "wrun_A", status: "accepted" });+ }+ if (path.endsWith("/compact") || path.endsWith("/clear")) {+ return Response.json(+ { ok: true, sessionId: "wrun_A", status: "accepted" },+ { status: 202 },+ );+ }+ return Response.json({ ok: true, previousSessionId: "wrun_A", status: "reset" });+ });+ const client = new Client({ host: "https://eve.test" });++ const session = client.sessions.attach("wrun_A");+ expect(requests).toHaveLength(0);+ await session.send("follow-up");+ await session.cancel();+ await session.compact();+ await session.clear();+ await session.reset({ reason: "fresh start" });++ expect(requests.map(({ url }) => new URL(url).pathname)).toEqual([+ "/eve/v1/session/wrun_A",+ "/eve/v1/session/wrun_A/cancel",+ "/eve/v1/session/wrun_A/compact",+ "/eve/v1/session/wrun_A/clear",+ "/eve/v1/session/wrun_A/reset",+ ]);+ expect(JSON.parse(requests[0]!.body!)).toEqual({ message: "follow-up" });+ expect(JSON.parse(requests[4]!.body!)).toEqual({ reason: "fresh start" });+ expect(session.state).toEqual({ sessionId: "wrun_A", streamIndex: 0 });+ });+});diff --git a/packages/eve/src/client/sessions.ts b/packages/eve/src/client/sessions.tsnew file mode 100644index 000000000..3f654037b--- /dev/null+++ b/packages/eve/src/client/sessions.ts@@ -0,0 +1,35 @@+import { ClientSession, type ClientSessionContext } from "#client/session.js";+import type { MessageResponse } from "#client/message-response.js";+import type { SendTurnInput } from "#client/types.js";++/** Result of explicitly creating an ID-addressed client session. */+export interface CreatedClientSession<TOutput = unknown> {+ readonly response: MessageResponse<TOutput>;+ readonly session: ClientSession;+}++/** Collection surface for explicitly creating or attaching ID-addressed sessions. */+export class ClientSessions {+ readonly #context: ClientSessionContext;++ /** @internal */+ constructor(context: ClientSessionContext) {+ this.#context = context;+ }++ /** Creates a session immediately and returns its fixed handle plus first-turn response. */+ async create<TOutput = unknown>(+ input: SendTurnInput<TOutput>,+ ): Promise<CreatedClientSession<TOutput>> {+ return await ClientSession.create(this.#context, input);+ }++ /** Attaches a fixed handle to a known session ID without performing I/O. */+ attach(sessionId: string, options?: { readonly streamIndex?: number }): ClientSession {+ if (sessionId.length === 0) throw new Error("sessionId must be a non-empty string.");+ return new ClientSession(this.#context, {+ sessionId,+ streamIndex: options?.streamIndex ?? 0,+ });+ }+}diff --git a/packages/eve/src/client/stream-follow.integration.test.ts b/packages/eve/src/client/stream-follow.integration.test.tsindex e7aeb9b8b..32295239c 100644--- a/packages/eve/src/client/stream-follow.integration.test.ts+++ b/packages/eve/src/client/stream-follow.integration.test.ts@@ -45,7 +45,10 @@ describe("stream following over real sockets", () => {{ type: "step.started", data: {} },{ type: "step.completed", data: {} },{ type: "step.started", data: {} },- { type: "session.waiting", data: { wait: "next-user-message", continuationToken: "eve:x" } },+ {+ type: "session.waiting",+ data: { continuationToken: "session-id", wait: "next-user-message" },+ },];let connections = 0;const host = await listen(@@ -64,7 +67,7 @@ describe("stream following over real sockets", () => {);const client = new Client({ host });- const session = client.session({ sessionId: "s1", streamIndex: 0 });+ const session = client.sessions.attach("s1");const received: string[] = [];for await (const event of session.stream()) {@@ -142,7 +145,7 @@ describe("stream following over real sockets", () => {);const client = new Client({ host });- const session = client.session({ sessionId: "s1", streamIndex: 0 });+ const session = client.sessions.attach("s1");const received: string[] = [];for await (const event of session.stream({ follow: false })) {diff --git a/packages/eve/src/client/types.ts b/packages/eve/src/client/types.tsindex 26b940693..6167083fe 100644--- a/packages/eve/src/client/types.ts+++ b/packages/eve/src/client/types.ts@@ -2,7 +2,7 @@ import type { UserContent } from "ai";import type { StandardJSONSchemaV1 } from "#compiled/@standard-schema/spec/index.js";import type { MessageStreamEvent } from "#protocol/message.js";-import type { CancelTurnStatus } from "#protocol/cancel-turn.js";+import type { CancelTurnResult } 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";@@ -97,34 +97,17 @@ export interface ClientOptions {* redirect.*/readonly redirect?: ClientRedirectPolicy;-- /**- * Keep a session's continuation token after a normal `session.completed`- * boundary.- *- * By default, completed turns reset the client-side session so the next- * `send()` starts a fresh server-side conversation. Interactive clients can- * set this to preserve durable session state, including framework-managed- * sandbox state, across follow-up prompts until they explicitly create a new- * session.- *- * @default false- */- readonly preserveCompletedSessions?: boolean;}/**- * Input payload for {@link ClientSession.send}. Pass a string as shorthand for- * `{ message: string }`, or pass an object to include a message, HITL input- * responses, one-turn client context, structured-output schema, abort signal,- * and per-turn headers.+ * Input object for creating a client session. The first message is required.*/-export type SendTurnInput<TOutput = unknown> = string | SendTurnPayload<TOutput>;+export interface SendTurnInput<TOutput = unknown> extends SendTurnOptions<TOutput> {+ readonly message: string | UserContent;+}-/**- * Object form accepted by {@link ClientSession.send}.- */-export interface SendTurnPayload<TOutput = unknown> {+/** Options shared by message sends and HITL responses on a client session. */+export interface SendTurnOptions<TOutput = unknown> {/*** Ephemeral client/page context for the next model call only.*@@ -135,16 +118,6 @@ export interface SendTurnPayload<TOutput = unknown> {*/readonly clientContext?: string | readonly string[] | JsonObject;- /**- * HITL responses resolving pending approvals or questions.- */- readonly inputResponses?: readonly InputResponse[];-- /**- * Optional follow-up user message for the same turn.- */- readonly message?: string | UserContent;-/*** Optional schema the harness must satisfy before this turn terminates.*@@ -173,6 +146,20 @@ export interface SendTurnPayload<TOutput = unknown> {readonly headers?: Readonly<Record<string, string>>;}+/** Options for answering pending HITL input requests on a client session. */+export type RespondTurnOptions<TOutput = unknown> = SendTurnOptions<TOutput>;++/** @internal Transport envelope used by stores and command adapters. */+export type SendTurnPayload<TOutput = unknown> =+ | (SendTurnOptions<TOutput> & {+ readonly inputResponses?: never;+ readonly message: string | UserContent;+ })+ | (RespondTurnOptions<TOutput> & {+ readonly inputResponses: readonly InputResponse[];+ readonly message?: never;+ });+/** Retry and backoff settings for one kind of stream reconnection. */export interface StreamReconnectRetryPolicy {/** Initial delay before retrying, in milliseconds. */@@ -232,12 +219,7 @@ export interface StreamOptions {}/** Result of requesting cancellation for a client session's active turn. */-export interface CancelSessionResult {- /** Session whose active turn was targeted. */- readonly sessionId: string;- /** Both outcomes are successful; `no_active_turn` means there was nothing left to cancel. */- readonly status: CancelTurnStatus;-}+export type CancelSessionResult = CancelTurnResult;/** Result of requesting a context clear for a client session. */export type ClearResult =@@ -247,7 +229,7 @@ export type ClearResult =readonly status: Extract<ClearStatus, "accepted">;}| {- /** The client had no continuation token or the token was already free. */+ /** The fixed session ID was unknown or no longer active. */readonly status: Extract<ClearStatus, "no_active_session">;};@@ -259,19 +241,19 @@ export type CompactResult =readonly status: Extract<CompactStatus, "accepted">;}| {- /** The client had no continuation token or the token was already free. */+ /** The fixed session ID was unknown or no longer active. */readonly status: Extract<CompactStatus, "no_active_session">;};/** Result of terminally resetting a client session. */export type ResetResult =| {- /** The prior session was retired and its continuation token released. */+ /** The prior session was terminally retired. */readonly previousSessionId: string;readonly status: Extract<ResetStatus, "reset">;}| {- /** The client had no continuation token or the token was already free. */+ /** The fixed session ID was unknown or no longer active. */readonly status: Extract<ResetStatus, "no_active_session">;};@@ -329,12 +311,10 @@ export interface HealthResult {}/**- * Serializable session cursor. Persist this value and pass it back to- * {@link Client.session} to resume a conversation later.+ * Serializable cursor for one fixed, ID-addressed client session.*/-export interface SessionState {- readonly continuationToken?: string;- readonly sessionId?: string;+export interface ClientSessionState {+ readonly sessionId: string;readonly streamIndex: number;}@@ -346,5 +326,5 @@ export interface SessionSnapshot {readonly events: readonly MessageStreamEvent[];/** Session cursor advanced exactly past {@link events}. */- readonly session: SessionState;+ readonly session: ClientSessionState;}diff --git a/packages/eve/src/compiler/normalize-subagent.ts b/packages/eve/src/compiler/normalize-subagent.tsindex bbabc7a8b..fcb5b18ac 100644--- a/packages/eve/src/compiler/normalize-subagent.ts+++ b/packages/eve/src/compiler/normalize-subagent.ts@@ -21,7 +21,7 @@ import {expectOnlyKnownKeys,expectString,} from "#internal/authored-module.js";-import { EVE_CREATE_SESSION_ROUTE_PATH } from "#protocol/routes.js";+import { EVE_SESSION_ROUTE_PATH } from "#protocol/routes.js";import { DEFAULT_AGENT_MODEL_ID } from "#shared/default-agent-model.js";import { serializeOutputSchema, type ToolSchemaSource } from "#shared/tool-schema.js";import type { JsonObject } from "#shared/json.js";@@ -413,10 +413,7 @@ function normalizeRemoteAgentDefinition(return {description: expectString(record.description, message),outputSchema: serializeOutputSchema(record.outputSchema as ToolSchemaSource | undefined),- path:- record.path === undefined- ? EVE_CREATE_SESSION_ROUTE_PATH- : expectString(record.path, message),+ path: record.path === undefined ? EVE_SESSION_ROUTE_PATH : expectString(record.path, message),// A function `url` is resolved at runtime, not baked into the manifest.url: typeof record.url === "function" ? undefined : expectString(record.url, message),};diff --git a/packages/eve/src/context/dynamic-resolve-context.test.ts b/packages/eve/src/context/dynamic-resolve-context.test.tsindex 859a1ed66..2b846335a 100644--- a/packages/eve/src/context/dynamic-resolve-context.test.ts+++ b/packages/eve/src/context/dynamic-resolve-context.test.ts@@ -31,6 +31,7 @@ describe("buildResolveContext", () => {const resolveCtx = buildResolveContext(ctx, []);+ expect(resolveCtx.channel.continuationToken).toBe("token-1");expect(resolveCtx.channel.metadata).toEqual({threadTs: "1234.5678",userId: "U123",@@ -46,6 +47,15 @@ describe("buildResolveContext", () => {expect(resolveCtx.channel.metadata).toBeUndefined();});+ it("omits continuation token for an ID-only session", () => {+ const ctx = new ContextContainer();+ ctx.set(SessionIdKey, "sess-1");+ ctx.set(AuthKey, null);+ ctx.set(InitiatorAuthKey, null);++ expect(buildResolveContext(ctx, []).channel.continuationToken).toBeUndefined();+ });+it("sets metadata to empty object when projection has no metadata", () => {const ctx = createCtx();ctx.set(ChannelKey, { kind: "http" });diff --git a/packages/eve/src/context/hook-lifecycle.integration.test.ts b/packages/eve/src/context/hook-lifecycle.integration.test.tsindex 22395cebe..3027318f5 100644--- a/packages/eve/src/context/hook-lifecycle.integration.test.ts+++ b/packages/eve/src/context/hook-lifecycle.integration.test.ts@@ -59,7 +59,8 @@ describe("dispatchStreamEventHooks", () => {const registry = createRuntimeHookRegistry([hook("audit", {events: {- "session.completed": async () => {+ "session.completed": async (_event, hookContext) => {+ expect(hookContext.channel.continuationToken).toBe("test:continuation");calls.push("typed");},},diff --git a/packages/eve/src/evals/cli/eval-client.test.ts b/packages/eve/src/evals/cli/eval-client.test.tsindex b391add03..e84873caa 100644--- a/packages/eve/src/evals/cli/eval-client.test.ts+++ b/packages/eve/src/evals/cli/eval-client.test.ts@@ -28,7 +28,6 @@ describe("resolveEvalClientOptions", () => {url: "https://example.vercel.app",});expect(options.host).toBe("https://example.vercel.app");- expect(options.preserveCompletedSessions).toBe(false);expect(options.headers).toBeUndefined();expect(options.auth).toBeUndefined();});diff --git a/packages/eve/src/evals/cli/eval-client.ts b/packages/eve/src/evals/cli/eval-client.tsindex 73d608b0f..fe72cf988 100644--- a/packages/eve/src/evals/cli/eval-client.ts+++ b/packages/eve/src/evals/cli/eval-client.ts@@ -20,10 +20,7 @@ export function resolveEvalClientOptions(return { host: target.url };}- const options = {- ...resolveDevelopmentClientOptions(target.url),- preserveCompletedSessions: false,- };+ const options = resolveDevelopmentClientOptions(target.url);const explicitToken = process.env.EVE_EVAL_AUTH_TOKEN?.trim();if (explicitToken) {return { ...options, auth: { bearer: explicitToken }, redirect: "manual" };diff --git a/packages/eve/src/evals/context.ts b/packages/eve/src/evals/context.tsindex f7ee0aef7..a44b5bf2a 100644--- a/packages/eve/src/evals/context.ts+++ b/packages/eve/src/evals/context.ts@@ -1,4 +1,3 @@-import type { SendTurnInput } from "#client/types.js";import { EvalSessionManager } from "#evals/session.js";import { AssertionCollector } from "#evals/assertions/collector.js";import { createScopedAssertions } from "#evals/assertions/scoped.js";@@ -56,15 +55,15 @@ export function createEvalContext(deps: {},cancel: () => primary().cancel(),requireInputRequest: (filter) => primary().requireInputRequest(filter),- respond: (...responses) => primary().respond(...responses),+ respond: (responses, options) => primary().respond(responses, options),respondAll: (optionId) => primary().respondAll(optionId),- send: (input) => {- lastPrompt = promptText(input);- return primary().send(input);+ send: (message, options) => {+ lastPrompt = typeof message === "string" ? message : "";+ return primary().send(message, options);},- start: (input) => {- lastPrompt = promptText(input);- return primary().start(input);+ start: (message, options) => {+ lastPrompt = message;+ return primary().start(message, options);},sendFile: (text, filePath, mediaType) => {lastPrompt = text;@@ -137,12 +136,6 @@ async function evaluateAssertion(return { score: await assertion.score(value) };}-function promptText(input: SendTurnInput): string {- if (typeof input === "string") return input;- const message = (input as { readonly message?: unknown }).message;- return typeof message === "string" ? message : "";-}-function sleep(ms = 1_000, signal?: AbortSignal): Promise<void> {if (!Number.isFinite(ms) || ms < 0) {throw new Error("sleep() duration must be a non-negative finite number.");diff --git a/packages/eve/src/evals/runner/derive-run-facts.test.ts b/packages/eve/src/evals/runner/derive-run-facts.test.tsindex 4fb357fa8..6bb14533f 100644--- a/packages/eve/src/evals/runner/derive-run-facts.test.ts+++ b/packages/eve/src/evals/runner/derive-run-facts.test.ts@@ -434,7 +434,7 @@ describe("deriveRunFacts", () => {{ type: "turn.completed", data: { sequence: 1, turnId: "t1" } },{type: "session.waiting",- data: { continuationToken: "eve:test", wait: "next-user-message" },+ data: { continuationToken: "session-id", wait: "next-user-message" },},] as UnstampedMessageStreamEvent[];@@ -453,7 +453,7 @@ describe("deriveRunFacts", () => {{ type: "turn.completed", data: { sequence: 3, turnId: "t1" } },{type: "session.waiting",- data: { continuationToken: "eve:test", wait: "next-user-message" },+ data: { continuationToken: "session-id", wait: "next-user-message" },},] as UnstampedMessageStreamEvent[];diff --git a/packages/eve/src/evals/runner/execute-task.test.ts b/packages/eve/src/evals/runner/execute-task.test.tsindex 3be1e69a4..f021d942c 100644--- a/packages/eve/src/evals/runner/execute-task.test.ts+++ b/packages/eve/src/evals/runner/execute-task.test.ts@@ -119,7 +119,6 @@ describe("executeTask", () => {expect(server.posts.map((post) => post.body)).toEqual([{ message: "run pwd" },{- continuationToken: "eve:session_1",inputResponses: [{ optionId: "approve", requestId: "approval_1" }],},]);@@ -354,7 +353,7 @@ describe("executeTask", () => {turnStarted("parent-turn"),subagentCalled("parent-turn", "child-session", "sleeper"),turnCompleted("parent-turn"),- sessionWaiting("eve:parent-session"),+ sessionWaiting(),],},{@@ -363,7 +362,7 @@ describe("executeTask", () => {turnStarted("child-follow-up"),messageCompleted("child continued", "child-follow-up"),turnCompleted("child-follow-up"),- sessionWaiting("eve:child-session-next"),+ sessionWaiting(),],},],@@ -376,7 +375,7 @@ describe("executeTask", () => {turnStarted("child-turn"),actionsRequested("child-turn", "wait-for-cancellation"),turnCompleted("child-turn"),- sessionWaiting("eve:child-session"),+ sessionWaiting(),],},],@@ -426,7 +425,6 @@ describe("executeTask", () => {expect(outcome.error).toBeUndefined();expect(server.cancels).toEqual(["parent-session"]);expect(server.posts[1]?.body).toEqual({- continuationToken: "eve:child-session",message: "continue child",});expect(outcome.result.sessions?.map((session) => session.sessionId)).toEqual([@@ -502,7 +500,7 @@ describe("executeTask", () => {expect(outcome.assertions.every((assertion) => assertion.passed)).toBe(true);});- it("sends a follow-up on an attached session via the stream-recovered continuation token", async () => {+ it("sends a follow-up on an attached fixed session ID", async () => {// The attached stream parks with a token the eval never saw from a POST// response: the only way the follow-up can carry it is recovery from the// `session.waiting` boundary event.@@ -514,7 +512,7 @@ describe("executeTask", () => {turnStarted("turn_2"),messageCompleted("follow-up done", "turn_2"),turnCompleted("turn_2"),- sessionWaiting("eve:channel-rekeyed"),+ sessionWaiting(),],},],@@ -526,7 +524,7 @@ describe("executeTask", () => {turnStarted("turn_1"),messageCompleted("channel done", "turn_1"),turnCompleted("turn_1"),- sessionWaiting("eve:channel-rekeyed"),+ sessionWaiting(),],},],@@ -549,7 +547,6 @@ describe("executeTask", () => {expect(server.posts).toHaveLength(1);expect(new URL(server.posts[0]!.url).pathname).toBe("/eve/v1/session/channel-session");expect(server.posts[0]?.body).toEqual({- continuationToken: "eve:channel-rekeyed",message: "continue please",});expect(outcome.assertions.every((assertion) => assertion.passed)).toBe(true);@@ -581,7 +578,7 @@ describe("executeTask", () => {client: new Client({ host: target.url }),target,evaluation: createTestEval(async (t) => {- const turn = await t.send({ message: "structured", outputSchema: { type: "object" } });+ const turn = await t.send("structured", { outputSchema: { type: "object" } });turn.outputMatches(z.object({ count: z.number(), title: z.string() }));turn.outputEquals({ count: 2, title: "Done" });}, "structured-output"),@@ -646,9 +643,12 @@ function createScriptedServer(if (method === "POST" && pathname.endsWith("/cancel")) {const sessionId = decodeURIComponent(pathname.split("/").at(-2) ?? "");cancels.push(sessionId);+ const status = options.cancelStatus ?? "no_active_turn";return Response.json(- { ok: true, sessionId, status: options.cancelStatus ?? "no_active_turn" },- { status: 202 },+ status === "accepted"+ ? { ok: true, sessionId, status: "accepted" }+ : { ok: true, status: "no_active_turn" },+ { status: status === "accepted" ? 202 : 200 },);}@@ -665,7 +665,6 @@ function createScriptedServer(return Response.json({- continuationToken: `eve:${next.sessionId}`,ok: true,sessionId: next.sessionId,},@@ -706,9 +705,9 @@ function turnCompleted(turnId: string): UnstampedMessageStreamEvent {return { data: { sequence: 3, turnId }, type: "turn.completed" };}-function sessionWaiting(continuationToken = "eve:session_1"): UnstampedMessageStreamEvent {+function sessionWaiting(): UnstampedMessageStreamEvent {return {- data: { continuationToken, wait: "next-user-message" },+ data: { continuationToken: "session-id", wait: "next-user-message" },type: "session.waiting",};}diff --git a/packages/eve/src/evals/session.ts b/packages/eve/src/evals/session.tsindex 128dbea91..d368dcc42 100644--- a/packages/eve/src/evals/session.ts+++ b/packages/eve/src/evals/session.ts@@ -6,9 +6,10 @@ import type { Client } from "#client/client.js";import type { ClientSession } from "#client/session.js";import type {CancelSessionResult,+ ClientSessionState,SendTurnInput,+ SendTurnOptions,SendTurnPayload,- SessionState,} from "#client/types.js";import type { MessageStreamEvent, TurnFailureStreamEvent } from "#protocol/message.js";import { isCurrentTurnBoundaryEvent, isTurnFailureEvent } from "#protocol/message.js";@@ -59,7 +60,8 @@ export class EveEvalTurnFailedError extends Error {export interface EvalSessionDriver extends EveEvalAssertions, EveEvalOutputAssertions {}export class EvalSessionDriver implements EveEvalSession {- readonly #session: ClientSession;+ readonly #client: Client;+ #session: ClientSession | undefined;readonly #signal: AbortSignal | undefined;readonly #collector: AssertionCollector;readonly #events: MessageStreamEvent[] = [];@@ -67,10 +69,12 @@ export class EvalSessionDriver implements EveEvalSession {#pendingInputRequests: readonly InputRequest[] = [];constructor(input: {+ readonly client: Client;readonly collector: AssertionCollector;- readonly session: ClientSession;+ readonly session?: ClientSession;readonly signal?: AbortSignal;}) {+ this.#client = input.client;this.#collector = input.collector;this.#session = input.session;this.#signal = input.signal;@@ -100,14 +104,15 @@ export class EvalSessionDriver implements EveEvalSession {}get sessionId(): string | undefined {- return this.#session.state.sessionId ?? this.#lastTurn?.sessionId;+ return this.#session?.state.sessionId ?? this.#lastTurn?.sessionId;}- get state(): SessionState {- return this.#session.state;+ get state(): ClientSessionState | undefined {+ return this.#session?.state;}async cancel(): Promise<CancelSessionResult> {+ if (this.#session === undefined) throw new Error("Eval session has not started.");return await this.#session.cancel();}@@ -133,12 +138,15 @@ export class EvalSessionDriver implements EveEvalSession {return matching[0]!;}- async respond(...responses: InputResponse[]): Promise<EveEvalTurn> {+ async respond(+ responses: readonly InputResponse[],+ options: SendTurnOptions = {},+ ): Promise<EveEvalTurn> {if (responses.length === 0) {throw new Error("respond() requires at least one input response.");}- return await this.send({ inputResponses: responses });+ return await (await this.#start({ ...options, inputResponses: responses })).result();}async respondAll(optionId: string): Promise<EveEvalTurn> {@@ -151,19 +159,44 @@ export class EvalSessionDriver implements EveEvalSession {}return await this.respond(- ...requests.map((request) => ({+ requests.map((request) => ({optionId,requestId: request.requestId,})),);}- async send(input: SendTurnInput): Promise<EveEvalTurn> {- return await (await this.start(input)).result();+ async send(+ message: SendTurnInput["message"],+ options: SendTurnOptions = {},+ ): Promise<EveEvalTurn> {+ return await (await this.#start({ ...options, message })).result();+ }++ async start(message: string, options: SendTurnOptions = {}): Promise<EveEvalLiveTurn> {+ return await this.#start({ ...options, message });}- async start(input: SendTurnInput): Promise<EveEvalLiveTurn> {- const response = await this.#session.send(attachSignal(input, this.#signal));+ async #start(input: SendTurnPayload): Promise<EveEvalLiveTurn> {+ const turnInput = attachSignal(input, this.#signal);+ let response;+ if (this.#session === undefined) {+ if (turnInput.message === undefined) {+ throw new Error("Eval session has not started.");+ }+ const created = await this.#client.sessions.create({+ ...turnInput,+ message: turnInput.message,+ });+ this.#session = created.session;+ response = created.response;+ } else {+ const { inputResponses, message, ...options } = turnInput;+ response =+ inputResponses === undefined+ ? await this.#session.send(message!, options)+ : await this.#session.respond(inputResponses, options);+ }return new EvalLiveTurn({events: response,record: (events) => this.#recordObservedTurn(response.sessionId, events),@@ -180,7 +213,7 @@ export class EvalSessionDriver implements EveEvalSession {mediaType: mediaType ?? inferMediaType(filePath),text,});- return await this.send({ message });+ return await this.send(message);}async readTurn(options?: { readonly startIndex?: number }): Promise<EveEvalTurn> {@@ -192,6 +225,7 @@ export class EvalSessionDriver implements EveEvalSession {options?: { readonly startIndex?: number },sessionId = requireSessionId(this.sessionId),): EveEvalLiveTurn {+ if (this.#session === undefined) throw new Error("Eval session has not started.");return new EvalLiveTurn({events: this.#session.stream({signal: this.#signal,@@ -210,7 +244,7 @@ export class EvalSessionDriver implements EveEvalSession {events: [...this.#events],primary,sessionId,- state: this.#session.state,+ state: this.#session?.state,};}@@ -523,8 +557,8 @@ export class EvalSessionManager {#createSession(): EvalSessionDriver {const session = new EvalSessionDriver({+ client: this.#client,collector: this.#collector,- session: this.#client.session(),signal: this.#signal,});this.#sessions.push(session);@@ -536,8 +570,11 @@ export class EvalSessionManager {options?: { readonly startIndex?: number },): EvalSessionDriver {const session = new EvalSessionDriver({+ client: this.#client,collector: this.#collector,- session: this.#client.session({ sessionId, streamIndex: options?.startIndex ?? 0 }),+ session: this.#client.sessions.attach(sessionId, {+ streamIndex: options?.startIndex ?? 0,+ }),signal: this.#signal,});this.#sessions.push(session);@@ -545,15 +582,9 @@ export class EvalSessionManager {}}-function attachSignal(input: SendTurnInput, signal: AbortSignal | undefined): SendTurnInput {+function attachSignal(input: SendTurnPayload, signal: AbortSignal | undefined): SendTurnPayload {if (signal === undefined) return input;-- if (typeof input === "string") {- return { message: input, signal };- }-- const payload = input as SendTurnPayload;- return payload.signal === undefined ? { ...payload, signal } : payload;+ return input.signal === undefined ? { ...input, signal } : input;}function formatInputRequestFilter(filter: EveEvalInputRequestMatchOptions): string {diff --git a/packages/eve/src/evals/types.ts b/packages/eve/src/evals/types.tsindex 81689d1da..5cd3976c4 100644--- a/packages/eve/src/evals/types.ts+++ b/packages/eve/src/evals/types.ts@@ -2,7 +2,12 @@ import type { LanguageModel } from "ai";import type { StandardSchemaV1 } from "#compiled/@standard-schema/spec/index.js";import type { RuntimeIdentity, MessageStreamEvent } from "#protocol/message.js";-import type { CancelSessionResult, SendTurnInput, SessionState } from "#client/types.js";+import type {+ CancelSessionResult,+ ClientSessionState,+ SendTurnInput,+ SendTurnOptions,+} from "#client/types.js";import type { InputRequest, InputResponse } from "#runtime/input/types.js";import type { JsonObject, JsonValue } from "#shared/json.js";import type { AgentModelOptionsDefinition } from "#shared/agent-definition.js";@@ -85,7 +90,7 @@ export interface EveEvalSessionResult {readonly events: readonly MessageStreamEvent[];readonly primary: boolean;readonly sessionId?: string;- readonly state: SessionState;+ readonly state: ClientSessionState | undefined;}/**@@ -275,7 +280,7 @@ export interface EveEvalSessionDriver {/** Input requests left pending by the last parked turn. */readonly pendingInputRequests: readonly InputRequest[];/** Serializable cursor for resuming this session. */- readonly state: SessionState;+ readonly state: ClientSessionState | undefined;/** eve session id after the first successful send. */readonly sessionId: string | undefined;/** Request cooperative cancellation of this session's active turn. */@@ -283,13 +288,13 @@ export interface EveEvalSessionDriver {/** Require exactly one pending input request matching `filter`, or abort dependent control flow. */requireInputRequest(filter?: EveEvalInputRequestMatchOptions): InputRequest;/** Resolve specific pending requests and run the resumed turn. */- respond(...responses: InputResponse[]): Promise<EveEvalTurn>;+ respond(responses: readonly InputResponse[], options?: SendTurnOptions): Promise<EveEvalTurn>;/** Resolve every pending request with the same option id. */respondAll(optionId: string): Promise<EveEvalTurn>;/** Send one turn through this session. */- send(input: SendTurnInput): Promise<EveEvalTurn>;- /** Start one turn and return as soon as its session is accepted. */- start(input: SendTurnInput): Promise<EveEvalLiveTurn>;+ send(message: SendTurnInput["message"], options?: SendTurnOptions): Promise<EveEvalTurn>;+ /** Start one text turn and return as soon as its session is accepted. */+ start(message: string, options?: SendTurnOptions): Promise<EveEvalLiveTurn>;/** Send one text turn with a local file attached as a data URL. */sendFile(text: string, filePath: string, mediaType?: string): Promise<EveEvalTurn>;}@@ -433,8 +438,8 @@ export interface EveEvalTargetHandle extends EveEvalTarget {* Attach to a pre-existing session and consume one turn boundary.** When that boundary is `session.waiting`, the attached session recovers- * the current continuation token from the stream, so `session.send(...)`- * and `session.respond(...)` continue the same durable session.+ * the exact session ID, so `session.send(...)` and `session.respond(...)`+ * continue the same durable session.*/attachSession(sessionId: string,diff --git a/packages/eve/src/execution/agent-handle-dispatch.ts b/packages/eve/src/execution/agent-handle-dispatch.tsindex 3792dffc8..59c03899e 100644--- a/packages/eve/src/execution/agent-handle-dispatch.ts+++ b/packages/eve/src/execution/agent-handle-dispatch.ts@@ -228,16 +228,6 @@ async function deliverToAgentHandle(input: {const { address, identity } = handle;if (address.kind === "agent/remote") {- // A remote deployment old enough to omit a continuationToken cannot- // receive continuations; no retry can change that.- if (address.continuationToken === undefined) {- return err({- cause: new Error(- `Remote agent "${identity.name}" returned no continuationToken at start; its deployment does not support continuations.`,- ),- permanent: true,- });- }let resolvedRemote;try {resolvedRemote = resolveRemoteAgentForAction({@@ -261,7 +251,6 @@ async function deliverToAgentHandle(input: {createEveCallbackRoutePath(input.parentToken),),},- continuationToken: address.continuationToken,message: readSubagentMessage(action),outputSchema: normalizeRequestedOutputSchema(action.input.outputSchema),remote: { ...resolvedRemote, url: address.url },diff --git a/packages/eve/src/execution/agent-messaging.scenario.test.ts b/packages/eve/src/execution/agent-messaging.scenario.test.tsindex 1ef9dd787..4ae1d7f04 100644--- a/packages/eve/src/execution/agent-messaging.scenario.test.ts+++ b/packages/eve/src/execution/agent-messaging.scenario.test.ts@@ -257,7 +257,7 @@ async function runScriptedParentSession(input: {const client = new Client({ host: input.serverUrl });const parentEvents = await collectStreamToEnd({label: "parent task completion",- stream: client.session({ sessionId: parentSessionId, streamIndex: 0 }).stream(),+ stream: client.sessions.attach(parentSessionId).stream(),});const calls = filterEventsByType(parentEvents, "subagent.called");@@ -295,9 +295,7 @@ async function expectRetainedChildConversation(input: {}): Promise<void> {const childEvents = await collectStreamToEnd({label: "persisted child events",- stream: input.client- .session({ sessionId: input.childSessionId, streamIndex: 0 })- .stream({ follow: false }),+ stream: input.client.sessions.attach(input.childSessionId).stream({ follow: false }),});const childTurnStarts = indexesOf(childEvents, "turn.started");const childWaits = indexesOf(childEvents, "session.waiting");diff --git a/packages/eve/src/execution/cancel-descendant-turns-step.test.ts b/packages/eve/src/execution/cancel-descendant-turns-step.test.tsindex f2e06eb6e..1680d2fff 100644--- a/packages/eve/src/execution/cancel-descendant-turns-step.test.ts+++ b/packages/eve/src/execution/cancel-descendant-turns-step.test.ts@@ -49,7 +49,6 @@ const LOCAL_RUNNING_HANDLE: AgentHandle = {const REMOTE_RUNNING_HANDLE: AgentHandle = {address: {callbackBaseUrl: "https://parent.example.com",- continuationToken: "remote-token",kind: "agent/remote",sessionId: "remote-child",url: "https://remote.example.com",@@ -85,8 +84,14 @@ describe("cancelDescendantTurnsStep", () => {it("cancels every running local and remote child in parallel", async () => {installRemoteRegistry();vi.mocked(resolveRemoteAgentForAction).mockReturnValue(remote as never);- vi.mocked(requestWorkflowTurnCancellation).mockResolvedValue({ status: "accepted" });- vi.mocked(cancelRemoteAgentTurn).mockResolvedValue({ status: "accepted" });+ vi.mocked(requestWorkflowTurnCancellation).mockResolvedValue({+ sessionId: "local-child",+ status: "accepted",+ });+ vi.mocked(cancelRemoteAgentTurn).mockResolvedValue({+ sessionId: "remote-child",+ status: "accepted",+ });await cancelDescendantTurnsStep({serializedContext: { context: "parent" },@@ -110,7 +115,10 @@ describe("cancelDescendantTurnsStep", () => {});it("does not deserialize remote context for local-only descendants", async () => {- vi.mocked(requestWorkflowTurnCancellation).mockResolvedValue({ status: "accepted" });+ vi.mocked(requestWorkflowTurnCancellation).mockResolvedValue({+ sessionId: "local-child",+ status: "accepted",+ });await cancelDescendantTurnsStep({serializedContext: {},@@ -136,8 +144,14 @@ describe("cancelDescendantTurnsStep", () => {remoteAgent: dynamicRemoteAgent,});vi.mocked(resolveRemoteAgentForAction).mockReturnValue(remote as never);- vi.mocked(requestWorkflowTurnCancellation).mockResolvedValue({ status: "accepted" });- vi.mocked(cancelRemoteAgentTurn).mockResolvedValue({ status: "accepted" });+ vi.mocked(requestWorkflowTurnCancellation).mockResolvedValue({+ sessionId: "local-child",+ status: "accepted",+ });+ vi.mocked(cancelRemoteAgentTurn).mockResolvedValue({+ sessionId: "remote-child",+ status: "accepted",+ });await cancelDescendantTurnsStep({serializedContext: {},@@ -186,10 +200,10 @@ describe("cancelDescendantTurnsStep", () => {vi.mocked(resolveRemoteAgentForAction).mockReturnValue(remote as never);vi.mocked(requestWorkflowTurnCancellation).mockResolvedValueOnce({ status: "no_active_turn" })- .mockResolvedValueOnce({ status: "accepted" });+ .mockResolvedValueOnce({ sessionId: "local-child", status: "accepted" });vi.mocked(cancelRemoteAgentTurn).mockResolvedValueOnce({ status: "no_active_turn" })- .mockResolvedValueOnce({ status: "accepted" });+ .mockResolvedValueOnce({ sessionId: "remote-child", status: "accepted" });const cancellation = cancelDescendantTurnsStep({serializedContext: {},@@ -235,7 +249,6 @@ describe("cancelDescendantTurnsStep", () => {it("warns loudly when a descendant cancel is never accepted", async () => {vi.useFakeTimers();vi.mocked(requestWorkflowTurnCancellation).mockResolvedValue({- reason: "EntityConflictError",status: "no_active_turn",});const warn = vi.spyOn(console, "warn").mockImplementation(() => {});@@ -253,7 +266,6 @@ describe("cancelDescendantTurnsStep", () => {expect.objectContaining({childSessionId: "local-child",finalStatus: "no_active_turn",- reason: "EntityConflictError",}),);});diff --git a/packages/eve/src/execution/cancel-descendant-turns-step.ts b/packages/eve/src/execution/cancel-descendant-turns-step.tsindex 8c1874aa6..1aaedde7d 100644--- a/packages/eve/src/execution/cancel-descendant-turns-step.ts+++ b/packages/eve/src/execution/cancel-descendant-turns-step.ts@@ -86,7 +86,6 @@ async function cancelLocalDescendant(input: {callId: handle.operation.callId,childSessionId: handle.address.sessionId,finalStatus: final.status,- reason: final.reason,subagentName: handle.identity.name,});}@@ -134,7 +133,6 @@ async function cancelRemoteDescendant(input: {callId: handle.operation.callId,childSessionId: handle.address.sessionId,finalStatus: final.status,- reason: final.reason,remoteAgentName: handle.identity.name,});}diff --git a/packages/eve/src/execution/dispatch-runtime-actions-step.integration.test.ts b/packages/eve/src/execution/dispatch-runtime-actions-step.integration.test.tsindex 44eb77389..caa342cba 100644--- a/packages/eve/src/execution/dispatch-runtime-actions-step.integration.test.ts+++ b/packages/eve/src/execution/dispatch-runtime-actions-step.integration.test.ts@@ -102,7 +102,6 @@ const LOCAL_PARKED_HANDLE: AgentHandle = {const REMOTE_PARKED_HANDLE: AgentHandle = {address: {callbackBaseUrl: "https://caller.example.com",- continuationToken: "remote-token",kind: "agent/remote",sessionId: "remote-session-123456789012",url: "https://remote.example.com",@@ -131,7 +130,6 @@ beforeEach(() => {mocks.dispatchSession.mockResolvedValue({ sessionId: CHILD_SESSION_ID, status: "accepted" });mocks.continueRemoteAgentSession.mockResolvedValue(undefined);mocks.startRemoteAgentSession.mockResolvedValue({- continuationToken: "remote-child-token",sessionId: "remote-session-123456789012",});mocks.hydrateDurableSession.mockImplementation(({ durable }) => durable);@@ -238,7 +236,6 @@ describe("dispatchRuntimeActionsStep child starts", () => {expect.objectContaining({address: {callbackBaseUrl: "https://caller.example.com",- continuationToken: "remote-child-token",kind: "agent/remote",sessionId: "remote-session-123456789012",url: "https://registry.example.com",@@ -583,13 +580,12 @@ describe("dispatchRuntimeActionsStep agent delivery", () => {expect(mocks.continueRemoteAgentSession).toHaveBeenCalledWith(expect.objectContaining({- continuationToken: REMOTE_PARKED_HANDLE.address.continuationToken,message: "continue with raw input",remote: expect.objectContaining({nodeId: REMOTE_PARKED_HANDLE.identity.nodeId,url: "https://remote.example.com",}),- sessionId: REMOTE_PARKED_HANDLE.address.sessionId,+ sessionId: "remote-session-123456789012",}),);expect(result.results[0]).toMatchObject({diff --git a/packages/eve/src/execution/dispatch-runtime-actions-step.ts b/packages/eve/src/execution/dispatch-runtime-actions-step.tsindex 4fe974ada..a6bbebe60 100644--- a/packages/eve/src/execution/dispatch-runtime-actions-step.ts+++ b/packages/eve/src/execution/dispatch-runtime-actions-step.ts@@ -654,9 +654,6 @@ async function startRemoteSubagent(input: {kind: "agent/remote",sessionId: child.sessionId,url: resolvedRemote.url,- ...(child.continuationToken === undefined- ? {}- : { continuationToken: child.continuationToken }),} as const;return {address,diff --git a/packages/eve/src/execution/multi-agent-callback-routing.scenario.test.ts b/packages/eve/src/execution/multi-agent-callback-routing.scenario.test.tsindex ec99f874b..e96938117 100644--- a/packages/eve/src/execution/multi-agent-callback-routing.scenario.test.ts+++ b/packages/eve/src/execution/multi-agent-callback-routing.scenario.test.ts@@ -17,7 +17,6 @@ import { fireSessionCallbackStep } from "#execution/session-callback-step.js";import { startRemoteAgentSession } from "#execution/remote-agent-dispatch.js";import { resolveWorkflowCallbackBaseUrl } from "#execution/workflow-callback-url.js";import { authHookToken, CallbackBaseUrlKey, getHookUrl } from "#harness/authorization.js";-import { EVE_SESSION_ID_HEADER } from "#protocol/message.js";import {createEveCallbackRoutePath,createEveConnectionCallbackRoutePath,@@ -223,21 +222,19 @@ describe("multi-agent callback routing", () => {});deploymentOrigin = await listen(deploymentServer);- // Remote subagent: records the create-session body and returns a session- // id and continuation token, like the eve channel's create-session route.+ // Remote subagent: records the create-session body and returns the eve+ // channel's canonical accepted response.remoteAgentServer = createServer((request, response) => {const chunks: Buffer[] = [];request.on("data", (chunk: Buffer) => chunks.push(chunk));request.on("end", () => {createSessionBodies.push(JSON.parse(Buffer.concat(chunks).toString("utf8")));- response.writeHead(200, {- "content-type": "application/json",- [EVE_SESSION_ID_HEADER]: "remote-session-1",- });+ response.writeHead(202, { "content-type": "application/json" });response.end(JSON.stringify({- continuationToken: "remote-session-1:continuation",ok: true,+ sessionId: "remote-session-1",+ status: "accepted",}),);});diff --git a/packages/eve/src/execution/reconcile-session-continuation-token.test.ts b/packages/eve/src/execution/reconcile-session-continuation-token.test.tsindex 87bdb82a0..1cf473bf9 100644--- a/packages/eve/src/execution/reconcile-session-continuation-token.test.ts+++ b/packages/eve/src/execution/reconcile-session-continuation-token.test.ts@@ -35,8 +35,8 @@ describe("reconcileSessionContinuationToken", () => {expect(next).toBe(session);});- it("re-stamps the session's continuation token when a handler called setContinuationToken", () => {- // The session handle's `setContinuationToken(...)` writes through+ it("re-stamps the session's continuation token when a handler called continuation.rekey", () => {+ // The session handle's `continuation.rekey(...)` writes through// to ContinuationTokenKey during the step. After the step,// reconcile picks the new token up and stamps it onto the// HarnessSession the workflow body reads back.diff --git a/packages/eve/src/execution/remote-agent-dispatch.test.ts b/packages/eve/src/execution/remote-agent-dispatch.test.tsindex 588049471..d20a35eca 100644--- a/packages/eve/src/execution/remote-agent-dispatch.test.ts+++ b/packages/eve/src/execution/remote-agent-dispatch.test.ts@@ -80,14 +80,11 @@ describe("startRemoteAgentSession", () => {const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({- continuationToken: "remote-token",ok: true,sessionId: "remote-session",+ status: "accepted",}),- {- headers: { "x-eve-session-id": "remote-session-header" },- status: 202,- },+ { status: 202 },),);vi.stubGlobal("fetch", fetchMock);@@ -113,10 +110,7 @@ describe("startRemoteAgentSession", () => {},});- expect(childSessionId).toEqual({- continuationToken: "remote-token",- sessionId: "remote-session-header",- });+ expect(childSessionId).toEqual({ sessionId: "remote-session" });expect(fetchMock).toHaveBeenCalledWith("https://remote.example.com/eve/v1/session", {body: expect.any(String),headers: {@@ -147,7 +141,7 @@ describe("startRemoteAgentSession", () => {});});- it("accepts a create-session response without a continuationToken from an older deployment", async () => {+ it("rejects the former create-session response shape", async () => {const fetchMock = vi.fn().mockResolvedValue(@@ -155,28 +149,21 @@ describe("startRemoteAgentSession", () => {);vi.stubGlobal("fetch", fetchMock);- const coordinates = await startRemoteAgentSession({- action: createAction(),- callbackBaseUrl: "https://caller.example.com",- remote: createRemoteAgent(),- session: {- agent: {- modelReference: { id: "mock/test" },- system: "",- tools: [],- },- compaction: {- recentWindowSize: 10,- threshold: 100000,+ await expect(+ startRemoteAgentSession({+ action: createAction(),+ callbackBaseUrl: "https://caller.example.com",+ remote: createRemoteAgent(),+ session: {+ agent: { modelReference: { id: "mock/test" }, system: "", tools: [] },+ compaction: { recentWindowSize: 10, threshold: 100000 },+ continuationToken: "eve:parent-token",+ history: [],+ sessionId: "parent-session",+ state: {},},- continuationToken: "eve:parent-token",- history: [],- sessionId: "parent-session",- state: {},- },- });-- expect(coordinates).toEqual({ sessionId: "remote-session" });+ }),+ ).rejects.toThrow("create-session response was invalid");});it("rejects a create-session response without any sessionId", async () => {@@ -206,18 +193,20 @@ describe("startRemoteAgentSession", () => {state: {},},}),- ).rejects.toThrow("create-session response did not include a sessionId");+ ).rejects.toThrow("create-session response was invalid");});it("preserves a prefixed remote base path on create-session requests", async () => {- const fetchMock = vi- .fn()- .mockResolvedValue(- new Response(- JSON.stringify({ continuationToken: "remote-token", sessionId: "remote-session" }),- { status: 202 },- ),- );+ const fetchMock = vi.fn().mockResolvedValue(+ new Response(+ JSON.stringify({+ ok: true,+ sessionId: "remote-session",+ status: "accepted",+ }),+ { status: 202 },+ ),+ );vi.stubGlobal("fetch", fetchMock);await startRemoteAgentSession({@@ -246,14 +235,11 @@ describe("startRemoteAgentSession", () => {const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({- continuationToken: "remote-token",ok: true,sessionId: "remote-session",+ status: "accepted",}),- {- headers: { "x-eve-session-id": "remote-session-header" },- status: 202,- },+ { status: 202 },),);vi.stubGlobal("fetch", fetchMock);@@ -292,9 +278,9 @@ describe("startRemoteAgentSession", () => {const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({- continuationToken: "remote-token",ok: true,sessionId: "remote-session",+ status: "accepted",}),{status: 202,@@ -323,14 +309,16 @@ describe("startRemoteAgentSession", () => {});it("targets an active turn inbox when a callback token is supplied", async () => {- const fetchMock = vi- .fn()- .mockResolvedValue(- new Response(- JSON.stringify({ continuationToken: "remote-token", sessionId: "remote-session" }),- { status: 202 },- ),- );+ const fetchMock = vi.fn().mockResolvedValue(+ new Response(+ JSON.stringify({+ ok: true,+ sessionId: "remote-session",+ status: "accepted",+ }),+ { status: 202 },+ ),+ );vi.stubGlobal("fetch", fetchMock);await startRemoteAgentSession({@@ -360,9 +348,9 @@ describe("startRemoteAgentSession", () => {const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({- continuationToken: "remote-token",ok: true,sessionId: "remote-session",+ status: "accepted",}),{ status: 202 },),@@ -425,7 +413,11 @@ describe("startRemoteAgentSession — forwarded principal", () => {function createSessionResponse(): Response {return new Response(- JSON.stringify({ continuationToken: "remote-token", ok: true, sessionId: "remote-session" }),+ JSON.stringify({+ ok: true,+ sessionId: "remote-session",+ status: "accepted",+ }),{status: 202,},@@ -455,7 +447,7 @@ describe("startRemoteAgentSession — forwarded principal", () => {remote: { ...createRemoteAgent(), forwardPrincipal: true },session: createSession(),}),- ).resolves.toEqual({ continuationToken: "remote-token", sessionId: "remote-session" });+ ).resolves.toEqual({ sessionId: "remote-session" });expect(JSON.parse(fetchMock.mock.calls[0]?.[1]?.body as string).forwardedPrincipal).toEqual({current: CURRENT_AUTH,@@ -485,9 +477,9 @@ describe("startRemoteAgentSession — forwarded principal", () => {const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({- continuationToken: "remote-token",ok: true,sessionId: "remote-session",+ status: "accepted",}),{ status: 202 },),@@ -503,7 +495,7 @@ describe("startRemoteAgentSession — forwarded principal", () => {remote: { ...createRemoteAgent(), forwardPrincipal: true },session: createSession(),}),- ).resolves.toEqual({ continuationToken: "remote-token", sessionId: "remote-session" });+ ).resolves.toEqual({ sessionId: "remote-session" });expect(JSON.parse(fetchMock.mock.calls[0]?.[1]?.body as string)).not.toHaveProperty("forwardedPrincipal",@@ -514,9 +506,9 @@ describe("startRemoteAgentSession — forwarded principal", () => {const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({- continuationToken: "remote-token",ok: true,sessionId: "remote-session",+ status: "accepted",}),{ status: 202 },),@@ -532,7 +524,7 @@ describe("startRemoteAgentSession — forwarded principal", () => {remote: createRemoteAgent(),session: createSession(),}),- ).resolves.toEqual({ continuationToken: "remote-token", sessionId: "remote-session" });+ ).resolves.toEqual({ sessionId: "remote-session" });expect(JSON.parse(fetchMock.mock.calls[0]?.[1]?.body as string)).not.toHaveProperty("forwardedPrincipal",@@ -556,7 +548,6 @@ describe("continueRemoteAgentSession", () => {token: "parent-inbox",url: "https://caller.example.com/eve/v1/callback/parent-inbox",},- continuationToken: "remote-token",message: "follow up",outputSchema: { type: "object" },remote: createRemoteAgent(),@@ -573,7 +564,6 @@ describe("continueRemoteAgentSession", () => {token: "parent-inbox",url: "https://caller.example.com/eve/v1/callback/parent-inbox",},- continuationToken: "remote-token",message: "follow up",outputSchema: { type: "object" },}),@@ -604,7 +594,6 @@ describe("continueRemoteAgentSession", () => {token: "parent-inbox",url: "https://caller.example.com/eve/v1/callback/parent-inbox",},- continuationToken: "remote-token",message: "follow up",remote: createRemoteAgent(),sessionId: "remote-session",@@ -638,12 +627,7 @@ describe("cancelRemoteAgentTurn", () => {.mockResolvedValueOnce({ headers: { authorization: "Bearer second" } });const fetchMock = vi.fn()- .mockResolvedValueOnce(- Response.json(- { ok: true, sessionId: "remote/session id", status: "no_active_turn" },- { status: 202 },- ),- )+ .mockResolvedValueOnce(Response.json({ ok: true, status: "no_active_turn" }, { status: 200 })).mockResolvedValueOnce(Response.json({ ok: true, sessionId: "remote/session id", status: "accepted" },@@ -658,7 +642,7 @@ describe("cancelRemoteAgentTurn", () => {).resolves.toEqual({ status: "no_active_turn" });await expect(cancelRemoteAgentTurn({ remote, sessionId: "remote/session id" }),- ).resolves.toEqual({ status: "accepted" });+ ).resolves.toEqual({ sessionId: "remote/session id", status: "accepted" });expect(auth).toHaveBeenCalledTimes(2);expect(fetchMock).toHaveBeenNthCalledWith(@@ -697,7 +681,7 @@ describe("cancelRemoteAgentTurn", () => {},sessionId: "remote/session id",}),- ).resolves.toEqual({ status: "accepted" });+ ).resolves.toEqual({ sessionId: "remote/session id", status: "accepted" });expect(fetchMock).toHaveBeenCalledWith("https://remote.example.com/eve/agents/researcher/eve/v1/session/remote%2Fsession%20id/cancel",diff --git a/packages/eve/src/execution/remote-agent-dispatch.ts b/packages/eve/src/execution/remote-agent-dispatch.tsindex 3114bd51d..e315d3c7a 100644--- a/packages/eve/src/execution/remote-agent-dispatch.ts+++ b/packages/eve/src/execution/remote-agent-dispatch.ts@@ -1,8 +1,11 @@import { z } from "#compiled/zod/index.js";-import { EVE_SESSION_ID_HEADER } from "#protocol/message.js";import { CancelTurnResponseSchema } from "#protocol/cancel-turn.js";import { AgentHandleError } from "#protocol/agent-handle-error.js";-import { createEveCallbackRoutePath, createEveCancelTurnRoutePath } from "#protocol/routes.js";+import {+ createEveCallbackRoutePath,+ createEveSessionCancelRoutePath,+ createEveSessionRoutePath,+} from "#protocol/routes.js";import type { CancelTurnResult, SessionAuthContext } from "#channel/types.js";import type { ForwardedPrincipal } from "#channel/forwarded-principal.js";import type { HeadersValue } from "#client/types.js";@@ -20,15 +23,12 @@ import { expectFunction, expectObjectRecord } from "#internal/authored-module.jsimport type { JsonObject } from "#shared/json.js";const CreateSessionResponseSchema = z.object({- // Older eve deployments do not return a continuationToken. Their children- // still run to completion as task-mode one-shots; they just can never be- // continued, so the handle records no token.- continuationToken: z.string().min(1).optional(),- sessionId: z.string().min(1).optional(),+ ok: z.literal(true),+ sessionId: z.string().min(1),+ status: z.literal("accepted"),});type RemoteAgentSessionCoordinates = {- readonly continuationToken?: string;readonly sessionId: string;};@@ -130,26 +130,16 @@ export async function startRemoteAgentSession(input: {}const parsed = CreateSessionResponseSchema.safeParse(body);- const sessionIdFromHeader = response.headers.get(EVE_SESSION_ID_HEADER);- const sessionId =- sessionIdFromHeader !== null && sessionIdFromHeader.length > 0- ? sessionIdFromHeader- : parsed.success- ? parsed.data.sessionId- : undefined;-- if (!parsed.success || sessionId === undefined) {+ if (!parsed.success) {throw new Error(- `Remote agent "${input.action.remoteAgentName}" create-session response did not include a sessionId.`,+ `Remote agent "${input.action.remoteAgentName}" create-session response was invalid.`,);}- return parsed.data.continuationToken === undefined- ? { sessionId }- : { continuationToken: parsed.data.continuationToken, sessionId };+ return { sessionId: parsed.data.sessionId };}-/** Continues one remote-agent session via agentId. */+/** Continues one remote-agent session by its immutable session ID. */export async function continueRemoteAgentSession(input: {readonly callback: {readonly callId: string;@@ -157,7 +147,6 @@ export async function continueRemoteAgentSession(input: {readonly token: string;readonly url: string;};- readonly continuationToken: string;readonly message: string;readonly outputSchema?: JsonObject;readonly remote: ResolvedRuntimeRemoteAgentNode;@@ -166,7 +155,6 @@ export async function continueRemoteAgentSession(input: {const response = await fetch(createRemoteAgentContinueUrl(input.remote, input.sessionId), {body: JSON.stringify({callback: input.callback,- continuationToken: input.continuationToken,message: input.message,outputSchema: input.outputSchema,}),@@ -282,14 +270,19 @@ export async function cancelRemoteAgentTurn(input: {}const result = CancelTurnResponseSchema.safeParse(body);- if (!result.success || result.data.sessionId !== input.sessionId) {+ if (+ !result.success ||+ (result.data.status === "accepted" && result.data.sessionId !== input.sessionId)+ ) {throw new RemoteAgentCancelRequestError(`Remote agent "${input.remote.name}" cancel-turn response was invalid.`,{ retryable: false },);}- return { status: result.data.status };+ return result.data.status === "accepted"+ ? { sessionId: result.data.sessionId, status: "accepted" }+ : { status: "no_active_turn" };}export function isRetryableRemoteAgentCancelError(error: unknown): boolean {@@ -412,14 +405,14 @@ function createRemoteAgentCancelTurnUrl(remote: ResolvedRuntimeRemoteAgentNode,sessionId: string,): string {- return createRemoteAgentRouteUrl(remote.url, createEveCancelTurnRoutePath(sessionId));+ return createRemoteAgentRouteUrl(remote.url, createEveSessionCancelRoutePath(sessionId));}function createRemoteAgentContinueUrl(remote: ResolvedRuntimeRemoteAgentNode,sessionId: string,): string {- return createRemoteAgentRouteUrl(remote.url, `/eve/v1/session/${encodeURIComponent(sessionId)}`);+ return createRemoteAgentRouteUrl(remote.url, createEveSessionRoutePath(sessionId));}function createRemoteAgentRouteUrl(baseUrl: string, routePath: string): string {diff --git a/packages/eve/src/execution/runtime-context.test.ts b/packages/eve/src/execution/runtime-context.test.tsindex aa9abb88d..f4d7d8f4c 100644--- a/packages/eve/src/execution/runtime-context.test.ts+++ b/packages/eve/src/execution/runtime-context.test.ts@@ -3,6 +3,7 @@ import { ContextContainer, contextStorage, loadContext } from "#context/containeimport {AuthKey,ChannelInstrumentationKey,+ ContinuationTokenKey,type Session,type SessionAuthContext,SessionIdKey,@@ -177,6 +178,20 @@ describe("buildRunContext", () => {expect(ctx.require(AuthKey)).toBeNull();});+ it("does not invent a continuation for an ID-only run", () => {+ const ctx = buildRunContext({+ bundle: createMinimalBundle(),+ run: {+ auth: null,+ adapter: { kind: "http" },+ input: { message: "hi" },+ mode: "conversation",+ },+ });++ expect(ctx.get(ContinuationTokenKey)).toBeUndefined();+ });+it("does not throw when channel has no onContext", () => {expect(() =>buildRunContext({diff --git a/packages/eve/src/execution/runtime-context.ts b/packages/eve/src/execution/runtime-context.tsindex 13d4a8938..7f625b9fc 100644--- a/packages/eve/src/execution/runtime-context.ts+++ b/packages/eve/src/execution/runtime-context.ts@@ -41,7 +41,9 @@ export function buildRunContext(input: {});}- ctx.set(ContinuationTokenKey, run.continuationToken ?? "");+ if (run.continuationToken !== undefined) {+ ctx.set(ContinuationTokenKey, run.continuationToken);+ }ctx.set(ModeKey, run.mode);ctx.set(AuthKey, auth);ctx.set(InitiatorAuthKey, run.initiatorAuth ?? auth);diff --git a/packages/eve/src/execution/runtime-errors.ts b/packages/eve/src/execution/runtime-errors.tsindex 2c0d0bc3a..e5026bdaa 100644--- a/packages/eve/src/execution/runtime-errors.ts+++ b/packages/eve/src/execution/runtime-errors.ts@@ -1,7 +1,7 @@/*** Thrown by a {@link Runtime}'s `deliver` when no in-flight session* matches the continuation token. Callers using the resume-or-start- * pattern (e.g. {@link createSendFn}) treat this as the signal to start+ * pattern (e.g. a channel address send) treat this as the signal to start* a fresh session.*/export class RuntimeNoActiveSessionError extends Error {diff --git a/packages/eve/src/execution/session-command-token.ts b/packages/eve/src/execution/session-command-token.tsindex 5f700d8b0..d915075f2 100644--- a/packages/eve/src/execution/session-command-token.ts+++ b/packages/eve/src/execution/session-command-token.ts@@ -1,5 +1,10 @@const SESSION_COMMAND_NAMESPACE = "eve:session";+/** Returns whether a token belongs to eve's framework-reserved session command namespace. */+export function isReservedSessionCommandToken(token: string): boolean {+ return token.startsWith(`${SESSION_COMMAND_NAMESPACE}:`);+}+/** Derives the framework-reserved stable command inbox token for a session. */export function sessionCommandHookToken(sessionId: string): string {return `${SESSION_COMMAND_NAMESPACE}:${sessionId}:inbox`;diff --git a/packages/eve/src/execution/settle-cancelled-turn-step.ts b/packages/eve/src/execution/settle-cancelled-turn-step.tsindex 2c65f258b..10eaddd36 100644--- a/packages/eve/src/execution/settle-cancelled-turn-step.ts+++ b/packages/eve/src/execution/settle-cancelled-turn-step.ts@@ -109,7 +109,7 @@ export async function settleCancelledTurnStep(input: {turnId: activeTurnId(emissionState),}) ?? baseEmit;return {- result: await emitCancelledTurn(emit, emissionState, enrichedSession.continuationToken),+ result: await emitCancelledTurn(emit, emissionState),session: enrichedSession,};});diff --git a/packages/eve/src/execution/subagent-auth-proxy.integration.test.ts b/packages/eve/src/execution/subagent-auth-proxy.integration.test.tsindex 6a6c43c2c..cfac5bac0 100644--- a/packages/eve/src/execution/subagent-auth-proxy.integration.test.ts+++ b/packages/eve/src/execution/subagent-auth-proxy.integration.test.ts@@ -30,7 +30,7 @@ const authorizationAdapter: ChannelAdapter<AuthorizationAdapterContext> = {kind: "authorization-proxy-test","authorization.required"(data, ctx) {ctx.state.pendingName = data.name;- ctx.session.setContinuationToken("auth-thread");+ ctx.session.continuation?.rekey("auth-thread");},"authorization.completed"(data, ctx) {delete ctx.state.pendingName;diff --git a/packages/eve/src/execution/subagent-hitl-proxy.ts b/packages/eve/src/execution/subagent-hitl-proxy.tsindex ef411516a..89b2e8a91 100644--- a/packages/eve/src/execution/subagent-hitl-proxy.ts+++ b/packages/eve/src/execution/subagent-hitl-proxy.ts@@ -46,12 +46,7 @@ export async function emitProxiedInputRequest(input: {if (input.mode === "conversation") {const state = getHarnessEmissionState(input.session.state);- const nextState = await emitTurnEpilogue(- input.emit,- state,- input.mode,- input.session.continuationToken,- );+ const nextState = await emitTurnEpilogue(input.emit, state, input.mode);nextSession = setHarnessEmissionState(input.session, nextState);}diff --git a/packages/eve/src/execution/terminate-child-sessions-step.test.ts b/packages/eve/src/execution/terminate-child-sessions-step.test.tsindex 729a61387..13bc23c96 100644--- a/packages/eve/src/execution/terminate-child-sessions-step.test.ts+++ b/packages/eve/src/execution/terminate-child-sessions-step.test.ts@@ -105,15 +105,14 @@ function makeIdentity(id: string): { id: string; name: string; nodeId: string }}function makeAddress(kind: AddressKind, sessionId: string) {- const base = { continuationToken: `${sessionId}:token`, sessionId };return kind === "agent/remote"? {- ...base,callbackBaseUrl: "https://parent.example.com",kind,+ sessionId,url: "https://remote.example.com",}- : { ...base, kind };+ : { continuationToken: `${sessionId}:token`, kind, sessionId };}function runningHandle(input: {diff --git a/packages/eve/src/execution/turn-cancellation.integration.test.ts b/packages/eve/src/execution/turn-cancellation.integration.test.tsindex bc134a140..e6bd10379 100644--- a/packages/eve/src/execution/turn-cancellation.integration.test.ts+++ b/packages/eve/src/execution/turn-cancellation.integration.test.ts@@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest";import { getWorld, resumeHook, start } from "#internal/workflow/runtime.js";import { createTestRuntime, type TestRuntime } from "#internal/testing/app-harness.js";+import { mockChannelContext } from "#internal/testing/mocks/mock-channel-operations.js";import {captureTurnEvents,containsEventSequence,@@ -14,17 +15,15 @@ import { sessionCommandHookToken } from "#execution/session-command-token.js";import { turnCancellationHookToken } from "#execution/turn-cancellation-token.js";import { workflowEntry } from "#execution/workflow-entry.js";import { createWorkflowRuntime } from "#execution/workflow-runtime.js";-import { createEveCancelTurnRoutePath } from "#protocol/routes.js";+import { createEveSessionCancelRoutePath } from "#protocol/routes.js";import type { UnstampedMessageStreamEvent } from "#protocol/message.js";-import { createCancelFn } from "#channel/cancel.js";+import { createChannelAddress } from "#channel/channel-address.js";import type { RouteHandlerArgs } from "#channel/routes.js";import { createSession } from "#channel/session.js";import { none } from "#public/channels/auth.js";import { eveChannel } from "#public/channels/eve.js";-import type { Agent } from "#public/definitions/channel.js";import type { ToolContext } from "#public/definitions/tool.js";import type { ResolvedToolDefinition } from "#runtime/types.js";-import { attachRouteAgent } from "#internal/nitro/routes/channel-route-context.js";import { toInputSchema } from "#shared/tool-schema.js";/**@@ -224,74 +223,45 @@ function createCancelRouteCaller(): (const runtime = createWorkflowRuntime({compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),});- const agent: Agent = {- cancelTurn: (input) =>- runtime.dispatchSession({- command: { kind: "cancel", turnId: input.turnId },- sessionId: input.sessionId,- }),- async deliver() {- throw new Error("cancel route must not deliver");- },- async getEventStream() {- throw new Error("cancel route must not read events");- },- async run() {- throw new Error("cancel route must not start a session");- },- };return async (sessionId, body) => {- const request = new Request(`https://example.com${createEveCancelTurnRoutePath(sessionId)}`, {- method: "POST",- ...(body === undefined- ? {}- : { body: JSON.stringify(body), headers: { "content-type": "application/json" } }),- });- const args = attachRouteAgent(+ const request = new Request(+ `https://example.com${createEveSessionCancelRoutePath(sessionId)}`,{- send: () => {- throw new Error("cancel route must not send");- },- resolveActiveSession: async () => undefined,- 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");- },- reset: () => {- throw new Error("cancel route must not reset a session");- },- getSession: () => {- throw new Error("cancel route must not get a session");- },- receive: () => {- throw new Error("cancel route must not receive");- },- params: { sessionId },- waitUntil: () => undefined,- requestIp: "127.0.0.1",- } satisfies RouteHandlerArgs,- agent,+ method: "POST",+ ...(body === undefined+ ? {}+ : { body: JSON.stringify(body), headers: { "content-type": "application/json" } }),+ },);+ const args = {+ ...mockChannelContext(() => {+ throw new Error("cancel route must not send through a channel address");+ }),+ attachSession: (id: string) => createSession(id, runtime),+ to: () => {+ throw new Error("cancel route must not send to another channel");+ },+ params: { sessionId },+ waitUntil: () => undefined,+ requestIp: "127.0.0.1",+ } satisfies RouteHandlerArgs;return await handler(request, args);};}async function expectCancelResponse(response: Response,- expected: { readonly sessionId: string; readonly status: "accepted" | "no_active_turn" },+ expected:+ | { readonly sessionId: string; readonly status: "accepted" }+ | { readonly status: "no_active_turn" },): Promise<void> {- expect(response.status).toBe(202);- await expect(response.json()).resolves.toEqual({- ok: true,- sessionId: expected.sessionId,- status: expected.status,- });+ expect(response.status).toBe(expected.status === "accepted" ? 202 : 200);+ await expect(response.json()).resolves.toEqual(+ expected.status === "accepted"+ ? { ok: true, sessionId: expected.sessionId, status: "accepted" }+ : { ok: true, status: "no_active_turn" },+ );}describe("turn cancellation integration", () => {@@ -379,7 +349,6 @@ describe("turn cancellation integration", () => {await fixture.runtime.run(async () => {await expectCancelResponse(await cancelViaRoute("missing-session"), {- sessionId: "missing-session",status: "no_active_turn",});@@ -453,13 +422,18 @@ describe("turn cancellation integration", () => {const workflowRuntime = createWorkflowRuntime({compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),});- const cancel = createCancelFn(workflowRuntime, "http");+ const address = (continuationToken: string) =>+ createChannelAddress({+ adapter: { kind: "http" },+ channelName: "http",+ continuationToken,+ runtime: workflowRuntime,+ });await fixture.runtime.run(async () => {// A token no session owns is the benign "nothing to cancel" success// and must never start a session.- await expect(cancel({ continuationToken: "no-such-thread" })).resolves.toEqual({- reason: "HookNotFoundError",+ await expect(address("no-such-thread").cancel()).resolves.toEqual({status: "no_active_turn",});@@ -479,7 +453,8 @@ describe("turn cancellation integration", () => {await waitForHookByToken(continuationToken);await fixture.toolStarted;- await expect(cancel({ continuationToken: rawToken })).resolves.toEqual({+ await expect(address(rawToken).cancel()).resolves.toEqual({+ sessionId: run.runId,status: "accepted",});@@ -498,8 +473,9 @@ describe("turn cancellation integration", () => {expect(fixture.toolAborts()).toBe(1);// Session.cancel() addresses the same parked session by its stable ID.- const session = createSession(run.runId, rawToken, workflowRuntime);+ const session = createSession(run.runId, workflowRuntime);await expect(session.cancel()).resolves.toEqual({+ sessionId: run.runId,status: "accepted",});diff --git a/packages/eve/src/execution/turn-control-receiver.test.ts b/packages/eve/src/execution/turn-control-receiver.test.tsindex af5b1d63e..f8c84d9e1 100644--- a/packages/eve/src/execution/turn-control-receiver.test.ts+++ b/packages/eve/src/execution/turn-control-receiver.test.ts@@ -63,21 +63,29 @@ describe("TurnControlReceiver", () => {expect(bufferedDeliveries).toEqual([delivery]);});- it("re-buffers an unresolved forwarded delivery when the turn terminates", async () => {- const delivery: DeliverHookPayload = { kind: "deliver", payloads: [{ message: "hello" }] };+ it("keeps earlier remainders ahead of an unresolved delivery when the turn terminates", async () => {+ const outstanding: DeliverHookPayload = {+ kind: "deliver",+ payloads: [{ message: "outstanding" }],+ };+ const earlierRemainder: DeliverHookPayload = {+ kind: "deliver",+ payloads: [{ message: "earlier remainder" }],+ };installControlHook([deliveryRequest("req-1"),{action: { kind: "done", output: "bye", serializedContext: {}, sessionState: createState() },+ bufferedDeliveries: [earlierRemainder],kind: "turn-result",},]);- const bufferedDeliveries: DeliverHookPayload[] = [delivery];+ const bufferedDeliveries: DeliverHookPayload[] = [outstanding];const action = await runReceiver(bufferedDeliveries);expect(action).toMatchObject({ kind: "done", output: "bye" });- expect(bufferedDeliveries).toEqual([delivery]);+ expect(bufferedDeliveries).toEqual([earlierRemainder, outstanding]);});it("hands the turn's remainders back ahead of existing buffered deliveries", async () => {diff --git a/packages/eve/src/execution/turn-control-receiver.ts b/packages/eve/src/execution/turn-control-receiver.tsindex 053a3b9ce..16e2203ba 100644--- a/packages/eve/src/execution/turn-control-receiver.ts+++ b/packages/eve/src/execution/turn-control-receiver.ts@@ -222,8 +222,8 @@ export class TurnControlReceiver {/*** Waits for the active turn to resolve a forwarded delivery. The turn either* accepts it (consumed) or releases it on cancellation or termination, in- * which case the delivery returns to the buffer ahead of the turn's own- * remainders so the next parent turn still observes it in arrival order.+ * which case the delivery returns behind remainders from earlier deliveries+ * accepted by the turn and ahead of deliveries that arrived later.*/private async awaitForwardedDelivery(requestId: string,diff --git a/packages/eve/src/execution/turn-workflow.test.ts b/packages/eve/src/execution/turn-workflow.test.tsindex e1c491ed4..22d43af3a 100644--- a/packages/eve/src/execution/turn-workflow.test.ts+++ b/packages/eve/src/execution/turn-workflow.test.ts@@ -465,7 +465,7 @@ describe("turnWorkflow", () => {expect(cancelHookTokens()).toEqual([]);});- it("registers no cancel hook when the session cannot park", async () => {+ it("registers a cancel hook for a task session without a continuation alias", async () => {const sessionState = createSessionState({ continuationToken: "" });installInbox([]);vi.mocked(turnStep).mockResolvedValueOnce({@@ -482,8 +482,8 @@ describe("turnWorkflow", () => {});await turnWorkflow(input);- expect(vi.mocked(turnStep).mock.calls[0]?.[0].abortSignal).toBeUndefined();- expect(cancelHookTokens()).toEqual([]);+ expect(vi.mocked(turnStep).mock.calls[0]?.[0].abortSignal).toBeInstanceOf(AbortSignal);+ expect(cancelHookTokens()).toEqual(["turn-token:cancel"]);});it("deduplicates concurrent turn workflows through inbox ownership", async () => {diff --git a/packages/eve/src/execution/turn-workflow.ts b/packages/eve/src/execution/turn-workflow.tsindex 1e7b52039..bfbe57f75 100644--- a/packages/eve/src/execution/turn-workflow.ts+++ b/packages/eve/src/execution/turn-workflow.ts@@ -33,16 +33,6 @@ import type { RuntimeActionResult } from "#runtime/actions/types.js";const TASK_MODE_WAIT_ERROR_MESSAGE = "Task mode cannot wait for follow-up input (`next: null`).";-// A cancelled turn settles by parking the session, so the cancel hook is-// only claimed where a park can land: conversation sessions always accept-// follow-up input, and task sessions can park only when a continuation-// token anchors them to a waiting parent (delegated subagents always have-// one). A root task run without one is unparkable, so it stays-// uncancellable rather than settling a cancel as `session.failed`.-function canSettleCancelledTurnAsPark(input: TurnWorkflowInput): boolean {- return input.mode === "conversation" || input.stepInput.sessionState.continuationToken !== "";-}-export type { TurnWorkflowInput };/**@@ -99,10 +89,7 @@ async function runTurnOwnedWorkflow(input: TurnWorkflowInput): Promise<void> {// Claimed after the inbox claim so a losing duplicate run never// contends for the session cancel token.- if (- input.driverCapabilities?.cancelledTurnSettle === true &&- canSettleCancelledTurnAsPark(input)- ) {+ if (input.driverCapabilities?.cancelledTurnSettle === true) {cancellation = await createTurnCancellationControl({controlToken: input.completionToken,expectedTurnId: activeTurnId(input.stepInput.sessionState.emissionState),@@ -124,12 +111,10 @@ async function runTurnOwnedWorkflow(input: TurnWorkflowInput): Promise<void> {(cancellation?.signal.aborted === true && pendingActionKeys === undefined)) {// No `canPark` check here: that gate rejects model-authored waits- // (`next: null`) in task mode, whereas a cancelled turn parks by- // design and its parkability was already established when the- // cancel hook was claimed (`canSettleCancelledTurnAsPark`). The- // epilogue runs in the driver (`settleCancelledTurnStep`), not as- // a step in this run, where queued cancel wakes could re-dispatch- // it.+ // (`next: null`) in task mode, whereas every session can resume by+ // stable ID after a cancelled turn. The epilogue runs in the driver+ // (`settleCancelledTurnStep`), not as a step in this run, where queued+ // cancel wakes could re-dispatch it.await finishCancelledTurn({ bufferedDeliveries, cancellation, cursor });return;}diff --git a/packages/eve/src/execution/workflow-entry.integration.test.ts b/packages/eve/src/execution/workflow-entry.integration.test.tsindex 75394dcfd..fc1858c84 100644--- a/packages/eve/src/execution/workflow-entry.integration.test.ts+++ b/packages/eve/src/execution/workflow-entry.integration.test.ts@@ -2,7 +2,7 @@ import { describe, expect, it } from "vitest";import { getWorld, resumeHook, start } from "#internal/workflow/runtime.js";import { hydrateWorkflowArguments } from "@workflow/core/serialization";-import { createSendFn } from "#channel/send.js";+import { createChannelAddress } from "#channel/channel-address.js";import { captureTurnEvents, filterEventsByType } from "#internal/testing/events.js";import { createTestRuntime } from "#internal/testing/app-harness.js";import { waitForHook } from "#internal/testing/workflow-test-helpers.js";@@ -28,7 +28,7 @@ function buildSerializedContext(overrides: {auth?: Record<string, unknown>;channelKind: string;channelState?: Record<string, unknown>;- continuationToken: string;+ continuationToken?: string;mode: string;parent?: {readonly callId: string;@@ -44,9 +44,11 @@ function buildSerializedContext(overrides: {"eve.auth": overrides.auth ?? null,"eve.bundle": { source: createBundledRuntimeCompiledArtifactsSource() },"eve.channel": { kind: overrides.channelKind, state: overrides.channelState ?? {} },- "eve.continuationToken": overrides.continuationToken,"eve.mode": overrides.mode,};+ if (overrides.continuationToken !== undefined) {+ context["eve.continuationToken"] = overrides.continuationToken;+ }if (overrides.parent !== undefined) {context["eve.parentSession"] = overrides.parent;}@@ -260,7 +262,10 @@ describe("workflowEntry integration", () => {const firstTurn = await stream.nextTurn();expect(hook.token).toBe(continuationToken);- expect(firstTurn.at(-1)?.type).toBe("session.waiting");+ expect(firstTurn.at(-1)).toMatchObject({+ data: { continuationToken: "workflow-entry-conversation" },+ type: "session.waiting",+ });expect(firstTurn.every((event) => typeof event.meta?.at === "string")).toBe(true);expect(firstTurn.some(@@ -298,6 +303,33 @@ describe("workflowEntry integration", () => {});});+ it("publishes the session ID as the waiting address for an ID-only session", async () => {+ const runtime = createTestRuntime({ agent: { name: "workflow-entry-id-only" } });++ await runtime.run(async () => {+ const run = await start(workflowEntry, [+ {+ input: { message: "hello there" },+ serializedContext: buildSerializedContext({+ channelKind: "http",+ mode: "conversation",+ }),+ },+ ]);+ const stream = captureTurnEvents(run);++ try {+ expect((await stream.nextTurn()).at(-1)).toMatchObject({+ data: { continuationToken: run.runId },+ type: "session.waiting",+ });+ } finally {+ stream.dispose();+ await run.cancel();+ }+ });+ });+it("stamps every stream event with an id that survives a rewind", async () => {const runtime = createTestRuntime({ agent: { name: "workflow-entry-event-ids" } });const continuationToken = "http:workflow-entry-event-ids";@@ -392,10 +424,13 @@ describe("workflowEntry integration", () => {expect(filterEventsByType(events, "session.failed")).toHaveLength(0);await expect(run.returnValue).resolves.toEqual({ output: "" });- const send = createSendFn(workflowRuntime, { kind: "http" }, "http");- const replacement = await send("start fresh", {- auth: null,+ const replacement = await createChannelAddress({+ adapter: { kind: "http" },+ channelName: "http",continuationToken: "workflow-entry-timeout",+ runtime: workflowRuntime,+ }).send("start fresh", {+ auth: null,});replacementSessionId = replacement.id;diff --git a/packages/eve/src/execution/workflow-runtime.test.ts b/packages/eve/src/execution/workflow-runtime.test.tsindex ae7090e0a..d4dbc5455 100644--- a/packages/eve/src/execution/workflow-runtime.test.ts+++ b/packages/eve/src/execution/workflow-runtime.test.ts@@ -161,37 +161,31 @@ describe("createWorkflowRuntime command dispatch", () => {command: { kind: "cancel", turnId: "turn-2" },sessionId: "session-1",}),- ).resolves.toEqual({ status: "accepted" });+ ).resolves.toEqual({ sessionId: "session-1", status: "accepted" });expect(resumeHookMock).toHaveBeenCalledWith(sessionCommandHookToken("session-1"), {kind: "cancel",turnId: "turn-2",});});- it("maps missing and terminal targets to 'no_active_turn' with a classified reason", async () => {+ it("maps missing and terminal targets to 'no_active_turn'", async () => {const { EntityConflictError, HookNotFoundError, RunExpiredError, WorkflowRunNotFoundError } =await import("#compiled/@workflow/errors/index.js");const errors = [- {- error: new HookNotFoundError(sessionCommandHookToken("session-1")),- reason: "HookNotFoundError",- },- { error: new WorkflowRunNotFoundError("turn-run"), reason: "WorkflowRunNotFoundError" },- { error: new RunExpiredError("turn already completed"), reason: "RunExpiredError" },- {- error: new EntityConflictError("turn completed during cancellation"),- reason: "EntityConflictError",- },+ new HookNotFoundError(sessionCommandHookToken("session-1")),+ new WorkflowRunNotFoundError("turn-run"),+ new RunExpiredError("turn already completed"),+ new EntityConflictError("turn completed during cancellation"),];- for (const { error, reason } of errors) {+ for (const error of errors) {resumeHookMock.mockRejectedValueOnce(error);await expect(buildRuntime().dispatchSession({command: { kind: "cancel" },sessionId: "session-1",}),- ).resolves.toEqual({ reason, status: "no_active_turn" });+ ).resolves.toEqual({ status: "no_active_turn" });}});diff --git a/packages/eve/src/execution/workflow-runtime.ts b/packages/eve/src/execution/workflow-runtime.tsindex 392cde255..a4aea51a6 100644--- a/packages/eve/src/execution/workflow-runtime.ts+++ b/packages/eve/src/execution/workflow-runtime.ts@@ -191,7 +191,6 @@ export function createWorkflowRuntime(config: {};return {- continuationToken: input.continuationToken ?? run.runId,get events() {return getEvents();},@@ -258,7 +257,7 @@ async function dispatchWorkflowCommand<TCommand extends SessionCommand>(hook = normalizeWorkflowHook(await resumeHook(token, command));} catch (error) {if (isInactiveCommandTarget(error)) {- return inactiveCommandResult(command, error);+ return inactiveCommandResult(command);}logError(log, "failed to dispatch session command", error, {command: command.kind,@@ -282,20 +281,19 @@ function activeCommandResult<TCommand extends SessionCommand>(command.kind === "reset"? { previousSessionId: sessionId, status: "reset" as const }: command.kind === "cancel"- ? { status: "accepted" as const }+ ? { sessionId, status: "accepted" as const }: { sessionId, status: "accepted" as const };return result as SessionCommandResult<TCommand>;}function inactiveCommandResult<TCommand extends SessionCommand>(command: TCommand,- error: unknown,): SessionCommandResult<TCommand> {const result =command.kind === "send"? { status: "session_not_active" as const }: command.kind === "cancel"- ? { reason: classifyInactiveCancelTarget(error), status: "no_active_turn" as const }+ ? { status: "no_active_turn" as const }: { status: "no_active_session" as const };return result as SessionCommandResult<TCommand>;}@@ -310,14 +308,6 @@ export async function requestWorkflowTurnCancellation(});}-function classifyInactiveCancelTarget(error: unknown): string | undefined {- if (HookNotFoundError.is(error)) return "HookNotFoundError";- if (WorkflowRunNotFoundError.is(error)) return "WorkflowRunNotFoundError";- if (RunExpiredError.is(error)) return "RunExpiredError";- if (EntityConflictError.is(error)) return "EntityConflictError";- return undefined;-}-function isInactiveCommandTarget(error: unknown): boolean {if (HookNotFoundError.is(error)) return true;for (const candidate of walkCauseChain(error)) {diff --git a/packages/eve/src/execution/workflow-steps.test.ts b/packages/eve/src/execution/workflow-steps.test.tsindex c3431ca3e..e4c9b992a 100644--- a/packages/eve/src/execution/workflow-steps.test.ts+++ b/packages/eve/src/execution/workflow-steps.test.ts@@ -664,14 +664,16 @@ describe("dispatchRuntimeActionsStep", () => {vi.mocked(getCompiledRuntimeAgentBundle).mockResolvedValue(compiledBundle);vi.stubGlobal("fetch",- vi- .fn()- .mockResolvedValue(- Response.json(- { continuationToken: "remote-continuation", ok: true, sessionId: "remote-child" },- { headers: { "x-eve-session-id": "remote-child" }, status: 202 },- ),+ vi.fn().mockResolvedValue(+ Response.json(+ {+ ok: true,+ sessionId: "remote-child",+ status: "accepted",+ },+ { headers: { "x-eve-session-id": "remote-child" }, status: 202 },),+ ),);const session = setPendingRuntimeActionBatch({@@ -771,7 +773,7 @@ describe("dispatchRuntimeActionsStep", () => {.fn().mockResolvedValue(Response.json(- { sessionId: "dynamic-remote-child" },+ { ok: true, sessionId: "dynamic-remote-child", status: "accepted" },{ headers: { "x-eve-session-id": "dynamic-remote-child" }, status: 202 },),);@@ -2131,7 +2133,7 @@ describe("runProxySubagentEventStep", () => {const rekeyingAdapter: ChannelAdapter = {kind: "thread-context",async "input.requested"(_data, adapterCtx) {- adapterCtx.session.setContinuationToken("proxy-rekeyed");+ adapterCtx.session.continuation?.rekey("proxy-rekeyed");},};diff --git a/packages/eve/src/execution/workflow-steps.ts b/packages/eve/src/execution/workflow-steps.tsindex f6f59e52c..0105a4162 100644--- a/packages/eve/src/execution/workflow-steps.ts+++ b/packages/eve/src/execution/workflow-steps.ts@@ -462,7 +462,7 @@ export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResu}// Re-stamp the in-memory session's continuation token in case a- // handler called `setContinuationToken(...)` (eg. Slack auto-anchor).+ // handler called `session.continuation.rekey(...)` (eg. Slack auto-anchor).const rekeyed = reconcileSessionContinuationToken(ctx, stepResult.session);const nextSerializedContext = serializeContext(ctx);stepResult = { ...stepResult, session: rekeyed };diff --git a/packages/eve/src/harness/attachment-staging.test.ts b/packages/eve/src/harness/attachment-staging.test.tsindex a4985ee67..58f567628 100644--- a/packages/eve/src/harness/attachment-staging.test.ts+++ b/packages/eve/src/harness/attachment-staging.test.ts@@ -22,9 +22,8 @@ const STUB_ADAPTER_CTX: ChannelAdapterContext = {state: {},session: {id: "",- continuationToken: "",auth: { current: null, initiator: null },- setContinuationToken: () => {},+ continuation: { token: "", rekey: () => {} },},};diff --git a/packages/eve/src/harness/cancelled-turn-emission.test.ts b/packages/eve/src/harness/cancelled-turn-emission.test.tsindex c65f47950..9efb92bb9 100644--- a/packages/eve/src/harness/cancelled-turn-emission.test.ts+++ b/packages/eve/src/harness/cancelled-turn-emission.test.ts@@ -11,7 +11,6 @@ describe("emitCancelledTurn", () => {events.push(event);},{ sessionStarted: true, sequence: 3, stepIndex: 2, turnId: "turn_3" },- "slack:C1:T1",);expect(events.map((event) => event.type)).toEqual(["turn.cancelled", "session.waiting"]);@@ -20,7 +19,7 @@ describe("emitCancelledTurn", () => {type: "turn.cancelled",});expect(events[1]).toEqual({- data: { continuationToken: "C1:T1", wait: "next-user-message" },+ data: { continuationToken: "", wait: "next-user-message" },type: "session.waiting",});expect(next).toEqual({ sessionStarted: true, sequence: 4, stepIndex: 0, turnId: "" });@@ -37,7 +36,6 @@ describe("emitCancelledTurn", () => {events.push(event);},{ sessionStarted: false, sequence: 0, stepIndex: 0, turnId: "" },- "eve:eve:test",);expect(events[0]).toMatchObject({diff --git a/packages/eve/src/harness/cancelled-turn-emission.ts b/packages/eve/src/harness/cancelled-turn-emission.tsindex 1b1a4afa3..948779cb9 100644--- a/packages/eve/src/harness/cancelled-turn-emission.ts+++ b/packages/eve/src/harness/cancelled-turn-emission.ts@@ -15,7 +15,6 @@ import type { HarnessEmissionState } from "#harness/emission.js";export async function emitCancelledTurn(emitFn: HarnessEmitFn,state: HarnessEmissionState,- continuationToken: string,): Promise<HarnessEmissionState> {await emitFn(createTurnCancelledEvent({@@ -23,7 +22,7 @@ export async function emitCancelledTurn(turnId: activeTurnId(state),}),);- await emitFn(createSessionWaitingEvent(continuationToken));+ await emitFn(createSessionWaitingEvent());return {sessionStarted: true,diff --git a/packages/eve/src/harness/emission.ts b/packages/eve/src/harness/emission.tsindex 2ea5e212a..c7b730d7f 100644--- a/packages/eve/src/harness/emission.ts+++ b/packages/eve/src/harness/emission.ts@@ -182,7 +182,7 @@ export async function emitRecoverableFailedTurn(input: FailedStepPayload & { readonly continuationToken: string },): Promise<HarnessEmissionState> {await emitStepAndTurnFailed(emitFn, state, input);- await emitFn(createSessionWaitingEvent(input.continuationToken));+ await emitFn(createSessionWaitingEvent());return {sessionStarted: state.sessionStarted,@@ -210,7 +210,6 @@ export async function emitTurnEpilogue(emitFn: HarnessEmitFn,state: HarnessEmissionState,mode: RunMode,- continuationToken: string,): Promise<HarnessEmissionState> {await emitFn(createTurnCompletedEvent({@@ -220,7 +219,7 @@ export async function emitTurnEpilogue();if (mode === "conversation") {- await emitFn(createSessionWaitingEvent(continuationToken));+ await emitFn(createSessionWaitingEvent());} else {await emitFn(createSessionCompletedEvent());}diff --git a/packages/eve/src/harness/handles/prompt.test.ts b/packages/eve/src/harness/handles/prompt.test.tsindex c1a3406b6..64a450863 100644--- a/packages/eve/src/harness/handles/prompt.test.ts+++ b/packages/eve/src/harness/handles/prompt.test.ts@@ -32,7 +32,6 @@ const runningHandle: AgentHandle = {const parkedRemoteHandle: AgentHandle = {address: {callbackBaseUrl: "https://CALLBACK_SENTINEL.invalid",- continuationToken: "CONTINUATION_TOKEN_SENTINEL",kind: "agent/remote",sessionId: "SESSION_ID_SENTINEL_123456789",url: "https://URL_SENTINEL.invalid",@@ -64,7 +63,6 @@ describe("projectParkedAgentHandles / renderAgentsSnippet", () => {expect(snippet).toContain("(no status)");expect(snippet).not.toContain(parkedRemoteHandle.address.sessionId);- expect(snippet).not.toContain(parkedRemoteHandle.address.continuationToken);expect(snippet).not.toContain("URL_SENTINEL");expect(snippet).not.toContain("CALLBACK_SENTINEL");});diff --git a/packages/eve/src/harness/handles/store.ts b/packages/eve/src/harness/handles/store.tsindex 7c0240709..319839ded 100644--- a/packages/eve/src/harness/handles/store.ts+++ b/packages/eve/src/harness/handles/store.ts@@ -85,11 +85,6 @@ export type AgentAddress =| {readonly kind: "agent/remote";readonly sessionId: string;- /**- * Absent when the remote deployment predates continuation tokens; the- * child completes as a task-mode one-shot and can never be continued.- */- readonly continuationToken?: string;readonly url: string;readonly callbackBaseUrl: string;};@@ -181,7 +176,6 @@ const addressSchema: z.ZodType<AgentAddress> = z.discriminatedUnion("kind", [}),z.strictObject({callbackBaseUrl: z.url(),- continuationToken: nonEmptyString.optional(),kind: z.literal("agent/remote"),sessionId: nonEmptyString,url: z.url(),diff --git a/packages/eve/src/harness/instrumentation-native-events.test.ts b/packages/eve/src/harness/instrumentation-native-events.test.tsindex c9928a450..2d3bc62bc 100644--- a/packages/eve/src/harness/instrumentation-native-events.test.ts+++ b/packages/eve/src/harness/instrumentation-native-events.test.ts@@ -42,7 +42,7 @@ describe("createInstrumentationHandleEvent", () => {}),);await handleEvent(createTurnCompletedEvent({ sequence: 0, turnId: "turn-1" }));- await handleEvent(createSessionWaitingEvent("continue-1"));+ await handleEvent(createSessionWaitingEvent());expect(order).toEqual(["durable:session.started",@@ -86,7 +86,7 @@ describe("createInstrumentationHandleEvent", () => {turnId: "turn-1",})!;- await handleEvent(createSessionWaitingEvent("continue-1"));+ await handleEvent(createSessionWaitingEvent());expect(events).toEqual([{ sessionId: "session-1", turnId: "turn-1", type: "session.waiting" }]);});diff --git a/packages/eve/src/harness/runtime-actions.ts b/packages/eve/src/harness/runtime-actions.tsindex 398f6ac5b..05cdc445d 100644--- a/packages/eve/src/harness/runtime-actions.ts+++ b/packages/eve/src/harness/runtime-actions.ts@@ -245,7 +245,7 @@ export async function resolvePendingRuntimeActions(input: {if (outcome === undefined) {continue;}- if (outcome.kind === "terminal" && handle.address.continuationToken !== undefined) {+ if (outcome.kind === "terminal" && "continuationToken" in handle.address) {nextSession = clearProxyInputRequestsForChild(nextSession, handle.address.continuationToken);}const settled = settleAgentTurn(nextSession, {diff --git a/packages/eve/src/harness/session-limit-enforcement.ts b/packages/eve/src/harness/session-limit-enforcement.tsindex a3c45d49c..b5fa8afa9 100644--- a/packages/eve/src/harness/session-limit-enforcement.ts+++ b/packages/eve/src/harness/session-limit-enforcement.ts@@ -164,12 +164,7 @@ async function parkOnSessionTokenLimit(input: {);if (input.config.mode === "conversation") {- emissionState = await emitTurnEpilogue(- input.emit,- emissionState,- input.config.mode,- parkedSession.continuationToken,- );+ emissionState = await emitTurnEpilogue(input.emit, emissionState, input.config.mode);}return {diff --git a/packages/eve/src/harness/tool-loop.ts b/packages/eve/src/harness/tool-loop.tsindex daae23f32..110b80b65 100644--- a/packages/eve/src/harness/tool-loop.ts+++ b/packages/eve/src/harness/tool-loop.ts@@ -598,7 +598,7 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {turnId: activeTurnId(emissionState),}),);- await emit?.(createSessionWaitingEvent(session.continuationToken));+ await emit?.(createSessionWaitingEvent());return { next: null, session };}@@ -641,7 +641,7 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {}}- await emit?.(createSessionWaitingEvent(session.continuationToken));+ await emit?.(createSessionWaitingEvent());return { next: null, session };}@@ -693,12 +693,7 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {emissionState,config.runtimeIdentity,);- emissionState = await emitTurnEpilogue(- emit,- emissionState,- config.mode,- pending.session.continuationToken,- );+ emissionState = await emitTurnEpilogue(emit, emissionState, config.mode);return {next: null,session: setHarnessEmissionState(pending.session, emissionState),@@ -2157,12 +2152,7 @@ async function handleStepResult(input: {);if (config.mode === "conversation") {- emissionState = await emitTurnEpilogue(- emit,- emissionState,- config.mode,- parkedSession.continuationToken,- );+ emissionState = await emitTurnEpilogue(emit, emissionState, config.mode);parkedSession = setHarnessEmissionState(parkedSession, emissionState);}}@@ -2300,7 +2290,6 @@ async function emitStructuredResult(emissionState: ReturnType<typeof getHarnessEmissionState>,structured: JsonValue,mode: RunMode,- continuationToken: string,): Promise<ReturnType<typeof getHarnessEmissionState>> {await emit(createResultCompletedEvent({@@ -2310,7 +2299,7 @@ async function emitStructuredResult(turnId: emissionState.turnId,}),);- return emitTurnEpilogue(emit, emissionState, mode, continuationToken);+ return emitTurnEpilogue(emit, emissionState, mode);}/**@@ -2332,12 +2321,7 @@ async function finishTaskTurn(input: {if (schema === undefined) {if (emit) {- emissionState = await emitTurnEpilogue(- emit,- emissionState,- "task",- session.continuationToken,- );+ emissionState = await emitTurnEpilogue(emit, emissionState, "task");session = setHarnessEmissionState(session, emissionState);}return { next: { done: true, output: stepOutput ?? "" }, session };@@ -2359,13 +2343,7 @@ async function finishTaskTurn(input: {session = persistStructuredAssistantTurn(session, history, structured);if (emit) {- emissionState = await emitStructuredResult(- emit,- emissionState,- structured,- "task",- session.continuationToken,- );+ emissionState = await emitStructuredResult(emit, emissionState, structured, "task");session = setHarnessEmissionState(session, emissionState);}return { next: { done: true, output: structured }, session };@@ -2390,12 +2368,7 @@ async function finishConversationTurn(input: {if (schema === undefined) {if (emit) {- emissionState = await emitTurnEpilogue(- emit,- emissionState,- "conversation",- session.continuationToken,- );+ emissionState = await emitTurnEpilogue(emit, emissionState, "conversation");session = setHarnessEmissionState(session, emissionState);}const settledTurn = { output: stepOutput ?? "" } satisfies SettledTurn;@@ -2420,13 +2393,7 @@ async function finishConversationTurn(input: {session = persistStructuredAssistantTurn(session, history, structured);if (emit) {- emissionState = await emitStructuredResult(- emit,- emissionState,- structured,- "conversation",- session.continuationToken,- );+ emissionState = await emitStructuredResult(emit, emissionState, structured, "conversation");session = setHarnessEmissionState(session, emissionState);}const settledTurn = { output: structured } satisfies SettledTurn;diff --git a/packages/eve/src/internal/nitro/routes/channel-dispatch.test.ts b/packages/eve/src/internal/nitro/routes/channel-dispatch.test.tsindex 2a64b5e93..76f0a3769 100644--- a/packages/eve/src/internal/nitro/routes/channel-dispatch.test.ts+++ b/packages/eve/src/internal/nitro/routes/channel-dispatch.test.ts@@ -25,9 +25,8 @@ import {getInstrumentationConfig,registerInstrumentationConfig,} from "#harness/instrumentation-config.js";-import type { CancelTurnInput, DeliverInput, RunInput, Runtime } from "#channel/types.js";+import type { Runtime } from "#channel/types.js";import { readVercelProjectLink } from "#internal/vercel/project-link.js";-import type { RouteContext } from "#public/definitions/channel.js";import { resolveVercelOidcCurrentProject } from "#runtime/governance/auth/vercel-oidc-project.js";import type { ResolvedChannelDefinition } from "#runtime/types.js";import {@@ -197,10 +196,27 @@ describe("dispatchChannelRequest", () => {await expect(response.text()).resolves.toBe("ok");});- it("hands the route handler an args.receive() that hits another channel's receive", async () => {+ it("hands the route handler a ctx.to() that hits another channel's receive", async () => {const targetReceive = vi.fn().mockResolvedValue({id: "sess_target",- continuationToken: "tok",+ async send() {+ return { sessionId: "sess_target", status: "accepted" };+ },+ async respond() {+ return { sessionId: "sess_target", status: "accepted" };+ },+ async cancel() {+ return { status: "no_active_turn" };+ },+ async compact() {+ return { sessionId: "sess_target", status: "accepted" };+ },+ async clear() {+ return { sessionId: "sess_target", status: "accepted" };+ },+ async reset() {+ return { previousSessionId: "sess_target", status: "reset" };+ },async getEventStream() {return new ReadableStream();},@@ -221,9 +237,7 @@ describe("dispatchChannelRequest", () => {{handler: async (_req, args) => {capturedArgs = args;- await args.receive(targetDefinition, {- message: "handoff",- target: { foo: "bar" },+ await args.to(targetDefinition, { foo: "bar" }).send("handoff", {auth: {attributes: {},authenticator: "app",@@ -266,12 +280,12 @@ describe("dispatchChannelRequest", () => {);expect(response.status).toBe(200);- expect(typeof capturedArgs?.receive).toBe("function");+ expect(typeof capturedArgs?.to).toBe("function");expect(targetReceive).toHaveBeenCalledTimes(1);const [input, ctx] = targetReceive.mock.calls[0]!;expect(input.message).toBe("handoff");expect(input.target).toEqual({ foo: "bar" });- expect(typeof ctx.send).toBe("function");+ expect(typeof ctx.from).toBe("function");});it("tags route sends with Vercel's request id", async () => {@@ -286,9 +300,8 @@ describe("dispatchChannelRequest", () => {channels: [{handler: async (_req, args) => {- await args.send("hello", {+ await args.from("route-token").send("hello", {auth: null,- continuationToken: "route-token",});return new Response("ok");},@@ -333,8 +346,7 @@ describe("dispatchChannelRequest", () => {{handler: async (_req, args) =>Response.json(- await args.reset({- continuationToken: "direct:+15551234567:+15557654321",+ await args.from("direct:+15551234567:+15557654321").reset({reason: "User requested /new",}),),@@ -377,9 +389,7 @@ describe("dispatchChannelRequest", () => {channels: [{handler: async (_req, args) =>- Response.json(- await args.clear({ continuationToken: "direct:+15551234567:+15557654321" }),- ),+ Response.json(await args.from("direct:+15551234567:+15557654321").clear()),fetch: async () => new Response("ok"),logicalPath: "agent/channels/imessage.ts",method: "POST",@@ -420,9 +430,8 @@ describe("dispatchChannelRequest", () => {channels: [{handler: async (_req, args) => {- await args.send("hello", {+ await args.from("route-token").send("hello", {auth: null,- continuationToken: "route-token",});return new Response("ok");},@@ -451,81 +460,6 @@ describe("dispatchChannelRequest", () => {).toHaveProperty("requestId", undefined);});- it("does not mutate route-owned run and deliver inputs", async () => {- const runtimeForTest = createRuntime({- createSession: vi.fn().mockResolvedValue({- continuationToken: "route-token",- events: new ReadableStream(),- sessionId: "sess_run",- }),- dispatchContinuation: vi.fn().mockResolvedValue({- sessionId: "sess_deliver",- status: "accepted",- }),- dispatchSession: vi.fn().mockResolvedValue({ status: "accepted" }),- });- const deliverInput = Object.freeze({- auth: null,- continuationToken: "route-token",- payload: { message: "follow up" },- } satisfies DeliverInput);- const runInput = Object.freeze({- adapter: { kind: "channel:test" },- auth: null,- input: { message: "start" },- mode: "conversation",- } satisfies RunInput);- const cancelInput = Object.freeze({- sessionId: "sess_run",- turnId: "turn_1",- } satisfies CancelTurnInput);-- mockedResolveNitroChannelRuntimeBundle.mockResolvedValue({- channels: [- {- fetch: async (_request: Request, ctx: RouteContext) => {- await ctx.agent.cancelTurn(cancelInput);- await ctx.agent.deliver(deliverInput);- await ctx.agent.run(runInput);- return new Response("ok");- },- logicalPath: "agent/channels/internal.ts",- method: "POST",- name: "internal",- sourceId: "channel-internal",- sourceKind: "module",- urlPath: "/internal",- } satisfies ResolvedChannelDefinition,- ],- runtime: runtimeForTest,- });-- const response = await dispatchChannelRequest(- createEvent({- headers: { "x-vercel-id": "iad1::abc123-1710000000000-deadbeef" },- waitUntil: vi.fn(),- }),- "POST /internal",- {} as never,- );-- expect(response.status).toBe(200);- const deliveredInput = vi.mocked(runtimeForTest.dispatchContinuation).mock.calls[0]?.[0];- const startedInput = vi.mocked(runtimeForTest.createSession).mock.calls[0]?.[0];- expect(runtimeForTest.dispatchSession).toHaveBeenCalledWith({- command: { kind: "cancel", turnId: "turn_1" },- sessionId: "sess_run",- });- expect(deliveredInput).not.toBe(deliverInput);- expect(startedInput).not.toBe(runInput);- expect(deliveredInput?.command).toMatchObject({- requestId: "iad1::abc123-1710000000000-deadbeef",- });- expect(startedInput?.requestId).toBe("iad1::abc123-1710000000000-deadbeef");- expect(deliverInput).not.toHaveProperty("requestId");- expect(runInput).not.toHaveProperty("requestId");- });-it("hands websocket route handlers the same route args", async () => {const waitUntil = vi.fn<(task: Promise<unknown>) => void>();let capturedArgs: RouteHandlerArgs | undefined;@@ -567,9 +501,9 @@ describe("dispatchChannelRequest", () => {context: { ok: true },});expect(capturedArgs?.requestIp).toBe("203.0.113.4");- expect(typeof capturedArgs?.send).toBe("function");- expect(typeof capturedArgs?.getSession).toBe("function");- expect(typeof capturedArgs?.receive).toBe("function");+ expect(typeof capturedArgs?.from).toBe("function");+ expect(typeof capturedArgs?.attachSession).toBe("function");+ expect(typeof capturedArgs?.to).toBe("function");expect(waitUntil).toHaveBeenCalledTimes(1);});diff --git a/packages/eve/src/internal/nitro/routes/channel-dispatch.ts b/packages/eve/src/internal/nitro/routes/channel-dispatch.tsindex abbc571b4..d57957df0 100644--- a/packages/eve/src/internal/nitro/routes/channel-dispatch.ts+++ b/packages/eve/src/internal/nitro/routes/channel-dispatch.ts@@ -1,26 +1,16 @@import type { H3Event } from "nitro";-import type { Agent, RouteContext } from "#public/definitions/channel.js";+import type { RouteContext } from "#public/definitions/channel.js";import { getChannelInstrumentationKind } from "#channel/compiled-channel.js";-import {- createCrossChannelReceiveFn,- toCrossChannelTargets,-} from "#channel/cross-channel-receive.js";-import type { DeliverInput, RunInput, Runtime } from "#channel/types.js";+import { createCrossChannelToFn, toCrossChannelTargets } from "#channel/cross-channel-receive.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";-import { createResolveActiveSessionFn } from "#channel/resolve-active-session.js";-import { createGetSessionFn } from "#channel/session.js";+import { createChannelOperations } from "#channel/channel-operations.js";+import { createAttachSessionFn } from "#channel/session.js";import { createLogger, logError } from "#internal/logging.js";-import { RuntimeNoActiveSessionError } from "#execution/runtime-errors.js";import { readTrustedDevelopmentClientAddress } from "#internal/nitro/dev-client-address.js";import { DEVELOPMENT_WORKFLOW_SECRET_ENV } from "#internal/workflow/development-world-protocol.js";import {attachAgentInfoRouteResponse,- attachRouteAgent,+ attachRouteSessionCreator,} from "#internal/nitro/routes/channel-route-context.js";import type { NitroArtifactsConfig } from "#internal/nitro/routes/runtime-artifacts.js";import { traceChannelRequest } from "#internal/nitro/routes/channel-request-instrumentation.js";@@ -31,7 +21,6 @@ import { withVercelOidcProjectResolver } from "#runtime/governance/auth/vercel-oconst log = createLogger("channel.dispatch");interface BuiltRouteArgs {- readonly agent: Agent;readonly args: RouteHandlerArgs;readonly backgroundTasks: Promise<unknown>[];}@@ -47,11 +36,8 @@ interface BuiltRouteArgs {* Nitro forwards that work to `event.waitUntil()` so webhook* acknowledgements can return immediately.*- * Two dispatch shapes: authored channels (`defineChannel` and its- * wrappers) carry a `handler` field and receive `RouteHandlerArgs` with- * `send`, `getSession`, etc. Framework-internal channels (the- * connection callback route) build `ResolvedChannelDefinition` directly- * with just `fetch` and receive a `RouteContext` carrying `agent`.+ * Authored channels receive `RouteHandlerArgs`; framework-internal channels+ * receive the smaller `RouteContext` used by callback routes.*/export async function dispatchChannelRequest(event: H3Event,@@ -99,7 +85,6 @@ export async function dispatchChannelRequest(// Framework-internal fetch-only channel (e.g. the connection// callback route). Build a RouteContext with the agent handle.const ctx: RouteContext = {- agent: routeArgs.agent,waitUntil: routeArgs.args.waitUntil,params: routeArgs.args.params,requestIp: routeArgs.args.requestIp,@@ -213,83 +198,45 @@ function buildRouteArgs(};const channel = bundle.channels.find((candidate) => candidate.name === channelName);const adapter = channel?.adapter ?? { kind: "channel" };- const agent = createRouteAgent(bundle.runtime, requestId);- 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);- const receive = createCrossChannelReceiveFn(- bundle.runtime,- toCrossChannelTargets(bundle.channels),- );+ const channelOperations = createChannelOperations({+ adapter,+ channelName,+ metadata: { requestId },+ runtime: bundle.runtime,+ });+ const attachSession = createAttachSessionFn(bundle.runtime, { requestId });+ const to = createCrossChannelToFn(bundle.runtime, toCrossChannelTargets(bundle.channels));- const args = attachRouteAgent(+ const args = attachRouteSessionCreator(attachAgentInfoRouteResponse({- send,- resolveActiveSession,- cancel,- clear,- compact,- reset,- getSession,- receive,+ attachSession,+ ...channelOperations,params,- waitUntil,requestIp,+ to,+ waitUntil,},async () => {const { handleAgentInfoRequest } = await import("#internal/nitro/routes/info.js");return await handleAgentInfoRequest(config);},),- agent,+ async (input) =>+ await bundle.runtime.createSession({+ ...input,+ adapter,+ channelName,+ requestId,+ }),);return {- agent,args,backgroundTasks,};}-function createRouteAgent(runtime: Runtime, requestId: string | undefined): Agent {- return {- async cancelTurn(input) {- return await runtime.dispatchSession({- command: { kind: "cancel", turnId: input.turnId },- sessionId: input.sessionId,- });- },- async deliver(input) {- const deliverInput: DeliverInput = { ...input, requestId }; // Avoid mutating a frozen caller input.- const result = await runtime.dispatchContinuation({- command: {- auth: deliverInput.auth,- kind: "send",- payload: deliverInput.payload,- requestId: deliverInput.requestId,- },- continuationToken: deliverInput.continuationToken,- });- if (result.status === "session_not_active") {- throw new RuntimeNoActiveSessionError(deliverInput.continuationToken);- }- return { sessionId: result.sessionId };- },- async getEventStream(sessionId, options) {- return await runtime.getEventStream(sessionId, options);- },- async run(input) {- const runInput: RunInput = { ...input, requestId }; // Avoid mutating a frozen caller input.- return await runtime.createSession(runInput);- },- };-}-function readVercelRequestId(headers: Headers): string | undefined {const requestId = headers.get("x-vercel-id")?.trim();return requestId === "" ? undefined : requestId;diff --git a/packages/eve/src/internal/nitro/routes/channel-route-context.ts b/packages/eve/src/internal/nitro/routes/channel-route-context.tsindex 7104d6107..d0c8673ab 100644--- a/packages/eve/src/internal/nitro/routes/channel-route-context.ts+++ b/packages/eve/src/internal/nitro/routes/channel-route-context.ts@@ -1,14 +1,17 @@import type { RouteHandlerArgs } from "#channel/routes.js";-import type { Agent } from "#public/definitions/channel.js";+import type { RunHandle, RunInput } from "#channel/types.js";type AgentInfoRouteResponse = () => Promise<Response>;+export type RouteSessionCreator = (+ input: Omit<RunInput, "adapter" | "channelName" | "requestId">,+) => Promise<RunHandle>;const agentInfoRouteResponseKey = "__eveAgentInfoRouteResponse";-const routeAgentKey = "__eveRouteAgent";+const routeSessionCreatorKey = "__eveRouteSessionCreator";type InternalRouteArgs = RouteHandlerArgs & {[agentInfoRouteResponseKey]?: AgentInfoRouteResponse;- [routeAgentKey]?: Agent;+ [routeSessionCreatorKey]?: RouteSessionCreator;};export function attachAgentInfoRouteResponse<TArgs extends RouteHandlerArgs>(@@ -27,13 +30,16 @@ export function readAgentInfoRouteResponse(return routeArgs[agentInfoRouteResponseKey];}-export function attachRouteAgent<TArgs extends RouteHandlerArgs>(args: TArgs, agent: Agent): TArgs {+export function attachRouteSessionCreator<TArgs extends RouteHandlerArgs>(+ args: TArgs,+ createSession: RouteSessionCreator,+): TArgs {const routeArgs: InternalRouteArgs = args;- routeArgs[routeAgentKey] = agent;+ routeArgs[routeSessionCreatorKey] = createSession;return args;}-export function readRouteAgent(args: RouteHandlerArgs): Agent | undefined {+export function readRouteSessionCreator(args: RouteHandlerArgs): RouteSessionCreator | undefined {const routeArgs: InternalRouteArgs = args;- return routeArgs[routeAgentKey];+ return routeArgs[routeSessionCreatorKey];}diff --git a/packages/eve/src/internal/structural-tests/file-length.test.ts b/packages/eve/src/internal/structural-tests/file-length.test.tsindex f422f8808..52209b567 100644--- a/packages/eve/src/internal/structural-tests/file-length.test.ts+++ b/packages/eve/src/internal/structural-tests/file-length.test.ts@@ -22,7 +22,6 @@ const LONG_SOURCE_FILE_ALLOWLIST = new Set<string>(["public/channels/eve.ts","public/channels/auth.ts","public/channels/slack/slackChannel.ts",- "public/channels/discord/discordChannel.ts","public/channels/teams/teamsChannel.ts",]);diff --git a/packages/eve/src/internal/testing/mocks/mock-channel-operations.ts b/packages/eve/src/internal/testing/mocks/mock-channel-operations.tsnew file mode 100644index 000000000..a9a3b3aba--- /dev/null+++ b/packages/eve/src/internal/testing/mocks/mock-channel-operations.ts@@ -0,0 +1,62 @@+import type { UserContent } from "ai";++import type {+ ChannelReceiveContext,+ ChannelRespondOptions,+ ChannelSendOptions,+ InternalChannelSource,+} from "#channel/channel-operations.js";+import { INTERNAL_CHANNEL_DELIVER } from "#channel/channel-operations.js";+import type { InputResponse } from "#runtime/input/types.js";++export type ObservedChannelDelivery<TState> =+ | (ChannelSendOptions<TState> & { readonly message: string | UserContent })+ | (ChannelRespondOptions & { readonly inputResponses: readonly InputResponse[] });++type DeliveryObserver<TState> = (+ continuationToken: string,+ input: ObservedChannelDelivery<TState>,+) => unknown;++/** Creates a channel receive context backed by a test-owned delivery observer. */+export function mockChannelContext<TState = undefined>(+ observeDelivery: DeliveryObserver<TState>,+): ChannelReceiveContext<TState> {+ return {+ from(continuationToken) {+ const source: InternalChannelSource<TState> = {+ async send(message, options) {+ return (await observeDelivery(continuationToken, { ...options, message })) as never;+ },+ async respond(inputResponses, options) {+ return (await observeDelivery(continuationToken, {+ ...options,+ inputResponses,+ })) as never;+ },+ async cancel() {+ return { status: "no_active_turn" } as never;+ },+ async compact() {+ return { status: "no_active_session" } as never;+ },+ async clear() {+ return { status: "no_active_session" } as never;+ },+ async reset() {+ return { status: "no_active_session" } as never;+ },+ async [INTERNAL_CHANNEL_DELIVER](payload, options) {+ return (await observeDelivery(continuationToken, {+ ...options,+ ...payload,+ } as ObservedChannelDelivery<TState>)) as never;+ },+ };+ return source;+ },+ async resolveSession() {+ return undefined;+ },+ };+}diff --git a/packages/eve/src/internal/testing/route-harness.ts b/packages/eve/src/internal/testing/route-harness.tsdeleted file mode 100644index 08c080562..000000000--- a/packages/eve/src/internal/testing/route-harness.ts+++ /dev/null@@ -1,84 +0,0 @@-import type { Mock } from "vitest";-import { vi } from "vitest";--import type { Agent, RouteContext } from "#public/definitions/channel.js";--/**- * Reusable primitives for testing channel routes that depend on the- * framework-ctx surface (`agent.run`, `agent.deliver`, `waitUntil`).- *- * Kept internal so unit tests can wire up the minimum needed to exercise- * the `fetch` handler without pulling in real runtime machinery.- */--/**- * Observable mock {@link Agent}. The `run` / `deliver` / `cancelTurn` / `getEventStream`- * methods are `vi.fn()` instances, so tests can assert on call counts,- * arguments, and reorder return values mid-test with `mockResolvedValueOnce`.- */-export interface MockAgent extends Agent {- readonly cancelTurn: Mock;- readonly run: Mock;- readonly deliver: Mock;- readonly getEventStream: Mock;-}--/**- * Builds a {@link MockAgent} with sensible default resolved values:- *- * - `run` resolves to a fake handle whose `result` is `{ status: "completed", output: "ok" }`.- * - `deliver` resolves to `undefined`.- * - `getEventStream` resolves to an empty `ReadableStream`.- *- * Override individual methods with `mockResolvedValueOnce` /- * `mockRejectedValueOnce` etc. when you need a different per-test flow.- */-export function createMockAgent(): MockAgent {- return {- cancelTurn: vi.fn().mockResolvedValue({ status: "no_active_turn" }),- deliver: vi.fn().mockResolvedValue(undefined),- getEventStream: vi.fn().mockResolvedValue(new ReadableStream()),- run: vi.fn().mockResolvedValue({- continuationToken: "http:test",- events: new ReadableStream(),- result: Promise.resolve({ output: "ok", status: "completed" as const }),- sessionId: "test-session-id",- }),- } satisfies MockAgent;-}--/**- * Builds a minimal {@link RouteContext} for tests. `waitUntil` is a- * no-op, `params` is empty, and `requestIp` defaults to `127.0.0.1`- * unless overridden.- */-export function createRouteContext(input: {- readonly agent: Agent;- readonly params?: Readonly<Record<string, string>>;- readonly requestIp?: string;-}): RouteContext {- return {- agent: input.agent,- params: input.params ?? {},- requestIp: input.requestIp ?? "127.0.0.1",- waitUntil: () => undefined,- };-}--/**- * Canonical URL for the HTTP message route. Hoisted into a constant so- * tests stay independent of the actual mount path constant.- */-export const HTTP_CREATE_ROUTE_URL = "https://example.com/eve/v1/session";-export const HTTP_CONTINUE_ROUTE_URL = "https://example.com/eve/v1/session";--/**- * Builds a JSON POST `Request` for the HTTP message route.- */-export function createJsonMessageRequest(body: unknown): Request {- return new Request(HTTP_CREATE_ROUTE_URL, {- body: JSON.stringify(body),- headers: { "content-type": "application/json" },- method: "POST",- });-}diff --git a/packages/eve/src/internal/testing/scenario-apps/custom-channel-portability.ts b/packages/eve/src/internal/testing/scenario-apps/custom-channel-portability.tsindex 721baeedc..9a0d6d092 100644--- a/packages/eve/src/internal/testing/scenario-apps/custom-channel-portability.ts+++ b/packages/eve/src/internal/testing/scenario-apps/custom-channel-portability.ts@@ -12,18 +12,17 @@ export default defineChannel({},routes: [- POST("/api/message", async (req, { send }) => {+ POST("/api/message", async (req, { from }) => {const body = await req.json();- const session = await send(body.message, {+ const session = await from("test:" + crypto.randomUUID()).send(body.message, {auth: null,- continuationToken: "test:" + crypto.randomUUID(),state: { lastSender: body.userId ?? "anonymous" },});- return Response.json({ sessionId: session.id, continuationToken: session.continuationToken });+ return Response.json({ sessionId: session.id });}),- GET("/api/stream/:sessionId", async (req, { getSession, params }) => {- const session = getSession(params.sessionId);+ GET("/api/stream/:sessionId", async (req, { attachSession, params }) => {+ const session = attachSession(params.sessionId);const events = await session.getEventStream();return new Response(events, { headers: { "content-type": "text/event-stream" } });}),diff --git a/packages/eve/src/internal/testing/scenario-apps/session-reset.ts b/packages/eve/src/internal/testing/scenario-apps/session-reset.tsindex 89877ea0a..c68115cac 100644--- a/packages/eve/src/internal/testing/scenario-apps/session-reset.ts+++ b/packages/eve/src/internal/testing/scenario-apps/session-reset.ts@@ -18,22 +18,20 @@ const AUTH = {export default defineChannel({routes: [- POST("/session-reset/:threadId/messages", async (request, { params, send }) => {+ POST("/session-reset/:threadId/messages", async (request, { from, params }) => {const body = (await request.json().catch(() => ({}))) as { message?: string };- const session = await send(body.message ?? "Reply with hello.", {+ const session = await from(params.threadId ?? "").send(body.message ?? "Reply with hello.", {auth: AUTH,- continuationToken: params.threadId ?? "",});return Response.json({ sessionId: session.id });}),- POST("/session-reset/:threadId/owner", async (_request, { params, resolveActiveSession }) => {- const owner = await resolveActiveSession({ continuationToken: params.threadId ?? "" });- return Response.json({ sessionId: owner?.sessionId ?? null });+ POST("/session-reset/:threadId/owner", async (_request, { params, resolveSession }) => {+ const owner = await resolveSession(params.threadId ?? "");+ return Response.json({ sessionId: owner?.id ?? null });}),- POST("/session-reset/:threadId/new", async (_request, { params, reset }) => {+ POST("/session-reset/:threadId/new", async (_request, { from, params }) => {return Response.json(- await reset({- continuationToken: params.threadId ?? "",+ await from(params.threadId ?? "").reset({reason: "Vercel session reset integration test",}),);diff --git a/packages/eve/src/protocol/cancel-turn.test.ts b/packages/eve/src/protocol/cancel-turn.test.tsindex d26d5fcb5..c99d6ed65 100644--- a/packages/eve/src/protocol/cancel-turn.test.ts+++ b/packages/eve/src/protocol/cancel-turn.test.ts@@ -3,12 +3,32 @@ import { describe, expect, it } from "vitest";import { CancelTurnResponseSchema } from "#protocol/cancel-turn.js";describe("CancelTurnResponseSchema", () => {- it.each(["accepted", "no_active_turn"] as const)("accepts the %s outcome", (status) => {+ it("accepts the asynchronous accepted outcome", () => {expect(- CancelTurnResponseSchema.safeParse({ ok: true, sessionId: "session-1", status }).success,+ CancelTurnResponseSchema.safeParse({+ ok: true,+ sessionId: "session-1",+ status: "accepted",+ }).success,).toBe(true);});+ it("accepts an inactive outcome without a session id", () => {+ expect(CancelTurnResponseSchema.safeParse({ ok: true, status: "no_active_turn" }).success).toBe(+ true,+ );+ });++ it("rejects a session id on an inactive outcome", () => {+ expect(+ CancelTurnResponseSchema.safeParse({+ ok: true,+ sessionId: "session-1",+ status: "no_active_turn",+ }).success,+ ).toBe(false);+ });+it("rejects the former in-progress wording", () => {expect(CancelTurnResponseSchema.safeParse({diff --git a/packages/eve/src/protocol/cancel-turn.ts b/packages/eve/src/protocol/cancel-turn.tsindex 1ea500896..d6a9fad89 100644--- a/packages/eve/src/protocol/cancel-turn.ts+++ b/packages/eve/src/protocol/cancel-turn.ts@@ -3,16 +3,23 @@ import { z } from "#compiled/zod/index.js";/** Outcome of requesting cooperative turn cancellation. */export type CancelTurnStatus = "accepted" | "no_active_turn";+/** Transport-independent result of requesting cooperative turn cancellation. */+export type CancelTurnResult =+ | { readonly sessionId: string; readonly status: "accepted" }+ | { readonly status: "no_active_turn" };+/** Successful standard turn-cancellation response. */-export interface CancelTurnResponse {- readonly ok: true;- readonly sessionId: string;- readonly status: CancelTurnStatus;-}+export type CancelTurnResponse = CancelTurnResult & { readonly ok: true };/** Successful response returned by the standard turn-cancellation route. */-export const CancelTurnResponseSchema: z.ZodType<CancelTurnResponse> = z.object({- ok: z.literal(true),- sessionId: z.string().min(1),- status: z.enum(["accepted", "no_active_turn"]),-});+export const CancelTurnResponseSchema: z.ZodType<CancelTurnResponse> = z.discriminatedUnion(+ "status",+ [+ z.strictObject({+ ok: z.literal(true),+ sessionId: z.string().min(1),+ status: z.literal("accepted"),+ }),+ z.strictObject({ ok: z.literal(true), status: z.literal("no_active_turn") }),+ ],+);diff --git a/packages/eve/src/protocol/message.ts b/packages/eve/src/protocol/message.tsindex 41de239cd..2fa37aa13 100644--- a/packages/eve/src/protocol/message.ts+++ b/packages/eve/src/protocol/message.ts@@ -132,26 +132,14 @@ export interface RuntimeIdentity {*/export type HandleMessageRequestBody =| {+ readonly inputResponses?: never;readonly message: string | UserContent;readonly clientContext?: string | readonly string[] | JsonObject;readonly outputSchema?: JsonObject;}| {- readonly continuationToken: string;- readonly message: string | UserContent;- readonly clientContext?: string | readonly string[] | JsonObject;- readonly outputSchema?: JsonObject;- }- | {- readonly continuationToken: string;readonly inputResponses: readonly InputResponse[];- readonly clientContext?: string | readonly string[] | JsonObject;- readonly outputSchema?: JsonObject;- }- | {- readonly continuationToken: string;- readonly inputResponses: readonly InputResponse[];- readonly message: string | UserContent;+ readonly message?: never;readonly clientContext?: string | readonly string[] | JsonObject;readonly outputSchema?: JsonObject;};@@ -595,7 +583,7 @@ export interface AuthorizationCompletedStreamEvent {*/export interface SessionWaitingStreamEvent {data: {- /** Channel-owned resume handle for the next user turn. */+ /** Channel-local continuation token, or the immutable session ID for an ID-only session. */continuationToken: string;wait: "next-user-message";};@@ -1451,7 +1439,7 @@ export function createCompactionCompletedEvent(input: {* wait.*/export function createSessionWaitingEvent(- namespacedContinuationToken: string,+ namespacedContinuationToken: string = "",): SessionWaitingStreamEvent {return {data: {diff --git a/packages/eve/src/protocol/reset-session.ts b/packages/eve/src/protocol/reset-session.tsindex dfeb72bb2..dfc814910 100644--- a/packages/eve/src/protocol/reset-session.ts+++ b/packages/eve/src/protocol/reset-session.ts@@ -1,6 +1,6 @@import { z } from "#compiled/zod/index.js";-/** Outcome of retiring the owner of a continuation token. */+/** Outcome of retiring one exact durable session. */export type ResetStatus = "no_active_session" | "reset";/** Successful response returned by the standard session-reset route. */diff --git a/packages/eve/src/protocol/routes.ts b/packages/eve/src/protocol/routes.tsindex 36ef897b1..ec4b339e6 100644--- a/packages/eve/src/protocol/routes.ts+++ b/packages/eve/src/protocol/routes.ts@@ -16,46 +16,26 @@ export const EVE_HEALTH_ROUTE_PATH = `${EVE_ROUTE_PREFIX}/health`;*/export const EVE_INFO_ROUTE_PATH = `${EVE_ROUTE_PREFIX}/info`;-/**- * Stable framework-owned route for creating a new session.- */-export const EVE_CREATE_SESSION_ROUTE_PATH = `${EVE_ROUTE_PREFIX}/session`;+/** Stable route for creating ID-addressed sessions. */+export const EVE_SESSION_ROUTE_PATH = `${EVE_ROUTE_PREFIX}/session`;-/**- * Stable framework-owned route for retiring the session that owns a client- * continuation token. The request body supplies the channel-local token.- */-export const EVE_RESET_SESSION_ROUTE_PATH = `${EVE_ROUTE_PREFIX}/session/reset`;+/** Stable route pattern for sending a message to one exact session ID. */+export const EVE_SESSION_ROUTE_PATTERN = `${EVE_SESSION_ROUTE_PATH}/:sessionId`;-/**- * Stable framework-owned route for compacting the session that owns a client- * continuation token. The request body supplies the channel-local token.- */-export const EVE_COMPACT_SESSION_ROUTE_PATH = `${EVE_ROUTE_PREFIX}/session/compact`;+/** Stable route pattern for cancelling one exact session ID. */+export const EVE_SESSION_CANCEL_ROUTE_PATTERN = `${EVE_SESSION_ROUTE_PATH}/:sessionId/cancel`;-/**- * 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 route pattern for compacting one exact session ID. */+export const EVE_SESSION_COMPACT_ROUTE_PATTERN = `${EVE_SESSION_ROUTE_PATH}/:sessionId/compact`;-/**- * Stable framework-owned route pattern for sending a message to an existing- * session.- */-export const EVE_CONTINUE_SESSION_ROUTE_PATTERN = `${EVE_ROUTE_PREFIX}/session/:sessionId`;+/** Stable route pattern for clearing one exact session ID. */+export const EVE_SESSION_CLEAR_ROUTE_PATTERN = `${EVE_SESSION_ROUTE_PATH}/:sessionId/clear`;-/**- * Stable framework-owned message stream route pattern.- */-export const EVE_MESSAGE_STREAM_ROUTE_PATTERN = `${EVE_ROUTE_PREFIX}/session/:sessionId/stream`;+/** Stable route pattern for resetting one exact session ID. */+export const EVE_SESSION_RESET_ROUTE_PATTERN = `${EVE_SESSION_ROUTE_PATH}/:sessionId/reset`;-/**- * Stable framework-owned route pattern for cancelling a session's- * in-flight turn. Accepts an optional `{ turnId }` body guard scoping- * the cancel to the turn the caller observed.- */-export const EVE_CANCEL_TURN_ROUTE_PATTERN = `${EVE_ROUTE_PREFIX}/session/:sessionId/cancel`;+/** Stable event-stream route pattern for one exact session ID. */+export const EVE_SESSION_STREAM_ROUTE_PATTERN = `${EVE_SESSION_ROUTE_PATH}/:sessionId/stream`;/*** Framework-owned route pattern for dispatching one authored schedule@@ -65,7 +45,7 @@ export const EVE_CANCEL_TURN_ROUTE_PATTERN = `${EVE_ROUTE_PREFIX}/session/:sessi* never mount this route. Smoke tests and human developers use it to* trigger a schedule out-of-band (without a cron firing) and recover the* resulting `{ scheduleId, sessionIds }` payload as JSON so they can- * subscribe to {@link EVE_MESSAGE_STREAM_ROUTE_PATTERN} for each session.+ * subscribe to {@link EVE_SESSION_STREAM_ROUTE_PATTERN} for each session.** `:scheduleId` is the authored schedule's filesystem-derived name (e.g.* `agent/schedules/heartbeat.ts` -> `"heartbeat"`).@@ -127,25 +107,34 @@ export const EVE_CONNECTION_CALLBACK_ROUTE_PATTERN = `${EVE_ROUTE_PREFIX}/connec*/export const EVE_CALLBACK_ROUTE_PATTERN = `${EVE_ROUTE_PREFIX}/callback/:token`;-/**- * Creates the stable framework-owned message stream route path for one session.- */-export function createEveMessageStreamRoutePath(sessionId: string): string {- return `${EVE_ROUTE_PREFIX}/session/${encodeURIComponent(sessionId)}/stream`;+/** Builds the ID-addressed message route for one session. */+export function createEveSessionRoutePath(sessionId: string): string {+ return `${EVE_SESSION_ROUTE_PATH}/${encodeURIComponent(sessionId)}`;}-/**- * Creates the stable framework-owned continue-session route path.- */-export function createEveContinueSessionRoutePath(sessionId: string): string {- return `${EVE_ROUTE_PREFIX}/session/${encodeURIComponent(sessionId)}`;+/** Builds the ID-addressed cancel route for one session. */+export function createEveSessionCancelRoutePath(sessionId: string): string {+ return `${EVE_SESSION_ROUTE_PATH}/${encodeURIComponent(sessionId)}/cancel`;}-/**- * Creates the stable framework-owned cancel-turn route path for one session.- */-export function createEveCancelTurnRoutePath(sessionId: string): string {- return `${EVE_ROUTE_PREFIX}/session/${encodeURIComponent(sessionId)}/cancel`;+/** Builds the ID-addressed compact route for one session. */+export function createEveSessionCompactRoutePath(sessionId: string): string {+ return `${EVE_SESSION_ROUTE_PATH}/${encodeURIComponent(sessionId)}/compact`;+}++/** Builds the ID-addressed clear route for one session. */+export function createEveSessionClearRoutePath(sessionId: string): string {+ return `${EVE_SESSION_ROUTE_PATH}/${encodeURIComponent(sessionId)}/clear`;+}++/** Builds the ID-addressed reset route for one session. */+export function createEveSessionResetRoutePath(sessionId: string): string {+ return `${EVE_SESSION_ROUTE_PATH}/${encodeURIComponent(sessionId)}/reset`;+}++/** Builds the ID-addressed event-stream route for one session. */+export function createEveSessionStreamRoutePath(sessionId: string): string {+ return `${EVE_SESSION_ROUTE_PATH}/${encodeURIComponent(sessionId)}/stream`;}/**diff --git a/packages/eve/src/public/channels/auth.test.ts b/packages/eve/src/public/channels/auth.test.tsindex 72bb9a97f..e2d2459da 100644--- a/packages/eve/src/public/channels/auth.test.ts+++ b/packages/eve/src/public/channels/auth.test.ts@@ -1,7 +1,7 @@import { exportJWK, exportSPKI, generateKeyPair, SignJWT } from "jose";import { afterEach, describe, expect, it, vi } from "vitest";-import { EVE_CREATE_SESSION_ROUTE_PATH } from "#protocol/routes.js";+import { EVE_SESSION_ROUTE_PATH } from "#protocol/routes.js";import type { SessionAuthContext } from "#channel/types.js";import { withVercelOidcProjectResolver } from "#runtime/governance/auth/vercel-oidc-project.js";import {@@ -28,7 +28,7 @@ import {withAuthChallenges,} from "#public/channels/auth.js";-const TEST_ROUTE_URL = `https://example.com${EVE_CREATE_SESSION_ROUTE_PATH}`;+const TEST_ROUTE_URL = `https://example.com${EVE_SESSION_ROUTE_PATH}`;describe("verifyHttpBasic", () => {it("returns ok with the authenticated principal when credentials match", () => {diff --git a/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.test.ts b/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.test.tsindex 812cd59be..455a64b10 100644--- a/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.test.ts+++ b/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.test.ts@@ -6,6 +6,7 @@ import { isCompiledChannel, type CompiledChannel } from "#channel/compiled-channimport { isHttpRouteDefinition } from "#channel/routes.js";import { ContextContainer, contextStorage } from "#context/container.js";import { SessionKey } from "#context/keys.js";+import { mockChannelContext } from "#internal/testing/mocks/mock-channel-operations.js";import type { UnstampedMessageStreamEvent } from "#protocol/message.js";import {chatSdkChannel,@@ -13,7 +14,7 @@ import {messageToUserContent,type ChatSdkChannelState,} from "#public/channels/chat-sdk/index.js";-import type { CancelFn, RouteHandlerArgs, SendFn } from "#public/definitions/channel.js";+import type { RouteHandlerArgs } from "#public/definitions/channel.js";import type {Adapter,AdapterPostableMessage,@@ -88,9 +89,9 @@ async function firePost(path: string,body: Record<string, unknown>,): Promise<{- cancel: ReturnType<typeof vi.fn<CancelFn>>;+ cancel: ReturnType<typeof vi.fn>;response: Response;- send: ReturnType<typeof vi.fn<SendFn<ChatSdkChannelState>>>;+ send: ReturnType<typeof vi.fn>;waitUntil: ReturnType<typeof vi.fn>;}> {const compiled = asCompiled<ChatSdkChannelState>(channel);@@ -98,21 +99,10 @@ async function firePost(if (!post || !isHttpRouteDefinition(post)) {throw new Error(`Expected POST ${path}.`);}- const send = vi.fn<SendFn<ChatSdkChannelState>>().mockResolvedValue({- continuationToken: "chat-sdk:test",- id: "session-1",- async cancel() {- return { status: "no_active_turn" as const };- },- async getEventStream() {- return new ReadableStream();- },- async getStreamTailIndex() {- return -1;- },- });- const cancel = vi.fn<CancelFn>().mockResolvedValue({ status: "accepted" });+ const send = vi.fn().mockResolvedValue({ id: "session-1" });+ const cancel = vi.fn().mockResolvedValue({ sessionId: "session-1", status: "accepted" });const waitUntil = vi.fn();+ const channelContext = mockChannelContext<ChatSdkChannelState>(send);const response = await post.handler(new Request(`https://example.com${path}`, {@@ -121,16 +111,17 @@ async function firePost(method: "POST",}),{- getSession: vi.fn() as any,- resolveActiveSession: async () => undefined,- cancel,- clear: vi.fn(),- compact: vi.fn(),- reset: vi.fn(),+ from(continuationToken) {+ return {+ ...channelContext.from(continuationToken),+ cancel: () => cancel({ continuationToken }) as never,+ };+ },+ resolveSession: channelContext.resolveSession,+ attachSession: vi.fn() as any,params: {},- receive: vi.fn() as any,+ to: vi.fn() as any,requestIp: null,- send,waitUntil,} satisfies RouteHandlerArgs<ChatSdkChannelState>,);@@ -180,16 +171,11 @@ describe("chatSdkChannel", () => {const response = await get.handler(new Request("https://example.com/eve/v1/test?crc_token=abc123", { method: "GET" }),{- getSession: vi.fn() as any,- resolveActiveSession: async () => undefined,- cancel: vi.fn(),- clear: vi.fn(),- compact: vi.fn(),- reset: vi.fn(),+ ...mockChannelContext(vi.fn()),+ attachSession: vi.fn() as any,params: {},- receive: vi.fn() as any,+ to: vi.fn() as any,requestIp: null,- send: vi.fn() as any,waitUntil: vi.fn(),} satisfies RouteHandlerArgs<ChatSdkChannelState>,);@@ -198,7 +184,7 @@ describe("chatSdkChannel", () => {expect(await response.json()).toEqual({ response_token: "sha256=abc123" });});- it("hands Chat SDK mentions to Eve through bridge.send", async () => {+ it("hands Chat SDK mentions to eve through bridge.send", async () => {const adapter = testAdapter();const bridge = chatSdkChannel({adapters: { test: adapter },@@ -218,10 +204,10 @@ describe("chatSdkChannel", () => {expect(response.status).toBe(200);expect(cancel).not.toHaveBeenCalled();expect(send).toHaveBeenCalledTimes(1);- expect(send.mock.calls[0]?.[0]).toBe("@bot hello");+ expect(send.mock.calls[0]?.[0]).toBe(THREAD_ID);expect(send.mock.calls[0]?.[1]).toMatchObject({auth: AUTH,- continuationToken: THREAD_ID,+ message: "@bot hello",state: {thread: {_type: "chat:Thread",@@ -256,9 +242,9 @@ describe("chatSdkChannel", () => {expect(response.status).toBe(200);expect(cancel).toHaveBeenCalledWith({ continuationToken: THREAD_ID });- expect(send).toHaveBeenCalledWith("@bot correction", {+ expect(send).toHaveBeenCalledWith(THREAD_ID, {auth: AUTH,- continuationToken: THREAD_ID,+ message: "@bot correction",state: {thread: expect.objectContaining({adapterName: "test",@@ -291,8 +277,10 @@ describe("chatSdkChannel", () => {expect(response.status).toBe(200);expect(cancel).not.toHaveBeenCalled();expect(send).toHaveBeenCalledWith(- { inputResponses: [{ optionId: "approve", requestId: "request-1" }] },- expect.objectContaining({ continuationToken: THREAD_ID }),+ THREAD_ID,+ expect.objectContaining({+ inputResponses: [{ optionId: "approve", requestId: "request-1" }],+ }),);});@@ -318,19 +306,7 @@ describe("chatSdkChannel", () => {state: memoryState(),userName: "bot",});- const send = vi.fn<SendFn<ChatSdkChannelState>>().mockResolvedValue({- continuationToken: "chat-sdk:test",- id: "session-1",- async cancel() {- return { status: "no_active_turn" as const };- },- async getEventStream() {- return new ReadableStream();- },- async getStreamTailIndex() {- return -1;- },- });+ const send = vi.fn().mockResolvedValue({ id: "session-1" });await bridge.channel.receive?.({@@ -338,12 +314,12 @@ describe("chatSdkChannel", () => {message: "proactive",target: { adapterName: "test", threadId: THREAD_ID },},- { send },+ mockChannelContext(send),);- expect(send).toHaveBeenCalledWith("proactive", {+ expect(send).toHaveBeenCalledWith(THREAD_ID, {auth: AUTH,- continuationToken: THREAD_ID,+ message: "proactive",state: {thread: {_type: "chat:Thread",@@ -357,7 +333,7 @@ describe("chatSdkChannel", () => {});});- it("posts completed Eve messages as markdown through the stored Chat SDK thread", async () => {+ it("posts completed eve messages as markdown through the stored Chat SDK thread", async () => {const adapter = testAdapter();const bridge = chatSdkChannel({adapters: { test: adapter },@@ -622,19 +598,16 @@ describe("chatSdkChannel", () => {value: "approve",});- expect(send).toHaveBeenCalledWith(- { inputResponses: [{ optionId: "approve", requestId: "request-1" }] },- {- auth: null,- continuationToken: THREAD_ID,- state: {- thread: expect.objectContaining({- adapterName: "test",- id: THREAD_ID,- }),- },+ expect(send).toHaveBeenCalledWith(THREAD_ID, {+ auth: null,+ inputResponses: [{ optionId: "approve", requestId: "request-1" }],+ state: {+ thread: expect.objectContaining({+ adapterName: "test",+ id: THREAD_ID,+ }),},- );+ });});});diff --git a/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.ts b/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.tsindex 516cd531e..a93f001bc 100644--- a/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.ts+++ b/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.ts@@ -1,3 +1,13 @@+import type { UserContent } from "ai";++import type { ChannelAddressDeliveryOptions } from "#channel/channel-address.js";+import {+ INTERNAL_CHANNEL_DELIVER,+ type ChannelFrom,+ type InternalChannelSource,+} from "#channel/channel-operations.js";+import { normalizeSendInput } from "#channel/send-input.js";+import type { SendPayload } from "#channel/routes.js";import type { SessionAuthContext } from "#channel/types.js";import { ContextContainer, contextStorage } from "#context/container.js";import { ContextKey } from "#context/key.js";@@ -29,11 +39,8 @@ import {POST,type Channel,type ChannelEvents,- type ChannelSessionOps,- type CancelFn,+ type ChannelContinuationOps,type RouteHandlerArgs,- type SendFn,- type SendOptions,type Session,} from "#public/definitions/channel.js";@@ -44,23 +51,20 @@ const DEFAULT_STREAMING_EDIT_INTERVAL_MS = 1_000;const MAX_TYPING_STATUS = 80;type ChatSdkAdapters = Record<string, Adapter>;-type ChatSdkSendInput = Parameters<SendFn<ChatSdkChannelState>>[0];+type ChatSdkSendInput = string | UserContent | SendPayload;+type MutableDeliveryOptions<TState> = {+ -readonly [Key in keyof ChannelAddressDeliveryOptions<TState>]: ChannelAddressDeliveryOptions<TState>[Key];+};type EventData<T extends UnstampedMessageStreamEvent["type"]> =Extract<UnstampedMessageStreamEvent, { type: T }> extends { data: infer D } ? D : undefined;interface ActiveWebhookContext {- readonly cancel: CancelFn;- readonly send: SendFn<ChatSdkChannelState>;+ readonly from: ChannelFrom<ChatSdkChannelState>;}const ActiveWebhookKey = new ContextKey<ActiveWebhookContext>("chat-sdk.active-webhook");-/**- * Durable channel state used by `chatSdkChannel`. Stores the last Chat SDK- * thread for the Eve session so event handlers can post replies without- * depending on hidden Chat SDK subscription state, plus the bookkeeping the- * default handlers use to stream assistant output and surface typing status.- */+/** Durable Chat SDK thread state plus default-handler streaming bookkeeping. */export interface ChatSdkChannelState extends Record<string, unknown> {thread: SerializedThread | null;/** Message id of the in-flight streamed assistant post (edit fallback). */@@ -91,7 +95,7 @@ export interface ChatSdkReceiveTarget {}/**- * Channel-owned metadata exposed to Eve instrumentation.+ * Channel-owned metadata exposed to eve instrumentation.*/export interface ChatSdkInstrumentationMetadata extends Record<string, unknown> {readonly adapterName: string | null;@@ -115,9 +119,9 @@ export interface ChatSdkChannelContext<TAdapters extends ChatSdkAdapters = ChatSreadonly streamingEditIntervalMs: number;}-/** Event-handler context for `chatSdkChannel`, including Eve session helpers. */+/** Event-handler context for `chatSdkChannel`, including continuation routing. */export interface ChatSdkEventContext<TAdapters extends ChatSdkAdapters = ChatSdkAdapters>- extends ChatSdkChannelContext<TAdapters>, ChannelSessionOps {}+ extends ChatSdkChannelContext<TAdapters>, ChannelContinuationOps {}/*** Per-event handlers for `chatSdkChannel({ events })`. Each supplied handler@@ -128,12 +132,12 @@ export type ChatSdkChannelEvents<TAdapters extends ChatSdkAdapters = ChatSdkAdap/*** Options for `bridge.send(...)` inside Chat SDK handlers. The `thread`- * determines the Eve continuation token and the persisted channel state.+ * determines the eve continuation token and the persisted channel state.*/export interface ChatSdkSendOptions {readonly auth?: SessionAuthContext | null;- readonly callback?: SendOptions<ChatSdkChannelState>["callback"];- readonly mode?: SendOptions<ChatSdkChannelState>["mode"];+ readonly callback?: ChannelAddressDeliveryOptions<ChatSdkChannelState>["callback"];+ readonly mode?: ChannelAddressDeliveryOptions<ChatSdkChannelState>["mode"];readonly thread: SerializedThread | Thread | string;readonly title?: string;/**@@ -153,7 +157,7 @@ export interface ChatSdkSendOptions {/*** Configuration for {@link chatSdkChannel}. It accepts normal Chat SDK- * `ChatConfig` fields, plus Eve route and event settings.+ * `ChatConfig` fields, plus eve route and event settings.*/export interface ChatSdkChannelConfig<TAdapters extends ChatSdkAdapters = ChatSdkAdapters,@@ -171,12 +175,12 @@ export interface ChatSdkChannelConfig<* settings.*/readonly routes?: Partial<Record<Extract<keyof TAdapters, string>, string>>;- /** Extra Chat SDK webhook options. Eve owns `waitUntil`. */+ /** Extra Chat SDK webhook options. eve owns `waitUntil`. */readonly webhook?: Omit<WebhookOptions, "waitUntil">;- /** Optional Eve event handlers. Supplied handlers replace built-in defaults. */+ /** Optional eve event handlers. Supplied handlers replace built-in defaults. */readonly events?: ChatSdkChannelEvents<TAdapters>;/**- * Prefix for default Eve HITL button action ids. Change this if your Chat SDK+ * Prefix for default eve HITL button action ids. Change this if your Chat SDK* app already uses the `eve_input:` prefix.*/readonly inputActionPrefix?: string;@@ -211,13 +215,13 @@ export interface ChatSdkChannel extends Channel</*** Return value of {@link chatSdkChannel}. Export `channel` from* `agent/channels/<name>.ts`, then register handlers on `bot` and call `send`- * from those handlers to hand work to Eve.+ * from those handlers to hand work to eve.*/export interface ChatSdkChannelBridge<TAdapters extends ChatSdkAdapters = ChatSdkAdapters> {readonly bot: Chat<TAdapters>;readonly channel: ChatSdkChannel;/**- * Starts or resumes an Eve session from inside a Chat SDK webhook handler.+ * Starts or resumes an eve session from inside a Chat SDK webhook handler.* Use `channel.receive(...)` for proactive sends that are not handling an* inbound Chat SDK webhook.*/@@ -225,7 +229,7 @@ export interface ChatSdkChannelBridge<TAdapters extends ChatSdkAdapters = ChatSd}/**- * Creates an Eve channel backed by one Chat SDK runtime and its adapters.+ * Creates an eve channel backed by one Chat SDK runtime and its adapters.** @example* ```ts@@ -304,7 +308,7 @@ export function chatSdkChannel<TAdapters extends ChatSdkAdapters>(): Promise<Response> => {const webhook = bot.webhooks[adapterName];const ctx = new ContextContainer();- ctx.setVirtualContext(ActiveWebhookKey, { cancel: args.cancel, send: args.send });+ ctx.setVirtualContext(ActiveWebhookKey, { from: args.from });return contextStorage.run(ctx, () =>webhook(request, {...config.webhook,@@ -316,11 +320,10 @@ export function chatSdkChannel<TAdapters extends ChatSdkAdapters>(};return [GET<ChatSdkChannelState>(path, handler), POST<ChatSdkChannelState>(path, handler)];}),- async receive(input, { send }) {+ async receive(input, { from }) {const thread = serializeReceiveTarget(bot, input.target);- return send(input.message, {+ return from(thread.id).send(input.message, {auth: input.auth,- continuationToken: thread.id,state: { thread },});},@@ -520,7 +523,7 @@ function renderInputRequest(request: InputRequest, inputActionPrefix: string) {return children;}children.push(- CardText("This request needs a freeform answer. Continue from the Eve session UI."),+ CardText("This request needs a freeform answer. Continue from the eve session UI."),);return children;}@@ -554,24 +557,19 @@ async function bridgeSend<TAdapters extends ChatSdkAdapters>();}const thread = serializeThread(bot, options.thread, options.adapterName);- const sendOptions: SendOptions<ChatSdkChannelState> = {+ const payload = normalizeSendInput(input);+ const deliveryOptions: MutableDeliveryOptions<ChatSdkChannelState> = {auth: options.auth ?? null,- continuationToken: thread.id,state: { thread },};- if (options.callback) {- sendOptions.callback = options.callback;- }- if (options.mode) {- sendOptions.mode = options.mode;- }- if (options.title) {- sendOptions.title = options.title;- }+ if (options.callback !== undefined) deliveryOptions.callback = options.callback;+ if (options.mode !== undefined) deliveryOptions.mode = options.mode;+ if (options.title !== undefined) deliveryOptions.title = options.title;+ const source = active.from(thread.id) as InternalChannelSource<ChatSdkChannelState>;if (options.turnPolicy === "experimental-steer" && hasMessageInput(input)) {- await active.cancel({ continuationToken: thread.id });+ await source.cancel();}- return active.send(input, sendOptions);+ return source[INTERNAL_CHANNEL_DELIVER](payload, deliveryOptions);}function hasMessageInput(input: ChatSdkSendInput): boolean {diff --git a/packages/eve/src/public/channels/discord/discordChannel.test.ts b/packages/eve/src/public/channels/discord/discordChannel.test.tsindex f087bf4c3..7a8161f63 100644--- a/packages/eve/src/public/channels/discord/discordChannel.test.ts+++ b/packages/eve/src/public/channels/discord/discordChannel.test.ts@@ -8,6 +8,7 @@ import { isCompiledChannel, type CompiledChannel } from "#channel/compiled-channimport { isHttpRouteDefinition } from "#channel/routes.js";import { ContextContainer, contextStorage } from "#context/container.js";import { SessionKey } from "#context/keys.js";+import { mockChannelContext } from "#internal/testing/mocks/mock-channel-operations.js";import type { UnstampedMessageStreamEvent } from "#protocol/message.js";import {DISCORD_HITL_FREEFORM_TEXT_INPUT_ID,@@ -122,16 +123,17 @@ async function firePost(if (!post || !isHttpRouteDefinition(post)) {throw new Error("Expected discord channel to define a POST route.");}- const send = vi.fn().mockResolvedValue({ continuationToken: "ct", id: "s1" });+ const send = vi.fn().mockResolvedValue({ id: "s1" });const waitUntil = vi.fn();const response = await post.handler(request, {- getSession: vi.fn() as any,+ attachSession: vi.fn() as any,+ ...mockChannelContext(send),+ to: vi.fn() as any,params: {},requestIp: null,- send,waitUntil,- } as any);+ });let drained = 0;while (drained < waitUntil.mock.calls.length) {@@ -200,15 +202,15 @@ describe("discordChannel() inbound route", () => {expect(response.status).toBe(200);await expect(response.json()).resolves.toEqual({ type: 5 });expect(send).toHaveBeenCalledTimes(1);- const [payload, options] = send.mock.calls[0]!;- expect((payload as { context: string[] }).context[0]).toContain("<discord_context>");- expect(String((payload as { message: string }).message)).toContain("hello discord");- expect(options).toMatchObject({+ const [continuationToken, input] = send.mock.calls[0]!;+ expect((input as { context: string[] }).context[0]).toContain("<discord_context>");+ expect(String((input as { message: string }).message)).toContain("hello discord");+ expect(continuationToken).toBe("C01:I01");+ expect(input).toMatchObject({auth: {authenticator: "discord-interaction",principalId: "discord:G01:U01",},- continuationToken: "C01:I01",state: {applicationId: "APP1",channelId: "C01",@@ -287,10 +289,10 @@ describe("discordChannel() inbound route", () => {expect(response.status).toBe(200);await expect(response.json()).resolves.toEqual({ type: 6 });expect(send).toHaveBeenCalledWith(- { inputResponses: [{ optionId: "approve", requestId: "call_1" }] },+ "C01:M01",expect.objectContaining({auth: null,- continuationToken: "C01:M01",+ inputResponses: [{ optionId: "approve", requestId: "call_1" }],}),);});@@ -360,9 +362,9 @@ describe("discordChannel() inbound route", () => {type: 4,});expect(submit.send).toHaveBeenCalledWith(- { inputResponses: [{ requestId: "call_1", text: "freeform answer" }] },+ "C01:M01",expect.objectContaining({- continuationToken: "C01:M01",+ inputResponses: [{ requestId: "call_1", text: "freeform answer" }],}),);});@@ -517,7 +519,7 @@ describe("discordChannel() default event handlers", () => {it("receive starts a proactive channel session", async () => {const channel = discordChannel({ credentials: { botToken: "bot-token" } });- const send = vi.fn().mockResolvedValue({ continuationToken: "C01:", id: "s1" });+ const send = vi.fn().mockResolvedValue({ id: "s1" });await channel.receive!({@@ -525,12 +527,14 @@ describe("discordChannel() default event handlers", () => {auth: null,message: "start",},- { send },+ {+ ...mockChannelContext(send),+ },);- expect(send).toHaveBeenCalledWith("start", {+ expect(send).toHaveBeenCalledWith("C01:", {auth: null,- continuationToken: "C01:",+ message: "start",state: {applicationId: null,channelId: "C01",diff --git a/packages/eve/src/public/channels/discord/discordChannel.ts b/packages/eve/src/public/channels/discord/discordChannel.tsindex efeff4d6c..62cb98485 100644--- a/packages/eve/src/public/channels/discord/discordChannel.ts+++ b/packages/eve/src/public/channels/discord/discordChannel.ts@@ -1,8 +1,9 @@import type { DiscordInstrumentationMetadata } from "#public/channels/discord/index.js";+import type { ChannelFrom } from "#channel/channel-operations.js";import type { SessionHandle } from "#channel/session.js";import type { SessionAuthContext } from "#channel/types.js";import type { SessionContext } from "#public/definitions/callback-context.js";-import type { ChannelSessionOps } from "#public/definitions/channel.js";+import type { ChannelContinuationOps } from "#public/definitions/channel.js";import { createLogger, logError } from "#internal/logging.js";import type { UnstampedMessageStreamEvent } from "#protocol/message.js";@@ -49,7 +50,7 @@ import { type DiscordWebhookVerifier } from "#public/channels/discord/verify.js"import { verifyDiscordInbound } from "#public/channels/discord/verifyInbound.js";import { readNonEmptyString } from "#shared/guards.js";import { parseJsonObject, type JsonObject } from "#shared/json.js";-import { defineChannel, POST, type Channel, type SendFn } from "#public/definitions/channel.js";+import { defineChannel, POST, type Channel } from "#public/definitions/channel.js";const log = createLogger("discord.channel");@@ -64,8 +65,8 @@ export interface DiscordContext {/** Channel-owned Discord context returned by `context()`. */export type DiscordChannelContext = DiscordContext & { state: DiscordChannelState };-/** Event-handler Discord context, including session operations. */-export interface DiscordEventContext extends DiscordChannelContext, ChannelSessionOps {}+/** Event-handler Discord context, including continuation routing. */+export interface DiscordEventContext extends DiscordChannelContext, ChannelContinuationOps {}/** JSON-serializable Discord channel state. */export interface DiscordChannelState {@@ -125,7 +126,7 @@ type DiscordSessionFailedHandler = (channel: DiscordEventContext,) => void | Promise<void>;-/** Per-event handlers for `discordChannel({ events })`. Supplied handlers override built-in defaults per key; unspecified events keep their defaults. `session.failed` receives only `(data, channel)`; every other handler also gets the session `ctx`. */+/** Per-event handlers for `discordChannel({ events })`. Supplied handlers override built-in defaults per key; unspecified events keep their defaults. `session.failed` receives only `(data, channel)` and exposes the ID as `data.sessionId`; every other handler also gets the session `ctx`. */export interface DiscordChannelEvents {readonly "turn.started"?: DiscordEventHandler<"turn.started">;readonly "actions.requested"?: DiscordEventHandler<"actions.requested">;@@ -228,7 +229,7 @@ export function discordChannel(config: DiscordChannelConfig = {}): DiscordChanneroutes: [POST<DiscordChannelState>(config.route ?? "/eve/v1/discord",- async (req, { send, waitUntil }) => {+ async (req, { from, waitUntil }) => {const body = await verifyDiscordInbound(req, config.credentials);if (body === null) return new Response("unauthorized", { status: 401 });@@ -253,14 +254,14 @@ export function discordChannel(config: DiscordChannelConfig = {}): DiscordChanneconfig,interaction,onCommand,- send,+ from,waitUntil,});},),],- async receive(input, { send }) {+ async receive(input, { from }) {const receiveTarget = input.target as Partial<DiscordReceiveTarget>;const channelId = readNonEmptyString(receiveTarget.channelId);if (!channelId) {@@ -289,9 +290,8 @@ export function discordChannel(config: DiscordChannelConfig = {}): DiscordChannehasMessageAnchor = posted.id.length > 0;}- return send(input.message, {+ return from(discordContinuationToken(channelId, conversationId)).send(input.message, {auth: input.auth,- continuationToken: discordContinuationToken(channelId, conversationId),state: {applicationId: null,channelId,@@ -333,7 +333,7 @@ function buildDiscordHandle(input: {state.conversationId = posted.id;state.hasMessageAnchor = true;if (state.channelId) {- input.session?.setContinuationToken(discordContinuationToken(state.channelId, posted.id));+ input.session?.continuation?.rekey(discordContinuationToken(state.channelId, posted.id));}}@@ -465,7 +465,7 @@ async function handleInteraction(input: {readonly config: DiscordChannelConfig;readonly interaction: DiscordInteraction;readonly onCommand: NonNullable<DiscordChannelConfig["onCommand"]>;- readonly send: SendFn<DiscordChannelState>;+ readonly from: ChannelFrom<DiscordChannelState>;readonly waitUntil: (task: Promise<unknown>) => void;}): Promise<Response> {if (input.interaction.type === DISCORD_INTERACTION_TYPE.APPLICATION_COMMAND) {@@ -473,20 +473,20 @@ async function handleInteraction(input: {config: input.config,interaction: input.interaction,onCommand: input.onCommand,- send: input.send,+ from: input.from,waitUntil: input.waitUntil,});}if (input.interaction.type === DISCORD_INTERACTION_TYPE.MESSAGE_COMPONENT) {return handleComponentInteraction({interaction: input.interaction,- send: input.send,+ from: input.from,waitUntil: input.waitUntil,});}return handleModalSubmitInteraction({interaction: input.interaction,- send: input.send,+ from: input.from,waitUntil: input.waitUntil,});}@@ -495,7 +495,7 @@ async function handleCommandInteraction(input: {readonly config: DiscordChannelConfig;readonly interaction: DiscordCommandInteraction;readonly onCommand: NonNullable<DiscordChannelConfig["onCommand"]>;- readonly send: SendFn<DiscordChannelState>;+ readonly from: ChannelFrom<DiscordChannelState>;readonly waitUntil: (task: Promise<unknown>) => void;}): Promise<Response> {const state = stateFromInteraction(input.interaction, {@@ -522,7 +522,7 @@ async function handleCommandInteraction(input: {dispatchCommand({interaction: input.interaction,result,- send: input.send,+ from: input.from,state,}),);@@ -531,7 +531,7 @@ async function handleCommandInteraction(input: {function handleComponentInteraction(input: {readonly interaction: DiscordComponentInteraction;- readonly send: SendFn<DiscordChannelState>;+ readonly from: ChannelFrom<DiscordChannelState>;readonly waitUntil: (task: Promise<unknown>) => void;}): Response {if (isDiscordFreeformComponent(input.interaction.customId)) {@@ -551,7 +551,7 @@ function handleComponentInteraction(input: {conversationId: input.interaction.messageId,inputResponses,interaction: input.interaction,- send: input.send,+ from: input.from,}),);}@@ -560,7 +560,7 @@ function handleComponentInteraction(input: {function handleModalSubmitInteraction(input: {readonly interaction: DiscordModalSubmitInteraction;- readonly send: SendFn<DiscordChannelState>;+ readonly from: ChannelFrom<DiscordChannelState>;readonly waitUntil: (task: Promise<unknown>) => void;}): Response {const inputResponses = deriveModalInputResponses(input.interaction);@@ -570,7 +570,7 @@ function handleModalSubmitInteraction(input: {conversationId: input.interaction.messageId ?? input.interaction.id,inputResponses,interaction: input.interaction,- send: input.send,+ from: input.from,}),);}@@ -580,7 +580,7 @@ function handleModalSubmitInteraction(input: {async function dispatchCommand(input: {readonly interaction: DiscordCommandInteraction;readonly result: Exclude<DiscordCommandResult, null>;- readonly send: SendFn<DiscordChannelState>;+ readonly from: ChannelFrom<DiscordChannelState>;readonly state: DiscordChannelState;}): Promise<void> {const turnMessage = commandInteractionMessage(input.interaction);@@ -595,20 +595,13 @@ async function dispatchCommand(input: {const channelContext = input.result.context ?? [];try {- await input.send(- {- message: turnMessage,- context: [contextBlock, ...channelContext],- },- {+ await input+ .from(discordContinuationToken(input.interaction.channelId, input.interaction.id))+ .send(turnMessage, {auth: input.result.auth,- continuationToken: discordContinuationToken(- input.interaction.channelId,- input.interaction.id,- ),+ context: [contextBlock, ...channelContext],state: input.state,- },- );+ });} catch (error) {log.error("command delivery failed", { error });}@@ -618,24 +611,14 @@ async function dispatchInputResponses(input: {readonly conversationId: string;readonly inputResponses: readonly { requestId: string; optionId?: string; text?: string }[];readonly interaction: DiscordComponentInteraction | DiscordModalSubmitInteraction;- readonly send: SendFn<DiscordChannelState>;+ readonly from: ChannelFrom<DiscordChannelState>;}): Promise<void> {try {- await input.send(- { inputResponses: input.inputResponses },- {+ await input+ .from(discordContinuationToken(input.interaction.channelId, input.conversationId))+ .respond(input.inputResponses, {auth: null,- continuationToken: discordContinuationToken(- input.interaction.channelId,- input.conversationId,- ),- state: stateFromInteraction(input.interaction, {- conversationId: input.conversationId,- hasMessageAnchor: true,- initialResponseSent: true,- }),- },- );+ });} catch (error) {log.error("interaction response delivery failed", { error });}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 7648bd666..d6ccb19a9 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@@ -9,16 +9,17 @@ import { describe, expect, it, vi } from "vitest";* Vercel Connect requires on the receiving deployment.*/-import type { RouteHandlerArgs, SendFn, SendOptions } from "#channel/routes.js";-import type { Session as ChannelSession } from "#channel/session.js";+import type { RouteHandlerArgs } from "#channel/routes.js";import type { RunInput, SessionAuthContext } from "#channel/types.js";import { contextStorage } from "#context/container.js";import { AuthKey, InitiatorAuthKey } from "#context/keys.js";import { buildRunContext } from "#execution/runtime-context.js";+import { mockChannelContext } from "#internal/testing/mocks/mock-channel-operations.js";import { isConnectionAuthorizationFailedError } from "#public/connections/errors.js";import { principalKey, resolveConnectionPrincipal } from "#runtime/connections/principal.js";import type { CompiledBundle } from "#runtime/sessions/runtime-context-keys.js";import { eveChannel, type EveChannelInput } from "#public/channels/eve.js";+import { attachRouteSessionCreator } from "#internal/nitro/routes/channel-route-context.js";const ROUTER_CALLER: SessionAuthContext = {attributes: {},@@ -54,36 +55,25 @@ function createEveCreateHandler(input: EveChannelInput) {);if (!createRoute) throw new Error("No create POST route found");- const mockSend = vi.fn<SendFn>().mockResolvedValue({- id: "receiver-session-id",- continuationToken: "eve:test",- async cancel() {- return { status: "no_active_turn" };- },- async getEventStream() {- return new ReadableStream();- },- async getStreamTailIndex() {- return -1;- },- } satisfies ChannelSession);+ const createSession = vi.fn().mockResolvedValue({+ events: new ReadableStream(),+ sessionId: "receiver-session-id",+ });return {- send: mockSend,+ createSession,async fetch(req: Request) {- const args: RouteHandlerArgs = {- send: mockSend,- resolveActiveSession: async () => undefined,- cancel: vi.fn(),- clear: vi.fn(),- compact: vi.fn(),- reset: vi.fn(),- getSession: vi.fn(),- receive: vi.fn() as never,- params: {},- waitUntil: () => undefined,- requestIp: "127.0.0.1",- };+ const args = attachRouteSessionCreator<RouteHandlerArgs>(+ {+ ...mockChannelContext(vi.fn()),+ attachSession: vi.fn() as any,+ to: vi.fn() as never,+ params: {},+ waitUntil: () => undefined,+ requestIp: "127.0.0.1",+ },+ createSession,+ );return (createRoute as { handler: (req: Request, args: RouteHandlerArgs) => unknown }).handler(req, args) as Promise<Response>;@@ -113,15 +103,14 @@ describe("eveChannel forwarded principal → runtime principal", () => {expect(response.status).toBe(202);await expect(response.json()).resolves.toMatchObject({ ok: true });- const options = handler.send.mock.calls[0]?.[1] as SendOptions;+ const options = handler.createSession.mock.calls[0]?.[0] as Omit<+ RunInput,+ "adapter" | "channelName" | "requestId"+ >;const run: RunInput = {adapter: { kind: "eve" },- auth: options.auth,channelName: "eve",- continuationToken: "eve:test",- initiatorAuth: options.initiatorAuth,- input: { message: "check my dashboards" },- mode: "task",+ ...options,};const ctx = buildRunContext({ bundle: {} as CompiledBundle, run });@@ -169,16 +158,16 @@ describe("eveChannel forwarded principal → runtime principal", () => {}),);- const options = handler.send.mock.calls[0]?.[1] as SendOptions;+ const options = handler.createSession.mock.calls[0]?.[0] as Omit<+ RunInput,+ "adapter" | "channelName" | "requestId"+ >;const ctx = buildRunContext({bundle: {} as CompiledBundle,run: {adapter: { kind: "eve" },- auth: options.auth,channelName: "eve",- continuationToken: "eve:test",- input: { message: "check my dashboards" },- mode: "task",+ ...options,},});diff --git a/packages/eve/src/public/channels/eve-session-routes.test.ts b/packages/eve/src/public/channels/eve-session-routes.test.tsnew file mode 100644index 000000000..51c2f4019--- /dev/null+++ b/packages/eve/src/public/channels/eve-session-routes.test.ts@@ -0,0 +1,206 @@+import { describe, expect, it, vi } from "vitest";++import type { RouteHandlerArgs } from "#channel/routes.js";+import type { Session } from "#channel/session.js";+import { attachRouteSessionCreator } from "#internal/nitro/routes/channel-route-context.js";+import { mockChannelContext } from "#internal/testing/mocks/mock-channel-operations.js";+import { none } from "#public/channels/auth.js";+import { eveChannel } from "#public/channels/eve.js";++function route(method: "GET" | "POST", path: string) {+ const found = eveChannel({ auth: none() }).routes.find(+ (candidate) => candidate.method === method && candidate.path === path,+ );+ if (found === undefined || !("handler" in found)) throw new Error(`Missing ${method} ${path}`);+ return found.handler as (request: Request, args: RouteHandlerArgs) => Promise<Response>;+}++function createFixedSession(overrides: Partial<Session> = {}): Session {+ return {+ id: "wrun_A",+ send: vi.fn().mockResolvedValue({ sessionId: "wrun_A", status: "accepted" }),+ respond: vi.fn().mockResolvedValue({ sessionId: "wrun_A", status: "accepted" }),+ cancel: vi.fn().mockResolvedValue({ sessionId: "wrun_A", status: "accepted" }),+ compact: vi.fn().mockResolvedValue({ sessionId: "wrun_A", status: "accepted" }),+ clear: vi.fn().mockResolvedValue({ sessionId: "wrun_A", status: "accepted" }),+ reset: vi.fn().mockResolvedValue({ previousSessionId: "wrun_A", status: "reset" }),+ getEventStream: vi.fn().mockResolvedValue(new ReadableStream()),+ getStreamTailIndex: vi.fn().mockResolvedValue(-1),+ ...overrides,+ };+}++function createArgs(session = createFixedSession()): RouteHandlerArgs {+ return {+ ...mockChannelContext(vi.fn()),+ attachSession: () => session,+ to: vi.fn() as never,+ params: { sessionId: "wrun_A" },+ waitUntil: vi.fn(),+ requestIp: "127.0.0.1",+ };+}++describe("eve ID-addressed session routes", () => {+ it("creates a session without a continuation token", async () => {+ const createSession = vi.fn().mockResolvedValue({+ events: new ReadableStream(),+ sessionId: "wrun_A",+ });+ const args = attachRouteSessionCreator(createArgs(), createSession);++ const response = await route("POST", "/eve/v1/session")(+ new Request("https://eve.test/eve/v1/session", {+ body: JSON.stringify({ message: "hello" }),+ headers: { "content-type": "application/json" },+ method: "POST",+ }),+ args,+ );++ expect(response.status).toBe(202);+ await expect(response.json()).resolves.toEqual({+ ok: true,+ sessionId: "wrun_A",+ status: "accepted",+ });+ expect(createSession).toHaveBeenCalledWith(+ expect.not.objectContaining({ continuationToken: expect.anything() }),+ );++ const rejected = await route("POST", "/eve/v1/session")(+ new Request("https://eve.test/eve/v1/session", {+ body: JSON.stringify({ continuationToken: "wrun_B", message: "redirect" }),+ headers: { "content-type": "application/json" },+ method: "POST",+ }),+ args,+ );+ expect(rejected.status).toBe(400);+ expect(createSession).toHaveBeenCalledTimes(1);+ });++ it("rejects input responses on session creation", async () => {+ const createSession = vi.fn();+ const args = attachRouteSessionCreator(createArgs(), createSession);++ const response = await route("POST", "/eve/v1/session")(+ new Request("https://eve.test/eve/v1/session", {+ body: JSON.stringify({+ inputResponses: [{ optionId: "approve", requestId: "request_1" }],+ }),+ headers: { "content-type": "application/json" },+ method: "POST",+ }),+ args,+ );++ expect(response.status).toBe(400);+ await expect(response.json()).resolves.toEqual({+ error: "'inputResponses' is only accepted for an existing session.",+ ok: false,+ });+ expect(createSession).not.toHaveBeenCalled();+ });++ it("sends directly to the path session ID and rejects token-bearing bodies", async () => {+ const session = createFixedSession();+ const handler = route("POST", "/eve/v1/session/:sessionId");+ const response = await handler(+ new Request("https://eve.test/eve/v1/session/wrun_A", {+ body: JSON.stringify({ message: "follow-up" }),+ headers: { "content-type": "application/json" },+ method: "POST",+ }),+ createArgs(session),+ );++ expect(response.status).toBe(202);+ expect(session.send).toHaveBeenCalledWith(+ "follow-up",+ expect.objectContaining({ auth: expect.objectContaining({ authenticator: "none" }) }),+ );++ const rejected = await handler(+ new Request("https://eve.test/eve/v1/session/wrun_A", {+ body: JSON.stringify({ continuationToken: "wrun_B", message: "redirect" }),+ headers: { "content-type": "application/json" },+ method: "POST",+ }),+ createArgs(session),+ );+ expect(rejected.status).toBe(400);+ expect(session.send).toHaveBeenCalledTimes(1);+ });++ it("returns conflict instead of creating when an exact session is inactive", async () => {+ const session = createFixedSession({+ send: vi.fn().mockResolvedValue({ status: "session_not_active" }),+ });+ const response = await route("POST", "/eve/v1/session/:sessionId")(+ new Request("https://eve.test/eve/v1/session/wrun_A", {+ body: JSON.stringify({ message: "late" }),+ headers: { "content-type": "application/json" },+ method: "POST",+ }),+ createArgs(session),+ );++ expect(response.status).toBe(409);+ await expect(response.json()).resolves.toEqual({+ code: "session_not_active",+ error: "The session is no longer active.",+ ok: false,+ });+ });++ it.each([+ ["cancel", "/eve/v1/session/:sessionId/cancel"],+ ["compact", "/eve/v1/session/:sessionId/compact"],+ ["clear", "/eve/v1/session/:sessionId/clear"],+ ["reset", "/eve/v1/session/:sessionId/reset"],+ ] as const)("dispatches %s through the fixed session handle", async (operation, path) => {+ const session = createFixedSession();+ const response = await route("POST", path)(+ new Request(`https://eve.test/eve/v1/session/wrun_A/${operation}`, { method: "POST" }),+ createArgs(session),+ );++ expect(response.ok).toBe(true);+ if (operation === "cancel") expect(response.status).toBe(202);+ expect(session[operation]).toHaveBeenCalledTimes(1);+ });++ it("returns a synchronous inactive cancellation result without a session id", async () => {+ const session = createFixedSession({+ cancel: vi.fn().mockResolvedValue({ status: "no_active_turn" }),+ });+ const response = await route("POST", "/eve/v1/session/:sessionId/cancel")(+ new Request("https://eve.test/eve/v1/session/wrun_A/cancel", { method: "POST" }),+ createArgs(session),+ );++ expect(response.status).toBe(200);+ await expect(response.json()).resolves.toEqual({ ok: true, status: "no_active_turn" });+ });++ it.each([+ ["cancel", "/eve/v1/session/:sessionId/cancel"],+ ["compact", "/eve/v1/session/:sessionId/compact"],+ ["clear", "/eve/v1/session/:sessionId/clear"],+ ["reset", "/eve/v1/session/:sessionId/reset"],+ ] as const)("rejects continuation tokens on the %s route", async (operation, path) => {+ const session = createFixedSession();+ const response = await route("POST", path)(+ new Request(`https://eve.test/eve/v1/session/wrun_A/${operation}`, {+ body: JSON.stringify({ continuationToken: "wrun_B" }),+ headers: { "content-type": "application/json" },+ method: "POST",+ }),+ createArgs(session),+ );++ expect(response.status).toBe(400);+ expect(session[operation]).not.toHaveBeenCalled();+ });+});diff --git a/packages/eve/src/public/channels/eve.test.ts b/packages/eve/src/public/channels/eve.test.tsindex c04910504..365c674d9 100644--- a/packages/eve/src/public/channels/eve.test.ts+++ b/packages/eve/src/public/channels/eve.test.ts@@ -4,13 +4,13 @@ import { describe, expect, it, vi } from "vitest";import { buildAdapterContext } from "#channel/adapter-context.js";import { callAdapterEventHandler, type ChannelAdapter } from "#channel/adapter.js";import { isCompiledChannel } from "#channel/compiled-channel.js";-import { createJsonMessageRequest, createMockAgent } from "#internal/testing/route-harness.js";-import { attachRouteAgent } from "#internal/nitro/routes/channel-route-context.js";+import { attachRouteSessionCreator } from "#internal/nitro/routes/channel-route-context.js";+import { mockChannelContext } from "#internal/testing/mocks/mock-channel-operations.js";import { type AuthFn, none } from "#public/channels/auth.js";import { eveChannel, defaultEveAuth, type EveChannelInput } from "#public/channels/eve.js";-import type { SessionAuthContext } from "#channel/types.js";-import type { RouteHandlerArgs, SendFn, SendOptions, SendPayload } from "#channel/routes.js";-import type { Session as ChannelSession } from "#channel/session.js";+import type { RunInput, SessionAuthContext } from "#channel/types.js";+import type { RouteHandlerArgs, SendPayload } from "#channel/routes.js";+import type { Session } from "#channel/session.js";import { ContextContainer, contextStorage } from "#context/container.js";import type { ContextAccessor } from "#context/key.js";import {@@ -20,7 +20,6 @@ import {type Session as RuntimeSession,} from "#context/keys.js";import { createMessageCompletedEvent } from "#protocol/message.js";-import { RuntimeNoActiveSessionError } from "#execution/runtime-errors.js";/*** Unit coverage for the inbound HTTP route's message-body parser and@@ -47,6 +46,52 @@ const OVERRIDE_AUTH: SessionAuthContext = {principalType: "user",};+type MockSendOptions = Pick<+ RunInput,+ "auth" | "callback" | "capabilities" | "initiatorAuth" | "mode" | "title"+>;++function createJsonMessageRequest(body: unknown): Request {+ return new Request("https://example.com/eve/v1/session", {+ body: JSON.stringify(body),+ headers: { "content-type": "application/json" },+ method: "POST",+ });+}++function createMockSession(overrides: Partial<Session> = {}): Session {+ return {+ id: "test-session-id",+ send: vi.fn().mockResolvedValue({ sessionId: "test-session-id", status: "accepted" }),+ respond: vi.fn().mockResolvedValue({ sessionId: "test-session-id", status: "accepted" }),+ cancel: vi.fn().mockResolvedValue({ status: "no_active_turn" }),+ compact: vi.fn().mockResolvedValue({ sessionId: "test-session-id", status: "accepted" }),+ clear: vi.fn().mockResolvedValue({ sessionId: "test-session-id", status: "accepted" }),+ reset: vi.fn().mockResolvedValue({+ previousSessionId: "test-session-id",+ status: "reset",+ }),+ async getEventStream() {+ return new ReadableStream();+ },+ async getStreamTailIndex() {+ return -1;+ },+ ...overrides,+ };+}++function createRouteArgs(): RouteHandlerArgs {+ return {+ ...mockChannelContext(vi.fn()),+ attachSession: () => createMockSession(),+ to: vi.fn() as never,+ params: {},+ waitUntil: () => undefined,+ requestIp: "127.0.0.1",+ };+}+/*** Creates a POST handler test harness for the create route (POST /eve/v1/session).* Returns a `fetch(req)` function and a `send` mock so tests can inspect@@ -59,36 +104,30 @@ function createEveCreateHandler(input: EveChannelInput) {);if (!createRoute) throw new Error("No create POST route found");- const mockSend = vi.fn<SendFn>().mockResolvedValue({- id: "test-session-id",- continuationToken: "eve:test",- async cancel() {- return { status: "no_active_turn" };- },- async getEventStream() {- return new ReadableStream();- },- async getStreamTailIndex() {- return -1;- },- } satisfies ChannelSession);+ const mockSend = vi.fn().mockResolvedValue(createMockSession());+ const createSession = vi.fn(async (runInput: RunInput) => {+ const payload =+ runInput.input.context === undefined && runInput.input.outputSchema === undefined+ ? runInput.input.message+ : runInput.input;+ await mockSend(payload, {+ auth: runInput.auth,+ callback: runInput.callback,+ capabilities: runInput.capabilities,+ initiatorAuth: runInput.initiatorAuth,+ mode: runInput.mode,+ title: runInput.title,+ } satisfies MockSendOptions);+ return {+ events: new ReadableStream(),+ sessionId: "test-session-id",+ };+ });return {send: mockSend,async fetch(req: Request) {- const args: RouteHandlerArgs = {- send: mockSend,- resolveActiveSession: async () => undefined,- cancel: vi.fn(),- clear: vi.fn(),- compact: vi.fn(),- reset: vi.fn(),- getSession: vi.fn(),- receive: vi.fn() as any,- params: {},- waitUntil: () => undefined,- requestIp: "127.0.0.1",- };+ const args = attachRouteSessionCreator(createRouteArgs(), createSession as never);return (createRoute as any).handler(req, args);},};@@ -105,38 +144,20 @@ function createEveContinueHandler(input: EveChannelInput) {);if (!continueRoute) throw new Error("No continue POST route found");- const mockSession: ChannelSession = {- id: "test-session-id",- continuationToken: "eve:test",- async cancel() {- return { status: "no_active_turn" };- },- async getEventStream() {- return new ReadableStream();- },- async getStreamTailIndex() {- return -1;- },- };-- const mockSend = vi.fn<SendFn>().mockResolvedValue(mockSession);- const mockGetSession = vi.fn().mockReturnValue(mockSession);+ const mockSend = vi.fn().mockResolvedValue({ sessionId: "test-session-id", status: "accepted" });+ const mockRespond = vi+ .fn()+ .mockResolvedValue({ sessionId: "test-session-id", status: "accepted" });+ const mockSession = createMockSession({ respond: mockRespond, send: mockSend });return {+ respond: mockRespond,send: mockSend,async fetch(req: Request) {const args: RouteHandlerArgs = {- send: mockSend,- resolveActiveSession: async () => undefined,- cancel: vi.fn(),- clear: vi.fn(),- compact: vi.fn(),- reset: vi.fn(),- getSession: mockGetSession,- receive: vi.fn() as any,+ ...createRouteArgs(),+ attachSession: () => mockSession,params: { sessionId: "test-session-id" },- waitUntil: () => undefined,- requestIp: "127.0.0.1",};return (continueRoute as any).handler(req, args);},@@ -154,28 +175,21 @@ function createEveCancelHandler(input: EveChannelInput) {);if (!cancelRoute) throw new Error("No cancel POST route found");- const agent = createMockAgent();- agent.cancelTurn.mockResolvedValue({ status: "accepted" });+ const cancelTurn = vi+ .fn()+ .mockResolvedValue({ sessionId: "test-session-id", status: "accepted" });+ const session = createMockSession({+ cancel: (options) => cancelTurn({ sessionId: "test-session-id", turnId: options?.turnId }),+ });return {- cancelTurn: agent.cancelTurn,+ cancelTurn,async fetch(req: Request) {- const args = attachRouteAgent(- {- send: vi.fn(),- resolveActiveSession: async () => undefined,- cancel: vi.fn(),- clear: vi.fn(),- compact: vi.fn(),- reset: vi.fn(),- getSession: vi.fn(),- receive: vi.fn() as any,- params: { sessionId: "test-session-id" },- waitUntil: () => undefined,- requestIp: "127.0.0.1",- } satisfies RouteHandlerArgs,- agent,- );+ const args: RouteHandlerArgs = {+ ...createRouteArgs(),+ attachSession: () => session,+ params: { sessionId: "test-session-id" },+ };return (cancelRoute as any).handler(req, args);},};@@ -193,11 +207,11 @@ function cancelRequest(body?: unknown): Request {});}-/** Creates a POST handler test harness for the continuation-addressed reset route. */+/** Creates a POST handler test harness for the ID-addressed reset route. */function createEveResetHandler(input: EveChannelInput) {const channel = eveChannel(input);const resetRoute = channel.routes.find(- (r) => r.method === "POST" && r.path === "/eve/v1/session/reset",+ (r) => r.method === "POST" && r.path === "/eve/v1/session/:sessionId/reset",);if (!resetRoute) throw new Error("No session reset POST route found");@@ -210,17 +224,9 @@ function createEveResetHandler(input: EveChannelInput) {reset,async fetch(req: Request) {const args: RouteHandlerArgs = {- send: vi.fn(),- resolveActiveSession: async () => undefined,- cancel: vi.fn(),- clear: vi.fn(),- compact: vi.fn(),- reset,- getSession: vi.fn(),- receive: vi.fn() as any,- params: {},- waitUntil: () => undefined,- requestIp: "127.0.0.1",+ ...createRouteArgs(),+ attachSession: () => createMockSession({ reset }),+ params: { sessionId: "test-session-id" },};return (resetRoute as any).handler(req, args);},@@ -228,7 +234,7 @@ function createEveResetHandler(input: EveChannelInput) {}function resetRequest(body: unknown): Request {- return new Request("https://example.com/eve/v1/session/reset", {+ return new Request("https://example.com/eve/v1/session/test-session-id/reset", {body: JSON.stringify(body),headers: { "content-type": "application/json" },method: "POST",@@ -236,18 +242,26 @@ function resetRequest(body: unknown): Request {}function clearRequest(body: unknown): Request {- return new Request("https://example.com/eve/v1/session/clear", {+ return new Request("https://example.com/eve/v1/session/test-session-id/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 compactRequest(body: unknown): Request {+ return new Request("https://example.com/eve/v1/session/test-session-id/compact", {+ body: JSON.stringify(body),+ headers: { "content-type": "application/json" },+ method: "POST",+ });+}++/** Creates a POST handler test harness for the ID-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",+ (route) => route.method === "POST" && route.path === "/eve/v1/session/:sessionId/clear",);if (!clearRoute) throw new Error("No session clear POST route found");@@ -260,28 +274,20 @@ function createEveClearHandler(input: EveChannelInput) {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",+ ...createRouteArgs(),+ attachSession: () => createMockSession({ clear }),+ params: { sessionId: "test-session-id" },};return (clearRoute as any).handler(req, args);},};}-/** Creates a POST handler test harness for the continuation-addressed compact route. */+/** Creates a POST handler test harness for the ID-addressed compact route. */function createEveCompactHandler(input: EveChannelInput) {const channel = eveChannel(input);const compactRoute = channel.routes.find(- (route) => route.method === "POST" && route.path === "/eve/v1/session/compact",+ (route) => route.method === "POST" && route.path === "/eve/v1/session/:sessionId/compact",);if (!compactRoute) throw new Error("No session compact POST route found");@@ -294,17 +300,9 @@ function createEveCompactHandler(input: EveChannelInput) {compact,async fetch(req: Request) {const args: RouteHandlerArgs = {- send: vi.fn(),- resolveActiveSession: async () => undefined,- cancel: vi.fn(),- clear: vi.fn(),- compact,- reset: vi.fn(),- getSession: vi.fn(),- receive: vi.fn() as any,- params: {},- waitUntil: () => undefined,- requestIp: "127.0.0.1",+ ...createRouteArgs(),+ attachSession: () => createMockSession({ compact }),+ params: { sessionId: "test-session-id" },};return (compactRoute as any).handler(req, args);},@@ -321,30 +319,19 @@ function createEveStreamHandler(input: EveChannelInput) {const getEventStream = vi.fn().mockResolvedValue(new ReadableStream());const getStreamTailIndex = vi.fn().mockResolvedValue(-1);- const mockGetSession = vi.fn().mockReturnValue({- cancel: vi.fn(),- continuationToken: "eve:test",+ const session = createMockSession({getEventStream,getStreamTailIndex,- id: "test-session-id",- } satisfies ChannelSession);+ });return {getEventStream,getStreamTailIndex,async fetch(url: string) {const args: RouteHandlerArgs = {- send: vi.fn(),- resolveActiveSession: async () => undefined,- cancel: vi.fn(),- clear: vi.fn(),- compact: vi.fn(),- reset: vi.fn(),- getSession: mockGetSession,- receive: vi.fn() as any,+ ...createRouteArgs(),+ attachSession: () => session,params: { sessionId: "test-session-id" },- waitUntil: () => undefined,- requestIp: "127.0.0.1",};return (streamRoute as any).handler(new Request(url), args);},@@ -478,7 +465,7 @@ describe("eveChannel — events", () => {events: {"message.completed"(data, channel, ctx) {observed.push(data.message ?? "");- observed.push(channel.continuationToken);+ observed.push(channel.continuation?.token ?? "");observed.push(ctx.session.id);},},@@ -508,7 +495,7 @@ describe("eveChannel — events", () => {);});- expect(observed).toEqual(["done", "eve:continuation", "sess-eve-event"]);+ expect(observed).toEqual(["done", "continuation", "sess-eve-event"]);});});@@ -606,7 +593,7 @@ describe("eveChannel — onMessage", () => {message: "What word is selected?",context: ["Client context:\nselection: jazz", "Authenticated caller profile: enterprise"],});- const options = handler.send.mock.calls[0]?.[1] as SendOptions;+ const options = handler.send.mock.calls[0]?.[1] as MockSendOptions;expect(options.auth).toEqual(ACCEPTED_AUTH);});@@ -622,7 +609,7 @@ describe("eveChannel — onMessage", () => {expect(handler.send).toHaveBeenCalledTimes(1);const payload = handler.send.mock.calls[0]?.[0] as SendPayload;expect(payload).toEqual({ message: "hi", context: ["override context"] });- const options = handler.send.mock.calls[0]?.[1] as SendOptions;+ const options = handler.send.mock.calls[0]?.[1] as MockSendOptions;expect(options.auth).toEqual(OVERRIDE_AUTH);});@@ -640,16 +627,20 @@ describe("eveChannel — onMessage", () => {expect(handler.send).not.toHaveBeenCalled();});- it("accepts a create request without dispatching when onMessage returns null", async () => {+ it("rejects an invalid null onMessage result instead of returning an empty success", async () => {const handler = createEveCreateHandler({auth: none(),- onMessage: () => null,+ onMessage: (() => null) as never,});const response = await handler.fetch(createJsonMessageRequest({ message: "hi" }));- expect(response.status).toBe(204);+ expect(response.status).toBe(500);expect(handler.send).not.toHaveBeenCalled();+ await expect(response.json()).resolves.toMatchObject({+ error: "onMessage handler failed.",+ ok: false,+ });});it("allows onMessage to dispatch with an empty context array", async () => {@@ -663,7 +654,7 @@ describe("eveChannel — onMessage", () => {expect(response.status).toBe(202);expect(handler.send).toHaveBeenCalledTimes(1);expect(handler.send.mock.calls[0]?.[0]).toEqual({ message: "hi", context: [] });- const options = handler.send.mock.calls[0]?.[1] as SendOptions;+ const options = handler.send.mock.calls[0]?.[1] as MockSendOptions;expect(options.auth).toBeNull();});@@ -685,7 +676,7 @@ describe("eveChannel — onMessage", () => {});});- it("passes session context to onMessage on continue requests", async () => {+ it("rejects combined messages and input responses on continue requests", async () => {const onMessage = vi.fn((ctx, message) => {expect(ctx.eve.caller).toEqual(ACCEPTED_AUTH);expect(defaultEveAuth(ctx)).toEqual(ACCEPTED_AUTH);@@ -701,22 +692,15 @@ describe("eveChannel — onMessage", () => {const response = await handler.fetch(createJsonMessageRequest({clientContext: "approval modal open",- continuationToken: "http:existing",inputResponses: [{ requestId: "req-1", optionId: "approve" }],message: "yes please",}),);- expect(response.status).toBe(200);- expect(onMessage).toHaveBeenCalledTimes(1);- const payload = handler.send.mock.calls[0]?.[0] as SendPayload;- expect(payload.context).toEqual([- "Client context:\napproval modal open",- "Authenticated continuation context",- ]);- expect(payload.inputResponses).toEqual([{ requestId: "req-1", optionId: "approve" }]);- const options = handler.send.mock.calls[0]?.[1] as SendOptions;- expect(options.auth).toEqual(ACCEPTED_AUTH);+ expect(response.status).toBe(400);+ expect(onMessage).not.toHaveBeenCalled();+ expect(handler.send).not.toHaveBeenCalled();+ expect(handler.respond).not.toHaveBeenCalled();});it("does not run onMessage for inputResponses-only continue requests", async () => {@@ -728,21 +712,20 @@ describe("eveChannel — onMessage", () => {const response = await handler.fetch(createJsonMessageRequest({- continuationToken: "http:existing",inputResponses: [{ requestId: "req-1", optionId: "deny" }],}),);- expect(response.status).toBe(200);+ expect(response.status).toBe(202);expect(onMessage).not.toHaveBeenCalled();- expect(handler.send).toHaveBeenCalledTimes(1);- const payload = handler.send.mock.calls[0]?.[0] as SendPayload;- expect(payload.context).toBeUndefined();- const options = handler.send.mock.calls[0]?.[1] as SendOptions;- expect(options.auth).toEqual(ACCEPTED_AUTH);+ expect(handler.respond).toHaveBeenCalledWith(+ [{ requestId: "req-1", optionId: "deny" }],+ expect.objectContaining({ auth: ACCEPTED_AUTH }),+ );+ expect(handler.send).not.toHaveBeenCalled();});- it("maps validated continuation callback metadata onto the turn caller", async () => {+ it("passes validated continuation callback metadata through the public session API", async () => {const handler = createEveContinueHandler({ auth: none() });const response = await handler.fetch(@@ -753,24 +736,20 @@ describe("eveChannel — onMessage", () => {token: "tok123",url: "https://caller.example.com/eve/v1/callback/tok123",},- continuationToken: "http:existing",message: "follow up",}),);- expect(response.status).toBe(200);+ expect(response.status).toBe(202);expect(handler.send).toHaveBeenCalledWith(- expect.not.objectContaining({ caller: expect.anything() }),+ "follow up",expect.objectContaining({- caller: {+ callback: {callId: "call-2",- replyTo: {- kind: "callback",- url: "https://caller.example.com/eve/v1/callback/tok123",- },subagentName: "research",+ token: "tok123",+ url: "https://caller.example.com/eve/v1/callback/tok123",},- intent: "resume",}),);});@@ -786,7 +765,6 @@ describe("eveChannel — onMessage", () => {token: "tok123",url: "https://caller.example.com/eve/v1/callback/other",},- continuationToken: "http:existing",message: "follow up",}),);@@ -795,27 +773,39 @@ describe("eveChannel — onMessage", () => {expect(handler.send).not.toHaveBeenCalled();});- it("returns SESSION_NOT_RESUMABLE instead of starting a replacement session", async () => {+ it("returns session_not_active instead of starting a replacement session", async () => {const handler = createEveContinueHandler({ auth: none() });- handler.send.mockRejectedValueOnce(new RuntimeNoActiveSessionError("eve:http:existing"));+ handler.send.mockResolvedValueOnce({ status: "session_not_active" });const response = await handler.fetch(createJsonMessageRequest({- continuationToken: "http:existing",message: "follow up",}),);- expect(response.status).toBe(404);+ expect(response.status).toBe(409);await expect(response.json()).resolves.toEqual({- code: "SESSION_NOT_RESUMABLE",- error: "Session is not active and cannot be resumed.",+ code: "session_not_active",+ error: "The session is no longer active.",ok: false,});});});describe("eveChannel — create session (text)", () => {+ it("returns a structured 500 when session creation fails", async () => {+ const handler = createEveCreateHandler({ auth: none() });+ handler.send.mockRejectedValue(new Error("backing store outage"));++ const response = await handler.fetch(createJsonMessageRequest({ message: "hi" }));++ expect(response.status).toBe(500);+ await expect(response.json()).resolves.toMatchObject({+ error: "Failed to create the session.",+ ok: false,+ });+ });+it("accepts a plain-string message and opens a new session", async () => {const handler = createEveCreateHandler({ auth: none() });@@ -1337,7 +1327,7 @@ describe("eveChannel — uploadPolicy enforcement", () => {expect(handler.send).toHaveBeenCalledTimes(1);});- it("enforces upload policy on continue (continuationToken) requests as well", async () => {+ it("enforces upload policy on ID-addressed follow-up requests as well", async () => {const handler = createEveContinueHandler({auth: none(),uploadPolicy: { maxBytes: 4 },@@ -1346,7 +1336,6 @@ describe("eveChannel — uploadPolicy enforcement", () => {const base64 = Buffer.from("too-big-for-policy", "utf8").toString("base64");const response = await handler.fetch(createJsonMessageRequest({- continuationToken: "http:existing",message: [filePartBody({ data: base64, filename: "big.txt", mediaType: "text/plain" })],}),);@@ -1375,22 +1364,17 @@ describe("eveChannel — uploadPolicy enforcement", () => {});describe("eveChannel — continue session HITL (inputResponses)", () => {- it("forwards inputResponses alongside a message", async () => {+ it("returns a structured 500 when fixed-session delivery fails", async () => {const handler = createEveContinueHandler({ auth: none() });+ handler.send.mockRejectedValue(new Error("backing store outage"));- const response = await handler.fetch(- createJsonMessageRequest({- continuationToken: "http:existing",- inputResponses: [{ requestId: "req-1", optionId: "approve" }],- message: "yes please",- }),- );+ const response = await handler.fetch(createJsonMessageRequest({ message: "follow-up" }));- expect(response.status).toBe(200);- expect(handler.send).toHaveBeenCalledTimes(1);- const payload = handler.send.mock.calls[0]?.[0] as SendPayload;- expect(payload.message).toBe("yes please");- expect(payload.inputResponses).toEqual([{ requestId: "req-1", optionId: "approve" }]);+ expect(response.status).toBe(500);+ await expect(response.json()).resolves.toMatchObject({+ error: "Failed to send the session message.",+ ok: false,+ });});it("converts clientContext on continue-session requests", async () => {@@ -1399,16 +1383,15 @@ describe("eveChannel — continue session HITL (inputResponses)", () => {const response = await handler.fetch(createJsonMessageRequest({clientContext: "approval modal open",- continuationToken: "http:existing",message: "yes please",}),);- expect(response.status).toBe(200);- expect(handler.send).toHaveBeenCalledTimes(1);- const payload = handler.send.mock.calls[0]?.[0] as SendPayload;- expect(payload.message).toBe("yes please");- expect(payload.context).toEqual(["Client context:\napproval modal open"]);+ expect(response.status).toBe(202);+ expect(handler.send).toHaveBeenCalledWith(+ "yes please",+ expect.objectContaining({ context: ["Client context:\napproval modal open"] }),+ );});it("forwards outputSchema with a continue-session message", async () => {@@ -1421,16 +1404,19 @@ describe("eveChannel — continue session HITL (inputResponses)", () => {const response = await handler.fetch(createJsonMessageRequest({- continuationToken: "http:existing",message: "Summarize",outputSchema,}),);- expect(response.status).toBe(200);- expect(handler.send).toHaveBeenCalledTimes(1);- const payload = handler.send.mock.calls[0]?.[0] as SendPayload;- expect(payload).toEqual({ message: "Summarize", outputSchema });+ expect(response.status).toBe(202);+ expect(handler.send).toHaveBeenCalledWith(+ "Summarize",+ expect.objectContaining({+ auth: expect.objectContaining({ authenticator: "none" }),+ outputSchema,+ }),+ );});it("rejects invalid continue-session clientContext", async () => {@@ -1439,7 +1425,6 @@ describe("eveChannel — continue session HITL (inputResponses)", () => {const response = await handler.fetch(createJsonMessageRequest({clientContext: 123,- continuationToken: "http:existing",message: "hi",}),);@@ -1456,16 +1441,16 @@ describe("eveChannel — continue session HITL (inputResponses)", () => {const response = await handler.fetch(createJsonMessageRequest({- continuationToken: "http:existing",inputResponses: [{ requestId: "req-1", optionId: "deny" }],}),);- expect(response.status).toBe(200);- expect(handler.send).toHaveBeenCalledTimes(1);- const payload = handler.send.mock.calls[0]?.[0] as SendPayload;- expect(payload.message).toBeUndefined();- expect(payload.inputResponses).toEqual([{ requestId: "req-1", optionId: "deny" }]);+ expect(response.status).toBe(202);+ expect(handler.respond).toHaveBeenCalledWith(+ [{ requestId: "req-1", optionId: "deny" }],+ expect.any(Object),+ );+ expect(handler.send).not.toHaveBeenCalled();});});@@ -1498,7 +1483,7 @@ describe("eveChannel — auth array shape", () => {expect(response.status).toBe(202);expect(order).toEqual(["skip-null", "skip-undefined", "accept"]);- const options = handler.send.mock.calls[0]?.[1] as SendOptions;+ const options = handler.send.mock.calls[0]?.[1] as MockSendOptions;expect(options.auth).toEqual(ACCEPTED);});@@ -1529,7 +1514,7 @@ describe("eveChannel — auth array shape", () => {const response = await handler.fetch(createJsonMessageRequest({ message: "hi" }));expect(response.status).toBe(202);- const options = handler.send.mock.calls[0]?.[1] as SendOptions;+ const options = handler.send.mock.calls[0]?.[1] as MockSendOptions;expect(options.auth).toEqual(ACCEPTED);});@@ -1540,14 +1525,12 @@ describe("eveChannel — auth array shape", () => {const response = await handler.fetch(createJsonMessageRequest({- continuationToken: "http:existing",message: "follow-up",}),);- expect(response.status).toBe(200);- const options = handler.send.mock.calls[0]?.[1] as SendOptions;- expect(options.auth).toEqual(ACCEPTED);+ expect(response.status).toBe(202);+ expect(handler.send.mock.calls[0]?.[1]).toMatchObject({ auth: ACCEPTED });});});@@ -1559,7 +1542,6 @@ describe("eveChannel — cancel turn", () => {expect(response.status).toBe(202);expect(response.headers.get("cache-control")).toBe("no-store");- expect(response.headers.get("x-eve-session-id")).toBe("test-session-id");await expect(response.json()).resolves.toEqual({ok: true,sessionId: "test-session-id",@@ -1602,10 +1584,9 @@ describe("eveChannel — cancel turn", () => {const response = await handler.fetch(cancelRequest());- expect(response.status).toBe(202);+ expect(response.status).toBe(200);await expect(response.json()).resolves.toEqual({ok: true,- sessionId: "test-session-id",status: "no_active_turn",});});@@ -1647,10 +1628,10 @@ describe("eveChannel — cancel turn", () => {});describe("eveChannel — reset session", () => {- it("retires the owner of the supplied channel-local continuation token", async () => {+ it("retires the exact session ID and forwards an optional reason", async () => {const handler = createEveResetHandler({ auth: none() });- const response = await handler.fetch(resetRequest({ continuationToken: "eve:token" }));+ const response = await handler.fetch(resetRequest({ reason: "Start over" }));expect(response.status).toBe(200);expect(response.headers.get("cache-control")).toBe("no-store");@@ -1659,17 +1640,14 @@ describe("eveChannel — reset session", () => {previousSessionId: "test-session-id",status: "reset",});- expect(handler.reset).toHaveBeenCalledWith({- continuationToken: "eve:token",- reason: "Client requested session reset",- });+ expect(handler.reset).toHaveBeenCalledWith({ reason: "Start over" });});- it("reports a token that is already free as a successful no-op", async () => {+ it("reports an inactive session ID as a successful no-op", async () => {const handler = createEveResetHandler({ auth: none() });handler.reset.mockResolvedValue({ status: "no_active_session" });- const response = await handler.fetch(resetRequest({ continuationToken: "eve:token" }));+ const response = await handler.fetch(resetRequest({}));expect(response.status).toBe(200);await expect(response.json()).resolves.toEqual({ ok: true, status: "no_active_session" });@@ -1678,16 +1656,16 @@ describe("eveChannel — reset session", () => {it("rejects unauthenticated reset requests", async () => {const handler = createEveResetHandler({ auth: [] });- const response = await handler.fetch(resetRequest({ continuationToken: "eve:token" }));+ const response = await handler.fetch(resetRequest({}));expect(response.status).toBe(401);expect(handler.reset).not.toHaveBeenCalled();});it.each([- ["an empty token", { continuationToken: "" }],- ["a non-string token", { continuationToken: 7 }],- ["a non-object body", ["eve:token"]],+ ["an empty reason", { reason: "" }],+ ["a non-string reason", { reason: 7 }],+ ["a non-object body", ["Start over"]],])("rejects %s with 400", async (_description, body) => {const handler = createEveResetHandler({ auth: none() });@@ -1701,7 +1679,7 @@ describe("eveChannel — reset session", () => {const handler = createEveResetHandler({ auth: none() });handler.reset.mockRejectedValue(new Error("backing store outage"));- const response = await handler.fetch(resetRequest({ continuationToken: "eve:token" }));+ const response = await handler.fetch(resetRequest({}));expect(response.status).toBe(500);await expect(response.json()).resolves.toMatchObject({@@ -1712,10 +1690,10 @@ describe("eveChannel — reset session", () => {});describe("eveChannel — compact session", () => {- it("queues compaction for the supplied channel-local continuation token", async () => {+ it("queues compaction for the exact session ID", async () => {const handler = createEveCompactHandler({ auth: none() });- const response = await handler.fetch(resetRequest({ continuationToken: "eve:token" }));+ const response = await handler.fetch(compactRequest({}));expect(response.status).toBe(202);expect(response.headers.get("cache-control")).toBe("no-store");@@ -1724,14 +1702,14 @@ describe("eveChannel — compact session", () => {sessionId: "test-session-id",status: "accepted",});- expect(handler.compact).toHaveBeenCalledWith({ continuationToken: "eve:token" });+ expect(handler.compact).toHaveBeenCalledWith();});- it("reports a token that no active session owns", async () => {+ it("reports an inactive session ID", async () => {const handler = createEveCompactHandler({ auth: none() });handler.compact.mockResolvedValue({ status: "no_active_session" });- const response = await handler.fetch(resetRequest({ continuationToken: "eve:token" }));+ const response = await handler.fetch(compactRequest({}));expect(response.status).toBe(200);await expect(response.json()).resolves.toEqual({ ok: true, status: "no_active_session" });@@ -1739,10 +1717,10 @@ describe("eveChannel — compact session", () => {});describe("eveChannel — clear session context", () => {- it("queues a clear for the supplied channel-local continuation token", async () => {+ it("queues a clear for the exact session ID", async () => {const handler = createEveClearHandler({ auth: none() });- const response = await handler.fetch(clearRequest({ continuationToken: "eve:token" }));+ const response = await handler.fetch(clearRequest({}));expect(response.status).toBe(202);expect(response.headers.get("cache-control")).toBe("no-store");@@ -1751,14 +1729,14 @@ describe("eveChannel — clear session context", () => {sessionId: "test-session-id",status: "accepted",});- expect(handler.clear).toHaveBeenCalledWith({ continuationToken: "eve:token" });+ expect(handler.clear).toHaveBeenCalledWith();});- it("reports a token that no active session owns", async () => {+ it("reports an inactive session ID", async () => {const handler = createEveClearHandler({ auth: none() });handler.clear.mockResolvedValue({ status: "no_active_session" });- const response = await handler.fetch(clearRequest({ continuationToken: "eve:token" }));+ const response = await handler.fetch(clearRequest({}));expect(response.status).toBe(200);await expect(response.json()).resolves.toEqual({ ok: true, status: "no_active_session" });@@ -1878,7 +1856,7 @@ describe("eveChannel — forwarded principal", () => {sessionId: "test-session-id",});- const options = handler.send.mock.calls[0]?.[1] as SendOptions;+ const options = handler.send.mock.calls[0]?.[1] as MockSendOptions;expect(options.auth).toEqual({...FORWARDED_CURRENT,attributes: {@@ -1904,7 +1882,7 @@ describe("eveChannel — forwarded principal", () => {await handler.fetch(forwardedRequest({ current: FORWARDED_CURRENT }));- const options = handler.send.mock.calls[0]?.[1] as SendOptions;+ const options = handler.send.mock.calls[0]?.[1] as MockSendOptions;expect(options.initiatorAuth).toEqual(options.auth);});@@ -1923,7 +1901,7 @@ describe("eveChannel — forwarded principal", () => {}),);- const options = handler.send.mock.calls[0]?.[1] as SendOptions;+ const options = handler.send.mock.calls[0]?.[1] as MockSendOptions;expect(options.auth?.attributes["eve:forwarded-by"]).toBe(ROUTER_CALLER.principalId);});@@ -1943,7 +1921,7 @@ describe("eveChannel — forwarded principal", () => {expect(response.status).toBe(202);expect(onMessage).toHaveBeenCalledTimes(1);- const options = handler.send.mock.calls[0]?.[1] as SendOptions;+ const options = handler.send.mock.calls[0]?.[1] as MockSendOptions;expect(options.auth?.principalId).toBe(FORWARDED_CURRENT.principalId);});@@ -1956,9 +1934,9 @@ describe("eveChannel — forwarded principal", () => {const response = await handler.fetch(createJsonMessageRequest({ message: "hi" }));expect(response.status).toBe(202);- const options = handler.send.mock.calls[0]?.[1] as SendOptions;+ const options = handler.send.mock.calls[0]?.[1] as MockSendOptions;expect(options.auth).toEqual(ROUTER_CALLER);- expect(options).not.toHaveProperty("initiatorAuth");+ expect(options.initiatorAuth).toBeUndefined();});it("rejects forwarded principal on the continue route", async () => {@@ -1970,7 +1948,6 @@ describe("eveChannel — forwarded principal", () => {const response = await handler.fetch(new Request("https://example.com/eve/v1/session/test-session-id", {body: JSON.stringify({- continuationToken: "eve:test",forwardedPrincipal: { current: FORWARDED_CURRENT },message: "hi",}),diff --git a/packages/eve/src/public/channels/eve.ts b/packages/eve/src/public/channels/eve.tsindex db0dc9dd1..72d053bac 100644--- a/packages/eve/src/public/channels/eve.ts+++ b/packages/eve/src/public/channels/eve.ts@@ -1,26 +1,19 @@import { type FilePart, type TextPart, type UserContent } from "ai";-import type {- CancelTurnResult,- SessionAuthContext,- SessionCallback,- SessionCapabilities,-} from "#channel/types.js";+import type { SessionAuthContext, SessionCallback, SessionCapabilities } 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";+import type { Session } from "#channel/session.js";import { resolveForwardedPrincipal, type TrustedForwarders } from "#channel/forwarded-principal.js";import { parseSessionCallback } from "#channel/session-callback.js";-import { isRuntimeNoActiveSessionError } from "#execution/runtime-errors.js";import { hasInternalRefScheme } from "#internal/attachments/url-refs.js";import { createLogger, logError } from "#internal/logging.js";import {readAgentInfoRouteResponse,- readRouteAgent,+ readRouteSessionCreator,} from "#internal/nitro/routes/channel-route-context.js";-import { AgentHandleError } from "#protocol/agent-handle-error.js";import {EVE_MESSAGE_STREAM_CONTENT_TYPE,EVE_MESSAGE_STREAM_FORMAT,@@ -31,11 +24,14 @@ import {EVE_STREAM_VERSION_HEADER,} 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,+ EVE_SESSION_ROUTE_PATH,+ EVE_SESSION_CANCEL_ROUTE_PATTERN,+ EVE_SESSION_CLEAR_ROUTE_PATTERN,+ EVE_SESSION_COMPACT_ROUTE_PATTERN,+ EVE_SESSION_ROUTE_PATTERN,+ EVE_SESSION_RESET_ROUTE_PATTERN,+ EVE_SESSION_STREAM_ROUTE_PATTERN,} from "#protocol/routes.js";import { type InputResponse, isInputResponse } from "#runtime/input/types.js";import { type AuthFn, routeAuth } from "#public/channels/auth.js";@@ -53,7 +49,7 @@ import {type Channel,type ChannelCors,type ChannelEvents,- type ChannelSessionOps,+ type ChannelContinuationOps,} from "#public/definitions/channel.js";import type { ChannelMethod } from "#public/definitions/channel.js";import type { RunMode } from "#shared/run-mode.js";@@ -63,9 +59,10 @@ const log = createLogger("eve.channel");/*** Event-handler channel context exposed by `eveChannel({ events })`. The default eve HTTP channel- * has no platform-specific state, so handlers receive session continuation operations plus the `SessionContext` third arg from {@link ChannelEvents}.+ * has no platform-specific state, so handlers receive optional continuation routing here and the+ * `SessionContext` third argument from {@link ChannelEvents}.*/-export type EveEventContext = ChannelSessionOps;+export type EveEventContext = ChannelContinuationOps;/** Runtime stream-event handlers supported by `eveChannel({ events })`. */export type EveChannelEvents = ChannelEvents<EveEventContext>;@@ -101,7 +98,7 @@ export interface EveHandle {/** Route-auth result for the request; `onMessage` chooses session auth by returning `{ auth }`. */readonly caller: SessionAuthContext | null;readonly request: Request;- /** Existing runtime session id for continuation requests. */+ /** Existing runtime session id for follow-up requests. */readonly sessionId?: string;}@@ -111,13 +108,13 @@ export interface EveMessageContext {}/**- * Result of `eveChannel({ onMessage })`. An object dispatches the inbound message,- * optionally prepending `context` strings as user messages; `null` accepts without dispatching.+ * Result of `eveChannel({ onMessage })`. The object dispatches the inbound message,+ * optionally prepending `context` strings as user messages.*/export type EveMessageResult = {readonly auth: SessionAuthContext | null;readonly context?: readonly string[];-} | null;+};/** Synchronous or asynchronous `onMessage` result. */export type EveMessageResultOrPromise = EveMessageResult | Promise<EveMessageResult>;@@ -195,9 +192,9 @@ export interface EveChannel extends Channel {}/*** Builds the default eve HTTP channel: a {@link defineChannel} instance serving the- * built-in `/eve/v1` routes (GET inspects the agent, POST creates a session, POST- * delivers a follow-up, POST cancels an active turn or retires a session, GET- * streams a session's NDJSON event feed). Every route+ * built-in `/eve/v1` routes (GET inspects the agent, POST creates a session,+ * ID-addressed POST routes deliver follow-ups and controls, and GET streams a+ * session's NDJSON event feed). Every route* runs {@link EveChannelInput.auth} via {@link routeAuth} before dispatching.* Default-export the result as your `agent/channels/eve.ts` channel; reach for* {@link defineChannel} directly only for a custom transport.@@ -223,30 +220,23 @@ export function eveChannel(input: EveChannelInput): EveChannel {return await respond();}),- POST("/eve/v1/session", async (req, { send }) => {+ POST(EVE_SESSION_ROUTE_PATH, async (req, args) => {const authResult = await routeAuth(req, input.auth);if (authResult instanceof Response) return authResult;- const sessionAuth = authResult;- let payload: unknown;- try {- payload = await req.json();- } catch {- return Response.json({ error: "Invalid JSON body.", ok: false }, { status: 400 });- }-- if (payload === null || typeof payload !== "object") {- return Response.json({ error: "Expected a JSON object.", ok: false }, { status: 400 });- }+ const payload = await parseJsonRequest(req);+ if (payload instanceof Response) return payload;+ const tokenRejection = rejectSessionContinuationToken(payload);+ if (tokenRejection !== null) return tokenRejection;const forwarded = await resolveForwardedPrincipal({trustedForwarders: input.trustedForwarders,- forwarder: sessionAuth,- payload: payload as Record<string, unknown>,+ forwarder: authResult,+ payload,});if (forwarded instanceof Response) return forwarded;- const body = parseCreateBody(payload as Record<string, unknown>);+ const body = parseCreateBody(payload);if (body instanceof Response) return body;const policyRejection = checkUploadPolicy(body, uploadPolicy);@@ -259,304 +249,252 @@ export function eveChannel(input: EveChannelInput): EveChannel {request: req,});if (messageResult instanceof Response) return messageResult;- if (!messageResult.dispatch) return droppedMessageResponse();-- const token = `eve:${crypto.randomUUID()}`;- const context = mergeContext(body.context, messageResult.context);-- const sendOptions: SendOptions = {- auth: messageResult.auth,- callback: body.callback,- capabilities: body.capabilities,- continuationToken: token,- mode: body.mode,- };- if (forwarded.accepted) {- sendOptions.initiatorAuth = forwarded.initiatorAuth;+ const createSession = readRouteSessionCreator(args);+ if (createSession === undefined) {+ return Response.json(+ { error: "Session creation requires internal channel dispatch context.", ok: false },+ { status: 500 },+ );+ }++ let handle: Awaited<ReturnType<typeof createSession>>;+ try {+ handle = await createSession({+ auth: messageResult.auth,+ capabilities:+ body.capabilities ?? (body.mode === "task" ? undefined : { requestInput: true }),+ callback: body.callback,+ initiatorAuth: forwarded.accepted ? forwarded.initiatorAuth : undefined,+ input: {+ message: body.message,+ context: mergeContext(body.context, messageResult.context),+ outputSchema: body.outputSchema,+ },+ mode: body.mode ?? "conversation",+ });+ } catch (error) {+ const errorId = logError(log, "session-create request failed", error);+ return Response.json(+ { error: "Failed to create the session.", errorId, ok: false },+ { status: 500 },+ );}- const session = await send(createSendPayload(body, context), sendOptions);return Response.json(- {- continuationToken: session.continuationToken,- ok: true,- sessionId: session.id,- },+ { ok: true, sessionId: handle.sessionId, status: "accepted" },{headers: {"cache-control": "no-store",- [EVE_SESSION_ID_HEADER]: session.id,+ [EVE_SESSION_ID_HEADER]: handle.sessionId,},status: 202,},);}),- POST(EVE_RESET_SESSION_ROUTE_PATH, async (req, { reset }) => {+ POST(EVE_SESSION_ROUTE_PATTERN, async (req, { attachSession, params }) => {const authResult = await routeAuth(req, input.auth);if (authResult instanceof Response) return authResult;- const body = await parseContinuationTokenBody(req);+ const sessionId = requireSessionId(params);+ if (sessionId instanceof Response) return sessionId;+ const payload = await parseJsonRequest(req);+ if (payload instanceof Response) return payload;+ const body = parseSessionMessageBody(payload);if (body instanceof Response) return body;- let result: Awaited<ReturnType<typeof reset>>;- try {- result = await reset({- continuationToken: body.continuationToken,- reason: "Client requested session reset",+ const policyRejection = checkUploadPolicy(body, uploadPolicy);+ if (policyRejection !== null) return policyRejection;++ let context = body.context;+ let dispatchAuth: SessionAuthContext | null = authResult;+ if (body.message !== undefined) {+ const messageResult = await resolveOnMessage({+ auth: authResult,+ config: input,+ message: body.message,+ request: req,+ sessionId,});+ if (messageResult instanceof Response) return messageResult;+ context = mergeContext(body.context, messageResult.context);+ dispatchAuth = messageResult.auth;+ }++ let result: Awaited<ReturnType<Session["send"]>>;+ try {+ const session = attachSession(sessionId);+ const options = {+ auth: dispatchAuth,+ callback: body.callback,+ context,+ outputSchema: body.outputSchema,+ };+ result =+ body.inputResponses === undefined+ ? await session.send(body.message!, options)+ : await session.respond(body.inputResponses, options);} catch (error) {- const errorId = logError(log, "session-reset request failed", error);+ const errorId = logError(log, "session-message request failed", error, { sessionId });return Response.json(- { error: "Failed to reset the session.", errorId, ok: false },+ { error: "Failed to send the session message.", errorId, ok: false },{ status: 500 },);}+ if (result.status === "session_not_active") {+ return Response.json(+ {+ code: "session_not_active",+ error: "The session is no longer active.",+ ok: false,+ },+ { headers: { "cache-control": "no-store" }, status: 409 },+ );+ }- const response: ResetResponse =- result.status === "reset"- ? { ok: true, previousSessionId: result.previousSessionId, status: "reset" }- : { ok: true, status: "no_active_session" };- return Response.json(response, {- headers: { "cache-control": "no-store" },- });+ return Response.json(+ { ok: true, sessionId: result.sessionId, status: "accepted" },+ {+ headers: {+ "cache-control": "no-store",+ [EVE_SESSION_ID_HEADER]: result.sessionId,+ },+ status: 202,+ },+ );}),- POST(EVE_CLEAR_SESSION_ROUTE_PATH, async (req, { clear }) => {+ POST(EVE_SESSION_CANCEL_ROUTE_PATTERN, async (req, { attachSession, params }) => {const authResult = await routeAuth(req, input.auth);if (authResult instanceof Response) return authResult;-- const body = await parseContinuationTokenBody(req);+ const sessionId = requireSessionId(params);+ if (sessionId instanceof Response) return sessionId;+ const body = await parseCancelTurnBody(req);if (body instanceof Response) return body;-- let result: Awaited<ReturnType<typeof clear>>;+ let result: Awaited<ReturnType<Session["cancel"]>>;try {- result = await clear({ continuationToken: body.continuationToken });+ result = await attachSession(sessionId).cancel({ turnId: body.turnId });} catch (error) {- const errorId = logError(log, "session-clear request failed", error);+ const errorId = logError(log, "cancel-turn request failed", error, { sessionId });return Response.json(- { error: "Failed to clear the session context.", errorId, ok: false },+ { error: "Failed to cancel the turn.", errorId, ok: false },{ status: 500 },);}-- const response: ClearResponse =+ return Response.json(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,- });+ ? ({+ ok: true,+ sessionId: result.sessionId,+ status: "accepted",+ } satisfies CancelTurnResponse)+ : ({ ok: true, status: "no_active_turn" } satisfies CancelTurnResponse),+ {+ headers: { "cache-control": "no-store" },+ status: result.status === "accepted" ? 202 : 200,+ },+ );}),- POST(EVE_COMPACT_SESSION_ROUTE_PATH, async (req, { compact }) => {+ POST(EVE_SESSION_COMPACT_ROUTE_PATTERN, async (req, { attachSession, params }) => {const authResult = await routeAuth(req, input.auth);if (authResult instanceof Response) return authResult;-- const body = await parseContinuationTokenBody(req);+ const sessionId = requireSessionId(params);+ if (sessionId instanceof Response) return sessionId;+ const body = await parseSessionControlBody(req);if (body instanceof Response) return body;-- let result: Awaited<ReturnType<typeof compact>>;+ let result: Awaited<ReturnType<Session["compact"]>>;try {- result = await compact({ continuationToken: body.continuationToken });+ result = await attachSession(sessionId).compact();} catch (error) {- const errorId = logError(log, "session-compaction request failed", error);+ const errorId = logError(log, "session-compaction request failed", error, { sessionId });return Response.json({ error: "Failed to compact the session.", errorId, ok: false },{ status: 500 },);}-- const response: CompactResponse =+ return Response.json(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,- });+ ? ({+ ok: true,+ sessionId: result.sessionId,+ status: "accepted",+ } satisfies CompactResponse)+ : ({ ok: true, status: "no_active_session" } satisfies CompactResponse),+ {+ headers: { "cache-control": "no-store" },+ status: result.status === "accepted" ? 202 : 200,+ },+ );}),- POST("/eve/v1/session/:sessionId", async (req, { send, getSession, params }) => {+ POST(EVE_SESSION_CLEAR_ROUTE_PATTERN, async (req, { attachSession, params }) => {const authResult = await routeAuth(req, input.auth);if (authResult instanceof Response) return authResult;- const sessionAuth = authResult;-- const sessionId = params.sessionId;- if (!sessionId) {- return Response.json({ error: "Missing session id.", ok: false }, { status: 400 });- }-- try {- getSession(sessionId);- } catch {- return Response.json({ error: "Session not found.", ok: false }, { status: 404 });- }-- let payload: unknown;- try {- payload = await req.json();- } catch {- return Response.json({ error: "Invalid JSON body.", ok: false }, { status: 400 });- }-- if (payload === null || typeof payload !== "object") {- return Response.json({ error: "Expected a JSON object.", ok: false }, { status: 400 });- }-- const body = parseContinueBody(payload as Record<string, unknown>);+ const sessionId = requireSessionId(params);+ if (sessionId instanceof Response) return sessionId;+ const body = await parseSessionControlBody(req);if (body instanceof Response) return body;-- const policyRejection = checkUploadPolicy(body, uploadPolicy);- if (policyRejection !== null) return policyRejection;-- let context = body.context;- let dispatchAuth: SessionAuthContext | null = sessionAuth;- if (body.message !== undefined) {- const messageResult = await resolveOnMessage({- auth: sessionAuth,- config: input,- message: body.message,- request: req,- sessionId,- });- if (messageResult instanceof Response) return messageResult;- if (!messageResult.dispatch) return droppedMessageResponse();- context = mergeContext(body.context, messageResult.context);- dispatchAuth = messageResult.auth;- }-- const sendOptions: SendOptions = {- auth: dispatchAuth,- continuationToken: body.continuationToken,- // This route addresses the session in the URL. If its continuation- // token no longer resolves, starting a new session would silently- // change that identity, so surface SESSION_NOT_RESUMABLE instead.- intent: "resume",- };- if (body.callback !== undefined) {- sendOptions.caller = {- callId: body.callback.callId,- replyTo: { kind: "callback", url: body.callback.url },- subagentName: body.callback.subagentName,- };- }-- let session;+ let result: Awaited<ReturnType<Session["clear"]>>;try {- session = await send(- {- inputResponses: body.inputResponses,- message: body.message,- context,- outputSchema: body.outputSchema,- },- sendOptions,- );+ result = await attachSession(sessionId).clear();} catch (error) {- if (!isRuntimeNoActiveSessionError(error)) {- throw error;- }- return Response.json(AgentHandleError.SessionNotResumable.toJson(), { status: 404 });+ 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),{- ok: true,- sessionId: session.id,- },- {- headers: {- "cache-control": "no-store",- [EVE_SESSION_ID_HEADER]: session.id,- },- status: 200,+ headers: { "cache-control": "no-store" },+ status: result.status === "accepted" ? 202 : 200,},);}),- POST(EVE_CANCEL_TURN_ROUTE_PATTERN, async (req, args) => {+ POST(EVE_SESSION_RESET_ROUTE_PATTERN, async (req, { attachSession, params }) => {const authResult = await routeAuth(req, input.auth);if (authResult instanceof Response) return authResult;-- const sessionId = args.params.sessionId;- if (!sessionId) {- return Response.json({ error: "Missing session id.", ok: false }, { status: 400 });- }-- const body = await parseCancelTurnBody(req);+ const sessionId = requireSessionId(params);+ if (sessionId instanceof Response) return sessionId;+ const body = await parseResetBody(req);if (body instanceof Response) return body;-- let result: CancelTurnResult;+ let result: Awaited<ReturnType<Session["reset"]>>;try {- const agent = readRouteAgent(args);- if (agent === undefined) {- throw new Error("Missing route agent.");- }- result = await agent.cancelTurn({ sessionId, turnId: body.turnId });+ result = await attachSession(sessionId).reset({ reason: body.reason });} catch (error) {- const errorId = logError(log, "cancel-turn request failed", error, { sessionId });+ const errorId = logError(log, "session-reset request failed", error, { sessionId });return Response.json(- { error: "Failed to cancel the turn.", errorId, ok: false },+ { error: "Failed to reset the session.", errorId, ok: false },{ status: 500 },);}-return Response.json(- { ok: true, sessionId, status: result.status } satisfies CancelTurnResponse,- {- headers: {- "cache-control": "no-store",- [EVE_SESSION_ID_HEADER]: sessionId,- },- status: 202,- },+ result.status === "reset"+ ? ({+ ok: true,+ previousSessionId: result.previousSessionId,+ status: "reset",+ } satisfies ResetResponse)+ : ({ ok: true, status: "no_active_session" } satisfies ResetResponse),+ { headers: { "cache-control": "no-store" } },);}),- GET("/eve/v1/session/:sessionId/stream", async (req, { getSession, params }) => {+ GET(EVE_SESSION_STREAM_ROUTE_PATTERN, async (req, { attachSession, params }) => {const authResult = await routeAuth(req, input.auth);if (authResult instanceof Response) return authResult;-- const sessionId = params.sessionId;- if (!sessionId) {- return Response.json({ error: "Missing session id.", ok: false }, { status: 400 });- }-- const startIndex = parseStartIndex(req);- if (startIndex instanceof Response) return startIndex;-- const includeTailIndex = parseIncludeTailIndex(req);-- try {- const session = getSession(sessionId);-- // The tail lookup is opt-in: only requests that bound a read pay for it.- const tailIndex = includeTailIndex ? await session.getStreamTailIndex() : undefined;- const events = await session.getEventStream({ startIndex });-- const ndjson = serializeAsNdjson(events);- return new Response(ndjson, {- headers: {- // Opt out of intermediary-proxy buffering. Buffering reverse- // proxies (notably the Vercel sandbox / v0 preview edge) otherwise- // withhold this streamed response until it closes, starving the- // browser of incremental events until a timeout fires.- "cache-control": "no-store, no-transform",- "content-type": EVE_MESSAGE_STREAM_CONTENT_TYPE,- "x-accel-buffering": "no",- [EVE_SESSION_ID_HEADER]: sessionId,- [EVE_STREAM_FORMAT_HEADER]: EVE_MESSAGE_STREAM_FORMAT,- ...(tailIndex === undefined- ? {}- : { [EVE_STREAM_TAIL_INDEX_HEADER]: String(tailIndex) }),- [EVE_STREAM_VERSION_HEADER]: EVE_MESSAGE_STREAM_VERSION,- },- });- } catch {- return Response.json({ error: "Session not found.", ok: false }, { status: 404 });- }+ const sessionId = requireSessionId(params);+ if (sessionId instanceof Response) return sessionId;+ return await createSessionStreamResponse(req, attachSession(sessionId));}),],events: input.events,@@ -620,15 +558,10 @@ function normalizeEveCorsOrigin(return origin;}-type OnMessageOutcome =- | {- readonly auth: SessionAuthContext | null;- readonly context?: readonly string[];- readonly dispatch: true;- }- | {- readonly dispatch: false;- };+interface OnMessageOutcome {+ readonly auth: SessionAuthContext | null;+ readonly context?: readonly string[];+}async function resolveOnMessage(input: {readonly auth: SessionAuthContext | null;@@ -639,7 +572,7 @@ async function resolveOnMessage(input: {}): Promise<OnMessageOutcome | Response> {const handler = input.config.onMessage ?? defaultOnMessage;- let result: EveMessageResult | undefined;+ let result: EveMessageResult;try {const eve: EveHandle =input.sessionId === undefined@@ -647,6 +580,9 @@ async function resolveOnMessage(input: {: { caller: input.auth, request: input.request, sessionId: input.sessionId };const ctx: EveMessageContext = { eve };result = await handler(ctx, input.message);+ if (result === null || result === undefined) {+ throw new TypeError("eveChannel onMessage must return an auth result.");+ }} catch (error) {const errorId = logError(log, "onMessage handler failed", error, {sessionId: input.sessionId,@@ -657,26 +593,16 @@ async function resolveOnMessage(input: {);}- if (result === null || result === undefined) {- return { dispatch: false };- }if (result.context === undefined) {- return { auth: result.auth, dispatch: true };+ return { auth: result.auth };}- return { auth: result.auth, context: result.context, dispatch: true };+ return { auth: result.auth, context: result.context };}-function defaultOnMessage(ctx: EveMessageContext): Exclude<EveMessageResult, null> {+function defaultOnMessage(ctx: EveMessageContext): EveMessageResult {return { auth: defaultEveAuth(ctx) };}-function droppedMessageResponse(): Response {- return new Response(null, {- headers: { "cache-control": "no-store" },- status: 204,- });-}-interface ParsedCreateBody {callback?: SessionCallback;capabilities?: SessionCapabilities;@@ -687,6 +613,12 @@ interface ParsedCreateBody {}function parseCreateBody(payload: Record<string, unknown>): ParsedCreateBody | Response {+ if (payload.inputResponses !== undefined) {+ return Response.json(+ { error: "'inputResponses' is only accepted for an existing session.", ok: false },+ { status: 400 },+ );+ }const message = parseMessageField(payload.message);if (message instanceof Response) return message;@@ -715,18 +647,19 @@ function parseCreateBody(payload: Record<string, unknown>): ParsedCreateBody | Rreturn { callback, capabilities, message, mode, context, outputSchema };}-interface ParsedContinueBody {+interface ParsedSessionMessageBody {callback?: SessionCallback;message?: string | UserContent;- continuationToken: string;inputResponses?: readonly InputResponse[];context?: readonly string[];outputSchema?: JsonObject;}-function parseContinueBody(payload: Record<string, unknown>): ParsedContinueBody | Response {- // Fail loud instead of silently running the delivery as the transport- // principal: principal forwarding is create-only today.+function parseSessionMessageBody(+ payload: Record<string, unknown>,+): ParsedSessionMessageBody | Response {+ const tokenRejection = rejectSessionContinuationToken(payload);+ if (tokenRejection !== null) return tokenRejection;if (payload.forwardedPrincipal !== undefined) {return Response.json({ error: "A forwarded principal is only accepted on session creation.", ok: false },@@ -734,89 +667,102 @@ function parseContinueBody(payload: Record<string, unknown>): ParsedContinueBody);}- const continuationToken =- typeof payload.continuationToken === "string" && payload.continuationToken.length > 0- ? payload.continuationToken- : undefined;-- if (continuationToken === undefined) {- return Response.json(- { error: "Missing or empty 'continuationToken' field.", ok: false },- { status: 400 },- );- }-const message = parseMessageField(payload.message);if (message instanceof Response) return message;-const callback = parseCallbackField(payload.callback);if (callback instanceof Response) return callback;-const inputResponses = parseInputResponses(payload.inputResponses);if (inputResponses instanceof Response) return inputResponses;-const context = parseClientContextField(payload.clientContext);if (context instanceof Response) return context;-const outputSchema = parseOutputSchemaField(payload.outputSchema);if (outputSchema instanceof Response) return outputSchema;if (message === undefined && inputResponses === undefined) {return Response.json({- error: "Expected a non-empty 'message', a non-empty 'inputResponses' array, or both.",+ error: "Expected a non-empty 'message' or a non-empty 'inputResponses' array.",ok: false,},{ status: 400 },);}- return { callback, message, continuationToken, inputResponses, context, outputSchema };+ if (message !== undefined && inputResponses !== undefined) {+ return Response.json(+ { error: "'message' and 'inputResponses' are mutually exclusive.", ok: false },+ { status: 400 },+ );+ }++ return { callback, message, inputResponses, context, outputSchema };}interface ParsedCancelTurnBody {turnId?: string;}-interface ParsedContinuationTokenBody {- readonly continuationToken: string;+async function parseCancelTurnBody(req: Request): Promise<ParsedCancelTurnBody | Response> {+ const payload = await parseOptionalJsonRequest(req);+ if (payload instanceof Response) return payload;+ const tokenRejection = rejectSessionContinuationToken(payload);+ if (tokenRejection !== null) return tokenRejection;++ const turnId = payload.turnId;+ if (turnId === undefined) {+ return {};+ }+ if (typeof turnId !== "string" || turnId.length === 0) {+ return Response.json(+ { error: "Expected 'turnId' to be a non-empty string.", ok: false },+ { status: 400 },+ );+ }+ return { turnId };}-async function parseContinuationTokenBody(- req: Request,-): Promise<ParsedContinuationTokenBody | Response> {+async function parseJsonRequest(req: Request): Promise<Record<string, unknown> | Response> {let payload: unknown;try {payload = await req.json();} catch {return Response.json({ error: "Invalid JSON body.", ok: false }, { status: 400 });}-if (payload === null || typeof payload !== "object" || Array.isArray(payload)) {return Response.json({ error: "Expected a JSON object.", ok: false }, { status: 400 });}+ return payload as Record<string, unknown>;+}- const continuationToken = (payload as { continuationToken?: unknown }).continuationToken;- if (typeof continuationToken !== "string" || continuationToken.length === 0) {+async function parseResetBody(req: Request): Promise<{ readonly reason?: string } | Response> {+ const payload = await parseOptionalJsonRequest(req);+ if (payload instanceof Response) return payload;+ const tokenRejection = rejectSessionContinuationToken(payload);+ if (tokenRejection !== null) return tokenRejection;+ const reason = payload.reason;+ if (reason !== undefined && (typeof reason !== "string" || reason.length === 0)) {return Response.json(- { error: "Expected 'continuationToken' to be a non-empty string.", ok: false },+ { error: "Expected 'reason' to be a non-empty string.", ok: false },{ status: 400 },);}+ return reason === undefined ? {} : { reason };+}- return { continuationToken };+async function parseSessionControlBody(req: Request): Promise<Record<string, unknown> | Response> {+ const payload = await parseOptionalJsonRequest(req);+ if (payload instanceof Response) return payload;+ return rejectSessionContinuationToken(payload) ?? payload;}-async function parseCancelTurnBody(req: Request): Promise<ParsedCancelTurnBody | Response> {+async function parseOptionalJsonRequest(req: Request): Promise<Record<string, unknown> | Response> {let text: string;try {text = await req.text();} catch {return Response.json({ error: "Unreadable request body.", ok: false }, { status: 400 });}- if (text.trim().length === 0) {- return {};- }+ if (text.trim().length === 0) return {};let payload: unknown;try {@@ -827,46 +773,48 @@ async function parseCancelTurnBody(req: Request): Promise<ParsedCancelTurnBody |if (payload === null || typeof payload !== "object" || Array.isArray(payload)) {return Response.json({ error: "Expected a JSON object.", ok: false }, { status: 400 });}+ return payload as Record<string, unknown>;+}- const turnId = (payload as { turnId?: unknown }).turnId;- if (turnId === undefined) {- return {};- }- if (typeof turnId !== "string" || turnId.length === 0) {- return Response.json(- { error: "Expected 'turnId' to be a non-empty string.", ok: false },- { status: 400 },- );- }- return { turnId };+function rejectSessionContinuationToken(payload: Record<string, unknown>): Response | null {+ return "continuationToken" in payload+ ? Response.json(+ { error: "Session-ID routes do not accept 'continuationToken'.", ok: false },+ { status: 400 },+ )+ : null;}-function createSendPayload(- body: ParsedCreateBody,- context = body.context,-):- | string- | UserContent- | {- readonly message: string | UserContent;- readonly context?: readonly string[];- readonly outputSchema?: JsonObject;- } {- if (context === undefined && body.outputSchema === undefined) {- return body.message;- }- const payload: {- message: string | UserContent;- context?: readonly string[];- outputSchema?: JsonObject;- } = { message: body.message };- if (context !== undefined) {- payload.context = context;- }- if (body.outputSchema !== undefined) {- payload.outputSchema = body.outputSchema;+function requireSessionId(params: Readonly<Record<string, string>>): string | Response {+ const sessionId = params.sessionId;+ return sessionId || Response.json({ error: "Missing session id.", ok: false }, { status: 400 });+}++async function createSessionStreamResponse(request: Request, session: Session): Promise<Response> {+ const startIndex = parseStartIndex(request);+ if (startIndex instanceof Response) return startIndex;+ const includeTailIndex = parseIncludeTailIndex(request);++ try {+ const tailIndex = includeTailIndex ? await session.getStreamTailIndex() : undefined;+ const events = await session.getEventStream({ startIndex });+ const headers = new Headers({+ "cache-control": "no-store, no-transform",+ "content-type": EVE_MESSAGE_STREAM_CONTENT_TYPE,+ "x-accel-buffering": "no",+ [EVE_SESSION_ID_HEADER]: session.id,+ [EVE_STREAM_FORMAT_HEADER]: EVE_MESSAGE_STREAM_FORMAT,+ [EVE_STREAM_VERSION_HEADER]: EVE_MESSAGE_STREAM_VERSION,+ });+ if (tailIndex !== undefined) {+ headers.set(EVE_STREAM_TAIL_INDEX_HEADER, String(tailIndex));+ }+ return new Response(serializeAsNdjson(events), {+ headers,+ });+ } catch {+ return Response.json({ error: "Session not found.", ok: false }, { status: 404 });}- return payload;}function parseOutputSchemaField(value: unknown): JsonObject | Response | undefined {@@ -1003,7 +951,7 @@ function parseMessagePart(raw: unknown): TextPart | FilePart | Response {}function checkUploadPolicy(- body: ParsedCreateBody | ParsedContinueBody,+ body: ParsedCreateBody | ParsedSessionMessageBody,policy: UploadPolicy,): Response | null {if (!body.message) return null;diff --git a/packages/eve/src/public/channels/github/dispatch.ts b/packages/eve/src/public/channels/github/dispatch.tsindex a7f36a9b0..cfddca4ac 100644--- a/packages/eve/src/public/channels/github/dispatch.ts+++ b/packages/eve/src/public/channels/github/dispatch.ts@@ -1,4 +1,5 @@import type { SessionAuthContext } from "#channel/types.js";+import type { ChannelFrom } from "#channel/channel-operations.js";import { createLogger, logError } from "#internal/logging.js";import { buildGitHubBinding } from "#public/channels/github/binding.js";@@ -39,7 +40,6 @@ import type {GitHubInboundResult,GitHubInboundResultOrPromise,} from "#public/channels/github/githubChannel.js";-import type { SendFn } from "#public/definitions/channel.js";const log = createLogger("github.dispatch");@@ -56,7 +56,7 @@ export async function dispatchIssueComment(input: {readonly config: GitHubChannelConfig;readonly event: GitHubIssueCommentEvent;readonly handler: NonNullable<GitHubChannelConfig["onComment"]>;- readonly send: SendFn<GitHubChannelState>;+ readonly from: ChannelFrom<GitHubChannelState>;}): Promise<void> {if (isIgnoredInboundComment(input.event.comment.body, input.event.comment.author, input.botName)@@ -71,7 +71,7 @@ export async function dispatchIssueComment(input: {event: input.event,handlerResult: () => input.handler(ctx, toGitHubComment(input.event.comment)),config: input.config,- send: input.send,+ from: input.from,state: stateFromIssueCommentEvent(input.event),});}@@ -82,7 +82,7 @@ export async function dispatchPullRequestReviewComment(input: {readonly config: GitHubChannelConfig;readonly event: GitHubPullRequestReviewCommentEvent;readonly handler: NonNullable<GitHubChannelConfig["onComment"]>;- readonly send: SendFn<GitHubChannelState>;+ readonly from: ChannelFrom<GitHubChannelState>;}): Promise<void> {if (isIgnoredInboundComment(input.event.comment.body, input.event.comment.author, input.botName)@@ -97,7 +97,7 @@ export async function dispatchPullRequestReviewComment(input: {event: input.event,handlerResult: () => input.handler(ctx, toGitHubComment(input.event.comment)),config: input.config,- send: input.send,+ from: input.from,state: stateFromPullRequestReviewCommentEvent(input.event),});}@@ -107,7 +107,7 @@ export async function dispatchIssue(input: {readonly config: GitHubChannelConfig;readonly event: GitHubIssueWebhookEvent;readonly handler: NonNullable<GitHubChannelConfig["onIssue"]>;- readonly send: SendFn<GitHubChannelState>;+ readonly from: ChannelFrom<GitHubChannelState>;}): Promise<void> {const ctx = buildInboundContext(input.config, input.event);await dispatchWebhookEventTurn({@@ -115,7 +115,7 @@ export async function dispatchIssue(input: {event: input.event,handlerResult: () => input.handler(ctx, input.event.issue),message: formatIssueEventMessage(input.event),- send: input.send,+ from: input.from,state: stateFromIssueEvent(input.event),});}@@ -125,7 +125,7 @@ export async function dispatchPullRequest(input: {readonly config: GitHubChannelConfig;readonly event: GitHubPullRequestWebhookEvent;readonly handler: NonNullable<GitHubChannelConfig["onPullRequest"]>;- readonly send: SendFn<GitHubChannelState>;+ readonly from: ChannelFrom<GitHubChannelState>;}): Promise<void> {const ctx = buildInboundContext(input.config, input.event);await dispatchWebhookEventTurn({@@ -133,7 +133,7 @@ export async function dispatchPullRequest(input: {event: input.event,handlerResult: () => input.handler(ctx, input.event.pullRequest),message: formatPullRequestEventMessage(input.event),- send: input.send,+ from: input.from,state: stateFromPullRequestEvent(input.event),});}@@ -143,7 +143,7 @@ export async function dispatchCheckSuite(input: {readonly config: GitHubChannelConfig;readonly event: GitHubCheckSuiteWebhookEvent;readonly handler: NonNullable<GitHubChannelConfig["onCheckSuite"]>;- readonly send: SendFn<GitHubChannelState>;+ readonly from: ChannelFrom<GitHubChannelState>;}): Promise<void> {await dispatchCiEvent({...input,@@ -158,7 +158,7 @@ export async function dispatchCheckRun(input: {readonly config: GitHubChannelConfig;readonly event: GitHubCheckRunWebhookEvent;readonly handler: NonNullable<GitHubChannelConfig["onCheckRun"]>;- readonly send: SendFn<GitHubChannelState>;+ readonly from: ChannelFrom<GitHubChannelState>;}): Promise<void> {await dispatchCiEvent({...input,@@ -173,7 +173,7 @@ export async function dispatchWorkflowRun(input: {readonly config: GitHubChannelConfig;readonly event: GitHubWorkflowRunWebhookEvent;readonly handler: NonNullable<GitHubChannelConfig["onWorkflowRun"]>;- readonly send: SendFn<GitHubChannelState>;+ readonly from: ChannelFrom<GitHubChannelState>;}): Promise<void> {await dispatchCiEvent({...input,@@ -189,7 +189,7 @@ async function dispatchCiEvent(input: {readonly event: GitHubCiWebhookEvent;readonly handlerResult: (ctx: GitHubInboundContext) => GitHubInboundResultOrPromise;readonly label: string;- readonly send: SendFn<GitHubChannelState>;+ readonly from: ChannelFrom<GitHubChannelState>;}): Promise<void> {const state = stateFromCiEvent(input.event);const ctx = buildInboundContext(input.config, input.event);@@ -212,7 +212,7 @@ async function dispatchCiEvent(input: {event: input.event,handlerResult: () => input.handlerResult(ctx),message: formatCiEventMessage(input.label, input.ci),- send: input.send,+ from: input.from,state,});}@@ -222,7 +222,7 @@ async function dispatchWebhookEventTurn(input: {readonly event: GitHubCiWebhookEvent | GitHubIssueWebhookEvent | GitHubPullRequestWebhookEvent;readonly handlerResult: () => GitHubInboundResultOrPromise;readonly message: string;- readonly send: SendFn<GitHubChannelState>;+ readonly from: ChannelFrom<GitHubChannelState>;readonly state: GitHubChannelState;}): Promise<void> {const result = await runInboundHandler({@@ -239,7 +239,7 @@ async function dispatchWebhookEventTurn(input: {github: await buildPullRequestContext(input.config, input.state, input.event.delivery.id),hook: result.context,}),- send: input.send,+ from: input.from,state: input.state,});}@@ -251,7 +251,7 @@ async function dispatchCommentTurn(input: {readonly config: GitHubChannelConfig;readonly event: GitHubIssueCommentEvent | GitHubPullRequestReviewCommentEvent;readonly handlerResult: () => GitHubInboundResultOrPromise;- readonly send: SendFn<GitHubChannelState>;+ readonly from: ChannelFrom<GitHubChannelState>;readonly state: GitHubChannelState;}): Promise<void> {const result = await runInboundHandler({@@ -275,7 +275,7 @@ async function dispatchCommentTurn(input: {github: await buildPullRequestContext(input.config, input.state, input.event.delivery.id),hook: result.context,}),- send: input.send,+ from: input.from,state: input.state,});}@@ -301,7 +301,7 @@ async function sendGitHubTurn(input: {readonly logMessage?: string;readonly message: string;readonly context: readonly string[] | undefined;- readonly send: SendFn<GitHubChannelState>;+ readonly from: ChannelFrom<GitHubChannelState>;readonly state: GitHubChannelState;}): Promise<void> {const contextBlock = formatGitHubContextBlock({@@ -316,17 +316,11 @@ async function sendGitHubTurn(input: {const turnMessage = prependGitHubContext(input.message, contextBlock);try {- await input.send(- {- message: turnMessage,- context: input.context,- },- {- auth: input.auth,- continuationToken: continuationTokenFromState(input.state),- state: input.state,- },- );+ await input.from(continuationTokenFromState(input.state)).send(turnMessage, {+ auth: input.auth,+ context: input.context,+ state: input.state,+ });} catch (error) {logError(log, input.logMessage ?? "GitHub delivery failed", error, {deliveryId: input.event.delivery.id,diff --git a/packages/eve/src/public/channels/github/githubChannel.test.ts b/packages/eve/src/public/channels/github/githubChannel.test.tsindex 93a64ddaf..67ed8c4f6 100644--- a/packages/eve/src/public/channels/github/githubChannel.test.ts+++ b/packages/eve/src/public/channels/github/githubChannel.test.ts@@ -6,6 +6,7 @@ import { isCompiledChannel, type CompiledChannel } from "#channel/compiled-channimport { isHttpRouteDefinition } from "#channel/routes.js";import { ContextContainer, contextStorage } from "#context/container.js";import { SandboxKey, SessionKey } from "#context/keys.js";+import { mockChannelContext } from "#internal/testing/mocks/mock-channel-operations.js";import { mockSandbox, type MockSandbox } from "#internal/testing/mocks/mock-sandbox.js";import type { UnstampedMessageStreamEvent } from "#protocol/message.js";import {@@ -167,20 +168,15 @@ async function firePost(if (!post || !isHttpRouteDefinition(post)) {throw new Error("Expected github channel to define a POST route.");}- const send = vi.fn().mockResolvedValue({ continuationToken: "github:test", id: "s1" });+ const send = vi.fn().mockResolvedValue({ id: "s1" });const waitUntil = vi.fn();const response = await post.handler(request, {- cancel: vi.fn(),- clear: vi.fn(),- compact: vi.fn(),- reset: vi.fn(),- resolveActiveSession: async () => undefined,- getSession: vi.fn() as any,+ attachSession: vi.fn() as any,+ ...mockChannelContext(send),params: {},- receive: vi.fn() as any,+ to: vi.fn() as any,requestIp: null,- send,waitUntil,});@@ -234,11 +230,12 @@ describe("githubChannel", () => {);expect(send).toHaveBeenCalledTimes(1);- const [payload, options] = send.mock.calls[0]!;- expect(payload.message).toContain("<github_context>");- expect(payload.message).toContain("help me");- expect(payload.inputResponses).toBeUndefined();- expect(options).toMatchObject({+ const [continuationToken, input] = send.mock.calls[0]!;+ expect(input.message).toContain("<github_context>");+ expect(input.message).toContain("help me");+ expect(input.inputResponses).toBeUndefined();+ expect(continuationToken).toBe("repo:123:issue:5");+ expect(input).toMatchObject({auth: {attributes: {conversation_kind: "issue",@@ -250,7 +247,6 @@ describe("githubChannel", () => {authenticator: "github-webhook",principalId: "github:1",},- continuationToken: "repo:123:issue:5",state: {conversationKind: "issue",issueNumber: 5,@@ -284,16 +280,16 @@ describe("githubChannel", () => {);expect(send).toHaveBeenCalledTimes(1);- const [payload, options] = send.mock.calls[0]!;- expect(payload.message).toContain("delivery_id: inferred:issue_comment:10:created");- expect(payload.message).toContain("help me");- expect(options).toMatchObject({+ const [continuationToken, input] = send.mock.calls[0]!;+ expect(input.message).toContain("delivery_id: inferred:issue_comment:10:created");+ expect(input.message).toContain("help me");+ expect(continuationToken).toBe("repo:123:issue:5");+ expect(input).toMatchObject({auth: {attributes: {delivery_id: "inferred:issue_comment:10:created",},},- continuationToken: "repo:123:issue:5",});expect(warn).toHaveBeenCalledWith("[eve:github.channel] GitHub webhook missing standard headers; inferred metadata from payload",@@ -407,9 +403,9 @@ describe("githubChannel", () => {);expect(fetchMock.mock.calls[0]?.[0]).toBe("https://github.test/repos/vercel/eve/pulls/7");- const [payload] = send.mock.calls[0]!;- expect(payload.context?.[0]).toContain("title: Add GitHub context");- expect(payload.context?.[0]).toContain("head_sha: head-sha");+ const [, input] = send.mock.calls[0]!;+ expect(input.context?.[0]).toContain("title: Add GitHub context");+ expect(input.context?.[0]).toContain("head_sha: head-sha");});it("dispatches inline review comments to the review-thread token", async () => {@@ -435,8 +431,8 @@ describe("githubChannel", () => {),);+ expect(send.mock.calls[0]?.[0]).toBe("repo:123:pull:7:review-comment:99");expect(send.mock.calls[0]?.[1]).toMatchObject({- continuationToken: "repo:123:pull:7:review-comment:99",state: {conversationKind: "review_thread",headSha: "abc123",@@ -498,10 +494,10 @@ describe("githubChannel", () => {expect.objectContaining({ action: "opened", issueNumber: 5 }),);expect(send).toHaveBeenCalledTimes(1);- const [payload, options] = send.mock.calls[0]!;- expect(payload.message).toContain("Issue opened: #5 Track webhook issue events");- expect(options).toMatchObject({- continuationToken: "repo:123:issue:5",+ const [continuationToken, input] = send.mock.calls[0]!;+ expect(input.message).toContain("Issue opened: #5 Track webhook issue events");+ expect(continuationToken).toBe("repo:123:issue:5");+ expect(input).toMatchObject({state: {conversationKind: "issue",issueNumber: 5,@@ -549,10 +545,10 @@ describe("githubChannel", () => {expect.objectContaining({ action: "opened", headSha, pullRequestNumber: 7 }),);expect(send).toHaveBeenCalledTimes(1);- const [payload, options] = send.mock.calls[0]!;- expect(payload.message).toContain("Pull request opened: #7 Add webhook PR handling");- expect(options).toMatchObject({- continuationToken: "repo:123:pull:7",+ const [continuationToken, input] = send.mock.calls[0]!;+ expect(input.message).toContain("Pull request opened: #7 Add webhook PR handling");+ expect(continuationToken).toBe("repo:123:pull:7");+ expect(input).toMatchObject({state: {baseRef: "main",baseSha,@@ -635,10 +631,10 @@ describe("githubChannel", () => {}),);expect(send).toHaveBeenCalledTimes(1);- const [payload, options] = send.mock.calls[0]!;- expect(payload.message).toContain(`${testCase.label} completed: 9001 (failure)`);- expect(options).toMatchObject({- continuationToken: "repo:123:pull:7",+ const [continuationToken, input] = send.mock.calls[0]!;+ expect(input.message).toContain(`${testCase.label} completed: 9001 (failure)`);+ expect(continuationToken).toBe("repo:123:pull:7");+ expect(input).toMatchObject({state: {conversationKind: "pull_request",headSha,diff --git a/packages/eve/src/public/channels/github/githubChannel.ts b/packages/eve/src/public/channels/github/githubChannel.tsindex 48abb061f..1f8f706b0 100644--- a/packages/eve/src/public/channels/github/githubChannel.ts+++ b/packages/eve/src/public/channels/github/githubChannel.ts@@ -1,7 +1,7 @@import type { SessionHandle } from "#channel/session.js";import type { SessionAuthContext } from "#channel/types.js";import type { SessionContext } from "#public/definitions/callback-context.js";-import type { ChannelSessionOps } from "#public/definitions/channel.js";+import type { ChannelContinuationOps } from "#public/definitions/channel.js";import { createLogger } from "#internal/logging.js";import type { UnstampedMessageStreamEvent } from "#protocol/message.js";@@ -94,8 +94,8 @@ export interface GitHubChannelContext {state: GitHubChannelState;}-/** Event-handler GitHub context, including session operations. */-export interface GitHubEventContext extends GitHubChannelContext, ChannelSessionOps {}+/** Event-handler GitHub context, including continuation routing. */+export interface GitHubEventContext extends GitHubChannelContext, ChannelContinuationOps {}/*** Result of a GitHub inbound hook. Return `null` to acknowledge without@@ -240,7 +240,7 @@ export function githubChannel(config: GitHubChannelConfig = {}): GitHubChannel {routes: [POST<GitHubChannelState>(config.route ?? GITHUB_CHANNEL_DEFAULT_ROUTE,- async (req, { send, waitUntil }) => {+ async (req, { from, waitUntil }) => {const body = await verifyInbound(req, config.credentials);if (body === null) return new Response("unauthorized", { status: 401 });const missingHeaders = missingGitHubWebhookHeaders(req.headers);@@ -284,7 +284,7 @@ export function githubChannel(config: GitHubChannelConfig = {}): GitHubChannel {handler:config.onComment ??((ctx, comment) => defaultOnComment(ctx, comment, dispatchOptions)),- send,+ from,}),);return jsonOk({ ok: true });@@ -299,7 +299,7 @@ export function githubChannel(config: GitHubChannelConfig = {}): GitHubChannel {handler:config.onComment ??((ctx, comment) => defaultOnComment(ctx, comment, dispatchOptions)),- send,+ from,}),);return jsonOk({ ok: true });@@ -311,7 +311,7 @@ export function githubChannel(config: GitHubChannelConfig = {}): GitHubChannel {config,event,handler: config.onIssue,- send,+ from,}),);return jsonOk({ ok: true });@@ -323,7 +323,7 @@ export function githubChannel(config: GitHubChannelConfig = {}): GitHubChannel {config,event,handler: config.onPullRequest,- send,+ from,}),);return jsonOk({ ok: true });@@ -335,7 +335,7 @@ export function githubChannel(config: GitHubChannelConfig = {}): GitHubChannel {config,event,handler: config.onCheckSuite,- send,+ from,}),);return jsonOk({ ok: true });@@ -347,7 +347,7 @@ export function githubChannel(config: GitHubChannelConfig = {}): GitHubChannel {config,event,handler: config.onCheckRun,- send,+ from,}),);return jsonOk({ ok: true });@@ -359,7 +359,7 @@ export function githubChannel(config: GitHubChannelConfig = {}): GitHubChannel {config,event,handler: config.onWorkflowRun,- send,+ from,}),);return jsonOk({ ok: true });@@ -370,7 +370,7 @@ export function githubChannel(config: GitHubChannelConfig = {}): GitHubChannel {),],- async receive(input, { send }) {+ async receive(input, { from }) {const target = input.target as Partial<GitHubReceiveTarget>;const owner = readNonEmptyString(target.owner);const repo = readNonEmptyString(target.repo);@@ -412,9 +412,8 @@ export function githubChannel(config: GitHubChannelConfig = {}): GitHubChannel {await thread.post(target.initialMessage);}- return send(input.message, {+ return from(continuationTokenFromState(state)).send(input.message, {auth: input.auth,- continuationToken: continuationTokenFromState(state),state,});},diff --git a/packages/eve/src/public/channels/github/pr-context.ts b/packages/eve/src/public/channels/github/pr-context.tsindex 9fa43a99a..8b914ae75 100644--- a/packages/eve/src/public/channels/github/pr-context.ts+++ b/packages/eve/src/public/channels/github/pr-context.ts@@ -75,7 +75,7 @@ export interface GitHubPullRequestContextInput {* Builds bounded, one-shot pull-request background for a GitHub turn: PR* metadata plus the changed-file diff (noisy files excluded from the patch).*- * The returned strings are intended for `SendPayload.context`; each is appended+ * The returned strings are intended for a send operation's `context`; each is appended* as a `role: "user"` message to session history before the delivery message.*/export async function buildGitHubPullRequestContext(diff --git a/packages/eve/src/public/channels/index.ts b/packages/eve/src/public/channels/index.tsindex b2b87af48..f1cd65306 100644--- a/packages/eve/src/public/channels/index.ts+++ b/packages/eve/src/public/channels/index.ts@@ -6,33 +6,31 @@ export {PATCH,DELETE,WS,- type CancelFn,- type CancelOptions,+ type AttachSessionFn,type CancelTurnResult,- type ClearFn,- type ClearOptions,type ClearSessionResult,- type CompactFn,- type CompactOptions,type CompactSessionResult,+ type ResetSessionResult,type Channel,+ type ChannelFrom,+ type ChannelReceiveContext,+ type ChannelResolveSession,+ type ChannelRespondOptions,+ type ChannelSendOptions,+ type ChannelSource,type ChannelCors,type ChannelCorsOptions,type ChannelDefinition,- type ChannelSessionOps,+ type ChannelContinuationOps,type ChannelEvents,type InferChannelMetadata,type Session,+ type SessionCallback,type SessionHandle,+ type SessionRespondOptions,+ type SessionSendOptions,type RouteDefinition,type RouteHandlerArgs,- type ResetFn,- type ResetOptions,- type ResetResult,- type SendFn,- type SendOptions,- type SendPayload,- type GetSessionFn,type HttpRouteDefinition,type WebSocketMessage,type WebSocketPeer,diff --git a/packages/eve/src/public/channels/linear/linearChannel.test.ts b/packages/eve/src/public/channels/linear/linearChannel.test.tsindex 1b534360d..5eece9699 100644--- a/packages/eve/src/public/channels/linear/linearChannel.test.ts+++ b/packages/eve/src/public/channels/linear/linearChannel.test.ts@@ -6,6 +6,7 @@ import { isCompiledChannel, type CompiledChannel } from "#channel/compiled-channimport { isHttpRouteDefinition } from "#channel/routes.js";import { ContextContainer, contextStorage } from "#context/container.js";import { SessionKey } from "#context/keys.js";+import { mockChannelContext } from "#internal/testing/mocks/mock-channel-operations.js";import type { UnstampedMessageStreamEvent } from "#protocol/message.js";import { linearChannel, type LinearChannelState } from "#public/channels/linear/linearChannel.js";import { signLinearWebhookBody } from "#public/channels/linear/verify.js";@@ -122,20 +123,15 @@ async function firePost(if (!post || !isHttpRouteDefinition(post)) {throw new Error("Expected linear channel to define a POST route.");}- const send = vi.fn().mockResolvedValue({ continuationToken: "linear:test", id: "s1" });+ const send = vi.fn().mockResolvedValue({ id: "s1" });const waitUntil = vi.fn();const response = await post.handler(request, {- cancel: vi.fn(),- clear: vi.fn(),- compact: vi.fn(),- reset: vi.fn(),- resolveActiveSession: async () => undefined,- getSession: vi.fn() as any,+ attachSession: vi.fn() as any,+ ...mockChannelContext(send),params: {},- receive: vi.fn() as any,+ to: vi.fn() as any,requestIp: null,- send,waitUntil,});@@ -166,16 +162,16 @@ describe("linearChannel inbound Agent Session events", () => {expect(response.status).toBe(200);expect(send).toHaveBeenCalledTimes(1);- const [payload, options] = send.mock.calls[0]!;- expect(payload.message).toBe("Please handle this issue.");- expect(payload.context[0]).toContain("<linear_context>");- expect(payload.context[0]).toContain("issue_identifier: EVE-123");- expect(options).toMatchObject({+ const [continuationToken, input] = send.mock.calls[0]!;+ expect(input.message).toBe("Please handle this issue.");+ expect(input.context?.[0]).toContain("<linear_context>");+ expect(input.context?.[0]).toContain("issue_identifier: EVE-123");+ expect(continuationToken).toBe("agent-session:agent_session_1");+ expect(input).toMatchObject({auth: {authenticator: "linear-agent-webhook",principalId: "linear:user_1",},- continuationToken: "agent-session:agent_session_1",state: {agentSessionId: "agent_session_1",issueId: "issue_1",@@ -203,9 +199,9 @@ describe("linearChannel inbound Agent Session events", () => {);expect(send).toHaveBeenCalledTimes(1);- const [payload] = send.mock.calls[0]!;- expect(payload.inputResponses).toBeUndefined();- expect(payload.message).toBe("approve");+ const [, input] = send.mock.calls[0]!;+ expect(input.inputResponses).toBeUndefined();+ expect(input.message).toBe("approve");});it("attaches authenticated Linear upload images to prompted messages", async () => {@@ -240,10 +236,10 @@ describe("linearChannel inbound Agent Session events", () => {expect(new Headers(fetchMock.mock.calls[0]?.[1]?.headers).get("authorization")).toBe("Bearer linear-token",);- const [payload] = send.mock.calls[0]!;- expect(payload.message[0]).toEqual({ text: "Inspect screenshot.", type: "text" });- expect(payload.message[1]).toMatchObject({ mediaType: "image/webp", type: "file" });- expect(payload.message[1].data).toEqual(Buffer.from([1, 2, 3]));+ const [, input] = send.mock.calls[0]!;+ expect(input.message?.[0]).toEqual({ text: "Inspect screenshot.", type: "text" });+ expect(input.message?.[1]).toMatchObject({ mediaType: "image/webp", type: "file" });+ expect(input.message?.[1]?.data).toEqual(Buffer.from([1, 2, 3]));});it("acks generic data webhooks without dispatch when no hook is configured", async () => {@@ -502,7 +498,7 @@ describe("linearChannel default event handlers", () => {it("receive starts a session from an existing Agent Session id", async () => {const channel = linearChannel();- const send = vi.fn().mockResolvedValue({ continuationToken: "linear:test", id: "s1" });+ const send = vi.fn().mockResolvedValue({ id: "s1" });await channel.receive!({@@ -510,12 +506,14 @@ describe("linearChannel default event handlers", () => {message: "start",target: { agentSessionId: "agent_session_1" },},- { send },+ {+ ...mockChannelContext(send),+ },);- expect(send).toHaveBeenCalledWith("start", {+ expect(send).toHaveBeenCalledWith("agent-session:agent_session_1", {auth: null,- continuationToken: "agent-session:agent_session_1",+ message: "start",state: {agentSessionId: "agent_session_1",agentSessionUrl: null,@@ -550,7 +548,7 @@ describe("linearChannel default event handlers", () => {api: { apiBaseUrl: "https://linear.test/graphql", fetch: fetchMock },credentials: { accessToken: "linear-token" },});- const send = vi.fn().mockResolvedValue({ continuationToken: "linear:test", id: "s1" });+ const send = vi.fn().mockResolvedValue({ id: "s1" });await channel.receive!({@@ -558,15 +556,17 @@ describe("linearChannel default event handlers", () => {message: "start",target: { issueId: "issue_1" },},- { send },+ {+ ...mockChannelContext(send),+ },);expect(requestBody(fetchMock.mock.calls[0]?.[1])).toMatchObject({variables: { input: { issueId: "issue_1" } },});- expect(send).toHaveBeenCalledWith("start", {+ expect(send).toHaveBeenCalledWith("agent-session:agent_session_2", {auth: null,- continuationToken: "agent-session:agent_session_2",+ message: "start",state: expect.objectContaining({agentSessionId: "agent_session_2",issueId: "issue_1",diff --git a/packages/eve/src/public/channels/linear/linearChannel.ts b/packages/eve/src/public/channels/linear/linearChannel.tsindex d6c020f2b..8abc71003 100644--- a/packages/eve/src/public/channels/linear/linearChannel.ts+++ b/packages/eve/src/public/channels/linear/linearChannel.ts@@ -1,5 +1,6 @@import type { SessionHandle } from "#channel/session.js";import type { SessionAuthContext } from "#channel/types.js";+import type { ChannelFrom } from "#channel/channel-operations.js";import { createLogger } from "#internal/logging.js";import type { UnstampedMessageStreamEvent } from "#protocol/message.js";import {@@ -31,8 +32,7 @@ import {defineChannel,POST,type Channel,- type ChannelSessionOps,- type SendFn,+ type ChannelContinuationOps,} from "#public/definitions/channel.js";import { isObject, readNonEmptyString } from "#shared/guards.js";import type { JsonObject } from "#shared/json.js";@@ -102,8 +102,8 @@ export interface LinearChannelContext {state: LinearChannelState;}-/** Event-handler Linear context, including session operations. */-export interface LinearEventContext extends LinearChannelContext, ChannelSessionOps {}+/** Event-handler Linear context, including continuation routing. */+export interface LinearEventContext extends LinearChannelContext, ChannelContinuationOps {}/** Low-level Linear handle exposed to hooks and event handlers. */export interface LinearHandle {@@ -224,7 +224,7 @@ export function linearChannel(config: LinearChannelConfig = {}): LinearChannel {routes: [POST<LinearChannelState>(config.route ?? LINEAR_CHANNEL_DEFAULT_ROUTE,- async (req, { send, waitUntil }) => {+ async (req, { from, waitUntil }) => {const body = await verifyInbound(req, config.credentials);if (body === null) return new Response("unauthorized", { status: 401 });@@ -239,7 +239,7 @@ export function linearChannel(config: LinearChannelConfig = {}): LinearChannel {if (event === null) return jsonOk({ ignored: true, ok: true });if (event.kind === "agent_session") {- waitUntil(dispatchAgentSession({ config, event, onAgentSession, send }));+ waitUntil(dispatchAgentSession({ config, event, from, onAgentSession }));return jsonOk({ ok: true });}@@ -253,7 +253,7 @@ export function linearChannel(config: LinearChannelConfig = {}): LinearChannel {),],- async receive(input, { send }) {+ async receive(input, { from }) {const target = input.target as Record<string, unknown>;const session = await resolveReceiveSession(target, config);@@ -269,9 +269,8 @@ export function linearChannel(config: LinearChannelConfig = {}): LinearChannel {});}- return send(input.message, {+ return from(linearContinuationToken(session.id)).send(input.message, {auth: input.auth,- continuationToken: linearContinuationToken(session.id),state: stateFromAgentSession(session),});},@@ -330,10 +329,10 @@ function buildLinearHandle(input: {}async function dispatchAgentSession(input: {+ readonly from: ChannelFrom<LinearChannelState>;readonly config: LinearChannelConfig;readonly event: LinearAgentSessionEvent;readonly onAgentSession: NonNullable<LinearChannelConfig["onAgentSession"]>;- readonly send: SendFn<LinearChannelState>;}): Promise<void> {const { event } = input;const context: LinearSessionContext = {@@ -350,21 +349,15 @@ async function dispatchAgentSession(input: {fetch: input.config.api?.fetch,});- await input.send(- {- context: [- formatLinearContextBlock(event),- ...event.previousComments,- ...(result.context ?? []),- ],- message,- },- {- auth: result.auth,- continuationToken: linearContinuationToken(event.agentSession.id),- state: stateFromAgentSession(event.agentSession),- },- );+ await input.from(linearContinuationToken(event.agentSession.id)).send(message, {+ auth: result.auth,+ context: [+ formatLinearContextBlock(event),+ ...event.previousComments,+ ...(result.context ?? []),+ ],+ state: stateFromAgentSession(event.agentSession),+ });}async function resolveReceiveSession(diff --git a/packages/eve/src/public/channels/photon/photonIMessageChannel.test.ts b/packages/eve/src/public/channels/photon/photonIMessageChannel.test.tsindex e52be32b9..95b73a637 100644--- a/packages/eve/src/public/channels/photon/photonIMessageChannel.test.ts+++ b/packages/eve/src/public/channels/photon/photonIMessageChannel.test.ts@@ -34,7 +34,7 @@ describe("photonIMessageChannel", () => {vi.clearAllMocks();});- it("cancels the active Eve turn before steering a direct message into its thread", async () => {+ it("cancels the active eve turn before steering a direct message into its thread", async () => {photonIMessageChannel({credentials: async () => ({ projectId: "project-id", projectSecret: "project-secret" }),});diff --git a/packages/eve/src/public/channels/slack/index.ts b/packages/eve/src/public/channels/slack/index.tsindex b21e93335..027def271 100644--- a/packages/eve/src/public/channels/slack/index.ts+++ b/packages/eve/src/public/channels/slack/index.ts@@ -12,18 +12,17 @@ export {type SlackAuthorizationEventContext,type SlackAuthorizationRequiredHandler,type SlackBotToken,- type SlackCancelOptions,type SlackChannel,type SlackChannelConfig,type SlackChannelCredentials,type SlackChannelEvents,type SlackChannelState,type SlackContext,- type SlackEventCancelOptions,type SlackEventContext,- type SlackEventReceiveFn,- type SlackEventReceiveOptions,- type SlackEventResetOptions,+ type SlackEventRespondFn,+ type SlackEventRespondOptions,+ type SlackEventSendFn,+ type SlackEventSendOptions,type SlackHandle,type SlackInboundEventContext,type SlackInboundMessageContext,@@ -36,8 +35,10 @@ export {type SlackMentionResult,type SlackMentionResultOrPromise,type SlackReceiveTarget,- type SlackResetOptions,type SlackSessionTarget,+ type SlackRespondOptions,+ type SlackSendOptions,+ type SlackSessionOperations,type SlackThread,type SlackWebhookVerifier,type SlackWorkspaceHandle,diff --git a/packages/eve/src/public/channels/slack/interactions.ts b/packages/eve/src/public/channels/slack/interactions.tsindex b8ca0d119..f4f341eb6 100644--- a/packages/eve/src/public/channels/slack/interactions.ts+++ b/packages/eve/src/public/channels/slack/interactions.ts@@ -53,7 +53,8 @@ import type {SlackInteractionContext,SlackInteractionUser,} from "#public/channels/slack/slackChannel.js";-import type { CancelFn, ResetFn, SendFn } from "#public/definitions/channel.js";+import type { ChannelFrom, ChannelResolveSession } from "#channel/channel-operations.js";+import { bindSlackSessionOperations } from "#public/channels/slack/session-operations.js";const log = createLogger("slack.interactions");@@ -339,9 +340,8 @@ export interface InteractionHandlerDeps {export async function handleInteractionPost(rawBody: string,ctx: {- cancel: CancelFn;- reset: ResetFn;- send: SendFn<SlackChannelState>;+ from: ChannelFrom<SlackChannelState>;+ resolveSession: ChannelResolveSession;waitUntil: (task: Promise<unknown>) => void;},deps: InteractionHandlerDeps,@@ -384,25 +384,16 @@ export async function handleInteractionPost(ctx.waitUntil(ctx- .send(- { inputResponses },- {- auth: buildSlackAuthContext({- channelId: interaction.channelId,- teamId: interaction.teamId,- threadTs: interaction.threadTs,- userId: user.id,- userName: user.username ?? user.name,- }),- continuationToken,- state: {- channelId: interaction.channelId,- threadTs: interaction.threadTs,- teamId: interaction.teamId ?? null,- triggeringUserId: user.id,- },- },- )+ .from(continuationToken)+ .respond(inputResponses, {+ auth: buildSlackAuthContext({+ channelId: interaction.channelId,+ teamId: interaction.teamId,+ threadTs: interaction.threadTs,+ userId: user.id,+ userName: user.username ?? user.name,+ }),+ }).catch((error: unknown) => {log.error("HITL interaction delivery failed", { error });}),@@ -419,6 +410,7 @@ export async function handleInteractionPost(if (onInteraction) {const customActions = interaction.actions.filter((a) => !isHitlAction(a.actionId));if (customActions.length > 0) {+ const actionUser = customActions[0]!.user;const { thread, slack } = buildSlackBinding({botToken: deps.config.credentials?.botToken,channelId: interaction.channelId,@@ -426,16 +418,24 @@ export async function handleInteractionPost(teamId: interaction.teamId,});const slackCtx: SlackInteractionContext = {- cancel: (options = {}) =>- ctx.cancel({- continuationToken,- turnId: options.turnId,- }),- reset: (options = {}) =>- ctx.reset({- continuationToken,- reason: options.reason,+ ...bindSlackSessionOperations({+ address: continuationToken,+ defaultAuth: buildSlackAuthContext({+ channelId: interaction.channelId,+ teamId: interaction.teamId,+ threadTs: interaction.threadTs,+ userId: actionUser.id,+ userName: actionUser.username ?? actionUser.name,}),+ from: ctx.from,+ resolveSession: ctx.resolveSession,+ state: {+ channelId: interaction.channelId,+ teamId: interaction.teamId ?? null,+ threadTs: interaction.threadTs,+ triggeringUserId: actionUser.id,+ },+ }),thread,slack,};@@ -508,7 +508,7 @@ async function openFreeformModal(input: {async function handleViewSubmission(payload: SlackViewSubmissionPayload,ctx: {- send: SendFn<SlackChannelState>;+ from: ChannelFrom<SlackChannelState>;waitUntil: (task: Promise<unknown>) => void;},_deps: InteractionHandlerDeps,@@ -550,25 +550,16 @@ async function handleViewSubmission(ctx.waitUntil(ctx- .send(- { inputResponses: [{ requestId: metadata.requestId, text }] },- {- auth: buildSlackAuthContext({- channelId: metadata.channelId,- teamId,- threadTs: metadata.threadTs,- userId: triggeringUserId,- userName: user?.username ?? user?.name,- }),- continuationToken: metadata.continuationToken,- state: {- channelId: metadata.channelId,- threadTs: metadata.threadTs,- teamId,- triggeringUserId,- },- },- )+ .from(metadata.continuationToken)+ .respond([{ requestId: metadata.requestId, text }], {+ auth: buildSlackAuthContext({+ channelId: metadata.channelId,+ teamId,+ threadTs: metadata.threadTs,+ userId: triggeringUserId,+ userName: user?.username ?? user?.name,+ }),+ }).catch((error: unknown) => {log.error("freeform answer delivery failed", { error });}),diff --git a/packages/eve/src/public/channels/slack/session-operations.ts b/packages/eve/src/public/channels/slack/session-operations.tsnew file mode 100644index 000000000..37e0c83d2--- /dev/null+++ b/packages/eve/src/public/channels/slack/session-operations.ts@@ -0,0 +1,81 @@+import type {+ ChannelFrom,+ ChannelResolveSession,+ ChannelRespondOptions,+ ChannelSendOptions,+ ChannelSource,+} from "#channel/channel-operations.js";+import type { SessionAuthContext } from "#channel/types.js";+import type { InputResponse } from "#runtime/input/types.js";+import type { UserContent } from "ai";+import type { SlackChannelState } from "#public/channels/slack/slackChannel.js";++type SlackSource = ChannelSource<SlackChannelState>;++/** Options for a message send already bound to one Slack thread. */+export type SlackSendOptions = Omit<ChannelSendOptions<SlackChannelState>, "auth" | "state"> & {+ readonly auth?: SessionAuthContext | null;+};++/** Options for an input response already bound to one Slack thread. */+export type SlackRespondOptions = Omit<ChannelRespondOptions, "auth"> & {+ readonly auth?: SessionAuthContext | null;+};++/** Current-owner operations already bound to one Slack thread. */+export interface SlackSessionOperations {+ send(message: string | UserContent, options?: SlackSendOptions): ReturnType<SlackSource["send"]>;+ respond(+ inputResponses: readonly InputResponse[],+ options?: SlackRespondOptions,+ ): ReturnType<SlackSource["respond"]>;+ cancel(options?: { readonly turnId?: string }): ReturnType<SlackSource["cancel"]>;+ compact(): ReturnType<SlackSource["compact"]>;+ clear(): ReturnType<SlackSource["clear"]>;+ reset(options?: { readonly reason?: string }): ReturnType<SlackSource["reset"]>;+ resolveSession(): ReturnType<ChannelResolveSession>;+}++/** Binds Slack state and default auth needed only when a message creates a session. */+export function bindSlackSessionOperations(input: {+ readonly address: string;+ readonly defaultAuth: SessionAuthContext | null;+ readonly from: ChannelFrom<SlackChannelState>;+ readonly resolveSession: ChannelResolveSession;+ readonly state: SlackChannelState;+}): SlackSessionOperations {+ const source = input.from(input.address);+ const auth = (value: SessionAuthContext | null | undefined) =>+ value === undefined ? input.defaultAuth : value;++ return {+ async send(message, options = {}) {+ return await source.send(message, {+ ...options,+ auth: auth(options.auth),+ state: input.state,+ });+ },+ async respond(inputResponses, options = {}) {+ return await source.respond(inputResponses, {+ ...options,+ auth: auth(options.auth),+ });+ },+ async cancel(options) {+ return await source.cancel(options);+ },+ async compact() {+ return await source.compact();+ },+ async clear() {+ return await source.clear();+ },+ async reset(options) {+ return await source.reset(options);+ },+ async resolveSession() {+ return await input.resolveSession(input.address);+ },+ };+}diff --git a/packages/eve/src/public/channels/slack/slackChannel.test.ts b/packages/eve/src/public/channels/slack/slackChannel.test.tsindex 123fdd5aa..fb791cba6 100644--- a/packages/eve/src/public/channels/slack/slackChannel.test.ts+++ b/packages/eve/src/public/channels/slack/slackChannel.test.ts@@ -5,9 +5,14 @@ import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from "vitesimport { buildAdapterContext } from "#channel/adapter-context.js";import { callAdapterEventHandler, type ChannelAdapter } from "#channel/adapter.js";import { isCompiledChannel, type CompiledChannel } from "#channel/compiled-channel.js";+import type { ChannelFrom, ChannelSource } from "#channel/channel-operations.js";import { isHttpRouteDefinition } from "#channel/routes.js";import { ContextContainer, contextStorage } from "#context/container.js";import { SessionKey } from "#context/keys.js";+import {+ mockChannelContext,+ type ObservedChannelDelivery,+} from "#internal/testing/mocks/mock-channel-operations.js";import type { UnstampedMessageStreamEvent } from "#protocol/message.js";import { decodeSlackApiBody } from "#public/channels/slack/api-encoding.js";import {@@ -86,7 +91,7 @@ function callEvent(/*** Accessor whose `set` writes are captured so tests can assert on- * `setContinuationToken` flowing through the SessionHandle. Returns+ * `continuation.rekey` flowing through the SessionHandle. Returns* undefined for unset keys (matching the real `ContextContainer`* behavior), while seeding the current continuation token so* SessionHandle can preserve the runtime namespace.@@ -250,13 +255,16 @@ async function firePost(channel: unknown,request: Request,overrides: {- readonly cancel?: ReturnType<typeof vi.fn>;- readonly reset?: ReturnType<typeof vi.fn>;- readonly resolveActiveSession?: ReturnType<typeof vi.fn>;+ readonly cancel?: (address: string, options?: { readonly turnId?: string }) => Promise<unknown>;+ readonly clear?: (address: string) => Promise<unknown>;+ readonly compact?: (address: string) => Promise<unknown>;+ readonly reset?: (address: string, options?: { readonly reason?: string }) => Promise<unknown>;+ readonly resolveSession?: (address: string) => Promise<unknown>;+ readonly send?: ReturnType<typeof vi.fn>;} = {},): Promise<{- cancel: ReturnType<typeof vi.fn>;- reset: ReturnType<typeof vi.fn>;+ cancel: ReturnType<typeof vi.fn<(options?: Record<string, unknown>) => Promise<unknown>>>;+ reset: ReturnType<typeof vi.fn<(options?: Record<string, unknown>) => Promise<unknown>>>;response: Response;send: ReturnType<typeof vi.fn>;waitUntil: ReturnType<typeof vi.fn>;@@ -266,24 +274,49 @@ async function firePost(if (!post || !isHttpRouteDefinition(post)) {throw new Error("Expected slack channel to define a POST route.");}- const cancel = overrides.cancel ?? vi.fn().mockResolvedValue({ status: "accepted" });- const reset =- overrides.reset ??- vi.fn().mockResolvedValue({ status: "reset", previousSessionId: "session_previous" });- const send = vi.fn().mockResolvedValue({ id: "s1", continuationToken: "ct" });+ const cancel = vi+ .fn<(options?: Record<string, unknown>) => Promise<unknown>>()+ .mockResolvedValue({ sessionId: "session_current", status: "accepted" });+ const reset = vi+ .fn<(options?: Record<string, unknown>) => Promise<unknown>>()+ .mockResolvedValue({ status: "reset", previousSessionId: "session_previous" });+ const send = vi.fn().mockResolvedValue({ id: "s1" });+ const observeSend = overrides.send ?? send;+ const baseFrom = mockChannelContext<SlackChannelState>(+ observeSend as (address: string, input: ObservedChannelDelivery<SlackChannelState>) => unknown,+ ).from;+ const from: ChannelFrom<SlackChannelState> = (address) => {+ const source = baseFrom(address);+ return {+ ...source,+ cancel: (options) =>+ (overrides.cancel?.(address, options) ??+ cancel({ ...options, continuationToken: address })) as ReturnType<+ ChannelSource<SlackChannelState>["cancel"]+ >,+ clear: () =>+ (overrides.clear?.(address) ??+ Promise.resolve({ sessionId: "s1", status: "accepted" })) as never,+ compact: () =>+ (overrides.compact?.(address) ??+ Promise.resolve({ sessionId: "s1", status: "accepted" })) as never,+ reset: (options) =>+ (overrides.reset?.(address, options) ??+ reset({ ...options, continuationToken: address })) as never,+ };+ };const waitUntil = vi.fn();const response = await post.handler(request, {- cancel,- reset,- send,- resolveActiveSession:- overrides.resolveActiveSession ?? vi.fn().mockResolvedValue({ sessionId: "s1" }),+ from,+ resolveSession: (address) =>+ (overrides.resolveSession?.(address) ?? Promise.resolve({ id: "s1" })) as never,waitUntil,- getSession: vi.fn() as any,+ attachSession: vi.fn() as any,+ to: vi.fn() as any,params: {},requestIp: null,- } as any);+ });let drained = 0;while (drained < waitUntil.mock.calls.length) {@@ -957,7 +990,7 @@ describe("rebuildSlackContext", () => {expect((adapter.state as { threadTs: string | null }).threadTs).toBe("1800000000.123456");// The anchor moment wrote the new continuation token to context- // via `session.setContinuationToken(...)`. The workflow body picks+ // via `session.continuation.rekey(...)`. The workflow body picks// this up via `reconcileSessionContinuationToken` after the step.const tokenWrites = writes.filter(([key]) => key === "eve.continuationToken");expect(tokenWrites).toEqual([["eve.continuationToken", "slack:C01:1800000000.123456"]]);@@ -984,7 +1017,7 @@ describe("rebuildSlackContext", () => {const secondBody = parseSlackRequestBody(fetchMock.mock.calls[1]![1] as RequestInit);expect(secondBody.thread_ts).toBe("1800000000.123456");- // Once anchored, setContinuationToken does not fire again — the+ // Once anchored, continuation.rekey does not fire again — the// raw token is unchanged across subsequent posts.const allTokenWrites = writes.filter(([key]) => key === "eve.continuationToken");expect(allTokenWrites).toHaveLength(1);@@ -1093,6 +1126,55 @@ describe("slackChannel() inbound mention pipeline", () => {});});+ it("binds onAppMention to flat session operations", async () => {+ const clear = vi.fn().mockResolvedValue({ sessionId: "s1", status: "accepted" });+ const channel = slackChannel({+ credentials: { botToken: "xoxb-test" },+ async onAppMention(ctx) {+ await ctx.clear();+ return { auth: null };+ },+ });+ const { body } = buildMentionBody({+ channel: "C_BOUND",+ threadTs: "1700000000.000300",+ });++ await firePost(channel, buildSignedRequest({ body }), { clear });++ expect(clear).toHaveBeenCalledWith("C_BOUND:1700000000.000300");+ });++ it("sends from the flat message context with Slack-derived auth", async () => {+ const channel = slackChannel({+ credentials: { botToken: "xoxb-test" },+ async onAppMention(ctx) {+ await ctx.send("Imperative follow-up");+ return null;+ },+ });+ const { body } = buildMentionBody({+ channel: "C_BOUND",+ threadTs: "1700000000.000300",+ });++ const { send } = await firePost(channel, buildSignedRequest({ body }));++ expect(send).toHaveBeenCalledWith("C_BOUND:1700000000.000300", {+ auth: expect.objectContaining({+ authenticator: "slack-webhook",+ principalId: "slack:T01:U01",+ }),+ message: "Imperative follow-up",+ state: {+ channelId: "C_BOUND",+ teamId: "T01",+ threadTs: "1700000000.000300",+ triggeringUserId: "U01",+ },+ });+ });+it("lets onAppMention cancel the active turn before dispatching its replacement", async () => {const channel = slackChannel({credentials: { botToken: "xoxb-test" },@@ -1241,8 +1323,8 @@ describe("slackChannel() inbound mention pipeline", () => {const { send } = await firePost(channel, buildSignedRequest({ body }));expect(send).toHaveBeenCalledTimes(1);- const [payload] = send.mock.calls[0]!;- const { context, message } = payload as { context: readonly string[]; message: string };+ const [, input] = send.mock.calls[0]!;+ const { context, message } = input as { context: readonly string[]; message: string };expect(context).toEqual(["prior thread context"]);expect(message).toContain("<slack_message>");expect(message).toContain("sender_id: U01");@@ -1259,12 +1341,12 @@ describe("slackChannel() inbound mention pipeline", () => {const { send } = await firePost(channel, buildSignedRequest({ body }));expect(send).toHaveBeenCalledTimes(1);- const [payload, options] = send.mock.calls[0]!;- const { context, message } = payload as { context?: readonly string[]; message: string };+ const [, input] = send.mock.calls[0]!;+ const { context, message } = input as { context?: readonly string[]; message: string };expect(context).toBeUndefined();expect(message).toContain("sender_id: U01");expect(message).toContain("message_ts:");- expect(options.title).toBe("hello");+ expect(input.title).toBe("hello");});it("uses only this app's reply as the incremental thread context boundary", async () => {@@ -1341,7 +1423,7 @@ describe("slackChannel() inbound mention pipeline", () => {const { send } = await firePost(channel, buildSignedRequest({ body }));- const [{ message }] = send.mock.calls[0]! as [{ message: string }];+ const [, { message }] = send.mock.calls[0]! as [string, { message: string }];expect(message).toContain("<slack_thread_context>");expect(message).toContain("sender_id: U_BACKEND");expect(message).toContain("sender_id: U_OTHER_BOT");@@ -1496,8 +1578,8 @@ describe("slackChannel() onMessage", () => {const { send } = await firePost(channel, buildSignedRequest({ body: reply }));expect(send).toHaveBeenCalledWith(+ "C01:1700000000.000100",expect.objectContaining({ message: expect.any(String) }),- expect.objectContaining({ continuationToken: "C01:1700000000.000100" }),);});@@ -1670,8 +1752,7 @@ describe("slackChannel() generic Events API pipeline", () => {credentials: { botToken: "xoxb-test" },async onEvent(ctx) {await ctx.cancel({- channelId: "C01",- threadTs: "1700000000.000001",+ target: { channelId: "C01", threadTs: "1700000000.000001" },turnId: "turn_observed",});},@@ -1686,14 +1767,57 @@ describe("slackChannel() generic Events API pipeline", () => {});});+ it("targets session operations from generic Slack events", async () => {+ const compact = vi.fn().mockResolvedValue({ sessionId: "s1", status: "accepted" });+ const channel = slackChannel({+ credentials: { botToken: "xoxb-test" },+ async onEvent(ctx) {+ await ctx.compact({+ target: { channelId: "C01", threadTs: "1700000000.000001" },+ });+ },+ });++ const body = buildEventBody({ type: "reaction_added", user: "U01" });+ await firePost(channel, buildSignedRequest({ body }), { compact });++ expect(compact).toHaveBeenCalledWith("C01:1700000000.000001");+ });++ it("binds Slack session state when a generic event send creates", async () => {+ const send = vi.fn().mockResolvedValue({ id: "s1" });+ const channel = slackChannel({+ credentials: { botToken: "xoxb-test" },+ async onEvent(ctx) {+ await ctx.send("follow up", {+ auth: null,+ target: { channelId: "C01", threadTs: "1700000000.000001" },+ });+ },+ });++ const body = buildEventBody({ type: "reaction_added", user: "U01" }, { teamId: "T_WORKSPACE" });+ await firePost(channel, buildSignedRequest({ body }), { send });++ expect(send).toHaveBeenCalledWith("C01:1700000000.000001", {+ auth: null,+ message: "follow up",+ state: {+ channelId: "C01",+ teamId: "T_WORKSPACE",+ threadTs: "1700000000.000001",+ triggeringUserId: "U01",+ },+ });+ });+it("resets a targeted Slack thread from onEvent", async () => {const channel = slackChannel({credentials: { botToken: "xoxb-test" },async onEvent(ctx) {await ctx.reset({- channelId: "C01",- threadTs: "1700000000.000001",reason: "Reaction requested a fresh conversation",+ target: { channelId: "C01", threadTs: "1700000000.000001" },});},});@@ -1707,7 +1831,7 @@ describe("slackChannel() generic Events API pipeline", () => {});});- it("can start multiple turns through the pre-bound receive function", async () => {+ it("can start multiple turns through ctx.send", async () => {const auth = {attributes: { source: "reaction" },authenticator: "test",@@ -1716,17 +1840,15 @@ describe("slackChannel() generic Events API pipeline", () => {};const channel = slackChannel({credentials: { botToken: "xoxb-test" },- async onEvent({ receive }, event) {+ async onEvent(ctx, event) {expect(event.type).toBe("reaction_added");await Promise.all([- receive({+ ctx.send("Investigate the first message.", {auth,- message: "Investigate the first message.",target: { channelId: "C01", threadTs: "1700000000.000001" },}),- receive({+ ctx.send("Investigate the second message.", {auth: null,- message: "Investigate the second message.",target: { channelId: "C02", threadTs: "1700000000.000002" },}),]);@@ -1740,15 +1862,15 @@ describe("slackChannel() generic Events API pipeline", () => {const { send } = await firePost(channel, buildSignedRequest({ body }));expect(send).toHaveBeenCalledTimes(2);- expect(send.mock.calls.map(([message]) => message)).toEqual([+ expect(send.mock.calls.map(([, input]) => input.message)).toEqual(["Investigate the first message.","Investigate the second message.",]);- expect(send.mock.calls.map(([, options]) => options.continuationToken)).toEqual([+ expect(send.mock.calls.map(([continuationToken]) => continuationToken)).toEqual(["C01:1700000000.000001","C02:1700000000.000002",]);- expect(send.mock.calls.map(([, options]) => options.state.teamId)).toEqual([+ expect(send.mock.calls.map(([, input]) => input.state.teamId)).toEqual(["T_WORKSPACE","T_WORKSPACE",]);@@ -1756,14 +1878,13 @@ describe("slackChannel() generic Events API pipeline", () => {expect(send.mock.calls[1]![1].auth).toBeNull();});- it("keeps detached receive calls alive through the handler waitUntil", async () => {+ it("keeps detached send calls alive through the handler waitUntil", async () => {const channel = slackChannel({credentials: { botToken: "xoxb-test" },onEvent(ctx) {ctx.waitUntil(- ctx.receive({+ ctx.send("Run detached work.", {auth: null,- message: "Run detached work.",target: { channelId: "C01" },}),);@@ -2179,11 +2300,9 @@ describe("slackChannel() HITL interaction pipeline", () => {);expect(send).toHaveBeenCalledTimes(1);- const [payload, options] = send.mock.calls[0]!;- expect(payload).toEqual({- inputResponses: [{ optionId: "approve", requestId: "approval_abc123" }],- });- expect(options).toMatchObject({+ const [continuationToken, input] = send.mock.calls[0]!;+ expect(continuationToken).toBe("C01:1700000000.000001");+ expect(input).toMatchObject({auth: {attributes: {author_type: "user",@@ -2198,13 +2317,7 @@ describe("slackChannel() HITL interaction pipeline", () => {principalId: "slack:T01:U_APPROVER",principalType: "user",},- continuationToken: "C01:1700000000.000001",- state: {- channelId: "C01",- teamId: "T01",- threadTs: "1700000000.000001",- triggeringUserId: "U_APPROVER",- },+ inputResponses: [{ optionId: "approve", requestId: "approval_abc123" }],});});@@ -2307,7 +2420,8 @@ describe("slackChannel() HITL interaction pipeline", () => {);expect(send).toHaveBeenCalledTimes(1);- expect(send.mock.calls[0]?.[0]).toEqual({+ expect(send.mock.calls[0]?.[0]).toBe("C01:1700000000.000001");+ expect(send.mock.calls[0]?.[1]).toMatchObject({inputResponses: [{ optionId: "approve", requestId: "approval_451" }],});@@ -2453,7 +2567,8 @@ describe("slackChannel() HITL interaction pipeline", () => {);expect(send).toHaveBeenCalledTimes(1);- expect(send.mock.calls[0]?.[0]).toEqual({+ expect(send.mock.calls[0]?.[0]).toBe("C01:1700000000.000001");+ expect(send.mock.calls[0]?.[1]).toMatchObject({inputResponses: [{ optionId: "deny", requestId: "approval_451" }],});@@ -2520,11 +2635,9 @@ describe("slackChannel() HITL interaction pipeline", () => {);expect(send).toHaveBeenCalledTimes(1);- const [payload, options] = send.mock.calls[0]!;- expect(payload).toEqual({- inputResponses: [{ requestId: "call_abc123", text: "approved with context" }],- });- expect(options).toMatchObject({+ const [continuationToken, input] = send.mock.calls[0]!;+ expect(continuationToken).toBe("C01:1700000000.000001");+ expect(input).toMatchObject({auth: {attributes: {author_type: "user",@@ -2539,13 +2652,7 @@ describe("slackChannel() HITL interaction pipeline", () => {principalId: "slack:T01:U_SUBMITTER",principalType: "user",},- continuationToken: "C01:1700000000.000001",- state: {- channelId: "C01",- teamId: "T01",- threadTs: "1700000000.000001",- triggeringUserId: "U_SUBMITTER",- },+ inputResponses: [{ requestId: "call_abc123", text: "approved with context" }],});});});@@ -2636,26 +2743,26 @@ describe("slackChannel().receive", () => {}it("sends with an explicit continuation token built from channelId + threadTs", async () => {- const send = vi.fn().mockResolvedValue({ id: "s", continuationToken: "ct" });+ const send = vi.fn().mockResolvedValue({ id: "s" });await buildReceive()({message: "do the thing",target: { channelId: "C123", threadTs: "1700000000.000001" },auth: { attributes: {}, authenticator: "app", principalId: "p", principalType: "user" },},- { send },+ mockChannelContext(send),);expect(send).toHaveBeenCalledTimes(1);- const [message, options] = send.mock.calls[0]!;- expect(message).toBe("do the thing");- expect(options.continuationToken).toBe("C123:1700000000.000001");- expect(options.state).toEqual({+ const [continuationToken, input] = send.mock.calls[0]!;+ expect(continuationToken).toBe("C123:1700000000.000001");+ expect(input.message).toBe("do the thing");+ expect(input.state).toEqual({channelId: "C123",threadTs: "1700000000.000001",teamId: null,triggeringUserId: null,});- expect(options.auth.principalId).toBe("p");+ expect(input.auth.principalId).toBe("p");});it("gives each threadless proactive session a unique temporary continuation token", async () => {@@ -2663,7 +2770,7 @@ describe("slackChannel().receive", () => {.spyOn(crypto, "randomUUID").mockReturnValueOnce("00000000-0000-4000-8000-000000000001").mockReturnValueOnce("00000000-0000-4000-8000-000000000002");- const send = vi.fn().mockResolvedValue({ id: "s", continuationToken: "ct" });+ const send = vi.fn().mockResolvedValue({ id: "s" });try {const receive = buildReceive();@@ -2673,14 +2780,14 @@ describe("slackChannel().receive", () => {auth: null,};- await receive(input, { send });- await receive(input, { send });+ await receive(input, mockChannelContext(send));+ await receive(input, mockChannelContext(send));- expect(send.mock.calls.map(([, options]) => options.continuationToken)).toEqual([+ expect(send.mock.calls.map(([continuationToken]) => continuationToken)).toEqual(["C123:00000000-0000-4000-8000-000000000001","C123:00000000-0000-4000-8000-000000000002",]);- expect(send.mock.calls.map(([, options]) => options.state.threadTs)).toEqual([null, null]);+ expect(send.mock.calls.map(([, input]) => input.state.threadTs)).toEqual([null, null]);} finally {randomUUID.mockRestore();}@@ -2689,7 +2796,7 @@ describe("slackChannel().receive", () => {it("requires channelId", async () => {const send = vi.fn();await expect(- buildReceive()({ message: "x", target: {}, auth: null }, { send }),+ buildReceive()({ message: "x", target: {}, auth: null }, mockChannelContext(send)),).rejects.toThrow(/requires target.channelId/);expect(send).not.toHaveBeenCalled();});@@ -2700,7 +2807,7 @@ describe("slackChannel().receive", () => {headers: { "content-type": "application/json" },}),);- const send = vi.fn().mockResolvedValue({ id: "s", continuationToken: "ct" });+ const send = vi.fn().mockResolvedValue({ id: "s" });const { Card, CardText } = await import("#compiled/chat/index.js");await buildReceive()(@@ -2715,7 +2822,7 @@ describe("slackChannel().receive", () => {},auth: null,},- { send },+ mockChannelContext(send),);expect(fetchMock).toHaveBeenCalledTimes(1);@@ -2729,9 +2836,9 @@ describe("slackChannel().receive", () => {expect(Array.isArray(body.blocks)).toBe(true);expect(send).toHaveBeenCalledTimes(1);- const [, options] = send.mock.calls[0]!;- expect(options.continuationToken).toBe("C123:1800000000.000900");- expect(options.state.threadTs).toBe("1800000000.000900");+ const [continuationToken, input] = send.mock.calls[0]!;+ expect(continuationToken).toBe("C123:1800000000.000900");+ expect(input.state.threadTs).toBe("1800000000.000900");});it("rejects passing both threadTs and initialMessage", async () => {@@ -2748,7 +2855,7 @@ describe("slackChannel().receive", () => {},auth: null,},- { send },+ mockChannelContext(send),),).rejects.toThrow(/mutually exclusive/);expect(send).not.toHaveBeenCalled();@@ -2775,7 +2882,7 @@ describe("slackChannel().receive", () => {},auth: null,},- { send },+ mockChannelContext(send),),).rejects.toThrow(/not_in_channel/);expect(send).not.toHaveBeenCalled();@@ -2793,7 +2900,7 @@ describe("slackChannel().receive", () => {headers: { "content-type": "application/json" },}),);- const send = vi.fn().mockResolvedValue({ id: "s", continuationToken: "ct" });+ const send = vi.fn().mockResolvedValue({ id: "s" });const { Card, CardText } = await import("#compiled/chat/index.js");await buildReceive()(@@ -2808,17 +2915,16 @@ describe("slackChannel().receive", () => {},auth: null,},- { send },+ mockChannelContext(send),);- const receiveToken = (send.mock.calls[0]![1] as { continuationToken: string })- .continuationToken;+ const receiveToken = send.mock.calls[0]![0] as string;expect(receiveToken).toBe(`C123:${initialMessageTs}`);// Now simulate Slack delivering an `app_mention` reply threaded// under the anchor card. The inbound dispatch path builds the// token from `event.thread_ts` so it matches the one receive()// used, and the parked session resumes via runtime.deliver.- const inboundSend = vi.fn().mockResolvedValue({ id: "s", continuationToken: "ct" });+ const inboundSend = vi.fn().mockResolvedValue({ id: "s" });const mentionBody = JSON.stringify({type: "event_callback",team_id: "T01",@@ -2842,13 +2948,13 @@ describe("slackChannel().receive", () => {if (!post) throw new Error("expected POST route");const waitUntil = vi.fn();await post.handler(req, {- send: inboundSend,+ attachSession: vi.fn() as any,+ ...mockChannelContext(inboundSend),waitUntil,- getSession: vi.fn() as any,- receive: vi.fn() as any,+ to: vi.fn() as any,params: {},requestIp: null,- } as any);+ });let drained = 0;while (drained < waitUntil.mock.calls.length) {@@ -2858,8 +2964,7 @@ describe("slackChannel().receive", () => {}expect(inboundSend).toHaveBeenCalledTimes(1);- const inboundToken = (inboundSend.mock.calls[0]![1] as { continuationToken: string })- .continuationToken;+ const inboundToken = inboundSend.mock.calls[0]![0] as string;expect(inboundToken).toBe(receiveToken);});});diff --git a/packages/eve/src/public/channels/slack/slackChannel.ts b/packages/eve/src/public/channels/slack/slackChannel.tsindex dbfa0c5ab..fb6b1bf09 100644--- a/packages/eve/src/public/channels/slack/slackChannel.ts+++ b/packages/eve/src/public/channels/slack/slackChannel.ts@@ -1,11 +1,16 @@import { parseSlackWebhookBody } from "#compiled/@chat-adapter/slack/webhook.js";-import type { CrossChannelReceiveOptions } from "#channel/cross-channel-receive.js";+import type { UserContent } from "ai";+import type {+ ChannelFrom,+ ChannelResolveSession,+ ChannelSource,+} from "#channel/channel-operations.js";import type { Session, SessionHandle } from "#channel/session.js";-import type { CancelTurnResult, SessionAuthContext } from "#channel/types.js";+import type { SessionAuthContext } from "#channel/types.js";import type { CardElement } from "#compiled/chat/index.js";import type { SessionContext } from "#public/definitions/callback-context.js";-import type { ChannelSessionOps } from "#public/definitions/channel.js";+import type { ChannelContinuationOps } from "#public/definitions/channel.js";import { createLogger, logError } from "#internal/logging.js";import type { UnstampedMessageStreamEvent } from "#protocol/message.js";@@ -47,26 +52,29 @@ import {loadThreadContextMessages,type LoadThreadContextMessagesOptions,} from "#public/channels/slack/thread.js";-import { slackUserIdFromAuthContext } from "#public/channels/slack/auth.js";+import { buildSlackAuthContext, slackUserIdFromAuthContext } from "#public/channels/slack/auth.js";import { SLACK_CHANNEL_DEFAULT_ROUTE } from "#public/channels/slack/constants.js";import { handleInteractionPost } from "#public/channels/slack/interactions.js";+import {+ bindSlackSessionOperations,+ type SlackSendOptions,+ type SlackSessionOperations,+} from "#public/channels/slack/session-operations.js";import {mergeUploadPolicy,type UploadPolicy,type UploadPolicyInput,} from "#public/channels/upload-policy.js";import { verifySlackRequest, type SlackWebhookVerifier } from "#public/channels/slack/verify.js";-import {- defineChannel,- POST,- type CancelFn,- type Channel,- type ResetFn,- type ResetResult,- type SendFn,-} from "#public/definitions/channel.js";+import { defineChannel, POST, type Channel } from "#public/definitions/channel.js";import { markEventHandled } from "./utils.js";+export type {+ SlackRespondOptions,+ SlackSendOptions,+ SlackSessionOperations,+} from "#public/channels/slack/session-operations.js";+const log = createLogger("slack.channel");type EventData<T extends UnstampedMessageStreamEvent["type"]> =@@ -97,10 +105,10 @@ export interface SlackChannelContext extends SlackContext {/*** Slack context handed to `events[type]` handlers. Extends* {@link SlackChannelContext} (`thread`, `slack`, hydrated `state`) with- * session operations ({@link ChannelSessionOps}). Unlike the pre-dispatch+ * continuation routing ({@link ChannelContinuationOps}). Unlike the pre-dispatch* {@link SlackContext}, `state` is hydrated here.*/-export interface SlackEventContext extends SlackChannelContext, ChannelSessionOps {}+export interface SlackEventContext extends SlackChannelContext, ChannelContinuationOps {}export type {SlackApiResponse,@@ -245,7 +253,7 @@ export interface SlackChannelCredentials {readonly webhookVerifier?: SlackWebhookVerifier;}-/** Target accepted by `receive(slack, { target })` for proactive sessions. */+/** Target accepted by `ctx.to(slack, target)` from route and schedule handlers. */export interface SlackReceiveTarget {readonly channelId: string;readonly threadTs?: string;@@ -269,17 +277,33 @@ export interface SlackInitialMessage {}/**- * One imperative turn start requested by a generic Slack event handler.- * The schedule API's `receive(slack, options)` payload with the Slack- * channel already bound by the inbound webhook.+ * Options for one turn requested by a generic Slack event handler.*/-export type SlackEventReceiveOptions = CrossChannelReceiveOptions<SlackReceiveTarget>;+export interface SlackEventSendOptions {+ readonly auth: SessionAuthContext | null;+ readonly target: SlackReceiveTarget;+}++/** Options for answering pending input requests from a generic Slack event handler. */+export interface SlackEventRespondOptions {+ readonly auth: SessionAuthContext | null;+ readonly target: SlackSessionTarget;+}/*** Starts a session on the current Slack channel from `onEvent`. Call it zero,* one, or many times; each invocation returns the resulting session.*/-export type SlackEventReceiveFn = (options: SlackEventReceiveOptions) => Promise<Session>;+export type SlackEventSendFn = (+ message: string | UserContent,+ options: SlackEventSendOptions,+) => Promise<Session>;++/** Answers pending input requests on one Slack thread. */+export type SlackEventRespondFn = (+ inputResponses: Parameters<SlackSessionOperations["respond"]>[0],+ options: SlackEventRespondOptions,+) => ReturnType<SlackSessionOperations["respond"]>;/*** Slack thread identity used by workspace-scoped inbound helpers.@@ -289,54 +313,39 @@ export interface SlackSessionTarget {readonly threadTs: string;}-/**- * Options for cancelling the turn bound to a message or interaction context.- * `turnId` guards against a stale request cancelling a newer turn.- */-export interface SlackCancelOptions {- readonly turnId?: string;-}--/** Options for resetting the session bound to a message or interaction context. */-export interface SlackResetOptions {- /** Human-readable terminal reason. Do not include credentials or message contents. */- readonly reason?: string;-}--/**- * Target and optional stale-turn guard accepted by `onEvent`'s cancellation- * helper.- */-export interface SlackEventCancelOptions extends SlackSessionTarget, SlackCancelOptions {}--/** Target and optional terminal reason accepted by `onEvent`'s reset helper. */-export interface SlackEventResetOptions extends SlackSessionTarget, SlackResetOptions {}-/*** Imperative surface handed to `slackChannel({ onEvent })`. Generic Events API* payloads are not necessarily tied to one thread, so the context exposes a- * workspace API handle plus a Slack-bound `receive` function rather than the+ * workspace API handle plus Slack-bound operations rather than the* thread-scoped {@link SlackContext} used by message handlers.*/export interface SlackInboundEventContext {- /**- * Cancels the active turn for a Slack thread. Both `"accepted"` and- * `"no_active_turn"` are successful outcomes.- */- readonly cancel: (options: SlackEventCancelOptions) => Promise<CancelTurnResult>;+ /** Starts a turn on this Slack channel using the proactive send contract. */+ readonly send: SlackEventSendFn;+ /** Answers pending input requests on one Slack thread. */+ readonly respond: SlackEventRespondFn;+ /** Cancels the active turn for one Slack thread. */+ cancel(input: {+ readonly target: SlackSessionTarget;+ readonly turnId?: string;+ }): ReturnType<ChannelSource<SlackChannelState>["cancel"]>;+ /** Compacts the current session for one Slack thread. */+ compact(input: {+ readonly target: SlackSessionTarget;+ }): ReturnType<ChannelSource<SlackChannelState>["compact"]>;+ /** Clears the current session for one Slack thread. */+ clear(input: {+ readonly target: SlackSessionTarget;+ }): ReturnType<ChannelSource<SlackChannelState>["clear"]>;+ /** Resets the current session for one Slack thread. */+ reset(input: {+ readonly reason?: string;+ readonly target: SlackSessionTarget;+ }): ReturnType<ChannelSource<SlackChannelState>["reset"]>;+ /** Resolves the current session for one Slack thread. */+ resolveSession(input: { readonly target: SlackSessionTarget }): ReturnType<ChannelResolveSession>;/** The complete signed Events API callback envelope. */readonly envelope: SlackEventEnvelope;- /** Starts a turn on this Slack channel using the proactive receive contract. */- readonly receive: SlackEventReceiveFn;- /** Resolves the active eve session for a Slack channel thread. */- readonly resolveActiveSession: (- target: SlackSessionTarget,- ) => Promise<{ readonly sessionId: string } | undefined>;- /**- * Terminally retires the session for a Slack thread so its next message starts- * a fresh session.- */- readonly reset: (options: SlackEventResetOptions) => Promise<ResetResult>;/** Workspace-scoped Slack identity and raw Web API escape hatch. */readonly slack: SlackWorkspaceHandle;/** Keeps detached handler work alive after the Slack webhook is acknowledged. */@@ -347,36 +356,15 @@ export interface SlackInboundEventContext {* Message-scoped context handed to `onMessage`, `onAppMention`, and* `onDirectMessage`.*/-export interface SlackInboundMessageContext extends SlackContext {- /**- * Cancels the active turn in this message's thread. Both `"accepted"` and- * `"no_active_turn"` are successful outcomes.- */- cancel(options?: SlackCancelOptions): Promise<CancelTurnResult>;+export interface SlackInboundMessageContext extends SlackContext, SlackSessionOperations {/** Returns whether this message belongs to a thread with an active eve session. */isSubscribed(): Promise<boolean>;/** Returns whether the inbound event explicitly mentions this bot. */isBotMentioned(): boolean;- /**- * Terminally retires this thread's session so its next delivered message- * starts with fresh history and state.- */- reset(options?: SlackResetOptions): Promise<ResetResult>;}/** Interaction-scoped context handed to `slackChannel({ onInteraction })`. */-export interface SlackInteractionContext extends SlackContext {- /**- * Cancels the active turn in the interaction's thread. Both `"accepted"` and- * `"no_active_turn"` are successful outcomes.- */- cancel(options?: SlackCancelOptions): Promise<CancelTurnResult>;- /**- * Terminally retires this thread's session so the continuation token can- * start a fresh session.- */- reset(options?: SlackResetOptions): Promise<ResetResult>;-}+export interface SlackInteractionContext extends SlackContext, SlackSessionOperations {}export interface SlackInteractionAction {readonly actionId: string;@@ -445,7 +433,8 @@ export type SlackInboundResultOrPromise = SlackMentionResultOrPromise;* `slackChannel({ events })`. Each key is optional; supplying one replaces* only that event's built-in default (see {@link defaultEvents}). Handlers* receive the event data, the {@link SlackEventContext}, and the session- * {@link SessionContext}; `session.failed` receives only data and context.+ * {@link SessionContext}; `session.failed` receives only data and channel+ * context and exposes the ID as `data.sessionId`.*/export interface SlackChannelEvents {readonly "turn.started"?: SlackEventHandler<"turn.started">;@@ -567,7 +556,7 @@ export interface SlackChannelConfig {* neither a specialized handler nor `onEvent` is authored, mentions and DMs* retain their built-in defaults and other event types are ignored.*- * The handler owns control flow. Call `ctx.receive(...)` zero, one, or many+ * The handler owns control flow. Call `ctx.send(...)` zero, one, or many* times to start turns on Slack, and use `ctx.waitUntil(...)` for detached* work. The return value is ignored. Runs after the webhook has been* acknowledged through the host's `waitUntil` mechanism. Errors are caught@@ -617,7 +606,7 @@ function rebuildSlackContext(onThreadTsChanged(ts) {state.threadTs = ts;if (state.channelId) {- session.setContinuationToken(slackContinuationToken(state.channelId, ts));+ session.continuation?.rekey(slackContinuationToken(state.channelId, ts));}},});@@ -703,38 +692,35 @@ export function slackChannel(config: SlackChannelConfig = {}): SlackChannel {},routes: [- POST<SlackChannelState>(- config.route ?? SLACK_CHANNEL_DEFAULT_ROUTE,- async (req, { cancel, reset, resolveActiveSession, send, waitUntil }) => {- const body = await verifyInbound(req, config.credentials);- if (body === null) return new Response("unauthorized", { status: 401 });-- if (shouldDropSlackHttpTimeoutRetry(req.headers)) {- return new Response("ok");- }-- const contentType = req.headers.get("content-type") ?? "";- if (contentType.includes("application/x-www-form-urlencoded")) {- return handleInteractionPost(body, { cancel, reset, send, waitUntil }, { config });- }- return handleEventPost({- body,- cancel,- reset,- send,- resolveActiveSession,- waitUntil,- config,- uploadPolicy,- handledEvents,- headers: req.headers,- });- },- ),+ POST<SlackChannelState>(config.route ?? SLACK_CHANNEL_DEFAULT_ROUTE, async (req, args) => {+ const { waitUntil } = args;+ const { from, resolveSession } = args;+ const body = await verifyInbound(req, config.credentials);+ if (body === null) return new Response("unauthorized", { status: 401 });++ if (shouldDropSlackHttpTimeoutRetry(req.headers)) {+ return new Response("ok");+ }++ const contentType = req.headers.get("content-type") ?? "";+ if (contentType.includes("application/x-www-form-urlencoded")) {+ return handleInteractionPost(body, { from, resolveSession, waitUntil }, { config });+ }+ return handleEventPost({+ body,+ from,+ resolveSession,+ waitUntil,+ config,+ uploadPolicy,+ handledEvents,+ headers: req.headers,+ });+ }),],- receive(input, { send }) {- return receiveOnSlack(input, { credentials: config.credentials, send });+ receive(input, { from }) {+ return receiveOnSlack(input, { from, credentials: config.credentials });},events: mergedEvents,@@ -743,15 +729,21 @@ export function slackChannel(config: SlackChannelConfig = {}): SlackChannel {/*** Shared proactive Slack receive path used by both the channel's public- * `receive` hook and the pre-bound function exposed to `onEvent`.+ * `receive` hook and the pre-bound `send` function exposed to `onEvent`.*/async function receiveOnSlack(- input: SlackEventReceiveOptions,+ input: {+ readonly auth: SessionAuthContext | null;+ readonly message: string | UserContent;+ readonly target: SlackReceiveTarget;+ },deps: {+ readonly from: ChannelFrom<SlackChannelState>;readonly credentials: SlackChannelCredentials | undefined;- readonly send: SendFn<SlackChannelState>;/** Slack team id seeded into session state, when the trigger carried one. */readonly teamId?: string;+ /** Slack user id seeded into session state, when the trigger carried one. */+ readonly triggeringUserId?: string;},): Promise<Session> {const receiveTarget = input.target as Partial<SlackReceiveTarget>;@@ -790,14 +782,13 @@ async function receiveOnSlack(// Slack post supplies the real thread timestamp and re-keys the session.const continuationThreadTs = threadTs || crypto.randomUUID();- return deps.send(input.message, {+ return deps.from(slackContinuationToken(channelId, continuationThreadTs)).send(input.message, {auth: input.auth,- continuationToken: slackContinuationToken(channelId, continuationThreadTs),state: {channelId,threadTs: threadTs || null,teamId: deps.teamId ?? null,- triggeringUserId: null,+ triggeringUserId: deps.triggeringUserId ?? null,},});}@@ -837,13 +828,9 @@ function shouldDropSlackHttpTimeoutRetry(headers: Headers): boolean {*/async function handleEventPost(input: {readonly body: string;- readonly cancel: CancelFn;- readonly reset: ResetFn;+ readonly from: ChannelFrom<SlackChannelState>;+ readonly resolveSession: ChannelResolveSession;readonly headers: Headers;- readonly send: SendFn<SlackChannelState>;- readonly resolveActiveSession: (options: {- readonly continuationToken: string;- }) => Promise<{ readonly sessionId: string } | undefined>;readonly waitUntil: (task: Promise<unknown>) => void;readonly config: SlackChannelConfig;readonly uploadPolicy: UploadPolicy;@@ -887,14 +874,12 @@ async function handleEventPost(input: {dispatchSlackMessage({appId,botUserId,- cancel: input.cancel,+ from: input.from,+ resolveSession: input.resolveSession,credentials: config.credentials,handler,kind,message,- resolveActiveSession: input.resolveActiveSession,- reset: input.reset,- send: input.send,threadContext: config.threadContext,uploadPolicy: input.uploadPolicy,});@@ -905,14 +890,12 @@ async function handleEventPost(input: {dispatchSlackMessage({appId,botUserId,- cancel: input.cancel,+ from: input.from,+ resolveSession: input.resolveSession,credentials: config.credentials,handler,kind,message,- resolveActiveSession: input.resolveActiveSession,- reset: input.reset,- send: input.send,threadContext: config.threadContext,uploadPolicy: input.uploadPolicy,});@@ -934,14 +917,12 @@ async function handleEventPost(input: {dispatchSlackMessage({appId,botUserId,- cancel: input.cancel,+ from: input.from,+ resolveSession: input.resolveSession,credentials: config.credentials,handler: config.onMessage!,kind: "channel_message",message,- resolveActiveSession: input.resolveActiveSession,- reset: input.reset,- send: input.send,threadContext: config.threadContext,uploadPolicy: input.uploadPolicy,});@@ -955,13 +936,11 @@ async function handleEventPost(input: {if (dispatch === null && onEvent !== undefined) {dispatch = () =>dispatchSlackEvent({- cancel: input.cancel,+ from: input.from,+ resolveSession: input.resolveSession,credentials: config.credentials,envelope,handler: onEvent,- resolveActiveSession: input.resolveActiveSession,- reset: input.reset,- send: input.send,});}@@ -1002,16 +981,12 @@ function isSelfAuthoredSlackMessage(async function dispatchSlackMessage(input: {readonly appId: string | undefined;readonly botUserId: string | undefined;- readonly cancel: CancelFn;+ readonly from: ChannelFrom<SlackChannelState>;+ readonly resolveSession: ChannelResolveSession;readonly credentials: SlackChannelCredentials | undefined;readonly handler: NonNullable<SlackChannelConfig["onMessage"]>;readonly kind: "app_mention" | "channel_message" | "direct_message";readonly message: SlackMessage;- readonly resolveActiveSession: (options: {- readonly continuationToken: string;- }) => Promise<{ readonly sessionId: string } | undefined>;- readonly reset: ResetFn;- readonly send: SendFn<SlackChannelState>;readonly threadContext: LoadThreadContextMessagesOptions | undefined;readonly uploadPolicy: UploadPolicy;}): Promise<void> {@@ -1024,24 +999,36 @@ async function dispatchSlackMessage(input: {threadTs: input.message.threadTs,teamId: input.message.teamId,});+ const author = input.message.author;+ const sessionOperations = bindSlackSessionOperations({+ address: continuationToken,+ defaultAuth:+ author === undefined+ ? null+ : buildSlackAuthContext({+ channelId: input.message.channelId,+ fullName: author.fullName,+ isBot: author.isBot,+ teamId: input.message.teamId,+ threadTs: input.message.threadTs,+ userId: author.userId,+ userName: author.userName,+ }),+ from: input.from,+ resolveSession: input.resolveSession,+ state: {+ channelId: input.message.channelId,+ teamId: input.message.teamId ?? null,+ threadTs: input.message.threadTs,+ triggeringUserId: author?.userId ?? null,+ },+ });const ctx: SlackInboundMessageContext = {- cancel: (options = {}) =>- input.cancel({- continuationToken,- turnId: options.turnId,- }),+ ...sessionOperations,isBotMentioned: () =>input.kind === "app_mention" ||(input.botUserId !== undefined && input.message.text.includes(`<@${input.botUserId}`)),- isSubscribed: async () =>- (await input.resolveActiveSession({- continuationToken,- })) !== undefined,- reset: (options = {}) =>- input.reset({- continuationToken,- reason: options.reason,- }),+ isSubscribed: async () => (await sessionOperations.resolveSession()) !== undefined,slack,thread,};@@ -1062,24 +1049,20 @@ async function dispatchSlackMessage(input: {kind: input.kind,message: input.message,result,- send: input.send,+ sessionOperations,thread,threadContext: input.threadContext,uploadPolicy: input.uploadPolicy,});}-/** Runs a generic Events API handler with an imperative Slack receive surface. */+/** Runs a generic Events API handler with an imperative Slack operation surface. */async function dispatchSlackEvent(input: {- readonly cancel: CancelFn;+ readonly from: ChannelFrom<SlackChannelState>;+ readonly resolveSession: ChannelResolveSession;readonly credentials: SlackChannelCredentials | undefined;readonly envelope: SlackEventEnvelope;readonly handler: NonNullable<SlackChannelConfig["onEvent"]>;- readonly resolveActiveSession: (options: {- readonly continuationToken: string;- }) => Promise<{ readonly sessionId: string } | undefined>;- readonly reset: ResetFn;- readonly send: SendFn<SlackChannelState>;}): Promise<void> {const eventTeamId = input.envelope.event.team_id;const teamId =@@ -1089,28 +1072,30 @@ async function dispatchSlackEvent(input: {? input.envelope.team_id: undefined;const waitUntilTasks: Promise<unknown>[] = [];+ const sourceFor = (target: SlackSessionTarget) =>+ input.from(slackContinuationToken(target.channelId, target.threadTs));const ctx: SlackInboundEventContext = {- cancel: ({ channelId, threadTs, turnId }) =>- input.cancel({- continuationToken: slackContinuationToken(channelId, threadTs),- turnId,- }),+ cancel: ({ target, turnId }) => sourceFor(target).cancel({ turnId }),+ clear: ({ target }) => sourceFor(target).clear(),+ compact: ({ target }) => sourceFor(target).compact(),envelope: input.envelope,- receive: (options) =>- receiveOnSlack(options, {- credentials: input.credentials,- send: input.send,- teamId,- }),- resolveActiveSession: ({ channelId, threadTs }) =>- input.resolveActiveSession({- continuationToken: slackContinuationToken(channelId, threadTs),- }),- reset: ({ channelId, threadTs, reason }) =>- input.reset({- continuationToken: slackContinuationToken(channelId, threadTs),- reason,- }),+ reset: ({ reason, target }) => sourceFor(target).reset({ reason }),+ resolveSession: ({ target }) =>+ input.resolveSession(slackContinuationToken(target.channelId, target.threadTs)),+ respond: (inputResponses, { auth, target }) =>+ sourceFor(target).respond(inputResponses, { auth }),+ send: (message, { auth, target }) =>+ receiveOnSlack(+ { auth, message, target },+ {+ from: input.from,+ credentials: input.credentials,+ teamId,+ ...(typeof input.envelope.event.user === "string"+ ? { triggeringUserId: input.envelope.event.user }+ : {}),+ },+ ),slack: buildSlackWorkspaceHandle({botToken: input.credentials?.botToken,teamId,@@ -1155,11 +1140,11 @@ async function verifyInbound(}async function deliverSlackMessage(input: {+ readonly sessionOperations: SlackSessionOperations;readonly credentials: SlackChannelCredentials | undefined;readonly kind: string;readonly message: SlackMessage;readonly result: Exclude<SlackInboundResult, null>;- readonly send: SendFn<SlackChannelState>;readonly thread: SlackThread;readonly threadContext: LoadThreadContextMessagesOptions | undefined;readonly uploadPolicy: UploadPolicy;@@ -1193,23 +1178,16 @@ async function deliverSlackMessage(input: {);const channelContext = input.result.context ?? [];-- await input.send(+ const sendOptions: SlackSendOptions =channelContext.length === 0- ? { message: turnMessage }- : { message: turnMessage, context: channelContext },- {- auth: input.result.auth,- continuationToken: slackContinuationToken(message.channelId, message.threadTs),- state: {- channelId: message.channelId,- threadTs: message.threadTs,- teamId: message.teamId ?? null,- triggeringUserId: inboundContext.userId || null,- },- title: message.markdown,- },- );+ ? { auth: input.result.auth, title: message.markdown }+ : {+ auth: input.result.auth,+ context: channelContext,+ title: message.markdown,+ };++ await input.sessionOperations.send(turnMessage, sendOptions);} catch (error) {logError(log, `${input.kind} delivery failed`, error, { channelId: message.channelId });}diff --git a/packages/eve/src/public/channels/teams/teamsChannel.test.ts b/packages/eve/src/public/channels/teams/teamsChannel.test.tsindex 039f6a4d4..2883245a4 100644--- a/packages/eve/src/public/channels/teams/teamsChannel.test.ts+++ b/packages/eve/src/public/channels/teams/teamsChannel.test.ts@@ -2,6 +2,7 @@ import { describe, expect, it, vi } from "vitest";import { isCompiledChannel, type CompiledChannel } from "#channel/compiled-channel.js";import { isHttpRouteDefinition } from "#channel/routes.js";+import { mockChannelContext } from "#internal/testing/mocks/mock-channel-operations.js";import { teamsChannel, type TeamsChannelState } from "#public/channels/teams/index.js";function asCompiled<T = unknown>(channel: unknown): CompiledChannel<T> {@@ -15,9 +16,7 @@ async function firePost(channel: unknown,body: Record<string, unknown>,overrides: {- readonly resolveActiveSession?: (options: {- readonly continuationToken: string;- }) => Promise<{ readonly sessionId: string } | undefined>;+ readonly resolveSession?: (continuationToken: string) => Promise<unknown>;} = {},): Promise<{readonly response: Response;@@ -38,6 +37,7 @@ async function firePost(id: "SESSION",}));const waitUntil = vi.fn();+ const baseFrom = mockChannelContext<TeamsChannelState>(send).from;const response = await post.handler(new Request("https://eve.test/eve/v1/teams", {body: JSON.stringify(body),@@ -45,16 +45,17 @@ async function firePost(method: "POST",}),{- getSession: vi.fn(),- resolveActiveSession: overrides.resolveActiveSession ?? vi.fn().mockResolvedValue(undefined),- cancel: vi.fn(),- clear: vi.fn(),- compact: vi.fn(),- reset: vi.fn(),+ from(continuationToken) {+ return baseFrom(continuationToken);+ },+ resolveSession: (continuationToken) =>+ (overrides.resolveSession ?? vi.fn().mockResolvedValue(undefined))(+ continuationToken,+ ) as never,+ attachSession: vi.fn() as any,params: {},- receive: vi.fn(),+ to: vi.fn(),requestIp: null,- send,waitUntil,},);@@ -100,15 +101,15 @@ describe("teamsChannel", () => {expect(response.status).toBe(200);expect(send).toHaveBeenCalledTimes(1);+ expect(send.mock.calls[0]![0]).toBe("TENANT:CONV:");expect(send.mock.calls[0]![1]).toMatchObject({- continuationToken: "TENANT:CONV:",state: {conversationId: "CONV",replyToActivityId: null,serviceUrl: "https://smba.example.test/teams",},});- expect(send.mock.calls[0]![0].context[0]).toContain("<teams_context>");+ expect(send.mock.calls[0]![1].context[0]).toContain("<teams_context>");});it("default dispatch ignores unmentioned group messages", async () => {@@ -132,7 +133,7 @@ describe("teamsChannel", () => {it("exposes the subscription helper to onMessage", async () => {const observed: boolean[] = [];- const resolveActiveSession = vi.fn().mockResolvedValue({ sessionId: "SESSION" });+ const resolveSession = vi.fn().mockResolvedValue({ id: "SESSION" });const channel = teamsChannel({credentials: { webhookVerifier: () => true },async onMessage(ctx) {@@ -144,12 +145,10 @@ describe("teamsChannel", () => {raw.entities = [];raw.conversation = { conversationType: "channel", id: "CONV;messageid=THREAD_ROOT" };- await firePost(channel, raw, { resolveActiveSession });+ await firePost(channel, raw, { resolveSession });expect(observed).toEqual([true]);- expect(resolveActiveSession).toHaveBeenCalledWith({- continuationToken: "TENANT:CONV:THREAD_ROOT",- });+ expect(resolveSession).toHaveBeenCalledWith("TENANT:CONV:THREAD_ROOT");});it("allows a mention-or-subscription onMessage policy", async () => {@@ -164,7 +163,7 @@ describe("teamsChannel", () => {raw.conversation = { conversationType: "channel", id: "CONV;messageid=THREAD_ROOT" };const { send } = await firePost(channel, raw, {- resolveActiveSession: vi.fn().mockResolvedValue({ sessionId: "SESSION" }),+ resolveSession: vi.fn().mockResolvedValue({ id: "SESSION" }),});expect(send).toHaveBeenCalledTimes(1);@@ -212,10 +211,10 @@ describe("teamsChannel", () => {expect(await response.json()).toMatchObject({ statusCode: 200 });expect(send).toHaveBeenCalledWith(- { inputResponses: [{ optionId: "approve", requestId: "REQ" }] },+ "TENANT:CONV:THREAD_ROOT",expect.objectContaining({auth: expect.objectContaining({ subject: "AAD_USER" }),- continuationToken: "TENANT:CONV:THREAD_ROOT",+ inputResponses: [{ optionId: "approve", requestId: "REQ" }],}),);});@@ -242,8 +241,10 @@ describe("teamsChannel", () => {expect(onMessage).not.toHaveBeenCalled();expect(send).toHaveBeenCalledWith(- { inputResponses: [{ optionId: "deny", requestId: "REQ" }] },- expect.objectContaining({ continuationToken: "TENANT:CONV:THREAD_ROOT" }),+ "TENANT:CONV:THREAD_ROOT",+ expect.objectContaining({+ inputResponses: [{ optionId: "deny", requestId: "REQ" }],+ }),);});@@ -283,8 +284,8 @@ describe("teamsChannel", () => {const { send } = await firePost(channel, raw);+ expect(send.mock.calls[0]![0]).toBe("TENANT:CONV:THREAD_ROOT");expect(send.mock.calls[0]![1]).toMatchObject({- continuationToken: "TENANT:CONV:THREAD_ROOT",state: { replyToActivityId: "THREAD_ROOT" },});});@@ -303,15 +304,13 @@ describe("teamsChannel", () => {const initialRequest = await firePost(channel, initial);const followUpRequest = await firePost(channel, followUp);- const initialOptions = initialRequest.send.mock.calls[0]![1] as {- readonly continuationToken: string;- };+ const initialToken = initialRequest.send.mock.calls[0]![0] as string;+ expect(followUpRequest.send.mock.calls[0]![0]).toBe(initialToken);expect(followUpRequest.send.mock.calls[0]![1]).toMatchObject({- continuationToken: initialOptions.continuationToken,state: { replyToActivityId: "THREAD_ROOT" },});- expect(initialOptions.continuationToken).toBe("TENANT:CONV:THREAD_ROOT");+ expect(initialToken).toBe("TENANT:CONV:THREAD_ROOT");});it("receive starts proactive sessions and anchors initial channel messages", async () => {@@ -348,12 +347,12 @@ describe("teamsChannel", () => {auth: null,message: "Begin",},- { send },+ mockChannelContext(send),);expect(requests[0]!.url).toBe("https://service.example/teams/v3/conversations/CONV/activities");+ expect(send.mock.calls[0]![0]).toBe("TENANT:CONV:ANCHOR");expect(send.mock.calls[0]![1]).toMatchObject({- continuationToken: "TENANT:CONV:ANCHOR",state: { replyToActivityId: "ANCHOR" },});});diff --git a/packages/eve/src/public/channels/teams/teamsChannel.ts b/packages/eve/src/public/channels/teams/teamsChannel.tsindex 6cf09d8a7..fd41f2b17 100644--- a/packages/eve/src/public/channels/teams/teamsChannel.ts+++ b/packages/eve/src/public/channels/teams/teamsChannel.ts@@ -1,8 +1,9 @@import type { TeamsInstrumentationMetadata } from "#public/channels/teams/index.js";+import type { ChannelFrom, ChannelResolveSession } from "#channel/channel-operations.js";import type { SessionHandle } from "#channel/session.js";import type { SessionAuthContext } from "#channel/types.js";import type { SessionContext } from "#public/definitions/callback-context.js";-import type { ChannelSessionOps } from "#public/definitions/channel.js";+import type { ChannelContinuationOps } from "#public/definitions/channel.js";import { createLogger, logError } from "#internal/logging.js";import type { UnstampedMessageStreamEvent } from "#protocol/message.js";@@ -56,7 +57,7 @@ import {import { verifyTeamsRequest, type TeamsWebhookVerifier } from "#public/channels/teams/verify.js";import { readNonEmptyString } from "#shared/guards.js";import { parseJsonObject, type JsonObject } from "#shared/json.js";-import { defineChannel, POST, type Channel, type SendFn } from "#public/definitions/channel.js";+import { defineChannel, POST, type Channel } from "#public/definitions/channel.js";const log = createLogger("teams.channel");@@ -81,8 +82,8 @@ export interface TeamsChannelContext extends TeamsContext {state: TeamsChannelState;}-/** Event-handler Teams context, including session operations. */-export interface TeamsEventContext extends TeamsChannelContext, ChannelSessionOps {}+/** Event-handler Teams context, including continuation routing. */+export interface TeamsEventContext extends TeamsChannelContext, ChannelContinuationOps {}/** JSON-serializable Teams channel state. */export interface TeamsChannelState {@@ -297,7 +298,7 @@ export function teamsChannel(config: TeamsChannelConfig = {}): TeamsChannel {routes: [POST<TeamsChannelState>(config.route ?? "/eve/v1/teams",- async (req, { resolveActiveSession, send, waitUntil }) => {+ async (req, { from, resolveSession, waitUntil }) => {const body = await verifyInbound(req, config.credentials);if (body === null) return new Response("unauthorized", { status: 401 });@@ -315,14 +316,14 @@ export function teamsChannel(config: TeamsChannelConfig = {}): TeamsChannel {if (activity.type === "message") {waitUntil(isTeamsInputResponseActivity(activity)- ? dispatchInputResponses({ activity, config, onInputResponse, send })+ ? dispatchInputResponses({ activity, config, from, onInputResponse }): dispatchMessage({activity,config,filesPolicy,onMessage,- resolveActiveSession,- send,+ from,+ resolveSession,}),);return teamsOk();@@ -333,8 +334,8 @@ export function teamsChannel(config: TeamsChannelConfig = {}): TeamsChannel {activity,config,onInputResponse,- send,waitUntil,+ from,});}@@ -343,7 +344,7 @@ export function teamsChannel(config: TeamsChannelConfig = {}): TeamsChannel {),],- async receive(input, { send }) {+ async receive(input, { from }) {const receiveTarget = input.target as Partial<TeamsReceiveTarget>;const serviceUrl = readNonEmptyString(receiveTarget.serviceUrl);const conversationId = readNonEmptyString(receiveTarget.conversationId);@@ -382,15 +383,13 @@ export function teamsChannel(config: TeamsChannelConfig = {}): TeamsChannel {}}- return send(input.message, {- auth: input.auth,- continuationToken: teamsContinuationToken({+ return from(+ teamsContinuationToken({conversationId,replyToActivityId,tenantId: state.tenantId,}),- state,- });+ ).send(input.message, { auth: input.auth, state });},events: mergedEvents,@@ -460,7 +459,7 @@ function buildTeamsHandle(input: {state.replyToActivityId = posted.id;const conversationId = state.conversationId;if (conversationId) {- input.session?.setContinuationToken(+ input.session?.continuation?.rekey(teamsContinuationToken({conversationId,replyToActivityId: posted.id,@@ -567,21 +566,18 @@ async function verifyInbound(async function dispatchMessage(input: {readonly activity: TeamsMessageActivity;+ readonly from: ChannelFrom<TeamsChannelState>;+ readonly resolveSession: ChannelResolveSession;readonly config: TeamsChannelConfig;readonly filesPolicy: TeamsFilesPolicy;readonly onMessage: NonNullable<TeamsChannelConfig["onMessage"]>;- readonly resolveActiveSession: (options: {- readonly continuationToken: string;- }) => Promise<{ readonly sessionId: string } | undefined>;- readonly send: SendFn<TeamsChannelState>;}): Promise<void> {const state = stateFromActivity(input.activity);const binding = buildTeamsBinding({ config: input.config, state });const continuationToken = stateToken(state);const ctx: TeamsInboundMessageContext = {...binding,- isSubscribed: async () =>- (await input.resolveActiveSession({ continuationToken })) !== undefined,+ isSubscribed: async () => (await input.resolveSession(continuationToken)) !== undefined,};let result: TeamsInboundResult;@@ -609,17 +605,11 @@ async function dispatchMessage(input: {const channelContext = result.context ?? [];try {- await input.send(- {- message: turnMessage,- context: [formatTeamsContextBlock(inboundContext), ...channelContext],- },- {- auth: result.auth,- continuationToken,- state,- },- );+ await input.from(continuationToken).send(turnMessage, {+ auth: result.auth,+ context: [formatTeamsContextBlock(inboundContext), ...channelContext],+ state,+ });} catch (error) {log.error("Teams message delivery failed", { error });}@@ -627,9 +617,9 @@ async function dispatchMessage(input: {async function handleInvoke(input: {readonly activity: TeamsInvokeActivity;+ readonly from: ChannelFrom<TeamsChannelState>;readonly config: TeamsChannelConfig;readonly onInputResponse: NonNullable<TeamsChannelConfig["onInputResponse"]>;- readonly send: SendFn<TeamsChannelState>;readonly waitUntil: (task: Promise<unknown>) => void;}): Promise<Response> {if (isTeamsInputResponseActivity(input.activity)) {@@ -638,7 +628,7 @@ async function handleInvoke(input: {activity: input.activity,config: input.config,onInputResponse: input.onInputResponse,- send: input.send,+ from: input.from,}),);return Response.json(teamsInvokeResponse());@@ -654,9 +644,9 @@ async function handleInvoke(input: {async function dispatchInputResponses(input: {readonly activity: TeamsInvokeActivity | TeamsMessageActivity;+ readonly from: ChannelFrom<TeamsChannelState>;readonly config: TeamsChannelConfig;readonly onInputResponse: NonNullable<TeamsChannelConfig["onInputResponse"]>;- readonly send: SendFn<TeamsChannelState>;}): Promise<void> {const inputResponses = deriveTeamsInputResponses(input.activity as TeamsActivity);if (inputResponses.length === 0) return;@@ -671,14 +661,9 @@ async function dispatchInputResponses(input: {}if (result === null) return;try {- await input.send(- { inputResponses },- {- auth: result.auth,- continuationToken: resolveInputContinuationToken(input.activity, state),- state,- },- );+ await input.from(resolveInputContinuationToken(input.activity, state)).respond(inputResponses, {+ auth: result.auth,+ });} catch (error) {log.error("Teams input response delivery failed", { error });}diff --git a/packages/eve/src/public/channels/telegram/telegramChannel.test.ts b/packages/eve/src/public/channels/telegram/telegramChannel.test.tsindex d7e10e4e3..3322f826f 100644--- a/packages/eve/src/public/channels/telegram/telegramChannel.test.ts+++ b/packages/eve/src/public/channels/telegram/telegramChannel.test.ts@@ -6,6 +6,7 @@ import { isCompiledChannel, type CompiledChannel } from "#channel/compiled-channimport { isHttpRouteDefinition } from "#channel/routes.js";import { ContextContainer, contextStorage } from "#context/container.js";import { SessionKey } from "#context/keys.js";+import { mockChannelContext } from "#internal/testing/mocks/mock-channel-operations.js";import type { UnstampedMessageStreamEvent } from "#protocol/message.js";import { telegramChannel, type TelegramChannelState } from "#public/channels/telegram/index.js";@@ -82,16 +83,17 @@ async function firePost(if (!post || !isHttpRouteDefinition(post)) {throw new Error("Expected telegram channel to define a POST route.");}- const send = vi.fn().mockResolvedValue({ continuationToken: "ct", id: "s1" });+ const send = vi.fn().mockResolvedValue({ id: "s1" });const waitUntil = vi.fn();const response = await post.handler(signedRequest(JSON.stringify(body)), {- getSession: vi.fn() as any,+ attachSession: vi.fn() as any,+ ...mockChannelContext(send),+ to: vi.fn() as any,params: {},requestIp: null,- send,waitUntil,- } as any);+ });let drained = 0;while (drained < waitUntil.mock.calls.length) {@@ -154,15 +156,15 @@ describe("telegramChannel() inbound route", () => {expect(response.status).toBe(200);expect(send).toHaveBeenCalledTimes(1);- const [payload, options] = send.mock.calls[0]!;- expect((payload as { context: string[] }).context[0]).toContain("<telegram_context>");- expect(String((payload as { message: string }).message)).toContain("hello");- expect(options).toMatchObject({+ const [continuationToken, input] = send.mock.calls[0]!;+ expect((input as { context: string[] }).context[0]).toContain("<telegram_context>");+ expect(String((input as { message: string }).message)).toContain("hello");+ expect(continuationToken).toBe("42::");+ expect(input).toMatchObject({auth: {authenticator: "telegram-webhook",principalId: "telegram:42",},- continuationToken: "42::",state: {chatId: "42",chatType: "private",@@ -197,9 +199,7 @@ describe("telegramChannel() inbound route", () => {},});expect(mentioned.send).toHaveBeenCalledTimes(1);- expect(mentioned.send.mock.calls[0]![1]).toMatchObject({- continuationToken: "-1001::11",- });+ expect(mentioned.send.mock.calls[0]![0]).toBe("-1001::11");});it("delivers Telegram callback queries as compact HITL input responses", async () => {@@ -221,10 +221,10 @@ describe("telegramChannel() inbound route", () => {});expect(send).toHaveBeenCalledWith(- { inputResponses: [{ optionId: "selected", requestId: "telegram_callback:eve:0" }] },+ "-1001::55",expect.objectContaining({auth: null,- continuationToken: "-1001::55",+ inputResponses: [{ optionId: "selected", requestId: "telegram_callback:eve:0" }],}),);});@@ -249,11 +249,10 @@ describe("telegramChannel() inbound route", () => {},});- const [payload] = send.mock.calls[0]!;- expect(payload).toMatchObject({+ const [, input] = send.mock.calls[0]!;+ expect(input).toMatchObject({inputResponses: [{ requestId: "telegram_reply:55", text: "approved" }],});- expect(String((payload as { message: string }).message)).toContain("approved");});it("rejects requests with invalid webhook verification", async () => {@@ -272,12 +271,13 @@ describe("telegramChannel() inbound route", () => {method: "POST",}),{- getSession: vi.fn() as any,+ attachSession: vi.fn() as any,+ ...mockChannelContext(send),+ to: vi.fn() as any,params: {},requestIp: null,- send,waitUntil: vi.fn(),- } as any,+ },);expect(response.status).toBe(401);@@ -620,7 +620,7 @@ describe("telegramChannel().receive", () => {credentials: { botToken: "bot-token" },}),);- const send = vi.fn().mockResolvedValue({ continuationToken: "ct", id: "s1" });+ const send = vi.fn().mockResolvedValue({ id: "s1" });await channel.receive!({@@ -628,13 +628,13 @@ describe("telegramChannel().receive", () => {auth: null,message: "run",},- { send },+ mockChannelContext(send),);expect(send).toHaveBeenCalledWith(- "run",+ "42::",expect.objectContaining({- continuationToken: "42::",+ message: "run",state: expect.objectContaining({chatId: "42",chatType: "private",@@ -659,7 +659,7 @@ describe("telegramChannel().receive", () => {credentials: { botToken: "bot-token" },}),);- const send = vi.fn().mockResolvedValue({ continuationToken: "ct", id: "s1" });+ const send = vi.fn().mockResolvedValue({ id: "s1" });await channel.receive!({@@ -667,13 +667,13 @@ describe("telegramChannel().receive", () => {auth: null,message: "run",},- { send },+ mockChannelContext(send),);expect(send).toHaveBeenCalledWith(- "run",+ "42:7:",expect.objectContaining({- continuationToken: "42:7:",+ message: "run",state: expect.objectContaining({chatId: "42",chatType: "private",@@ -700,7 +700,7 @@ describe("telegramChannel().receive", () => {credentials: { botToken: "bot-token" },}),);- const send = vi.fn().mockResolvedValue({ continuationToken: "ct", id: "s1" });+ const send = vi.fn().mockResolvedValue({ id: "s1" });await channel.receive!({@@ -708,13 +708,13 @@ describe("telegramChannel().receive", () => {auth: null,message: "run",},- { send },+ mockChannelContext(send),);expect(send).toHaveBeenCalledWith(- "run",+ "-1001::88",expect.objectContaining({- continuationToken: "-1001::88",+ message: "run",state: expect.objectContaining({chatId: "-1001",chatType,@@ -737,7 +737,7 @@ describe("telegramChannel().receive", () => {credentials: { botToken: "bot-token" },}),);- const send = vi.fn().mockResolvedValue({ continuationToken: "ct", id: "s1" });+ const send = vi.fn().mockResolvedValue({ id: "s1" });await channel.receive!({@@ -745,13 +745,13 @@ describe("telegramChannel().receive", () => {auth: null,message: "run",},- { send },+ mockChannelContext(send),);expect(send).toHaveBeenCalledWith(- "run",+ "42::",expect.objectContaining({- continuationToken: "42::",+ message: "run",state: expect.objectContaining({chatId: "42",chatType: null,@@ -776,7 +776,7 @@ describe("telegramChannel().receive", () => {credentials: { botToken: "bot-token" },}),);- const send = vi.fn().mockResolvedValue({ continuationToken: "ct", id: "s1" });+ const send = vi.fn().mockResolvedValue({ id: "s1" });await channel.receive!({@@ -784,13 +784,13 @@ describe("telegramChannel().receive", () => {auth: null,message: "run",},- { send },+ mockChannelContext(send),);expect(send).toHaveBeenCalledWith(- "run",+ "42::",expect.objectContaining({- continuationToken: "42::",+ message: "run",state: expect.objectContaining({chatId: "42",chatType: null,@@ -805,7 +805,7 @@ describe("telegramChannel().receive", () => {const send = vi.fn();await expect(- channel.receive!({ target: {}, auth: null, message: "run" }, { send }),+ channel.receive!({ target: {}, auth: null, message: "run" }, mockChannelContext(send)),).rejects.toThrow(/requires target.chatId/);await expect(channel.receive!(@@ -814,7 +814,7 @@ describe("telegramChannel().receive", () => {auth: null,message: "run",},- { send },+ mockChannelContext(send),),).rejects.toThrow(/mutually exclusive/);});diff --git a/packages/eve/src/public/channels/telegram/telegramChannel.ts b/packages/eve/src/public/channels/telegram/telegramChannel.tsindex 90c169b46..7eb1c9774 100644--- a/packages/eve/src/public/channels/telegram/telegramChannel.ts+++ b/packages/eve/src/public/channels/telegram/telegramChannel.ts@@ -1,9 +1,10 @@import type { TelegramInstrumentationMetadata } from "#public/channels/telegram/index.js";import { defaultDeliverResult, type ChannelAdapterContext } from "#channel/adapter.js";+import type { ChannelFrom } from "#channel/channel-operations.js";import type { SessionHandle } from "#channel/session.js";import type { DeliverPayload, SessionAuthContext } from "#channel/types.js";import type { SessionContext } from "#public/definitions/callback-context.js";-import type { ChannelSessionOps } from "#public/definitions/channel.js";+import type { ChannelContinuationOps } from "#public/definitions/channel.js";import { isCompiledChannel } from "#channel/compiled-channel.js";import { createLogger, logError } from "#internal/logging.js";import type { UnstampedMessageStreamEvent } from "#protocol/message.js";@@ -52,7 +53,7 @@ import {type TelegramWebhookSecretToken,type TelegramWebhookVerifier,} from "#public/channels/telegram/verify.js";-import { defineChannel, POST, type Channel, type SendFn } from "#public/definitions/channel.js";+import { defineChannel, POST, type Channel } from "#public/definitions/channel.js";import { parseJsonObject, type JsonObject } from "#shared/json.js";const log = createLogger("telegram.channel");@@ -70,8 +71,8 @@ export interface TelegramChannelContext extends TelegramContext {state: TelegramChannelState;}-/** Event-handler Telegram context, including session operations. */-export interface TelegramEventContext extends TelegramChannelContext, ChannelSessionOps {}+/** Event-handler Telegram context, including continuation routing. */+export interface TelegramEventContext extends TelegramChannelContext, ChannelContinuationOps {}/** JSON-serializable Telegram channel state. */export interface TelegramChannelState extends TelegramHitlState {@@ -124,7 +125,7 @@ type TelegramSessionFailedHandler = (channel: TelegramEventContext,) => void | Promise<void>;-/** Per-event handlers for `telegramChannel({ events })`. Each entry overrides the built-in default (handlers merge over {@link defaultEvents}). `session.failed` receives `(data, channel)`; all others also receive the {@link SessionContext}. */+/** Per-event handlers for `telegramChannel({ events })`. Each entry overrides the built-in default (handlers merge over {@link defaultEvents}). `session.failed` receives `(data, channel)` and exposes the ID as `data.sessionId`; all others also receive the {@link SessionContext}. */export interface TelegramChannelEvents {readonly "turn.started"?: TelegramEventHandler<"turn.started">;readonly "actions.requested"?: TelegramEventHandler<"actions.requested">;@@ -231,7 +232,7 @@ export function telegramChannel(config: TelegramChannelConfig = {}): TelegramCharoutes: [POST<TelegramChannelState>(config.route ?? "/eve/v1/telegram",- async (req, { send, waitUntil }) => {+ async (req, { from, waitUntil }) => {const body = await verifyInbound(req, config.credentials);if (body === null) return new Response("unauthorized", { status: 401 });@@ -252,8 +253,8 @@ export function telegramChannel(config: TelegramChannelConfig = {}): TelegramChaconfig,message: update.message,onMessage,- send,uploadPolicy,+ from,}),);return new Response("ok");@@ -263,7 +264,7 @@ export function telegramChannel(config: TelegramChannelConfig = {}): TelegramChadispatchCallbackQuery({config,query: update.callbackQuery,- send,+ from,}),);return new Response("ok");@@ -271,7 +272,7 @@ export function telegramChannel(config: TelegramChannelConfig = {}): TelegramCha),],- async receive(input, { send }) {+ async receive(input, { from }) {const receiveTarget = input.target as Partial<TelegramReceiveTarget>;const chatId = readChatId(receiveTarget.chatId);if (chatId === undefined) {@@ -304,9 +305,8 @@ export function telegramChannel(config: TelegramChannelConfig = {}): TelegramChaawait handle.sendMessage(initialMessage);}- return send(input.message, {+ return from(continuationTokenFromState(receiveState)).send(input.message, {auth: input.auth,- continuationToken: continuationTokenFromState(receiveState),state: receiveState,});},@@ -346,7 +346,7 @@ function buildTelegramHandle(input: {if (!posted.id || !shouldAnchorTelegramConversation(chatType)) return;state.conversationId = posted.id;if (state.chatId) {- input.session?.setContinuationToken(+ input.session?.continuation?.rekey(telegramContinuationToken({chatId: state.chatId,conversationId: posted.id,@@ -475,7 +475,7 @@ async function dispatchMessage(input: {readonly config: TelegramChannelConfig;readonly message: TelegramMessage;readonly onMessage: NonNullable<TelegramChannelConfig["onMessage"]>;- readonly send: SendFn<TelegramChannelState>;+ readonly from: ChannelFrom<TelegramChannelState>;readonly uploadPolicy: UploadPolicy;}): Promise<void> {if (input.message.from?.isBot === true) return;@@ -520,18 +520,19 @@ async function dispatchMessage(input: {: undefined;try {- await input.send(- {- inputResponses: replyInputResponses,- message: turnMessage,- context: [contextBlock, ...channelContext],- },- {+ const source = input.from(continuationTokenFromState(state));+ if (replyInputResponses === undefined) {+ await source.send(turnMessage, {auth: result.auth,- continuationToken: continuationTokenFromState(state),+ context: [contextBlock, ...channelContext],state,- },- );+ });+ } else {+ await source.respond(replyInputResponses, {+ auth: result.auth,+ context: [contextBlock, ...channelContext],+ });+ }} catch (error) {log.error("message delivery failed", { error });}@@ -540,7 +541,7 @@ async function dispatchMessage(input: {async function dispatchCallbackQuery(input: {readonly config: TelegramChannelConfig;readonly query: TelegramCallbackQuery;- readonly send: SendFn<TelegramChannelState>;+ readonly from: ChannelFrom<TelegramChannelState>;}): Promise<void> {const state = stateFromCallbackQuery(input.query, input.config);const telegram: TelegramContext = {@@ -559,16 +560,10 @@ async function dispatchCallbackQuery(input: {if (!input.query.message || !state.chatId) return;try {- await input.send(- {- inputResponses: [telegramCallbackInputResponse(input.query.data)],- },- {- auth: null,- continuationToken: continuationTokenFromState(state),- state,- },- );+ const source = input.from(continuationTokenFromState(state));+ await source.respond([telegramCallbackInputResponse(input.query.data)], {+ auth: null,+ });} catch (error) {log.error("callback query delivery failed", { error });}diff --git a/packages/eve/src/public/channels/twilio/twilioChannel.test.ts b/packages/eve/src/public/channels/twilio/twilioChannel.test.tsindex 320f58de0..b31802b4d 100644--- a/packages/eve/src/public/channels/twilio/twilioChannel.test.ts+++ b/packages/eve/src/public/channels/twilio/twilioChannel.test.ts@@ -6,6 +6,7 @@ import { isCompiledChannel, type CompiledChannel } from "#channel/compiled-channimport { isHttpRouteDefinition } from "#channel/routes.js";import { ContextContainer, contextStorage } from "#context/container.js";import { SessionKey } from "#context/keys.js";+import { mockChannelContext } from "#internal/testing/mocks/mock-channel-operations.js";import type { UnstampedMessageStreamEvent } from "#protocol/message.js";import type { TwilioTextMessage } from "#public/channels/twilio/inbound.js";import { twilioChannel, type TwilioContext } from "#public/channels/twilio/twilioChannel.js";@@ -105,16 +106,17 @@ async function firePost(if (!post || !isHttpRouteDefinition(post)) {throw new Error(`Expected Twilio channel to define POST ${path}.`);}- const send = vi.fn().mockResolvedValue({ continuationToken: "ct", id: "s1" });+ const send = vi.fn().mockResolvedValue({ id: "s1" });const waitUntil = vi.fn();const response = await post.handler(signedFormRequest(path, params), {- getSession: vi.fn() as any,+ attachSession: vi.fn() as any,+ ...mockChannelContext(send),+ to: vi.fn() as any,params: {},requestIp: null,- send,waitUntil,- } as any);+ });let drained = 0;while (drained < waitUntil.mock.calls.length) {@@ -140,16 +142,17 @@ async function fireGet(if (!get || !isHttpRouteDefinition(get)) {throw new Error(`Expected Twilio channel to define GET ${path}.`);}- const send = vi.fn().mockResolvedValue({ continuationToken: "ct", id: "s1" });+ const send = vi.fn().mockResolvedValue({ id: "s1" });const waitUntil = vi.fn();const response = await get.handler(signedGetRequest(path, params), {- getSession: vi.fn() as any,+ attachSession: vi.fn() as any,+ ...mockChannelContext(send),+ to: vi.fn() as any,params: {},requestIp: null,- send,waitUntil,- } as any);+ });let drained = 0;while (drained < waitUntil.mock.calls.length) {@@ -208,8 +211,8 @@ describe("twilioChannel() inbound text pipeline", () => {expect(response.status).toBe(200);expect(await response.text()).toBe("<Response></Response>");expect(send).toHaveBeenCalledTimes(1);- const [payload, options] = send.mock.calls[0]!;- const { message, context } = payload as { message: string; context: string[] };+ const [continuationToken, input] = send.mock.calls[0]!;+ const { message, context } = input as { message: string; context: string[] };const contextBlock = context[0]!;expect(contextBlock).toContain("<twilio_context>");expect(contextBlock).toContain("channel: text");@@ -217,12 +220,12 @@ describe("twilioChannel() inbound text pipeline", () => {expect(contextBlock).toContain("Reply for SMS in plain text.");expect(contextBlock).toContain("avoid Markdown formatting");expect(message).toBe("hello");- expect(options).toMatchObject({+ expect(continuationToken).toBe("+15551234567:+15557654321");+ expect(input).toMatchObject({auth: {authenticator: "twilio-webhook",principalId: "twilio:+15551234567",},- continuationToken: "+15551234567:+15557654321",state: {from: "+15551234567",lastMessageSid: "SM123",@@ -244,10 +247,10 @@ describe("twilioChannel() inbound text pipeline", () => {expect(response.status).toBe(200);expect(send).toHaveBeenCalledTimes(1);- const [payload, options] = send.mock.calls[0]!;- expect(payload).toMatchObject({ message: "hello from get" });- expect(options).toMatchObject({- continuationToken: "+15551234567:+15557654321",+ const [continuationToken, input] = send.mock.calls[0]!;+ expect(continuationToken).toBe("+15551234567:+15557654321");+ expect(input).toMatchObject({+ message: "hello from get",state: {from: "+15551234567",lastMessageSid: "SM123",@@ -357,12 +360,13 @@ describe("twilioChannel() inbound text pipeline", () => {method: "POST",}),{- getSession: vi.fn() as any,+ attachSession: vi.fn() as any,+ ...mockChannelContext(send),+ to: vi.fn() as any,params: {},requestIp: null,- send,waitUntil: vi.fn(),- } as any,+ },);expect(response.status).toBe(401);@@ -391,12 +395,12 @@ describe("twilioChannel() inbound text pipeline", () => {}),);+ expect(first.send.mock.calls[0]![0]).toBe("+15551234567:+15550000001");expect(first.send.mock.calls[0]![1]).toMatchObject({- continuationToken: "+15551234567:+15550000001",state: { from: "+15551234567", to: "+15550000001" },});+ expect(second.send.mock.calls[0]![0]).toBe("+15551234567:+15550000002");expect(second.send.mock.calls[0]![1]).toMatchObject({- continuationToken: "+15551234567:+15550000002",state: { from: "+15551234567", to: "+15550000002" },});});@@ -522,15 +526,15 @@ describe("twilioChannel() voice pipeline", () => {expect(response.status).toBe(200);expect(await response.text()).toContain("Thanks. I'll follow up by text.");expect(send).toHaveBeenCalledTimes(1);- const [payload, options] = send.mock.calls[0]!;- const { message, context } = payload as { message: string; context: string[] };+ const [continuationToken, input] = send.mock.calls[0]!;+ const { message, context } = input as { message: string; context: string[] };const contextBlock = context[0]!;expect(contextBlock).toContain("channel: voice");expect(contextBlock).toContain("response_medium: sms");expect(contextBlock).toContain("Reply for SMS in plain text.");expect(message).toBe("book a table");- expect(options).toMatchObject({- continuationToken: "+15551234567:+15557654321",+ expect(continuationToken).toBe("+15551234567:+15557654321");+ expect(input).toMatchObject({state: {from: "+15551234567",lastCallSid: "CA123",@@ -637,7 +641,7 @@ describe("twilioChannel() default event handlers", () => {allowFrom: "*",messaging: { from: "+15557654321" },});- const send = vi.fn().mockResolvedValue({ continuationToken: "+15551234567", id: "s1" });+ const send = vi.fn().mockResolvedValue({ id: "s1" });await channel.receive!({@@ -645,12 +649,14 @@ describe("twilioChannel() default event handlers", () => {auth: null,message: "start",},- { send },+ {+ ...mockChannelContext(send),+ },);- expect(send).toHaveBeenCalledWith("start", {+ expect(send).toHaveBeenCalledWith("+15551234567:+15557654321", {auth: null,- continuationToken: "+15551234567:+15557654321",+ message: "start",state: {from: "+15551234567",lastCallSid: null,diff --git a/packages/eve/src/public/channels/twilio/twilioChannel.ts b/packages/eve/src/public/channels/twilio/twilioChannel.tsindex cf8f89dfd..c21892ff7 100644--- a/packages/eve/src/public/channels/twilio/twilioChannel.ts+++ b/packages/eve/src/public/channels/twilio/twilioChannel.ts@@ -1,8 +1,9 @@import type { SessionHandle } from "#channel/session.js";import type { SessionAuthContext } from "#channel/types.js";import type { RouteHandler } from "#channel/routes.js";+import type { ChannelFrom } from "#channel/channel-operations.js";import type { SessionContext } from "#public/definitions/callback-context.js";-import type { ChannelSessionOps } from "#public/definitions/channel.js";+import type { ChannelContinuationOps } from "#public/definitions/channel.js";import { createLogger } from "#internal/logging.js";import type { UnstampedMessageStreamEvent } from "#protocol/message.js";@@ -43,13 +44,7 @@ import {} from "#public/channels/twilio/routing.js";import { type TwilioAuthToken, type TwilioWebhookUrl } from "#public/channels/twilio/verify.js";import { readNonEmptyString } from "#shared/guards.js";-import {- defineChannel,- GET,- POST,- type Channel,- type SendFn,-} from "#public/definitions/channel.js";+import { defineChannel, GET, POST, type Channel } from "#public/definitions/channel.js";const log = createLogger("twilio.channel");@@ -66,8 +61,8 @@ export interface TwilioChannelContext extends TwilioContext {state: TwilioChannelState;}-/** Event-handler Twilio context, including session operations. */-export interface TwilioEventContext extends TwilioChannelContext, ChannelSessionOps {}+/** Event-handler Twilio context, including continuation routing. */+export interface TwilioEventContext extends TwilioChannelContext, ChannelContinuationOps {}/** JSON-serializable state for the phone-number conversation. */export interface TwilioChannelState {@@ -329,22 +324,24 @@ export function twilioChannel(config: TwilioChannelConfig): TwilioChannel {POST<TwilioChannelState>(routes.transcription, transcription),],- async receive(input, { send }) {+ async receive(input, { from }) {const phoneNumber = readNonEmptyString(input.target.phoneNumber);if (!phoneNumber) {throw new Error("twilioChannel().receive requires target.phoneNumber.");}- const from = readNonEmptyString(input.target.from) ?? config.messaging?.from ?? null;- return send(input.message, {- auth: input.auth,- continuationToken: twilioContinuationToken(phoneNumber, from ?? undefined),- state: {- from: phoneNumber,- lastCallSid: null,- lastMessageSid: null,- to: from,+ const senderNumber = readNonEmptyString(input.target.from) ?? config.messaging?.from ?? null;+ return from(twilioContinuationToken(phoneNumber, senderNumber ?? undefined)).send(+ input.message,+ {+ auth: input.auth,+ state: {+ from: phoneNumber,+ lastCallSid: null,+ lastMessageSid: null,+ to: senderNumber,+ },},- });+ );},events: mergedEvents,@@ -355,7 +352,7 @@ function handleTwilioMessages(input: {readonly config: TwilioChannelConfig;readonly onText: NonNullable<TwilioChannelConfig["onText"]>;}): RouteHandler<TwilioChannelState> {- return async (req, { send, waitUntil }) => {+ return async (req, { from, waitUntil }) => {const verified = await verifyTwilioInbound(req, input.config);if (verified === null) return new Response("unauthorized", { status: 401 });@@ -370,7 +367,7 @@ function handleTwilioMessages(input: {config: input.config,message,onText: input.onText,- send,+ from,}),);return emptyTwilioResponse();@@ -422,7 +419,7 @@ function handleTwilioTranscription(input: {readonly onVoiceTranscription: NonNullable<TwilioChannelConfig["onVoiceTranscription"]>;readonly routes: TwilioRoutes;}): RouteHandler<TwilioChannelState> {- return async (req, { send, waitUntil }) => {+ return async (req, { from, waitUntil }) => {const verified = await verifyTwilioInbound(req, input.config);if (verified === null) return new Response("unauthorized", { status: 401 });@@ -444,7 +441,7 @@ function handleTwilioTranscription(input: {dispatchVoiceTranscription({config: input.config,onVoiceTranscription: input.onVoiceTranscription,- send,+ from,transcription,}),);@@ -531,7 +528,7 @@ async function dispatchText(input: {readonly config: TwilioChannelConfig;readonly message: TwilioTextMessage;readonly onText: NonNullable<TwilioChannelConfig["onText"]>;- readonly send: SendFn<TwilioChannelState>;+ readonly from: ChannelFrom<TwilioChannelState>;}): Promise<void> {const { message } = input;const twilio: TwilioContext = {@@ -560,22 +557,16 @@ async function dispatchText(input: {});try {- await input.send(- {- message: message.body,- context: [contextBlock],- },- {- auth: result.auth,- continuationToken: twilioContinuationToken(message.from, message.to),- state: {- from: message.from,- lastCallSid: null,- lastMessageSid: message.messageSid ?? null,- to: message.to ?? null,- },+ await input.from(twilioContinuationToken(message.from, message.to)).send(message.body, {+ auth: result.auth,+ context: [contextBlock],+ state: {+ from: message.from,+ lastCallSid: null,+ lastMessageSid: message.messageSid ?? null,+ to: message.to ?? null,},- );+ });} catch (error) {log.error("text delivery failed", { error });}@@ -607,7 +598,7 @@ async function acceptVoiceCall(input: {async function dispatchVoiceTranscription(input: {readonly config: TwilioChannelConfig;readonly onVoiceTranscription: NonNullable<TwilioChannelConfig["onVoiceTranscription"]>;- readonly send: SendFn<TwilioChannelState>;+ readonly from: ChannelFrom<TwilioChannelState>;readonly transcription: TwilioVoiceTranscription;}): Promise<void> {const { transcription } = input;@@ -637,22 +628,18 @@ async function dispatchVoiceTranscription(input: {});try {- await input.send(- {- message: transcription.text,- context: [contextBlock],- },- {+ await input+ .from(twilioContinuationToken(transcription.from, transcription.to))+ .send(transcription.text, {auth: result.auth,- continuationToken: twilioContinuationToken(transcription.from, transcription.to),+ context: [contextBlock],state: {from: transcription.from,lastCallSid: transcription.callSid ?? null,lastMessageSid: null,to: transcription.to ?? null,},- },- );+ });} catch (error) {log.error("voice transcription delivery failed", { error });}diff --git a/packages/eve/src/public/definitions/callback-context.ts b/packages/eve/src/public/definitions/callback-context.tsindex c34d20503..21137a3e3 100644--- a/packages/eve/src/public/definitions/callback-context.ts+++ b/packages/eve/src/public/definitions/callback-context.ts@@ -14,8 +14,7 @@ export type { SessionAuth, SessionParent, SessionTurn };*/export interface SessionContext {/**- * Active session metadata. Mirrors the `Session` type but exposes the- * identifier as `id` here, where `Session` names it `sessionId`.+ * Active session metadata for the callback's exact durable session.*/readonly session: {readonly id: string;diff --git a/packages/eve/src/public/definitions/channel.test.ts b/packages/eve/src/public/definitions/channel.test.tsindex a2e961d3b..637345b90 100644--- a/packages/eve/src/public/definitions/channel.test.ts+++ b/packages/eve/src/public/definitions/channel.test.ts@@ -6,7 +6,7 @@ import { isCompiledChannel } from "#channel/compiled-channel.js";import type { InferReceiveTarget } from "#channel/receive-target.js";import { ContextContainer, contextStorage } from "#context/container.js";import type { ContextAccessor } from "#context/key.js";-import { SessionKey, type Session } from "#context/keys.js";+import { SessionIdKey, SessionKey, type Session } from "#context/keys.js";import type { slackChannel, SlackInstrumentationMetadata } from "#public/channels/slack/index.js";import type {twilioChannel,@@ -179,15 +179,13 @@ describe("defineChannel", () => {return { state };},routes: [- POST<State>("/x", async (_request, { send }) => {- await send("hello", {+ POST<State>("/x", async (_request, { from }) => {+ await from("x").send("hello", {auth: null,- continuationToken: "x",state: { completedTurns: 1 },});- await send("hello", {+ await from("x").send("hello", {auth: null,- continuationToken: "x",// @ts-expect-error route send state is inferred from defineChannel state.state: { completedTurns: "1" },});@@ -321,7 +319,9 @@ describe("defineChannel", () => {readonly threadTs: string | null;}- const captured: { sessions: Array<{ setContinuationToken: (t: string) => void }> } = {+ const captured: {+ sessions: Array<{ continuation?: { rekey(token: string): void } }>;+ } = {sessions: [],};const channel = defineChannel<State, { state: State }>({@@ -337,7 +337,7 @@ describe("defineChannel", () => {const adapter = getAdapter(channel);// Stand up a minimal accessor whose `set` calls are captured so the- // session handle's `setContinuationToken` is observable.+ // session handle's continuation rekey is observable.const writes: Array<[string, unknown]> = [];let continuationToken = "slack:C123:";const accessor: ContextAccessor = {@@ -369,7 +369,7 @@ describe("defineChannel", () => {// The session is the one ctx.session exposes (same reference).expect(adapterCtx.session).toBe(captured.sessions[0]);- captured.sessions[0]!.setContinuationToken("C123:T456");+ captured.sessions[0]!.continuation?.rekey("C123:T456");expect(writes).toEqual([["eve.continuationToken", "slack:C123:T456"]]);});@@ -395,6 +395,7 @@ describe("defineChannel", () => {};const ctx = new ContextContainer();ctx.set(SessionKey, session);+ ctx.set(SessionIdKey, session.sessionId);const accessor: ContextAccessor = {get: (key) => ctx.get(key as any),@@ -415,8 +416,8 @@ describe("defineChannel", () => {expect(typeof capturedCtx.getSkill).toBe("function");expect(capturedCtx.session.id).toBe("sess-channel-test");expect(capturedCtx.session.turn).toEqual({ id: "turn-1", sequence: 0 });- expect(typeof capturedChannel.continuationToken).toBe("string");- expect(typeof capturedChannel.setContinuationToken).toBe("function");+ expect(capturedChannel.session).toBeUndefined();+ expect(capturedChannel.continuation).toBeUndefined();});it("registers reasoning event handlers with channel and session context", async () => {@@ -446,6 +447,7 @@ describe("defineChannel", () => {};const ctx = new ContextContainer();ctx.set(SessionKey, session);+ ctx.set(SessionIdKey, session.sessionId);const accessor: ContextAccessor = {get: (key) => ctx.get(key as any),@@ -495,19 +497,24 @@ describe("defineChannel", () => {reasoning: "Need to inspect the repo.",turnId: "turn-1",});- expect(typeof capturedChannel.continuationToken).toBe("string");+ expect(capturedChannel.session).toBeUndefined();+ expect(capturedChannel.continuation).toBeUndefined();expect(capturedCtx.session.id).toBe("sess-channel-test");});- it("session.failed handler receives no ctx parameter", async () => {+ it("session.failed exposes its session id in event data without a ctx parameter", async () => {let called = false;let argCount = 0;+ let observedSessionId: string | undefined;+ let capturedChannel: any;const channel = defineChannel({routes: [POST("/x", async () => new Response("ok"))],events: {"session.failed": (...args) => {called = true;argCount = args.length;+ observedSessionId = args[0].sessionId;+ capturedChannel = args[1];},},});@@ -537,6 +544,8 @@ describe("defineChannel", () => {expect(called).toBe(true);expect(argCount).toBe(2);+ expect(observedSessionId).toBe("sess-1");+ expect(capturedChannel.session).toBeUndefined();});it("advertises typed cross-channel receive targets from raw defineChannel", () => {@@ -557,10 +566,24 @@ describe("defineChannel", () => {return {id: channelId,- continuationToken: channelId,+ async send() {+ return { sessionId: channelId, status: "accepted" as const };+ },+ async respond() {+ return { sessionId: channelId, status: "accepted" as const };+ },async cancel() {return { status: "no_active_turn" as const };},+ async compact() {+ return { sessionId: channelId, status: "accepted" as const };+ },+ async clear() {+ return { sessionId: channelId, status: "accepted" as const };+ },+ async reset() {+ return { previousSessionId: channelId, status: "reset" as const };+ },async getEventStream() {return new ReadableStream();},diff --git a/packages/eve/src/public/definitions/channel.ts b/packages/eve/src/public/definitions/channel.tsindex bc4c23d91..cacb6e276 100644--- a/packages/eve/src/public/definitions/channel.ts+++ b/packages/eve/src/public/definitions/channel.ts@@ -1,55 +1,55 @@import type { ChannelAdapter, ChannelInstrumentationMetadata } from "#channel/adapter.js";import { defaultDeliverResult } from "#channel/adapter.js";-import { CHANNEL_SENTINEL, type CompiledChannel } from "#channel/compiled-channel.js";+import {+ CHANNEL_SENTINEL,+ type ChannelReference,+ type CompiledChannel,+} from "#channel/compiled-channel.js";import { normalizeChannelCors, type ChannelCorsOptions } from "#channel/cors.js";import { HTTP_ADAPTER_KIND } from "#channel/http.js";-import type { TypedReceiveTarget } from "#channel/receive-target.js";-import type { RouteDefinition, SendFn } from "#channel/routes.js";-import type { Session, SessionHandle } from "#channel/session.js";import type {- CancelTurnInput,- CancelTurnResult,- DeliverInput,- DeliverPayload,- GetEventStreamOptions,- RunHandle,- RunInput,-} from "#channel/types.js";+ ChannelFrom,+ ChannelReceiveContext,+ ChannelResolveSession,+ ChannelRespondOptions,+ ChannelSendOptions,+ ChannelSource,+} from "#channel/channel-operations.js";+import type { RouteDefinition } from "#channel/routes.js";+import type { Session, SessionHandle } from "#channel/session.js";+import type { DeliverPayload } from "#channel/types.js";import { buildCallbackContext } from "#context/build-callback-context.js";-import type { UnstampedMessageStreamEvent, MessageStreamEvent } from "#protocol/message.js";+import type { UnstampedMessageStreamEvent } from "#protocol/message.js";import type { SessionContext } from "#public/definitions/callback-context.js";import type { GenericChannelDefinition, GenericReceiveInput } from "#shared/channel-definition.js";declare const CHANNEL_METADATA_TYPE: unique symbol;export type {- CancelTurnInput,CancelTurnResult,ClearSessionResult,CompactSessionResult,GetEventStreamOptions,+ ResetSessionResult,+ SessionCallback,} from "#channel/types.js";export type { Session, SessionHandle } from "#channel/session.js";+export type { SessionRespondOptions, SessionSendOptions } from "#channel/session.js";+export type {+ ChannelFrom,+ ChannelReceiveContext,+ ChannelResolveSession,+ ChannelRespondOptions,+ ChannelSendOptions,+ ChannelSource,+};export type { ChannelCors, ChannelCorsOptions } from "#channel/cors.js";export { GET, POST, PUT, PATCH, DELETE, WS } from "#channel/routes.js";export type {- CancelFn,- CancelOptions,- ClearFn,- ClearOptions,- CompactFn,- CompactOptions,- ResetFn,- ResetOptions,- ResetResult,+ AttachSessionFn,HttpRouteDefinition,RouteDefinition,RouteHandlerArgs,- SendFn,- SendOptions,- SendPayload,- ResolveActiveSessionFn,- GetSessionFn,WebSocketMessage,WebSocketPeer,WebSocketRouteDefinition,@@ -79,27 +79,14 @@ export type ChannelRouteMethod = ChannelMethod | "WEBSOCKET";* framework constructs this per request and passes it as the second* argument.*- * Routes call into the agent to start sessions, deliver follow-ups,- * cancel turns, and read events.+ * Framework callback routes use this for request metadata and background work.*/export interface RouteContext {- /**- * Handle to the agent that this route sends inbound requests to.- * Conceptually the runtime + harness combined: routes call `run`,- * `deliver`, `cancelTurn`, and `getEventStream` to drive sessions of- * this agent without knowing about the workflow runtime, the harness,- * or any other execution-layer detail.- *- * Every route speaks the same `RunInput` shape regardless of which- * webhook it serves — `agent` is platform-agnostic.- */- readonly agent: Agent;/*** Hands a background promise to the request host so the serverless* invocation stays alive until the promise resolves. Use this when the* route responds to the platform immediately (e.g. a Slack `200 OK`- * acknowledgement) but still needs to drive an `agent.run()` call to- * completion.+ * acknowledgement) but still needs to finish background work.*/readonly waitUntil: (task: Promise<unknown>) => void;/**@@ -121,58 +108,6 @@ export interface RouteContext {readonly requestIp: string | null;}-/**- * Route-facing handle to the agent that owns this request.- *- * `Agent` is conceptually the workflow runtime plus the tool-loop harness:- * routes call `run` to start a new session of the agent, `deliver` to- * send a follow-up to a parked session, `cancelTurn` to stop in-flight work,- * and `getEventStream` to read events from a previously-started session.- * The framework's internal `Runtime`- * interface (in `channel/types.ts`) is the underlying primitive — `Agent`- * is the *public* shape exposed on `RouteContext` so route authors- * speak in terms of the agent rather than the runtime.- */-export interface Agent {- /**- * Starts a new agent session and returns a handle. The session's identity- * is the supplied `continuationToken` — subsequent calls to `deliver()`- * with the same token resume the same session.- */- run(input: RunInput): Promise<RunHandle>;- /**- * Requests cancellation of a session's in-flight turn. A `turnId` limits- * the request to the turn the caller observed.- *- * `"accepted"` means a cancellation hook accepted the request; observe- * the event stream for `turn.cancelled` to confirm that it affected the- * current turn. `"no_active_turn"` means no cancellable hook was active.- * Both outcomes are successful.- */- cancelTurn(input: CancelTurnInput): Promise<CancelTurnResult>;- /**- * Sends a follow-up message to a session that is currently parked waiting- * for input. Throws if no parked session exists for the supplied- * `continuationToken` — routes typically catch the failure and fall back- * to `run()` to start a new session.- */- deliver(input: DeliverInput): Promise<{ sessionId: string }>;- /**- * Returns a readable NDJSON-style stream of lifecycle events for an- * existing session. Used by the framework's HTTP session-stream route and by- * any user-authored route that exposes an event-streaming endpoint.- *- * Nonnegative `options.startIndex` values skip events the caller has already- * consumed. Negative values read relative to the current tail (`-1` starts- * at the latest event). The framework HTTP session-stream route forwards- * the `startIndex` query parameter unchanged.- */- getEventStream(- sessionId: string,- options?: GetEventStreamOptions,- ): Promise<ReadableStream<MessageStreamEvent>>;-}-/*** Marker discriminator written into every {@link DisabledRouteSentinel}.*/@@ -214,19 +149,19 @@ export function isDisabledRouteSentinel(value: unknown): value is DisabledRouteStype EventData<T extends UnstampedMessageStreamEvent["type"]> =Extract<UnstampedMessageStreamEvent, { type: T }> extends { data: infer D } ? D : undefined;-/**- * Session operations on the `channel` argument of every channel event handler.- */-export interface ChannelSessionOps {- readonly continuationToken: string;- setContinuationToken(token: string): void;+/** Continuation routing on the `channel` argument of every channel event handler. */+export interface ChannelContinuationOps {+ readonly continuation?: {+ readonly token: string;+ rekey(token: string): void;+ };}/*** Channel context passed to event handlers: `TCtx` intersected with- * {@link ChannelSessionOps}.+ * {@link ChannelContinuationOps}.*/-export type ChannelContext<TCtx> = TCtx & ChannelSessionOps;+export type ChannelContext<TCtx> = TCtx & ChannelContinuationOps;type ChannelEventHandler<T extends UnstampedMessageStreamEvent["type"], TCtx> = (data: EventData<T>,@@ -243,7 +178,7 @@ type ChannelSessionFailedHandler<TCtx> = (* Optional handlers keyed by session lifecycle event name. Each handler receives* the event `data`, the {@link ChannelContext}, and a {@link SessionContext}* `ctx`. The `session.failed` handler is the exception: it receives only `data`- * and the channel context, with no `ctx`.+ * and the channel context, with no `ctx`; its data includes `sessionId`.*/export interface ChannelEvents<TCtx = void> {readonly "context.cleared"?: ChannelEventHandler<"context.cleared", TCtx>;@@ -304,14 +239,13 @@ export interface Channel<TState = undefined,TReceiveTarget = Record<string, unknown>,TMetadata extends Record<string, unknown> = Record<string, unknown>,-> extends TypedReceiveTarget<TReceiveTarget> {- readonly __kind: typeof CHANNEL_SENTINEL;+> extends ChannelReference<TReceiveTarget> {readonly [CHANNEL_METADATA_TYPE]?: TMetadata;readonly routes: readonly RouteDefinition<TState>[];readonly cors?: ChannelCorsOptions;readonly receive?: (input: ReceiveInput<TReceiveTarget>,- args: { send: SendFn<TState> },+ ctx: ChannelReceiveContext<TState>,) => Promise<Session>;}@@ -396,10 +330,16 @@ function buildAdapter<TState, TCtx, TReceiveTarget, TMetadata extends Record<strif (userHandler) {hasEventHandlers = true;eventHandlers[eventType] = (data: unknown, adapterCtx: any) => {+ const { session, ...platformContext } = adapterCtx;const channel = {- ...adapterCtx,- continuationToken: adapterCtx.session?.continuationToken ?? "",- setContinuationToken: (token: string) => adapterCtx.session?.setContinuationToken(token),+ ...platformContext,+ continuation:+ session?.continuation === undefined+ ? undefined+ : {+ token: session.continuation.token,+ rekey: (token: string) => session.continuation?.rekey(token),+ },};if (eventType === "session.failed") {return (userHandler as (data: unknown, channel: any) => void | Promise<void>)(diff --git a/packages/eve/src/public/definitions/exact.test.ts b/packages/eve/src/public/definitions/exact.test.tsindex a7c78bf5c..2cff701fa 100644--- a/packages/eve/src/public/definitions/exact.test.ts+++ b/packages/eve/src/public/definitions/exact.test.ts@@ -230,9 +230,10 @@ function typeOnlyFixtures(): void {const sessionId: string = ctx.session.id;void sessionId;},- "session.failed"(_data, _channel) {+ "session.failed"(data, _channel) {// session.failed has no ctx — fires outside ALS on terminal failures.- void _data;+ const sessionId: string = data.sessionId;+ void sessionId;void _channel;},},@@ -284,18 +285,28 @@ function typeOnlyFixtures(): void {},events: {"turn.started"(_data, channel, ctx) {- const continuationToken: string = channel.continuationToken;+ const continuationToken: string | undefined = channel.continuation?.token;const sessionId: string = ctx.session.id;void continuationToken;void sessionId;},- "session.failed"(_data, channel) {- const continuationToken: string = channel.continuationToken;+ "session.failed"(data, channel) {+ const sessionId: string = data.sessionId;+ const continuationToken: string | undefined = channel.continuation?.token;+ void sessionId;void continuationToken;},},});+ eveChannel({+ auth: none(),+ // @ts-expect-error canonical eve HTTP messages must dispatch or fail.+ onMessage() {+ return null;+ },+ });+defineSandbox({async onSession({ ctx, use }) {const sessionId: string = ctx.session.id;diff --git a/packages/eve/src/public/definitions/remote-agent.ts b/packages/eve/src/public/definitions/remote-agent.tsindex 324d593da..de6993e48 100644--- a/packages/eve/src/public/definitions/remote-agent.ts+++ b/packages/eve/src/public/definitions/remote-agent.ts@@ -1,7 +1,7 @@import type { StandardJSONSchemaV1 } from "#compiled/@standard-schema/spec/index.js";import type { HeadersValue } from "#client/types.js";import type { OutboundAuthFn } from "#public/agents/auth.js";-import { EVE_CREATE_SESSION_ROUTE_PATH } from "#protocol/routes.js";+import { EVE_SESSION_ROUTE_PATH } from "#protocol/routes.js";import type { JsonObject } from "#shared/json.js";/**@@ -79,6 +79,6 @@ export function defineRemoteAgent(input: RemoteAgentDefinitionInput): RemoteAgenreturn {...input,kind: "remote",- path: input.path ?? EVE_CREATE_SESSION_ROUTE_PATH,+ path: input.path ?? EVE_SESSION_ROUTE_PATH,};}diff --git a/packages/eve/src/public/definitions/schedule.ts b/packages/eve/src/public/definitions/schedule.tsindex b2cfbbc7c..43757bbdf 100644--- a/packages/eve/src/public/definitions/schedule.ts+++ b/packages/eve/src/public/definitions/schedule.ts@@ -1,4 +1,4 @@-import type { CrossChannelReceiveFn } from "#channel/cross-channel-receive.js";+import type { CrossChannelToFn } from "#channel/cross-channel-receive.js";import type { SessionAuthContext } from "#channel/types.js";import type { ExactDefinition } from "#public/definitions/exact.js";import type {@@ -9,18 +9,20 @@ import type {export type { InferReceiveTarget, TypedReceiveTarget } from "#channel/receive-target.js";+/** Selects a proactive target channel from a schedule handler. */+export type ScheduleToFn = CrossChannelToFn;+/*** Arguments passed to a schedule's `run` handler. A tight subset of a route- * handler's args: `receive` starts a session on another channel and `waitUntil`- * extends the task lifetime. There is no `send` because a schedule has no- * current channel.+ * handler's args: `to` selects another channel and `waitUntil`+ * extends the task lifetime.*/export interface ScheduleHandlerArgs {/**- * Starts a session on another channel, using the same contract as a route- * handler's `args.receive(channel, ...)`.+ * Selects a proactive target on another channel. Call `.send(message, options)`+ * on the returned handle.*/- readonly receive: CrossChannelReceiveFn;+ readonly to: ScheduleToFn;/*** Extends the cron task's lifetime past handler return so the runtime awaits* background work (the parked workflow session, in-flight fetches, etc.)@@ -28,7 +30,7 @@ export interface ScheduleHandlerArgs {*/readonly waitUntil: (task: Promise<unknown>) => void;/**- * Pre-built APP auth context. Pass this to `receive(channel, { auth })`+ * Pre-built APP auth context. Pass this to `to(channel, target).send(message, { auth })`* for schedules that run on behalf of the agent itself.*/readonly appAuth: SessionAuthContext;@@ -36,7 +38,7 @@ export interface ScheduleHandlerArgs {/*** The `run` form of {@link ScheduleDefinition} invokes this handler when a- * schedule's cron fires. It receives {@link ScheduleHandlerArgs} (`receive`,+ * schedule's cron fires. It receives {@link ScheduleHandlerArgs} (`to`,* `waitUntil`, `appAuth`) and may return synchronously or as a promise.*/export type ScheduleRunHandler = GenericScheduleRunHandler<ScheduleHandlerArgs>;@@ -49,7 +51,7 @@ export type ScheduleRunHandler = GenericScheduleRunHandler<ScheduleHandlerArgs>;* on the prompt and discards the output (equivalent to the `<name>.md`* markdown form).* - `run`: full handler ({@link ScheduleRunHandler}). Receives- * `{ receive, waitUntil, appAuth }` and decides what to do.+ * `{ to, waitUntil, appAuth }` and decides what to do.** Identity is derived from the file path under `agent/schedules/`; authored* definitions do not carry a `name` field.@@ -69,12 +71,11 @@ export type ScheduleDefinition = GenericScheduleDefinition<ScheduleHandlerArgs>;** export default defineSchedule({* cron: "0 9 * * 1-5",- * async run({ receive, waitUntil, appAuth }) {- * waitUntil(receive(slack, {- * message: "Post the daily standup summary.",- * target: { channelId: "C0123ABC" },- * auth: appAuth,- * }));+ * async run({ to, waitUntil, appAuth }) {+ * waitUntil(to(slack, { channelId: "C0123ABC" }).send(+ * "Post the daily standup summary.",+ * { auth: appAuth },+ * ));* },* });* ```diff --git a/packages/eve/src/public/schedules/index.ts b/packages/eve/src/public/schedules/index.tsindex 392d1c78e..d9aac20a0 100644--- a/packages/eve/src/public/schedules/index.ts+++ b/packages/eve/src/public/schedules/index.ts@@ -7,5 +7,6 @@ export {type ScheduleDefinition,type ScheduleHandlerArgs,type ScheduleRunHandler,+ type ScheduleToFn,type TypedReceiveTarget,} from "#public/definitions/schedule.js";diff --git a/packages/eve/src/react/use-eve-agent.test.ts b/packages/eve/src/react/use-eve-agent.test.tsindex e0d98169a..3890578ea 100644--- a/packages/eve/src/react/use-eve-agent.test.ts+++ b/packages/eve/src/react/use-eve-agent.test.ts@@ -15,7 +15,7 @@ import {type UnstampedMessageStreamEvent,} from "#protocol/message.js";import { stampTestEvents } from "#internal/testing/events.js";-import type { SessionState } from "#client/types.js";+import type { ClientSessionState } from "#client/types.js";function createStartedMessageResponse(sessionId: string, continuationToken: string): Response {return new Response(JSON.stringify({ continuationToken, ok: true, sessionId }), {@@ -155,7 +155,7 @@ describe("useEveAgent", () => {stepIndex: 0,turnId: "turn_1",}),- createSessionWaitingEvent("eve:http:session_1"),+ createSessionWaitingEvent(),];const startResponse = createDeferred<Response>();@@ -164,16 +164,19 @@ describe("useEveAgent", () => {.mockReturnValueOnce(startResponse.promise).mockResolvedValueOnce(createEagerStreamResponse(events));+ const lifecycle: string[] = [];const seenEvents: UnstampedMessageStreamEvent[] = [];- const seenSessions: SessionState[] = [];+ const seenSessions: Array<ClientSessionState | undefined> = [];let helpers: UseEveAgentHelpers<EveMessageData> | undefined;function TestComponent() {helpers = useEveAgent({onEvent(event) {+ lifecycle.push(`event:${event.type}`);seenEvents.push(event);},onSessionChange(session) {+ lifecycle.push(`session:${String(session?.streamIndex)}`);seenSessions.push(session);},});@@ -186,7 +189,7 @@ describe("useEveAgent", () => {let sendPromise: Promise<void> | undefined;await act(async () => {- sendPromise = helpers?.send({ message: "Hello" });+ sendPromise = helpers?.send("Hello");await Promise.resolve();});@@ -200,17 +203,20 @@ describe("useEveAgent", () => {});expect(fetchMock).toHaveBeenCalledTimes(2);+ expect(lifecycle[0]).toBe("session:0");expect(seenEvents).toEqual(stampTestEvents(events));expect(seenSessions).toEqual([{- continuationToken: "http:session_1",+ sessionId: "session_1",+ streamIndex: 0,+ },+ {sessionId: "session_1",streamIndex: 3,},]);expect(helpers?.status).toBe("ready");expect(helpers?.session).toEqual({- continuationToken: "http:session_1",sessionId: "session_1",streamIndex: 3,});@@ -228,9 +234,7 @@ describe("useEveAgent", () => {const fetchMock = vi.spyOn(globalThis, "fetch").mockReturnValueOnce(startResponse.promise)- .mockResolvedValueOnce(- createEagerStreamResponse([createSessionWaitingEvent("eve:http:session_1")]),- );+ .mockResolvedValueOnce(createEagerStreamResponse([createSessionWaitingEvent()]));let randomWord = "jazz";let helpers: UseEveAgentHelpers<EveMessageData> | undefined;@@ -255,7 +259,7 @@ describe("useEveAgent", () => {let sendPromise: Promise<void> | undefined;await act(async () => {- sendPromise = helpers?.send({ message: "What word is currently selected?" });+ sendPromise = helpers?.send("What word is currently selected?");await Promise.resolve();});@@ -283,9 +287,7 @@ describe("useEveAgent", () => {const fetchMock = vi.spyOn(globalThis, "fetch").mockReturnValueOnce(startResponse.promise)- .mockResolvedValueOnce(- createEagerStreamResponse([createSessionWaitingEvent("eve:http:session_1")]),- );+ .mockResolvedValueOnce(createEagerStreamResponse([createSessionWaitingEvent()]));let helpers: UseEveAgentHelpers<EveMessageData> | undefined;@@ -302,7 +304,7 @@ describe("useEveAgent", () => {let sendPromise: Promise<void> | undefined;await act(async () => {- sendPromise = helpers?.send({ message: "Hello" });+ sendPromise = helpers?.send("Hello");await Promise.resolve();});@@ -337,7 +339,7 @@ describe("useEveAgent", () => {});await act(async () => {- await helpers?.send({ message: "Hello" });+ await helpers?.send("Hello");});expect(seenErrors.map((error) => error.message)).toEqual(["Network failed"]);@@ -361,7 +363,7 @@ describe("useEveAgent", () => {stepIndex: 0,turnId: "turn_2",}),- createSessionWaitingEvent("eve:http:session_1"),+ createSessionWaitingEvent(),];vi.spyOn(globalThis, "fetch")@@ -387,7 +389,7 @@ describe("useEveAgent", () => {let firstSendPromise: Promise<void> | undefined;await act(async () => {- firstSendPromise = helpers?.send({ message: "First" });+ firstSendPromise = helpers?.send("First");await Promise.resolve();});@@ -400,7 +402,7 @@ describe("useEveAgent", () => {let secondSendPromise: Promise<void> | undefined;await act(async () => {- secondSendPromise = helpers?.send({ message: "Second" });+ secondSendPromise = helpers?.send("Second");await Promise.resolve();});@@ -469,7 +471,7 @@ describe("useEveAgent", () => {let sendPromise: Promise<void> | undefined;await act(async () => {- sendPromise = helpers?.send({ message: "Hello" });+ sendPromise = helpers?.send("Hello");await Promise.resolve();});@@ -511,7 +513,7 @@ describe("useEveAgent", () => {sequence: 0,turnId: "turn_1",}),- createSessionWaitingEvent("eve:http:session_1"),+ createSessionWaitingEvent(),];const startResponse = createDeferred<Response>();@@ -537,7 +539,7 @@ describe("useEveAgent", () => {let sendPromise: Promise<void> | undefined;await act(async () => {- sendPromise = helpers?.send({ message: "Hello" });+ sendPromise = helpers?.send("Hello");await Promise.resolve();});@@ -556,16 +558,13 @@ describe("useEveAgent", () => {const startResponse = createDeferred<Response>();vi.spyOn(globalThis, "fetch").mockReturnValueOnce(startResponse.promise)- .mockResolvedValueOnce(- createEagerStreamResponse([createSessionWaitingEvent("eve:http:session_1")]),- );+ .mockResolvedValueOnce(createEagerStreamResponse([createSessionWaitingEvent()]));let helpers: UseEveAgentHelpers<readonly string[]> | undefined;function TestComponent() {helpers = useEveAgent<readonly string[]>({initialSession: {- continuationToken: "http:session_1",sessionId: "session_1",streamIndex: 0,},@@ -587,9 +586,7 @@ describe("useEveAgent", () => {let sendPromise: Promise<void> | undefined;await act(async () => {- sendPromise = helpers?.send({- inputResponses: [{ optionId: "deny", requestId: "approval_1" }],- });+ sendPromise = helpers?.respond([{ optionId: "deny", requestId: "approval_1" }]);await Promise.resolve();});diff --git a/packages/eve/src/react/use-eve-agent.ts b/packages/eve/src/react/use-eve-agent.tsindex 7e9bdc029..bc0f7b092 100644--- a/packages/eve/src/react/use-eve-agent.ts+++ b/packages/eve/src/react/use-eve-agent.ts@@ -12,7 +12,14 @@ import type { EveAgentReducer } from "#client/reducer.js";import type { ClientSession } from "#client/session.js";import { defaultMessageReducer, type EveMessageData } from "#client/message-reducer.js";import type { MessageStreamEvent } from "#protocol/message.js";-import type { ClientAuth, HeadersValue, SendTurnPayload, SessionState } from "#client/types.js";+import type { UserContent } from "ai";+import type {+ ClientAuth,+ HeadersValue,+ RespondTurnOptions,+ SendTurnOptions,+ ClientSessionState,+} from "#client/types.js";export type { PrepareSend };@@ -39,8 +46,16 @@ export type UseEveAgentSnapshot<TData> = EveAgentStoreSnapshot<TData>;export interface UseEveAgentHelpers<TData> extends UseEveAgentSnapshot<TData> {/** Resets the session: aborts any in-flight turn, recreates the owned session, and clears events and projected data. */readonly reset: () => void;- /** Sends a turn (message, HITL responses, and/or client context). Rejects if a turn is already in flight. */- readonly send: <TOutput = unknown>(input: SendTurnPayload<TOutput>) => Promise<void>;+ /** Sends a message. Rejects if a turn is already in flight. */+ readonly send: <TOutput = unknown>(+ message: string | UserContent,+ options?: SendTurnOptions<TOutput>,+ ) => Promise<void>;+ /** Answers pending HITL input requests. Rejects if a turn is already in flight. */+ readonly respond: <TOutput = unknown>(+ inputResponses: Parameters<ClientSession["respond"]>[0],+ options?: RespondTurnOptions<TOutput>,+ ) => Promise<void>;/** Aborts the in-flight turn's stream, if any. */readonly stop: () => void;}@@ -77,7 +92,7 @@ export interface UseEveAgentOptions<TData> extends EveAgentStoreCallbacks<TData>readonly host?: string;/** Ordered prefix of the session stream used to rehydrate projected state. */readonly initialEvents?: readonly MessageStreamEvent[];- readonly initialSession?: SessionState;+ readonly initialSession?: ClientSessionState;/*** Project submitted user messages before eve confirms them with a* `message.received` stream event.@@ -104,7 +119,7 @@ export function useEveAgent<TData>(* React hook that drives an eve session and projects its event stream into UI data.** Returns the current snapshot (`data`, `events`, `session`, `status`, `error`)- * plus the commands `send`, `stop`, and `reset`. With no reducer, `data` is the+ * plus the commands `send`, `respond`, `stop`, and `reset`. With no reducer, `data` is the* built-in `UIMessage` projection from {@link defaultMessageReducer} (`TData`* is {@link EveMessageData}); pass a reducer to project into your own shape and* infer `TData`.@@ -155,20 +170,28 @@ export function useEveAgent<TData>(const reset = useCallback(() => store.reset(), [store]);const send = useCallback(- <TOutput = unknown>(input: SendTurnPayload<TOutput>) => {- return store.send(input);+ <TOutput = unknown>(message: string | UserContent, options?: SendTurnOptions<TOutput>) => {+ return store.send({ ...options, message });},[store],);+ const respond = useCallback(+ <TOutput = unknown>(+ inputResponses: Parameters<ClientSession["respond"]>[0],+ options?: RespondTurnOptions<TOutput>,+ ) => store.send({ ...options, inputResponses }),+ [store],+ );const stop = useCallback(() => store.stop(), [store]);return useMemo(() => ({...snapshot,reset,+ respond,send,stop,}),- [reset, send, snapshot, stop],+ [reset, respond, send, snapshot, stop],);}diff --git a/packages/eve/src/runtime/connections/callback-route.test.ts b/packages/eve/src/runtime/connections/callback-route.test.tsindex 221076b11..81c237291 100644--- a/packages/eve/src/runtime/connections/callback-route.test.ts+++ b/packages/eve/src/runtime/connections/callback-route.test.ts@@ -20,7 +20,6 @@ vi.mock("#compiled/@workflow/core/runtime.js", () => ({function buildRouteContext(params: Readonly<Record<string, string>>): RouteContext {return {- agent: {} as RouteContext["agent"],waitUntil: () => {},params,requestIp: null,diff --git a/packages/eve/src/runtime/session-callback-route.test.ts b/packages/eve/src/runtime/session-callback-route.test.tsindex 62aaa7444..bcf8b5e28 100644--- a/packages/eve/src/runtime/session-callback-route.test.ts+++ b/packages/eve/src/runtime/session-callback-route.test.ts@@ -393,20 +393,6 @@ describe("session callback route", () => {function createRouteContext(params: Record<string, string>): RouteContext {return {- agent: {- async cancelTurn() {- throw new Error("unexpected cancelTurn");- },- async deliver() {- throw new Error("unexpected deliver");- },- async getEventStream() {- throw new Error("unexpected getEventStream");- },- async run() {- throw new Error("unexpected run");- },- },params,requestIp: null,waitUntil() {},diff --git a/packages/eve/src/runtime/subagents/dynamic-remote-agent-config.ts b/packages/eve/src/runtime/subagents/dynamic-remote-agent-config.tsindex a662fcf45..a36243ac6 100644--- a/packages/eve/src/runtime/subagents/dynamic-remote-agent-config.ts+++ b/packages/eve/src/runtime/subagents/dynamic-remote-agent-config.ts@@ -7,7 +7,7 @@ import {getOptionalStringRecordProperty,} from "#internal/authored-module.js";import type { OutboundAuthFn } from "#public/agents/auth.js";-import { EVE_CREATE_SESSION_ROUTE_PATH } from "#protocol/routes.js";+import { EVE_SESSION_ROUTE_PATH } from "#protocol/routes.js";import type { JsonObject } from "#shared/json.js";import { serializeOutputSchema, type ToolSchemaSource } from "#shared/tool-schema.js";@@ -56,10 +56,7 @@ export async function normalizeDynamicRemoteAgentConfig(input: {url: string;} = {description: expectString(record.description, message),- path:- record.path === undefined- ? EVE_CREATE_SESSION_ROUTE_PATH- : expectString(record.path, message),+ path: record.path === undefined ? EVE_SESSION_ROUTE_PATH : expectString(record.path, message),url,};diff --git a/packages/eve/src/runtime/types.ts b/packages/eve/src/runtime/types.tsindex 773c978c9..ef98aadd8 100644--- a/packages/eve/src/runtime/types.ts+++ b/packages/eve/src/runtime/types.ts@@ -232,7 +232,7 @@ export interface ResolvedChannelDefinition extends ResolvedModuleSourceRef {/*** Universal entry point for new sessions, called by cross-channel* initiators (the schedule dispatcher today). Typed precisely as- * {@link CompiledChannel.receive} — `(input, { send }) => Session` —+ * {@link CompiledChannel.receive} — `(input, ctx) => Session` —* so any caller passing the wrong context shape is a typecheck error,* not a runtime crash.*@@ -244,7 +244,7 @@ export interface ResolvedChannelDefinition extends ResolvedModuleSourceRef {readonly receive?: CompiledChannel["receive"];/*** Reference to the authored {@link CompiledChannel} value the channel- * module exported. Preserved so callers of `args.receive(channel, …)`+ * module exported. Preserved so callers of `ctx.to(channel, target)`* can identify a target by the same imported reference. `undefined`* for framework-internal channels constructed without going through* `defineChannel`.diff --git a/packages/eve/src/services/dev-client.test.ts b/packages/eve/src/services/dev-client.test.tsindex 0c45c3d30..dd7ef787f 100644--- a/packages/eve/src/services/dev-client.test.ts+++ b/packages/eve/src/services/dev-client.test.ts@@ -21,17 +21,17 @@ describe("runtime-artifact refresher session continuity", () => {const refresher = createDevelopmentRuntimeArtifactRefresher({serverUrl: "http://127.0.0.1:3000",});- const session = client.session();+ const session = client.sessions.attach("session_test");await refresher.refresh({message: "first",});- await (await session.send({ message: "first" })).result();+ await (await session.send("first")).result();const sessionId = session.state.sessionId;await refresher.refresh({message: "second",});- await (await session.send({ message: "second" })).result();+ await (await session.send("second")).result();expect(session.state.sessionId).toBe(sessionId);const postUrls = requests@@ -40,7 +40,7 @@ describe("runtime-artifact refresher session continuity", () => {return request.method === "POST" && !pathname.startsWith("/eve/v1/dev/runtime-artifacts");}).map((request) => new URL(request.url).pathname);- expect(postUrls).toEqual(["/eve/v1/session", "/eve/v1/session/session-1"]);+ expect(postUrls).toEqual(["/eve/v1/session/session_test", "/eve/v1/session/session_test"]);});it("keeps the active session eligible when a candidate rebuild fails", async () => {@@ -55,14 +55,14 @@ describe("runtime-artifact refresher session continuity", () => {const refresher = createDevelopmentRuntimeArtifactRefresher({serverUrl: "http://127.0.0.1:3000",});- const session = client.session();+ const session = client.sessions.attach("session_test");await refresher.refresh({ message: "first" });- await (await session.send({ message: "first" })).result();+ await (await session.send("first")).result();const sessionId = session.state.sessionId;await refresher.refresh({ message: "second" });- await (await session.send({ message: "second" })).result();+ await (await session.send("second")).result();expect(session.state.sessionId).toBe(sessionId);const postUrls = requests@@ -71,7 +71,7 @@ describe("runtime-artifact refresher session continuity", () => {return request.method === "POST" && !pathname.startsWith("/eve/v1/dev/runtime-artifacts");}).map((request) => new URL(request.url).pathname);- expect(postUrls).toEqual(["/eve/v1/session", "/eve/v1/session/session-1"]);+ expect(postUrls).toEqual(["/eve/v1/session/session_test", "/eve/v1/session/session_test"]);});it("keeps the active local session for input-response resumes after the dev artifact revision changes", async () => {@@ -86,17 +86,17 @@ describe("runtime-artifact refresher session continuity", () => {serverUrl: "http://localhost:3000",});const inputResponses = [{ optionId: "approve", requestId: "request-1" }];- const session = client.session();+ const session = client.sessions.attach("session_test");await refresher.refresh({message: "approve a tool",});- await (await session.send({ message: "approve a tool" })).result();+ await (await session.send("approve a tool")).result();const sessionId = session.state.sessionId;await refresher.refresh({inputResponses,});- await (await session.send({ inputResponses })).result();+ await (await session.respond(inputResponses)).result();expect(session.state.sessionId).toBe(sessionId);@@ -110,7 +110,7 @@ describe("runtime-artifact refresher session continuity", () => {}).map((request) => new URL(request.url).pathname);expect(rebuilds).toHaveLength(1);- expect(postUrls).toEqual(["/eve/v1/session", "/eve/v1/session/session-1"]);+ expect(postUrls).toEqual(["/eve/v1/session/session_test", "/eve/v1/session/session_test"]);});});@@ -126,10 +126,10 @@ describe("createDevelopmentRuntimeArtifactRefresher", () => {const refresher = createDevelopmentRuntimeArtifactRefresher({serverUrl: "http://localhost:3000",});- const session = client.session();+ const session = client.sessions.attach("session_test");await refresher.refreshIdle({});- await (await session.send({ message: "first" })).result();+ await (await session.send("first")).result();const sessionId = session.state.sessionId;await refresher.refreshAfterSourceChange({});@@ -157,9 +157,9 @@ describe("createDevelopmentRuntimeArtifactRefresher", () => {const refresher = createDevelopmentRuntimeArtifactRefresher({serverUrl: "http://localhost:3000",});- const session = client.session();+ const session = client.sessions.attach("session_test");- await (await session.send({ message: "first" })).result();+ await (await session.send("first")).result();const sessionId = session.state.sessionId;await refresher.refreshAfterSourceChange({});@@ -287,11 +287,8 @@ function createDevFetchMock(input: {const sessionId =pathname === "/eve/v1/session"? `session-${String(++nextSessionIndex)}`- : (pathname.split("/").at(-1) ?? `session-${String(++nextSessionIndex)}`);- return Response.json({- continuationToken: `token-${sessionId}`,- sessionId,- });+ : (pathname.split("/")[4] ?? `session-${String(++nextSessionIndex)}`);+ return Response.json({ sessionId });}return new Response(@@ -300,10 +297,7 @@ function createDevFetchMock(input: {controller.enqueue(encoder.encode(`${JSON.stringify({- data: {- continuationToken: `token-${nextSessionIndex}`,- wait: "next-user-message",- },+ data: { continuationToken: "session-id", wait: "next-user-message" },type: "session.waiting",})}\n`,),diff --git a/packages/eve/src/services/dev-client/client-options.test.ts b/packages/eve/src/services/dev-client/client-options.test.tsindex 5d045b714..30e2945bb 100644--- a/packages/eve/src/services/dev-client/client-options.test.ts+++ b/packages/eve/src/services/dev-client/client-options.test.ts@@ -26,12 +26,6 @@ describe("resolveDevelopmentClientOptions", () => {expect(remote.headers).toBeUndefined();});- it("does not preserve completed sessions across dev prompts", () => {- expect(resolveDevelopmentClientOptions("http://localhost:3000").preserveCompletedSessions).toBe(- undefined,- );- });-it("skips the OIDC bearer for local hosts", () => {for (const url of ["http://localhost:3000", "http://127.0.0.1:3000", "http://[::1]:3000"]) {expect(isLocalDevelopmentServerUrl(url)).toBe(true);diff --git a/packages/eve/src/services/inspect-application.ts b/packages/eve/src/services/inspect-application.tsindex 8dc3d84b3..f2fda8f72 100644--- a/packages/eve/src/services/inspect-application.ts+++ b/packages/eve/src/services/inspect-application.ts@@ -6,9 +6,9 @@ import {import { DiscoveryProjectResolutionError } from "#discover/project.js";import { type ApplicationInfo, getApplicationInfo } from "#internal/application/paths.js";import {- EVE_CREATE_SESSION_ROUTE_PATH,- EVE_CONTINUE_SESSION_ROUTE_PATTERN,- EVE_MESSAGE_STREAM_ROUTE_PATTERN,+ EVE_SESSION_ROUTE_PATH,+ EVE_SESSION_ROUTE_PATTERN,+ EVE_SESSION_STREAM_ROUTE_PATTERN,} from "#protocol/routes.js";/**@@ -16,7 +16,7 @@ import {*/export interface ApplicationInspectionMessaging {readonly createSessionRoutePath: string;- readonly continueSessionRoutePattern: string;+ readonly sessionMessagesRoutePattern: string;readonly streamRoutePattern: string;}@@ -41,9 +41,9 @@ export async function inspectApplication(appRoot: string): Promise<ApplicationInapplication,compiledState,messaging: {- createSessionRoutePath: EVE_CREATE_SESSION_ROUTE_PATH,- continueSessionRoutePattern: EVE_CONTINUE_SESSION_ROUTE_PATTERN,- streamRoutePattern: EVE_MESSAGE_STREAM_ROUTE_PATTERN,+ createSessionRoutePath: EVE_SESSION_ROUTE_PATH,+ sessionMessagesRoutePattern: EVE_SESSION_ROUTE_PATTERN,+ streamRoutePattern: EVE_SESSION_STREAM_ROUTE_PATTERN,},};}diff --git a/packages/eve/src/setup/channel-add-conflicts.ts b/packages/eve/src/setup/channel-add-conflicts.tsindex 0b7d79d72..da79c0dbe 100644--- a/packages/eve/src/setup/channel-add-conflicts.ts+++ b/packages/eve/src/setup/channel-add-conflicts.ts@@ -5,7 +5,7 @@ import type { DisabledChannelReasons } from "#setup/cli/index.js";import { compileChannelDefinition } from "#compiler/normalize-channel.js";import { discoverAgent } from "#discover/discover-agent.js";-import { EVE_CREATE_SESSION_ROUTE_PATH } from "#protocol/routes.js";+import { EVE_SESSION_ROUTE_PATH } from "#protocol/routes.js";const SCAFFOLDED_WEB_CHANNEL_LOGICAL_PATH = "channels/eve.ts";const SCAFFOLDED_SLACK_CHANNEL_LOGICAL_PATH = "channels/slack.ts";@@ -49,7 +49,7 @@ export async function inspectExistingChannelRegistrations(if (definition.kind !== "channel") {continue;}- if (definition.method === "POST" && definition.urlPath === EVE_CREATE_SESSION_ROUTE_PATH) {+ if (definition.method === "POST" && definition.urlPath === EVE_SESSION_ROUTE_PATH) {webRouteOwners.add(source.logicalPath);}if (definition.adapterKind === "slack") {@@ -62,7 +62,7 @@ export async function inspectExistingChannelRegistrations(if ([...webRouteOwners].some((logicalPath) => logicalPath !== SCAFFOLDED_WEB_CHANNEL_LOGICAL_PATH)) {- disabledChannelReasons.web = `POST ${EVE_CREATE_SESSION_ROUTE_PATH} already registered`;+ disabledChannelReasons.web = `POST ${EVE_SESSION_ROUTE_PATH} already registered`;}if (slackOwners.size > 0) {disabledChannelReasons.slack = "Slack channel already registered";@@ -90,7 +90,7 @@ export function assertCanAddSelectedChannels();if (conflictingOwner !== undefined) {throw new Error(- `Cannot scaffold Web Chat because agent/${conflictingOwner} already defines POST ${EVE_CREATE_SESSION_ROUTE_PATH}. Web Chat scaffolds the same eve session routes.`,+ `Cannot scaffold Web Chat because agent/${conflictingOwner} already defines POST ${EVE_SESSION_ROUTE_PATH}. Web Chat scaffolds the same eve session routes.`,);}}diff --git a/packages/eve/src/setup/scaffold/create/web-template.ts b/packages/eve/src/setup/scaffold/create/web-template.tsindex f70d6721d..7835c7e22 100644--- a/packages/eve/src/setup/scaffold/create/web-template.ts+++ b/packages/eve/src/setup/scaffold/create/web-template.ts@@ -5,7 +5,7 @@ export const WEB_APP_TEMPLATE_FILES = {"agent/channels/eve.ts":'import { eveChannel } from "eve/channels/eve";\nimport { localDev, placeholderAuth, vercelOidc } from "eve/channels/auth";\n\nexport default eveChannel({\n auth: [\n // Lets the eve TUI and your Vercel deployments reach the deployed agent.\n vercelOidc(),\n // Open on localhost for `eve dev` and the REPL; ignored in production.\n localDev(),\n // This placeholder will not allow browser requests in production.\n // Replace it with your app\'s auth provider, like Auth.js or Clerk,\n // or use none() for a public demo.\n placeholderAuth(),\n ],\n});\n',"app/_components/agent-chat.tsx":- '"use client";\n\nimport type { UserContent } from "ai";\nimport { Client, type MessageStreamEvent } from "eve/client";\nimport { useEveAgent } from "eve/react";\nimport { AlertCircleIcon } from "lucide-react";\nimport { useCallback, useRef, useState } from "react";\nimport {\n Conversation,\n ConversationContent,\n ConversationScrollButton,\n} from "@/components/ai-elements/conversation";\nimport {\n PromptInput,\n type PromptInputMessage,\n PromptInputSubmit,\n PromptInputTextarea,\n} from "@/components/ai-elements/prompt-input";\nimport { cn } from "@/lib/utils";\nimport { AgentMessage } from "./agent-message";\n\nconst AGENT_NAME = "__EVE_INIT_APP_NAME__";\n\ntype AgentStatus = ReturnType<typeof useEveAgent>["status"];\ntype CancellationState = "idle" | "requested" | "cancelling";\n\ntype Cancellation = {\n requested: boolean;\n sentTurnId?: string;\n turnId?: string;\n};\n\nexport function AgentChat() {\n const [session] = useState(() =>\n new Client({ host: "", preserveCompletedSessions: true }).session(),\n );\n const cancellationRef = useRef<Cancellation>({ requested: false });\n const [cancellationError, setCancellationError] = useState<string>();\n const [cancellationState, setCancellationState] = useState<CancellationState>("idle");\n\n const cancelTurn = useCallback(\n (turnId: string) => {\n const cancellation = cancellationRef.current;\n if (!cancellation.requested || cancellation.sentTurnId === turnId) {\n return;\n }\n\n cancellation.sentTurnId = turnId;\n setCancellationState("cancelling");\n\n void session.cancel({ turnId }).catch((error: unknown) => {\n if (cancellationRef.current !== cancellation) {\n return;\n }\n\n cancellation.requested = false;\n cancellation.sentTurnId = undefined;\n setCancellationError(toErrorMessage(error));\n setCancellationState("idle");\n });\n },\n [session],\n );\n\n const handleEvent = useCallback(\n (event: MessageStreamEvent) => {\n if (event.type !== "turn.started") {\n return;\n }\n\n const cancellation = cancellationRef.current;\n cancellation.turnId = event.data.turnId;\n cancelTurn(event.data.turnId);\n },\n [cancelTurn],\n );\n\n const agent = useEveAgent({ onEvent: handleEvent, session });\n const isBusy = agent.status === "submitted" || agent.status === "streaming";\n const isEmpty = agent.data.messages.length === 0;\n const errorMessage = cancellationError ?? agent.error?.message;\n const submitStatus = isBusy && cancellationState !== "idle" ? "submitted" : agent.status;\n\n const prepareTurn = () => {\n cancellationRef.current = { requested: false };\n setCancellationError(undefined);\n setCancellationState("idle");\n };\n\n const requestCancellation = () => {\n if (!isBusy || cancellationState !== "idle") {\n return;\n }\n\n const cancellation = cancellationRef.current;\n cancellation.requested = true;\n setCancellationError(undefined);\n setCancellationState("requested");\n\n if (cancellation.turnId !== undefined) {\n cancelTurn(cancellation.turnId);\n }\n };\n\n const handleSubmit = async (message: PromptInputMessage) => {\n const text = message.text.trim();\n if ((text.length === 0 && message.files.length === 0) || isBusy) return;\n\n prepareTurn();\n\n if (message.files.length === 0) {\n await agent.send({ message: text });\n return;\n }\n\n const parts: UserContent = [];\n if (text.length > 0) {\n parts.push({ text, type: "text" });\n }\n for (const file of message.files) {\n parts.push({\n data: file.url,\n filename: file.filename,\n mediaType: file.mediaType,\n type: "file",\n });\n }\n\n await agent.send({ message: parts });\n };\n\n const composer = (\n <PromptInput onSubmit={handleSubmit}>\n <PromptInputTextarea placeholder="Send a message…" />\n <PromptInputSubmit onStop={requestCancellation} status={submitStatus} />\n </PromptInput>\n );\n\n return (\n <main className="flex h-dvh flex-col overflow-hidden bg-background text-foreground">\n {isEmpty ? null : (\n <header className="flex h-14 shrink-0 items-center justify-center gap-3 pl-4 pr-2">\n <span className="flex min-w-0 items-center gap-2">\n <span className="truncate text-muted-foreground text-sm">{AGENT_NAME}</span>\n <StatusDot status={agent.status} />\n </span>\n </header>\n )}\n\n {errorMessage ? (\n <div className="mx-auto w-full max-w-3xl shrink-0 px-4 pt-2 sm:px-6">\n <div className="flex items-start gap-3 rounded-lg border border-destructive/30 bg-destructive/5 px-3 py-2.5 text-sm">\n <AlertCircleIcon className="mt-0.5 size-4 shrink-0 text-destructive" />\n <div>\n <p className="font-medium">Request failed</p>\n <p className="mt-0.5 text-muted-foreground">{errorMessage}</p>\n </div>\n </div>\n </div>\n ) : null}\n\n {isEmpty ? null : (\n <Conversation className="min-h-0 flex-1">\n <ConversationContent className="mx-auto w-full max-w-3xl gap-6 px-4 py-6 sm:px-6">\n {agent.data.messages.map((message, index) => (\n <AgentMessage\n canRespond={!isBusy}\n isStreaming={\n agent.status === "streaming" && index === agent.data.messages.length - 1\n }\n key={message.id}\n message={message}\n onInputResponses={(inputResponses) => {\n prepareTurn();\n return agent.send({ inputResponses });\n }}\n />\n ))}\n </ConversationContent>\n <ConversationScrollButton />\n </Conversation>\n )}\n\n <div\n className={cn(\n "mx-auto w-full px-4 sm:px-6",\n isEmpty\n ? "flex max-w-xl flex-1 flex-col items-center justify-center gap-8 pb-[10vh]"\n : "max-w-3xl shrink-0 pb-6",\n )}\n >\n {isEmpty ? (\n <div className="flex flex-col items-center gap-3 text-center">\n <h1 className="font-medium text-5xl tracking-tighter">{AGENT_NAME}</h1>\n </div>\n ) : null}\n <div className="w-full">{composer}</div>\n </div>\n </main>\n );\n}\n\nfunction toErrorMessage(error: unknown): string {\n return error instanceof Error ? error.message : "Unable to cancel the response.";\n}\n\nfunction StatusDot({ status }: { readonly status: AgentStatus }) {\n const isLive = status === "submitted" || status === "streaming";\n const tone =\n status === "error"\n ? "bg-destructive"\n : isLive\n ? "bg-emerald-500"\n : status === "ready"\n ? "bg-muted-foreground"\n : "bg-muted-foreground/50";\n\n return (\n <span className="relative flex size-1">\n {isLive ? (\n <span\n className={cn(\n "absolute inline-flex size-full animate-ping rounded-full opacity-75",\n tone,\n )}\n />\n ) : null}\n <span className={cn("relative inline-flex size-1 rounded-full transition-colors", tone)} />\n </span>\n );\n}\n',+ '"use client";\n\nimport type { UserContent } from "ai";\nimport { Client, type MessageStreamEvent } from "eve/client";\nimport { useEveAgent } from "eve/react";\nimport { AlertCircleIcon } from "lucide-react";\nimport { useCallback, useRef, useState } from "react";\nimport {\n Conversation,\n ConversationContent,\n ConversationScrollButton,\n} from "@/components/ai-elements/conversation";\nimport {\n PromptInput,\n type PromptInputMessage,\n PromptInputSubmit,\n PromptInputTextarea,\n} from "@/components/ai-elements/prompt-input";\nimport { cn } from "@/lib/utils";\nimport { AgentMessage } from "./agent-message";\n\nconst AGENT_NAME = "__EVE_INIT_APP_NAME__";\n\ntype AgentStatus = ReturnType<typeof useEveAgent>["status"];\ntype CancellationState = "idle" | "requested" | "cancelling";\n\ntype Cancellation = {\n requested: boolean;\n sentTurnId?: string;\n turnId?: string;\n};\n\nexport function AgentChat() {\n const [client] = useState(() => new Client({ host: "" }));\n const sessionIdRef = useRef<string | undefined>(undefined);\n const cancellationRef = useRef<Cancellation>({ requested: false });\n const [cancellationError, setCancellationError] = useState<string>();\n const [cancellationState, setCancellationState] = useState<CancellationState>("idle");\n\n const cancelTurn = useCallback(\n (turnId: string) => {\n const cancellation = cancellationRef.current;\n if (!cancellation.requested || cancellation.sentTurnId === turnId) {\n return;\n }\n\n cancellation.sentTurnId = turnId;\n setCancellationState("cancelling");\n\n const sessionId = sessionIdRef.current;\n if (sessionId === undefined) {\n return;\n }\n\n void client.sessions\n .attach(sessionId)\n .cancel({ turnId })\n .catch((error: unknown) => {\n if (cancellationRef.current !== cancellation) {\n return;\n }\n\n cancellation.requested = false;\n cancellation.sentTurnId = undefined;\n setCancellationError(toErrorMessage(error));\n setCancellationState("idle");\n });\n },\n [client],\n );\n\n const handleEvent = useCallback(\n (event: MessageStreamEvent) => {\n if (event.type !== "turn.started") {\n return;\n }\n\n const cancellation = cancellationRef.current;\n cancellation.turnId = event.data.turnId;\n cancelTurn(event.data.turnId);\n },\n [cancelTurn],\n );\n\n const agent = useEveAgent({\n onEvent: handleEvent,\n onSessionChange(session) {\n sessionIdRef.current = session?.sessionId;\n },\n });\n const isBusy = agent.status === "submitted" || agent.status === "streaming";\n const isEmpty = agent.data.messages.length === 0;\n const errorMessage = cancellationError ?? agent.error?.message;\n const submitStatus = isBusy && cancellationState !== "idle" ? "submitted" : agent.status;\n\n const prepareTurn = () => {\n cancellationRef.current = { requested: false };\n setCancellationError(undefined);\n setCancellationState("idle");\n };\n\n const requestCancellation = () => {\n if (!isBusy || cancellationState !== "idle") {\n return;\n }\n\n const cancellation = cancellationRef.current;\n cancellation.requested = true;\n setCancellationError(undefined);\n setCancellationState("requested");\n\n if (cancellation.turnId !== undefined) {\n cancelTurn(cancellation.turnId);\n }\n };\n\n const handleSubmit = async (message: PromptInputMessage) => {\n const text = message.text.trim();\n if ((text.length === 0 && message.files.length === 0) || isBusy) return;\n\n prepareTurn();\n\n if (message.files.length === 0) {\n await agent.send(text);\n return;\n }\n\n const parts: UserContent = [];\n if (text.length > 0) {\n parts.push({ text, type: "text" });\n }\n for (const file of message.files) {\n parts.push({\n data: file.url,\n filename: file.filename,\n mediaType: file.mediaType,\n type: "file",\n });\n }\n\n await agent.send(parts);\n };\n\n const composer = (\n <PromptInput onSubmit={handleSubmit}>\n <PromptInputTextarea placeholder="Send a message…" />\n <PromptInputSubmit onStop={requestCancellation} status={submitStatus} />\n </PromptInput>\n );\n\n return (\n <main className="flex h-dvh flex-col overflow-hidden bg-background text-foreground">\n {isEmpty ? null : (\n <header className="flex h-14 shrink-0 items-center justify-center gap-3 pl-4 pr-2">\n <span className="flex min-w-0 items-center gap-2">\n <span className="truncate text-muted-foreground text-sm">{AGENT_NAME}</span>\n <StatusDot status={agent.status} />\n </span>\n </header>\n )}\n\n {errorMessage ? (\n <div className="mx-auto w-full max-w-3xl shrink-0 px-4 pt-2 sm:px-6">\n <div className="flex items-start gap-3 rounded-lg border border-destructive/30 bg-destructive/5 px-3 py-2.5 text-sm">\n <AlertCircleIcon className="mt-0.5 size-4 shrink-0 text-destructive" />\n <div>\n <p className="font-medium">Request failed</p>\n <p className="mt-0.5 text-muted-foreground">{errorMessage}</p>\n </div>\n </div>\n </div>\n ) : null}\n\n {isEmpty ? null : (\n <Conversation className="min-h-0 flex-1">\n <ConversationContent className="mx-auto w-full max-w-3xl gap-6 px-4 py-6 sm:px-6">\n {agent.data.messages.map((message, index) => (\n <AgentMessage\n canRespond={!isBusy}\n isStreaming={\n agent.status === "streaming" && index === agent.data.messages.length - 1\n }\n key={message.id}\n message={message}\n onInputResponses={(inputResponses) => {\n prepareTurn();\n return agent.respond(inputResponses);\n }}\n />\n ))}\n </ConversationContent>\n <ConversationScrollButton />\n </Conversation>\n )}\n\n <div\n className={cn(\n "mx-auto w-full px-4 sm:px-6",\n isEmpty\n ? "flex max-w-xl flex-1 flex-col items-center justify-center gap-8 pb-[10vh]"\n : "max-w-3xl shrink-0 pb-6",\n )}\n >\n {isEmpty ? (\n <div className="flex flex-col items-center gap-3 text-center">\n <h1 className="font-medium text-5xl tracking-tighter">{AGENT_NAME}</h1>\n </div>\n ) : null}\n <div className="w-full">{composer}</div>\n </div>\n </main>\n );\n}\n\nfunction toErrorMessage(error: unknown): string {\n return error instanceof Error ? error.message : "Unable to cancel the response.";\n}\n\nfunction StatusDot({ status }: { readonly status: AgentStatus }) {\n const isLive = status === "submitted" || status === "streaming";\n const tone =\n status === "error"\n ? "bg-destructive"\n : isLive\n ? "bg-emerald-500"\n : status === "ready"\n ? "bg-muted-foreground"\n : "bg-muted-foreground/50";\n\n return (\n <span className="relative flex size-1">\n {isLive ? (\n <span\n className={cn(\n "absolute inline-flex size-full animate-ping rounded-full opacity-75",\n tone,\n )}\n />\n ) : null}\n <span className={cn("relative inline-flex size-1 rounded-full transition-colors", tone)} />\n </span>\n );\n}\n',"app/_components/agent-message.tsx":'"use client";\n\nimport type {\n EveAuthorizationPart,\n EveDynamicToolPart,\n EveMessage,\n EveMessagePart,\n} from "eve/react";\nimport {\n CheckCircleIcon,\n ExternalLinkIcon,\n FileIcon,\n ImageIcon,\n KeyRoundIcon,\n XCircleIcon,\n} from "lucide-react";\nimport { Message, MessageContent, MessageResponse } from "@/components/ai-elements/message";\nimport { Reasoning, ReasoningContent, ReasoningTrigger } from "@/components/ai-elements/reasoning";\nimport {\n Tool,\n ToolContent,\n ToolHeader,\n ToolInput,\n ToolOutput,\n} from "@/components/ai-elements/tool";\nimport { Button } from "@/components/ui/button";\nimport { cn } from "@/lib/utils";\n\nexport type AgentInputResponse = {\n readonly optionId?: string;\n readonly requestId: string;\n readonly text?: string;\n};\n\ntype EveFilePart = Extract<EveMessagePart, { type: "file" }>;\n\nexport function AgentMessage({\n canRespond,\n isStreaming,\n message,\n onInputResponses,\n}: {\n readonly canRespond: boolean;\n readonly isStreaming: boolean;\n readonly message: EveMessage;\n readonly onInputResponses: (responses: readonly AgentInputResponse[]) => void | Promise<void>;\n}) {\n const lastTextIndex = message.parts.reduce(\n (last, part, index) => (part.type === "text" ? index : last),\n -1,\n );\n\n return (\n <Message\n data-optimistic={message.metadata?.optimistic ? "true" : undefined}\n from={message.role}\n >\n <MessageContent>\n {message.parts.map((part, index) => (\n <AgentMessagePart\n canRespond={canRespond}\n key={partKey(part, index)}\n onInputResponses={onInputResponses}\n part={part}\n showCaret={isStreaming && message.role === "assistant" && index === lastTextIndex}\n />\n ))}\n </MessageContent>\n </Message>\n );\n}\n\nfunction AgentMessagePart({\n canRespond,\n onInputResponses,\n part,\n showCaret,\n}: {\n readonly canRespond: boolean;\n readonly onInputResponses: (responses: readonly AgentInputResponse[]) => void | Promise<void>;\n readonly part: EveMessagePart;\n readonly showCaret: boolean;\n}) {\n switch (part.type) {\n case "step-start":\n return null;\n case "text":\n return (\n <MessageResponse caret="block" isAnimating={showCaret}>\n {part.text}\n </MessageResponse>\n );\n case "reasoning":\n return (\n <Reasoning defaultOpen isStreaming={part.state === "streaming"}>\n <ReasoningTrigger />\n <ReasoningContent>{part.text}</ReasoningContent>\n </Reasoning>\n );\n case "file":\n return <AttachmentPart part={part} />;\n case "authorization":\n return <AuthorizationPrompt part={part} />;\n case "dynamic-tool":\n return (\n <Tool\n defaultOpen={part.state === "approval-requested" || part.state === "approval-responded"}\n >\n <ToolHeader\n state={part.state}\n title={part.toolName}\n toolName={part.toolName}\n type="dynamic-tool"\n />\n <ToolContent>\n <ToolInput input={part.input} />\n <InputRequestActions\n canRespond={canRespond}\n part={part}\n onInputResponses={onInputResponses}\n />\n <ToolOutput errorText={part.errorText} output={part.output} />\n </ToolContent>\n </Tool>\n );\n }\n}\n\nfunction AttachmentPart({ part }: { readonly part: EveFilePart }) {\n const label = part.filename ?? "Attachment";\n const detail = [part.mediaType, formatBytes(part.size)].filter(Boolean).join(" - ");\n const isImage = part.mediaType.startsWith("image/") && part.url !== undefined;\n const Icon = isImage ? ImageIcon : FileIcon;\n const body = (\n <span className="flex max-w-sm items-center gap-3 rounded-md border bg-background/60 p-2 text-sm">\n {isImage ? (\n <img alt={label} className="size-12 shrink-0 rounded-sm object-cover" src={part.url} />\n ) : (\n <span className="flex size-10 shrink-0 items-center justify-center rounded-sm bg-muted text-muted-foreground">\n <Icon className="size-4" />\n </span>\n )}\n <span className="min-w-0 flex-1">\n <span className="block truncate font-medium">{label}</span>\n {detail ? <span className="block truncate text-muted-foreground">{detail}</span> : null}\n </span>\n {part.url ? <ExternalLinkIcon className="size-4 shrink-0 text-muted-foreground" /> : null}\n </span>\n );\n\n return part.url ? (\n <a href={part.url} rel="noreferrer" target="_blank">\n {body}\n </a>\n ) : (\n body\n );\n}\n\nfunction AuthorizationPrompt({ part }: { readonly part: EveAuthorizationPart }) {\n const isAuthorized = part.state === "completed" && part.outcome === "authorized";\n const isCompleted = part.state === "completed";\n const Icon = isAuthorized ? CheckCircleIcon : isCompleted ? XCircleIcon : KeyRoundIcon;\n const instructions = part.authorization?.instructions;\n const shouldShowInstructions = instructions !== undefined && instructions !== part.description;\n\n return (\n <div\n className={cn(\n "space-y-3 rounded-md border p-3",\n isAuthorized\n ? "border-emerald-500/30 bg-emerald-500/5"\n : isCompleted\n ? "border-destructive/30 bg-destructive/5"\n : "border-blue-500/30 bg-blue-500/5",\n )}\n >\n <div className="flex items-start gap-3">\n <span\n className={cn(\n "mt-0.5 flex size-8 shrink-0 items-center justify-center rounded-full",\n isAuthorized\n ? "bg-emerald-500/10 text-emerald-700 dark:text-emerald-300"\n : isCompleted\n ? "bg-destructive/10 text-destructive"\n : "bg-blue-500/10 text-blue-700 dark:text-blue-300",\n )}\n >\n <Icon className="size-4" />\n </span>\n <div className="min-w-0 flex-1 space-y-2">\n <p className="font-medium text-sm">{authorizationTitle(part)}</p>\n <p className="text-muted-foreground text-sm">{authorizationDescription(part)}</p>\n {shouldShowInstructions ? (\n <p className="text-muted-foreground text-sm">{instructions}</p>\n ) : null}\n {part.state === "required" && part.authorization?.userCode ? (\n <div className="flex flex-wrap items-center gap-2 text-sm">\n <span className="text-muted-foreground">Code</span>\n <code className="rounded-md bg-background px-2 py-1 font-mono">\n {part.authorization.userCode}\n </code>\n </div>\n ) : null}\n {part.state === "required" && part.authorization?.url ? (\n <Button asChild size="sm">\n <a href={part.authorization.url} rel="noreferrer" target="_blank">\n <ExternalLinkIcon className="size-4" />\n Sign in with {part.displayName}\n </a>\n </Button>\n ) : null}\n </div>\n </div>\n </div>\n );\n}\n\nfunction authorizationTitle(part: EveAuthorizationPart): string {\n if (part.state === "required") {\n return `Connect ${part.displayName}`;\n }\n if (part.outcome === "authorized") {\n return `${part.displayName} connected`;\n }\n return `${part.displayName} authorization ${formatAuthorizationOutcome(part.outcome)}`;\n}\n\nfunction authorizationDescription(part: EveAuthorizationPart): string {\n if (part.state === "required") {\n return part.description;\n }\n if (part.outcome === "authorized") {\n return `${part.displayName} connected.`;\n }\n const tail = part.reason !== undefined ? ` (${part.reason})` : "";\n return `${part.displayName} authorization ${formatAuthorizationOutcome(part.outcome)}${tail}.`;\n}\n\nfunction formatAuthorizationOutcome(outcome: NonNullable<EveAuthorizationPart["outcome"]>): string {\n switch (outcome) {\n case "authorized":\n return "authorized";\n case "declined":\n return "declined";\n case "failed":\n return "failed";\n case "timed-out":\n return "timed out";\n }\n}\n\nfunction formatBytes(size: number | undefined): string | undefined {\n if (size === undefined) {\n return undefined;\n }\n if (size < 1024) {\n return `${size} B`;\n }\n if (size < 1024 * 1024) {\n return `${(size / 1024).toFixed(1)} KB`;\n }\n return `${(size / (1024 * 1024)).toFixed(1)} MB`;\n}\n\nfunction InputRequestActions({\n canRespond,\n onInputResponses,\n part,\n}: {\n readonly canRespond: boolean;\n readonly onInputResponses: (responses: readonly AgentInputResponse[]) => void | Promise<void>;\n readonly part: EveDynamicToolPart;\n}) {\n const inputRequest = part.toolMetadata?.eve?.inputRequest;\n if (!inputRequest) {\n return null;\n }\n\n const inputResponse = part.toolMetadata?.eve?.inputResponse;\n const selectedOption = inputRequest.options?.find(\n (option) => option.id === inputResponse?.optionId,\n );\n\n return (\n <div className="space-y-3 rounded-md border border-yellow-500/30 bg-yellow-500/5 p-3">\n <p className="text-muted-foreground text-sm">{inputRequest.prompt}</p>\n {inputResponse ? (\n <p className="font-medium text-sm">\n Responded: {selectedOption?.label ?? inputResponse.text ?? inputResponse.optionId}\n </p>\n ) : (\n <div className="flex flex-wrap gap-2">\n {inputRequest.options?.map((option) => (\n <Button\n disabled={!canRespond}\n key={option.id}\n onClick={() => {\n void onInputResponses([\n {\n optionId: option.id,\n requestId: inputRequest.requestId,\n },\n ]);\n }}\n size="sm"\n type="button"\n variant={option.style === "danger" ? "destructive" : "default"}\n >\n {option.label}\n </Button>\n ))}\n </div>\n )}\n </div>\n );\n}\n\nfunction partKey(part: EveMessagePart, index: number): string {\n switch (part.type) {\n case "authorization":\n return `authorization:${part.turnId}:${part.stepIndex}:${part.name}`;\n case "dynamic-tool":\n return part.toolCallId;\n default:\n return `${part.type}:${index}`;\n }\n}\n',"app/globals.css":diff --git a/packages/eve/src/setup/scaffold/index.integration.test.ts b/packages/eve/src/setup/scaffold/index.integration.test.tsindex 31a79c5ff..6fbfe45f7 100644--- a/packages/eve/src/setup/scaffold/index.integration.test.ts+++ b/packages/eve/src/setup/scaffold/index.integration.test.ts@@ -385,8 +385,9 @@ describe("ensureChannel", () => {join(projectRoot, "app/_components/agent-chat.tsx"),"utf8",);- expect(agentChatSource).toContain("preserveCompletedSessions: true");- expect(agentChatSource).toContain("session.cancel({ turnId })");+ expect(agentChatSource).toContain(".attach(sessionId)");+ expect(agentChatSource).toContain(".cancel({ turnId })");+ expect(agentChatSource).toContain("onSessionChange(session)");expect(agentChatSource).toContain("cancellation.sentTurnId === turnId");expect(agentChatSource).not.toContain("onStop={agent.stop}");});diff --git a/packages/eve/src/shared/channel-definition.ts b/packages/eve/src/shared/channel-definition.tsindex 043c9970c..1ffa5cc7b 100644--- a/packages/eve/src/shared/channel-definition.ts+++ b/packages/eve/src/shared/channel-definition.ts@@ -1,5 +1,7 @@import { type ChannelCors } from "#channel/cors.js";-import type { RouteDefinition, SendFn } from "#channel/routes.js";+import type { UserContent } from "ai";+import type { ChannelReceiveContext } from "#channel/channel-operations.js";+import type { RouteDefinition } from "#channel/routes.js";import type { Session, SessionHandle } from "#channel/session.js";import type { SessionAuthContext } from "#channel/types.js";@@ -25,7 +27,7 @@ export type FetchFileFunction = (url: string) => Promise<Buffer | FetchFileResul* schedule proactively routes a message to it.*/export interface GenericReceiveInput<TReceiveTarget = Record<string, unknown>> {- readonly message: string;+ readonly message: string | UserContent;readonly target: Readonly<TReceiveTarget>;readonly auth: SessionAuthContext | null;}@@ -64,15 +66,15 @@ export interface GenericChannelDefinition<** Return the channel-owned context (thread handles, API clients, etc.). The* framework passes it as the `channel` argument to event handlers (with- * {@link ChannelSessionOps} injected) and passes {@link SessionContext} as a- * separate `ctx` argument.+ * {@link ChannelContinuationOps} injected) and passes {@link SessionContext}+ * as a separate `ctx` argument.*/context?(state: NonNullable<TState>, session: SessionHandle): TCtx;readonly routes: readonly RouteDefinition<TState>[];receive?(input: GenericReceiveInput<TReceiveTarget>,- args: { send: SendFn<TState> },+ ctx: ChannelReceiveContext<TState>,): Promise<Session>;readonly events?: TEvents;diff --git a/packages/eve/src/shared/schedule-definition.ts b/packages/eve/src/shared/schedule-definition.tsindex 92572f40b..860a49d80 100644--- a/packages/eve/src/shared/schedule-definition.ts+++ b/packages/eve/src/shared/schedule-definition.ts@@ -1,6 +1,6 @@/*** The `run` form of {@link ScheduleDefinition} invokes this handler when a- * schedule's cron fires. It receives {@link ScheduleHandlerArgs} (`receive`,+ * schedule's cron fires. It receives {@link ScheduleHandlerArgs} (`to`,* `waitUntil`, `appAuth`) and may return synchronously or as a promise.*/export type GenericScheduleRunHandler<TArgs> = (args: TArgs) => Promise<void> | void;@@ -20,7 +20,7 @@ export interface GenericScheduleDefinitionFields<TArgs> {* on the prompt and discards the output (equivalent to the `<name>.md`* markdown form).* - `run`: full handler ({@link GenericScheduleRunHandler}). Receives- * `{ receive, waitUntil, appAuth }` and decides what to do.+ * `{ to, waitUntil, appAuth }` and decides what to do.** Identity is derived from the file path under `agent/schedules/`; authored* definitions do not carry a `name` field.diff --git a/packages/eve/src/svelte/use-eve-agent.test.ts b/packages/eve/src/svelte/use-eve-agent.test.tsindex e63e76645..1d4aef04a 100644--- a/packages/eve/src/svelte/use-eve-agent.test.ts+++ b/packages/eve/src/svelte/use-eve-agent.test.ts@@ -52,7 +52,6 @@ describe("useEveAgent (Svelte rune binding)", () => {}),]),initialSession: {- continuationToken: "http:session_1",sessionId: "session_1",streamIndex: 2,},@@ -61,7 +60,6 @@ describe("useEveAgent (Svelte rune binding)", () => {expect(agent.status).toBe("ready");expect(agent.data.messages).toHaveLength(2);expect(agent.session).toEqual({- continuationToken: "http:session_1",sessionId: "session_1",streamIndex: 2,});@@ -77,7 +75,7 @@ describe("useEveAgent (Svelte rune binding)", () => {vi.spyOn(globalThis, "fetch").mockRejectedValueOnce(new Error("Network failed"));- await agent.send({ message: "ignored" });+ await agent.send("ignored");expect(agent.data).toBe(dataBeforeSend);expect(agent.status).toBe("ready");@@ -87,7 +85,7 @@ describe("useEveAgent (Svelte rune binding)", () => {vi.stubGlobal("window", {});const events = [createMessageReceivedEvent({ message: "Hello", sequence: 0, turnId: "turn_1" }),- createSessionWaitingEvent("eve:http:session_1"),+ createSessionWaitingEvent(),];vi.spyOn(globalThis, "fetch").mockResolvedValueOnce(createStartedMessageResponse("session_1", "http:session_1"))@@ -100,7 +98,7 @@ describe("useEveAgent (Svelte rune binding)", () => {},});- await agent.send({ message: "Hello" });+ await agent.send("Hello");expect(seenEvents).toEqual(stampTestEvents(events));});diff --git a/packages/eve/src/svelte/use-eve-agent.ts b/packages/eve/src/svelte/use-eve-agent.tsindex d0017b23b..f0c762d13 100644--- a/packages/eve/src/svelte/use-eve-agent.ts+++ b/packages/eve/src/svelte/use-eve-agent.ts@@ -1,4 +1,5 @@import { createSubscriber } from "svelte/reactivity";+import type { UserContent } from "ai";import {EveAgentStore,@@ -11,7 +12,13 @@ import { resolveEveAgentHost } from "#client/agent-host.js";import { defaultMessageReducer, type EveMessageData } from "#client/message-reducer.js";import type { EveAgentReducer } from "#client/reducer.js";import type { ClientSession } from "#client/session.js";-import type { ClientAuth, HeadersValue, SendTurnPayload, SessionState } from "#client/types.js";+import type {+ ClientAuth,+ HeadersValue,+ RespondTurnOptions,+ SendTurnOptions,+ ClientSessionState,+} from "#client/types.js";import type { MessageStreamEvent } from "#protocol/message.js";export type { PrepareSend };@@ -46,10 +53,18 @@ export interface UseEveAgentReturn<TData> {readonly events: readonly MessageStreamEvent[];/** Clear all state and start a new session. */readonly reset: () => void;- /** Send a turn with full structured input (message, attachments, input responses). */- readonly send: <TOutput = unknown>(input: SendTurnPayload<TOutput>) => Promise<void>;+ /** Send a message with optional turn settings. */+ readonly send: <TOutput = unknown>(+ message: string | UserContent,+ options?: SendTurnOptions<TOutput>,+ ) => Promise<void>;+ /** Answer pending HITL input requests. */+ readonly respond: <TOutput = unknown>(+ inputResponses: Parameters<ClientSession["respond"]>[0],+ options?: RespondTurnOptions<TOutput>,+ ) => Promise<void>;/** Current session identity and stream cursor. */- readonly session: SessionState;+ readonly session: ClientSessionState | undefined;/** Lifecycle phase: `"ready"` (idle), `"submitted"` (request sent, awaiting first event), `"streaming"` (events arriving), or `"error"`. */readonly status: UseEveAgentStatus;/** Abort the in-flight request. */@@ -93,7 +108,7 @@ export interface UseEveAgentOptions<TData> extends EveAgentStoreCallbacks<TData>/** Ordered prefix of the session stream used to rehydrate projected state. */readonly initialEvents?: readonly MessageStreamEvent[];/** Seed session identity and stream cursor for resuming a prior conversation. */- readonly initialSession?: SessionState;+ readonly initialSession?: ClientSessionState;/*** Project submitted user messages before eve confirms them with a* `message.received` stream event. Optimistic events are reducer-facing@@ -153,7 +168,7 @@ class SvelteEveAgent<TData> implements UseEveAgentReturn<TData> {return this.#snapshot.events;}- get session(): SessionState {+ get session(): ClientSessionState | undefined {this.#subscribe();return this.#snapshot.session;}@@ -167,8 +182,18 @@ class SvelteEveAgent<TData> implements UseEveAgentReturn<TData> {this.#store.reset();};- send = <TOutput = unknown>(input: SendTurnPayload<TOutput>): Promise<void> => {- return this.#store.send(input);+ respond = <TOutput = unknown>(+ inputResponses: Parameters<ClientSession["respond"]>[0],+ options?: RespondTurnOptions<TOutput>,+ ): Promise<void> => {+ return this.#store.send({ ...options, inputResponses });+ };++ send = <TOutput = unknown>(+ message: string | UserContent,+ options?: SendTurnOptions<TOutput>,+ ): Promise<void> => {+ return this.#store.send({ ...options, message });};stop = (): void => {diff --git a/packages/eve/src/vue/use-eve-agent.test.ts b/packages/eve/src/vue/use-eve-agent.test.tsindex 76ab41c4a..6717bf0ee 100644--- a/packages/eve/src/vue/use-eve-agent.test.ts+++ b/packages/eve/src/vue/use-eve-agent.test.ts@@ -14,7 +14,7 @@ import {} from "#protocol/message.js";import { stampTestEvents } from "#internal/testing/events.js";import { defaultMessageReducer } from "#client/message-reducer.js";-import type { SessionState } from "#client/types.js";+import type { ClientSessionState } from "#client/types.js";function createStartedMessageResponse(sessionId: string, continuationToken: string): Response {return new Response(JSON.stringify({ continuationToken, ok: true, sessionId }), {@@ -139,7 +139,7 @@ describe("EveAgentStore (Vue composable backing store)", () => {stepIndex: 0,turnId: "turn_1",}),- createSessionWaitingEvent("eve:http:session_1"),+ createSessionWaitingEvent(),];const startResponse = createDeferred<Response>();@@ -152,7 +152,7 @@ describe("EveAgentStore (Vue composable backing store)", () => {});const seenEvents: UnstampedMessageStreamEvent[] = [];- const seenSessions: SessionState[] = [];+ const seenSessions: Array<ClientSessionState | undefined> = [];store.setCallbacks({onEvent(event) {seenEvents.push(event);@@ -191,7 +191,10 @@ describe("EveAgentStore (Vue composable backing store)", () => {);expect(seenSessions).toEqual([{- continuationToken: "http:session_1",+ sessionId: "session_1",+ streamIndex: 0,+ },+ {sessionId: "session_1",streamIndex: 3,},@@ -297,13 +300,10 @@ describe("EveAgentStore (Vue composable backing store)", () => {const startResponse = createDeferred<Response>();vi.spyOn(globalThis, "fetch").mockReturnValueOnce(startResponse.promise)- .mockResolvedValueOnce(- createEagerStreamResponse([createSessionWaitingEvent("eve:http:session_1")]),- );+ .mockResolvedValueOnce(createEagerStreamResponse([createSessionWaitingEvent()]));const store = new EveAgentStore<readonly string[]>({initialSession: {- continuationToken: "http:session_1",sessionId: "session_1",streamIndex: 0,},@@ -344,7 +344,7 @@ describe("useEveAgent (Vue composable wiring)", () => {stepIndex: 0,turnId: "turn_1",}),- createSessionWaitingEvent("eve:http:session_1"),+ createSessionWaitingEvent(),];const startResponse = createDeferred<Response>();@@ -359,7 +359,7 @@ describe("useEveAgent (Vue composable wiring)", () => {expect(agent.status.value).toBe("ready");expect(agent.data.value.messages).toEqual([]);- const sendPromise = agent.send({ message: "Hello" });+ const sendPromise = agent.send("Hello");await Promise.resolve();expect(agent.status.value).toBe("submitted");@@ -385,7 +385,7 @@ describe("useEveAgent (Vue composable wiring)", () => {.mockResolvedValueOnce(createEagerStreamResponse([createMessageReceivedEvent({ message: "After", sequence: 0, turnId: "turn_1" }),- createSessionWaitingEvent("eve:http:session_1"),+ createSessionWaitingEvent(),]),);@@ -396,7 +396,7 @@ describe("useEveAgent (Vue composable wiring)", () => {const dataBeforeDispose = agent.data.value;scope.stop();- await agent.send({ message: "After" });+ await agent.send("After");expect(agent.data.value).toBe(dataBeforeDispose);expect(agent.data.value.messages).toEqual([]);@@ -414,7 +414,6 @@ describe("useEveAgent (Vue composable wiring)", () => {}),]),initialSession: {- continuationToken: "http:session_1",sessionId: "session_1",streamIndex: 2,},@@ -425,7 +424,7 @@ describe("useEveAgent (Vue composable wiring)", () => {vi.spyOn(globalThis, "fetch").mockRejectedValueOnce(new Error("Network failed"));const dataBeforeSend = agent.data.value;- await agent.send({ message: "ignored" });+ await agent.send("ignored");expect(agent.data.value).toBe(dataBeforeSend);expect(agent.status.value).toBe("ready");diff --git a/packages/eve/src/vue/use-eve-agent.ts b/packages/eve/src/vue/use-eve-agent.tsindex 978ef8b85..740acf94f 100644--- a/packages/eve/src/vue/use-eve-agent.ts+++ b/packages/eve/src/vue/use-eve-agent.ts@@ -1,4 +1,5 @@import { shallowRef, computed, onScopeDispose, type ComputedRef } from "vue";+import type { UserContent } from "ai";import {EveAgentStore,@@ -12,7 +13,13 @@ import type { EveAgentReducer } from "#client/reducer.js";import type { ClientSession } from "#client/session.js";import { defaultMessageReducer, type EveMessageData } from "#client/message-reducer.js";import type { MessageStreamEvent } from "#protocol/message.js";-import type { ClientAuth, HeadersValue, SendTurnPayload, SessionState } from "#client/types.js";+import type {+ ClientAuth,+ HeadersValue,+ RespondTurnOptions,+ SendTurnOptions,+ ClientSessionState,+} from "#client/types.js";export type { PrepareSend };@@ -44,10 +51,18 @@ export interface UseEveAgentReturn<TData> {readonly events: ComputedRef<readonly MessageStreamEvent[]>;/** Clear all state and start a new session. */readonly reset: () => void;- /** Send a turn with full structured input (message, attachments, input responses). */- readonly send: <TOutput = unknown>(input: SendTurnPayload<TOutput>) => Promise<void>;+ /** Send a message with optional turn settings. */+ readonly send: <TOutput = unknown>(+ message: string | UserContent,+ options?: SendTurnOptions<TOutput>,+ ) => Promise<void>;+ /** Answer pending HITL input requests. */+ readonly respond: <TOutput = unknown>(+ inputResponses: Parameters<ClientSession["respond"]>[0],+ options?: RespondTurnOptions<TOutput>,+ ) => Promise<void>;/** Current session identity and stream cursor. */- readonly session: ComputedRef<SessionState>;+ readonly session: ComputedRef<ClientSessionState | undefined>;/** Lifecycle phase: `"ready"` (idle), `"submitted"` (request sent, awaiting first event), `"streaming"` (events arriving), or `"error"`. */readonly status: ComputedRef<UseEveAgentStatus>;/** Abort the in-flight request. */@@ -91,7 +106,7 @@ export interface UseEveAgentOptions<TData> extends EveAgentStoreCallbacks<TData>/** Ordered prefix of the session stream used to rehydrate projected state. */readonly initialEvents?: readonly MessageStreamEvent[];/** Prior session cursor to resume from on mount. */- readonly initialSession?: SessionState;+ readonly initialSession?: ClientSessionState;/*** Project submitted user messages before eve confirms them with a* `message.received` stream event.@@ -131,7 +146,7 @@ export function useEveAgent<TData>(* Without a `reducer`, events project into `EveMessageData` via* `defaultMessageReducer()`; pass `reducer` to project into a custom `TData`.* Returns reactive refs (`data`, `error`, `events`, `session`, `status`) plus- * `send`, `stop`, and `reset`. Configuration is read once on store creation;+ * `send`, `respond`, `stop`, and `reset`. Configuration is read once on store creation;* remount to change it. On scope dispose, the in-flight request is aborted and* the store unsubscribed.*/@@ -177,7 +192,12 @@ export function useEveAgent<TData>(error: computed(() => snapshot.value.error),events: computed(() => snapshot.value.events),reset: () => store.reset(),- send: <TOutput = unknown>(input: SendTurnPayload<TOutput>) => store.send(input),+ respond: <TOutput = unknown>(+ inputResponses: Parameters<ClientSession["respond"]>[0],+ options?: RespondTurnOptions<TOutput>,+ ) => store.send({ ...options, inputResponses }),+ send: <TOutput = unknown>(message: string | UserContent, options?: SendTurnOptions<TOutput>) =>+ store.send({ ...options, message }),session: computed(() => snapshot.value.session),status: computed(() => snapshot.value.status),stop: () => store.stop(),diff --git a/packages/eve/test/client.test.ts b/packages/eve/test/client.test.tsindex 29783ee74..5a3af7530 100644--- a/packages/eve/test/client.test.ts+++ b/packages/eve/test/client.test.ts@@ -53,8 +53,8 @@ function createControlledStreamResponse(): {};}-function createStartedMessageResponse(sessionId: string, continuationToken: string): Response {- return new Response(JSON.stringify({ continuationToken, ok: true, sessionId }), {+function createStartedMessageResponse(sessionId: string): Response {+ return new Response(JSON.stringify({ ok: true, sessionId }), {headers: {"content-type": "application/json",[EVE_SESSION_ID_HEADER]: sessionId,@@ -63,8 +63,8 @@ function createStartedMessageResponse(sessionId: string, continuationToken: stri});}-function createResumedMessageResponse(continuationToken: string): Response {- return new Response(JSON.stringify({ continuationToken, ok: true }), {+function createResumedMessageResponse(): Response {+ return new Response(JSON.stringify({ ok: true }), {headers: { "content-type": "application/json" },status: 200,});@@ -86,7 +86,6 @@ function createEagerStreamResponse(events: readonly unknown[]): Response {}function singleTurnEvents(input: {- continuationToken?: string;message: string;sequence: number;turnId: string;@@ -105,7 +104,7 @@ function singleTurnEvents(input: {turnId: input.turnId,}),createTurnCompletedEvent({ sequence: input.sequence, turnId: input.turnId }),- createSessionWaitingEvent(`eve:${input.continuationToken ?? "http:session_001"}`),+ createSessionWaitingEvent(),];}@@ -342,10 +341,10 @@ describe("Session.send (result)", () => {const events = singleTurnEvents({ message: "Hello", sequence: 1, turnId: "turn_001" });vi.spyOn(globalThis, "fetch")- .mockResolvedValueOnce(createStartedMessageResponse("session_001", "http:session_001"))+ .mockResolvedValueOnce(createStartedMessageResponse("session_001")).mockResolvedValueOnce(createEagerStreamResponse(events));- const session = new Client({ host: "http://localhost:3000" }).session();+ const session = new Client({ host: "http://localhost:3000" }).sessions.attach("session_001");const res = await session.send("Hello");expect(res.sessionId).toBe("session_001");@@ -358,7 +357,7 @@ describe("Session.send (result)", () => {expect(result.events).toEqual(events);});- it("sends continuation token on follow-up messages", async () => {+ it("sends follow-up messages through the fixed session ID", async () => {const firstEvents = singleTurnEvents({ message: "Hello", sequence: 1, turnId: "turn_001" });const secondEvents = singleTurnEvents({message: "Follow up",@@ -368,12 +367,12 @@ describe("Session.send (result)", () => {const fetchMock = vi.spyOn(globalThis, "fetch")- .mockResolvedValueOnce(createStartedMessageResponse("session_001", "http:session_001"))+ .mockResolvedValueOnce(createStartedMessageResponse("session_001")).mockResolvedValueOnce(createEagerStreamResponse(firstEvents))- .mockResolvedValueOnce(createResumedMessageResponse("http:session_001"))+ .mockResolvedValueOnce(createResumedMessageResponse()).mockResolvedValueOnce(createEagerStreamResponse(secondEvents));- const session = new Client({ host: "http://localhost:3000" }).session();+ const session = new Client({ host: "http://localhost:3000" }).sessions.attach("session_001");await (await session.send("Hello")).result();const second = await (await session.send("Follow up")).result();@@ -384,8 +383,10 @@ describe("Session.send (result)", () => {string,unknown>;- expect(secondPostBody.continuationToken).toBe("http:session_001");expect(secondPostBody.message).toBe("Follow up");+ expect(new URL(String(fetchMock.mock.calls[2]?.[0])).pathname).toBe(+ "/eve/v1/session/session_001",+ );const secondStreamUrl = String(fetchMock.mock.calls[3]?.[0]);expect(secondStreamUrl).toContain("startIndex=5");@@ -402,10 +403,10 @@ describe("Session.send (result)", () => {];vi.spyOn(globalThis, "fetch")- .mockResolvedValueOnce(createStartedMessageResponse("session_001", "http:session_001"))+ .mockResolvedValueOnce(createStartedMessageResponse("session_001")).mockResolvedValueOnce(createEagerStreamResponse(events));- const session = new Client({ host: "http://localhost:3000" }).session();+ const session = new Client({ host: "http://localhost:3000" }).sessions.attach("session_001");const result = await (await session.send("Hello")).result();expect(result.status).toBe("failed");@@ -427,10 +428,10 @@ describe("Session.send (result)", () => {];vi.spyOn(globalThis, "fetch")- .mockResolvedValueOnce(createStartedMessageResponse("session_001", "http:session_001"))+ .mockResolvedValueOnce(createStartedMessageResponse("session_001")).mockResolvedValueOnce(createEagerStreamResponse(events));- const session = new Client({ host: "http://localhost:3000" }).session();+ const session = new Client({ host: "http://localhost:3000" }).sessions.attach("session_001");const result = await (await session.send("Do a task")).result();expect(result.status).toBe("completed");@@ -463,16 +464,16 @@ describe("Session.send (result)", () => {turnId: "turn_001",}),createTurnCompletedEvent({ sequence: 1, turnId: "turn_001" }),- createSessionWaitingEvent("eve:http:session_001"),+ createSessionWaitingEvent(),];const fetchMock = vi.spyOn(globalThis, "fetch")- .mockResolvedValueOnce(createStartedMessageResponse("session_001", "http:session_001"))+ .mockResolvedValueOnce(createStartedMessageResponse("session_001")).mockResolvedValueOnce(createEagerStreamResponse(events));- const session = new Client({ host: "http://localhost:3000" }).session();- const response = await session.send<{ title: string }>({ message: "Summarize", outputSchema });+ const session = new Client({ host: "http://localhost:3000" }).sessions.attach("session_001");+ const response = await session.send<{ title: string }>("Summarize", { outputSchema });const result = await response.result();expect(result.data).toEqual({ title: "Done" });@@ -483,7 +484,7 @@ describe("Session.send (result)", () => {expect(postBody.outputSchema).toEqual(outputSchema);});- it("resets session state after session.completed", async () => {+ it("keeps the handle pinned after session.completed", async () => {const firstEvents: UnstampedMessageStreamEvent[] = [createTurnStartedEvent({ sequence: 1, turnId: "turn_001" }),createMessageCompletedEvent({@@ -495,7 +496,6 @@ describe("Session.send (result)", () => {createSessionCompletedEvent(),];const secondEvents = singleTurnEvents({- continuationToken: "http:session_002",message: "New conversation",sequence: 1,turnId: "turn_001",@@ -503,20 +503,18 @@ describe("Session.send (result)", () => {const fetchMock = vi.spyOn(globalThis, "fetch")- .mockResolvedValueOnce(createStartedMessageResponse("session_001", "http:session_001"))+ .mockResolvedValueOnce(createStartedMessageResponse("session_001")).mockResolvedValueOnce(createEagerStreamResponse(firstEvents))- .mockResolvedValueOnce(createStartedMessageResponse("session_002", "http:session_002"))+ .mockResolvedValueOnce(createResumedMessageResponse()).mockResolvedValueOnce(createEagerStreamResponse(secondEvents));- const session = new Client({ host: "http://localhost:3000" }).session();+ const session = new Client({ host: "http://localhost:3000" }).sessions.attach("session_001");await (await session.send("Task")).result();await (await session.send("New conversation")).result();- const secondPostBody = JSON.parse(fetchMock.mock.calls[2]?.[1]?.body as string) as Record<- string,- unknown- >;- expect(secondPostBody.continuationToken).toBeUndefined();+ expect(new URL(String(fetchMock.mock.calls[2]?.[0])).pathname).toBe(+ "/eve/v1/session/session_001",+ );});it("throws ClientError when the POST fails", async () => {@@ -524,7 +522,7 @@ describe("Session.send (result)", () => {new Response('{"ok":false,"error":"Bad request"}', { status: 400 }),);- const session = new Client({ host: "http://localhost:3000" }).session();+ const session = new Client({ host: "http://localhost:3000" }).sessions.attach("session_001");await expect(session.send("Hello")).rejects.toThrow(ClientError);});@@ -539,10 +537,10 @@ describe("Session.send (stream)", () => {const stream = createControlledStreamResponse();vi.spyOn(globalThis, "fetch")- .mockResolvedValueOnce(createStartedMessageResponse("session_001", "http:session_001"))+ .mockResolvedValueOnce(createStartedMessageResponse("session_001")).mockResolvedValueOnce(stream.response);- const session = new Client({ host: "http://localhost:3000" }).session();+ const session = new Client({ host: "http://localhost:3000" }).sessions.attach("session_001");const res = await session.send("Hello");const collected: UnstampedMessageStreamEvent[] = [];@@ -562,7 +560,7 @@ describe("Session.send (stream)", () => {turnId: "turn_001",}),);- stream.pushEvent(createSessionWaitingEvent("eve:http:session_001"));+ stream.pushEvent(createSessionWaitingEvent());}, 0);await iterationPromise;@@ -577,16 +575,16 @@ describe("Session.send (stream)", () => {const stream = createControlledStreamResponse();vi.spyOn(globalThis, "fetch")- .mockResolvedValueOnce(createStartedMessageResponse("session_001", "http:session_001"))+ .mockResolvedValueOnce(createStartedMessageResponse("session_001")).mockResolvedValueOnce(stream.response);- const session = new Client({ host: "http://localhost:3000" }).session();+ const session = new Client({ host: "http://localhost:3000" }).sessions.attach("session_001");const res = await session.send("Hello");expect(res.sessionId).toBe("session_001");setTimeout(() => {- stream.pushEvent(createSessionWaitingEvent("eve:http:session_001"));+ stream.pushEvent(createSessionWaitingEvent());}, 0);for await (const _ of res) {@@ -596,14 +594,14 @@ describe("Session.send (stream)", () => {it("throws when consumed twice", async () => {vi.spyOn(globalThis, "fetch")- .mockResolvedValueOnce(createStartedMessageResponse("session_001", "http:session_001"))+ .mockResolvedValueOnce(createStartedMessageResponse("session_001")).mockResolvedValueOnce(createEagerStreamResponse(singleTurnEvents({ message: "Hello", sequence: 1, turnId: "turn_001" }),),);- const session = new Client({ host: "http://localhost:3000" }).session();+ const session = new Client({ host: "http://localhost:3000" }).sessions.attach("session_001");const res = await session.send("Hello");await res.result();@@ -630,16 +628,16 @@ describe("Session.send (reconnection)", () => {turnId: "turn_001",}),createTurnCompletedEvent({ sequence: 1, turnId: "turn_001" }),- createSessionWaitingEvent("eve:http:session_001"),+ createSessionWaitingEvent(),];const fetchMock = vi.spyOn(globalThis, "fetch")- .mockResolvedValueOnce(createStartedMessageResponse("session_001", "http:session_001"))+ .mockResolvedValueOnce(createStartedMessageResponse("session_001")).mockResolvedValueOnce(firstStream.response).mockResolvedValueOnce(createEagerStreamResponse(reconnectEvents));- const session = new Client({ host: "http://localhost:3000" }).session();+ const session = new Client({ host: "http://localhost:3000" }).sessions.attach("session_001");const res = await session.send("Hello");setTimeout(() => {@@ -670,96 +668,81 @@ describe("Session.send (reconnection)", () => {describe("Session state", () => {it("exposes state after a turn completes", async () => {vi.spyOn(globalThis, "fetch")- .mockResolvedValueOnce(createStartedMessageResponse("session_001", "http:session_001"))+ .mockResolvedValueOnce(createStartedMessageResponse("session_001")).mockResolvedValueOnce(createEagerStreamResponse(singleTurnEvents({ message: "Hello", sequence: 1, turnId: "turn_001" }),),);- const session = new Client({ host: "http://localhost:3000" }).session();+ const session = new Client({ host: "http://localhost:3000" }).sessions.attach("session_001");- expect(session.state).toEqual({ streamIndex: 0 });+ expect(session.state).toEqual({ sessionId: "session_001", streamIndex: 0 });await (await session.send("Hello")).result();expect(session.state).toEqual({- continuationToken: "http:session_001",sessionId: "session_001",streamIndex: 5,});});- it("resumes from a saved SessionState", async () => {+ it("resumes from a saved ClientSessionState", async () => {const events = singleTurnEvents({ message: "I'm back", sequence: 2, turnId: "turn_002" });const fetchMock = vi.spyOn(globalThis, "fetch")- .mockResolvedValueOnce(createResumedMessageResponse("http:session_001"))+ .mockResolvedValueOnce(createResumedMessageResponse()).mockResolvedValueOnce(createEagerStreamResponse(events));const client = new Client({ host: "http://localhost:3000" });- const session = client.session({- continuationToken: "http:session_001",- sessionId: "session_001",- streamIndex: 5,- });+ const session = client.sessions.attach("session_001", { streamIndex: 5 });await (await session.send("I'm back")).result();- const postBody = JSON.parse(fetchMock.mock.calls[0]?.[1]?.body as string) as Record<- string,- unknown- >;- expect(postBody.continuationToken).toBe("http:session_001");-const streamUrl = String(fetchMock.mock.calls[1]?.[0]);expect(streamUrl).toContain("startIndex=5");});- it("resumes from a continuation token string shorthand", async () => {+ it("attaches a fixed session ID without sending it in the body", async () => {const events = singleTurnEvents({ message: "Hello", sequence: 1, turnId: "turn_001" });const fetchMock = vi.spyOn(globalThis, "fetch")- .mockResolvedValueOnce(createStartedMessageResponse("run_001", "http:session_001"))+ .mockResolvedValueOnce(createStartedMessageResponse("session_001")).mockResolvedValueOnce(createEagerStreamResponse(events));const client = new Client({ host: "http://localhost:3000" });- const session = client.session("http:session_001");+ const session = client.sessions.attach("session_001");await (await session.send("Hello")).result();- const postBody = JSON.parse(fetchMock.mock.calls[0]?.[1]?.body as string) as Record<- string,- unknown- >;- expect(postBody.continuationToken).toBe("http:session_001");+ expect(new URL(String(fetchMock.mock.calls[0]?.[0])).pathname).toBe(+ "/eve/v1/session/session_001",+ );});it("allows multiple independent sessions on the same client", async () => {const eventsA = singleTurnEvents({- continuationToken: "http:session_a",message: "A",sequence: 1,turnId: "turn_a",});const eventsB = singleTurnEvents({- continuationToken: "http:session_b",message: "B",sequence: 1,turnId: "turn_b",});vi.spyOn(globalThis, "fetch")- .mockResolvedValueOnce(createStartedMessageResponse("session_a", "http:session_a"))+ .mockResolvedValueOnce(createStartedMessageResponse("session_a")).mockResolvedValueOnce(createEagerStreamResponse(eventsA))- .mockResolvedValueOnce(createStartedMessageResponse("session_b", "http:session_b"))+ .mockResolvedValueOnce(createStartedMessageResponse("session_b")).mockResolvedValueOnce(createEagerStreamResponse(eventsB));const client = new Client({ host: "http://localhost:3000" });- const sessionA = client.session();- const sessionB = client.session();+ const sessionA = client.sessions.attach("session_a");+ const sessionB = client.sessions.attach("session_b");const resultA = await (await sessionA.send("A")).result();const resultB = await (await sessionB.send("B")).result();@@ -773,32 +756,27 @@ describe("Session state", () => {it("creating a new session starts a fresh conversation", async () => {const firstEvents = singleTurnEvents({ message: "Hello", sequence: 1, turnId: "turn_001" });const secondEvents = singleTurnEvents({- continuationToken: "http:session_002",message: "Fresh start",sequence: 1,turnId: "turn_001",});- const fetchMock = vi- .spyOn(globalThis, "fetch")- .mockResolvedValueOnce(createStartedMessageResponse("session_001", "http:session_001"))+ vi.spyOn(globalThis, "fetch")+ .mockResolvedValueOnce(createStartedMessageResponse("session_001")).mockResolvedValueOnce(createEagerStreamResponse(firstEvents))- .mockResolvedValueOnce(createStartedMessageResponse("session_002", "http:session_002"))+ .mockResolvedValueOnce(createStartedMessageResponse("session_002")).mockResolvedValueOnce(createEagerStreamResponse(secondEvents));const client = new Client({ host: "http://localhost:3000" });- const first = client.session();- await (await first.send("Hello")).result();+ const first = await client.sessions.create({ message: "Hello" });+ await first.response.result();- const second = client.session();- await (await second.send("Fresh start")).result();+ const second = await client.sessions.create({ message: "Fresh start" });+ await second.response.result();- const secondPostBody = JSON.parse(fetchMock.mock.calls[2]?.[1]?.body as string) as Record<- string,- unknown- >;- expect(secondPostBody.continuationToken).toBeUndefined();+ expect(first.session.state.sessionId).toBe("session_001");+ expect(second.session.state.sessionId).toBe("session_002");});});@@ -807,10 +785,9 @@ describe("Session state", () => {// ---------------------------------------------------------------------------describe("Session.stream", () => {- it("throws when no session ID is available", () => {- const session = new Client({ host: "http://localhost:3000" }).session();-- expect(() => session.stream()).toThrow("no session ID");+ it("rejects an empty session ID at attach time", () => {+ const client = new Client({ host: "http://localhost:3000" });+ expect(() => client.sessions.attach("")).toThrow("sessionId must be a non-empty string");});it("uses the session sessionId and streamIndex", async () => {@@ -821,7 +798,7 @@ describe("Session.stream", () => {stepIndex: 0,turnId: "turn_002",}),- createSessionWaitingEvent("eve:http:session_001"),+ createSessionWaitingEvent(),];const fetchMock = vi@@ -829,11 +806,7 @@ describe("Session.stream", () => {.mockResolvedValueOnce(createEagerStreamResponse(events));const client = new Client({ host: "http://localhost:3000" });- const session = client.session({- continuationToken: "http:session_001",- sessionId: "session_001",- streamIndex: 10,- });+ const session = client.sessions.attach("session_001", { streamIndex: 10 });const collected: UnstampedMessageStreamEvent[] = [];for await (const event of session.stream()) {@@ -861,7 +834,7 @@ describe("Client auth (async bearer)", () => {let tokenCounter = 0;const fetchMock = vi.spyOn(globalThis, "fetch")- .mockResolvedValueOnce(createStartedMessageResponse("session_001", "http:session_001"))+ .mockResolvedValueOnce(createStartedMessageResponse("session_001")).mockResolvedValueOnce(createEagerStreamResponse(singleTurnEvents({ message: "Hello", sequence: 1, turnId: "turn_001" }),@@ -878,7 +851,7 @@ describe("Client auth (async bearer)", () => {host: "http://localhost:3000",});- await (await client.session().send("Hello")).result();+ await (await client.sessions.attach("session_001").send("Hello")).result();expect(tokenCounter).toBe(2);const postHeaders = new Headers(fetchMock.mock.calls[0]?.[1]?.headers);diff --git a/packages/eve/test/dev-client-harness/send-message.ts b/packages/eve/test/dev-client-harness/send-message.tsindex 3110a3865..9b586a939 100644--- a/packages/eve/test/dev-client-harness/send-message.ts+++ b/packages/eve/test/dev-client-harness/send-message.ts@@ -1,9 +1,9 @@import type { MessageStreamEvent } from "#protocol/message.js";import { EVE_SESSION_ID_HEADER } from "#protocol/message.js";import {- EVE_CREATE_SESSION_ROUTE_PATH,- createEveContinueSessionRoutePath,- createEveMessageStreamRoutePath,+ EVE_SESSION_ROUTE_PATH,+ createEveSessionRoutePath,+ createEveSessionStreamRoutePath,} from "#protocol/routes.js";import {createDevelopmentRequestHeadersAsync,@@ -33,7 +33,7 @@ async function fetchDevelopmentSessionStreamResponse(input: {readonly response: Response;}> {const canonicalResourceUrl = resolveDevelopmentServerResourceUrl({- resource: createEveMessageStreamRoutePath(input.sessionId),+ resource: createEveSessionStreamRoutePath(input.sessionId),serverUrl: input.serverUrl,});const requestResourceUrl = new URL(canonicalResourceUrl);@@ -148,8 +148,8 @@ export async function sendDevelopmentMessage(input: {}> {const session = input.session;const routePath = session.sessionId- ? createEveContinueSessionRoutePath(session.sessionId)- : EVE_CREATE_SESSION_ROUTE_PATH;+ ? createEveSessionRoutePath(session.sessionId)+ : EVE_SESSION_ROUTE_PATH;const messageRouteUrl = resolveDevelopmentServerRouteUrl({routePath,serverUrl: input.serverUrl,@@ -180,13 +180,10 @@ export async function sendDevelopmentMessage(input: {const payload = (await response.json()) as Record<string, unknown>;if (payload.status === "completed" && typeof payload.output === "string") {- const continuationToken =- typeof payload.continuationToken === "string" ? payload.continuationToken : undefined;-return {completedMessage: payload.output,events: [],- session: createDevelopmentSessionState({ continuationToken }),+ session: createDevelopmentSessionState(),};}@@ -195,11 +192,6 @@ export async function sendDevelopmentMessage(input: {response.headers.get(EVE_SESSION_ID_HEADER)?.trim() ??session.sessionId ??undefined;- const continuationToken =- typeof payload.continuationToken === "string"- ? payload.continuationToken- : session.continuationToken;-if (!sessionId) {throw new Error("Message route did not return a session id.");}@@ -237,7 +229,6 @@ export async function sendDevelopmentMessage(input: {}const nextSession = updateDevelopmentSessionState({- continuationToken,events,sessionId,session,diff --git a/packages/eve/test/dev-client-harness/session.ts b/packages/eve/test/dev-client-harness/session.tsindex 51df8c111..485e325ef 100644--- a/packages/eve/test/dev-client-harness/session.ts+++ b/packages/eve/test/dev-client-harness/session.ts@@ -9,10 +9,6 @@ export interface DevelopmentSessionState {* Number of turn-boundary events already consumed from the run stream.*/readonly boundaryCount: number;- /**- * V2 continuation token for resuming a parked session across turns.- */- readonly continuationToken?: string;/*** Number of streamed workflow chunks already consumed from the session stream.*/@@ -30,14 +26,12 @@ export interface DevelopmentSessionState {export function createDevelopmentSessionState(input: {readonly boundaryCount?: number;- readonly continuationToken?: string;readonly sessionId?: string;readonly streamIndex?: number;} = {},): DevelopmentSessionState {return {boundaryCount: input.boundaryCount ?? 0,- continuationToken: input.continuationToken,sessionId: input.sessionId,streamIndex: input.streamIndex ?? 0,};@@ -51,13 +45,6 @@ export function createDevelopmentMessageRequest(input: {readonly message: string;readonly session: DevelopmentSessionState;}): HandleMessageRequestBody {- if (input.session.continuationToken) {- return {- continuationToken: input.session.continuationToken,- message: input.message,- };- }-return {message: input.message,};@@ -68,7 +55,6 @@ export function createDevelopmentMessageRequest(input: {* observed.*/export function updateDevelopmentSessionState(input: {- readonly continuationToken?: string;readonly events: readonly MessageStreamEvent[];readonly sessionId: string;readonly session: DevelopmentSessionState;@@ -80,7 +66,6 @@ export function updateDevelopmentSessionState(input: {if (boundaryEvent?.type === "session.waiting") {return createDevelopmentSessionState({boundaryCount,- continuationToken: input.continuationToken ?? input.session.continuationToken,sessionId: input.sessionId,streamIndex,});diff --git a/packages/eve/test/dev-send-message.test.ts b/packages/eve/test/dev-send-message.test.tsindex 183509c2e..e9da7d1ef 100644--- a/packages/eve/test/dev-send-message.test.ts+++ b/packages/eve/test/dev-send-message.test.ts@@ -10,7 +10,7 @@ import {createTurnCompletedEvent,createTurnStartedEvent,} from "../src/protocol/message.js";-import { createEveMessageStreamRoutePath } from "../src/protocol/routes.js";+import { createEveSessionStreamRoutePath } from "../src/protocol/routes.js";import { VERCEL_PROTECTION_BYPASS_HEADER } from "../src/services/dev-client/request-headers.js";import { VERCEL_TRUSTED_OIDC_IDP_TOKEN_HEADER } from "../src/client/types.js";import { sendDevelopmentMessage } from "./dev-client-harness/send-message.js";@@ -54,12 +54,8 @@ function createControlledStreamResponse(): {};}-function createStartedMessageResponse(- sessionId: string,- continuationToken: string,- location: string,-): Response {- return new Response(JSON.stringify({ continuationToken, ok: true, sessionId }), {+function createStartedMessageResponse(sessionId: string, location: string): Response {+ return new Response(JSON.stringify({ ok: true, sessionId }), {headers: {"content-type": "application/json",location,@@ -69,8 +65,8 @@ function createStartedMessageResponse(});}-function createResumedMessageResponse(continuationToken: string): Response {- return new Response(JSON.stringify({ continuationToken, ok: true }), {+function createResumedMessageResponse(): Response {+ return new Response(JSON.stringify({ ok: true }), {headers: {"content-type": "application/json",},@@ -105,14 +101,10 @@ describe("sendDevelopmentMessage", () => {const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValueOnce(- createStartedMessageResponse(- "session_001",- "http:session_001",- createEveMessageStreamRoutePath("session_001"),- ),+ createStartedMessageResponse("session_001", createEveSessionStreamRoutePath("session_001")),).mockResolvedValueOnce(firstStream.response)- .mockResolvedValueOnce(createResumedMessageResponse("http:session_001"))+ .mockResolvedValueOnce(createResumedMessageResponse()).mockResolvedValueOnce(secondStream.response);const firstPromise = sendDevelopmentMessage({@@ -144,7 +136,7 @@ describe("sendDevelopmentMessage", () => {}),);firstStream.pushEvent(createTurnCompletedEvent({ sequence: 1, turnId: "turn_001" }));- firstStream.pushEvent(createSessionWaitingEvent("eve:http:session_001"));+ firstStream.pushEvent(createSessionWaitingEvent());}, 0);const first = await firstPromise;@@ -177,7 +169,7 @@ describe("sendDevelopmentMessage", () => {}),);secondStream.pushEvent(createTurnCompletedEvent({ sequence: 2, turnId: "turn_002" }));- secondStream.pushEvent(createSessionWaitingEvent("eve:http:session_001"));+ secondStream.pushEvent(createSessionWaitingEvent());}, 0);const second = await secondPromise;@@ -185,14 +177,12 @@ describe("sendDevelopmentMessage", () => {expect(first.sessionId).toBe("session_001");expect(first.session).toEqual({boundaryCount: 1,- continuationToken: "http:session_001",sessionId: "session_001",streamIndex: 5,});expect(second.sessionId).toBe("session_001");expect(second.session).toEqual({boundaryCount: 2,- continuationToken: "http:session_001",sessionId: "session_001",streamIndex: 10,});@@ -231,21 +221,18 @@ describe("sendDevelopmentMessage", () => {type: "turn.completed",},{- data: {- continuationToken: "http:session_001",- wait: "next-user-message",- },+ data: { continuationToken: "", wait: "next-user-message" },type: "session.waiting",},]);expect(fetchMock).toHaveBeenCalledTimes(4);expect(fetchMock.mock.calls[0]?.[1]?.method).toBe("POST");expect(String(fetchMock.mock.calls[1]?.[0])).toContain(- createEveMessageStreamRoutePath("session_001"),+ createEveSessionStreamRoutePath("session_001"),);expect(fetchMock.mock.calls[2]?.[1]?.method).toBe("POST");expect(String(fetchMock.mock.calls[3]?.[0])).toContain(- `${createEveMessageStreamRoutePath("session_001")}?startIndex=5`,+ `${createEveSessionStreamRoutePath("session_001")}?startIndex=5`,);});@@ -294,19 +281,15 @@ describe("sendDevelopmentMessage", () => {turnId: "turn_002",}),createTurnCompletedEvent({ sequence: 2, turnId: "turn_002" }),- createSessionWaitingEvent("eve:http:session_001"),+ createSessionWaitingEvent(),]);const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValueOnce(- createStartedMessageResponse(- "session_001",- "http:session_001",- createEveMessageStreamRoutePath("session_001"),- ),+ createStartedMessageResponse("session_001", createEveSessionStreamRoutePath("session_001")),).mockResolvedValueOnce(firstStream.response)- .mockResolvedValueOnce(createResumedMessageResponse("http:session_001"))+ .mockResolvedValueOnce(createResumedMessageResponse()).mockResolvedValueOnce(secondStream.response).mockResolvedValueOnce(resumedStream);@@ -339,7 +322,7 @@ describe("sendDevelopmentMessage", () => {}),);firstStream.pushEvent(createTurnCompletedEvent({ sequence: 1, turnId: "turn_001" }));- firstStream.pushEvent(createSessionWaitingEvent("eve:http:session_001"));+ firstStream.pushEvent(createSessionWaitingEvent());}, 0);const first = await firstPromise;@@ -433,22 +416,18 @@ describe("sendDevelopmentMessage", () => {type: "turn.completed",},{- data: {- continuationToken: "http:session_001",- wait: "next-user-message",- },+ data: { continuationToken: "", wait: "next-user-message" },type: "session.waiting",},]);expect(second.session).toEqual({boundaryCount: 2,- continuationToken: "http:session_001",sessionId: "session_001",streamIndex: 12,});expect(fetchMock).toHaveBeenCalledTimes(5);expect(String(fetchMock.mock.calls[4]?.[0])).toContain(- `${createEveMessageStreamRoutePath("session_001")}?startIndex=6`,+ `${createEveSessionStreamRoutePath("session_001")}?startIndex=6`,);});@@ -457,11 +436,7 @@ describe("sendDevelopmentMessage", () => {const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValueOnce(- createStartedMessageResponse(- "session_001",- "http:session_001",- createEveMessageStreamRoutePath("session_001"),- ),+ createStartedMessageResponse("session_001", createEveSessionStreamRoutePath("session_001")),).mockResolvedValueOnce(stream.response);@@ -499,7 +474,7 @@ describe("sendDevelopmentMessage", () => {}),);stream.pushEvent(createTurnCompletedEvent({ sequence: 1, turnId: "turn_001" }));- stream.pushEvent(createSessionWaitingEvent("eve:http:session_001"));+ stream.pushEvent(createSessionWaitingEvent());}, 0);const result = await messagePromise;@@ -513,7 +488,6 @@ describe("sendDevelopmentMessage", () => {expect(streamHeaders.get("authorization")).toBe("Basic dGVzdDpzZWNyZXQ=");expect(result.session).toEqual({boundaryCount: 1,- continuationToken: "http:session_001",sessionId: "session_001",streamIndex: 5,});@@ -524,11 +498,7 @@ describe("sendDevelopmentMessage", () => {const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValueOnce(- createStartedMessageResponse(- "session_001",- "http:session_001",- createEveMessageStreamRoutePath("session_001"),- ),+ createStartedMessageResponse("session_001", createEveSessionStreamRoutePath("session_001")),).mockResolvedValueOnce(stream.response);@@ -563,7 +533,7 @@ describe("sendDevelopmentMessage", () => {}),);stream.pushEvent(createTurnCompletedEvent({ sequence: 1, turnId: "turn_001" }));- stream.pushEvent(createSessionWaitingEvent("eve:http:session_001"));+ stream.pushEvent(createSessionWaitingEvent());}, 0);await messagePromise;diff --git a/packages/eve/test/eve-run-stream-channel.test.ts b/packages/eve/test/eve-run-stream-channel.test.tsindex bdb83a2a4..69178219e 100644--- a/packages/eve/test/eve-run-stream-channel.test.ts+++ b/packages/eve/test/eve-run-stream-channel.test.ts@@ -2,9 +2,10 @@ import { describe, expect, it, vi } from "vitest";import type { MessageStreamEvent } from "../src/protocol/message.js";import { stampTestEvents } from "../src/internal/testing/events.js";-import type { RouteHandlerArgs, GetSessionFn } from "../src/channel/routes.js";+import { mockChannelContext } from "../src/internal/testing/mocks/mock-channel-operations.js";+import type { AttachSessionFn, RouteHandlerArgs } from "../src/channel/routes.js";import type { Session } from "../src/channel/session.js";-import { EVE_MESSAGE_STREAM_ROUTE_PATTERN } from "../src/protocol/routes.js";+import { EVE_SESSION_STREAM_ROUTE_PATTERN } from "../src/protocol/routes.js";import { none } from "../src/public/channels/auth.js";import { eveChannel } from "../src/public/channels/eve.js";@@ -22,14 +23,14 @@ import { eveChannel } from "../src/public/channels/eve.js";function createGetHandler() {const channel = eveChannel({ auth: none() });const getRoute = channel.routes.find(- (r) => r.method === "GET" && r.path === EVE_MESSAGE_STREAM_ROUTE_PATTERN,+ (r) => r.method === "GET" && r.path === EVE_SESSION_STREAM_ROUTE_PATTERN,);if (!getRoute) throw new Error("No stream GET route found");return getRoute;}describe("eveChannel GET stream", () => {- it("forwards the startIndex query parameter into getSession/getEventStream", async () => {+ it("forwards the startIndex query parameter into attachSession/getEventStream", async () => {const getRoute = createGetHandler();const events = createEvents(stampTestEvents([@@ -45,76 +46,76 @@ describe("eveChannel GET stream", () => {},]),);- const getSession = createMockGetSession(events);+ const attachSession = createMockAttachSession(events);const response = await (getRoute as any).handler(new Request("https://example.com/eve/v1/session/session_xyz/stream?startIndex=42", {method: "GET",}),- createArgs({ getSession, params: { sessionId: "session_xyz" } }),+ createArgs({ attachSession, params: { sessionId: "session_xyz" } }),);expect(response.status).toBe(200);- expect(getSession).toHaveBeenCalledTimes(1);- expect(getSession.mock.calls[0]?.[0]).toBe("session_xyz");+ expect(attachSession).toHaveBeenCalledTimes(1);+ expect(attachSession.mock.calls[0]?.[0]).toBe("session_xyz");});it("passes startIndex undefined when the query parameter is absent", async () => {const getRoute = createGetHandler();- const getSession = createMockGetSession(createEvents([]));+ const attachSession = createMockAttachSession(createEvents([]));const response = await (getRoute as any).handler(new Request("https://example.com/eve/v1/session/session_xyz/stream", {method: "GET",}),- createArgs({ getSession, params: { sessionId: "session_xyz" } }),+ createArgs({ attachSession, params: { sessionId: "session_xyz" } }),);expect(response.status).toBe(200);- expect(getSession).toHaveBeenCalledTimes(1);+ expect(attachSession).toHaveBeenCalledTimes(1);});it("accepts negative tail-relative startIndex values", async () => {const getRoute = createGetHandler();- const getSession = createMockGetSession(createEvents([]));+ const attachSession = createMockAttachSession(createEvents([]));const response = await (getRoute as any).handler(new Request("https://example.com/eve/v1/session/session_xyz/stream?startIndex=-3", {method: "GET",}),- createArgs({ getSession, params: { sessionId: "session_xyz" } }),+ createArgs({ attachSession, params: { sessionId: "session_xyz" } }),);expect(response.status).toBe(200);- expect(getSession).toHaveBeenCalledTimes(1);+ expect(attachSession).toHaveBeenCalledTimes(1);});it("rejects non-integer startIndex values with 400", async () => {const getRoute = createGetHandler();- const getSession = createMockGetSession(createEvents([]));+ const attachSession = createMockAttachSession(createEvents([]));const response = await (getRoute as any).handler(new Request("https://example.com/eve/v1/session/session_xyz/stream?startIndex=banana", {method: "GET",}),- createArgs({ getSession, params: { sessionId: "session_xyz" } }),+ createArgs({ attachSession, params: { sessionId: "session_xyz" } }),);expect(response.status).toBe(400);- expect(getSession).not.toHaveBeenCalled();+ expect(attachSession).toHaveBeenCalledWith("session_xyz");});it("returns 400 when the sessionId path parameter is missing", async () => {const getRoute = createGetHandler();- const getSession = createMockGetSession(createEvents([]));+ const attachSession = createMockAttachSession(createEvents([]));const response = await (getRoute as any).handler(new Request("https://example.com/eve/v1/session//stream", { method: "GET" }),- createArgs({ getSession, params: {} }),+ createArgs({ attachSession, params: {} }),);expect(response.status).toBe(400);- expect(getSession).not.toHaveBeenCalled();+ expect(attachSession).not.toHaveBeenCalled();});it("re-serializes the parsed event stream as NDJSON bytes", async () => {@@ -132,16 +133,16 @@ describe("eveChannel GET stream", () => {},{type: "session.waiting",- data: { continuationToken: "eve:test", wait: "next-user-message" },+ data: { continuationToken: "session-id", wait: "next-user-message" },},]);- const getSession = createMockGetSession(createEvents(events));+ const attachSession = createMockAttachSession(createEvents(events));const response = await (getRoute as any).handler(new Request("https://example.com/eve/v1/session/session_xyz/stream", {method: "GET",}),- createArgs({ getSession, params: { sessionId: "session_xyz" } }),+ createArgs({ attachSession, params: { sessionId: "session_xyz" } }),);expect(response.status).toBe(200);@@ -167,13 +168,27 @@ function createEvents(events: readonly MessageStreamEvent[]): ReadableStream<Mes});}-function createMockGetSession(events: ReadableStream<MessageStreamEvent>) {- return vi.fn<GetSessionFn>().mockReturnValue({+function createMockAttachSession(events: ReadableStream<MessageStreamEvent>) {+ return vi.fn<AttachSessionFn>().mockReturnValue({id: "session_xyz",- continuationToken: "",+ async send() {+ return { sessionId: "session_xyz", status: "accepted" };+ },+ async respond() {+ return { sessionId: "session_xyz", status: "accepted" };+ },async cancel() {return { status: "no_active_turn" };},+ async compact() {+ return { sessionId: "session_xyz", status: "accepted" };+ },+ async clear() {+ return { sessionId: "session_xyz", status: "accepted" };+ },+ async reset() {+ return { previousSessionId: "session_xyz", status: "reset" };+ },async getEventStream() {return events;},@@ -184,18 +199,13 @@ function createMockGetSession(events: ReadableStream<MessageStreamEvent>) {}function createArgs(input: {- readonly getSession: GetSessionFn;+ readonly attachSession: AttachSessionFn;readonly params: Readonly<Record<string, string>>;}): RouteHandlerArgs {return {- send: vi.fn(),- resolveActiveSession: async () => undefined,- cancel: vi.fn(),- clear: vi.fn(),- compact: vi.fn(),- reset: vi.fn(),- getSession: input.getSession,- receive: vi.fn() as any,+ ...mockChannelContext(vi.fn()),+ attachSession: input.attachSession,+ to: vi.fn() as any,params: input.params,waitUntil: () => undefined,requestIp: "127.0.0.1",diff --git a/packages/eve/test/scenarios/agent-info-route.scenario.test.ts b/packages/eve/test/scenarios/agent-info-route.scenario.test.tsindex 92907adf6..30a878ef4 100644--- a/packages/eve/test/scenarios/agent-info-route.scenario.test.ts+++ b/packages/eve/test/scenarios/agent-info-route.scenario.test.ts@@ -8,7 +8,7 @@ import { compileAgent } from "../../src/compiler/compile-agent.js";import { createDevelopmentNitroArtifactsConfig } from "../../src/internal/nitro/host/artifacts-config.js";import type { AgentInfoResponse } from "../../src/internal/nitro/routes/agent-info/build-agent-info-response.js";import { dispatchChannelRequest } from "../../src/internal/nitro/routes/channel-dispatch.js";-import { EVE_CREATE_SESSION_ROUTE_PATH, EVE_INFO_ROUTE_PATH } from "../../src/protocol/routes.js";+import { EVE_INFO_ROUTE_PATH, EVE_SESSION_ROUTE_PATH } from "../../src/protocol/routes.js";import { useTemporaryAppRoots } from "../../src/internal/testing/use-temporary-app-roots.js";const createAppRoot = useTemporaryAppRoots();@@ -140,7 +140,7 @@ describe("eve agent info route", () => {status: "active",});expect(payload.channels.available.map((channel) => channel.urlPath)).toContain(- EVE_CREATE_SESSION_ROUTE_PATH,+ EVE_SESSION_ROUTE_PATH,);expect(payload.channels.framework.length).toBeGreaterThan(0);expect(payload.diagnostics).toEqual({diff --git a/packages/eve/test/scenarios/cli.scenario.test.ts b/packages/eve/test/scenarios/cli.scenario.test.tsindex 292f3b649..f8e055814 100644--- a/packages/eve/test/scenarios/cli.scenario.test.ts+++ b/packages/eve/test/scenarios/cli.scenario.test.ts@@ -11,10 +11,10 @@ import { useScenarioApp } from "../../src/internal/testing/scenario-app.js";import { WEATHER_AGENT_DESCRIPTOR } from "../../src/internal/testing/scenario-apps/weather-agent.js";import { resolveLocalWorkflowWorldDataDirectory } from "../../src/internal/workflow/local-world-data-directory.js";import {- EVE_CONTINUE_SESSION_ROUTE_PATTERN,- EVE_CREATE_SESSION_ROUTE_PATH,EVE_HEALTH_ROUTE_PATH,- EVE_MESSAGE_STREAM_ROUTE_PATTERN,+ EVE_SESSION_ROUTE_PATH,+ EVE_SESSION_ROUTE_PATTERN,+ EVE_SESSION_STREAM_ROUTE_PATTERN,} from "../../src/protocol/routes.js";import { useTemporaryDirectories } from "../../src/internal/testing/use-temporary-app-roots.js";@@ -245,9 +245,9 @@ describe("runCli", () => {expect(getLogOutput(logger)).toContain("eve Info");expect(getLogOutput(logger)).toContain("Application");expect(getLogOutput(logger)).toContain("Workflow ID");- expect(getLogOutput(logger)).toContain(`POST ${EVE_CREATE_SESSION_ROUTE_PATH}`);- expect(getLogOutput(logger)).toContain(`POST ${EVE_CONTINUE_SESSION_ROUTE_PATTERN}`);- expect(getLogOutput(logger)).toContain(`GET ${EVE_MESSAGE_STREAM_ROUTE_PATTERN}`);+ expect(getLogOutput(logger)).toContain(`POST ${EVE_SESSION_ROUTE_PATH}`);+ expect(getLogOutput(logger)).toContain(`POST ${EVE_SESSION_ROUTE_PATTERN}`);+ expect(getLogOutput(logger)).toContain(`GET ${EVE_SESSION_STREAM_ROUTE_PATTERN}`);});it("prints compiled discovery metadata when run inside an eve app", async () => {diff --git a/packages/eve/test/scenarios/cross-channel-receive.scenario.test.ts b/packages/eve/test/scenarios/cross-channel-receive.scenario.test.tsindex be7f3c4f2..8cf28e9c6 100644--- a/packages/eve/test/scenarios/cross-channel-receive.scenario.test.ts+++ b/packages/eve/test/scenarios/cross-channel-receive.scenario.test.ts@@ -4,7 +4,7 @@ import { join } from "node:path";import { describe, expect, it } from "vitest";import {- createCrossChannelReceiveFn,+ createCrossChannelToFn,toCrossChannelTargets,} from "../../src/channel/cross-channel-receive.js";import type { Runtime, SessionCommand, SessionCommandResult } from "../../src/channel/types.js";@@ -16,9 +16,10 @@ import {withRuntimeSession,} from "../../src/runtime/sessions/runtime-session.js";import { useTemporaryAppRoots } from "../../src/internal/testing/use-temporary-app-roots.js";+import { mockChannelContext } from "../../src/internal/testing/mocks/mock-channel-operations.js";/**- * Locks the cross-channel `args.receive(channel, …)` path end-to-end:+ * Locks the cross-channel `ctx.to(channel, target).send(...)` path end-to-end:* a two-channel agent is compiled from disk, its resolved bundle* preserves the per-channel `definition` reference, and dispatching by* that reference routes through to the target channel's `receive`@@ -43,11 +44,9 @@ export default {path: "/webhook",handler: async (req, args) => {const body = await req.json();- const session = await args.receive(target, {- message: body.message,- target: { sessionId: body.sessionId },- auth: body.auth,- });+ const session = await args+ .to(target, { sessionId: body.sessionId })+ .send(body.message, { auth: body.auth });return Response.json({ ok: true, sessionId: session.id });},},@@ -61,11 +60,10 @@ const TARGET_CHANNEL = `export default {routes: [{ method: "POST", path: "/target", handler: async () => new Response("ok") },],- async receive(input, { send }) {+ async receive(input, { from }) {const target = input.target;- return send(input.message, {+ return from(\`target:\${target.sessionId ?? "default"}\`).send(input.message, {auth: input.auth,- continuationToken: \`target:\${target.sessionId ?? "default"}\`,});},};@@ -139,7 +137,7 @@ describe("cross-channel receive end-to-end", () => {expect(target?.receive).toBeDefined();const captured: CapturedRun[] = [];- const receive = createCrossChannelReceiveFn(+ const to = createCrossChannelToFn(createCapturingRuntime(captured),toCrossChannelTargets(bundle.graph.root.channels),);@@ -151,11 +149,10 @@ describe("cross-channel receive end-to-end", () => {principalType: "service",} as const;- const session = await receive(target!.definition!, {- message: "incident triggered",- target: { sessionId: "scenario-123" },- auth,- });+ const session = await to(target!.definition!, { sessionId: "scenario-123" }).send(+ "incident triggered",+ { auth },+ );expect(session.id).toBe("sess_scenario");expect(captured).toHaveLength(1);@@ -175,26 +172,13 @@ describe("cross-channel receive end-to-end", () => {}),}),{- receive,- resolveActiveSession: async () => undefined,- send: async () => {- throw new Error("webhook should delegate to args.receive()");- },- 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");- },- reset: async () => {- throw new Error("webhook should not reset sessions");- },- getSession: () => {- throw new Error("webhook should not read sessions directly");+ ...mockChannelContext(() => {+ throw new Error("webhook should not send directly");+ }),+ attachSession: () => {+ throw new Error("webhook should not attach sessions directly");},+ to,params: {},requestIp: null,waitUntil: () => undefined,@@ -225,15 +209,13 @@ describe("cross-channel receive end-to-end", () => {const compiledArtifactsSource = createDiskRuntimeCompiledArtifactsSource(appRoot);const bundle = await getCompiledRuntimeAgentBundle({ compiledArtifactsSource });- const receive = createCrossChannelReceiveFn(+ const to = createCrossChannelToFn(createCapturingRuntime([]),toCrossChannelTargets(bundle.graph.root.channels),);- const stranger = { __kind: "eve:channel", routes: [], adapter: { kind: "x" } };+ const stranger = { __kind: "eve:channel", routes: [], adapter: { kind: "x" } } as const;- await expect(receive(stranger, { message: "x", target: {}, auth: null })).rejects.toThrow(- /not registered in this agent/,- );+ expect(() => to(stranger, {})).toThrow(/not registered in this agent/);});});});diff --git a/packages/eve/test/scenarios/remote-agent-principal-forwarding.scenario.test.ts b/packages/eve/test/scenarios/remote-agent-principal-forwarding.scenario.test.tsindex 8d00b0b15..0a0cbea75 100644--- a/packages/eve/test/scenarios/remote-agent-principal-forwarding.scenario.test.ts+++ b/packages/eve/test/scenarios/remote-agent-principal-forwarding.scenario.test.ts@@ -99,8 +99,6 @@ describe("remote agent auth forwarding", () => {session: createParentSession(),});expect(child.sessionId.length).toBeGreaterThan(0);- expect(child.continuationToken).toBeDefined();- expect(child.continuationToken?.length).toBeGreaterThan(0);// Mismatch: an authenticated caller outside the forwarder allow-list// fails loud at the hop instead of downgrading to service identity.diff --git a/packages/eve/test/scenarios/schedule-trigger.scenario.test.ts b/packages/eve/test/scenarios/schedule-trigger.scenario.test.tsindex b105bdaeb..230275a22 100644--- a/packages/eve/test/scenarios/schedule-trigger.scenario.test.ts+++ b/packages/eve/test/scenarios/schedule-trigger.scenario.test.ts@@ -64,7 +64,6 @@ function createCapturingRuntime(captured: CapturedRun[]): Runtime {});const handle: RunHandle = {- continuationToken: "scenario-token",events: new ReadableStream<MessageStreamEvent>(),sessionId: "scenario-session",};diff --git a/packages/eve/test/scenarios/turn-cancellation.scenario.test.ts b/packages/eve/test/scenarios/turn-cancellation.scenario.test.tsindex 2fc88dde8..bb90a99f8 100644--- a/packages/eve/test/scenarios/turn-cancellation.scenario.test.ts+++ b/packages/eve/test/scenarios/turn-cancellation.scenario.test.ts@@ -2,7 +2,7 @@ import { describe, expect, it } from "vitest";import { Client } from "../../src/client/client.js";import { type MessageStreamEvent, isCurrentTurnBoundaryEvent } from "../../src/protocol/message.js";-import { createEveCancelTurnRoutePath } from "../../src/protocol/routes.js";+import { createEveSessionCancelRoutePath } from "../../src/protocol/routes.js";import {type ScenarioAppDescriptor,useScenarioApp,@@ -117,13 +117,12 @@ describe("turn cancellation descendant cascade", () => {try {const parentClient = new Client({ host: parentServer.url });- const parentSession = parentClient.session();- const response = await parentSession.send(- [+ const { session: parentSession, response } = await parentClient.sessions.create({+ message: ["Call tools in parallel: local-sleeper, remote-sleeper",'message: "Use wait-for-cancel."',].join("\n"),- );+ });const parentIterator = response[Symbol.asyncIterator]();const called = await readSubagentCalls({count: 2,@@ -137,8 +136,8 @@ describe("turn cancellation descendant cascade", () => {}expect(remoteCalled.data.remote?.url).toBe(remoteServer.url);- const localIterator = parentClient- .session({ sessionId: localCalled.data.childSessionId, streamIndex: 0 })+ const localIterator = parentClient.sessions+ .attach(localCalled.data.childSessionId).stream()[Symbol.asyncIterator]();@@ -146,8 +145,8 @@ describe("turn cancellation descendant cascade", () => {auth: { bearer: REMOTE_TOKEN },host: remoteServer.url,});- const remoteIterator = remoteClient- .session({ sessionId: remoteCalled.data.childSessionId, streamIndex: 0 })+ const remoteIterator = remoteClient.sessions+ .attach(remoteCalled.data.childSessionId).stream()[Symbol.asyncIterator]();await Promise.all([@@ -164,7 +163,7 @@ describe("turn cancellation descendant cascade", () => {]);const cancelResponse = await parentClient.fetch(- createEveCancelTurnRoutePath(response.sessionId),+ createEveSessionCancelRoutePath(response.sessionId),{ method: "POST" },);expect(cancelResponse.status).toBe(202);diff --git a/packages/eve/test/tui-client/tui-connection-auth-states.ts b/packages/eve/test/tui-client/tui-connection-auth-states.tsindex 2f0960947..04720cf62 100644--- a/packages/eve/test/tui-client/tui-connection-auth-states.ts+++ b/packages/eve/test/tui-client/tui-connection-auth-states.ts@@ -43,10 +43,9 @@ class FakeSession extends ClientSession {super({host: "http://fake.invalid",- preserveCompletedSessions: false,resolveHeaders: async () => new Headers(),},- { streamIndex: 0 },+ { sessionId: "fake-session", streamIndex: 0 },);this.#turns = input.turns;this.#continuations = input.continuations;@@ -57,7 +56,6 @@ class FakeSession extends ClientSession {this.#turnIndex += 1;return new MessageResponse<TOutput>({sessionId: "fake-session",- continuationToken: `fake-token-${this.#turnIndex}`,createStream: () => pacedEvents(events),});}@@ -123,7 +121,7 @@ const firstTurn: UnstampedMessageStreamEvent[] = [},{type: "session.waiting",- data: { continuationToken: "eve:test", wait: "next-user-message" },+ data: { continuationToken: "session-id", wait: "next-user-message" },},];@@ -144,7 +142,7 @@ const firstCallbackTurn: UnstampedMessageStreamEvent[] = [},{type: "session.waiting",- data: { continuationToken: "eve:test", wait: "next-user-message" },+ data: { continuationToken: "session-id", wait: "next-user-message" },},];@@ -172,7 +170,7 @@ const secondTurn: UnstampedMessageStreamEvent[] = [},{type: "session.waiting",- data: { continuationToken: "eve:test", wait: "next-user-message" },+ data: { continuationToken: "session-id", wait: "next-user-message" },},];@@ -194,7 +192,7 @@ const secondCallbackTurn: UnstampedMessageStreamEvent[] = [},{type: "session.waiting",- data: { continuationToken: "eve:test", wait: "next-user-message" },+ data: { continuationToken: "session-id", wait: "next-user-message" },},];diff --git a/packages/eve/test/tui-client/tui-connection-auth-user.ts b/packages/eve/test/tui-client/tui-connection-auth-user.tsindex 561aa488c..58147bcad 100644--- a/packages/eve/test/tui-client/tui-connection-auth-user.ts+++ b/packages/eve/test/tui-client/tui-connection-auth-user.ts@@ -142,7 +142,7 @@ runEnvironment("tui-connection-auth-user", async ({ cleanup, target: resolveTargconst sessionId = startBody.sessionId;const client = new Client({ host: target.baseUrl });- const session = client.session({ sessionId, streamIndex: 0 });+ const session = client.sessions.attach(sessionId);const stream = session.stream();let requiredEvent: AuthorizationRequiredStreamEvent | undefined;diff --git a/packages/eve/test/tui-client/tui-log-modes.ts b/packages/eve/test/tui-client/tui-log-modes.tsindex bd314b6c6..40999afe0 100644--- a/packages/eve/test/tui-client/tui-log-modes.ts+++ b/packages/eve/test/tui-client/tui-log-modes.ts@@ -37,7 +37,7 @@ async function snapshotForMode(mode: "all" | "stderr" | "sandbox" | "none"): ProcaptureForeignOutput: true,logs: mode,});- const options: EveTUIRunnerOptions = { session: client.session(), client, renderer };+ const options: EveTUIRunnerOptions = { client, renderer };const runner = new EveTUIRunner(options);const runPromise = runner.run().catch((error: unknown) => {diff --git a/packages/eve/test/tui-client/tui-loglevel.ts b/packages/eve/test/tui-client/tui-loglevel.tsindex 1bccfd4c4..bfce4c81f 100644--- a/packages/eve/test/tui-client/tui-loglevel.ts+++ b/packages/eve/test/tui-client/tui-loglevel.ts@@ -37,7 +37,7 @@ void (async () => {captureForeignOutput: true,logs: "all",});- const options: EveTUIRunnerOptions = { session: client.session(), client, renderer };+ const options: EveTUIRunnerOptions = { client, renderer };const runner = new EveTUIRunner(options);const runPromise = runner.run().catch((error: unknown) => {diff --git a/packages/eve/test/tui-client/tui-questions-freeform.ts b/packages/eve/test/tui-client/tui-questions-freeform.tsindex c1767dfe8..af68b2d44 100644--- a/packages/eve/test/tui-client/tui-questions-freeform.ts+++ b/packages/eve/test/tui-client/tui-questions-freeform.ts@@ -21,11 +21,10 @@ process.env.EVE_TUI_UNICODE = "1";run({ app: "agent-tui-client", kind: "local-build" }, async (target) => {const client = new Client({ host: target.baseUrl });- const session = client.session();const screen = new MockScreen({ columns: 100, rows: 40 });const input = new MockUserInput();const runner = new EveTUIRunner({- session,+ client,screen,userInput: input,name: "TUI smoke",diff --git a/packages/eve/test/tui-client/tui-questions.ts b/packages/eve/test/tui-client/tui-questions.tsindex 1d806daba..0f8c614ad 100644--- a/packages/eve/test/tui-client/tui-questions.ts+++ b/packages/eve/test/tui-client/tui-questions.ts@@ -33,11 +33,10 @@ process.env.EVE_TUI_UNICODE = "1";run({ app: "agent-tui-client", kind: "local-build" }, async (target) => {const client = new Client({ host: target.baseUrl });- const session = client.session();const screen = new MockScreen({ columns: 100, rows: 40 });const input = new MockUserInput();const runner = new EveTUIRunner({- session,+ client,screen,userInput: input,name: "TUI smoke",diff --git a/packages/eve/test/tui-client/tui-queue-steer.ts b/packages/eve/test/tui-client/tui-queue-steer.tsindex d2e4d9390..d0049b123 100644--- a/packages/eve/test/tui-client/tui-queue-steer.ts+++ b/packages/eve/test/tui-client/tui-queue-steer.ts@@ -34,11 +34,9 @@ process.env.EVE_TUI_UNICODE = "1";run({ app: "agent-tui-client", kind: "local-build" }, async (target) => {const client = new Client({ host: target.baseUrl });- const session = client.session();const screen = new MockScreen({ columns: 110, rows: 44 });const input = new MockUserInput();const runner = new EveTUIRunner({- session,client,screen,userInput: input,diff --git a/packages/eve/test/tui-client/tui-rebuild-status.ts b/packages/eve/test/tui-client/tui-rebuild-status.tsindex df9c5bd55..c98c2cc96 100644--- a/packages/eve/test/tui-client/tui-rebuild-status.ts+++ b/packages/eve/test/tui-client/tui-rebuild-status.ts@@ -36,7 +36,7 @@ void (async () => {captureForeignOutput: true,logs: "all",});- const options: EveTUIRunnerOptions = { session: client.session(), client, renderer };+ const options: EveTUIRunnerOptions = { client, renderer };const runner = new EveTUIRunner(options);const runPromise = runner.run().catch((error: unknown) => {diff --git a/packages/eve/test/tui-client/tui-server-logs.ts b/packages/eve/test/tui-client/tui-server-logs.tsindex 1714f4b6f..2124f0589 100644--- a/packages/eve/test/tui-client/tui-server-logs.ts+++ b/packages/eve/test/tui-client/tui-server-logs.ts@@ -32,7 +32,7 @@ void (async () => {logs: "all",unicode: true,});- const runner = new EveTUIRunner({ session: client.session(), client, renderer });+ const runner = new EveTUIRunner({ client, renderer });const runPromise = runner.run().catch((error: unknown) => {if (error instanceof Error && error.message === "Interrupted") {diff --git a/packages/eve/test/tui-client/tui-subagents-weather.ts b/packages/eve/test/tui-client/tui-subagents-weather.tsindex aaeb6f848..3f7560a4e 100644--- a/packages/eve/test/tui-client/tui-subagents-weather.ts+++ b/packages/eve/test/tui-client/tui-subagents-weather.ts@@ -45,11 +45,9 @@ const WEATHER_SMOKE_TARGET: RunOptions = {run(WEATHER_SMOKE_TARGET, async (target) => {const client = new Client({ host: target.baseUrl });- const session = client.session();const screen = new MockScreen({ columns: 140, rows: 60 });const input = new MockUserInput();const runner = new EveTUIRunner({- session,client,screen,userInput: input,diff --git a/packages/eve/test/tui-client/tui-subagents.ts b/packages/eve/test/tui-client/tui-subagents.tsindex 8aed4b1da..f1f354350 100644--- a/packages/eve/test/tui-client/tui-subagents.ts+++ b/packages/eve/test/tui-client/tui-subagents.ts@@ -34,11 +34,9 @@ process.env.EVE_TUI_UNICODE = "1";run({ app: "agent-tui-client", kind: "local-build" }, async (target) => {const client = new Client({ host: target.baseUrl });- const session = client.session();const screen = new MockScreen({ columns: 120, rows: 50 });const input = new MockUserInput();const runner = new EveTUIRunner({- session,client,screen,userInput: input,diff --git a/packages/eve/test/tui-client/tui-traces.ts b/packages/eve/test/tui-client/tui-traces.tsindex 04fd4d48c..8c6469609 100644--- a/packages/eve/test/tui-client/tui-traces.ts+++ b/packages/eve/test/tui-client/tui-traces.ts@@ -45,7 +45,6 @@ void (async () => {const screen = new MockScreen({ columns: 110, rows: 40 });const input = new MockUserInput();const runner = new EveTUIRunner({- session: client.session(),client,screen,userInput: input,@@ -329,7 +328,6 @@ function bootRunner(appRoot: string) {const screen = new MockScreen({ columns: 110, rows: 40 });const input = new MockUserInput();const runner = new EveTUIRunner({- session: client.session(),client,screen,userInput: input,diff --git a/packages/eve/test/tui-client/tui-transport-error.ts b/packages/eve/test/tui-client/tui-transport-error.tsindex 62fd993bd..bd8d9201c 100644--- a/packages/eve/test/tui-client/tui-transport-error.ts+++ b/packages/eve/test/tui-client/tui-transport-error.ts@@ -18,11 +18,9 @@ process.env.EVE_TUI_UNICODE = "1";void (async () => {const client = new Client({ host: UNREACHABLE_HOST });- const session = client.session();const screen = new MockScreen({ columns: 100, rows: 40 });const input = new MockUserInput();const runner = new EveTUIRunner({- session,client,screen,userInput: input,