Custom Channels
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.
File location and identity
Custom channels live in agent/channels/ at the root agent or in an extension mounted there. Local subagents don't declare channels.
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.
Define a channel
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:
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.
A request with a method that its path doesn't declare gets 405 Method Not Allowed, with an Allow header that lists the methods the path declares. HEAD works differently: a path answers it only through a route you declare with HEAD(). A HEAD request to a path that declares GET but not HEAD gets 405, and the GET handler doesn't run. A HEAD request to a path with neither route gets 404.
Each route handler receives:
from(address)bindssend,respond,cancel,compact,clear, andendto an address: your channel's ID for one conversation, such as a thread ID. See Continuation tokens.resolveSession(address)returns the session that currently uses an address.attachSession(sessionId)returns a handle for one session ID, without a lookup.to(channel, target).send(message, options)hands work to another authored channel.params,waitUntil, andrequestIpprovide request metadata and lifetime control.describe(),invokeTool(),listSkillFiles(), andreadSkill()describe the agent and run its tools without a conversation. See Describe the agent and run tools directly.
params values are percent-decoded, except %2F and %5C: those stay encoded, so a parameter never contains a / or \ that the request path didn't have. Decode them in your handler if it expects them.
This fuller version adds commands, a stream route, and an event handler:
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.
ctx.session.ididentifies the session.ctx.positionlocates the event on the stream, andctx.viewis a read-only snapshot of the session at that point.ctx.channelis the channel's own context.ctx.channel.continuation.tokenis the address thatfrom(),resolveSession(), andalias()accept, without eve's prefixes.alias()adds another address.
For session state in channel event handlers, query ctx.view with selectors from eve/events instead of reconstructing it yourself. See Session views & selectors.
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.
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.
Describe the agent and run tools directly
A route handler can also describe the agent and run its tools without a conversation, as the MCP channel does:
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 carrynameanddescription, and both are sorted by name.invokeTool(name, input, { auth, key })runs one of those tools asauthoutside any conversation.listSkillFiles(skill)resolves to the skill's regular files, each with itspathunder the skill root andsizein bytes, sorted by path. It rejects a skill the agent doesn't have.readSkill(skill, path?)resolves to one skill file's raw bytes as aUint8Array; decode text yourself, for example withnew TextDecoder().decode(bytes).pathis relative to the skill root, such asreferences/api.md; omit it to readSKILL.md. It rejects absolute paths, paths with.,.., or empty segments, files the skill doesn't list, and files over 512 KiB.
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.
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:
"completed"with output."failed"with an error, including for invalid input."rejected"with a reason, including for approval or sign-in requirements, because a direct call can't pause for a person.
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. 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.
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).
Channel operations and session handles
Channel operations reach whichever session currently uses the address. create() and send() create a session when no session uses it. When two sends to a new address race, one session takes the address, eve forwards the other message to it, and both handles name that session. If the address keeps changing owners during the race, create() or send() throws SessionNotActiveError with code: "session_not_ready" and delivers nothing. Retry the call.
When another eve version built the session at an address, the session is stranded. 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.
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.
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.
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.
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:
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:
Message sends use the channel's turnPolicy, which defaults to "steer"; see 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.
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.
The payload is ChannelDelivery<TState> from eve/channels: message, answers, context, outputSchema, answerText, and state?: Partial<TState>. The hook's return value decides what reaches the session:
- Return nothing to keep it unchanged.
- Return a replacement with
message,answers,context,outputSchema, oranswerTextto change it. Other fields, includingstate, are not accepted; change saved state throughchannel.state. A replacement withoutanswerTextkeeps the delivery's. - Return
{}to ignore it.
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.
Set turnPolicy: "queue" on defineChannel(...) when messages should wait for the active turn to finish, or override one send:
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.
Typed answers
When a turn waits on an approval or a question, a message whose text matches an option answers it; see Human-in-the-loop. If your channel wraps what the person wrote before the model reads it, such as with their name, pass the bare text as answerText. The pending request resolves against answerText, and the model still reads the wrapped message:
A channel that can only show text should show one request at a time, the one a typed reply answers. Read it from the session with nextPrompt(view) from eve/events, for example in a committed handler, and show it again whenever it changes:
A reply of 1, an option's label, or its ID answers the request. Showing a different request than nextPrompt(view) returns makes a reply answer one the person didn't see.
Operation semantics
cancelasks the running turn to stop. Confirm it withturn.settledandoutcome: "cancelled"; the session accepts another message afterward.compactsummarizes model context without adding a user message. The stream showscontext.started, thencontext.settledwithkind: "compaction".clearcancels the running turn and every working task, then removes model-message history in place. It keeps the system prompt, skills, tools, state, limits, addresses, and session sandbox.endends the current session for good. A latersend()to the address creates a new session; a fixedSessionhandle still points at the ended ID.
Control operations never create a session. Unknown or inactive targets throw
SessionNotActiveError. A cancel with nothing to stop ends with outcome: "ignored". Authenticate and deduplicate command webhooks before
calling end, because a delayed duplicate can end a newer session at the same address.
Retried deliveries
After verifying a webhook, pass its stable event ID as idempotencyKey. Reuse the key
when retrying a failed or timed-out send:
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.
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.
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.
File uploads
from(address).send() and Session.send() accept MessageContent: a string, or an array mixing text and file parts:
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:
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:
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.
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.
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:
- 25 MB by default, with a 30-second timeout.
- No private or reserved addresses.
- At most 10 URLs per message, fetched one at a time.
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.
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.
See Inbound attachments for the shared storage, size, and provider-input behavior.
Cross-channel hand-off
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.
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.
Before sending:
- Verify the provider's signature and validate the payload, including size limits. Derive
event.sourcefrom the verified sender, not an untrusted payload field. - Filter out events that should not reach the agent.
- Pass the provider's stable event ID as
idempotencyKey, so a redelivered webhook doesn't deliver the message twice. See Retried deliveries for the limits.
The supplied auth identifies who started the session, and tools and event handlers read it as session.auth.initiator.
The destination's receive hook defines the target fields and how they map to a session; see Slack proactive sessions for Slack's. To let people continue the conversation, configure the destination's inbound handlers to accept follow-ups.
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.
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.
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.
Write a receive hook
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:
Route handlers, handler-form schedules, and tools provide to(...); other platform callbacks don't.
For notifications that don't need an agent turn, use the platform's API instead. See Durable cross-channel notifications when those posts also need retries.
CORS
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:
WebSocket routes
WS() declares a WebSocket route. Its handler runs once per upgrade request and returns the hooks for that connection:
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.
A WS() route registers for GET, the method an upgrade request uses. A path can also declare GET(): upgrade requests go to the WS() handler and other requests to the GET() handler. Both routes must use the same parameter names, or eve build fails.
Node upgrade server escape hatch
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.
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.
Channel metadata
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:
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 for the full consumption pattern.
Conversation audience
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:
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.
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.
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.
Conversation space
space(input) reports where the conversation happens on the platform, such as the channel a thread is in. Tools, dynamic values, and memory scopes read it as ctx.conversation.space to share data per place. See Spaces.
Return an id that is the same for every session in the place and unique across platforms and workspaces, usually by prefixing the platform and workspace. Return undefined when the channel can't tell. A throwing, asynchronous, or malformed space function reports no space. Like the audience, the space is fixed when the session is created.
Continuation tokens
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.
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.
| Builder | Address fields |
|---|---|
slackContinuationToken | channelId, threadTs |
slackCodeChannelContinuationToken | channelId (positional argument) |
twilioContinuationToken | from, optional to |
githubContinuationToken | repositoryId, conversationKind, and the matching issueNumber, pullRequestNumber, or reviewThreadRootCommentId |
discordContinuationToken | channelId, optional conversationId |
teamsContinuationToken | conversationId, optional tenantId and replyToActivityId |
telegramContinuationToken | chatId, optional messageThreadId and conversationId |
linearContinuationToken | agentSessionId |
A custom channel owns its token format; write a function that joins the platform's identity fields.
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.
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.
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.
Tokens must be nonempty. A session supports up to 256 addresses, including its stable inbox; repeating an existing alias doesn't use another address.
Wrap an existing channel's routes
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.
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:
Keep each route's method and path unless you mean to move the endpoint.
What to read next
- Channels overview
- Dynamic capabilities
- Auth & route protection
- Durable cross-channel notifications: deliver a provider message without starting an agent turn
- Universal Commerce Protocol (UCP): serve a UCP profile from a custom channel