eve 0.90.0 → 0.91.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (185) hide show
  1. package/CHANGELOG.md +34 -23
  2. package/dist/src/channel/auth/http-basic.js +1 -1
  3. package/dist/src/channel/channel-operations.d.ts +1 -1
  4. package/dist/src/channel/types.d.ts +2 -0
  5. package/dist/src/cli/dev/tui/prompt-commands.d.ts +1 -1
  6. package/dist/src/client/session.d.ts +1 -1
  7. package/dist/src/compiled/.vendor-stamp.json +1 -1
  8. package/dist/src/execution/dynamic-workflow/tool.js +1 -1
  9. package/dist/src/execution/proxied-deliver-step.js +1 -1
  10. package/dist/src/execution/sandbox/bash.js +2 -2
  11. package/dist/src/execution/session/active-turn.js +1 -1
  12. package/dist/src/execution/session/admission.d.ts +6 -0
  13. package/dist/src/execution/session/admission.js +1 -1
  14. package/dist/src/execution/session/delivery-facts.js +1 -1
  15. package/dist/src/execution/session/next-input.d.ts +2 -2
  16. package/dist/src/execution/session/next-input.js +1 -1
  17. package/dist/src/execution/session/program.js +1 -1
  18. package/dist/src/execution/session-inbox/inbox.d.ts +2 -2
  19. package/dist/src/execution/session-inbox/inbox.js +1 -1
  20. package/dist/src/execution/session-inbox/protocol.js +1 -1
  21. package/dist/src/execution/tools/agent-router-workflow.js +1 -1
  22. package/dist/src/harness/compaction/engine.js +2 -2
  23. package/dist/src/harness/current-messages.js +1 -1
  24. package/dist/src/harness/emission.d.ts +3 -0
  25. package/dist/src/harness/emission.js +1 -1
  26. package/dist/src/harness/facts.d.ts +5 -2
  27. package/dist/src/harness/facts.js +1 -1
  28. package/dist/src/harness/model-call/call.d.ts +7 -1
  29. package/dist/src/harness/model-call/call.js +3 -1
  30. package/dist/src/harness/provider-tool-history.d.ts +8 -0
  31. package/dist/src/harness/provider-tool-history.js +1 -1
  32. package/dist/src/harness/session-machine/transitions.d.ts +3 -2
  33. package/dist/src/harness/step/after-model.js +1 -1
  34. package/dist/src/harness/step/context.js +1 -1
  35. package/dist/src/harness/step/intake.js +1 -1
  36. package/dist/src/harness/step/prompt.js +1 -1
  37. package/dist/src/harness/tool-history-repair.d.ts +2 -0
  38. package/dist/src/harness/tool-history-repair.js +1 -1
  39. package/dist/src/harness/tool-loop.js +1 -1
  40. package/dist/src/internal/application/stamped-package-version.js +1 -1
  41. package/dist/src/protocol/session-events/families/delivery.d.ts +5 -3
  42. package/dist/src/protocol/session-events/families/delivery.js +1 -1
  43. package/dist/src/protocol/session-projection/fold.js +1 -1
  44. package/dist/src/public/channels/discord/hitl.js +1 -1
  45. package/dist/src/public/channels/slack/hitl.d.ts +2 -1
  46. package/dist/src/public/channels/slack/hitl.js +3 -3
  47. package/dist/src/public/channels/slack/interaction-cards.js +1 -1
  48. package/dist/src/public/channels/slack/request-card-render.js +1 -1
  49. package/dist/src/public/channels/teams/hitl.js +1 -1
  50. package/dist/src/public/channels/teams/verify.js +1 -1
  51. package/dist/src/public/definitions/hook.d.ts +90 -7
  52. package/dist/src/public/definitions/hook.js +1 -1
  53. package/dist/src/public/hooks/index.d.ts +3 -2
  54. package/dist/src/reactions/continuation.d.ts +19 -0
  55. package/dist/src/reactions/continuation.js +1 -0
  56. package/dist/src/reactions/intents.d.ts +10 -4
  57. package/dist/src/reactions/intents.js +1 -1
  58. package/dist/src/reactions/kinds/hook.js +1 -1
  59. package/dist/src/reactions/runner.js +1 -1
  60. package/dist/src/reactions/state.d.ts +15 -2
  61. package/dist/src/reactions/state.js +1 -1
  62. package/dist/src/runtime/resolve-connection.js +1 -1
  63. package/dist/src/runtime/subagents/workflow.js +1 -1
  64. package/dist/src/setup/primitives/open-url.js +1 -1
  65. package/dist/src/setup/scaffold/create/project.js +1 -1
  66. package/dist/src/shared/value-delta.d.ts +5 -4
  67. package/dist/src/shared/value-delta.js +1 -1
  68. package/dist/src/tools/provided/ask-question-workflow.js +1 -1
  69. package/dist/src/tools/provided/sleep-workflow.js +1 -1
  70. package/dist/src/tools/provided/web-fetch.js +1 -1
  71. package/docs/agent-config.md +199 -222
  72. package/docs/channels/chat-sdk.mdx +60 -64
  73. package/docs/channels/custom.mdx +264 -281
  74. package/docs/channels/discord.mdx +176 -123
  75. package/docs/channels/eve.mdx +136 -206
  76. package/docs/channels/github.mdx +24 -22
  77. package/docs/channels/linear.mdx +30 -30
  78. package/docs/channels/linq.mdx +25 -13
  79. package/docs/channels/mcp.mdx +154 -116
  80. package/docs/channels/overview.mdx +31 -32
  81. package/docs/channels/photon.mdx +32 -56
  82. package/docs/channels/slack.mdx +538 -375
  83. package/docs/channels/teams.mdx +40 -26
  84. package/docs/channels/telegram.mdx +13 -13
  85. package/docs/channels/twilio.mdx +11 -11
  86. package/docs/code-extension.mdx +40 -42
  87. package/docs/concepts/built-in-tools.md +89 -57
  88. package/docs/concepts/context-control.md +20 -20
  89. package/docs/concepts/default-harness.md +20 -36
  90. package/docs/concepts/execution-model-and-durability.mdx +96 -160
  91. package/docs/concepts/project-structure.mdx +21 -14
  92. package/docs/concepts/security-model.md +27 -27
  93. package/docs/concepts/sessions-runs-and-streaming.md +184 -198
  94. package/docs/concepts/state.md +7 -15
  95. package/docs/connections/mcp.mdx +109 -93
  96. package/docs/connections/openapi.mdx +57 -59
  97. package/docs/connections/overview.mdx +175 -170
  98. package/docs/evals/assertions.mdx +36 -29
  99. package/docs/evals/cases.mdx +38 -42
  100. package/docs/evals/judge.mdx +21 -29
  101. package/docs/evals/overview.mdx +42 -38
  102. package/docs/evals/reporters.mdx +54 -27
  103. package/docs/evals/running.mdx +15 -8
  104. package/docs/evals/targets.mdx +16 -19
  105. package/docs/evals/tool-stubs.mdx +111 -97
  106. package/docs/experimental/dynamic-schedules.mdx +118 -63
  107. package/docs/extensions.md +58 -65
  108. package/docs/getting-started.mdx +4 -6
  109. package/docs/guides/auth-and-route-protection.md +87 -70
  110. package/docs/guides/client/continuations.mdx +23 -26
  111. package/docs/guides/client/messages.mdx +47 -66
  112. package/docs/guides/client/output-schema.mdx +8 -8
  113. package/docs/guides/client/overview.mdx +45 -43
  114. package/docs/guides/client/streaming.mdx +62 -71
  115. package/docs/guides/decide.md +24 -79
  116. package/docs/guides/deployment/meta.json +1 -1
  117. package/docs/guides/deployment/overview.md +27 -18
  118. package/docs/guides/deployment/self-hosted-operations.md +99 -0
  119. package/docs/guides/deployment/self-hosting.md +63 -80
  120. package/docs/guides/deployment/vercel.mdx +31 -27
  121. package/docs/guides/deployment/workflow-worlds.md +100 -0
  122. package/docs/guides/dev-tui.md +48 -41
  123. package/docs/guides/dynamic-capabilities.md +49 -50
  124. package/docs/guides/frontend/nextjs.mdx +2 -2
  125. package/docs/guides/frontend/nuxt.mdx +11 -11
  126. package/docs/guides/frontend/overview.mdx +1 -1
  127. package/docs/guides/frontend/sveltekit.mdx +11 -11
  128. package/docs/guides/frontend/tanstack.mdx +16 -16
  129. package/docs/guides/frontend/use-eve-agent-svelte.mdx +21 -21
  130. package/docs/guides/frontend/use-eve-agent-vue.mdx +22 -22
  131. package/docs/guides/frontend/use-eve-agent.mdx +25 -25
  132. package/docs/guides/hooks.md +152 -106
  133. package/docs/guides/instrumentation/agent-runs.mdx +26 -30
  134. package/docs/guides/instrumentation/instrumentation.mdx +49 -76
  135. package/docs/guides/instrumentation/meta.json +1 -1
  136. package/docs/guides/instrumentation/otel.mdx +113 -179
  137. package/docs/guides/remote-agents.md +125 -187
  138. package/docs/guides/self-modification.md +18 -18
  139. package/docs/guides/session-context.md +16 -16
  140. package/docs/install-integrations.mdx +26 -24
  141. package/docs/instructions.mdx +37 -42
  142. package/docs/memory/custom-provider.md +35 -41
  143. package/docs/memory/file.md +93 -76
  144. package/docs/memory/overview.mdx +145 -156
  145. package/docs/patterns/durable-cross-channel-notifications.md +15 -19
  146. package/docs/patterns/dynamic-scheduling.md +19 -23
  147. package/docs/patterns/multi-tenant-approvals.md +17 -22
  148. package/docs/patterns/multi-tenant-auth.md +43 -42
  149. package/docs/patterns/multi-tenant-memory.md +39 -36
  150. package/docs/patterns/voice-notes.md +3 -3
  151. package/docs/protocols/acp.md +13 -13
  152. package/docs/protocols/ucp.mdx +7 -7
  153. package/docs/reference/agent-files.md +6 -6
  154. package/docs/reference/cli.md +99 -98
  155. package/docs/reference/telemetry.md +1 -1
  156. package/docs/reference/typescript-api.md +52 -53
  157. package/docs/responsible-use.md +2 -2
  158. package/docs/sandbox/custom-providers.mdx +60 -56
  159. package/docs/sandbox/default.mdx +23 -24
  160. package/docs/sandbox/docker.mdx +16 -10
  161. package/docs/sandbox/index.mdx +93 -61
  162. package/docs/sandbox/just-bash.mdx +17 -11
  163. package/docs/sandbox/troubleshooting.mdx +29 -23
  164. package/docs/sandbox/vercel.mdx +45 -52
  165. package/docs/schedules.mdx +65 -54
  166. package/docs/skills.mdx +74 -49
  167. package/docs/subagents/index.mdx +97 -136
  168. package/docs/tools/human-in-the-loop.md +160 -90
  169. package/docs/tools/meta.json +1 -1
  170. package/docs/tools/overview.mdx +229 -237
  171. package/docs/tools/tasks.md +118 -117
  172. package/docs/tools/workflows.mdx +447 -543
  173. package/docs/tutorial/connect-a-warehouse.mdx +11 -13
  174. package/docs/tutorial/first-agent.mdx +14 -16
  175. package/docs/tutorial/guard-the-spend.mdx +6 -8
  176. package/docs/tutorial/how-it-runs.mdx +8 -8
  177. package/docs/tutorial/query-sample-data.mdx +8 -8
  178. package/docs/tutorial/remember-definitions.mdx +4 -4
  179. package/docs/tutorial/run-analysis.mdx +20 -22
  180. package/docs/tutorial/ship-it.mdx +19 -19
  181. package/docs/tutorial/team-playbooks.mdx +9 -9
  182. package/docs/use-cases.mdx +13 -11
  183. package/package.json +1 -1
  184. package/docs/guides/instrumentation/migration.md +0 -96
  185. package/docs/tools/tasks-upgrade.md +0 -218
