The Open Framework for Building Agents
docs: clarify durable cross-channel delivery (#2285)
Colton Padden70a099bbdcfc
diff --git a/docs/channels/custom.mdx b/docs/channels/custom.mdxindex 977a4099f..a0b025c9b 100644--- a/docs/channels/custom.mdx+++ b/docs/channels/custom.mdx@@ -212,7 +212,9 @@ The bridge server does not listen on its own port. It receives only upgrade even## Cross-channel hand-off-Route handlers can start a session on a different channel via `ctx.to(channel, target).send(message, options)`. Use this when an inbound request on one channel should pivot the conversation onto another, such as an incident webhook that opens an investigation thread in Slack.+Route handlers can start or resume an agent session on a different channel via `ctx.to(channel, target).send(message, options)`. This is an agent hand-off: the message becomes turn input and invokes the model on the destination channel. Use it when an inbound request should pivot the conversation, such as an incident webhook that opens an investigation thread in Slack.++To post a provider notification without starting an agent turn, call the destination provider's API instead. If that notification must survive process failures, use an application-owned outbox; see [Durable cross-channel notifications](../patterns/durable-cross-channel-notifications).```tsimport { defineChannel, POST } from "eve/channels";@@ -247,6 +249,7 @@ Semantics:- The target channel's authored `receive(input, { from })` hook owns the continuation-token format and initial state. Callers supply the target to `to(...)`, then the message and auth to `send(...)`.- `auth` flows through to `session.auth.initiator` so the target's event handlers and the agent's tools can read who started the session.- Calling `ctx.to(...).send(...)` does not also start a session on the current channel. The inbound channel's response is whatever the route handler returns explicitly.+- `send(...)` is not a direct provider-message API. It supplies input to the agent on the destination channel.- The first argument is the target channel module's default export. Import it directly from `agent/channels/<name>.ts`. Identity is matched by reference.## Channel metadata@@ -397,4 +400,5 @@ The framework handles staging bytes to the sandbox, enforcing upload policy, hyd- [Channels overview](./overview)- [Dynamic capabilities](../guides/dynamic-capabilities)- [Auth & route protection](../guides/auth-and-route-protection)+- [Durable cross-channel notifications](../patterns/durable-cross-channel-notifications): deliver a provider message without starting an agent turn- [Universal Commerce Protocol (UCP)](../protocols/ucp): serve a UCP profile from a custom channeldiff --git a/docs/channels/github.mdx b/docs/channels/github.mdxindex b8e910087..1a4a8e473 100644--- a/docs/channels/github.mdx+++ b/docs/channels/github.mdx@@ -103,7 +103,9 @@ GitHub comments have no interactive button or card affordance. A human-in-the-lo### Proactive sessions-Start a session without an inbound comment invocation through `to(github, target).send(message, { auth })` from a schedule `run` handler, or `ctx.to(github, target).send(message, { auth })` from another channel. The target requires `owner`, `repo`, and exactly one of `issueNumber` or `pullRequestNumber`.+Start a session without an inbound comment invocation through `to(github, target).send(message, { auth })` from a schedule `run` handler, or `ctx.to(github, target).send(message, { auth })` from another channel. The target requires `owner`, `repo`, and exactly one of `issueNumber` or `pullRequestNumber`. This sends turn input to the agent; it is not a direct GitHub comment.++To post without invoking the model, use `channel.thread.post(...)` inside a GitHub event handler. For application-managed retries and deduplication across providers, see [Durable cross-channel notifications](../patterns/durable-cross-channel-notifications).### Attachmentsdiff --git a/docs/channels/overview.mdx b/docs/channels/overview.mdxindex 7df680c8b..8b2fbce63 100644--- a/docs/channels/overview.mdx+++ b/docs/channels/overview.mdx@@ -55,7 +55,9 @@ The eve channel is the framework's default HTTP session API, the routes the term## Custom channels-When eve doesn't ship a channel for your surface, build one with `defineChannel` from `eve/channels`. A custom channel declares route handlers (`GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `WS`), an `events` map, and uses `send(address, input)` to start or resume a session. See [Custom channels](./custom) for the full walkthrough, including WebSocket routes, cross-channel hand-off, channel metadata, address tokens, and file uploads.+When eve doesn't ship a channel for your surface, build one with `defineChannel` from `eve/channels`. A custom channel declares route handlers (`GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `WS`), an `events` map, and uses `send(address, input)` to start or resume a session. See [Custom channels](./custom) for the full walkthrough, including WebSocket routes, cross-channel agent hand-off, channel metadata, address tokens, and file uploads.++A cross-channel `send(...)` supplies input to the agent and invokes the model on the destination channel. eve does not currently provide a direct cross-channel provider-message queue. To post without starting a turn, use the provider API. See [Durable cross-channel notifications](../patterns/durable-cross-channel-notifications) when delivery also needs application-managed retries and deduplication.## Relationship to the Chat SDK@@ -95,5 +97,6 @@ Where an eve agent communicates with people, you may be required to disclose tha- [Photon](./photon), [Discord](./discord), [Teams](./teams), [Telegram](./telegram), [Twilio](./twilio), [GitHub](./github), and [Linear](./linear): the other first-class platform channels- [Chat SDK adapters](./chat-sdk): reach services eve has no first-class channel for- [Custom channels](./custom): build a channel for any surface with `defineChannel`+- [Durable cross-channel notifications](../patterns/durable-cross-channel-notifications): post to another platform without starting an agent turn- [Frontend](../guides/frontend/overview): browser chat on the eve channel with `useEveAgent`- [Integrations](/integrations): browse every built-in channel in one gallery using the Channels filterdiff --git a/docs/channels/slack.mdx b/docs/channels/slack.mdxindex d244264df..aa509dcd8 100644--- a/docs/channels/slack.mdx+++ b/docs/channels/slack.mdx@@ -346,9 +346,7 @@ const session = await ctx.resolveSession({ target });### Slack API calls outside a handler-Inside webhook-side handlers (`onAppMention`, `onEvent`, `onInteraction`, `onInputResponse`, `events`),-`ctx.slack.request(operation, body)` is the raw-API escape hatch. Outside-those contexts there is no handle — a schedule resolving reactions on old+Inside inbound webhook handlers such as `onAppMention`, `onEvent`, `onInteraction`, and `onInputResponse`, `ctx.slack.request(operation, body)` is the raw-API escape hatch. Inside an `events` handler, use `channel.slack.request(...)` instead. Outside those contexts there is no handle — a schedule resolving reactions on oldmessages, for example, has no inbound Slack request. For that, call thesame primitive the handle uses directly:@@ -416,7 +414,9 @@ events: {### Proactive sessions-Start a session without an inbound message through `ctx.to(slack, target).send(message, { auth })` from another channel, or `to(slack, target).send(message, { auth })` from a schedule `run` handler. The proactive target shape is `{ channelId, threadTs?, initialMessage? }`.+Start a session without an inbound message through `ctx.to(slack, target).send(message, { auth })` from another channel, or `to(slack, target).send(message, { auth })` from a schedule `run` handler. The proactive target shape is `{ channelId, threadTs?, initialMessage? }`. This sends turn input to the agent; it is not a direct Slack post.++To post without invoking the model, use `ctx.thread.post(...)` in an inbound Slack handler or `channel.thread.post(...)` in an `events` handler. Use `callSlackApi(...)` where no Slack channel context exists. For application-managed retries and deduplication, see [Durable cross-channel notifications](../patterns/durable-cross-channel-notifications).### Attachmentsdiff --git a/docs/guides/hooks.md b/docs/guides/hooks.mdindex a01efb6cd..c169d92e3 100644--- a/docs/guides/hooks.md+++ b/docs/guides/hooks.md@@ -28,6 +28,30 @@ The slug is the path-relative basename. `agent/hooks/audit.ts` becomes `"audit"`A hook file declares stream-event subscribers under the `events` map, keyed by event type, with `*` matching every event. Subscribe to any event in the runtime stream vocabulary documented in [Sessions, runs and streaming](../concepts/sessions-runs-and-streaming), including the lifecycle events `session.started`, `turn.completed`, `message.completed`, `action.partial`, and `action.result`. Handlers are observe-only. They cannot inject model context. To contribute runtime model messages, use `defineDynamic` and `defineInstructions` in `agent/instructions/`.+## Scope side effects to a channel++A hook under `agent/hooks/` observes matching events from every channel on the root agent. `defineHook` has no channel filter. Use a channel's `events` configuration when a handler assumes a specific platform or should run only for sessions owned by that channel:++```ts title="agent/channels/github.ts"+import { githubChannel } from "eve/channels/github";++export default githubChannel({+ events: {+ async "turn.completed"(event, channel, ctx) {+ console.info("GitHub turn completed", {+ repository: channel.repository.fullName,+ sessionId: ctx.session.id,+ turnId: event.turnId,+ });+ },+ },+});+```++A GitHub channel event handler cannot fire for a Slack-owned session, so platform-specific side effects do not depend on an early-return guard. On a built-in channel, an authored handler replaces that channel's default handler for the same event key. Check the channel page before overriding events that deliver replies, progress, errors, or human-input prompts.++Use `ctx.channel.kind` inside a global hook only when the operation is otherwise agent-wide and conditional handling is intentional. For typed channel metadata in dynamic resolvers or instrumentation, import the channel definition and narrow with `isChannel`; see [Instrumentation](./instrumentation#runtime-context).+## Hook structure and contextEvery handler receives the same `HookContext`, including the shared sessiondiff --git a/docs/patterns/durable-cross-channel-notifications.md b/docs/patterns/durable-cross-channel-notifications.mdnew file mode 100644index 000000000..d2ea0a314--- /dev/null+++ b/docs/patterns/durable-cross-channel-notifications.md@@ -0,0 +1,114 @@+---+title: "Durable cross-channel notifications"+description: "Send a notification to another platform without starting an agent turn, using an application-owned outbox for retries and deduplication."+---++`ctx.to(channel, target).send(...)` hands a message to another channel and starts or resumes an agent session there. eve does not currently provide a direct cross-channel message queue or provider outbox. To post a notification without a model call, use the destination platform's API instead. When the notification must survive a crash, record the intent in an application-owned outbox before attempting delivery.++An application-owned outbox is the current pattern for durable provider notifications. It provides at-least-once processing. It does not by itself guarantee exactly-once delivery: if the provider accepts a request but the response is lost, the dispatcher cannot know whether to retry. Use a provider idempotency key when one is available. Otherwise, make duplicates harmless or reconcile the destination before retrying an ambiguous request.++This example posts to Slack and requires `SLACK_REVIEW_CHANNEL_ID` and `SLACK_BOT_TOKEN`. If your channel uses Vercel Connect, pass the connector's `botToken` resolver to `callSlackApi` instead.++## Record the notification intent++Attach a platform-specific side effect to that platform's channel rather than filtering a global hook. This GitHub channel records one Slack notification per completed GitHub turn:++```ts title="agent/channels/github.ts"+import { githubChannel } from "eve/channels/github";++import { notificationOutbox } from "../lib/notification-outbox";++export default githubChannel({+ botName: process.env.GITHUB_APP_SLUG,+ events: {+ async "turn.completed"(event, channel, ctx) {+ await notificationOutbox.enqueue({+ key: `github-review:${ctx.session.id}:${event.turnId}`,+ destination: {+ channelId: process.env.SLACK_REVIEW_CHANNEL_ID!,+ provider: "slack",+ },+ message: `PR review completed for ${channel.repository.fullName}.`,+ });+ },+ },+});+```++`enqueue` must enforce a unique constraint on `key`, for example with `INSERT ... ON CONFLICT DO NOTHING`. A durable step can re-run after an interruption, and channel event handlers are at least once. The stable key prevents those attempts from creating multiple outbox rows.++A channel's `events` handlers run only for sessions owned by that channel. On built-in channels, an authored handler replaces the built-in handler for the same event key; use an event without a built-in handler or reproduce behavior you intend to replace. See [Hooks](../guides/hooks#scope-side-effects-to-a-channel) for the channel-scoping rules.++## Claim and deliver pending rows++Use one handler-form schedule as the dispatcher. Claim rows with a lease, call the provider API, then mark each row complete:++```ts title="agent/schedules/notification-outbox.ts"+import { callSlackApi } from "eve/channels/slack";+import { defineSchedule } from "eve/schedules";++import { notificationOutbox } from "../lib/notification-outbox";++export default defineSchedule({+ cron: "* * * * *",+ run({ waitUntil }) {+ waitUntil(+ (async () => {+ const notifications = await notificationOutbox.claim({+ limit: 25,+ leaseForMs: 5 * 60_000,+ });++ await Promise.all(+ notifications.map(async (notification) => {+ try {+ const response = await callSlackApi({+ botToken: undefined,+ operation: "chat.postMessage",+ body: {+ channel: notification.destination.channelId,+ text: notification.message,+ },+ });+ if (!response.ok) throw new Error(String(response.error));++ await notificationOutbox.complete(notification, {+ providerMessageId: String(response.ts),+ });+ } catch (error) {+ await notificationOutbox.release(notification, {+ error,+ retryAt: new Date(Date.now() + 5 * 60_000),+ });+ }+ }),+ );+ })(),+ );+ },+});+```++`callSlackApi` falls back to `SLACK_BOT_TOKEN` when `botToken` is `undefined`.++The storage adapter is application code. It needs these semantics:++- `enqueue` inserts once by the stable operation key.+- `claim` atomically leases pending rows so overlapping dispatchers do not send the same row concurrently.+- `complete` records the provider message ID and marks the row delivered.+- `release` records the error and makes the row eligible after `retryAt`.+- Expired leases return to the pending set.++## Handle ambiguous delivery++An error that proves the provider did not accept the request is safe to retry. A timeout, connection reset, or crash after the request leaves your process is ambiguous. The provider may have accepted the notification even though the dispatcher did not record completion.++Handle that window in this order:++1. Pass the outbox key through the provider's idempotency-key option when the API supports one.+2. Otherwise, store a stable marker in provider metadata and query for it before retrying, when the provider offers a reliable lookup.+3. If neither is available, design the notification so a duplicate is safe and visible as the same logical operation.++Do not mark an ambiguous row complete merely to suppress a duplicate; that can lose a notification the provider never accepted. Do not describe an outbox as exactly once unless the provider's contract closes this ambiguity window.++If the destination should run the agent rather than receive a notification, use [`ctx.to(...).send(...)`](../channels/custom#cross-channel-hand-off) instead. That path creates or resumes a durable session and invokes the model.diff --git a/docs/patterns/dynamic-scheduling.md b/docs/patterns/dynamic-scheduling.mdindex 9946069ff..9cd0bf97f 100644--- a/docs/patterns/dynamic-scheduling.md+++ b/docs/patterns/dynamic-scheduling.md@@ -244,7 +244,7 @@ Implement that adapter with whichever durable store already belongs to your appl- `complete` disables one-time rows or computes the next recurring run;- expired leases are recoverable.-Delivery is at least once. A crash after `receive` succeeds but before `complete` can dispatch again, so side-effecting tasks need application-level idempotency.+Delivery is at least once. A crash after `receive` succeeds but before `complete` can dispatch again, so side-effecting tasks need application-level idempotency. When the destination should receive a provider message without another agent turn, use the outbox pattern in [Durable cross-channel notifications](./durable-cross-channel-notifications) instead of `to(...).send(...)`.## Scheduling instructionsdiff --git a/docs/patterns/meta.json b/docs/patterns/meta.jsonindex 5f257b873..d58bb0397 100644--- a/docs/patterns/meta.json+++ b/docs/patterns/meta.json@@ -4,6 +4,7 @@"pages": ["multi-tenant-memory","dynamic-scheduling",+ "durable-cross-channel-notifications","multi-tenant-auth","multi-tenant-approvals"]diff --git a/docs/tools/overview.mdx b/docs/tools/overview.mdxindex 4599077c7..fc6b7c66d 100644--- a/docs/tools/overview.mdx+++ b/docs/tools/overview.mdx@@ -71,6 +71,20 @@ Running in the app runtime is what lets a tool import shared code from `lib/`, reve never runs authored tools during discovery. The model sees descriptors first, and only what it actually calls gets executed. Completed steps never re-run; eve replays the recorded result. A step interrupted mid-execution re-runs, so make non-idempotent side effects like charges or emails idempotent, or gate them with approval.+## When a tool throws++If an authored tool's `execute` function throws, eve records a failed `action.result` and gives the error to the model as a tool error. The model can respond, choose another action, or call the tool again. eve does not automatically call the tool again based on the exception type, an upstream HTTP status, or a `retryable` property.++Authored tools have no public terminal-error class or retry policy for thrown exceptions. Handle retry policy inside the tool when the operation is safe to retry, and return or throw an actionable error when it is not. Do not rely on that distinction to protect a write: an interruption before the durable step completes can re-run the step and execute the tool again even if the first request reached the upstream service.++Protect non-idempotent operations with the strongest mechanism the service supports:++1. Pass a stable idempotency key to the upstream API.+2. Otherwise, record a unique application operation before writing and check it on every attempt.+3. Use human approval when a person must authorize each execution, not as a substitute for deduplication after an ambiguous network result.++See [Execution model and durability](/docs/concepts/execution-model-and-durability#resuming-after-a-crash) for step replay semantics. For one-way provider notifications, see [Durable cross-channel notifications](/docs/patterns/durable-cross-channel-notifications).+## Gate a tool on human approvalA tool can require a person to sign off before it runs. Set `approval` with the helpers from `eve/tools/approval`: