Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat(eve): add prior history to sessions (#4477)

Ben Pankowb34844b6fb6c
diff --git a/.changeset/session-history-seeding.md b/.changeset/session-history-seeding.md
new file mode 100644
index 000000000..e09efd418
--- /dev/null
+++ b/.changeset/session-history-seeding.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Channel `send()`, channel message hooks, and a new `create()` on channel addresses accept `history` to add prior user and assistant messages, such as a stored transcript, as real turns. `create()` starts a session that waits for its first message and reports with `created` whether it did. A new `history.imported` stream event publishes added messages; the default client reducer renders them, and `transcriptReducer()` includes them. Slack `threadContext` now adds earlier replies as history when a message starts the thread's session; later messages keep the existing transcript.
diff --git a/docs/channels/eve.mdx b/docs/channels/eve.mdx
index 0597dc0e0..33b8a160e 100644
--- a/docs/channels/eve.mdx
+++ b/docs/channels/eve.mdx
@@ -368,6 +368,52 @@ export default eveChannel({
- eve labels client-supplied entries `Client context:` for the model. Returned context is sent without the label.
- `onMessage` runs only for requests with a message. An input response keeps the context its request sent.
+### Start from prior history
+
+Pass `history` to bring in conversation eve did not produce, such as a transcript your app stored, a conversation moving from another system, or a branch of an earlier exchange. The model sees each entry as a real user or assistant turn, not as a transcript inside one message.
+
+Create a session that starts from stored history and waits for its first message with `create()` on a channel address. No turn runs until a message arrives:
+
+```ts title="agent/channels/app.ts"
+import { defineChannel, POST } from "eve/channels";
+
+export default defineChannel({
+ routes: [
+ POST("/conversations/:id/session", async (req, { from, params }) => {
+ const auth = await authenticate(req);
+ // Load only conversations this caller may read.
+ const conversation = await db.conversations.findForUser(params.id!, auth);
+ const { created, session } = await from(`conversation:${conversation.id}`).create({
+ auth,
+ history: conversation.messages.map((message) => ({
+ id: message.id,
+ role: message.role, // "user" | "assistant"
+ text: message.body,
+ })),
+ });
+ if (!created) {
+ return Response.json({ error: "Conversation already has a session." }, { status: 409 });
+ }
+ return Response.json({ sessionId: session.id });
+ }),
+ ],
+});
+```
+
+The client then resumes that session by id, for example with `useEveAgent({ initialSession: { sessionId, streamIndex: 0 }, resume: true })`. `created` is `false` when a session already owned the address, or another `create()` or `send()` claimed it first. That session comes back unchanged and your `history` was not added, so check `created` before treating the session as seeded. Use a new address for each new conversation or branch.
+
+When the session at the address is [stranded](../concepts/execution-model-and-durability#stranded-sessions), `create()` throws `SessionStrandedError` instead of replacing it, because that session may hold the conversation you meant to import. Call `reset()` on the address, then `create()` again.
+
+`create()` returns once the new session claims its address, so a `send()` right after it reaches that session. It throws if no session claims the address within 15 seconds.
+
+`send()` accepts the same `history` option. The entries are added right before that message and its `context`, whether the send creates the session or continues it. The eve channel's `onMessage` can return `history` the same way. It applies to every message it is returned for, so return it only when the message should carry those turns.
+
+Each entry has a `role` of `"user"` or `"assistant"`, non-empty `text`, and an optional `id` that is unique within the call. Invalid history throws an `InvalidSessionHistoryError`, exported from `eve/channels`, that names the entry and the rule it broke. eve doesn't cap how many entries or how much text one call carries. Your route decides how much stored conversation to load, so trim long conversations there, for example to the newest messages. Tool calls, files, and reasoning are not supported.
+
+eve never accepts `history` from a client request body. Resolve it on the server and authorize the caller against the stored conversation.
+
+The stream publishes added entries in `history.imported`, right before the `message.received` of the turn they join. Each event message has the same `role`, `text`, and `id` you passed. `transcriptReducer()` from `eve/client` includes them, so its `{ role, text }` messages can be passed straight back as `history` to branch a session. The default client reducer renders them ahead of that turn's message with `metadata.imported` set and your `id` in `metadata.historyId`, so you can rejoin your own annotations. Message ids stay unique even when a later call reuses an `id`. After that, the entries are ordinary history: compaction, `clear()`, and handoffs treat them like any other turn.
+
## Clients
The browser side of this API lives in the [Frontend](../guides/frontend/overview) docs, where `useEveAgent` drives the eve channel from React UI.
diff --git a/docs/channels/slack.mdx b/docs/channels/slack.mdx
index fff12a8e1..93c826955 100644
--- a/docs/channels/slack.mdx
+++ b/docs/channels/slack.mdx
@@ -100,7 +100,7 @@ controls observability content capture, not access to the channel. See
### Message hooks
-Message hooks return `{ auth }` to dispatch, `null` to drop, or `{ auth, context }` to inject background into history. Public conversations use the returned `title`, or the triggering message text when `title` is omitted. DMs and private channels always use `Private message` so the run title does not expose message details.
+Message hooks return `{ auth }` to dispatch, `null` to drop, `{ auth, context }` to inject background into history, or `{ auth, history }` to add prior conversation as user and assistant turns (see [Start from prior history](./eve#start-from-prior-history)). Public conversations use the returned `title`, or the triggering message text when `title` is omitted. DMs and private channels always use `Private message` so the run title does not expose message details.
- `onMessage(ctx, message)` handles newly posted Slack messages. eve drops messages authored by the installed app before this hook runs, preventing self-reply loops. Messages from other bots remain visible; check `message.author?.isBot` when those should also be ignored. `ctx.isBotMentioned()` and `ctx.isSubscribed()` support mention and active-thread policies.
- `onAppMention(ctx, message)` handles only `app_mention` and takes precedence over `onMessage`. Its default derives workspace-scoped auth.
@@ -247,6 +247,8 @@ export default slackChannel({
`threadContext` requires the matching Slack history scope. Thread helpers reuse messages already loaded within the same inbound handler, and overlapping refreshes share one `conversations.replies` request. Omit it when the agent should see only direct mentions. `loadThreadContextMessages` remains available when you need custom filtering or non-model processing of the raw thread messages.
+When the triggering message starts the thread's session, eve adds those replies as session history instead of a transcript. Replies from this installed app become assistant turns, and replies from people and other bots become user messages with their Slack user ids attached. If the agent posted a report and people replied to it, the new session sees that report as its own earlier turn. Slack shows rendered output rather than the model's original response, so these assistant turns can differ from what the model wrote. Later messages in the same thread keep the transcript behavior above. When a hook returns its own `history`, eve keeps the transcript and does not add thread replies as history.
+
#### Control overlapping turns
Accepted Slack messages steer by default. Before assistant answer output or local tool execution begins, steering interrupts pending model generation and continues the same turn with the correction. Executing tools finish and checkpoint their results first; after answer output starts, steering waits for the next committed workflow boundary. Reasoning and search progress do not count as answer output, and interrupted provider-managed search may run again.
@@ -302,7 +304,7 @@ Reset returns `{ status: "reset", previousSessionId }` when the thread had a ses
### 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. Call `ctx.send(message, { target, auth, title })` zero, one, or many times to start turns. `title` sets the run title without changing the message sent to the model. Each call 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, title, history })` zero, one, or many times to start turns. `title` sets the run title without changing the message sent to the model, and `history` adds prior conversation before the message (see [Start from prior history](./eve#start-from-prior-history)). Each call returns the resulting session.
```ts title="agent/channels/slack.ts"
import { connectSlackCredentials } from "@vercel/connect/eve";
diff --git a/docs/concepts/execution-model-and-durability.mdx b/docs/concepts/execution-model-and-durability.mdx
index b5b965537..d24423b2c 100644
--- a/docs/concepts/execution-model-and-durability.mdx
+++ b/docs/concepts/execution-model-and-durability.mdx
@@ -66,6 +66,7 @@ See [How a stranded session ends](#how-a-stranded-session-ends) for the details.
For a root session, what happens next depends on how the message is addressed:
- **A channel address**, such as a Slack thread or any `from(address).send(...)`, resets the stranded session and starts a fresh session at the same address. The message becomes the fresh session's first turn. Concurrent messages to the address produce one fresh session. The fresh session names the session it replaced, whose recorded conversation your instructions can read; see [What a replacement session receives](#what-a-replacement-session-receives). A delivery that carries input responses, with or without a message, throws `SessionStrandedError` and leaves the stranded session in place, because a fresh session has no request for them to answer. See [custom channels](../channels/custom#channel-operations-and-session-handles).
+- **`create()` on a channel address** throws `SessionStrandedError` and leaves the stranded session in place. Call `reset()` on the address, then `create()` again; see [Start from prior history](../channels/eve#start-from-prior-history).
- **A session ID** is never reset implicitly. The eve HTTP channel returns `409` with `code: "session_stranded"` and the `eveVersion` that built the session when it recorded one. `Session.send()` and `Session.respond()` throw `SessionStrandedError` from `eve/channels`, and the TypeScript client's `ClientSession.send()` and `respond()` throw `ClientSessionStrandedError` from `eve/client`. Nothing is delivered, and the stranded run keeps its status and event log. See [Start and continue a session](../channels/eve#start-and-continue-a-session).
- **Following a stream** of a stranded session returns the same `409 session_stranded`. The TypeScript client stops reconnecting and reports `ClientSessionStrandedError`; the TUI explains how to recover. An existing connection learns this when it reconnects. Messages accepted before the upgrade are not redelivered.
- **Reading recorded history** still works. A bounded read (`stream({ follow: false })`, or `follow=false` on the stream route) returns the events recorded so far without inspecting or changing the session, so you can read a stranded conversation before deciding to reset it.
@@ -121,7 +122,7 @@ export default defineDynamic({
The resolver runs before the replacement's first model call, and its result enters the replacement's durable history once, ahead of the new message. In a session that replaced no other, `ctx.session.predecessor` is undefined and the instruction contributes nothing.
-`transcriptReducer()` keeps user message text and completed assistant text, oldest first, as `{ role, text }` messages. Reasoning, tool calls and results, attachments, approvals, and output from a turn that never completed are left out. A clear in the stranded session starts the transcript over, so text the user cleared is never returned. `maxMessages` keeps only the newest messages.
+`transcriptReducer()` keeps history added with `history`, user message text, and completed assistant text, oldest first, as `{ role, text }` messages. Reasoning, tool calls and results, attachments, approvals, and output from a turn that never completed are left out. A clear in the stranded session starts the transcript over, so text the user cleared is never returned. `maxMessages` keeps only the newest messages.
The read and the prompt are yours to bound:
diff --git a/docs/concepts/sessions-runs-and-streaming.md b/docs/concepts/sessions-runs-and-streaming.md
index 4a780a40c..4dec737ba 100644
--- a/docs/concepts/sessions-runs-and-streaming.md
+++ b/docs/concepts/sessions-runs-and-streaming.md
@@ -70,6 +70,7 @@ The stream is newline-delimited JSON (NDJSON), one event per line:
| Event | Meaning |
| ------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `session.started` | A durable session was created; carries `trace` when the runtime is traced, and `predecessor` when the session [replaced a stranded one](./execution-model-and-durability#what-a-replacement-session-receives). |
+| `history.imported` | A delivery added prior conversation with `history`; carries each message's `role`, `content`, and optional `id`. Precedes that delivery's `message.received` in the same turn. |
| `turn.started` | A new turn began; carries the active `trace` when the runtime is traced. |
| `message.received` | Input reached a turn; carries flattened text plus structured text/file parts. |
| `step.started` | A model step began. |
diff --git a/docs/guides/client/streaming.mdx b/docs/guides/client/streaming.mdx
index 2a00e12ca..ae326451e 100644
--- a/docs/guides/client/streaming.mdx
+++ b/docs/guides/client/streaming.mdx
@@ -136,6 +136,7 @@ The most common UI events are:
| Event | Use |
| ----------------------- | ------------------------------------------------------------------------------ |
+| `history.imported` | Render prior conversation a delivery added, before that turn's message. |
| `message.received` | Confirm the user message landed; `data.parts` includes text and file metadata. |
| `reasoning.appended` | Render reasoning deltas when the model provides them. |
| `message.appended` | Render assistant text deltas. |
diff --git a/e2e/fixtures/agent-channels/agent/agent.ts b/e2e/fixtures/agent-channels/agent/agent.ts
index 6ee424a36..5a37c0c6a 100644
--- a/e2e/fixtures/agent-channels/agent/agent.ts
+++ b/e2e/fixtures/agent-channels/agent/agent.ts
@@ -3,7 +3,12 @@ import { defineAgent } from "eve";
export default defineAgent({
...e2eAgentConfig({
- mock: ({ lastUserMessage }) => `Mock reply: ${lastUserMessage ?? ""}`,
+ // A recall question answers from the latest earlier assistant turn, so seeded history is
+ // observable without a live model.
+ mock: ({ lastUserMessage, messages }) =>
+ lastUserMessage?.includes("code word")
+ ? `Mock reply: ${[...messages].reverse().find((message) => message.role === "assistant")?.text ?? ""}`
+ : `Mock reply: ${lastUserMessage ?? ""}`,
}),
reasoning: "high",
});
diff --git a/e2e/fixtures/agent-channels/agent/channels/seeded.ts b/e2e/fixtures/agent-channels/agent/channels/seeded.ts
new file mode 100644
index 000000000..950767aa8
--- /dev/null
+++ b/e2e/fixtures/agent-channels/agent/channels/seeded.ts
@@ -0,0 +1,53 @@
+import { defineChannel, POST } from "eve/channels";
+
+const AUTH = {
+ attributes: {},
+ authenticator: "seeded",
+ principalId: "seeded-history-eval",
+ principalType: "service",
+} as const;
+
+const ALICE_EARLIER = [
+ {
+ id: "alice-1",
+ role: "user",
+ text: "Hi, this is Alice. Which code word should the launch checklist use?",
+ },
+ { id: "agent-1", role: "assistant", text: "Alice, the launch checklist code word is heron." },
+] as const;
+
+const BOB_LATER = [
+ { id: "bob-1", role: "user", text: "Hi, this is Bob. Please rotate the checklist code word." },
+ { id: "agent-2", role: "assistant", text: "Done, Bob. The checklist code word is now egret." },
+] as const;
+
+/**
+ * An app that stores its own transcripts: `create` starts a session from
+ * Alice's earlier conversation, and `send` can carry a later exchange with
+ * Bob that happened elsewhere.
+ */
+export default defineChannel({
+ routes: [
+ POST("/seeded", async (req, { from }) => {
+ const body = (await req.json().catch(() => ({}))) as {
+ message?: string;
+ mode?: "create" | "send";
+ sessionRef?: string;
+ withBob?: boolean;
+ };
+ const address = from(`seeded:${body.sessionRef ?? crypto.randomUUID()}`);
+ if (body.mode === "create") {
+ const { created, session } = await address.create({
+ auth: AUTH,
+ history: [...ALICE_EARLIER],
+ });
+ return Response.json({ created, ok: true, sessionId: session.id });
+ }
+ const session = await address.send(body.message ?? "What did we agree on?", {
+ auth: AUTH,
+ history: body.withBob === true ? [...BOB_LATER] : undefined,
+ });
+ return Response.json({ ok: true, sessionId: session.id });
+ }),
+ ],
+});
diff --git a/e2e/fixtures/agent-channels/evals/seeded-history/seeded-history.eval.ts b/e2e/fixtures/agent-channels/evals/seeded-history/seeded-history.eval.ts
new file mode 100644
index 000000000..e3832db56
--- /dev/null
+++ b/e2e/fixtures/agent-channels/evals/seeded-history/seeded-history.eval.ts
@@ -0,0 +1,64 @@
+import { defineEval } from "eve/evals";
+import { equals, satisfies } from "eve/evals/expect";
+
+import { postChannel } from "../custom-channels/shared";
+
+type MessageResponse = { created?: boolean; ok: boolean; sessionId?: string };
+
+function importedBeforeReceived(types: readonly string[]): boolean {
+ const imported = types.indexOf("history.imported");
+ return imported !== -1 && imported < types.indexOf("message.received");
+}
+
+/**
+ * History passed to `create()` and `send()` becomes real prior conversation:
+ * the stream publishes it before the turn it joins, and the agent answers
+ * from it.
+ */
+export default defineEval({
+ description: "A channel starts a session from prior history and adds more on a later message.",
+
+ async test(t) {
+ const sessionRef = crypto.randomUUID();
+ const created = await postChannel<MessageResponse>(t.target, "/seeded", {
+ mode: "create",
+ sessionRef,
+ });
+ await t.require(
+ created,
+ satisfies(
+ (value: MessageResponse) =>
+ value.ok === true && value.created === true && typeof value.sessionId === "string",
+ "create() creates a session",
+ ),
+ );
+
+ const firstTurn = t.target.watchTurn(created.sessionId!);
+ const first = await postChannel<MessageResponse>(t.target, "/seeded", {
+ message: "Alice again. What was the code word you gave me earlier? Reply with just the word.",
+ sessionRef,
+ });
+ await t.require(first.sessionId, equals(created.sessionId));
+ const turn = await firstTurn.result();
+ turn.succeeded();
+ await t.require(
+ turn.events.map((event) => event.type),
+ satisfies(importedBeforeReceived, "created history precedes the first message"),
+ );
+ turn.messageIncludes("heron");
+
+ const laterTurn = t.target.watchTurn(created.sessionId!, { startIndex: turn.events.length });
+ await postChannel<MessageResponse>(t.target, "/seeded", {
+ message: "Alice here. What is the checklist code word now? Reply with just the word.",
+ sessionRef,
+ withBob: true,
+ });
+ const later = await laterTurn.result();
+ later.succeeded();
+ await t.require(
+ later.events.map((event) => event.type),
+ satisfies(importedBeforeReceived, "sent history precedes its message"),
+ );
+ later.messageIncludes("egret");
+ },
+});
diff --git a/packages/eve/extension-contracts/compatibility/channel/v62.ts b/packages/eve/extension-contracts/compatibility/channel/v62.ts
new file mode 100644
index 000000000..312a16bcd
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/channel/v62.ts
@@ -0,0 +1,13 @@
+import { defineChannel, POST } from "#public/channels/index.js";
+
+// Epoch 62 had no `history` option, `create()`, or `history.imported` event; epoch 63 adds them, which is additive.
+export default defineChannel({
+ routes: [POST("/report", async () => new Response("ok"))],
+ state: { reply: "" },
+ context: (state) => state,
+ events: {
+ "message.completed"({ message }, channel, ctx) {
+ channel.reply = `${ctx.session.id}: ${message}`;
+ },
+ },
+});
diff --git a/packages/eve/extension-contracts/compatibility/connection/v51.ts b/packages/eve/extension-contracts/compatibility/connection/v51.ts
new file mode 100644
index 000000000..0570f7982
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/connection/v51.ts
@@ -0,0 +1,9 @@
+import { defineMcpClientConnection } from "#public/connections/index.js";
+
+// Epoch 51 had no `history` option or `history.imported` event; epoch 52 adds both, which is additive.
+export default defineMcpClientConnection({
+ description: "Specialist tools.",
+ url: "https://specialist.example.test/eve/v1/mcp",
+ protocolVersionDiscovery: false,
+ approval: ({ session }) => (session.auth.current === null ? "denied" : "user-approval"),
+});
diff --git a/packages/eve/extension-contracts/compatibility/dynamicInstructions/v40.ts b/packages/eve/extension-contracts/compatibility/dynamicInstructions/v40.ts
new file mode 100644
index 000000000..d20267d02
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/dynamicInstructions/v40.ts
@@ -0,0 +1,9 @@
+import { defineDynamic, defineInstructions } from "#public/instructions/index.js";
+
+// Epoch 40 had no `history` option or `history.imported` event; epoch 41 adds both, which is additive.
+export default defineDynamic({
+ events: {
+ "turn.started": (_event, ctx) =>
+ defineInstructions({ markdown: `Review evidence for session ${ctx.session.id}.` }),
+ },
+});
diff --git a/packages/eve/extension-contracts/compatibility/dynamicSkill/v39.ts b/packages/eve/extension-contracts/compatibility/dynamicSkill/v39.ts
new file mode 100644
index 000000000..684bc8369
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/dynamicSkill/v39.ts
@@ -0,0 +1,12 @@
+import { defineDynamic, defineSkill } from "#public/skills/index.js";
+
+// Epoch 39 had no `history` option or `history.imported` event; epoch 40 adds both, which is additive.
+export default defineDynamic({
+ events: {
+ "turn.started": (_event, ctx) =>
+ defineSkill({
+ description: `Review evidence for session ${ctx.session.id}.`,
+ markdown: "Check claims against sources.",
+ }),
+ },
+});
diff --git a/packages/eve/extension-contracts/compatibility/dynamicTool/v87.ts b/packages/eve/extension-contracts/compatibility/dynamicTool/v87.ts
new file mode 100644
index 000000000..c86258d3b
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/dynamicTool/v87.ts
@@ -0,0 +1,13 @@
+import { defineDynamic, defineTool } from "#public/tools/index.js";
+
+// Epoch 87 had no `history` option or `history.imported` event; epoch 88 adds both, which is additive.
+export default defineDynamic({
+ events: {
+ "turn.started": (_event, ctx) =>
+ defineTool({
+ description: "Report the current session.",
+ inputSchema: { type: "object", properties: {} },
+ execute: () => ({ sessionId: ctx.session.id }),
+ }),
+ },
+});
diff --git a/packages/eve/extension-contracts/compatibility/hook/v47.ts b/packages/eve/extension-contracts/compatibility/hook/v47.ts
new file mode 100644
index 000000000..1d8a911ce
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/hook/v47.ts
@@ -0,0 +1,10 @@
+import { defineHook } from "#public/hooks/index.js";
+
+// Epoch 47 had no `history` option or `history.imported` event; epoch 48 adds both, which is additive.
+export default defineHook({
+ events: {
+ "authorization.required": (event, ctx) => {
+ console.info("Sign-in required", { name: event.data.name, sessionId: ctx.session.id });
+ },
+ },
+});
diff --git a/packages/eve/extension-contracts/compatibility/schedule/v34.ts b/packages/eve/extension-contracts/compatibility/schedule/v34.ts
new file mode 100644
index 000000000..bafc5b1f6
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/schedule/v34.ts
@@ -0,0 +1,22 @@
+import { defineChannel } from "#public/channels/index.js";
+import { defineSchedule } from "#public/schedules/index.js";
+
+// Epoch 34 had no `history` option or `history.imported` event; epoch 35 adds both, which is additive.
+const updates = defineChannel({
+ routes: [],
+ events: {
+ "authorization.required"(event) {
+ console.info("sign-in required", { name: event.name });
+ },
+ },
+ receive(input, { from }) {
+ return from("daily-updates").send(input.message, { auth: input.auth });
+ },
+});
+
+export default defineSchedule({
+ cron: "0 9 * * *",
+ async run({ to, appAuth }) {
+ await to(updates, {}).send("Prepare the daily summary.", { auth: appAuth });
+ },
+});
diff --git a/packages/eve/extension-contracts/compatibility/subagent/v39.ts b/packages/eve/extension-contracts/compatibility/subagent/v39.ts
new file mode 100644
index 000000000..e0286c169
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/subagent/v39.ts
@@ -0,0 +1,14 @@
+import { defineAgent, defineDynamic } from "#public/index.js";
+
+// Epoch 39 had no `history` option or `history.imported` event; epoch 40 adds both, which is additive.
+export default defineDynamic({
+ events: {
+ "turn.started": (_event, ctx) =>
+ ctx.session.auth.current === null
+ ? null
+ : defineAgent({
+ description: "Investigate the authenticated request.",
+ model: "openai/gpt-5.6-sol",
+ }),
+ },
+});
diff --git a/packages/eve/extension-contracts/compatibility/tool/v93.ts b/packages/eve/extension-contracts/compatibility/tool/v93.ts
new file mode 100644
index 000000000..1fbc03095
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/tool/v93.ts
@@ -0,0 +1,10 @@
+import { z } from "zod";
+import { defineTool } from "#public/tools/index.js";
+
+// Epoch 93 had no `history` option or `history.imported` event; epoch 94 adds both, which is additive.
+export default defineTool({
+ description: "Report the authenticated caller.",
+ inputSchema: z.object({}),
+ outputSchema: z.object({ principalId: z.string().nullable() }),
+ execute: (_input, ctx) => ({ principalId: ctx.session.auth.current?.principalId ?? null }),
+});
diff --git a/packages/eve/extension-contracts/entrypoints/channel.ts b/packages/eve/extension-contracts/entrypoints/channel.ts
index 1502b04d1..235a87f85 100644
--- a/packages/eve/extension-contracts/entrypoints/channel.ts
+++ b/packages/eve/extension-contracts/entrypoints/channel.ts
@@ -2,6 +2,7 @@ export {
DELETE,
GET,
HEAD,
+ InvalidSessionHistoryError,
OPTIONS,
PATCH,
POST,
diff --git a/packages/eve/extension-contracts/reports/channel/v63.json b/packages/eve/extension-contracts/reports/channel/v63.json
new file mode 100644
index 000000000..6e8ec08ce
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/channel/v63.json
@@ -0,0 +1,24 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "channel",
+ "epoch": 63,
+ "sha256": "5a1344c9fc70b1279f6b9d371b8b8b10e27411003830f3b4c17d30f5c6dc441d",
+ "exports": [
+ "DELETE",
+ "GET",
+ "HEAD",
+ "InvalidSessionHistoryError",
+ "OPTIONS",
+ "PATCH",
+ "POST",
+ "PUT",
+ "SessionStrandedError",
+ "WS",
+ "attachmentError",
+ "createWebSocketUpgradeServer",
+ "defineChannel",
+ "disableRoute",
+ "isChannel",
+ "isDisabledRouteSentinel"
+ ]
+}
diff --git a/packages/eve/extension-contracts/reports/connection/v52.json b/packages/eve/extension-contracts/reports/connection/v52.json
new file mode 100644
index 000000000..fea7bfa08
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/connection/v52.json
@@ -0,0 +1,16 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "connection",
+ "epoch": 52,
+ "sha256": "a2fe6d7e4ef778f7354b6822a6989118e97859589dd936b64d65c6058fa99efc",
+ "exports": [
+ "ConnectionAuthorizationFailedError",
+ "ConnectionAuthorizationRequiredError",
+ "defineDynamic",
+ "defineInteractiveAuthorization",
+ "defineMcpClientConnection",
+ "defineOpenAPIConnection",
+ "isConnectionAuthorizationFailedError",
+ "isConnectionAuthorizationRequiredError"
+ ]
+}
diff --git a/packages/eve/extension-contracts/reports/dynamicInstructions/v41.json b/packages/eve/extension-contracts/reports/dynamicInstructions/v41.json
new file mode 100644
index 000000000..76b67b148
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/dynamicInstructions/v41.json
@@ -0,0 +1,7 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "dynamicInstructions",
+ "epoch": 41,
+ "sha256": "3bc1cb6fb1f1dfd24936c24afa9f98db0e48da6ba986be488b1b177700a1f9bb",
+ "exports": ["defineDynamic"]
+}
diff --git a/packages/eve/extension-contracts/reports/dynamicSkill/v40.json b/packages/eve/extension-contracts/reports/dynamicSkill/v40.json
new file mode 100644
index 000000000..23e31fd22
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/dynamicSkill/v40.json
@@ -0,0 +1,7 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "dynamicSkill",
+ "epoch": 40,
+ "sha256": "70ce0c6926c00439f4a243e5a8012188b99e90019cc47df4df17229c1bb24498",
+ "exports": ["defineDynamic"]
+}
diff --git a/packages/eve/extension-contracts/reports/dynamicTool/v88.json b/packages/eve/extension-contracts/reports/dynamicTool/v88.json
new file mode 100644
index 000000000..e3f8ee045
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/dynamicTool/v88.json
@@ -0,0 +1,16 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "dynamicTool",
+ "epoch": 88,
+ "sha256": "0fda54e2c762bc1c46863f8363168c4ccbfa5be295482b902eadde2b44311c77",
+ "exports": [
+ "DynamicToolEntry",
+ "DynamicToolEvents",
+ "DynamicToolResult",
+ "DynamicToolSet",
+ "auto",
+ "defineDurableCallback",
+ "defineDurableSchema",
+ "defineDynamic"
+ ]
+}
diff --git a/packages/eve/extension-contracts/reports/hook/v48.json b/packages/eve/extension-contracts/reports/hook/v48.json
new file mode 100644
index 000000000..d84714c58
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/hook/v48.json
@@ -0,0 +1,7 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "hook",
+ "epoch": 48,
+ "sha256": "8f51368ccdf0fe774b2f04092b65d14f702e2f25d488bf07eaa029c261b35b68",
+ "exports": ["defineHook"]
+}
diff --git a/packages/eve/extension-contracts/reports/schedule/v35.json b/packages/eve/extension-contracts/reports/schedule/v35.json
new file mode 100644
index 000000000..4da28daf5
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/schedule/v35.json
@@ -0,0 +1,15 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "schedule",
+ "epoch": 35,
+ "sha256": "a26d62eddb0048af313ce54a2a252a369b1bd028e86737a2533a6b2ce639cabe",
+ "exports": [
+ "ScheduleDefinition",
+ "ScheduleHandlerArgs",
+ "ScheduleRunHandler",
+ "ScheduleToFn",
+ "TypedReceiveTarget",
+ "defineSchedule",
+ "isScheduleAuth"
+ ]
+}
diff --git a/packages/eve/extension-contracts/reports/subagent/v40.json b/packages/eve/extension-contracts/reports/subagent/v40.json
new file mode 100644
index 000000000..bdc926a8e
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/subagent/v40.json
@@ -0,0 +1,23 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "subagent",
+ "epoch": 40,
+ "sha256": "e078c4da161b52171ea65bc44b4482bce23043aeb17234682f9d5b0dbf8ebbdb",
+ "exports": [
+ "AgentCompactionDefinition",
+ "AgentDefinition",
+ "AgentModelDefinition",
+ "AgentStaticModelDefinition",
+ "DefinedAgent",
+ "DynamicLocalSubagentDefinition",
+ "DynamicSubagentDefinition",
+ "RemoteAgentDefinition",
+ "RemoteAgentDefinitionInput",
+ "WorkspaceAgentDefinition",
+ "WorkspaceAgentTransport",
+ "defineAgent",
+ "defineDynamic",
+ "defineRemoteAgent",
+ "defineWorkspaceAgent"
+ ]
+}
diff --git a/packages/eve/extension-contracts/reports/tool/v94.json b/packages/eve/extension-contracts/reports/tool/v94.json
new file mode 100644
index 000000000..e7bed3804
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/tool/v94.json
@@ -0,0 +1,29 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "tool",
+ "epoch": 94,
+ "sha256": "6d0150923572c56be721492921c1f5de952e1204a041096f2e97ea108d17374e",
+ "exports": [
+ "AgentRouterInput",
+ "AgentRouterTool",
+ "WorkflowStepToolContext",
+ "WorkflowTool",
+ "WorkflowToolDefinition",
+ "WorkflowToolInput",
+ "WorkflowToolOptions",
+ "agentRouter",
+ "decide",
+ "defaultWebSearch",
+ "defineTool",
+ "defineWorkflowTool",
+ "disableTool",
+ "isDisabledToolSentinel",
+ "isWebSearchToolDefinition",
+ "serializeModelInputSchema",
+ "toolOutput",
+ "toolOutputPart",
+ "toolResultFrom",
+ "webSearch",
+ "workflow"
+ ]
+}
diff --git a/packages/eve/src/channel/channel-address.test.ts b/packages/eve/src/channel/channel-address.test.ts
index a06968863..949f15cd2 100644
--- a/packages/eve/src/channel/channel-address.test.ts
+++ b/packages/eve/src/channel/channel-address.test.ts
@@ -175,4 +175,44 @@ describe("createChannelAddress", () => {
sessionId: "sess_2",
});
});
+
+ it("reports whether create() started the session that owns the address", async () => {
+ const history = [{ text: "Earlier", role: "user" as const }];
+ const create = async (owners: readonly (string | undefined)[]) => {
+ const runtime = createRuntime();
+ vi.mocked(runtime.createSession).mockResolvedValue({
+ events: new ReadableStream(),
+ sessionId: "sess_started",
+ });
+ for (const owner of owners) {
+ vi.mocked(runtime.resolveContinuation).mockResolvedValueOnce(
+ owner === undefined ? undefined : { sessionId: owner },
+ );
+ }
+ const address = createChannelAddress({
+ adapter: { kind: "http" },
+ channelName: "app",
+ continuationToken: "conversation:1",
+ runtime,
+ });
+ const result = await address.create({ auth: null, history });
+ return { created: result.created, runtime, sessionId: result.session.id };
+ };
+
+ const won = await create([undefined, "sess_started"]);
+ expect(won).toMatchObject({ created: true, sessionId: "sess_started" });
+ expect(won.runtime.createSession).toHaveBeenCalledWith(
+ expect.objectContaining({ continuationToken: "app:conversation:1", input: { history } }),
+ );
+
+ // A concurrent send() or create() claimed the address first; this run's history never landed.
+ await expect(create([undefined, "sess_other"])).resolves.toMatchObject({
+ created: false,
+ sessionId: "sess_other",
+ });
+
+ const owned = await create(["sess_owner"]);
+ expect(owned).toMatchObject({ created: false, sessionId: "sess_owner" });
+ expect(owned.runtime.createSession).not.toHaveBeenCalled();
+ });
});
diff --git a/packages/eve/src/channel/channel-address.ts b/packages/eve/src/channel/channel-address.ts
index bac99bff1..fa6450a46 100644
--- a/packages/eve/src/channel/channel-address.ts
+++ b/packages/eve/src/channel/channel-address.ts
@@ -9,6 +9,7 @@ import type { SendPayload } from "#channel/routes.js";
import { normalizeSendInput, serializeFilePartsInMessage } from "#channel/send-input.js";
import { createSession, sessionCallbackToTurnCaller, type Session } from "#channel/session.js";
import { SessionNotActiveError } from "#channel/session-not-active-error.js";
+import { describeStrandedSession, SessionStrandedError } from "#channel/session-stranded-error.js";
import type {
CancelTurnResult,
ClearSessionResult,
@@ -23,6 +24,18 @@ import type {
} from "#channel/types.js";
import { DEFAULT_TURN_POLICY } from "#channel/types.js";
import { isReservedSessionCommandToken } from "#execution/session-inbox/address.js";
+import { validateSessionHistory } from "#shared/session-history.js";
+
+interface BaseChannelAddressCreateOptions {
+ readonly auth: SessionAuthContext | null;
+ readonly history?: SendPayload["history"];
+ readonly initiatorAuth?: SessionAuthContext | null;
+ readonly title?: string;
+}
+
+type ChannelAddressCreateOptions<TState = undefined> = [TState] extends [undefined]
+ ? BaseChannelAddressCreateOptions
+ : BaseChannelAddressCreateOptions & { readonly state?: Partial<TState> };
interface BaseChannelAddressDeliveryOptions {
readonly auth: SessionAuthContext | null;
@@ -32,6 +45,15 @@ interface BaseChannelAddressDeliveryOptions {
readonly turnPolicy?: TurnPolicy;
}
+/**
+ * Result of `create()`. `created` is `false` when another session already owned the address, or
+ * won it concurrently; that session is returned unchanged and any `history` was not added.
+ */
+export interface ChannelCreateResult {
+ readonly created: boolean;
+ readonly session: Session;
+}
+
/** Delivery options for a channel address whose continuation token is already bound. */
export type ChannelAddressDeliveryOptions<TState = undefined> = [TState] extends [undefined]
? BaseChannelAddressDeliveryOptions
@@ -39,14 +61,15 @@ export type ChannelAddressDeliveryOptions<TState = undefined> = [TState] extends
/**
* Dynamic handle for whichever durable session currently owns one channel-local address.
- * Only {@link send} may create a session: when the address is unowned, or in
- * place of a stranded session that another eve version built. Sends to a session whose
+ * Only {@link create} and {@link send} may create a session: when the address is unowned, and
+ * `send` also in place of a stranded session that another eve version built. Sends to a session whose
* owner is only unavailable throw `SessionStrandedError` and deliver nothing.
* Responses to an address no session holds throw `SessionNotActiveError`.
*/
interface ChannelAddress<TState = undefined> {
readonly continuationToken: string;
deliver(input: SendPayload, options: ChannelAddressDeliveryOptions<TState>): Promise<Session>;
+ create(options: ChannelAddressCreateOptions<TState>): Promise<ChannelCreateResult>;
send(
message: string | UserContent,
options: ChannelAddressDeliveryOptions<TState>,
@@ -87,7 +110,7 @@ export function createChannelAddress<TState = undefined>(input: {
metadata.channelKind !== undefined && metadata.channelName !== undefined
? createChannelDeliveryMetadata(metadata as ChannelDeliverySource)
: undefined;
- const payload = normalizeSendInput(sendInput);
+ const payload = withValidatedHistory(normalizeSendInput(sendInput));
const caller = sessionCallbackToTurnCaller(options.callback);
const commandWithoutCaller = {
auth: options.auth,
@@ -125,6 +148,7 @@ export function createChannelAddress<TState = undefined>(input: {
initiatorAuth: options.initiatorAuth,
input: {
context: payload.context,
+ history: payload.history,
message: serializeFilePartsInMessage(payload.message) ?? "",
outputSchema: payload.outputSchema,
state: payload.state,
@@ -146,6 +170,56 @@ export function createChannelAddress<TState = undefined>(input: {
}
return toSession((await input.runtime.createSession(runInput)).sessionId);
},
+ async create(options) {
+ const history = validateSessionHistory(options.history);
+ const toSession = (sessionId: string) =>
+ createSession(sessionId, input.runtime, { ...metadata, turnPolicy: input.turnPolicy });
+ let owner: { readonly sessionId: string } | undefined;
+ try {
+ owner = await input.runtime.resolveContinuation(namespacedToken, { runnable: true });
+ } catch (error) {
+ // Replacing a stranded session would end a conversation the caller may mean to import.
+ if (!SessionStrandedError.is(error)) throw error;
+ throw new SessionStrandedError(
+ error.owner,
+ describeStrandedSession(
+ error.owner,
+ "Call reset() on the address, then create() again to start a session from your history.",
+ ),
+ );
+ }
+ if (owner !== undefined) return { created: false, session: toSession(owner.sessionId) };
+ const state = (options as { readonly state?: TState }).state;
+ const started = await input.runtime.createSession({
+ adapter:
+ state === undefined
+ ? input.adapter
+ : {
+ ...input.adapter,
+ state: { ...input.adapter.state, ...(state as Record<string, unknown>) },
+ },
+ auth: options.auth,
+ capabilities: { requestInput: true },
+ channelName: input.channelName,
+ continuationToken: namespacedToken,
+ initiatorAuth: options.initiatorAuth,
+ input: history === undefined ? {} : { history },
+ requestId: metadata.requestId,
+ title: options.title,
+ });
+ // The new run claims the address asynchronously, and a concurrent `create()` or `send()`
+ // may claim it first. Waiting for the owner lets an immediate `send()` find it, and tells
+ // the caller whether its history landed: a losing run exits without forwarding anything.
+ const claimed = await waitForContinuationOwner(
+ input.runtime,
+ namespacedToken,
+ started.sessionId,
+ );
+ return {
+ created: claimed.sessionId === started.sessionId,
+ session: toSession(claimed.sessionId),
+ };
+ },
async send(message, options) {
return await this.deliver({ message }, options);
},
@@ -201,3 +275,31 @@ export function createChannelAddressFn<TState = undefined>(input: {
}): ChannelAddressFn<TState> {
return (continuationToken) => createChannelAddress({ ...input, continuationToken });
}
+
+function withValidatedHistory(payload: SendPayload): SendPayload {
+ const { history, ...rest } = payload;
+ const validated = validateSessionHistory(history);
+ return validated === undefined ? rest : { ...rest, history: validated };
+}
+
+const CREATE_CLAIM_TIMEOUT_MS = 15_000;
+
+async function waitForContinuationOwner(
+ runtime: Runtime,
+ continuationToken: string,
+ startedSessionId: string,
+): Promise<{ readonly sessionId: string }> {
+ const deadline = Date.now() + CREATE_CLAIM_TIMEOUT_MS;
+ for (let delayMs = 25; ; delayMs = Math.min(delayMs * 2, 500)) {
+ const owner = await runtime.resolveContinuation(continuationToken);
+ if (owner !== undefined) return owner;
+ if (Date.now() + delayMs > deadline) {
+ // Unclaimed, the address may still go to this run or to a concurrent one, so neither
+ // `created` value would be true yet.
+ throw new Error(
+ `create() started session "${startedSessionId}" for "${continuationToken}", but no session claimed the address within ${CREATE_CLAIM_TIMEOUT_MS / 1000}s. Call resolveSession() on the address to find its owner once one does.`,
+ );
+ }
+ await new Promise((resolve) => setTimeout(resolve, delayMs));
+ }
+}
diff --git a/packages/eve/src/channel/channel-operations.ts b/packages/eve/src/channel/channel-operations.ts
index 2e375f844..b6a647ebf 100644
--- a/packages/eve/src/channel/channel-operations.ts
+++ b/packages/eve/src/channel/channel-operations.ts
@@ -2,7 +2,9 @@ import type { UserContent } from "ai";
import type { ChannelAdapter } from "#channel/adapter.js";
import type { ChannelDeliverySource } from "#channel/delivery-metadata.js";
-import { createChannelAddressFn } from "#channel/channel-address.js";
+import { type ChannelCreateResult, createChannelAddressFn } from "#channel/channel-address.js";
+
+export type { ChannelCreateResult } from "#channel/channel-address.js";
import type { Session } from "#channel/session.js";
import type {
CancelTurnResult,
@@ -20,12 +22,19 @@ import {
type StrictInputResponses,
} from "#shared/input.js";
import type { JsonObject } from "#shared/json.js";
+import type { SessionHistoryMessage } from "#shared/session-history.js";
import { attachInputText, readInputText } from "#internal/input-text.js";
interface BaseChannelSendOptions {
readonly auth: SessionAuthContext | null;
readonly callback?: SessionCallback;
readonly context?: readonly string[];
+ /**
+ * Prior conversation added as user and assistant turns before this
+ * message and its `context`. Seeds a session this send creates, or
+ * extends the history of the session that owns the address.
+ */
+ readonly history?: readonly SessionHistoryMessage[];
readonly initiatorAuth?: SessionAuthContext | null;
/** JSON Schema for a structured final answer, as on `Session.send()`. */
readonly outputSchema?: JsonObject;
@@ -47,10 +56,31 @@ interface BaseChannelRespondOptions<TState = undefined> {
/** Options for answering pending input requests at an existing continuation address. */
export type ChannelRespondOptions<TState = undefined> = BaseChannelRespondOptions<TState>;
+interface BaseChannelCreateOptions {
+ readonly auth: SessionAuthContext | null;
+ /** Prior conversation the session starts with; it joins history with the first message. */
+ readonly history?: readonly SessionHistoryMessage[];
+ readonly initiatorAuth?: SessionAuthContext | null;
+ readonly title?: string;
+}
+
+/** Options for creating a session at a channel-local address without running a turn. */
+export type ChannelCreateOptions<TState = undefined> = [TState] extends [undefined]
+ ? BaseChannelCreateOptions
+ : BaseChannelCreateOptions & { readonly state: TState };
+
/** 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>;
+ /**
+ * Creates a session that waits for its first message, without running a
+ * turn. When another session owns the address, or claims it concurrently,
+ * returns that session unchanged with `created: false`; its `history` was not
+ * added. Throws `SessionStrandedError` when the owner is stranded; reset the
+ * address, then create again.
+ */
+ create(options: ChannelCreateOptions<TState>): Promise<ChannelCreateResult>;
/** Answers pending input requests. Never creates a session. */
respond<const TResponses extends readonly InputResponse[]>(
inputResponses: StrictInputResponses<TResponses>,
@@ -99,6 +129,7 @@ export function createChannelOperations<TState = undefined>(input: {
attachInputText(
{
context: options.context,
+ history: options.history,
message,
outputSchema: options.outputSchema,
state: (options as { readonly state?: TState }).state,
@@ -108,6 +139,9 @@ export function createChannelOperations<TState = undefined>(input: {
options,
);
},
+ async create(options) {
+ return await bound.create(options);
+ },
async respond(inputResponses, options) {
if (inputResponses.length === 0) {
throw new Error("respond() requires at least one input response.");
diff --git a/packages/eve/src/channel/routes.ts b/packages/eve/src/channel/routes.ts
index ac9c07e80..6d7b01d6b 100644
--- a/packages/eve/src/channel/routes.ts
+++ b/packages/eve/src/channel/routes.ts
@@ -6,6 +6,7 @@ import type { InvokeToolFn } from "#channel/invoke-tool.js";
import type { InputResponse } from "#shared/input.js";
import type { Session } from "#channel/session.js";
import type { JsonObject } from "#shared/json.js";
+import type { SessionHistoryMessage } from "#shared/session-history.js";
import type { ChannelMethod } from "#public/definitions/channel.js";
import type { AgentDescription, AgentSkillFileDescription } from "#channel/agent-description.js";
@@ -69,6 +70,11 @@ export interface SendPayload {
* message and persists it across the session.
*/
readonly context?: readonly string[];
+ /**
+ * Prior conversation added as user and assistant turns before this
+ * delivery's `context` and message.
+ */
+ readonly history?: readonly SessionHistoryMessage[];
/**
* Run-scoped JSON schema the turn's result must match.
*/
diff --git a/packages/eve/src/channel/session.ts b/packages/eve/src/channel/session.ts
index 74683f6d6..5434436a3 100644
--- a/packages/eve/src/channel/session.ts
+++ b/packages/eve/src/channel/session.ts
@@ -34,6 +34,7 @@ import {
type StrictInputResponses,
} from "#shared/input.js";
import type { JsonObject } from "#shared/json.js";
+import { type SessionHistoryMessage, validateSessionHistory } from "#shared/session-history.js";
import { toChannelLocalContinuationToken } from "#shared/continuation-token.js";
import { attachClientContext, readClientContext } from "#internal/client-context.js";
@@ -81,6 +82,8 @@ interface SessionDeliveryOptions {
/** Options for sending a message through a fixed session handle. */
export type SessionSendOptions = SessionDeliveryOptions & {
+ /** Prior conversation added as user and assistant turns before this message and its `context`. */
+ readonly history?: readonly SessionHistoryMessage[];
/** Initial workflow title for a prewarmed session. */
readonly title?: string;
readonly turnPolicy?: TurnPolicy;
@@ -116,12 +119,15 @@ export function createSession(
async send(message, options) {
const delivery = createDelivery(metadata);
const caller = sessionCallbackToTurnCaller(options.callback);
+ const history = validateSessionHistory(options.history);
const payload = attachClientContext<{
context?: readonly string[];
+ history?: readonly SessionHistoryMessage[];
message: string | UserContent | undefined;
outputSchema?: JsonObject;
}>({ message: serializeFilePartsInMessage(message) }, readClientContext(options));
if (options.context !== undefined) payload.context = options.context;
+ if (history !== undefined) payload.history = history;
if (options.outputSchema !== undefined) payload.outputSchema = options.outputSchema;
const commandWithoutCaller = {
auth: options.auth,
diff --git a/packages/eve/src/channel/types.ts b/packages/eve/src/channel/types.ts
index 61cb4f67c..5c348d35c 100644
--- a/packages/eve/src/channel/types.ts
+++ b/packages/eve/src/channel/types.ts
@@ -13,6 +13,7 @@ import type { InputRequest, InputResponse } from "#shared/input.js";
import type { ChannelAdapter } from "#channel/adapter.js";
import type { AgentLimitsDefinition } from "#shared/agent-definition.js";
import type { JsonObject } from "#shared/json.js";
+import type { SessionHistoryMessage } from "#shared/session-history.js";
import type { InstrumentationDecision } from "#shared/instrumentation-decision.js";
import type { ForwardedTraceAssertion } from "#shared/forwarded-trace-policy.js";
import type { ConversationContext } from "#shared/conversation-context.js";
@@ -177,6 +178,8 @@ export interface DeliverPayload {
readonly inputResponses?: readonly InputResponse[];
readonly message?: string | UserContent;
readonly context?: readonly string[];
+ /** Prior conversation added as user and assistant turns before this delivery's input. */
+ readonly history?: readonly SessionHistoryMessage[];
readonly outputSchema?: JsonObject;
readonly [key: string]: unknown;
}
@@ -522,6 +525,8 @@ export interface RunInput {
/** Omitted only when creating a conversation session before its first turn. */
readonly message?: string | UserContent;
readonly context?: readonly string[];
+ /** Prior conversation; with no message, it waits for the first message's turn. */
+ readonly history?: readonly SessionHistoryMessage[];
readonly outputSchema?: JsonObject;
/** Channel payload state for the first delivery, as later deliveries carry it. */
readonly state?: unknown;
@@ -625,9 +630,13 @@ export interface Runtime {
/**
* Resolves the session that currently owns a continuation token without
* delivering input or starting a run. Returns `undefined` when no session
- * owns the token.
+ * owns the token. With `runnable`, throws `SessionStrandedError` when the
+ * owner is stranded and can run nothing.
*/
- resolveContinuation(continuationToken: string): Promise<{ sessionId: string } | undefined>;
+ resolveContinuation(
+ continuationToken: string,
+ options?: { readonly runnable?: boolean },
+ ): Promise<{ sessionId: string } | undefined>;
/**
* Returns a readable stream of lifecycle events for an existing session.
diff --git a/packages/eve/src/client/index.ts b/packages/eve/src/client/index.ts
index e9d46d0ab..32420bc0b 100644
--- a/packages/eve/src/client/index.ts
+++ b/packages/eve/src/client/index.ts
@@ -129,6 +129,8 @@ export type {
ConnectionAuthorizationOutcome,
AuthorizationRequiredStreamEvent,
HandleMessageStreamEvent,
+ HistoryImportedMessage,
+ HistoryImportedStreamEvent,
MessageStreamEventMeta,
InputResolution,
InputResolutionOutcome,
diff --git a/packages/eve/src/client/message-reducer-types.ts b/packages/eve/src/client/message-reducer-types.ts
index a2917bcad..2de675f63 100644
--- a/packages/eve/src/client/message-reducer-types.ts
+++ b/packages/eve/src/client/message-reducer-types.ts
@@ -24,11 +24,15 @@ export interface EveMessage {
* `status` tracks this message's own lifecycle (distinct from session-level
* status): user messages use `"submitted"` or `"failed"`, assistant messages
* use `"streaming"` or `"complete"`. `optimistic` is set only while a
- * client-projected user message awaits server confirmation. `turnId` links the
- * message to its runtime turn; `result` holds the harness structured result
- * once the turn finalizes.
+ * client-projected user message awaits server confirmation. `imported` marks a
+ * message added through `history`, ahead of its turn's message, and carries no
+ * `turnId`; `historyId` is the app-owned `id` that history entry carried.
+ * `turnId` links the message to its runtime turn; `result` holds the harness
+ * structured result once the turn finalizes.
*/
export interface EveMessageMetadata {
+ readonly historyId?: string;
+ readonly imported?: true;
readonly optimistic?: true;
readonly result?: unknown;
readonly status?: "complete" | "failed" | "streaming" | "submitted";
diff --git a/packages/eve/src/client/message-reducer.test.ts b/packages/eve/src/client/message-reducer.test.ts
index 4ab2b2fbc..e77d30f96 100644
--- a/packages/eve/src/client/message-reducer.test.ts
+++ b/packages/eve/src/client/message-reducer.test.ts
@@ -10,6 +10,7 @@ import {
createApprovalSettledEvent,
createAuthorizationCompletedEvent,
createAuthorizationRequiredEvent,
+ createHistoryImportedEvent,
createInputResolvedEvent,
createInputRequestedEvent,
createMessageAppendedEvent,
@@ -100,6 +101,85 @@ describe("defaultMessageReducer", () => {
]);
});
+ it("places added history ahead of its turn's pending message and response", () => {
+ const reducer = defaultMessageReducer();
+ let data = reducer.reduce(reducer.initial(), {
+ data: { createdAt: 1, message: "Continue", submissionId: "first" },
+ type: "client.message.submitted",
+ });
+ data = reduceServerEvents(reducer, data, [
+ createHistoryImportedEvent({
+ messages: [
+ { text: "Earlier question", id: "m1", role: "user" },
+ { text: "Earlier answer", role: "assistant" },
+ ],
+ sequence: 0,
+ turnId: "turn_0",
+ }),
+ ]);
+ expect(data.messages.map(({ id }) => id)).toEqual([
+ expect.stringContaining(":imported:0"),
+ expect.stringContaining(":imported:1"),
+ "optimistic:first:user",
+ ]);
+ expect(data.messages.map(({ metadata }) => metadata)).toEqual([
+ { historyId: "m1", imported: true, status: "complete" },
+ { imported: true, status: "complete" },
+ expect.anything(),
+ ]);
+
+ // App ids are unique only within one call: a later call reusing one keeps both messages.
+ data = reduceServerEvents(reducer, reducer.initial(), [
+ createHistoryImportedEvent({
+ messages: [{ text: "Earlier question", id: "m1", role: "user" }],
+ sequence: 0,
+ turnId: "turn_0",
+ }),
+ createHistoryImportedEvent({
+ messages: [{ text: "Later question", id: "m1", role: "user" }],
+ sequence: 1,
+ turnId: "turn_1",
+ }),
+ ]);
+ expect(data.messages.map(({ metadata }) => metadata?.historyId)).toEqual(["m1", "m1"]);
+ expect(new Set(data.messages.map(({ id }) => id)).size).toBe(2);
+
+ // Steering into an active turn: added history lands before that turn's response, which keeps
+ // streaming into its own message.
+ data = reduceServerEvents(reducer, reducer.initial(), [
+ createMessageReceivedEvent({ message: "First", sequence: 0, turnId: "turn_1" }),
+ createMessageAppendedEvent({
+ messageDelta: "Working",
+ sequence: 1,
+ stepIndex: 0,
+ turnId: "turn_1",
+ }),
+ createHistoryImportedEvent({
+ messages: [{ text: "Bob: meanwhile", role: "user" }],
+ sequence: 2,
+ turnId: "turn_1",
+ }),
+ createMessageReceivedEvent({ message: "Correction", sequence: 2, turnId: "turn_1" }),
+ createMessageAppendedEvent({
+ messageDelta: " on it",
+ sequence: 3,
+ stepIndex: 0,
+ turnId: "turn_1",
+ }),
+ ]);
+ expect(
+ data.messages.map(({ parts, role }) => [
+ role,
+ parts.map((part) => ("text" in part ? part.text : "")).join(""),
+ ]),
+ ).toEqual([
+ ["user", "First"],
+ ["user", "Bob: meanwhile"],
+ ["user", "Correction"],
+ ["assistant", "Working on it"],
+ ]);
+ });
+
it("leaves a failed optimistic follow-up ahead of the active reply", () => {
const reducer = defaultMessageReducer();
let data = reduceServerEvents(reducer, reducer.initial(), [
diff --git a/packages/eve/src/client/message-reducer.ts b/packages/eve/src/client/message-reducer.ts
index 9e1cec8ed..042e71213 100644
--- a/packages/eve/src/client/message-reducer.ts
+++ b/packages/eve/src/client/message-reducer.ts
@@ -55,6 +55,7 @@ export type {
type EveAssistantMessage = EveMessage & { readonly role: "assistant" };
type MessageReceivedEvent = Extract<EveAgentReducerEvent, { readonly type: "message.received" }>;
+type HistoryImportedEvent = Extract<EveAgentReducerEvent, { readonly type: "history.imported" }>;
function receivedMessageEventId(event: MessageReceivedEvent): string {
const eventId: string | undefined = event.meta.id;
@@ -126,6 +127,9 @@ function reduceContent(data: EveMessageData, event: EveAgentReducerEvent): EveMe
event.data.turnId,
);
+ case "history.imported":
+ return importHistory(data, event);
+
case "step.started":
return updateAssistantMessage(data, event.data.turnId, (message) =>
ensureStepStartPart(message, event.data.stepIndex),
@@ -412,6 +416,38 @@ function reduceContent(data: EveMessageData, event: EveAgentReducerEvent): EveMe
}
}
+/**
+ * Added history precedes its turn's message: before that turn's response and any message the
+ * client submitted and the stream hasn't confirmed. App ids are unique only within one call, so
+ * message ids derive from the event and the app id rides in metadata for rejoining annotations.
+ */
+function importHistory(data: EveMessageData, event: HistoryImportedEvent): EveMessageData {
+ const eventId = event.meta.id ?? `${event.data.turnId}:${event.data.sequence}`;
+ const imported = event.data.messages.map((message, index): EveMessage => ({
+ id: `${eventId}:imported:${index}`,
+ // No `turnId`: the turn's response must never stream into an imported assistant message.
+ metadata:
+ message.id === undefined
+ ? { imported: true, status: "complete" }
+ : { historyId: message.id, imported: true, status: "complete" },
+ parts: [
+ message.role === "assistant"
+ ? { state: "done", text: message.text, type: "text" }
+ : { text: message.text, type: "text" },
+ ],
+ role: message.role,
+ }));
+ const ids = new Set(imported.map((message) => message.id));
+ const messages = data.messages.filter((message) => !ids.has(message.id));
+ const before = messages.findIndex(
+ (message) =>
+ message.metadata?.optimistic === true ||
+ (message.role === "assistant" && message.metadata?.turnId === event.data.turnId),
+ );
+ const at = before === -1 ? messages.length : before;
+ return { ...data, messages: [...messages.slice(0, at), ...imported, ...messages.slice(at)] };
+}
+
/** The tool calls whose state the event may have changed. */
function toolCallIds(data: EveMessageData, event: EveAgentReducerEvent): readonly string[] {
const byRequest = (requestId: string) =>
diff --git a/packages/eve/src/client/transcript-reducer.test.ts b/packages/eve/src/client/transcript-reducer.test.ts
index 4cfbde51a..dad1d6de1 100644
--- a/packages/eve/src/client/transcript-reducer.test.ts
+++ b/packages/eve/src/client/transcript-reducer.test.ts
@@ -3,6 +3,7 @@ import { describe, expect, it } from "vitest";
import { transcriptReducer } from "#client/transcript-reducer.js";
import {
createContextClearedEvent,
+ createHistoryImportedEvent,
createMessageAppendedEvent,
createMessageCompletedEvent,
createMessageReceivedEvent,
@@ -54,6 +55,27 @@ describe("transcriptReducer", () => {
]);
});
+ it("keeps imported history in order, ahead of its turn's message", () => {
+ expect(
+ reduce([
+ createHistoryImportedEvent({
+ ...TURN,
+ messages: [
+ { id: "m1", role: "user", text: "Alice asks for the venue list." },
+ { role: "assistant", text: "Here are three venues." },
+ ],
+ }),
+ received("Which one seats everyone?"),
+ completed("The second venue."),
+ ]).messages,
+ ).toEqual([
+ { role: "user", text: "Alice asks for the venue list." },
+ { role: "assistant", text: "Here are three venues." },
+ { role: "user", text: "Which one seats everyone?" },
+ { role: "assistant", text: "The second venue." },
+ ]);
+ });
+
it("starts over at a clear and at a reset that ended a stranded session", () => {
expect(
reduce([
diff --git a/packages/eve/src/client/transcript-reducer.ts b/packages/eve/src/client/transcript-reducer.ts
index bc5459ee2..1d3c9bb82 100644
--- a/packages/eve/src/client/transcript-reducer.ts
+++ b/packages/eve/src/client/transcript-reducer.ts
@@ -1,6 +1,9 @@
import type { EveAgentReducer, EveAgentReducerEvent } from "#client/reducer.js";
-/** One user message or completed assistant message in a {@link TranscriptData}. */
+/**
+ * One user message or completed assistant message in a {@link TranscriptData}.
+ * Matches the shape `history` accepts, so a transcript can seed another session.
+ */
export interface TranscriptMessage {
readonly role: "assistant" | "user";
readonly text: string;
@@ -23,8 +26,8 @@ export interface TranscriptReducerOptions {
/**
* Creates a reducer that projects a session's stream into its text
- * conversation: user message text and completed assistant text, oldest
- * first.
+ * conversation: history added with `history.imported`, user message text,
+ * and completed assistant text, oldest first.
*
* Reasoning, tool calls and results, attachments, approvals, and assistant
* output that never completed are left out. A `context.cleared` event, or a
@@ -70,6 +73,11 @@ export function transcriptReducer(
initial: () => ({ messages: [] }),
reduce(data, event) {
switch (event.type) {
+ case "history.imported":
+ return event.data.messages.reduce(
+ (next, { role, text }) => append(next, { role, text }),
+ data,
+ );
case "message.received":
return append(data, { role: "user", text: receivedText(event) });
case "message.completed":
diff --git a/packages/eve/src/compiler/extension-compatibility.ts b/packages/eve/src/compiler/extension-compatibility.ts
index f043c43f4..a7abd4d48 100644
--- a/packages/eve/src/compiler/extension-compatibility.ts
+++ b/packages/eve/src/compiler/extension-compatibility.ts
@@ -22,10 +22,10 @@ interface ExtensionCapabilityContract {
const EXTENSION_CAPABILITY_CONTRACTS = {
extension: { current: 1, supported: [1], dropped: {} },
tool: {
- current: 93,
+ current: 94,
supported: [
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 29, 30, 31, 32, 34, 35, 76, 77, 78, 80, 81, 82, 84,
- 85, 86, 87, 88, 89, 90, 91, 92, 93,
+ 85, 86, 87, 88, 89, 90, 91, 92, 93, 94,
],
dropped: {
14: "TaskExec.delegated was removed; migrate to workflow-backed background tools",
@@ -89,11 +89,11 @@ const EXTENSION_CAPABILITY_CONTRACTS = {
},
},
dynamicTool: {
- current: 87,
+ current: 88,
supported: [
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 22, 31, 32, 33, 52, 54,
60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 72, 73, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84,
- 85, 86, 87,
+ 85, 86, 87, 88,
],
dropped: {
21: "Message and reasoning append events now expose deltas instead of cumulative snapshots.",
@@ -134,10 +134,10 @@ const EXTENSION_CAPABILITY_CONTRACTS = {
},
},
channel: {
- current: 62,
+ current: 63,
supported: [
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 29, 31, 36, 37, 38, 39, 40, 41, 42,
- 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 54, 55, 56, 57, 58, 59, 60, 61, 62,
+ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63,
],
dropped: {
12: "Message and reasoning append events now expose deltas instead of cumulative snapshots.",
@@ -160,10 +160,10 @@ const EXTENSION_CAPABILITY_CONTRACTS = {
},
},
schedule: {
- current: 34,
+ current: 35,
supported: [
1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28,
- 29, 30, 31, 32, 33, 34,
+ 29, 30, 31, 32, 33, 34, 35,
],
dropped: {
5: "Message and reasoning append events now expose deltas instead of cumulative snapshots.",
@@ -172,10 +172,10 @@ const EXTENSION_CAPABILITY_CONTRACTS = {
},
},
subagent: {
- current: 39,
+ current: 40,
supported: [
3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 19, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33,
- 34, 35, 36, 37, 38, 39,
+ 34, 35, 36, 37, 38, 39, 40,
],
dropped: {
1: "Persistent subagent sessions are now the default and the experimental opt-in was removed",
@@ -189,10 +189,10 @@ const EXTENSION_CAPABILITY_CONTRACTS = {
},
},
connection: {
- current: 51,
+ current: 52,
supported: [
1, 2, 3, 4, 5, 6, 7, 8, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 24, 26, 32, 33, 34,
- 35, 36, 37, 38, 39, 40, 41, 43, 44, 45, 46, 47, 48, 49, 50, 51,
+ 35, 36, 37, 38, 39, 40, 41, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
],
dropped: {
9: "Dynamic connection resolvers no longer receive conversation or channel continuation data",
@@ -208,9 +208,9 @@ const EXTENSION_CAPABILITY_CONTRACTS = {
},
},
hook: {
- current: 47,
+ current: 48,
supported: [
- 20, 21, 22, 23, 25, 27, 31, 32, 33, 34, 35, 36, 37, 38, 39, 41, 42, 43, 44, 45, 46, 47,
+ 20, 21, 22, 23, 25, 27, 31, 32, 33, 34, 35, 36, 37, 38, 39, 41, 42, 43, 44, 45, 46, 47, 48,
],
dropped: {
1: "Model identity moved from session.started runtime metadata to step.started call attribution.",
@@ -242,10 +242,10 @@ const EXTENSION_CAPABILITY_CONTRACTS = {
},
skill: { current: 3, supported: [1, 2, 3], dropped: {} },
dynamicSkill: {
- current: 39,
+ current: 40,
supported: [
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 25, 26, 27, 28, 29, 30,
- 31, 32, 33, 34, 35, 36, 37, 38, 39,
+ 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
],
dropped: {
13: "Message and reasoning append events now expose deltas instead of cumulative snapshots.",
@@ -256,10 +256,10 @@ const EXTENSION_CAPABILITY_CONTRACTS = {
},
instructions: { current: 2, supported: [1, 2], dropped: {} },
dynamicInstructions: {
- current: 40,
+ current: 41,
supported: [
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17, 18, 19, 20, 21, 22, 26, 27, 28, 29, 30,
- 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
+ 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41,
],
dropped: {
14: "Message and reasoning append events now expose deltas instead of cumulative snapshots.",
diff --git a/packages/eve/src/eve-channel/index.ts b/packages/eve/src/eve-channel/index.ts
index 068a57eeb..432189f7b 100644
--- a/packages/eve/src/eve-channel/index.ts
+++ b/packages/eve/src/eve-channel/index.ts
@@ -74,6 +74,7 @@ import {
requireSessionId,
} from "#eve-channel/request.js";
import { attachClientContext } from "#internal/client-context.js";
+import { type SessionHistoryMessage, validateSessionHistory } from "#shared/session-history.js";
import type { ParsedCreateBody } from "#eve-channel/create-request.js";
import {
findRemoteAgentBinding,
@@ -365,6 +366,9 @@ export function eveChannel(input: EveChannelInput): EveChannel {
{
message: body.message,
context: messageResult.context,
+ history: validateSessionHistory(
+ "history" in messageResult ? messageResult.history : undefined,
+ ),
outputSchema: body.outputSchema,
},
messageResult.clientContext,
@@ -421,6 +425,7 @@ export function eveChannel(input: EveChannelInput): EveChannel {
let clientContext = resolveTurnClientContext(undefined, body.context);
let context: readonly string[] | undefined;
+ let history: readonly SessionHistoryMessage[] | undefined;
let title: string | undefined;
let dispatchAuth: SessionAuthContext | null = forwarded.auth;
if (body.message !== undefined) {
@@ -435,6 +440,7 @@ export function eveChannel(input: EveChannelInput): EveChannel {
if (messageResult instanceof Response) return messageResult;
clientContext = messageResult.clientContext;
context = messageResult.context;
+ history = messageResult.history;
title = messageResult.title;
dispatchAuth = messageResult.auth;
}
@@ -447,6 +453,7 @@ export function eveChannel(input: EveChannelInput): EveChannel {
auth: dispatchAuth,
callback: body.callback,
context,
+ history,
outputSchema: body.outputSchema,
turnPolicy: body.turnPolicy,
title,
diff --git a/packages/eve/src/eve-channel/support.ts b/packages/eve/src/eve-channel/support.ts
index 1aa1bb149..2e82786c5 100644
--- a/packages/eve/src/eve-channel/support.ts
+++ b/packages/eve/src/eve-channel/support.ts
@@ -2,6 +2,7 @@ import type { UserContent } from "ai";
import { SessionStrandedError } from "#channel/session-stranded-error.js";
import type { SessionAuthContext } from "#channel/types.js";
+import type { SessionHistoryMessage } from "#shared/session-history.js";
import { workflowEntryReference } from "#execution/workflow-runtime.js";
import { createLogger, logError } from "#internal/logging.js";
import type { MessageStreamEvent } from "#protocol/message.js";
@@ -162,6 +163,7 @@ interface OnMessageOutcome {
/** Model-ready turn context: `onMessage`'s replacement, or the request's labeled entries. */
readonly clientContext?: readonly string[];
readonly context?: readonly string[];
+ readonly history?: readonly SessionHistoryMessage[];
readonly title?: string;
}
@@ -208,6 +210,7 @@ export async function resolveOnMessage(input: {
auth: result.auth,
clientContext: resolveTurnClientContext(result.clientContext, input.clientContext),
context: result.context,
+ history: result.history,
title: result.title,
};
}
diff --git a/packages/eve/src/eve-channel/types.ts b/packages/eve/src/eve-channel/types.ts
index 9dfef74a8..bd0d2669c 100644
--- a/packages/eve/src/eve-channel/types.ts
+++ b/packages/eve/src/eve-channel/types.ts
@@ -14,6 +14,7 @@ import type {
ChannelMethod,
} from "#public/definitions/channel.js";
import type { ChannelAudience } from "#shared/channel-audience.js";
+import type { SessionHistoryMessage } from "#shared/session-history.js";
export type { ForwardedAssertion, TrustedForwarders } from "#channel/forwarded-principal.js";
@@ -94,6 +95,12 @@ export type EveMessageResult = {
* context; omit it to keep the request's context.
*/
readonly clientContext?: ClientContextValue;
+ /**
+ * Prior conversation added as user and assistant turns before this message.
+ * Resolve it on the server and authorize the caller against the stored
+ * conversation.
+ */
+ readonly history?: readonly SessionHistoryMessage[];
/** Sets the title when creating a workflow or sending its first message after prewarming. */
readonly title?: string;
};
diff --git a/packages/eve/src/execution/create-session-step.ts b/packages/eve/src/execution/create-session-step.ts
index bea17411a..b82cc24bf 100644
--- a/packages/eve/src/execution/create-session-step.ts
+++ b/packages/eve/src/execution/create-session-step.ts
@@ -14,6 +14,8 @@ import type { RunSessionLimits } from "#channel/types.js";
import type { JsonObject } from "#shared/json.js";
import { resolveEffectiveAgentRuntimeFromConfig } from "#execution/effective-agent-config.js";
import type { DynamicSubagentAgentConfig } from "#runtime/subagents/dynamic-agent-config.js";
+import { withPendingHistory } from "#execution/session/pending-history.js";
+import type { SessionHistoryMessage } from "#shared/session-history.js";
/**
* Result returned by {@link createSessionStep}.
@@ -36,6 +38,8 @@ export async function createSessionStep(input: {
readonly compiledArtifactsSource: DurableCompiledArtifactsSource;
readonly continuationToken: string;
readonly dynamicSubagentAgentConfig?: DynamicSubagentAgentConfig;
+ /** History from `create()`, held until the first message's turn adds it. */
+ readonly history?: readonly SessionHistoryMessage[];
readonly inheritedLimits?: RunSessionLimits;
readonly outputSchema?: JsonObject;
readonly nodeId?: string;
@@ -84,6 +88,9 @@ export async function createSessionStep(input: {
turnAgent: effectiveAgent.turnAgent,
});
- const { history, sessionState } = createDurableSessionValues(session);
+ const state = withPendingHistory(session.state, input.history);
+ const { history, sessionState } = createDurableSessionValues(
+ state === session.state ? session : { ...session, state },
+ );
return { history, state: sessionState };
}
diff --git a/packages/eve/src/execution/deliver-payloads.ts b/packages/eve/src/execution/deliver-payloads.ts
index 8aeff8087..bb8e544cf 100644
--- a/packages/eve/src/execution/deliver-payloads.ts
+++ b/packages/eve/src/execution/deliver-payloads.ts
@@ -2,7 +2,13 @@ import type { DeliverPayload } from "#channel/types.js";
import { coalesceTurnInputs } from "#harness/messages.js";
import type { StepInput } from "#harness/types.js";
-const COALESCED_DELIVER_FIELDS = ["context", "inputResponses", "message", "outputSchema"] as const;
+const COALESCED_DELIVER_FIELDS = [
+ "context",
+ "history",
+ "inputResponses",
+ "message",
+ "outputSchema",
+] as const;
/** Coalesces channel payloads while preserving turn input and adapter-specific fields. */
export function coalesceDeliverPayloads(payloads: readonly DeliverPayload[]): DeliverPayload {
diff --git a/packages/eve/src/execution/session-stranded.integration.test.ts b/packages/eve/src/execution/session-stranded.integration.test.ts
index c6c12c340..52812ea1e 100644
--- a/packages/eve/src/execution/session-stranded.integration.test.ts
+++ b/packages/eve/src/execution/session-stranded.integration.test.ts
@@ -405,6 +405,34 @@ describe("stranded sessions", () => {
});
});
+ it("refuses create() at a stranded address until it is reset", async () => {
+ const test = await createTestRuntime({ agent: { name: "stranded-session-create" } });
+ await test.run(async () => {
+ const continuationToken = "stranded-session-create";
+ const stranded = await parkStrandedOwner(`http:${continuationToken}`);
+ const runtime = channelRuntime();
+ const address = httpAddress(runtime, continuationToken);
+ const history = [{ role: "user" as const, text: "Alice asks for the venue list." }];
+ let createdSessionId: string | undefined;
+ try {
+ // A stranded owner cannot run, so `created: false` would hand back a dead session.
+ await expect(address.create({ auth: null, history })).rejects.toThrow(
+ "Call reset() on the address, then create() again",
+ );
+ expect(runtime.createSession).not.toHaveBeenCalled();
+ await expect(stranded.status).resolves.toBe("running");
+
+ await address.reset();
+ const result = await address.create({ auth: null, history });
+ createdSessionId = result.session.id;
+ expect(result.created).toBe(true);
+ } finally {
+ await resetSession(runtime, createdSessionId);
+ await cancelIfActive(stranded);
+ }
+ });
+ });
+
it("keeps a stranded session when a channel delivery also carries input responses", async () => {
const test = await createTestRuntime({ agent: { name: "stranded-session-responses" } });
await test.run(async () => {
diff --git a/packages/eve/src/execution/session/entry.ts b/packages/eve/src/execution/session/entry.ts
index e942ded07..308682417 100644
--- a/packages/eve/src/execution/session/entry.ts
+++ b/packages/eve/src/execution/session/entry.ts
@@ -184,6 +184,8 @@ export async function bootInitialOwner(
dynamicSubagentAgentConfig: serializedContext["eve.dynamicSubagentAgentConfig"] as
| DynamicSubagentAgentConfig
| undefined,
+ // With a first message, its delivery carries the history instead.
+ history: input.input.message === undefined ? input.input.history : undefined,
inheritedLimits: input.limits,
nodeId: serializedBundle.nodeId,
outputSchema: input.input.outputSchema,
@@ -486,6 +488,7 @@ function createInitialDelivery(
{
message: input.input.message,
context: input.input.context,
+ history: input.input.history,
outputSchema: input.input.outputSchema,
state: input.input.state,
},
diff --git a/packages/eve/src/execution/session/pending-history.integration.test.ts b/packages/eve/src/execution/session/pending-history.integration.test.ts
new file mode 100644
index 000000000..eb538950f
--- /dev/null
+++ b/packages/eve/src/execution/session/pending-history.integration.test.ts
@@ -0,0 +1,78 @@
+import { describe, expect, it } from "vitest";
+import { defineChannel, POST } from "#public/definitions/channel.js";
+import { workflowEntry } from "#execution/session/entry.js";
+import { sessionInboxHookToken } from "#execution/session-inbox/address.js";
+import { createTestRuntime } from "#internal/testing/app-harness.js";
+import { buildSerializedContext } from "#internal/testing/entry-test-helpers.js";
+import { captureTurnEvents } from "#internal/testing/events.js";
+import { waitForHook } from "#internal/testing/workflow-test-helpers.js";
+import { resumeHook, start } from "#internal/workflow/runtime.js";
+
+const channel = defineChannel({
+ routes: [POST("/drop", async () => new Response("ok"))],
+ state: {},
+ // A channel may drop a delivery, such as a message it does not handle.
+ deliver(payload) {
+ return payload.message === "drop me" ? undefined : { message: payload.message };
+ },
+});
+
+describe("pending session history", () => {
+ it("keeps history from create() until a message the channel accepts", async () => {
+ const continuationToken = "drop-history-session";
+ const runtime = await createTestRuntime({
+ agent: { name: "pending-history" },
+ modules: [
+ { loadNamespace: async () => ({ default: channel }), logicalPath: "channels/drop.ts" },
+ ],
+ });
+
+ await runtime.run(async () => {
+ const run = await start(workflowEntry, [
+ {
+ kind: "initial",
+ ownerDeploymentId: "dpl_inline",
+ input: {
+ history: [
+ { role: "user", text: "Earlier question" },
+ { role: "assistant", text: "Earlier answer" },
+ ],
+ },
+ serializedContext: buildSerializedContext({
+ channelKind: "channel:drop",
+ continuationToken,
+ }),
+ },
+ ]);
+ const stream = captureTurnEvents(run);
+ try {
+ const inbox = sessionInboxHookToken(continuationToken);
+ await waitForHook({ runId: run.runId }, { token: inbox });
+ await resumeHook(inbox, { kind: "send", payload: { message: "drop me" } });
+ await resumeHook(inbox, { kind: "send", payload: { message: "hello" } });
+
+ const turn = await stream.nextTurn();
+ expect(
+ turn
+ .filter(({ type }) => type === "history.imported" || type === "message.received")
+ .map(({ data, type }) => [type, data]),
+ ).toEqual([
+ [
+ "history.imported",
+ expect.objectContaining({
+ messages: [
+ { text: "Earlier question", role: "user" },
+ { text: "Earlier answer", role: "assistant" },
+ ],
+ turnId: "turn_0",
+ }),
+ ],
+ ["message.received", expect.objectContaining({ message: "hello", turnId: "turn_0" })],
+ ]);
+ } finally {
+ stream.dispose();
+ await run.cancel().catch(() => {});
+ }
+ });
+ });
+});
diff --git a/packages/eve/src/execution/session/pending-history.ts b/packages/eve/src/execution/session/pending-history.ts
new file mode 100644
index 000000000..086c455ee
--- /dev/null
+++ b/packages/eve/src/execution/session/pending-history.ts
@@ -0,0 +1,30 @@
+import type { SessionStateMap } from "#harness/types.js";
+import type { SessionHistoryMessage } from "#shared/session-history.js";
+
+/**
+ * History passed to `create()` waits in session state until the first message, so it joins
+ * history through the same turn-input path as `send()` history and is published with that turn.
+ */
+const PENDING_HISTORY_STATE_KEY = "eve.session.pendingHistory";
+
+export function withPendingHistory(
+ state: SessionStateMap | undefined,
+ history: readonly SessionHistoryMessage[] | undefined,
+): SessionStateMap | undefined {
+ if (history === undefined || history.length === 0) return state;
+ return { ...state, [PENDING_HISTORY_STATE_KEY]: history };
+}
+
+export function readPendingHistory(
+ state: SessionStateMap | undefined,
+): readonly SessionHistoryMessage[] {
+ return (state?.[PENDING_HISTORY_STATE_KEY] as readonly SessionHistoryMessage[] | undefined) ?? [];
+}
+
+export function withoutPendingHistory(
+ state: SessionStateMap | undefined,
+): SessionStateMap | undefined {
+ if (state === undefined || !(PENDING_HISTORY_STATE_KEY in state)) return state;
+ const { [PENDING_HISTORY_STATE_KEY]: _pending, ...rest } = state;
+ return rest;
+}
diff --git a/packages/eve/src/execution/session/turn-event-handler.ts b/packages/eve/src/execution/session/turn-event-handler.ts
index d4b083eea..ef8b823e8 100644
--- a/packages/eve/src/execution/session/turn-event-handler.ts
+++ b/packages/eve/src/execution/session/turn-event-handler.ts
@@ -32,6 +32,7 @@ const HOOK_CANCELLABLE_EVENTS = {
"compaction.completed": true,
"compaction.requested": true,
"context.cleared": false,
+ "history.imported": false,
"input.requested": true,
"input.resolved": true,
"message.appended": true,
diff --git a/packages/eve/src/execution/session/turn-step.ts b/packages/eve/src/execution/session/turn-step.ts
index 0be5622cb..71e6e948a 100644
--- a/packages/eve/src/execution/session/turn-step.ts
+++ b/packages/eve/src/execution/session/turn-step.ts
@@ -32,6 +32,7 @@ import { BundleKey, ChannelKey } from "#runtime/sessions/runtime-context-keys.js
import { deserializeContext, serializeContext } from "#context/serialize.js";
import { bindSessionInstrumentation } from "#instrumentation/runtime.js";
import { RuntimeActionSettlementTimesKey } from "#harness/runtime-action-settlement-state.js";
+import { readPendingHistory, withoutPendingHistory } from "#execution/session/pending-history.js";
import * as agentTraceState from "#tracing/eve/agent-trace-context-store.js";
import { matchAuthorizationCallbacks } from "#execution/authorization-callback-match.js";
import { isTurnCancellation, throwIfTurnAborted } from "#harness/turn-cancellation.js";
@@ -205,14 +206,21 @@ async function runSessionStepBody(
.requester
: undefined;
if (requester !== undefined) ctx.set(AuthKey, requester);
- const initialSession: HarnessSession = {
- ...hydrateDurableSession({
- compactionOverrides: {
- thresholdPercent: effectiveAgent.thresholdPercent,
- },
- durable: durableSession,
- turnAgent: effectiveAgent.turnAgent,
- }),
+ // History left by `create()` joins the first message's turn. It leaves state only once a
+ // deliver result carries it, so a dropped first message does not lose it.
+ const pendingHistory =
+ delivery?.payloads.some((payload) => payload.message !== undefined) === true
+ ? readPendingHistory(durableSession.state)
+ : [];
+ const hydrated = hydrateDurableSession({
+ compactionOverrides: {
+ thresholdPercent: effectiveAgent.thresholdPercent,
+ },
+ durable: durableSession,
+ turnAgent: effectiveAgent.turnAgent,
+ });
+ let initialSession: HarnessSession = {
+ ...hydrated,
history: validateHarnessModelMessages(input.history),
};
const history = createExecutionHistoryView(initialSession);
@@ -321,13 +329,21 @@ async function runSessionStepBody(
: defaultDeliverResult(payload);
if (result !== undefined && result !== null) {
- results.push(result);
+ // `history` is framework-owned, so a channel's deliver hook cannot drop or rewrite it.
+ const history = [
+ ...(results.length === 0 ? pendingHistory : []),
+ ...(payload.history ?? []),
+ ];
+ results.push(history.length === 0 ? result : { ...result, history });
}
}
} catch (error) {
await failChannelDeliveries(error);
throw error;
}
+ if (results.length > 0 && pendingHistory.length > 0) {
+ initialSession = { ...initialSession, state: withoutPendingHistory(initialSession.state) };
+ }
resolved = results.length === 0 ? undefined : results.reduce(coalesceTurnInputs);
}
// A delivery without auth acts as the session's current identity, so
diff --git a/packages/eve/src/execution/workflow-runtime.ts b/packages/eve/src/execution/workflow-runtime.ts
index 1023dce86..cd8f8db7f 100644
--- a/packages/eve/src/execution/workflow-runtime.ts
+++ b/packages/eve/src/execution/workflow-runtime.ts
@@ -451,9 +451,11 @@ function isInactiveCommandTarget(error: unknown): boolean {
/** The session holding a continuation token's inbox, if any does. */
export async function resolveContinuation(
continuationToken: string,
+ options?: { readonly runnable?: boolean },
): Promise<{ sessionId: string } | undefined> {
+ let owner: { sessionId: string };
try {
- return await resolveSessionInbox(continuationToken);
+ owner = await resolveSessionInbox(continuationToken);
} catch (error) {
if (HookNotFoundError.is(error)) {
return undefined;
@@ -463,6 +465,16 @@ export async function resolveContinuation(
});
throw error;
}
+ if (options?.runnable !== true) return owner;
+ try {
+ await assertRunnableSessionInbox(
+ sessionInboxHookToken(sessionCommandHookToken(owner.sessionId)),
+ );
+ } catch (error) {
+ if (error instanceof StrandedSessionOwnerError) throw sessionStrandedError(error);
+ throw error;
+ }
+ return owner;
}
/**
diff --git a/packages/eve/src/harness/hitl/approvals.ts b/packages/eve/src/harness/hitl/approvals.ts
index ee3562ddb..bbbd1eebb 100644
--- a/packages/eve/src/harness/hitl/approvals.ts
+++ b/packages/eve/src/harness/hitl/approvals.ts
@@ -482,6 +482,7 @@ export function hasRunnableQueue(view: SessionView): boolean {
if (
queued.message !== undefined ||
(queued.context?.length ?? 0) > 0 ||
+ (queued.history?.length ?? 0) > 0 ||
readClientContext(queued) !== undefined ||
queued.outputSchema !== undefined ||
(queued.runtimeActionResults?.length ?? 0) > 0
diff --git a/packages/eve/src/harness/hitl/delivery.ts b/packages/eve/src/harness/hitl/delivery.ts
index fad10d6f8..82f298cf9 100644
--- a/packages/eve/src/harness/hitl/delivery.ts
+++ b/packages/eve/src/harness/hitl/delivery.ts
@@ -94,6 +94,7 @@ export function resolveTextInput(
return compactInput({
...stepInput,
context: undefined,
+ history: undefined,
inputResponses: [...(stepInput.inputResponses ?? []), ...responses],
message: undefined,
messageConsumed: true,
@@ -128,6 +129,7 @@ export function resolveTypedApproval(
return {
...stepInput,
context: undefined,
+ history: undefined,
inputResponses: [...(stepInput.inputResponses ?? []), response],
message: undefined,
messageConsumed: true,
@@ -155,11 +157,16 @@ export function withoutResponses(input: ResolvedStepInput | undefined): StepInpu
return rest;
}
-/** The turn's own input: the message a plain-text answer didn't consume, and its context. */
+/** The turn's own input: the message a plain-text answer didn't consume, its history and context. */
export function turnInputOnly(input: ResolvedStepInput | undefined): StepInput | undefined {
if (input === undefined) return undefined;
- const result: { context?: StepInput["context"]; message?: StepInput["message"] } = {};
+ const result: {
+ context?: StepInput["context"];
+ history?: StepInput["history"];
+ message?: StepInput["message"];
+ } = {};
if ((input.context?.length ?? 0) > 0) result.context = input.context;
+ if ((input.history?.length ?? 0) > 0) result.history = input.history;
if (input.message !== undefined && input.messageConsumed !== true) result.message = input.message;
const turnInput = attachClientContext(result, readClientContext(input));
return isEmptyInput(turnInput) ? undefined : turnInput;
@@ -180,12 +187,14 @@ export function compactInput(input: ResolvedStepInput | undefined): ResolvedStep
if (input === undefined) return {};
const result: {
context?: StepInput["context"];
+ history?: StepInput["history"];
inputResponses?: StepInput["inputResponses"];
message?: StepInput["message"];
messageConsumed?: boolean;
outputSchema?: StepInput["outputSchema"];
} = {};
if ((input.context?.length ?? 0) > 0) result.context = input.context;
+ if ((input.history?.length ?? 0) > 0) result.history = input.history;
if ((input.inputResponses?.length ?? 0) > 0) result.inputResponses = input.inputResponses;
if (input.message !== undefined) result.message = input.message;
if (input.messageConsumed === true) result.messageConsumed = true;
diff --git a/packages/eve/src/harness/messages.ts b/packages/eve/src/harness/messages.ts
index 5962cfd02..a7a408935 100644
--- a/packages/eve/src/harness/messages.ts
+++ b/packages/eve/src/harness/messages.ts
@@ -10,6 +10,7 @@ import type { InputResponse } from "#shared/input.js";
import type { StepInput } from "#harness/types.js";
import { attachClientContext, readClientContext } from "#internal/client-context.js";
import { attachInputText, readInputText } from "#internal/input-text.js";
+import type { SessionHistoryMessage } from "#shared/session-history.js";
/** Reason a framework-authored user-role message was added to model history. */
export type FrameworkMessageKind =
@@ -59,6 +60,20 @@ export function createUserMessage(
return metadata === undefined ? message : { ...message, metadata };
}
+/** Metadata key marking a user message seeded from `history` rather than typed in a turn. */
+export const IMPORTED_MESSAGE_METADATA_KEY = "eve.imported";
+
+/** Maps seeded history to model messages: plain user and assistant text, nothing else. */
+export function createImportedHistoryMessages(
+ history: readonly SessionHistoryMessage[],
+): HarnessModelMessage[] {
+ return history.map((message) =>
+ message.role === "user"
+ ? createUserMessage("user", message.text, { [IMPORTED_MESSAGE_METADATA_KEY]: true })
+ : { content: message.text, role: "assistant" },
+ );
+}
+
/** Builds a framework-authored user-role message for model history. */
export function createFrameworkUserMessage(
kind: FrameworkMessageKind,
@@ -153,6 +168,7 @@ export function coalesceTurnInputs(a: StepInput, b: StepInput): StepInput {
a: a.context,
b: b.context,
});
+ const history = [...(a.history ?? []), ...(b.history ?? [])];
const frameworkMessageKind = coalesceFrameworkMessageKind({ a, b });
const ephemeralContext = coalesceContext({
a: readClientContext(a),
@@ -170,6 +186,7 @@ export function coalesceTurnInputs(a: StepInput, b: StepInput): StepInput {
inputResponses?: readonly InputResponse[];
message?: string | UserContent;
context?: readonly string[];
+ history?: StepInput["history"];
outputSchema?: StepInput["outputSchema"];
} = {};
@@ -189,6 +206,10 @@ export function coalesceTurnInputs(a: StepInput, b: StepInput): StepInput {
result.context = context;
}
+ if (history.length > 0) {
+ result.history = history;
+ }
+
if (outputSchema !== undefined) {
result.outputSchema = outputSchema;
}
diff --git a/packages/eve/src/harness/model-call/call.ts b/packages/eve/src/harness/model-call/call.ts
index ad4acf220..dfc19348a 100644
--- a/packages/eve/src/harness/model-call/call.ts
+++ b/packages/eve/src/harness/model-call/call.ts
@@ -21,7 +21,7 @@ import { toEntryStep, toEntryStream, toEntryTelemetry } from "#harness/execute-c
import { REPLY_TOOL_NAME } from "#protocol/reply-tool.js";
import type { GenerationSteering } from "#harness/generation-steering.js";
import { interruptStreamOnFailure } from "#harness/interruptible-stream.js";
-import type { HarnessModelMessage, UserModelMessage } from "#harness/messages.js";
+import type { HarnessModelMessage } from "#harness/messages.js";
import {
ContentFilteredModelResponseError,
EmptyModelResponseError,
@@ -98,7 +98,7 @@ interface ModelCallerInput {
readonly model: LanguageModel;
readonly generation: GenerationSteering;
readonly hidesHeldText: boolean;
- readonly turnMessages: readonly UserModelMessage[];
+ readonly turnMessages: readonly HarnessModelMessage[];
readonly approvedTools: ReadonlySet<string>;
readonly pendingApprovalsNote: string | undefined;
/** The prompt as the step started it, projected for the model. */
diff --git a/packages/eve/src/harness/model-call/request.ts b/packages/eve/src/harness/model-call/request.ts
index fab2eeb07..68ebc7c51 100644
--- a/packages/eve/src/harness/model-call/request.ts
+++ b/packages/eve/src/harness/model-call/request.ts
@@ -7,11 +7,7 @@ import type { StepCatalog } from "#execution/catalog/step-catalog.js";
import { dynamicSkillAnnouncements } from "#execution/skills/instructions.js";
import { taskSystemMessages } from "#execution/tasks/model-step.js";
import { createCurrentMessages } from "#harness/current-messages.js";
-import {
- createFrameworkUserMessage,
- type HarnessModelMessage,
- type UserModelMessage,
-} from "#harness/messages.js";
+import { createFrameworkUserMessage, type HarnessModelMessage } from "#harness/messages.js";
import type { ModelProfile } from "#harness/model-profile.js";
import { applySystemCacheBreakpoint } from "#harness/prompt-cache.js";
import type { Step } from "#harness/step/context.js";
@@ -29,7 +25,7 @@ export function requestMessages(
input: {
readonly messages: readonly HarnessModelMessage[];
readonly projectedMessages: readonly HarnessModelMessage[];
- readonly turnMessages: readonly UserModelMessage[];
+ readonly turnMessages: readonly HarnessModelMessage[];
readonly catalog: StepCatalog;
readonly hidesHeldText: boolean;
readonly pendingApprovalsNote: string | undefined;
diff --git a/packages/eve/src/harness/session-machine/transitions.ts b/packages/eve/src/harness/session-machine/transitions.ts
index d2843d640..0e0885f38 100644
--- a/packages/eve/src/harness/session-machine/transitions.ts
+++ b/packages/eve/src/harness/session-machine/transitions.ts
@@ -12,6 +12,7 @@ import {
createAuthorizationCompletedEvent,
createAuthorizationRequiredEvent,
createContextClearedEvent,
+ createHistoryImportedEvent,
createInputRequestedEvent,
createInputResolvedEvent,
createMessageReceivedEvent,
@@ -46,6 +47,7 @@ import {
} from "#protocol/session-projection.js";
import type { RuntimeActionResult } from "#shared/action-types.js";
import type { JsonObject, JsonValue } from "#shared/json.js";
+import type { SessionHistoryMessage } from "#shared/session-history.js";
import type { TokenUsage } from "#shared/token-usage.js";
import type { Transition } from "./commit.js";
import { inputWithdrawn, signInWithdrawn } from "./events.js";
@@ -93,11 +95,12 @@ function at(projection: SessionProjection) {
/**
* Input arrives: the session starts once, a turn opens unless one is open (steering joins it),
- * and a message is received.
+ * any history the delivery added is published, and a message is received.
*/
export function receive(
view: SessionView,
input: {
+ readonly imported?: readonly SessionHistoryMessage[];
readonly message?: string | UserContent;
/** The session this one replaced, when eve started it in place of a stranded one. */
readonly predecessor?: SessionPredecessor;
@@ -126,6 +129,15 @@ export function receive(
}),
);
}
+ if (input.imported !== undefined && input.imported.length > 0) {
+ events.push(
+ createHistoryImportedEvent({
+ messages: input.imported,
+ sequence: position.sequence,
+ turnId,
+ }),
+ );
+ }
if (input.message !== undefined) {
events.push(
createMessageReceivedEvent({ message: input.message, sequence: position.sequence, turnId }),
diff --git a/packages/eve/src/harness/step/context.ts b/packages/eve/src/harness/step/context.ts
index b7973551b..547df2370 100644
--- a/packages/eve/src/harness/step/context.ts
+++ b/packages/eve/src/harness/step/context.ts
@@ -36,6 +36,7 @@ import type {
import type { InstrumentationStepScope } from "#instrumentation/runtime.js";
import { createErrorId, createLogger } from "#internal/logging.js";
import { toErrorMessage } from "#shared/errors.js";
+import type { SessionHistoryMessage } from "#shared/session-history.js";
import type { createHistoryViewPreparer } from "#shared/history-view.js";
type HistoryViewPreparer = ReturnType<typeof createHistoryViewPreparer>;
@@ -113,6 +114,8 @@ export function createStep(input: {
export async function openTurn(
step: Step,
opened: {
+ /** Prior conversation the delivery added, published before the message. */
+ readonly imported?: readonly SessionHistoryMessage[];
readonly input: readonly HarnessModelMessage[];
readonly message?: StepInput["message"];
},
@@ -138,6 +141,7 @@ export async function openTurn(
});
await step.apply(
receive(step.view(), {
+ imported: opened.imported,
message: opened.message,
predecessor: ctx?.get(SessionPredecessorKey),
runtime: config.runtimeIdentity,
diff --git a/packages/eve/src/harness/step/intake.ts b/packages/eve/src/harness/step/intake.ts
index 70f46900e..2012d7c49 100644
--- a/packages/eve/src/harness/step/intake.ts
+++ b/packages/eve/src/harness/step/intake.ts
@@ -2,6 +2,7 @@ import { stageAttachmentsToSandbox, stageToolResultMedia } from "#harness/attach
import { forgetFinishedRuns, runtimeResultCalls } from "#harness/coordination.js";
import {
createFrameworkUserMessage,
+ createImportedHistoryMessages,
createUserMessage,
frameworkMessageKindForStepInput,
type HarnessModelMessage,
@@ -13,6 +14,7 @@ import { finishRun, settle } from "#harness/session-machine/transitions.js";
import { activeTurnId, runtimeWait } from "#harness/session-machine/view.js";
import { getTurnClientContextState } from "#harness/turn-client-context.js";
import type { StepInput } from "#harness/types.js";
+import type { SessionHistoryMessage } from "#shared/session-history.js";
import { readClientContext } from "#internal/client-context.js";
import { resolveRuntimeActionResultsForCallIds } from "#runtime/actions/results.js";
import type { Step } from "./context.js";
@@ -60,8 +62,10 @@ export interface TurnInput {
readonly clientContext: readonly string[] | undefined;
readonly storedClientContext: ReturnType<typeof getTurnClientContextState>;
readonly ephemeral: readonly UserModelMessage[];
- /** The context entries and the message, in history order. */
- readonly messages: readonly UserModelMessage[];
+ /** Prior conversation the delivery added, as published in `history.imported`. */
+ readonly imported: readonly SessionHistoryMessage[];
+ /** The added history, the context entries, and the message, in history order. */
+ readonly messages: readonly HarnessModelMessage[];
/** The input carries a user's message, which follows tool results across a boundary. */
readonly hasUserMessage: boolean;
}
@@ -82,9 +86,13 @@ export async function prepareTurnInput(
(clientContext ?? storedClientContext?.messages)?.map((content) =>
createFrameworkUserMessage("context.instruction", content),
) ?? [];
- const messages: UserModelMessage[] = (input?.context ?? []).map((entry) =>
- createFrameworkUserMessage("context.instruction", entry),
- );
+ const imported = input?.history ?? [];
+ const messages: HarnessModelMessage[] = [
+ ...createImportedHistoryMessages(imported),
+ ...(input?.context ?? []).map((entry) =>
+ createFrameworkUserMessage("context.instruction", entry),
+ ),
+ ];
const kind = frameworkMessageKindForStepInput(input);
const content = normalizeUserContent(input?.message);
const staged =
@@ -102,6 +110,7 @@ export async function prepareTurnInput(
clientContext,
ephemeral,
hasUserMessage: staged !== undefined && kind === undefined,
+ imported,
messages,
storedClientContext,
turnId,
diff --git a/packages/eve/src/harness/tool-loop.test.ts b/packages/eve/src/harness/tool-loop.test.ts
index 6894483c8..48cc57d99 100644
--- a/packages/eve/src/harness/tool-loop.test.ts
+++ b/packages/eve/src/harness/tool-loop.test.ts
@@ -1488,6 +1488,71 @@ describe("createToolLoopHarness", () => {
).rejects.toThrow(/Dynamic model selection is required/);
});
+ it("adds delivered history before each turn's context and message", async () => {
+ setupMockAgent({
+ finishReason: "stop",
+ response: { messages: [{ content: "ok", role: "assistant" }] },
+ text: "ok",
+ toolCalls: [],
+ toolResults: [],
+ });
+ const { emit, events } = createEventCollector();
+ const runStep = createToolLoopHarness(createTestConfig(emit));
+
+ const first = await runStep(createTestSession(), {
+ context: ["Current context"],
+ history: [
+ { id: "m1", role: "user", text: "What is the code word?" },
+ { role: "assistant", text: "It is heron." },
+ ],
+ message: "Repeat it.",
+ });
+ await runStep(first.session, {
+ history: [{ role: "user", text: "Bob: it changed to egret." }],
+ message: "And now?",
+ });
+
+ const agents = vi
+ .mocked(ToolLoopAgent)
+ .mock.results.map((result) => result.value as { stream: ReturnType<typeof vi.fn> });
+ expect(agents[0]?.stream.mock.calls[0]?.[0].messages).toEqual([
+ {
+ content: "What is the code word?",
+ kind: "user",
+ metadata: { "eve.imported": true },
+ role: "user",
+ },
+ { content: "It is heron.", role: "assistant" },
+ { content: "Current context", kind: "context.instruction", role: "user" },
+ { content: "Repeat it.", kind: "user", role: "user" },
+ ]);
+ expect(agents[1]?.stream.mock.calls[0]?.[0].messages.slice(-3)).toEqual([
+ { content: "ok", role: "assistant" },
+ {
+ content: "Bob: it changed to egret.",
+ kind: "user",
+ metadata: { "eve.imported": true },
+ role: "user",
+ },
+ { content: "And now?", kind: "user", role: "user" },
+ ]);
+ const received = events.filter(
+ (event) => event.type === "history.imported" || event.type === "message.received",
+ );
+ expect(received.map((event) => [event.type, event.data.turnId])).toEqual([
+ ["history.imported", "turn_0"],
+ ["message.received", "turn_0"],
+ ["history.imported", "turn_1"],
+ ["message.received", "turn_1"],
+ ]);
+ expect(received[0]?.data).toMatchObject({
+ messages: [
+ { id: "m1", role: "user", text: "What is the code word?" },
+ { role: "assistant", text: "It is heron." },
+ ],
+ });
+ });
+
it("passes projected history and incoming input to turn.started on every turn", async () => {
setupMockAgent({
finishReason: "stop",
diff --git a/packages/eve/src/harness/tool-loop.ts b/packages/eve/src/harness/tool-loop.ts
index 0145ad51e..90b84def8 100644
--- a/packages/eve/src/harness/tool-loop.ts
+++ b/packages/eve/src/harness/tool-loop.ts
@@ -132,6 +132,7 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {
});
if (intake.opensTurn) {
const failed = await openTurn(step, {
+ imported: turn.imported,
input: [...turn.ephemeral, ...turn.messages],
message: intake.message,
});
diff --git a/packages/eve/src/harness/types.ts b/packages/eve/src/harness/types.ts
index 73169cde7..714ab3b5e 100644
--- a/packages/eve/src/harness/types.ts
+++ b/packages/eve/src/harness/types.ts
@@ -20,6 +20,7 @@ import type { HarnessToolDefinition } from "#harness/execute-tool.js";
import type { HarnessModelMessage } from "#harness/messages.js";
import type { SessionInstrumentation } from "#instrumentation/runtime.js";
import type { HistoryViewProjector, PreparedHistoryView } from "#shared/history-view.js";
+import type { SessionHistoryMessage } from "#shared/session-history.js";
/**
* Serializable tool definition stored on the session.
@@ -165,6 +166,12 @@ export interface StepInput {
* delivery message. Populated by channels via `SendPayload.context`.
*/
readonly context?: readonly string[];
+ /**
+ * Prior conversation from the channel delivery, added as user and assistant
+ * turns before this turn's context and message. Populated by channels via
+ * `SendPayload.history`.
+ */
+ readonly history?: readonly SessionHistoryMessage[];
/**
* Run-scoped schema that replaces the session's current output schema when
* present. Omitted continuations keep the existing schema.
diff --git a/packages/eve/src/internal/testing/mocks/mock-channel-operations.ts b/packages/eve/src/internal/testing/mocks/mock-channel-operations.ts
index 1d198c5e1..15a295c59 100644
--- a/packages/eve/src/internal/testing/mocks/mock-channel-operations.ts
+++ b/packages/eve/src/internal/testing/mocks/mock-channel-operations.ts
@@ -27,6 +27,9 @@ export function mockChannelContext<TState = undefined>(
async send(message, options) {
return (await observeDelivery(continuationToken, { ...options, message })) as never;
},
+ async create() {
+ return { id: `session:${continuationToken}` } as never;
+ },
async respond(inputResponses, options) {
return (await observeDelivery(continuationToken, {
...options,
diff --git a/packages/eve/src/protocol/message.ts b/packages/eve/src/protocol/message.ts
index 1c9edabdd..99f1f7680 100644
--- a/packages/eve/src/protocol/message.ts
+++ b/packages/eve/src/protocol/message.ts
@@ -199,6 +199,28 @@ export interface SessionStartedStreamEvent {
type: "session.started";
}
+/** One message a delivery added with `history`, as `history.imported` publishes it. */
+export interface HistoryImportedMessage {
+ /** App-owned id the history entry carried, when one was supplied. */
+ readonly id?: string;
+ readonly role: "user" | "assistant";
+ readonly text: string;
+}
+
+/**
+ * Stream event emitted when a delivery adds prior conversation with `history`.
+ * It precedes that delivery's `message.received` in the same turn; the
+ * messages sit in model history just before that turn's input.
+ */
+export interface HistoryImportedStreamEvent {
+ data: {
+ messages: readonly HistoryImportedMessage[];
+ sequence: number;
+ turnId: string;
+ };
+ type: "history.imported";
+}
+
/**
* Stream event emitted when one runtime turn starts.
*/
@@ -899,6 +921,7 @@ export type UnstampedMessageStreamEvent =
| ApprovalSettledStreamEvent
| ContextClearedStreamEvent
| CompactionCompletedStreamEvent
+ | HistoryImportedStreamEvent
| CompactionRequestedStreamEvent
| AuthorizationCompletedStreamEvent
| AuthorizationRequiredStreamEvent
@@ -978,6 +1001,18 @@ export function isTurnFailureEvent<TEvent extends UnstampedMessageStreamEvent>(
);
}
+/** Creates the `history.imported` event for the messages one delivery added. */
+export function createHistoryImportedEvent(input: {
+ readonly messages: readonly HistoryImportedMessage[];
+ readonly sequence: number;
+ readonly turnId: string;
+}): HistoryImportedStreamEvent {
+ return {
+ data: { messages: input.messages, sequence: input.sequence, turnId: input.turnId },
+ type: "history.imported",
+ };
+}
+
/**
* Creates the `session.started` event for one session.
*/
diff --git a/packages/eve/src/public/channels/discord/discordChannel.ts b/packages/eve/src/public/channels/discord/discordChannel.ts
index c61004202..19875d2a4 100644
--- a/packages/eve/src/public/channels/discord/discordChannel.ts
+++ b/packages/eve/src/public/channels/discord/discordChannel.ts
@@ -1,4 +1,5 @@
import type { DiscordInstrumentationMetadata } from "#public/channels/discord/index.js";
+import type { SessionHistoryMessage } from "#shared/session-history.js";
import type { ChannelFrom } from "#channel/channel-operations.js";
import {
INACTIVE_REQUEST_NOTICE,
@@ -143,6 +144,8 @@ export type DiscordCommandResult = {
readonly auth: SessionAuthContext | null;
readonly ephemeral?: boolean;
readonly context?: readonly string[];
+ /** Prior conversation added as user and assistant turns before this message. */
+ readonly history?: readonly SessionHistoryMessage[];
readonly title?: string;
} | null;
@@ -692,6 +695,7 @@ async function dispatchCommand(input: {
.send(turnMessage, {
auth: input.result.auth,
context: [contextBlock, ...channelContext],
+ history: input.result.history,
state: input.state,
title: input.result.title,
});
diff --git a/packages/eve/src/public/channels/github/dispatch.ts b/packages/eve/src/public/channels/github/dispatch.ts
index 16883e0c0..c881c1d3e 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 { SessionHistoryMessage } from "#shared/session-history.js";
import type { ChannelFrom } from "#channel/channel-operations.js";
import { createLogger, logError } from "#internal/logging.js";
@@ -250,6 +251,7 @@ async function dispatchWebhookEventTurn(input: {
hook: result.context,
}),
from: input.from,
+ history: result.history,
state: input.state,
title: result.title,
});
@@ -289,6 +291,7 @@ async function dispatchCommentTurn(input: {
hook: result.context,
}),
from: input.from,
+ history: result.history,
state: input.state,
title: result.title,
});
@@ -318,6 +321,7 @@ async function sendGitHubTurn(input: {
readonly message: string;
readonly context: readonly string[] | undefined;
readonly from: ChannelFrom<GitHubChannelState>;
+ readonly history?: readonly SessionHistoryMessage[];
readonly state: GitHubChannelState;
readonly title: string | undefined;
}): Promise<void> {
@@ -337,6 +341,7 @@ async function sendGitHubTurn(input: {
await input.from(continuationTokenFromState(input.state)).send(input.message, {
auth: input.auth,
context: [contextBlock, ...(input.context ?? [])],
+ history: input.history,
state: input.state,
title: input.title,
});
diff --git a/packages/eve/src/public/channels/github/githubChannel.ts b/packages/eve/src/public/channels/github/githubChannel.ts
index 0c4a977f3..c3d8c346c 100644
--- a/packages/eve/src/public/channels/github/githubChannel.ts
+++ b/packages/eve/src/public/channels/github/githubChannel.ts
@@ -1,4 +1,5 @@
import type { SessionHandle } from "#channel/session.js";
+import type { SessionHistoryMessage } from "#shared/session-history.js";
import type { SessionAuthContext, TurnPolicy } from "#channel/types.js";
import type { SessionContext } from "#public/definitions/callback-context.js";
import type { ChannelContinuationOps } from "#public/definitions/channel.js";
@@ -109,6 +110,8 @@ export interface GitHubEventContext extends GitHubChannelContext, ChannelContinu
export type GitHubInboundResult = {
readonly auth: SessionAuthContext | null;
readonly context?: readonly string[];
+ /** Prior conversation added as user and assistant turns before this message. */
+ readonly history?: readonly SessionHistoryMessage[];
/** Overrides the workflow run title without changing the message sent to the model. */
readonly title?: string;
} | null;
diff --git a/packages/eve/src/public/channels/index.ts b/packages/eve/src/public/channels/index.ts
index 9bb0dd8a0..f1a7642be 100644
--- a/packages/eve/src/public/channels/index.ts
+++ b/packages/eve/src/public/channels/index.ts
@@ -26,6 +26,8 @@ export {
type ChannelReceiveContext,
type ChannelResolveSession,
type ChannelRespondOptions,
+ type ChannelCreateOptions,
+ type ChannelCreateResult,
type ChannelSendOptions,
type ChannelSource,
type ChannelCors,
@@ -66,6 +68,7 @@ export type {
FetchFileFunction,
FetchFileResult,
} from "#shared/channel-definition.js";
+export { InvalidSessionHistoryError, type SessionHistoryMessage } from "#shared/session-history.js";
export {
createWebSocketUpgradeServer,
type WebSocketUpgradeServerBridge,
diff --git a/packages/eve/src/public/channels/linear/linearChannel.ts b/packages/eve/src/public/channels/linear/linearChannel.ts
index 50aa43e0d..e70120789 100644
--- a/packages/eve/src/public/channels/linear/linearChannel.ts
+++ b/packages/eve/src/public/channels/linear/linearChannel.ts
@@ -1,4 +1,5 @@
import type { PromptQueueState } from "#channel/prompt-queue.js";
+import type { SessionHistoryMessage } from "#shared/session-history.js";
import type { SessionHandle } from "#channel/session.js";
import type { SessionAuthContext, TurnPolicy } from "#channel/types.js";
import type { ChannelFrom } from "#channel/channel-operations.js";
@@ -165,6 +166,8 @@ export interface LinearChannelEvents {
export type LinearInboundResult = {
readonly auth: SessionAuthContext | null;
readonly context?: readonly string[];
+ /** Prior conversation added as user and assistant turns before this message. */
+ readonly history?: readonly SessionHistoryMessage[];
/** Overrides the workflow run title without changing the message sent to the model. */
readonly title?: string;
} | null;
@@ -366,6 +369,7 @@ async function dispatchAgentSession(input: {
...event.previousComments,
...(result.context ?? []),
],
+ history: result.history,
state: stateFromAgentSession(event.agentSession),
title: result.title,
});
diff --git a/packages/eve/src/public/channels/linq/linqChannel.ts b/packages/eve/src/public/channels/linq/linqChannel.ts
index e6c9c4f1d..16c2a2406 100644
--- a/packages/eve/src/public/channels/linq/linqChannel.ts
+++ b/packages/eve/src/public/channels/linq/linqChannel.ts
@@ -1,4 +1,5 @@
import type { SessionAuthContext, TurnPolicy } from "#channel/types.js";
+import type { SessionHistoryMessage } from "#shared/session-history.js";
import { vercelOidc } from "#public/channels/auth.js";
import {
chatSdkChannel,
@@ -33,6 +34,8 @@ export interface LinqInboundMessageContext {
export type LinqInboundResult = {
readonly auth: SessionAuthContext | null;
readonly context?: readonly string[];
+ /** Prior conversation added as user and assistant turns before this message. */
+ readonly history?: readonly SessionHistoryMessage[];
/** Overrides the workflow run title without changing the message sent to the model. */
readonly title?: string;
} | null;
@@ -190,6 +193,7 @@ async function dispatchMessage(
await bridge.send(content, {
auth: result.auth,
context: [...(result.context ?? [])],
+ history: result.history,
thread,
title: result.title,
});
diff --git a/packages/eve/src/public/channels/photon/photonIMessageChannel.ts b/packages/eve/src/public/channels/photon/photonIMessageChannel.ts
index d114a65d0..e6d618ff3 100644
--- a/packages/eve/src/public/channels/photon/photonIMessageChannel.ts
+++ b/packages/eve/src/public/channels/photon/photonIMessageChannel.ts
@@ -1,4 +1,5 @@
import type { SessionAuthContext, TurnPolicy } from "#channel/types.js";
+import type { SessionHistoryMessage } from "#shared/session-history.js";
import { vercelOidc } from "#public/channels/auth.js";
import {
chatSdkChannel,
@@ -33,6 +34,8 @@ export interface PhotonInboundMessageContext {
export type PhotonInboundResult = {
readonly auth: SessionAuthContext | null;
readonly context?: readonly string[];
+ /** Prior conversation added as user and assistant turns before this message. */
+ readonly history?: readonly SessionHistoryMessage[];
/** Overrides the workflow run title without changing the message sent to the model. */
readonly title?: string;
} | null;
@@ -149,6 +152,7 @@ async function dispatchMessage(
await bridge.send(content, {
auth: result.auth,
context: [...(result.context ?? [])],
+ history: result.history,
thread,
title: result.title,
});
diff --git a/packages/eve/src/public/channels/slack/model-context.ts b/packages/eve/src/public/channels/slack/model-context.ts
index db68dac1e..8f1930e35 100644
--- a/packages/eve/src/public/channels/slack/model-context.ts
+++ b/packages/eve/src/public/channels/slack/model-context.ts
@@ -1,6 +1,7 @@
import type { SlackThreadMessage } from "#public/channels/slack/api.js";
import type { SlackInboundContext } from "#public/channels/slack/inbound.js";
import { slackMrkdwnToGfm } from "#public/channels/slack/mrkdwn.js";
+import type { SessionHistoryMessage } from "#shared/session-history.js";
interface SlackModelMessageInput {
readonly botUserId?: string;
@@ -102,3 +103,30 @@ function slackThreadSenderType(message: SlackThreadMessage): SlackModelMessageIn
if (message.user) return "user";
return "unknown";
}
+
+/**
+ * Maps fetched thread replies to seeded session history. This app's own replies become assistant
+ * turns; everyone else stays an attributed user message. Slack shows rendered output, so assistant
+ * turns approximate what the model said.
+ */
+export function slackThreadSessionHistory(
+ messages: readonly SlackThreadMessage[],
+): SessionHistoryMessage[] {
+ return messages.flatMap((message) => slackThreadHistoryMessage(message) ?? []);
+}
+
+function slackThreadHistoryMessage(message: SlackThreadMessage): SessionHistoryMessage | undefined {
+ if (message.markdown.trim().length === 0) return undefined;
+ if (message.isMe) return { id: message.ts, role: "assistant", text: message.markdown };
+ return {
+ id: message.ts,
+ role: "user",
+ text: formatSlackModelMessage({
+ content: message.markdown,
+ senderId: message.user ?? message.botId,
+ senderType: slackThreadSenderType(message),
+ threadTs: message.threadTs,
+ ts: message.ts,
+ }),
+ };
+}
diff --git a/packages/eve/src/public/channels/slack/slackChannel.test.ts b/packages/eve/src/public/channels/slack/slackChannel.test.ts
index 1f69990ec..006dc1f69 100644
--- a/packages/eve/src/public/channels/slack/slackChannel.test.ts
+++ b/packages/eve/src/public/channels/slack/slackChannel.test.ts
@@ -3303,6 +3303,71 @@ describe("slackChannel() inbound mention pipeline", () => {
);
});
+ it("adds prior thread replies as history when a mention starts the thread's session", async () => {
+ const threadTs = "1700000000.000001";
+ const currentTs = "1700000000.000004";
+ fetchMock.mockImplementation(async (request: string | URL | Request) => {
+ if (String(request).includes("conversations.replies")) {
+ return new Response(
+ JSON.stringify({
+ ok: true,
+ messages: [
+ { user: "U_ROOT", text: "Daily report?", ts: threadTs, thread_ts: threadTs },
+ {
+ app_id: "A01",
+ bot_id: "B_AGENT",
+ text: "Deploys are green.",
+ ts: "1700000000.000002",
+ thread_ts: threadTs,
+ user: "U_BOT",
+ },
+ { user: "U_OTHER", text: "Thanks!", ts: "1700000000.000003", thread_ts: threadTs },
+ { user: "U_CURRENT", text: "Any flakes?", ts: currentTs, thread_ts: threadTs },
+ ],
+ }),
+ { headers: { "content-type": "application/json" } },
+ );
+ }
+ return new Response(JSON.stringify({ ok: true, ts: "1700000001.000001" }), {
+ headers: { "content-type": "application/json" },
+ });
+ });
+ const channel = slackChannel({
+ credentials: { botToken: "xoxb-test" },
+ onAppMention: () => ({ auth: null }),
+ threadContext: {},
+ });
+ const body = buildEventBody(
+ {
+ channel: "C01",
+ event_ts: currentTs,
+ text: "Any flakes?",
+ thread_ts: threadTs,
+ ts: currentTs,
+ type: "app_mention",
+ user: "U_CURRENT",
+ },
+ { authorizations: [{ is_bot: true, user_id: "U_BOT" }] },
+ );
+
+ const { send } = await firePost(channel, buildSignedRequest({ body }), {
+ resolveSession: async () => undefined,
+ });
+
+ const [, input] = send.mock.calls[0]! as [
+ string,
+ { history?: readonly { id?: string; role: string; text: string }[]; message: string },
+ ];
+ expect(input.message).not.toContain("<slack_thread_context>");
+ expect(input.history?.map(({ id, role }) => ({ id, role }))).toEqual([
+ { id: threadTs, role: "user" },
+ { id: "1700000000.000002", role: "assistant" },
+ { id: "1700000000.000003", role: "user" },
+ ]);
+ expect(input.history?.[0]?.text).toContain("sender_id: U_ROOT");
+ expect(input.history?.[1]?.text).toBe("Deploys are green.");
+ });
+
it("does not dispatch when onAppMention resolves to null", async () => {
const channel = slackChannel({
credentials: { botToken: "xoxb-test" },
@@ -3782,13 +3847,14 @@ describe("slackChannel() generic Events API pipeline", () => {
expect(compact).toHaveBeenCalledWith("C01:1700000000.000001");
});
- it("binds Slack state and title on a generic event send", async () => {
+ it("binds Slack state, title, and history on a generic event send", 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,
+ history: [{ role: "user", text: "Earlier question" }],
target: { channelId: "C01", threadTs: "1700000000.000001" },
title: "Reaction follow-up",
});
@@ -3800,6 +3866,7 @@ describe("slackChannel() generic Events API pipeline", () => {
expect(send).toHaveBeenCalledWith("C01:1700000000.000001", {
auth: null,
+ history: [{ role: "user", text: "Earlier question" }],
message: "follow up",
state: {
channelId: "C01",
diff --git a/packages/eve/src/public/channels/slack/slackChannel.ts b/packages/eve/src/public/channels/slack/slackChannel.ts
index 92bcfe75c..d8488bfac 100644
--- a/packages/eve/src/public/channels/slack/slackChannel.ts
+++ b/packages/eve/src/public/channels/slack/slackChannel.ts
@@ -13,6 +13,7 @@ import type { DeliverPayload, SessionAuthContext, TurnPolicy } from "#channel/ty
import type { VercelConnectMetadata } from "#shared/vercel-connect-metadata.js";
import type { CardElement } from "#compiled/chat/index.js";
import type { SessionContext } from "#public/definitions/callback-context.js";
+import type { SessionHistoryMessage } from "#shared/session-history.js";
import type { ChannelContinuationOps } from "#public/definitions/channel.js";
import { maxBytesOf } from "#internal/attachments/limited-read.js";
@@ -81,6 +82,7 @@ import {
import {
formatSlackInboundMessage,
formatSlackThreadContext,
+ slackThreadSessionHistory,
} from "#public/channels/slack/model-context.js";
import { isPrivateSlackConversation } from "#public/channels/slack/privacy.js";
import {
@@ -359,6 +361,8 @@ export interface SlackInitialMessage {
*/
export interface SlackEventSendOptions {
readonly auth: SessionAuthContext | null;
+ /** Prior conversation added as user and assistant turns before the message. */
+ readonly history?: readonly SessionHistoryMessage[];
readonly target: SlackReceiveTarget;
/** Overrides the workflow run title without changing the message sent to the model. */
readonly title?: string;
@@ -581,12 +585,15 @@ export type SlackInputResponseResult = { readonly auth: SessionAuthContext | nul
* Result of an `onAppMention` or `onDirectMessage` callback. Return an
* object (auth may be `null`) to dispatch a turn, or `null` to drop the
* inbound message. `context` strings are appended as user messages to
- * session history before the delivery message. `title` overrides the
- * workflow run title without changing the message sent to the model.
+ * session history before the delivery message. `history` entries are added as
+ * user and assistant turns before it; when present, `threadContext` keeps its
+ * transcript and never seeds. `title` overrides the workflow run title without
+ * changing the message sent to the model.
*/
export type SlackMentionResult = {
readonly auth: SessionAuthContext | null;
readonly context?: readonly string[];
+ readonly history?: readonly SessionHistoryMessage[];
readonly title?: string;
} | null;
@@ -654,7 +661,9 @@ export interface SlackChannelConfig {
/**
* Adds earlier replies from the current Slack thread to each triggering
* turn. Messages are rendered with their Slack sender ids attached so a
- * multi-user transcript retains unambiguous speaker attribution. Omit this
+ * multi-user transcript retains unambiguous speaker attribution. When the
+ * message starts the thread's session, the same replies are added as
+ * history instead: this app's replies become assistant turns. Omit this
* option to avoid fetching thread history.
*/
readonly threadContext?: LoadThreadContextMessagesOptions;
@@ -968,6 +977,7 @@ function defaultOnInputResponse(ctx: SlackInputResponseContext): SlackInputRespo
async function receiveOnSlack(
input: {
readonly auth: SessionAuthContext | null;
+ readonly history?: readonly SessionHistoryMessage[];
readonly message: string | UserContent;
readonly target: SlackReceiveTarget;
readonly title?: string;
@@ -1049,7 +1059,7 @@ async function receiveOnSlack(
return deps
.from(slackContinuationToken(channelId, continuationThreadTs))
- .send(input.message, { auth: input.auth, state, title: input.title });
+ .send(input.message, { auth: input.auth, history: input.history, state, title: input.title });
}
function shouldDropSlackHttpTimeoutRetry(headers: Headers): boolean {
@@ -1375,9 +1385,9 @@ async function dispatchSlackEvent(input: {
typeof input.envelope.event.user === "string" ? input.envelope.event.user : undefined,
),
}),
- send: (message, { auth, target, title }) =>
+ send: (message, { auth, history, target, title }) =>
receiveOnSlack(
- { auth, message, target, title },
+ { auth, history, message, target, title },
{
from: input.from,
api: input.api,
@@ -1456,7 +1466,15 @@ async function deliverSlackMessage(input: {
input.threadContext === undefined
? []
: await loadThreadContextMessages(thread, message, input.threadContext);
- const threadContext = formatSlackThreadContext(priorMessages);
+ // A message that starts the thread's session carries the replies as history; a started
+ // session gets them as a transcript, as before. Authored history keeps the transcript.
+ const seedsHistory =
+ priorMessages.length > 0 &&
+ input.result.history === undefined &&
+ (await input.sessionOperations.resolveSession()) === undefined;
+ const threadContext = seedsHistory ? undefined : formatSlackThreadContext(priorMessages);
+ const history =
+ input.result.history ?? (seedsHistory ? slackThreadSessionHistory(priorMessages) : undefined);
const fileParts = await collectInboundFileParts({
botUserId: input.botUserId,
fetchThreadWindow: (latest, size) => fetchSlackThreadWindow(thread, latest, size),
@@ -1487,9 +1505,12 @@ async function deliverSlackMessage(input: {
? PRIVATE_SLACK_RUN_TITLE
: (input.result.title ?? message.markdown);
const sendOptions: SlackSendOptions = attachInputText(
- channelContext.length === 0
- ? { auth: input.result.auth, title }
- : { auth: input.result.auth, context: channelContext, title },
+ {
+ auth: input.result.auth,
+ title,
+ ...(channelContext.length > 0 && { context: channelContext }),
+ ...(history !== undefined && { history }),
+ },
// The envelope stays model-visible; pending input matches what the person typed.
input.resolvesTypedInput && fileParts.length === 0
? slackTypedText(message.text, input.botUserId)
diff --git a/packages/eve/src/public/channels/teams/teamsChannel.ts b/packages/eve/src/public/channels/teams/teamsChannel.ts
index e9c489967..106d9b60f 100644
--- a/packages/eve/src/public/channels/teams/teamsChannel.ts
+++ b/packages/eve/src/public/channels/teams/teamsChannel.ts
@@ -1,4 +1,5 @@
import { defaultDeliverResult } from "#channel/adapter.js";
+import type { SessionHistoryMessage } from "#shared/session-history.js";
import type { TeamsInstrumentationMetadata } from "#public/channels/teams/index.js";
import type { ChannelFrom, ChannelResolveSession } from "#channel/channel-operations.js";
import {
@@ -164,6 +165,8 @@ export interface TeamsReceiveTarget {
export type TeamsInboundResult = {
readonly auth: SessionAuthContext | null;
readonly context?: readonly string[];
+ /** Prior conversation added as user and assistant turns before this message. */
+ readonly history?: readonly SessionHistoryMessage[];
/** Overrides the workflow run title without changing the message sent to the model. */
readonly title?: string;
} | null;
@@ -680,6 +683,7 @@ async function dispatchMessage(input: {
await input.from(continuationToken).send(turnMessage, {
auth: result.auth,
context: [formatTeamsContextBlock(inboundContext), ...channelContext],
+ history: result.history,
state,
title: result.title,
});
diff --git a/packages/eve/src/public/channels/telegram/telegramChannel.ts b/packages/eve/src/public/channels/telegram/telegramChannel.ts
index 7b3332bfb..b63a29fc3 100644
--- a/packages/eve/src/public/channels/telegram/telegramChannel.ts
+++ b/packages/eve/src/public/channels/telegram/telegramChannel.ts
@@ -1,4 +1,5 @@
import type { TelegramInstrumentationMetadata } from "#public/channels/telegram/index.js";
+import type { SessionHistoryMessage } from "#shared/session-history.js";
import { defaultDeliverResult, type ChannelAdapterContext } from "#channel/adapter.js";
import type { ChannelFrom, ChannelResolveSession } from "#channel/channel-operations.js";
import {
@@ -137,6 +138,8 @@ export interface TelegramReceiveTarget {
export type TelegramInboundResult = {
readonly auth: SessionAuthContext | null;
readonly context?: readonly string[];
+ /** Prior conversation added as user and assistant turns before this message. */
+ readonly history?: readonly SessionHistoryMessage[];
/** Overrides the workflow run title without changing the message sent to the model. */
readonly title?: string;
} | null;
@@ -597,6 +600,7 @@ async function dispatchMessage(input: {
await input.from(telegramContinuationTokenFromState(state)).send(turnMessage, {
auth: result.auth,
context: [contextBlock, ...channelContext],
+ history: result.history,
state,
title: result.title,
});
diff --git a/packages/eve/src/public/definitions/channel.ts b/packages/eve/src/public/definitions/channel.ts
index 96461f2a7..74303b0d0 100644
--- a/packages/eve/src/public/definitions/channel.ts
+++ b/packages/eve/src/public/definitions/channel.ts
@@ -13,6 +13,8 @@ import {
import { normalizeChannelCors, type ChannelCorsOptions } from "#channel/cors.js";
import { HTTP_ADAPTER_KIND } from "#channel/http.js";
import type {
+ ChannelCreateOptions,
+ ChannelCreateResult,
ChannelFrom,
ChannelReceiveContext,
ChannelResolveSession,
@@ -51,6 +53,8 @@ export type {
} from "#shared/conversation-context.js";
export type { SessionRespondOptions, SessionSendOptions } from "#channel/session.js";
export type {
+ ChannelCreateOptions,
+ ChannelCreateResult,
ChannelFrom,
ChannelReceiveContext,
ChannelResolveSession,
diff --git a/packages/eve/src/public/definitions/hook.ts b/packages/eve/src/public/definitions/hook.ts
index a6738a14d..85b003afc 100644
--- a/packages/eve/src/public/definitions/hook.ts
+++ b/packages/eve/src/public/definitions/hook.ts
@@ -27,6 +27,7 @@ export interface HookEventMap {
readonly "compaction.completed": ProtocolEvent<"compaction.completed">;
readonly "compaction.requested": ProtocolEvent<"compaction.requested">;
readonly "context.cleared": ProtocolEvent<"context.cleared">;
+ readonly "history.imported": ProtocolEvent<"history.imported">;
readonly "input.requested": ProtocolEvent<"input.requested">;
readonly "input.resolved": ProtocolEvent<"input.resolved">;
readonly "message.appended": ProtocolEvent<"message.appended">;
diff --git a/packages/eve/src/shared/session-history.test.ts b/packages/eve/src/shared/session-history.test.ts
new file mode 100644
index 000000000..772b589f0
--- /dev/null
+++ b/packages/eve/src/shared/session-history.test.ts
@@ -0,0 +1,37 @@
+import { describe, expect, it } from "vitest";
+
+import { InvalidSessionHistoryError, validateSessionHistory } from "#shared/session-history.js";
+
+describe("validateSessionHistory", () => {
+ it("keeps only contract fields and accepts empty history", () => {
+ expect(validateSessionHistory(undefined)).toBeUndefined();
+ expect(validateSessionHistory([])).toEqual([]);
+ expect(
+ validateSessionHistory([
+ { text: "Hi", id: "m1", role: "user", toolCalls: [] },
+ { text: "Hello", role: "assistant" },
+ ]),
+ ).toEqual([
+ { text: "Hi", id: "m1", role: "user" },
+ { text: "Hello", role: "assistant" },
+ ]);
+ });
+
+ it.each([
+ ["a non-array", { role: "user" }, "history must be an array"],
+ ["an unknown role", [{ text: "x", role: "tool" }], 'history[0].role must be "user"'],
+ ["blank text", [{ text: " ", role: "user" }], "history[0].text must be"],
+ ["non-string text", [{ content: [{ type: "text" }], role: "user" }], "history[0].text"],
+ [
+ "a duplicate id",
+ [
+ { text: "a", id: "x", role: "user" },
+ { text: "b", id: "x", role: "assistant" },
+ ],
+ 'history[1].id "x" is not unique',
+ ],
+ ])("rejects %s with a precise error", (_label, history, message) => {
+ expect(() => validateSessionHistory(history)).toThrow(InvalidSessionHistoryError);
+ expect(() => validateSessionHistory(history)).toThrow(message);
+ });
+});
diff --git a/packages/eve/src/shared/session-history.ts b/packages/eve/src/shared/session-history.ts
new file mode 100644
index 000000000..9dde222f2
--- /dev/null
+++ b/packages/eve/src/shared/session-history.ts
@@ -0,0 +1,54 @@
+import { isObject } from "#shared/guards.js";
+
+/**
+ * One prior message passed as `history` to `send()` or `create()`.
+ *
+ * Entries become real user and assistant turns in the session's model history
+ * and are published in the `history.imported` stream event.
+ */
+export interface SessionHistoryMessage {
+ /** Optional app-owned id, echoed in `history.imported` so clients can join annotations. */
+ readonly id?: string;
+ readonly role: "user" | "assistant";
+ /** Plain text. Channels render speaker attribution into this text when needed. */
+ readonly text: string;
+}
+
+/** Thrown when `history` passed to a send does not satisfy the seeding contract. */
+export class InvalidSessionHistoryError extends Error {
+ override readonly name = "InvalidSessionHistoryError";
+}
+
+/**
+ * Validates `history` at the send boundary and returns a normalized copy that
+ * carries only contract fields. Returns `undefined` when `history` is omitted.
+ */
+export function validateSessionHistory(
+ history: unknown,
+): readonly SessionHistoryMessage[] | undefined {
+ if (history === undefined) return undefined;
+ if (!Array.isArray(history)) {
+ throw new InvalidSessionHistoryError("history must be an array of messages.");
+ }
+
+ const ids = new Set<string>();
+ return history.map((entry: unknown, index): SessionHistoryMessage => {
+ const at = `history[${index}]`;
+ if (!isObject(entry)) throw new InvalidSessionHistoryError(`${at} must be an object.`);
+ const { id, role, text } = entry;
+ if (role !== "user" && role !== "assistant") {
+ throw new InvalidSessionHistoryError(`${at}.role must be "user" or "assistant".`);
+ }
+ if (typeof text !== "string" || text.trim().length === 0) {
+ throw new InvalidSessionHistoryError(`${at}.text must be a non-empty string.`);
+ }
+ const message: SessionHistoryMessage = { role, text };
+ if (id === undefined) return message;
+ if (typeof id !== "string" || id.length === 0) {
+ throw new InvalidSessionHistoryError(`${at}.id must be a non-empty string.`);
+ }
+ if (ids.has(id)) throw new InvalidSessionHistoryError(`${at}.id "${id}" is not unique.`);
+ ids.add(id);
+ return { ...message, id };
+ });
+}
diff --git a/research/session-history-seeding.md b/research/session-history-seeding.md
new file mode 100644
index 000000000..cfd2eb5e5
--- /dev/null
+++ b/research/session-history-seeding.md
@@ -0,0 +1,188 @@
+---
+issue: https://github.com/vercel/eve/issues/91
+status: in-progress
+last_updated: "2026-10-20"
+---
+
+# Adding prior history to sessions
+
+> **AI status:** Written entirely by AI; human review pending.
+
+## Summary
+
+Apps want to start or continue an eve session with conversation eve did not produce: a stored
+transcript, a conversation moving from another system, a branch of an earlier exchange, or the
+earlier replies of a Slack thread the agent was mentioned into. Today the only option is
+`context: string[]`. Those strings become user-role messages, so the model reads the prior
+conversation as one user describing it. They also never reach the event stream, so clients cannot
+display them.
+
+This proposal adds a `history` option of user and assistant text. `send()` adds it as real turns
+right before that message, and a new `create()` on channel addresses starts a session from it
+without running a turn. The stream publishes added entries in `history.imported`. History always
+applies where it is passed: nothing is conditional on whether a session already exists.
+
+Requests that converge here: #91 (external transcripts), #3524 (branching from settled history,
+closed as a duplicate), and Slack `threadContext`.
+
+## Authoring API
+
+```ts
+/** One prior message passed as `history`. */
+export interface SessionHistoryMessage {
+ /** Optional app-owned id, echoed in `history.imported`. Unique within one call. */
+ readonly id?: string;
+ readonly role: "user" | "assistant";
+ /** Plain text. Channels render speaker attribution into this text when needed. */
+ readonly text: string;
+}
+```
+
+`create()` starts a session that waits for its first message. It is the primary API for
+migration, app-owned persistence, and branching:
+
+```ts
+POST("/conversations/:id/session", async (req, { from, params }) => {
+ const auth = await authenticate(req);
+ const conversation = await db.conversations.findForUser(params.id!, auth);
+ const { created, session } = await from(`conversation:${conversation.id}`).create({
+ auth,
+ history: conversation.messages.map((m) => ({ id: m.id, role: m.role, text: m.body })),
+ });
+ if (!created) return Response.json({ error: "Already started." }, { status: 409 });
+ return Response.json({ sessionId: session.id });
+});
+```
+
+`send()` takes the same option. That covers channel code that must add history and answer in
+one call, such as seeding from a platform thread:
+
+```ts
+await from(token).send(text, { auth, history: transcript });
+```
+
+Every built-in channel's message hook result, including `eveChannel`'s `onMessage`, gains
+`history?` and passes it to `send()`. `SendPayload`, `ChannelSendOptions`, and `SessionSendOptions`
+carry it for custom channels.
+
+## Semantics
+
+**Always applied.** `send()` history joins that delivery's turn input: it sits after earlier
+history and before the turn's `context` and message, whether the send creates the session or
+continues it. Payloads coalesced into one turn contribute their history in order. History follows
+the same paths as `context`: a message consumed as a plain-text answer to a pending question drops
+both.
+
+**`create()`.** Returns `{ session, created }`. If a session owns the address, it returns that
+session with `created: false`. Otherwise it starts a session without a message and waits, bounded,
+until some session claims the address, so an immediate `send()` finds it. `created` is `true` only
+when the session it started won the claim; a concurrent `create()` or `send()` that wins leaves
+this run to exit without forwarding its history, and the caller sees `created: false`. The history
+waits in session state and joins the first message's turn, so it reaches model history through
+the same path as `send()` history. It leaves session state only once a deliver result carries it,
+so a first message the channel drops does not lose it. A stranded owner makes `create()` throw
+`SessionStrandedError` rather than replace it, since that session may hold the conversation being
+imported; the caller resets the address and calls `create()` again.
+
+**Server-resolved only.** History comes from authored code. The eve HTTP request body does not
+accept it, and no client SDK option sets it. Code that loads stored history must authorize the
+caller against that conversation.
+
+**Validation.** `send()` and `create()` throw `InvalidSessionHistoryError`, exported from
+`eve/channels`, before anything is enqueued. The error names the offending entry and rule: unknown
+role, empty text, or an empty or duplicate id. eve sets no count or size caps; history comes from
+authored code, so the app decides how much prior conversation to load and trims it there.
+
+**Model history.** User entries become `kind: "user"` messages with
+`metadata: { "eve.imported": true }`. Assistant entries become plain assistant text. No tool
+calls, results, files, reasoning, or provider options are created.
+
+**Display history.** `history.imported` carries `messages` in the input shape (`id?`, `role`,
+`text`), `sequence`, and `turnId`, and precedes the `message.received` of the turn the entries joined. The default
+reducer places them before that turn's message, ahead of any unconfirmed optimistic message.
+`transcriptReducer()` includes the entries, and its `{ role, text }` messages are valid `history`, so
+a transcript of a seeded session can seed a branch. Imported messages carry `metadata.imported`
+and no `turnId`, so a turn's response never streams
+into one. Message ids derive from the event, since app ids are unique only within one call; the app
+id rides in `metadata.historyId`.
+
+**Everything else is unchanged.** Session state, sandbox, memory, and pending input are untouched.
+After joining history, entries are ordinary messages: pre-model compaction counts them, compaction
+and deployment handoffs carry them, and `clear()` removes them.
+
+```mermaid
+flowchart LR
+ Create["create({ history })"] --> Pending["pending in session state"]
+ Pending --> First["first message"]
+ Send["send(msg, { history })"] --> Turn["turn input: history, context, message"]
+ First --> Turn
+ Turn --> Event["history.imported, then message.received"]
+```
+
+## Runtime boundary
+
+History is framework-owned turn input next to `context`. The turn step attaches each payload's
+history after the channel's deliver hook runs, so a custom hook cannot drop it. The harness turns
+it into model messages in `prepareTurnInput`, and the `receive` transition publishes the event.
+`create()` reuses message-free session creation; the pending history lives in session state until
+the first message. No new workflow entry kind, checkpoint version, or step is needed. The option
+and event bump the extension capability epochs that expose them; prior epochs stay supported
+because both changes are additive.
+
+## Slack
+
+`threadContext` keeps its options and its behavior for messages in a thread that already has a
+session: the `since` slice is prepended as an attributed transcript. Only a message that starts
+the thread's session changes. Its slice is added as `history`, with this app's replies as
+assistant turns and everyone else as attributed user turns. Choosing between the two needs a
+`resolveSession()` check. A lost race only changes the representation of that slice (history
+versus transcript); nothing is dropped. When a hook returns its own `history`, the transcript
+behavior applies.
+
+Slack shows rendered output, not what the model actually produced, so seeded assistant turns
+approximate it.
+
+## Non-goals
+
+- Reading or forking sessions. Apps can build history from a session's event stream themselves.
+- Client-supplied history over HTTP or the client SDKs.
+- Channel-level history hooks. Most requests create sessions explicitly rather than per thread.
+- Tool calls and results, files and images, reasoning, and provider-specific message parts.
+- Separate display text and model text.
+- Workarounds for stranded sessions (#3022). Those belong in deployment handoff, not in history.
+- Appending history without a turn. #3023's `observe` is that operation.
+
+## Requests and coverage
+
+| Request | Source | Coverage | Notes |
+| --------------------------------------------- | ----------------- | ---------------- | ------------------------------------------------------------------- |
+| Continue a migrated transcript | #91 | Covered for text | `create()` per conversation. Tool calls, reasoning, and files drop. |
+| App-owned persistence | #91 | Covered | Server route calls `create()`; the client resumes by session id. |
+| Clients display imported history | #91, #3524 | Covered | `history.imported` renders on live and replayed streams. |
+| Client-supplied history | #91 | Non-goal | Server-only. |
+| Real roles instead of a transcript blob | #91, #75 | Covered | |
+| Initialize without execution | #3524 | Covered | `create()` runs no model or tool. |
+| Empty history | #3524 | Covered | |
+| Map imported ids | #3524 | Covered | App ids ride in `metadata.historyId`. |
+| Preserve tool calls and results | #3524 | Follow-up | |
+| Clear errors for invalid history | #3524 | Covered | |
+| Settled-history export, fork, or rewind | #3524, #75 | Not covered | Userland can build history from the event stream. |
+| Mid-thread Slack mentions see earlier replies | `threadContext` | Improved | First message adds them as roles; later messages unchanged. |
+| Follow a thread without mentions | #223, #874, #3023 | Out of scope | |
+
+## Validation
+
+- Unit: validation rules; history placement before each turn's context and message across turns;
+ reducer placement before pending optimistic messages and before an active turn's response;
+ Slack seeding on a message that starts the session, with unchanged catch-up.
+- E2E: a fixture channel creates a session from Alice's history, a first message answers from
+ it, and a later `send()` adds Bob's exchange; each turn publishes `history.imported` before its
+ `message.received`.
+
+## Open questions
+
+1. **Imported user message kind.** `"user"` plus metadata treats imported text like typed input. A
+ dedicated kind would let compaction, memory, and filters tell them apart.
+2. **`history.imported` content.** Full text duplicates the inbox payload in the stream.
+3. **Tool calls and results.** A validated tool tier would reuse the legacy import's
+ `normalizeHistory` and state its trust and approval semantics.