@@ -3,19 +3,46 @@ title: "Custom Channels"
3
3
  description: "Author custom HTTP and WebSocket channels with routes, events, metadata, continuation tokens, and file uploads."
4
4
  ---
5
5
 
6
- Build a custom channel to connect an HTTP or WebSocket endpoint to your agent. It can host a conversation or pass incoming events to another channel.
6
+ A custom channel connects your own HTTP or WebSocket endpoint to your agent. Each one is a file under `agent/channels/` that default-exports `defineChannel(...)` from `eve/channels`. Use one for an internal webhook, a WebSocket client, or a platform eve has no channel for. A custom channel can host a conversation or pass incoming events to another channel.
7
7
 
8
8
  ## File location and identity
9
9
 
10
- Custom channels live in `agent/channels/` at the root agent or in an [extension](../extensions) mounted there. Local subagents do not declare channels today.
10
+ Custom channels live in `agent/channels/` at the root agent or in an [extension](../extensions) mounted there. Local subagents don't declare channels.
11
11
 
12
- The channel file stem becomes the channel id, so `agent/channels/internal-webhook.ts` is addressed as `internal-webhook`. Export the channel definition as the module's default export.
13
-
14
- Hooks, instrumentation, and `delivery.admitted.data.source.channel` identify an authored channel as `channel:<name>`, including channels that only declare routes. Use `isChannel(ctx.channel, importedChannel)` from `eve/channels` to match a channel in a hook.
12
+ The file stem is the channel id, so `agent/channels/internal-webhook.ts` is addressed as `internal-webhook`. Hooks, instrumentation, and `delivery.admitted.data.source.channel` identify it as `channel:<name>`, including channels that only declare routes. Use `isChannel(ctx.channel, importedChannel)` from `eve/channels` to match a channel in a hook.
15
13
 
16
14
  ## Define a channel
17
15
 
18
- Pass the platform's conversation identity to each operation:
16
+ Declare routes, and pass the platform's conversation ID to `from(...)` in each one. A message to a new ID starts a session; later messages to the same ID continue it:
17
+
18
+ ```ts title="agent/channels/support.ts"
19
+ import { defineChannel, POST } from "eve/channels";
20
+
21
+ export default defineChannel({
22
+ routes: [
23
+ // required: one or more routes; the path is the app URL, with no channel prefix
24
+ POST("/threads/:threadId/messages", async (request, { from, params }) => {
25
+ const body = await request.json();
26
+ // from(address) names the conversation; the same address reaches the same session
27
+ const delivery = await from(params.threadId).send(body.message, { auth: null });
28
+ return Response.json(delivery, { status: 202 });
29
+ }),
30
+ ],
31
+ });
32
+ ```
33
+
34
+ A route's `path` is its app URL, without a channel-name prefix. The route above answers at `POST /threads/:threadId/messages`, not `/support/threads/:threadId/messages`. Give each route a unique method and path outside `/eve/v1/*`, which eve reserves.
35
+
36
+ Each route handler receives:
37
+
38
+ - `from(address)` binds `send`, `respond`, `cancel`, `compact`, `clear`, and `end` to an address: your channel's ID for one conversation, such as a thread ID. See [Continuation tokens](#continuation-tokens).
39
+ - `resolveSession(address)` returns the session that currently uses an address.
40
+ - `attachSession(sessionId)` returns a handle for one session ID, without a lookup.
41
+ - `to(channel, target).send(message, options)` hands work to another authored channel.
42
+ - `params`, `waitUntil`, and `requestIp` provide request metadata and lifetime control.
43
+ - `describe()`, `invokeTool()`, `listSkillFiles()`, and `readSkill()` describe the agent and run its tools without a conversation. See [Describe the agent and run tools directly](#describe-the-agent-and-run-tools-directly).
44
+
45
+ This fuller version adds commands, a stream route, and an event handler:
19
46
 
20
47
  ```ts title="agent/channels/support.ts"
21
48
  import { defineChannel, GET, POST } from "eve/channels";
@@ -78,46 +105,40 @@ export default defineChannel({
78
105
  });
79
106
  ```
80
107
 
81
- A route's `path` is its app URL; the channel filename does not prefix it. The route above answers at `POST /threads/:threadId/messages`, not `/support/threads/:threadId/messages`. Use a unique method-and-path pair for each route, and do not use the framework-owned `/eve/v1/*` namespace.
108
+ Event handlers receive `(event, ctx)`. The event has `type`, `data`, and `scope` (the turn or call it belongs to). Handlers run after eve records the event, so they can't change it.
82
109
 
83
- Each route receives these operation surfaces:
110
+ - `ctx.session.id` identifies the session.
111
+ - `ctx.position` locates the event on the stream, and `ctx.view` is a read-only snapshot of the session at that point.
112
+ - `ctx.channel` is the channel's own context. `ctx.channel.continuation.token` is the address that `from()`, `resolveSession()`, and `alias()` accept, without eve's prefixes. `alias()` adds another address.
84
113
 
85
- - `from(address)` binds `send`, `respond`, `cancel`, `compact`, `clear`, and `end` to a channel-local continuation address.
86
- - `resolveSession(address)` snapshots the session currently owning a channel-local continuation address.
87
- - `attachSession(sessionId)` creates an I/O-free handle pinned to one durable session ID.
88
- - `to(channel, target).send(message, options)` hands work to another authored channel.
89
- - `params`, `waitUntil`, and `requestIp` provide request metadata and lifetime control.
90
- - `describe()` returns the agent's name, description, the compiled tools a caller can run outside a turn, with their JSON schemas, and the compiled skills, each with its `name` and `description`, sorted by name. It reads the compiled manifest only, never a skill file, and carries no other paths, config, or inspection detail, so a channel can publish it to its callers. Tools that need a turn (framework tools, workflow and provider tools, tools without `execute`) and tools and skills added by dynamic resolvers or subagents are left out.
91
- - `invokeTool(name, input, { auth, key })` runs one of those tools as `auth`, outside any conversation: no model, turn, or workflow run. Authored state starts from its initial value and is not kept. Without `key`, each call gets its own session, and a sandbox the tool opens is deleted when the call ends. With `key` (1 to 512 characters), calls from the same `auth` principal with the same key share a session id and a sandbox, which is kept between calls; this needs Vercel Sandbox, just-bash, or a custom provider that sets `toolSessions: true`, and an authenticated `auth` (a keyed call from the anonymous principal is `denied`); see [MCP tool sessions](./mcp#tool-sessions). When a trusted forwarder asserted `auth`, pass the principal your route verified as `forwardedBy`: it is part of the session, so one user reached through two forwarders gets two sessions. It returns `outcome: "completed"` with output, `"failed"` with an error (including invalid input), or `"rejected"` with a reason (including approval or sign-in requirements); a direct call cannot pause for a person.
114
+ One stream line can hold several events. Use `committed(line, ctx)` to update a status or card once per line instead of once per event. It runs after the line's event handlers, with `line.facts`, `line.position`, and the line's snapshot at `ctx.view`.
115
+
116
+ Handle `interaction.settled` to remove a question or approval you posted once it ends, whether it was answered, withdrawn, or interrupted. Match by `interactionId` and check its `outcome`.
117
+
118
+ ### Describe the agent and run tools directly
119
+
120
+ A route handler can also describe the agent and run its tools without a conversation, as the [MCP channel](./mcp) does:
92
121
 
93
- A direct call doesn't go through the AI SDK, so AI SDK telemetry integrations never see it. Conversation tool calls do: an integration that an `agent/instrumentation/*.ts` module registers with `registerTelemetry()` from `ai` receives `onToolExecutionStart` and `onToolExecutionEnd` for each of them. A direct call is traced by eve itself instead. It gets an `execute_tool` span under the caller's trace and emits `call.requested` and `call.settled` to instrumentation, as a conversation's calls do. Over MCP, the caller's trace comes from the request's `_meta` trace context (see [Trace context](./mcp#trace-context)).
122
+ - `describe()` returns the agent's name and description, the tools a caller can run outside a turn, and the agent's skills. Tools carry their JSON schemas, skills carry `name` and `description`, and both are sorted by name.
123
+ - `invokeTool(name, input, { auth, key })` runs one of those tools as `auth` outside any conversation.
124
+ - `listSkillFiles(skill)` resolves to the skill's regular files, each with its `path` under the skill root and `size` in bytes, sorted by path. It rejects a skill the agent doesn't have.
125
+ - `readSkill(skill, path?)` resolves to one skill file's raw bytes as a `Uint8Array`; decode text yourself, for example with `new TextDecoder().decode(bytes)`. `path` is relative to the skill root, such as `references/api.md`; omit it to read `SKILL.md`. It rejects absolute paths, paths with `.`, `..`, or empty segments, files the skill doesn't list, and files over 512 KiB.
94
126
 
95
- - `listSkillFiles(skill)` resolves to the skill's regular files, each with its `path` under the skill root and its `size` in bytes, sorted by path. It rejects a skill the agent does not have.
96
- - `readSkill(skill, path?)` resolves to one skill file's raw bytes as a `Uint8Array`; decode text yourself, for example with `new TextDecoder().decode(bytes)`. `path` is relative to the skill root, such as `references/api.md`, and defaults to the skill's `SKILL.md`. It rejects absolute paths, paths with `.`, `..`, or empty segments, files the skill does not list, and files over 512 KiB.
127
+ `describe()` carries no skill file contents, paths, config, or inspection detail, so a channel can publish it to callers. It leaves out tools that need a turn: framework tools, workflow and provider tools, and tools without `execute`. It also leaves out tools and skills that dynamic resolvers or subagents add.
97
128
 
98
- Event handlers receive `(event, ctx)`: the whole fact, with its `type`, `data`, and
99
- `scope`, and a context. `ctx.session.id` identifies the exact session, `ctx.position`
100
- and `ctx.view` locate the fact on the stream and expose an opaque snapshot of its whole commit,
101
- and `ctx.channel` is the channel's own context. `ctx.channel.continuation` exposes the
102
- current address and `alias()` when this channel needs to add another address. Handlers
103
- run after the line is written, so they observe facts and never shape them.
129
+ `invokeTool()` runs no model, turn, or workflow run. Authored state starts from its initial value and isn't kept. It returns one of these outcomes:
104
130
 
105
- Use `committed(line, ctx)` when you need to update a status or card once per committed line, rather than once per fact. It runs after the line's fact handlers, with `line.facts`, `line.position`, and the whole line's snapshot at `ctx.view`.
131
+ - `"completed"` with output.
132
+ - `"failed"` with an error, including for invalid input.
133
+ - `"rejected"` with a reason, including for approval or sign-in requirements, because a direct call can't pause for a person.
106
134
 
107
- Handle `interaction.settled` to retire a rendered question or approval, whether it was answered, withdrawn, or interrupted. Match by `interactionId` and check its `outcome`.
135
+ Omit `key` to give each call its own session and delete any sandbox the tool opens when the call ends. Pass a `key` of 1 to 512 characters to share a session ID and sandbox across calls from the same `auth` identity. Keyed calls need Vercel Sandbox, just-bash, or a custom provider that sets `toolSessions: true`. They also need an authenticated `auth`; a keyed call without one is `denied`. See [MCP tool sessions](./mcp#tool-sessions). When a trusted forwarder passes `auth` for someone else, pass the forwarder identity your route verified as `forwardedBy`. It's part of the session, so one user reached through two forwarders gets two sessions.
108
136
 
109
- `ctx.channel.continuation.token` is always the channel-local address accepted by
110
- `from()`, `resolveSession()`, and `alias()`. Framework namespace prefixes are not
111
- part of the authored channel API.
137
+ A direct call doesn't go through the AI SDK. AI SDK telemetry integrations registered with `registerTelemetry()` from `ai` in an `agent/instrumentation/*.ts` module receive `onToolExecutionStart` and `onToolExecutionEnd` only for conversation tool calls. eve traces a direct call itself, with an `execute_tool` span under the caller's trace. Instrumentation also receives `call.requested` and `call.settled`. Over MCP, the caller's trace comes from the request's `_meta` trace context (see [Trace context](./mcp#trace-context)).
112
138
 
113
139
  ## Channel operations and session handles
114
140
 
115
- Channel operations are dynamic: every call targets whichever session currently
116
- owns the address. `create()` and `send()` can create a session when the address is unowned.
117
- Without an [idempotency key](#retried-deliveries), a new session's handle can
118
- return before it claims the address. If another send wins the address, eve
119
- forwards the message to that session. Call `resolveSession(address)` after
120
- startup to get the winning session's handle.
141
+ Channel operations reach whichever session currently uses the address. `create()` and `send()` create a session when no session uses it. Without an [idempotency key](#retried-deliveries), a new session's handle can return before the session takes the address. If another send takes it first, eve forwards the message to that session. Call `resolveSession(address)` after startup to get the handle of the session that won.
121
142
 
122
143
  ```ts
123
144
  const source = from(threadId);
@@ -133,21 +154,11 @@ await source.end({ reason: "Start over" });
133
154
  const currentSession = await resolveSession(threadId);
134
155
  ```
135
156
 
136
- When the session at an address is
137
- [stranded](../guides/deployment/self-hosting#recover-a-stranded-session) because another eve version
138
- built it, `send()` ends that session and starts a fresh one. The message becomes the fresh
139
- session's first turn, and the fresh session can read recent text from the earlier conversation;
140
- see [Recover a stranded session](../guides/deployment/self-hosting#recover-a-stranded-session). Concurrent sends to the same stranded address still
141
- produce one fresh session. A `respond()` call, or a `deliver()` that includes input responses,
142
- carries answers a fresh session has no request for, so it throws `SessionStrandedError` and leaves
143
- the stranded session in place.
144
-
145
- `Session` from `eve/sessions` is fixed: every call targets exactly one durable ID. It never
146
- creates, follows, or resolves a replacement. Shared `Delivery`, `DeliveryResult`, `SessionReader`,
147
- stream/read options, and `SessionNotActiveError` also come from `eve/sessions`, not `eve/channels`.
148
- Accepted commands return reusable deliveries: call `stream({ signal })` for events or
149
- `result({ signal })` for a settled summary with its `outcome` and failure `error`. Aborting a read
150
- does not cancel the command or other readers.
157
+ When another eve version built the session at an address, the session is [stranded](../guides/deployment/self-hosted-operations#recover-a-stranded-session). `send()` ends it and starts one fresh session, even for concurrent sends. The message becomes the fresh session's first turn, which can read recent text from the earlier conversation. A `respond()` call, or a `deliver()` with input responses, throws `SessionStrandedError` because a fresh session has no request to answer. The stranded session stays in place.
158
+
159
+ `Session` from `eve/sessions` is fixed to one session ID and never creates, follows, or finds a replacement. `Delivery`, `DeliveryResult`, `SessionReader`, stream and read options, and `SessionNotActiveError` also come from `eve/sessions`, not `eve/channels`.
160
+
161
+ Each accepted operation returns a `Delivery` receipt that you can read more than once. Call `stream({ signal })` for its events, or `result({ signal })` for a summary once it finishes, with its `outcome` and failure `error`. Aborting a read doesn't cancel the operation or other readers.
151
162
 
152
163
  ```ts
153
164
  const session = attachSession(sessionId);
@@ -161,15 +172,9 @@ await session.end({ reason: "Retire this session" });
161
172
  for await (const event of session.stream({ startIndex: 12 })) render(event);
162
173
  ```
163
174
 
164
- A following `getEventStream()` rejects before it returns a stream when the session does not exist
165
- or its recorded history has expired, so a route can answer with an error status before it sends any
166
- bytes.
175
+ Attaching does no lookup; the first operation reports whether the ID is active. A following `stream()` rejects on its first read when the session doesn't exist or its history has expired. A route can read once before sending headers, as the example above does, to answer with an error status.
167
176
 
168
- For a stranded session, `Session.send()`, `Session.respond()`, and a following
169
- read through `Session.stream()` throw `SessionStrandedError` from `eve/channels` and deliver nothing.
170
- `stream({ follow: false })` still reads the recorded history up to the current tail without
171
- changing the session. `error.owner.eveVersion` names the eve release that built the session when it recorded one. Call
172
- `end()` to retire the stranded session, then start a new one:
177
+ For a stranded session, `Session.send()`, `Session.respond()`, and a following `Session.stream()` throw `SessionStrandedError` from `eve/channels` and send nothing. `stream({ follow: false })` still reads the recorded history up to the current tail. `error.owner.eveVersion` names the eve release that built the session, when recorded. Call `end()` to retire the stranded session, then start a new one:
173
178
 
174
179
  ```ts
175
180
  import { SessionStrandedError } from "eve/channels";
@@ -182,10 +187,7 @@ try {
182
187
  }
183
188
  ```
184
189
 
185
- `respond()` accepts exact response literals directly. If responses have already
186
- been widened to `Answer[]`—for example, after decoding a platform
187
- payload—validate them with eve's strict schema before delivery. The validated
188
- type preserves that proof across channel wrappers:
190
+ `respond()` accepts exact response literals. Validate responses already widened to `Answer[]`, for example decoded from a platform payload, with `parseAnswers`; the validated type carries that proof across channel wrappers:
189
191
 
190
192
  ```ts
191
193
  import { parseAnswers } from "eve/client";
@@ -194,15 +196,17 @@ const answers = parseAnswers(decodedResponses);
194
196
  await source.respond(answers, { auth });
195
197
  ```
196
198
 
197
- Message sends use the channel's `turnPolicy`, which defaults to `"steer"`. Before assistant answer output or local tool execution begins, steering interrupts pending model generation and applies the correction in the same turn. 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. The turn ID stays the same.
199
+ Message sends use the channel's `turnPolicy`, which defaults to `"steer"`; see [Overlapping messages](./overview#overlapping-messages). A sent message can interrupt the model before your `deliver` hook runs. Filter events before `send(...)` when they should never interrupt the model.
198
200
 
199
- A sent delivery can interrupt generation before your `deliver` hook runs. If the hook ignores the correction, eve resumes the original request with its original auth, delivery provenance, and channel state. Filter events before `send(...)` when they should never interrupt generation.
201
+ Every `send()` and `respond()` passes its `state` option to the channel's `deliver(payload, channel)` hook as `payload.state`, including sends to an existing session. Use it for per-message values such as a message's author. The hook decides what to merge into `channel.state`; eve seeds `channel.state` from `state` only when `send()` creates the session.
200
202
 
201
- Every `send()` and `respond()` delivery passes its `state` option to your channel's `deliver(payload, channel)` hook as `payload.state`, including deliveries to an existing session. Use it for values that belong to one delivery, such as the author of a message. The hook decides what to merge into `channel.state`; eve seeds `channel.state` from `state` only when `send()` creates the session.
203
+ The payload is `ChannelDelivery<TState>` from `eve/channels`: `message`, `answers`, `context`, `outputSchema`, and `state?: Partial<TState>`. The hook's return value decides what reaches the session:
202
204
 
203
- The `state` you pass to `defineChannel(...)` is the seed for every session's `channel.state`, and must be plain JSON-like data. At each step boundary, eve restores any top-level seed field missing from the session's state, so a field you add to the seed in a later deploy holds its seed value in older sessions too, including in `context(state)` and event handlers. A field you `delete` is restored the same way; to clear one, set it to `null` (or `undefined`). eve doesn't merge nested objects: a stored object replaces the seed's object whole.
205
+ - Return nothing to keep it unchanged.
206
+ - Return a replacement with `message`, `answers`, `context`, or `outputSchema` to change it. Other fields, including `state`, are not accepted; change saved state through `channel.state`.
207
+ - Return `{}` to ignore it.
204
208
 
205
- The payload is `ChannelDelivery<TState>` from `eve/channels`: `message`, `answers`, `context`, `outputSchema`, and `state?: Partial<TState>`. Return a replacement with `message`, `answers`, `context`, or `outputSchema` to change the delivery, or return nothing to keep it unchanged. Change durable state through `channel.state`, not a `state` field on the replacement. To ignore a delivery, return `{}`. The hook does not return a harness input or accept arbitrary extra fields.
209
+ The `state` you pass to `defineChannel(...)` is the starting value of every session's `channel.state`, and must be plain JSON-like data. eve restores any top-level field from it that a session's state is missing, so a field you add in a later deploy also appears in existing sessions, including in `context(state)` and event handlers. A field you `delete` comes back the same way; to clear one, set it to `null` or `undefined`. eve doesn't merge nested objects: a saved object replaces the starting object whole.
206
210
 
207
211
  ```ts
208
212
  import { defineChannel } from "eve/channels";
@@ -219,7 +223,7 @@ export default defineChannel({
219
223
  });
220
224
  ```
221
225
 
222
- Configure `turnPolicy: "queue"` on `defineChannel(...)` when messages should wait for the active turn to finish, or override one send:
226
+ Set `turnPolicy: "queue"` on `defineChannel(...)` when messages should wait for the active turn to finish, or override one send:
223
227
 
224
228
  ```ts
225
229
  export default defineChannel({
@@ -237,11 +241,23 @@ export default defineChannel({
237
241
  });
238
242
  ```
239
243
 
240
- The same override is available on fixed `Session.send(...)` and cross-channel `to(...).send(...)`. `respond(...)` never steers: it delivers only addressed answers. Use `cancel()` when you need to stop work without a replacement message.
244
+ The same override works on fixed `Session.send(...)` and cross-channel `to(...).send(...)`. `respond(...)` never joins a running turn; it sends only the answers it names. Use `cancel()` to stop work without a replacement message.
241
245
 
242
- Attaching does no lookup. The first operation reports whether the ID is active.
243
- Call `resolveSession(address)` only when you explicitly need to snapshot an
244
- address's current owner as a fixed handle.
246
+ ## Operation semantics
247
+
248
+ - `cancel` asks the running turn to stop. Confirm it with `turn.settled` and
249
+ `outcome: "cancelled"`; the session accepts another message afterward.
250
+ - `compact` summarizes model context without adding a user message. The stream
251
+ shows `context.started`, then `context.settled` with `kind: "compaction"`.
252
+ - `clear` cancels the running turn and every working task, then removes
253
+ model-message history in place. It keeps the system prompt, skills, tools,
254
+ state, limits, addresses, and session sandbox.
255
+ - `end` ends the current session for good. A later `send()` to the address creates
256
+ a new session; a fixed `Session` handle still points at the ended ID.
257
+
258
+ Control operations never create a session. Unknown or inactive targets throw
259
+ `SessionNotActiveError`. A cancel with nothing to stop ends with `outcome: "ignored"`. Authenticate and deduplicate command webhooks before
260
+ calling `end`, because a delayed duplicate can end a newer session at the same address.
245
261
 
246
262
  ## Retried deliveries
247
263
 
@@ -255,150 +271,93 @@ const session = await from(conversationId).send(message, {
255
271
  });
256
272
  ```
257
273
 
258
- Channel and fixed-session `send()` and `respond()` calls accept this option,
259
- as does the Chat SDK bridge. Keys must contain 1–256 characters and identify one
260
- delivery. Prefix IDs with the provider or event type if they can overlap.
261
- Reusing a retained key ignores the new input, even if the message changed.
262
-
263
- Each session retains its last 1,024 distinct keys; reuse after eviction, after the session ends, or in another session can run again. Replicas must share the same durable Workflow World. A known duplicate returns a new receipt settled `ignored`, without repeating the original reply. Use `result()` to read a send's settlement.
274
+ Channel and fixed-session `send()` and `respond()` accept `idempotencyKey`, as does the Chat SDK bridge. A key has 1–256 characters and identifies one message or answer; prefix IDs with the provider or event type if they can overlap.
264
275
 
265
- Await `send()` before acknowledging a webhook when the provider allows it.
266
- Acknowledging sooner can lose work. This does not make tool calls, outbound
267
- posts, or work done before `send()` exactly once.
268
-
269
- ## Wrap an existing channel's routes
276
+ Reusing a remembered key ignores the new input, even if the message changed. It returns a new receipt whose result is `ignored`, and doesn't repeat the original reply. Use `result()` to read how a send ended. Each session remembers its last 1,024 keys. An older key runs again, and so does a key reused after the session ends or in another session. All replicas must use the same Workflow World.
270
277
 
271
- A channel value can be spread into a new object with replaced `routes`. eve keeps the channel's adapter, events, and build metadata (such as the Slack app manifest) on the spread copy, so `{ ...channel, routes }` compiles and runs like the original.
278
+ Await `send()` before acknowledging a webhook when the provider allows it, because acknowledging sooner can lose work. Keys don't make tool calls, outbound posts, or work done before `send()` exactly once.
272
279
 
273
- The built-in Slack, Teams, and Telegram channels, and the Chat SDK bridge's `send`, hand every inbound message to `from(address).send(message, options)`. A route wrapper that replaces `send` on the source returned by `from(address)` therefore sees each inbound message, and a rejected delivery reaches the wrapper as an error:
274
-
275
- ```ts title="agent/channels/slack.ts"
276
- import type { RouteHandlerArgs } from "eve/channels";
277
- import { slackChannel, type SlackChannelState } from "eve/channels/slack";
278
-
279
- const slack = slackChannel();
280
-
281
- function reportFailedDeliveries(
282
- args: RouteHandlerArgs<SlackChannelState>,
283
- ): RouteHandlerArgs<SlackChannelState> {
284
- return {
285
- ...args,
286
- from(address) {
287
- const source = args.from(address);
288
- return {
289
- ...source,
290
- async send(message, options) {
291
- try {
292
- return await source.send(message, options);
293
- } catch (error) {
294
- console.error("Slack delivery failed", { address, error });
295
- throw error;
296
- }
297
- },
298
- };
299
- },
300
- };
301
- }
280
+ ## File uploads
302
281
 
303
- const channel: typeof slack = {
304
- ...slack,
305
- routes: slack.routes.map((route) =>
306
- route.transport === "websocket"
307
- ? route
308
- : {
309
- ...route,
310
- handler: (request: Request, args: RouteHandlerArgs<SlackChannelState>) =>
311
- route.handler(request, reportFailedDeliveries(args)),
312
- },
313
- ),
314
- };
282
+ `from(address).send()` and `Session.send()` accept `MessageContent`: a string, or an array mixing text and file parts:
315
283
 
316
- export default channel;
284
+ ```ts
285
+ await from(continuationToken).send(
286
+ [
287
+ { type: "text", text: body.message },
288
+ { type: "file", data: imageBytes, mediaType: "image/png" },
289
+ ],
290
+ { auth },
291
+ );
317
292
  ```
318
293
 
319
- Keep each route's `method` and `path` unless you mean to move the endpoint.
320
-
321
- ## Operation semantics
322
-
323
- - `cancel` cooperatively stops the active turn. Confirm it with `turn.settled` and
324
- `outcome: "cancelled"`; the session accepts another message afterward.
325
- - `compact` summarizes model context without adding a synthetic user message. It
326
- is a context change: `context.started`, then `context.settled` with
327
- `kind: "compaction"`.
328
- - `clear` removes model-message history in place. It preserves the system prompt,
329
- skills, tools, durable state, limits, address ownership, and session sandbox.
330
- - `end` terminally retires the current session. A later address `send()` creates
331
- a fresh session; a fixed `Session` handle remains pinned to the retired ID.
332
-
333
- Control operations never create a session. Unknown or inactive targets throw
334
- `SessionNotActiveError`; an accepted no-op cancellation settles with `outcome: "ignored"`. Authenticate and deduplicate command webhooks before
335
- calling `end`, because a delayed duplicate can retire a newer address owner.
336
-
337
- ## CORS
338
-
339
- Custom HTTP channels leave CORS untouched unless you opt in. Pass `cors: true`
340
- for permissive browser access with preflight handling, or pass a serializable
341
- CORS options object to narrow origins, methods, and headers:
294
+ For files behind authenticated URLs, as on Slack, put a `URL` object in the file part's `data` and declare `fetchFile` on the channel config:
342
295
 
343
296
  ```ts
344
- import { defineChannel, POST } from "eve/channels";
345
-
346
- export default defineChannel({
347
- cors: {
348
- origin: ["https://app.example.com"],
349
- methods: ["POST"],
350
- allowHeaders: ["authorization", "content-type"],
297
+ defineChannel({
298
+ fetchFile(url) {
299
+ if (!url.startsWith("https://files.slack.com/")) return null;
300
+ return fetch(url, { headers: { authorization: `Bearer ${token}` } })
301
+ .then((r) => r.arrayBuffer())
302
+ .then((b) => ({ bytes: Buffer.from(b) }));
351
303
  },
352
- routes: [POST("/message", async () => new Response("ok"))],
304
+
305
+ routes: [
306
+ POST("/webhook", async (req, { from }) => {
307
+ await from(continuationToken).send(
308
+ [
309
+ { type: "text", text: message.text },
310
+ ...message.attachments.map((a) => ({
311
+ type: "file" as const,
312
+ data: new URL(a.url),
313
+ mediaType: a.mediaType,
314
+ })),
315
+ ],
316
+ {
317
+ auth,
318
+ state,
319
+ },
320
+ );
321
+ }),
322
+ ],
353
323
  });
354
324
  ```
355
325
 
356
- ## WebSocket routes
357
-
358
- Use `WS()` when a custom channel needs a WebSocket endpoint. The route handler runs once per upgrade request and returns lifecycle hooks for that connection:
326
+ If `fetchFile` throws, eve replaces that attachment with a model-visible note and continues the turn. To tell the model why, throw `attachmentError` from `eve/channels`:
359
327
 
360
328
  ```ts
361
- import { defineChannel, WS } from "eve/channels";
329
+ import { attachmentError } from "eve/channels";
362
330
 
363
- export default defineChannel({
364
- routes: [
365
- WS("/voice/ws", async (_req, { from }) => ({
366
- async message(_peer, message) {
367
- await from("voice-demo").send(message.text(), { auth: null });
368
- },
369
- })),
370
- ],
371
- });
331
+ async function fetchUpload(url: string) {
332
+ const response = await fetch(url, { headers: { authorization: `Bearer ${token}` } });
333
+ if (response.status === 413) {
334
+ throw attachmentError("The file is over 100 MB. Ask for a smaller file.");
335
+ }
336
+ return Buffer.from(await response.arrayBuffer());
337
+ }
372
338
  ```
373
339
 
374
- `WS()` handlers receive the same `from`, `to`, and `attachSession` operations,
375
- `params`, `waitUntil`, and `requestIp` arguments as HTTP route handlers. The
376
- returned hooks are eve-owned structural types compatible with Nitro/H3 websocket
377
- routing, including `upgrade`, `open`, `message`, `close`, and `error`.
340
+ The model then reads `Attachment report.pdf could not be retrieved: The file is over 100 MB. Ask for a smaller file.` The message reaches the model as written. Keep it to details the person can act on, such as a size limit or a missing permission. Never include URLs, tokens, or upstream response text. Pass the original error as `attachmentError(message, { cause })` to keep it in operator logs. Any other thrown error becomes a generic note, with the original in operator logs.
378
341
 
379
- ### Node upgrade server escape hatch
342
+ `fetchFile` receives the URL as a string (its `href`), so the example matches with `url.startsWith(...)`. A string with a URL scheme in `data`, such as `https://...` or `myapp-file:abc`, works the same as a `URL` object. The second argument carries the channel's `state` and the attachment's `session`, so a resolver can check a file against the caller in `session.auth`.
380
343
 
381
- Prefer the `WS()` lifecycle hooks above when you own the websocket behavior. eve also exposes `createWebSocketUpgradeServer()` for the narrower case where a third-party SDK or framework expects to bind directly to a Node `http.Server` with `server.on("upgrade", ...)`.
344
+ Return bytes to save the file to the sandbox. Return `null` for a URL your channel doesn't resolve, and eve downloads a public `https:` URL itself. eve's downloads have these limits:
382
345
 
383
- ```ts
384
- import { defineChannel, WS, createWebSocketUpgradeServer } from "eve/channels";
346
+ - 25 MB by default, with a 30-second timeout.
347
+ - No private or reserved addresses.
348
+ - At most 10 URLs per message, fetched one at a time.
385
349
 
386
- const bridge = createWebSocketUpgradeServer();
350
+ Any other URL, or a failed download, reaches the model as a note. The model provider never fetches an attachment, so a link that expires or needs credentials can't fail later model calls.
387
351
 
388
- thirdPartySdk.attach(bridge.server);
389
-
390
- export default defineChannel({
391
- routes: [WS("/vendor/ws", bridge.route)],
392
- });
393
- ```
352
+ Set `uploadPolicy` on `defineChannel` to cap what eve saves for the channel, for example `uploadPolicy: { maxBytes: 10 * 1024 * 1024, allowedMediaTypes: ["image/*", "application/pdf"] }`. eve checks every saved file, including its own downloads, by its actual bytes and detected media type. A violating file reaches the model as a note. Omit `uploadPolicy` to rely on your `fetchFile` checks, with eve's own downloads capped at 25 MB.
394
353
 
395
- The bridge server does not listen on its own port. It receives only upgrade events that matched the eve route, and only on hosts where Nitro exposes the raw Node upgrade request, socket, and head. Treat it as a compatibility adapter for libraries with server-binding APIs, not the primary way to build websocket channels in eve.
354
+ See [Inbound attachments](../sandbox#inbound-attachments) for the shared storage, size, and provider-input behavior.
396
355
 
397
356
  ## Cross-channel hand-off
398
357
 
399
- Use `ctx.to(channel, target).send(message, { auth })` in a route handler to start or resume a conversation on another channel. The agent runs and replies on the destination channel. The hand-off doesn't start a session on the source channel, which returns only its HTTP response.
358
+ A cross-channel hand-off starts or resumes a conversation on another channel from a route handler with `ctx.to(channel, target).send(message, { auth })`. The agent runs and replies on the destination channel. The source channel starts no session and returns only its HTTP response.
400
359
 
401
- This webhook filters incoming events and asks the agent to investigate in Slack. Import the destination channel's default export; `verifyAndParseEvent` is a helper you implement in your application.
360
+ This webhook filters incoming events and asks the agent to investigate in Slack. Import the destination channel's default export; `verifyAndParseEvent` is your own helper.
402
361
 
403
362
  ```ts title="agent/channels/intake.ts"
404
363
  import { defineChannel, POST } from "eve/channels";
@@ -438,15 +397,19 @@ Before sending:
438
397
  - Filter out events that should not reach the agent.
439
398
  - Pass the provider's stable event ID as `idempotencyKey`, so a redelivered webhook doesn't deliver the message twice. See [Retried deliveries](#retried-deliveries) for the limits.
440
399
 
441
- The supplied `auth` identifies who started the session, available to tools and event handlers as `session.auth.initiator`.
400
+ The supplied `auth` identifies who started the session, and tools and event handlers read it as `session.auth.initiator`.
401
+
402
+ The destination's `receive` hook defines the target fields and how they map to a session; see [Slack proactive sessions](./slack#proactive-sessions) for Slack's. To let people continue the conversation, configure the destination's inbound handlers to accept follow-ups.
403
+
404
+ `send` takes the same options as `from(address).send()` and `Session.send()`: `auth`, `context`, `history`, `idempotencyKey`, `outputSchema`, `title`, and `turnPolicy`. The destination's `receive` hook gets them with the message and target, and every built-in channel passes them on to the session.
442
405
 
443
- The destination's `receive` hook defines the target fields and how they map to a session. See [Slack proactive sessions](./slack#proactive-sessions) for its target options. To let people continue the conversation, configure the destination's inbound handlers to accept follow-ups.
406
+ The destination session dedupes keys from every sender. Prefix each key with its source, such as `pagerduty:${event.id}`, so keys stay unique across senders. Two senders that pick the same key reach the same session, and the second message is `ignored`. A Slack target with only a `channelId` uses the key to choose the session, so a retry reaches the same session.
444
407
 
445
- `send` takes the same options as `from(address).send()` and `Session.send()`: `auth`, `context`, `history`, `idempotencyKey`, `outputSchema`, `title`, and `turnPolicy`. The destination's `receive` hook gets them with the message and target, and every built-in channel passes them to the session. Keys are deduplicated per destination session, which every sender to that destination shares, and a Slack target with only a `channelId` uses the key to choose the session, so a retry reaches the same session. Make the key unique across all senders by prefixing it with the source, for example `pagerduty:${event.id}`. Two senders that pick the same key reach the same session, and the second delivery is `ignored`. The key still only dedupes within that session's retained keys: a retry after the key is evicted runs another turn, and a retry after the session ends starts a new one, which on Slack is a new thread. Anything a `receive` hook does before sending also repeats on retry, such as posting an `initialMessage` (Slack, Teams, Discord, GitHub, and Telegram) or creating a Linear Agent Session for an `issueId` or `commentId` target.
408
+ A key still dedupes only within that session's remembered keys. A retry after the key is dropped runs another turn. A retry after the session ends starts a new session, which on Slack is a new thread. Work a `receive` hook does before sending also repeats on retry. Examples are posting an `initialMessage` (Slack, Teams, Discord, GitHub, and Telegram) and creating a Linear Agent Session for an `issueId` or `commentId` target.
446
409
 
447
410
  ### Write a receive hook
448
411
 
449
- A custom channel's `receive` hook maps the target to an address. Pass the remaining input to `from(address).send()`, so the session gets every option the sender set:
412
+ A custom channel's `receive` hook maps the target to an address. Pass the rest of the input to `from(address).send()`, so the session gets every option the sender set:
450
413
 
451
414
  ```ts
452
415
  async receive({ message, target, ...send }, { from }) {
@@ -458,9 +421,64 @@ Route handlers, [handler-form schedules](../schedules#handler-form-run), and [to
458
421
 
459
422
  For notifications that don't need an agent turn, use the platform's API instead. See [Durable cross-channel notifications](../patterns/durable-cross-channel-notifications) when those posts also need retries.
460
423
 
424
+ ## CORS
425
+
426
+ Custom HTTP channels send no CORS headers by default. Pass `cors: true` for permissive browser access with preflight handling, or a serializable options object to narrow origins, methods, and headers:
427
+
428
+ ```ts
429
+ import { defineChannel, POST } from "eve/channels";
430
+
431
+ export default defineChannel({
432
+ cors: {
433
+ origin: ["https://app.example.com"],
434
+ methods: ["POST"],
435
+ allowHeaders: ["authorization", "content-type"],
436
+ },
437
+ routes: [POST("/message", async () => new Response("ok"))],
438
+ });
439
+ ```
440
+
441
+ ## WebSocket routes
442
+
443
+ `WS()` declares a WebSocket route. Its handler runs once per upgrade request and returns the hooks for that connection:
444
+
445
+ ```ts
446
+ import { defineChannel, WS } from "eve/channels";
447
+
448
+ export default defineChannel({
449
+ routes: [
450
+ WS("/voice/ws", async (_req, { from }) => ({
451
+ async message(_peer, message) {
452
+ await from("voice-demo").send(message.text(), { auth: null });
453
+ },
454
+ })),
455
+ ],
456
+ });
457
+ ```
458
+
459
+ `WS()` handlers receive the same `from`, `to`, `attachSession`, `params`, `waitUntil`, and `requestIp` arguments as HTTP route handlers. The returned hooks, `upgrade`, `open`, `message`, `close`, and `error`, are compatible with Nitro/H3 websocket routing.
460
+
461
+ ### Node upgrade server escape hatch
462
+
463
+ Use `createWebSocketUpgradeServer()` only when a third-party SDK or framework expects to bind to a Node `http.Server` with `server.on("upgrade", ...)`. Otherwise, use the `WS()` lifecycle hooks.
464
+
465
+ ```ts
466
+ import { defineChannel, WS, createWebSocketUpgradeServer } from "eve/channels";
467
+
468
+ const bridge = createWebSocketUpgradeServer();
469
+
470
+ thirdPartySdk.attach(bridge.server);
471
+
472
+ export default defineChannel({
473
+ routes: [WS("/vendor/ws", bridge.route)],
474
+ });
475
+ ```
476
+
477
+ The bridge server doesn't listen on its own port. It receives only upgrade events that matched the eve route, and only on hosts where Nitro exposes the raw Node upgrade request, socket, and head.
478
+
461
479
  ## Channel metadata
462
480
 
463
- A channel can project a subset of its adapter state as metadata, available to instrumentation resolvers and to the `select` of dynamic tools, skills, instructions, and other dynamic capabilities. Define a `metadata(state)` function on the channel config:
481
+ Channel metadata is the part of a channel's state that instrumentation and dynamic tools, skills, and instructions can read in their `select`. Define a `metadata(state)` function that returns it:
464
482
 
465
483
  ```ts
466
484
  import { defineChannel, POST } from "eve/channels";
@@ -498,13 +516,11 @@ export default defineChannel({
498
516
  });
499
517
  ```
500
518
 
501
- The projection is re-evaluated whenever adapter state changes after channel event handlers run. A dynamic capability's `select` reads it via `ctx.channel.metadata` and narrows it with `isChannel`. See [Dynamic capabilities](../guides/dynamic-capabilities) for the full consumption pattern.
519
+ eve recomputes the metadata when channel event handlers change state. A dynamic tool's or skill's `select` reads it as `ctx.channel.metadata` and narrows it with `isChannel`. See [Dynamic capabilities](../guides/dynamic-capabilities) for the full consumption pattern.
502
520
 
503
521
  ### Conversation audience
504
522
 
505
- Use `audience(input)` to assign an observability audience. The audience controls
506
- whether instrumentation may capture conversation content. The hook runs after
507
- route authentication and before the session is created:
523
+ `audience(input)` sets the session's audience, which controls whether traces may capture conversation content. It runs after route authentication and before the session is created:
508
524
 
509
525
  ```ts
510
526
  import { defineChannel, POST } from "eve/channels";
@@ -520,15 +536,15 @@ export default defineChannel({
520
536
  });
521
537
  ```
522
538
 
523
- The input contains the channel's `state`, `caller`, `channel`, and `environment`. A principal caller omits `principalId`, `issuer`, and `subject`, but its `attributes` come from route auth and can still contain identifying values. Return `"public"`, `"private"`, or `"unknown"`. Return `"unknown"` when the channel does not have enough evidence to classify confidently; consumers treat it as non-public. A missing, throwing, asynchronous, or malformed classifier also fails closed to `"unknown"`. A `metadata()` projection's `audience` field does not classify visibility; use `audience(input)`.
539
+ The input, typed `AudienceContext<TState>`, contains the channel's `state`, `caller`, `channel`, and `environment`. An authenticated caller (`caller.type === "principal"`) omits `principalId`, `issuer`, and `subject`. Its `attributes` come from route auth and can still identify the person.
524
540
 
525
- When you explicitly annotate a callback, use `AudienceContext<TState>`. The retired `AudienceInput`, `AudiencePrincipal`, and `auth` input are not supported; classify the privacy-limited `caller` instead.
541
+ Return `"public"`, `"private"`, or `"unknown"`. Return `"unknown"` when the channel can't tell; traces treat it as non-public. A missing, throwing, asynchronous, or malformed `audience` function also falls back to `"unknown"`. An `audience` field returned from `metadata()` sets nothing.
526
542
 
527
- Classification is fixed when the session is created. Continuation turns from a different caller do not reclassify an existing session. When a parent dispatches a local subagent, the child inherits the parent's audience while the framework forwards the parent's custom channel metadata separately.
543
+ The audience is fixed when the session is created, so turns from a different caller don't change it. A local subagent inherits its parent's audience, and eve forwards the parent's custom channel metadata separately.
528
544
 
529
545
  ## Continuation tokens
530
546
 
531
- Each channel operation accepts a channel-local token. The framework prepends the channel name, derived from the file stem under `agent/channels/`, before handing the token to the runtime.
547
+ A continuation token is the address that each channel operation accepts: your channel's ID for one conversation. Each token belongs to its channel, so tokens from different channels never collide.
532
548
 
533
549
  ```ts
534
550
  import { slackContinuationToken } from "eve/channels/slack";
@@ -538,7 +554,7 @@ slackContinuationToken({ channelId: "C0123ABC", threadTs: "1800000000.001234" })
538
554
  twilioContinuationToken({ from: "+15551234567", to: "+15557654321" }); // "+15551234567:+15557654321"
539
555
  ```
540
556
 
541
- Built-in channels export token builders from their own `eve/channels/<platform>` entry:
557
+ Each built-in channel exports a token builder from its `eve/channels/<platform>` entry. Pass the token to that channel's `from(...)` helper. A token is a routing address, not a credential, and doesn't replace authorization.
542
558
 
543
559
  | Builder | Address fields |
544
560
  | ----------------------------------- | ----------------------------------------------------------------------------------------------------------------------- |
@@ -551,22 +567,11 @@ Built-in channels export token builders from their own `eve/channels/<platform>`
551
567
  | `telegramContinuationToken` | `chatId`, optional `messageThreadId` and `conversationId` |
552
568
  | `linearContinuationToken` | `agentSessionId` |
553
569
 
554
- Pass the resulting channel-local token to that channel's `from(...)` helper.
555
- Tokens are routing addresses, not credentials or substitutes for authorization.
556
-
557
- Custom channels write their own function that joins the identity fields. The framework derives nothing for you; the channel owns its token format.
558
-
559
- When another identity should address a session, add it with `channel.continuation?.alias(rawToken)`. The runtime preserves the current channel namespace and exposes the new token as `channel.continuation.token` for later handlers.
570
+ A custom channel owns its token format; write a function that joins the platform's identity fields.
560
571
 
561
- Aliasing adds an address to the current session. Earlier addresses continue to resolve to the same session and accept the same payloads. `end` terminally retires the current session and makes all its addresses available to later `send()` calls. `cancel` stops only the active turn and leaves the session, history, and continuation-token ownership intact.
572
+ To let another identity address a session, call `channel.continuation?.alias(rawToken)`. The new token belongs to the same channel and becomes `channel.continuation.token` for later handlers. Earlier addresses still reach the same session and accept the same payloads. `end` ends the session and frees all its addresses for later `send()` calls. `cancel` stops only the running turn and keeps the session, history, and addresses.
562
573
 
563
- The `context(state, channel)` config option builds the per-step context read as `ctx.channel`
564
- in event handlers. Its second argument is `ChannelContext` from `eve/channels`: live
565
- `session.id` and `session.auth` information, plus channel-owned `continuation` routing. It does
566
- not expose session commands or put aliasing on session information. Close over
567
- `channel.continuation` for late-bound callbacks, or call `ctx.channel.continuation?.alias(token)`
568
- from an event handler. eve adds `ChannelContinuationOps` to the returned context and writes
569
- state mutations back to adapter state.
574
+ The `context(state, channel)` config option builds the per-step `ctx.channel` that event handlers read. Its second argument is `ChannelContext` from `eve/channels`: the current `session.id` and `session.auth`, plus `continuation`, without session commands. Keep a reference to `channel.continuation` for callbacks that run later, or call `ctx.channel.continuation?.alias(token)` from an event handler. eve adds `ChannelContinuationOps` to the returned context and saves changes you make to `state`.
570
575
 
571
576
  ```ts
572
577
  import { defineChannel } from "eve/channels";
@@ -593,83 +598,61 @@ defineChannel<{ ref: string | null }>({
593
598
  });
594
599
  ```
595
600
 
596
- At the next workflow boundary, the runtime adds the new address to the session's merged inbox. If another active session already owns the new token, the aliasing session fails instead of taking it over. Every address claimed by the session remains active until the session ends. Sessions with continuation addresses remain on their current deployment until Workflow supports atomic ownership transfer.
601
+ The new address joins the session at the next workflow boundary. If another active session already uses the token, the session that called `alias()` fails instead of taking it over. Every address stays active until the session ends. Sessions with continuation addresses stay on their current deployment.
597
602
 
598
- Tokens must be nonempty. A session supports up to 256 addresses, including its stable inbox; repeating an existing alias does not consume another address.
603
+ Tokens must be nonempty. A session supports up to 256 addresses, including its stable inbox; repeating an existing alias doesn't use another address.
599
604
 
600
- ## File uploads
605
+ ## Wrap an existing channel's routes
601
606
 
602
- `from(address).send()` accepts a `message` containing `MessageContent` (a string, or
603
- text and file parts), while `Session.send()` accepts `MessageContent` directly. To
604
- include file attachments, pass an array mixing text and file parts:
607
+ Spread a channel value into a new object with replaced `routes`. The copy keeps the channel's adapter, events, and build metadata, such as the Slack app manifest, so `{ ...channel, routes }` compiles and runs like the original.
605
608
 
606
- ```ts
607
- await from(continuationToken).send(
608
- [
609
- { type: "text", text: body.message },
610
- { type: "file", data: imageBytes, mediaType: "image/png" },
611
- ],
612
- { auth },
613
- );
614
- ```
609
+ The built-in Slack, Teams, and Telegram channels, and the Chat SDK bridge's `send`, hand every inbound message to `from(address).send(message, options)`. A wrapper that replaces `send` on the source from `from(address)` sees each inbound message, and a rejected delivery reaches it as an error:
615
610
 
616
- For platforms like Slack where files sit behind authenticated URLs, put a `URL` object in the file part's `data` and declare `fetchFile` on the channel config:
611
+ ```ts title="agent/channels/slack.ts"
612
+ import type { RouteHandlerArgs } from "eve/channels";
613
+ import { slackChannel, type SlackChannelState } from "eve/channels/slack";
617
614
 
618
- ```ts
619
- defineChannel({
620
- fetchFile(url) {
621
- if (!url.startsWith("https://files.slack.com/")) return null;
622
- return fetch(url, { headers: { authorization: `Bearer ${token}` } })
623
- .then((r) => r.arrayBuffer())
624
- .then((b) => ({ bytes: Buffer.from(b) }));
625
- },
615
+ const slack = slackChannel();
626
616
 
627
- routes: [
628
- POST("/webhook", async (req, { from }) => {
629
- await from(continuationToken).send(
630
- [
631
- { type: "text", text: message.text },
632
- ...message.attachments.map((a) => ({
633
- type: "file" as const,
634
- data: new URL(a.url),
635
- mediaType: a.mediaType,
636
- })),
637
- ],
638
- {
639
- auth,
640
- state,
617
+ function reportFailedDeliveries(
618
+ args: RouteHandlerArgs<SlackChannelState>,
619
+ ): RouteHandlerArgs<SlackChannelState> {
620
+ return {
621
+ ...args,
622
+ from(address) {
623
+ const source = args.from(address);
624
+ return {
625
+ ...source,
626
+ async send(message, options) {
627
+ try {
628
+ return await source.send(message, options);
629
+ } catch (error) {
630
+ console.error("Slack delivery failed", { address, error });
631
+ throw error;
632
+ }
641
633
  },
642
- );
643
- }),
644
- ],
645
- });
646
- ```
647
-
648
- If `fetchFile` throws, eve replaces that attachment with a model-visible note and continues the turn. To tell the model why, throw `attachmentError` from `eve/channels`:
649
-
650
- ```ts
651
- import { attachmentError } from "eve/channels";
652
-
653
- async function fetchUpload(url: string) {
654
- const response = await fetch(url, { headers: { authorization: `Bearer ${token}` } });
655
- if (response.status === 413) {
656
- throw attachmentError("The file is over 100 MB. Ask for a smaller file.");
657
- }
658
- return Buffer.from(await response.arrayBuffer());
634
+ };
635
+ },
636
+ };
659
637
  }
660
- ```
661
-
662
- The model then reads `Attachment report.pdf could not be retrieved: The file is over 100 MB. Ask for a smaller file.` The message reaches the model as written, so keep it to details the person can act on, such as a size limit or a missing permission, and never include URLs, tokens, or upstream response text. Pass the original error as `attachmentError(message, { cause })` to keep it in operator logs. Any other error that `fetchFile` throws becomes a generic note, and eve keeps the original error in operator logs.
663
-
664
- `fetchFile` receives the channel's `state` and the `session` the attachment arrived in as its second argument, so a resolver can check a file against the session's caller in `session.auth`.
665
638
 
666
- The `URL` object survives the queue boundary as a string and is reconstituted inside the workflow step. A string with a URL scheme, such as `https://...` or `myapp-file:abc`, is handled the same way. The staging pipeline calls `fetchFile` with the URL serialized as a string (the URL's `href`), which is why the example matches on `url.startsWith(...)`.
667
-
668
- Return bytes to stage the file to the sandbox. Return `null` when the URL is not one your channel resolves: eve then downloads a public `https:` URL itself, with the 25 MB default size cap and a 30-second timeout, and refuses private or reserved addresses. It downloads at most 10 URLs per message, one at a time. Any other URL, or a download that fails, reaches the model as a note. The model provider never fetches an attachment, so a link that expires or needs credentials can't fail later model calls.
639
+ const channel: typeof slack = {
640
+ ...slack,
641
+ routes: slack.routes.map((route) =>
642
+ route.transport === "websocket"
643
+ ? route
644
+ : {
645
+ ...route,
646
+ handler: (request: Request, args: RouteHandlerArgs<SlackChannelState>) =>
647
+ route.handler(request, reportFailedDeliveries(args)),
648
+ },
649
+ ),
650
+ };
669
651
 
670
- Set `uploadPolicy` on `defineChannel` to cap what eve stages for the channel, for example `uploadPolicy: { maxBytes: 10 * 1024 * 1024, allowedMediaTypes: ["image/*", "application/pdf"] }`. eve checks every staged file against it, on the final bytes and the media type they prove, including URLs it downloads itself. A file that breaks the policy reaches the model as a note. Without `uploadPolicy`, eve checks only what your `fetchFile` enforces, and its own downloads stop at 25 MB.
652
+ export default channel;
653
+ ```
671
654
 
672
- The framework handles staging bytes to the sandbox, hydrating files for the model call, and reconstituting `URL` objects after queue serialization. See [Inbound attachments](../sandbox#inbound-attachments) for the shared storage, size, and provider-input behavior.
655
+ Keep each route's `method` and `path` unless you mean to move the endpoint.
673
656
 
674
657
  ## What to read next
675
658