The Open Framework for Building Agents
feat(eve): public inbound delivery and APIs apps need instead of eve internals (#4065)
Andrew Barba7869f509145b
diff --git a/.changeset/chat-sdk-bridge-respond.md b/.changeset/chat-sdk-bridge-respond.mdnew file mode 100644index 000000000..d45f0b3e7--- /dev/null+++ b/.changeset/chat-sdk-bridge-respond.md@@ -0,0 +1,7 @@+---+"eve": minor+---++The Chat SDK bridge's `send` now takes a message plus channel send options, and a new `respond(inputResponses, { thread })` answers pending input requests. To migrate, replace `send({ message, context }, { thread })` with `send(message, { context, thread })`, and replace `send({ inputResponses }, { thread })` with `respond(inputResponses, { thread })`. Channel send options also accept `outputSchema`, as `Session.send()` does.++Telegram and Chat SDK inbound messages now go through the public channel `send()`, so route wrappers see them. A Telegram reply to a bot message that no session owns now starts a session instead of failing delivery.diff --git a/.changeset/inbound-through-public-send.md b/.changeset/inbound-through-public-send.mdnew file mode 100644index 000000000..7c4323658--- /dev/null+++ b/.changeset/inbound-through-public-send.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Inbound Slack messages now go through the public `from(address).send()`, so a route wrapper that replaces `send` sees every inbound message and receives delivery failures as errors. Channel `send()` also forwards its `state` option to the `deliver` hook as `payload.state` on every delivery, as `respond()` already did.diff --git a/.changeset/info-tool-input-schemas.md b/.changeset/info-tool-input-schemas.mdnew file mode 100644index 000000000..ae7e3ed06--- /dev/null+++ b/.changeset/info-tool-input-schemas.md@@ -0,0 +1,5 @@+---+"eve": patch+---++`eve info --json` now includes `toolInputSchemas`: each static tool's input schema, for the root agent and each declared subagent, in the form eve sends to the model. `eve/tools` also exports `serializeModelInputSchema(schema)`, which returns that JSON Schema for any tool input schema, so checks no longer need to read `.eve/` build output.diff --git a/.changeset/is-schedule-auth.md b/.changeset/is-schedule-auth.mdnew file mode 100644index 000000000..10af5b82c--- /dev/null+++ b/.changeset/is-schedule-auth.md@@ -0,0 +1,5 @@+---+"eve": patch+---++`eve/schedules` now exports `isScheduleAuth(auth)`, which returns `true` for the app principal that schedules pass as `appAuth`. Use it to tell the agent's own scheduled work from a user's turn without copying eve's internal principal values.diff --git a/.changeset/slack-hitl-helpers.md b/.changeset/slack-hitl-helpers.mdnew file mode 100644index 000000000..275dcfbd1--- /dev/null+++ b/.changeset/slack-hitl-helpers.md@@ -0,0 +1,5 @@+---+"eve": patch+---++`eve/channels/slack` now exports `renderInputRequestBlocks`, `deriveHitlResponse`, and `HITL_ACTION_PREFIX`, with the `SlackHitlAction`, `DerivedHitlResponse`, and `SlackHitlRoute` types. Apps can render eve's HITL Block Kit controls and decode clicks on them without importing from eve's build output.diff --git a/.changeset/spread-safe-channels.md b/.changeset/spread-safe-channels.mdnew file mode 100644index 000000000..b3da52ba2--- /dev/null+++ b/.changeset/spread-safe-channels.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Spreading a channel into a new object with replaced routes, such as `{ ...slackChannel(), routes }`, now keeps its build metadata, so the Slack app manifest and Vercel Connect credentials still reach the build. The custom channels docs now describe wrapping an existing channel's routes as supported.diff --git a/.changeset/task-settled-name-kind.md b/.changeset/task-settled-name-kind.mdnew file mode 100644index 000000000..d704d103c--- /dev/null+++ b/.changeset/task-settled-name-kind.md@@ -0,0 +1,5 @@+---+"eve": patch+---++`task.settled` events now carry the task's tool `name` and `kind`, the same values as on the call's `task.started`, so clients and hooks can label a settled task without tracking its start. Events recorded by earlier versions omit both fields.diff --git a/docs/channels/chat-sdk.mdx b/docs/channels/chat-sdk.mdxindex 368b93fd5..2ad31b650 100644--- a/docs/channels/chat-sdk.mdx+++ b/docs/channels/chat-sdk.mdx@@ -51,7 +51,7 @@ bot.onSubscribedMessage(async (thread: Thread, message: Message) => {export default channel;```-`adapters` is a map of adapter name to adapter instance; each entry mounts its own webhook (see below). `state` takes any Chat SDK state adapter: `createMemoryState()` is fine for local development, but use a durable adapter (Redis, Upstash, etc.) in production so thread subscriptions and inbound deduplication survive restarts. `send` accepts a plain string, an AI SDK `UserContent` array, or a `SendPayload`, and must be called from inside a Chat SDK handler — it dispatches the turn on the webhook that is currently running.+`adapters` is a map of adapter name to adapter instance; each entry mounts its own webhook (see below). `state` takes any Chat SDK state adapter: `createMemoryState()` is fine for local development, but use a durable adapter (Redis, Upstash, etc.) in production so thread subscriptions and inbound deduplication survive restarts. `send` accepts a plain string or an AI SDK `UserContent` array, and must be called from inside a Chat SDK handler — it dispatches the turn on the webhook that is currently running.Deploy once the channel file is in place:@@ -96,7 +96,7 @@ You choose which Chat SDK events start a turn by registering handlers on `bot` a- `bot.onSubscribedMessage(thread, message)` fires on subsequent messages in a subscribed thread.- `bot.onAction`, `bot.onReaction`, and `bot.onSlashCommand` are available for adapters that emit them.-`send(input, options)` starts or resumes the eve session. The `thread` you pass determines the continuation token and the persisted channel state, so replies land back on the originating thread:+`send(message, options)` starts or resumes the eve session. The `thread` you pass determines the continuation token and the persisted channel state, so replies land back on the originating thread:```tsbot.onNewMention(async (thread, message) => {@@ -104,7 +104,18 @@ bot.onNewMention(async (thread, message) => {});```-`options` accepts `{ thread, auth?, title?, callback?, adapterName?, turnPolicy? }`. `title` sets the eve session's display title without changing the model message; `auth` attaches an authenticated principal to the turn.+`options` accepts `thread` and `adapterName`, plus the channel send options `auth`, `context`, `outputSchema`, `title`, `callback`, and `turnPolicy`. `title` sets the eve session's display title without changing the model message; `auth` attaches an authenticated principal to the turn. `auth` defaults to `null`.++To answer pending input requests from a handler you render yourself, call `respond(inputResponses, { thread, auth?, context? })`. Like a channel's `respond()`, it never creates a session. This example answers a custom button whose `value` carries the eve request id:++```ts+export const { bot, channel, send, respond } = chatSdkChannel({/* ... */});++bot.onAction("approve_deploy", async (event) => {+ if (!event.thread || !event.value) return;+ await respond([{ requestId: event.value, optionId: "approve" }], { thread: event.thread });+});+```### Steering@@ -168,7 +179,7 @@ chatSdkChannel({### Human-in-the-loop (HITL)-HITL prompts render as a Chat SDK `Card` with buttons. Button clicks resume the parked session automatically — the channel wires `bot.onAction` for you. Change the action-id prefix with `inputActionPrefix` (default `eve_input:`) if your app already uses it, and provide `resolveInputAuth` to carry user or tenant auth across the resume:+HITL prompts render as a Chat SDK `Card` with buttons. Button clicks resume the parked session automatically — the channel wires `bot.onAction` to `respond` for you. Change the action-id prefix with `inputActionPrefix` (default `eve_input:`) if your app already uses it, and provide `resolveInputAuth` to carry user or tenant auth across the resume:```tschatSdkChannel({diff --git a/docs/channels/custom.mdx b/docs/channels/custom.mdxindex bc26be647..4d90abbd8 100644--- a/docs/channels/custom.mdx+++ b/docs/channels/custom.mdx@@ -136,6 +136,8 @@ Message sends use the channel's `turnPolicy`, which defaults to `"steer"`. BeforA 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.+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.+Configure `turnPolicy: "queue"` on `defineChannel(...)` when messages should wait for the active turn to finish, or override one send:```ts@@ -160,6 +162,58 @@ Attaching does no lookup. The first operation reports whether the ID is active.Call `resolveSession(address)` only when you explicitly need to snapshot anaddress's current owner as a fixed handle.+## Wrap an existing channel's routes++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.++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:++```ts title="agent/channels/slack.ts"+import type { RouteHandlerArgs } from "eve/channels";+import { slackChannel, type SlackChannelState } from "eve/channels/slack";++const slack = slackChannel();++function reportFailedDeliveries(+ args: RouteHandlerArgs<SlackChannelState>,+): RouteHandlerArgs<SlackChannelState> {+ return {+ ...args,+ from(address) {+ const source = args.from(address);+ return {+ ...source,+ async send(message, options) {+ try {+ return await source.send(message, options);+ } catch (error) {+ console.error("Slack delivery failed", { address, error });+ throw error;+ }+ },+ };+ },+ };+}++const channel: typeof slack = {+ ...slack,+ routes: slack.routes.map((route) =>+ route.transport === "websocket"+ ? route+ : {+ ...route,+ handler: (request: Request, args: RouteHandlerArgs<SlackChannelState>) =>+ route.handler(request, reportFailedDeliveries(args)),+ },+ ),+};++export default channel;+```++Keep each route's `method` and `path` unless you mean to move the endpoint.+## Operation semantics- `cancel` cooperatively stops the active turn. Confirm it with `turn.cancelled`diff --git a/docs/channels/slack.mdx b/docs/channels/slack.mdxindex 1b64619fb..f17ce098e 100644--- a/docs/channels/slack.mdx+++ b/docs/channels/slack.mdx@@ -678,6 +678,25 @@ export default slackChannel({});```+#### Render and decode HITL controls yourself++`eve/channels/slack` exports the helpers eve uses for its own HITL controls. `renderInputRequestBlocks(request, route?)` returns the Block Kit blocks for one `InputRequest`. `deriveHitlResponse(action)` decodes a click on those blocks into `{ response, kind?, route? }`, where `response` is the eve `InputResponse`, or returns `null` for any other action. Every eve-owned control's `action_id` starts with `HITL_ACTION_PREFIX` (`"eve_input:"`), so give your own buttons a different prefix to keep them routed to `onInteraction`.++```ts+import { deriveHitlResponse, renderInputRequestBlocks } from "eve/channels/slack";++const [card] = renderInputRequestBlocks(request) as [+ { actions: { action_id: string; value: string }[] },+];+const button = card.actions[0]!;++// For a request whose first option id is "approve":+deriveHitlResponse({ actionId: button.action_id, value: button.value });+// { response: { optionId: "approve", requestId: request.requestId } }+```++Use them to test a custom renderer against eve's wire format, or to post eve's controls from your own renderer. A click on these controls in the session's Slack thread resumes the session through `onInputResponse`, the same as eve's own controls. To pass `response` to `respond()` yourself, validate it first with `parseInputResponses` from `eve/client`.+Authorization prompts split public status from private credentials. A sign-in challenge (OAuth URL, device code) is a credential. Anyone who completes it binds their identity to the session's connection. The default `authorization.required` handler posts a public, link-free status in the thread, delivers the actual challenge ephemerally to the Slack user behind the event's `principalId`, device code included, and then updates that public status when `authorization.completed` fires. A renderer's `authorization.required` handler receives a private-delivery context with `postEphemeral`, `postDirectMessage` (needs the `im:write` scope), and `state`. There is, intentionally, no public `post` and no raw API access. Its `next()` reaches eve's default, which posts the public status; skip `next` to deliver the challenge yourself, as this handler does by direct message. `state.slackUsersByPrincipal` maps each principal eve has seen in the thread, through a message or an input response, to its Slack user ID. If the principal has no entry, the challenge is not sent privately.```tsdiff --git a/docs/channels/telegram.mdx b/docs/channels/telegram.mdxindex f67e5ac06..d4de56c95 100644--- a/docs/channels/telegram.mdx+++ b/docs/channels/telegram.mdx@@ -51,6 +51,8 @@ The default `message.completed` handler sends plain text via `sendMessage`. It pHuman-in-the-loop (HITL) turns option requests into inline-keyboard buttons and freeform requests into `ForceReply`. Telegram caps `callback_data` at 64 bytes, so eve keeps compact callback ids in channel state instead. It acknowledges its own callbacks with `answerCallbackQuery`; anything it doesn't recognize goes to `onCallbackQuery`.+A text reply to a bot message is sent as a normal message, with the replied-to message id in `state.replyToBotMessageId`. When that id matches a pending `ForceReply` prompt, the channel's `deliver` hook turns the reply into the answer. Otherwise the reply reaches the agent as a message, and starts a new session when none owns the thread.+### Proactive sessionsStart a session without an inbound message through `to(telegram, target).send(message, { auth })` from a schedule `run` handler, or `ctx.to(telegram, target).send(message, { auth })` from another channel. `target.chatId` is required. Add `messageThreadId` to land in a specific forum topic.diff --git a/docs/concepts/sessions-runs-and-streaming.md b/docs/concepts/sessions-runs-and-streaming.mdindex 61dcb3168..146d4d947 100644--- a/docs/concepts/sessions-runs-and-streaming.md+++ b/docs/concepts/sessions-runs-and-streaming.md@@ -81,7 +81,7 @@ The stream is newline-delimited JSON (NDJSON), one event per line:| `input.resolved` | The server accepted terminal human-input outcomes; carries `resolutions` with responses when provided. || `agent.started` | A workflow run opened a session with `ctx.agent`, such as an agent tool's; carries `taskId` when the run is a task, `sessionId`, and the `streamPath` that `session.agent(started).stream()` follows. || `task.started` | A tool call started a [task](#task-events); carries `taskId`, `callId`, `turnId`, the tool `name`, and `kind`: `"agent"` for an agent tool, `"tool"` otherwise. |-| `task.settled` | A task's call settled; carries `taskId`, `callId`, `turnId`, `status`, and `output` or `error.message`; a cancelled call carries neither. |+| `task.settled` | A task's call settled; carries `taskId`, `callId`, `turnId`, the tool `name`, `kind`, `status`, and `output` or `error.message`; a cancelled call carries neither. || `reasoning.appended` | A reasoning text delta. || `reasoning.completed` | The finalized reasoning block. || `message.appended` | An assistant text delta. |@@ -127,7 +127,7 @@ A question or sign-in from inside a running call does not end the turn. This cov### Task events-A call to a tool that runs as a task, such as an agent tool, `agentRouter()`, the `workflow` tool, or a workflow tool that defines [`task(input, ctx)`](/docs/tools/workflows#run-calls-as-tasks-task) or [`serve(receive, ctx)`](/docs/tools/workflows#resumable-tasks-serve), returns a receipt as its `action.result` and keeps working. `task.started` reports the task's `taskId` for the call's `callId` and `turnId`, both when a call starts a task and when a call reaches a resumable task by its `taskId`, before any event the task's run publishes for that call. `task.settled` comes once per call, with the same `turnId`, `status` `"completed"`, `"failed"`, or `"cancelled"`, and the call's `output` when it completed or `error.message` when it failed. Results reach the model as a message in its history, not as a stream event, so read outcomes from `task.settled`. A session the task's run opens with `ctx.agent` is announced with `agent.started` carrying the `taskId`. An `input.requested`, `authorization.required`, or `authorization.completed` event from a task's run carries its `taskId`. Each of these events names the call the task is serving when it happens: a resumable task's later call brings its own `callId` and `turnId`, which may belong to a later turn than the call that started the task.+A call to a tool that runs as a task, such as an agent tool, `agentRouter()`, the `workflow` tool, or a workflow tool that defines [`task(input, ctx)`](/docs/tools/workflows#run-calls-as-tasks-task) or [`serve(receive, ctx)`](/docs/tools/workflows#resumable-tasks-serve), returns a receipt as its `action.result` and keeps working. `task.started` reports the task's `taskId` for the call's `callId` and `turnId`, both when a call starts a task and when a call reaches a resumable task by its `taskId`, before any event the task's run publishes for that call. `task.settled` comes once per call, with the same `turnId`, `name`, and `kind` as its `task.started`, `status` `"completed"`, `"failed"`, or `"cancelled"`, and the call's `output` when it completed or `error.message` when it failed. Events recorded by earlier eve versions omit `name` and `kind` on `task.settled`, so match them to their `task.started` by `callId` when those fields are missing. Results reach the model as a message in its history, not as a stream event, so read outcomes from `task.settled`. A session the task's run opens with `ctx.agent` is announced with `agent.started` carrying the `taskId`. An `input.requested`, `authorization.required`, or `authorization.completed` event from a task's run carries its `taskId`. Each of these events names the call the task is serving when it happens: a resumable task's later call brings its own `callId` and `turnId`, which may belong to a later turn than the call that started the task.A turn doesn't end while tasks are working. When the model ends its text early, eve holds the turn and the stream emits `turn.waiting` for it; the turn continues once a result arrives or its caller writes. In a root session, that text completes as an ordinary `message.completed`. In a child session or a schedule's session, it reports `finishReason: "tool-calls"`, so channels post only the final reply. When the model calls `task_wait` and no result is ready yet, the stream also emits `turn.waiting`. Either way, the next `step.started` for the same `turnId` means the turn resumed, and `session.waiting` comes only after the turn ends. See [Tasks](/docs/tools/tasks#turns-wait-for-their-tasks).diff --git a/docs/guides/client/streaming.mdx b/docs/guides/client/streaming.mdxindex 54f13385c..75a5f479c 100644--- a/docs/guides/client/streaming.mdx+++ b/docs/guides/client/streaming.mdx@@ -155,7 +155,7 @@ For the complete event table, see [Sessions, runs & streaming](../../concepts/seFor `action.input.appended`, the default message reducer accumulates accepted deltas into a `dynamic-tool` part with `state: "input-streaming"`; its `inputText` field contains cumulative raw text that may be incomplete JSON. The matching `actions.requested` event upgrades the same `toolCallId` to `state: "input-available"` and puts the validated value in `input`.-A call to a tool that runs as a [task](/docs/tools/workflows#run-calls-as-tasks-task) returns a receipt as its `action.result` and settles later with `task.settled`, matched by `callId`. The model receives the result as a message in its history, but the stream reports it only as `task.settled`, so render the result from that event.+A call to a tool that runs as a [task](/docs/tools/workflows#run-calls-as-tasks-task) returns a receipt as its `action.result` and settles later with `task.settled`, matched by `callId`. The model receives the result as a message in its history, but the stream reports it only as `task.settled`, so render the result from that event. `task.settled` repeats the tool `name` and `kind` from `task.started`, so you can label a result without keeping the start event. Events recorded by earlier eve versions omit both fields.When a submitted message includes attachments, `message.received.data.message` stays theflattened compatibility summary, while `message.received.data.parts` carries renderable text anddiff --git a/docs/reference/cli.md b/docs/reference/cli.mdindex f525b8cd2..bdaf60617 100644--- a/docs/reference/cli.md+++ b/docs/reference/cli.md@@ -148,6 +148,49 @@ eve info [--json]Run this first when something behaves unexpectedly. It confirms a file was discovered, lists the active surface, and surfaces discovery diagnostics, all faster than booting the dev server. Static instructions appear in source order with their `system` or `user` role. Dynamic instruction results are runtime-only and do not appear here.+### JSON output++`eve info --json` prints one JSON object. Scripts and CI checks can read it instead of the files under `.eve/`:++| Field | Type | Description |+| ------------------ | ---------------- | ----------------------------------------------------------------------------------------- |+| `appRoot` | string | Application root |+| `agentRoot` | string or `null` | Agent directory, or `null` when the project could not be compiled |+| `layout` | string or `null` | Project layout |+| `status` | string | Compile status, such as `ready` or `failed`; `unavailable` when nothing compiled |+| `diagnostics` | object or `null` | Discovery diagnostic counts: `{ errors, warnings }` |+| `model` | string or `null` | Root agent model id |+| `instructions` | string or `null` | Static instruction files with their roles |+| `skills` | string[] | Static skill names |+| `tools` | string[] | Root agent tool names |+| `toolInputSchemas` | object | Each tool's input schema as eve sends it to the model (see below) |+| `subagents` | string[] | Declared subagent names |+| `schedules` | string[] | Schedule names |+| `channels` | object[] | Effective channel routes: `{ name, kind, method, urlPath }` |+| `messaging` | object | Session route patterns: `{ create, messages, stream }` |+| `artifacts` | object or `null` | Paths to the compiled manifest, discovery manifest, diagnostics, module map, and metadata |++`toolInputSchemas.root` maps each root agent tool name to its JSON Schema, including tools from mounted extensions under their namespaced names. `toolInputSchemas.subagents` maps each declared subagent name to the same kind of map for that subagent's tools. Each schema is the form eve sends to the model: schemas from a validation library such as Zod have `additionalProperties: false` on objects that allow no other keys, plain JSON Schema is kept as written, and tools whose calls run as `serve` tasks, including agent tools, include the optional `taskId` input eve adds.++```json+{+ "tools": ["get_weather"],+ "toolInputSchemas": {+ "root": {+ "get_weather": {+ "type": "object",+ "properties": { "city": { "type": "string" } },+ "required": ["city"],+ "additionalProperties": false+ }+ },+ "subagents": {}+ }+}+```++`toolInputSchemas` covers only tools compiled from tool files. It does not include provider-managed tools such as `web_search`, dynamic tools, connection tools, the tools eve generates at runtime for each subagent and remote agent, or the `task_wait` and `task_cancel` tools. Model providers can also transform a schema before the model reads it; those changes are not reflected here. To compute the same form for an input schema in your own code, such as in a test, call `serializeModelInputSchema(schema)` from `eve/tools`; it returns JSON Schema data and does not add `taskId`.+## `eve build````bashdiff --git a/docs/schedules.mdx b/docs/schedules.mdxindex 141123bb7..c802c60ca 100644--- a/docs/schedules.mdx+++ b/docs/schedules.mdx@@ -85,6 +85,20 @@ Every run delivers the agent's reply to the channel. To skip a run when there isThe `auth` option controls which principal the session runs as. A handler may instead supply a user principal when scheduled work needs that user's grants; a session created by that dispatch still retains schedule provenance.+### Detect the app principal++`isScheduleAuth(auth)` returns `true` when `auth` is the app principal that schedules pass as `appAuth` and that markdown-form sessions run as. Use it in tools, hooks, or channel handlers to treat the agent's own work differently from a user's:++```ts+import { isScheduleAuth } from "eve/schedules";++if (isScheduleAuth(ctx.session.auth.current)) {+ // The turn runs as the app principal, not as a user.+}+```++`isScheduleAuth` identifies the principal, not how the turn started. A turn from a schedule handler that sends with a user principal returns `false`, and any code that passes `appAuth` along returns `true`.+A handler-form session runs on the same durable runtime engine as any other session, so it can park (durably suspend), for instance when the channel handoff is waiting for a Slack reply. Markdown-form sessions park too, but no channel is attached, so they cannot receive follow-up messages.## Session continuitydiff --git a/docs/subagents/index.mdx b/docs/subagents/index.mdxindex fca0f5560..8a90d3be6 100644--- a/docs/subagents/index.mdx+++ b/docs/subagents/index.mdx@@ -229,7 +229,7 @@ By default, a subagent named `researcher` collides with an authored tool named `Do not rely on subagent delegation by itself as an approval boundary. Put sensitive tools behind `approval`, connection approval, route/session authorization, or other controls wherever those tools can be called.-Each delegated subagent spins up its own child session and stream. The parent stream carries the call's `task.started` and `task.settled` events, `agent.started` when the child session opens, plus interactive `input.requested`, `authorization.required`, and `authorization.completed` events proxied from descendants so the root channel can prompt the user. The parent emits `input.resolved` when it routes an answer back down to the descendant that asked. `task.settled` carries the child's reply as `output` when the call completes, or `error.message` when it fails. To follow the child's other progress, pass the `agent.started` event to [`session.agent()`](./guides/client/streaming#follow-a-subagent) on a client session attached to the parent and follow the child with `stream()`. It reads `agent.started.data.streamPath`: the child's own session stream for a local child, or a parent-origin proxy for a remote child, which the parent authenticates to the remote deployment.+Each delegated subagent spins up its own child session and stream. The parent stream carries the call's `task.started` and `task.settled` events, `agent.started` when the child session opens, plus interactive `input.requested`, `authorization.required`, and `authorization.completed` events proxied from descendants so the root channel can prompt the user. The parent emits `input.resolved` when it routes an answer back down to the descendant that asked. `task.settled` carries the child's reply as `output` when the call completes, or `error.message` when it fails, along with the same tool `name` and `kind: "agent"` as the call's `task.started`. To follow the child's other progress, pass the `agent.started` event to [`session.agent()`](./guides/client/streaming#follow-a-subagent) on a client session attached to the parent and follow the child with `stream()`. It reads `agent.started.data.streamPath`: the child's own session stream for a local child, or a parent-origin proxy for a remote child, which the parent authenticates to the remote deployment.`agent.started` carries the `callId` and `turnId` of the call that opened the session, the call's `taskId`, the agent `name`, and the child's `sessionId`. Later calls with the same `taskId` reach the same session and do not announce it again, so match a child to its calls by `taskId`. A session an authored workflow tool opens with `ctx.agent` is announced the same way, with its `taskId` only when the workflow tool call runs as a task.diff --git a/docs/tools/tasks-upgrade.md b/docs/tools/tasks-upgrade.mdindex 3bea4c380..d13a9fdfb 100644--- a/docs/tools/tasks-upgrade.md+++ b/docs/tools/tasks-upgrade.md@@ -114,11 +114,11 @@ failed task reports its error in `task.settled` and in its `task.result` block.The `subagent.called`, `subagent.started`, `subagent.completed`, and `subagent.event` events areremoved. Use these instead:-| Event | Replaces | Data |-| --------------- | -------------------- | -------------------------------------------------------------------------------- |-| `task.started` | `subagent.called` | `taskId`, `callId`, `turnId`, `name`, `kind` |-| `task.settled` | `subagent.completed` | `taskId`, `callId`, `turnId`, `status`, and `output` or `error` unless cancelled |-| `agent.started` | `subagent.started` | `callId`, `turnId`, `taskId`, `name`, `sessionId`, `streamPath` |+| Event | Replaces | Data |+| --------------- | -------------------- | ------------------------------------------------------------------------------------------------ |+| `task.started` | `subagent.called` | `taskId`, `callId`, `turnId`, `name`, `kind` |+| `task.settled` | `subagent.completed` | `taskId`, `callId`, `turnId`, `name`, `kind`, `status`, and `output` or `error` unless cancelled |+| `agent.started` | `subagent.started` | `callId`, `turnId`, `taskId`, `name`, `sessionId`, `streamPath` |Follow a child's own events, which `subagent.event` used to relay, on its stream:`session.streamSubagent()` is now `session.agent(started).stream()`, and it takes the `agent.started` event.diff --git a/docs/tools/tasks.md b/docs/tools/tasks.mdindex c81bacb5e..f1d4539cb 100644--- a/docs/tools/tasks.md+++ b/docs/tools/tasks.md@@ -263,17 +263,18 @@ same `taskId` continues where it left off. A `serve` body that doesn't return to## Stream events-| Event | When | Data |-| --------------- | ------------------------------------------------------------------------ | -------------------------------------------------------------------------------- |-| `task.started` | A call starts a task, or reaches a resumable task by its `taskId` | `taskId`, `callId`, `turnId`, the tool `name`, and `kind` |-| `task.settled` | A reply, return, failure, or cancel settles one call | `taskId`, `callId`, `turnId`, `status`, and `output` or `error` unless cancelled |-| `agent.started` | A workflow run, including an agent tool's, opens a session with an agent | `callId`, `turnId`, `taskId`, `name`, `sessionId`, `streamPath` |-| `turn.waiting` | An open turn parks on its tasks, a `task_wait`, a question, or a sign-in | `turnId` and `sequence` |+| Event | When | Data |+| --------------- | ------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ |+| `task.started` | A call starts a task, or reaches a resumable task by its `taskId` | `taskId`, `callId`, `turnId`, the tool `name`, and `kind` |+| `task.settled` | A reply, return, failure, or cancel settles one call | `taskId`, `callId`, `turnId`, `name`, `kind`, `status`, and `output` or `error` unless cancelled |+| `agent.started` | A workflow run, including an agent tool's, opens a session with an agent | `callId`, `turnId`, `taskId`, `name`, `sessionId`, `streamPath` |+| `turn.waiting` | An open turn parks on its tasks, a `task_wait`, a question, or a sign-in | `turnId` and `sequence` |`task.started` and `task.settled` come once each per call, and `(taskId, callId)` identifies thecall. Both carry that call's `turnId`, which for a resumable task's later call can be a later turn-than the one that started the task. `kind` is `"agent"` for an agent tool's call and `"tool"`-otherwise. `status` is `"completed"`, `"failed"`, or `"cancelled"`. A completed call carries+than the one that started the task, and the task's tool `name` and `kind`. `kind` is `"agent"` for+an agent tool's call and `"tool"` otherwise. Events recorded by earlier eve versions omit `name`+and `kind` on `task.settled`; match those to their `task.started` by `callId`. `status` is `"completed"`, `"failed"`, or `"cancelled"`. A completed call carries`output`, a failed call carries `error`, and a cancelled call carries neither.`agent.started` names the call and turn whose run opened the session, and its `taskId` is absentwhen an `execute` call opened it. Results reach the model as a message in its history, not as adiff --git a/e2e/fixtures/agent-router/evals/agent-router.eval.ts b/e2e/fixtures/agent-router/evals/agent-router.eval.tsindex 2fb37c1a8..5f040e669 100644--- a/e2e/fixtures/agent-router/evals/agent-router.eval.ts+++ b/e2e/fixtures/agent-router/evals/agent-router.eval.ts@@ -11,7 +11,10 @@ export default defineEval({turn.calledTool("agent", { count: 1 });turn.calledTool("task_wait", { count: 1 });turn.event("task.started", { count: 1, data: { kind: "tool", name: "agent" } });- turn.event("task.settled", { count: 1, data: { status: "completed" } });+ turn.event("task.settled", {+ count: 1,+ data: { kind: "tool", name: "agent", status: "completed" },+ });turn.event("agent.started", { count: 1, data: { name: "agent" } });t.succeeded();t.noFailedActions();diff --git a/packages/eve/extension-contracts/compatibility/channel/v39.ts b/packages/eve/extension-contracts/compatibility/channel/v39.tsnew file mode 100644index 000000000..a664fa575--- /dev/null+++ b/packages/eve/extension-contracts/compatibility/channel/v39.ts@@ -0,0 +1,17 @@+import { defineChannel, POST } from "#public/channels/index.js";++// Epoch 39 channel sends had no `outputSchema`; epoch 40 adds it as optional.+export default defineChannel<{ author: string | null }>({+ state: { author: null },+ routes: [+ POST("/threads/:threadId/messages", async (request, { from, params }) => {+ const session = await from(params.threadId!).send(await request.text(), {+ auth: null,+ context: ["Sent from the support form."],+ state: { author: "alice" },+ title: "Support thread",+ });+ return Response.json({ sessionId: session.id });+ }),+ ],+});diff --git a/packages/eve/extension-contracts/compatibility/channel/v40.ts b/packages/eve/extension-contracts/compatibility/channel/v40.tsnew file mode 100644index 000000000..ae2fc0974--- /dev/null+++ b/packages/eve/extension-contracts/compatibility/channel/v40.ts@@ -0,0 +1,11 @@+import { defineChannel } from "#public/channels/index.js";++// Epoch 40 `task.settled` events had no `name` or `kind`; epoch 41 adds both as optional.+export default defineChannel({+ routes: [],+ events: {+ "task.settled"(event) {+ console.info("task settled", { status: event.status, taskId: event.taskId });+ },+ },+});diff --git a/packages/eve/extension-contracts/compatibility/connection/v34.ts b/packages/eve/extension-contracts/compatibility/connection/v34.tsnew file mode 100644index 000000000..e30b68c2f--- /dev/null+++ b/packages/eve/extension-contracts/compatibility/connection/v34.ts@@ -0,0 +1,10 @@+import { defineMcpClientConnection } from "#public/connections/index.js";++// Epoch 34 `task.settled` events had no `name` or `kind`; epoch 35 adds both as optional.+export default defineMcpClientConnection({+ description: "Search the support knowledge base.",+ url: "https://support.example.com/mcp",+ approval({ toolName }) {+ return toolName.endsWith("__search") ? "approved" : "user-approval";+ },+});diff --git a/packages/eve/extension-contracts/compatibility/dynamicInstructions/v28.ts b/packages/eve/extension-contracts/compatibility/dynamicInstructions/v28.tsnew file mode 100644index 000000000..4c8e0e706--- /dev/null+++ b/packages/eve/extension-contracts/compatibility/dynamicInstructions/v28.ts@@ -0,0 +1,9 @@+import { defineDynamic, defineInstructions } from "#public/instructions/index.js";++// Epoch 28 `task.settled` events had no `name` or `kind`; epoch 29 adds both as optional.+export default defineDynamic({+ events: {+ "turn.started": (_event, ctx) =>+ defineInstructions({ markdown: `Review evidence for session ${ctx.session.id}.` }),+ },+});diff --git a/packages/eve/extension-contracts/compatibility/dynamicSkill/v27.ts b/packages/eve/extension-contracts/compatibility/dynamicSkill/v27.tsnew file mode 100644index 000000000..161db2e9f--- /dev/null+++ b/packages/eve/extension-contracts/compatibility/dynamicSkill/v27.ts@@ -0,0 +1,12 @@+import { defineDynamic, defineSkill } from "#public/skills/index.js";++// Epoch 27 `task.settled` events had no `name` or `kind`; epoch 28 adds both as optional.+export default defineDynamic({+ events: {+ "turn.started": (_event, ctx) =>+ defineSkill({+ description: "Review the active request.",+ markdown: `Review evidence for session ${ctx.session.id}.`,+ }),+ },+});diff --git a/packages/eve/extension-contracts/compatibility/dynamicTool/v64.ts b/packages/eve/extension-contracts/compatibility/dynamicTool/v64.tsnew file mode 100644index 000000000..ba87ec8c7--- /dev/null+++ b/packages/eve/extension-contracts/compatibility/dynamicTool/v64.ts@@ -0,0 +1,14 @@+import { defineDynamic, defineTool } from "#public/tools/index.js";++// Epoch 64 `task.settled` events had no `name` or `kind`; epoch 65 adds both as optional.+export default defineDynamic({+ events: {+ "turn.started": () => ({+ session_id: defineTool({+ description: "Return the current session id.",+ inputSchema: { type: "object", properties: {} },+ execute: (_input, ctx) => ctx.session.id,+ }),+ }),+ },+});diff --git a/packages/eve/extension-contracts/compatibility/hook/v33.ts b/packages/eve/extension-contracts/compatibility/hook/v33.tsnew file mode 100644index 000000000..f551c7c20--- /dev/null+++ b/packages/eve/extension-contracts/compatibility/hook/v33.ts@@ -0,0 +1,11 @@+import { defineHook } from "#public/hooks/index.js";++// Epoch 33 `task.settled` events had no `name` or `kind`; epoch 34 adds both+// as optional. Hooks that pair settled calls with `task.started` keep working.+export default defineHook({+ events: {+ "task.settled"(event) {+ console.info("task settled", { callId: event.data.callId, status: event.data.status });+ },+ },+});diff --git a/packages/eve/extension-contracts/compatibility/schedule/v21.ts b/packages/eve/extension-contracts/compatibility/schedule/v21.tsnew file mode 100644index 000000000..295b9f6f3--- /dev/null+++ b/packages/eve/extension-contracts/compatibility/schedule/v21.ts@@ -0,0 +1,17 @@+import { defineChannel } from "#public/channels/index.js";+import { defineSchedule } from "#public/schedules/index.js";++// Epoch 21 `task.settled` events had no `name` or `kind`; epoch 22 adds both as optional.+const updates = defineChannel({+ routes: [],+ receive(input, { from }) {+ return from("daily-updates").send(input.message, { auth: input.auth });+ },+});++export default defineSchedule({+ cron: "0 9 * * *",+ async run({ to, appAuth }) {+ await to(updates, {}).send("Prepare the daily summary.", { auth: appAuth });+ },+});diff --git a/packages/eve/extension-contracts/compatibility/schedule/v22.ts b/packages/eve/extension-contracts/compatibility/schedule/v22.tsnew file mode 100644index 000000000..1aa8e3aaf--- /dev/null+++ b/packages/eve/extension-contracts/compatibility/schedule/v22.ts@@ -0,0 +1,18 @@+import { defineChannel } from "#public/channels/index.js";+import { defineSchedule } from "#public/schedules/index.js";++// Epoch 22 schedules had no `isScheduleAuth` export; epoch 23 adds it.+// Schedules that pass `appAuth` through keep working.+const digest = defineChannel({+ routes: [],+ receive(input, { from }) {+ return from("weekly-digest").send(input.message, { auth: input.auth });+ },+});++export default defineSchedule({+ cron: "0 8 * * 1",+ async run({ to, appAuth, waitUntil }) {+ waitUntil(to(digest, {}).send("Prepare the weekly digest.", { auth: appAuth }));+ },+});diff --git a/packages/eve/extension-contracts/compatibility/subagent/v25.ts b/packages/eve/extension-contracts/compatibility/subagent/v25.tsnew file mode 100644index 000000000..67f9f8da7--- /dev/null+++ b/packages/eve/extension-contracts/compatibility/subagent/v25.ts@@ -0,0 +1,14 @@+import { defineAgent, defineDynamic } from "#public/index.js";++// Epoch 25 `task.settled` events had no `name` or `kind`; epoch 26 adds both as optional.+export default defineDynamic({+ events: {+ "turn.started": (_event, ctx) =>+ ctx.session.auth.current === null+ ? null+ : defineAgent({+ description: "Investigate the authenticated user request.",+ model: "openai/gpt-5.6-sol",+ }),+ },+});diff --git a/packages/eve/extension-contracts/compatibility/tool/v66.ts b/packages/eve/extension-contracts/compatibility/tool/v66.tsnew file mode 100644index 000000000..689d4677f--- /dev/null+++ b/packages/eve/extension-contracts/compatibility/tool/v66.ts@@ -0,0 +1,13 @@+import { defineTool } from "#public/tools/index.js";++// Epoch 66 `task.settled` events had no `name` or `kind`; epoch 67 adds both+// as optional. Tools that never read task events keep working.+export default defineTool({+ description: "Look up an order by id.",+ inputSchema: {+ type: "object",+ properties: { id: { type: "string" } },+ required: ["id"],+ },+ execute: (input) => ({ id: (input as { readonly id: string }).id }),+});diff --git a/packages/eve/extension-contracts/compatibility/tool/v67.ts b/packages/eve/extension-contracts/compatibility/tool/v67.tsnew file mode 100644index 000000000..41c709333--- /dev/null+++ b/packages/eve/extension-contracts/compatibility/tool/v67.ts@@ -0,0 +1,13 @@+import { defineTool } from "#public/tools/index.js";++// Epoch 67 had no `serializeModelInputSchema` export; epoch 68 adds it.+// Tools with plain JSON input schemas keep working.+export default defineTool({+ description: "Look up an order by id.",+ inputSchema: {+ type: "object",+ properties: { id: { type: "string" } },+ required: ["id"],+ },+ execute: (input) => ({ id: (input as { readonly id: string }).id }),+});diff --git a/packages/eve/extension-contracts/entrypoints/schedule.ts b/packages/eve/extension-contracts/entrypoints/schedule.tsindex a612823a7..4c6a3f0d0 100644--- a/packages/eve/extension-contracts/entrypoints/schedule.ts+++ b/packages/eve/extension-contracts/entrypoints/schedule.ts@@ -1,5 +1,6 @@export {defineSchedule,+ isScheduleAuth,type ScheduleDefinition,type ScheduleHandlerArgs,type ScheduleRunHandler,diff --git a/packages/eve/extension-contracts/entrypoints/tool.ts b/packages/eve/extension-contracts/entrypoints/tool.tsindex a981884c7..a7a6c7b3e 100644--- a/packages/eve/extension-contracts/entrypoints/tool.ts+++ b/packages/eve/extension-contracts/entrypoints/tool.ts@@ -3,6 +3,7 @@ export {defineWorkflowTool,disableTool,isDisabledToolSentinel,+ serializeModelInputSchema,toolOutput,toolOutputPart,toolResultFrom,diff --git a/packages/eve/extension-contracts/reports/channel/v40.json b/packages/eve/extension-contracts/reports/channel/v40.jsonnew file mode 100644index 000000000..66e3f23d3--- /dev/null+++ b/packages/eve/extension-contracts/reports/channel/v40.json@@ -0,0 +1,21 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "channel",+ "epoch": 40,+ "sha256": "2e0e7af02d1fa6af66a02901999b4baf2f01d2274cc0246e684870a42a5aefbe",+ "exports": [+ "DELETE",+ "GET",+ "HEAD",+ "OPTIONS",+ "PATCH",+ "POST",+ "PUT",+ "WS",+ "createWebSocketUpgradeServer",+ "defineChannel",+ "disableRoute",+ "isChannel",+ "isDisabledRouteSentinel"+ ]+}diff --git a/packages/eve/extension-contracts/reports/channel/v41.json b/packages/eve/extension-contracts/reports/channel/v41.jsonnew file mode 100644index 000000000..5524d302b--- /dev/null+++ b/packages/eve/extension-contracts/reports/channel/v41.json@@ -0,0 +1,21 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "channel",+ "epoch": 41,+ "sha256": "56c6b6d94589b7f85addc76dcc3fa1571ff1f535ae5bdb09f819f1a5406bcb57",+ "exports": [+ "DELETE",+ "GET",+ "HEAD",+ "OPTIONS",+ "PATCH",+ "POST",+ "PUT",+ "WS",+ "createWebSocketUpgradeServer",+ "defineChannel",+ "disableRoute",+ "isChannel",+ "isDisabledRouteSentinel"+ ]+}diff --git a/packages/eve/extension-contracts/reports/connection/v35.json b/packages/eve/extension-contracts/reports/connection/v35.jsonnew file mode 100644index 000000000..0433c4ea3--- /dev/null+++ b/packages/eve/extension-contracts/reports/connection/v35.json@@ -0,0 +1,16 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "connection",+ "epoch": 35,+ "sha256": "694baf596d4e56875aa2b444d5257d31462ed06f0dd8567034f5783080d4b9f4",+ "exports": [+ "ConnectionAuthorizationFailedError",+ "ConnectionAuthorizationRequiredError",+ "defineDynamic",+ "defineInteractiveAuthorization",+ "defineMcpClientConnection",+ "defineOpenAPIConnection",+ "isConnectionAuthorizationFailedError",+ "isConnectionAuthorizationRequiredError"+ ]+}diff --git a/packages/eve/extension-contracts/reports/dynamicInstructions/v29.json b/packages/eve/extension-contracts/reports/dynamicInstructions/v29.jsonnew file mode 100644index 000000000..0a27042fe--- /dev/null+++ b/packages/eve/extension-contracts/reports/dynamicInstructions/v29.json@@ -0,0 +1,7 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "dynamicInstructions",+ "epoch": 29,+ "sha256": "895383e08b599e1b94ffe231e7fb76526072c66cf54a0c82d96c3a49453212ff",+ "exports": ["defineDynamic"]+}diff --git a/packages/eve/extension-contracts/reports/dynamicSkill/v28.json b/packages/eve/extension-contracts/reports/dynamicSkill/v28.jsonnew file mode 100644index 000000000..10414746a--- /dev/null+++ b/packages/eve/extension-contracts/reports/dynamicSkill/v28.json@@ -0,0 +1,7 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "dynamicSkill",+ "epoch": 28,+ "sha256": "c6cc3e13f9c212045a8867060129804a4f90aa6e18665b9d22b67a17f99ad5ba",+ "exports": ["defineDynamic"]+}diff --git a/packages/eve/extension-contracts/reports/dynamicTool/v65.json b/packages/eve/extension-contracts/reports/dynamicTool/v65.jsonnew file mode 100644index 000000000..2bede5605--- /dev/null+++ b/packages/eve/extension-contracts/reports/dynamicTool/v65.json@@ -0,0 +1,16 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "dynamicTool",+ "epoch": 65,+ "sha256": "a7560618d7eb254f1983d32e2b729f3798ebc54eda44c45ac5cdcc951d58c5dd",+ "exports": [+ "DynamicToolEntry",+ "DynamicToolEvents",+ "DynamicToolResult",+ "DynamicToolSet",+ "auto",+ "defineDurableCallback",+ "defineDurableSchema",+ "defineDynamic"+ ]+}diff --git a/packages/eve/extension-contracts/reports/hook/v34.json b/packages/eve/extension-contracts/reports/hook/v34.jsonnew file mode 100644index 000000000..91273a8fe--- /dev/null+++ b/packages/eve/extension-contracts/reports/hook/v34.json@@ -0,0 +1,7 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "hook",+ "epoch": 34,+ "sha256": "8cfb166f39fec13e36f226376c1243321d0af1c0795ad8a9783d9e8264fe4081",+ "exports": ["defineHook"]+}diff --git a/packages/eve/extension-contracts/reports/schedule/v22.json b/packages/eve/extension-contracts/reports/schedule/v22.jsonnew file mode 100644index 000000000..0599ef707--- /dev/null+++ b/packages/eve/extension-contracts/reports/schedule/v22.json@@ -0,0 +1,14 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "schedule",+ "epoch": 22,+ "sha256": "b6d0ae59aac96522e773f2417d8f84fccac3a21ff756fb07f68ae245876827d0",+ "exports": [+ "ScheduleDefinition",+ "ScheduleHandlerArgs",+ "ScheduleRunHandler",+ "ScheduleToFn",+ "TypedReceiveTarget",+ "defineSchedule"+ ]+}diff --git a/packages/eve/extension-contracts/reports/schedule/v23.json b/packages/eve/extension-contracts/reports/schedule/v23.jsonnew file mode 100644index 000000000..e580d8351--- /dev/null+++ b/packages/eve/extension-contracts/reports/schedule/v23.json@@ -0,0 +1,15 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "schedule",+ "epoch": 23,+ "sha256": "7e6fc865f586d37bc7096d2dbe10c43442674150adf245c01c2f953928768097",+ "exports": [+ "ScheduleDefinition",+ "ScheduleHandlerArgs",+ "ScheduleRunHandler",+ "ScheduleToFn",+ "TypedReceiveTarget",+ "defineSchedule",+ "isScheduleAuth"+ ]+}diff --git a/packages/eve/extension-contracts/reports/subagent/v26.json b/packages/eve/extension-contracts/reports/subagent/v26.jsonnew file mode 100644index 000000000..834b9f0d9--- /dev/null+++ b/packages/eve/extension-contracts/reports/subagent/v26.json@@ -0,0 +1,23 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "subagent",+ "epoch": 26,+ "sha256": "3da9757005b69ca82ee5a4db2e78557d0d037a0cf3852c8fd98952c07cf2fbb7",+ "exports": [+ "AgentCompactionDefinition",+ "AgentDefinition",+ "AgentModelDefinition",+ "AgentStaticModelDefinition",+ "DefinedAgent",+ "DynamicLocalSubagentDefinition",+ "DynamicSubagentDefinition",+ "RemoteAgentDefinition",+ "RemoteAgentDefinitionInput",+ "WorkspaceAgentDefinition",+ "WorkspaceAgentTransport",+ "defineAgent",+ "defineDynamic",+ "defineRemoteAgent",+ "defineWorkspaceAgent"+ ]+}diff --git a/packages/eve/extension-contracts/reports/tool/v67.json b/packages/eve/extension-contracts/reports/tool/v67.jsonnew file mode 100644index 000000000..6475e479d--- /dev/null+++ b/packages/eve/extension-contracts/reports/tool/v67.json@@ -0,0 +1,28 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "tool",+ "epoch": 67,+ "sha256": "0a2f471fefef416b4add7be1816c256786698ebd64fb665a864e36f6cfc226b1",+ "exports": [+ "AgentRouterInput",+ "AgentRouterTool",+ "WorkflowStepToolContext",+ "WorkflowTool",+ "WorkflowToolDefinition",+ "WorkflowToolInput",+ "WorkflowToolOptions",+ "agentRouter",+ "defaultWebSearch",+ "defineTool",+ "defineWorkflowTool",+ "disableTool",+ "evaluate",+ "isDisabledToolSentinel",+ "isWebSearchToolDefinition",+ "toolOutput",+ "toolOutputPart",+ "toolResultFrom",+ "webSearch",+ "workflow"+ ]+}diff --git a/packages/eve/extension-contracts/reports/tool/v68.json b/packages/eve/extension-contracts/reports/tool/v68.jsonnew file mode 100644index 000000000..cb535839a--- /dev/null+++ b/packages/eve/extension-contracts/reports/tool/v68.json@@ -0,0 +1,29 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "tool",+ "epoch": 68,+ "sha256": "c4b949ea164e46665458e3858200b7321c075911b57911f32fbed8d2dcff91e8",+ "exports": [+ "AgentRouterInput",+ "AgentRouterTool",+ "WorkflowStepToolContext",+ "WorkflowTool",+ "WorkflowToolDefinition",+ "WorkflowToolInput",+ "WorkflowToolOptions",+ "agentRouter",+ "defaultWebSearch",+ "defineTool",+ "defineWorkflowTool",+ "disableTool",+ "evaluate",+ "isDisabledToolSentinel",+ "isWebSearchToolDefinition",+ "serializeModelInputSchema",+ "toolOutput",+ "toolOutputPart",+ "toolResultFrom",+ "webSearch",+ "workflow"+ ]+}diff --git a/packages/eve/src/channel/channel-operations.test.ts b/packages/eve/src/channel/channel-operations.test.tsindex 104fdbb80..a9156b212 100644--- a/packages/eve/src/channel/channel-operations.test.ts+++ b/packages/eve/src/channel/channel-operations.test.ts@@ -74,7 +74,7 @@ describe("createChannelOperations", () => {});});- it("carries an input-response state patch through the durable delivery", async () => {+ it("carries send and input-response state through the durable delivery", async () => {const runtime = createRuntime();const { from } = createChannelOperations<{ responder: string }>({adapter: { kind: "slack" },@@ -82,12 +82,23 @@ describe("createChannelOperations", () => {runtime,});+ await from("C1:T1").send("hello", { auth: null, state: { responder: "U_AUTHOR" } });await from("C1:T1").respond([{ optionId: "approve", requestId: "approval-1" }], {auth: null,state: { responder: "U_APPROVER" },});- expect(runtime.dispatchContinuation).toHaveBeenCalledWith({+ expect(runtime.dispatchContinuation).toHaveBeenNthCalledWith(1, {+ command: {+ auth: null,+ kind: "send",+ payload: { message: "hello", state: { responder: "U_AUTHOR" } },+ requestId: undefined,+ turnPolicy: "steer",+ },+ continuationToken: "slack:C1:T1",+ });+ expect(runtime.dispatchContinuation).toHaveBeenNthCalledWith(2, {command: {auth: null,kind: "send",diff --git a/packages/eve/src/channel/channel-operations.ts b/packages/eve/src/channel/channel-operations.tsindex abd9d236a..f893585ac 100644--- a/packages/eve/src/channel/channel-operations.ts+++ b/packages/eve/src/channel/channel-operations.ts@@ -2,11 +2,7 @@ import type { UserContent } from "ai";import type { ChannelAdapter } from "#channel/adapter.js";import type { ChannelDeliverySource } from "#channel/delivery-metadata.js";-import {- createChannelAddressFn,- type ChannelAddressDeliveryOptions,-} from "#channel/channel-address.js";-import type { SendPayload } from "#channel/routes.js";+import { createChannelAddressFn } from "#channel/channel-address.js";import type { Session } from "#channel/session.js";import type {CancelTurnResult,@@ -23,12 +19,15 @@ import {parseInputResponses,type StrictInputResponses,} from "#shared/input.js";+import type { JsonObject } from "#shared/json.js";interface BaseChannelSendOptions {readonly auth: SessionAuthContext | null;readonly callback?: SessionCallback;readonly context?: readonly string[];readonly initiatorAuth?: SessionAuthContext | null;+ /** JSON Schema for a structured final answer, as on `Session.send()`. */+ readonly outputSchema?: JsonObject;readonly title?: string;readonly turnPolicy?: TurnPolicy;}@@ -78,16 +77,6 @@ export interface ChannelReceiveContext<TState = undefined> {readonly resolveSession: ChannelResolveSession;}-export const INTERNAL_CHANNEL_DELIVER = Symbol("eve.internal.channel-deliver");--/** @internal Permissive transport delivery retained below public authoring surfaces. */-export interface InternalChannelSource<TState = undefined> extends ChannelSource<TState> {- [INTERNAL_CHANNEL_DELIVER](- payload: SendPayload,- options: ChannelAddressDeliveryOptions<TState>,- ): Promise<Session>;-}-/** Creates request-scoped channel operations backed by continuation dispatch. */export function createChannelOperations<TState = undefined>(input: {readonly adapter: ChannelAdapter<any>;@@ -101,12 +90,16 @@ export function createChannelOperations<TState = undefined>(input: {return {from(address) {const bound = channelAddress(address);- const source: InternalChannelSource<TState> = {+ const source: ChannelSource<TState> = {async send(message, options) {+ // Deliver hooks read per-delivery state (such as the message author)+ // from the payload, as they do for `respond()`.return await bound.deliver({context: options.context,message,+ outputSchema: options.outputSchema,+ state: (options as { readonly state?: TState }).state,},options,);@@ -137,9 +130,6 @@ export function createChannelOperations<TState = undefined>(input: {async reset(options) {return await bound.reset(options);},- async [INTERNAL_CHANNEL_DELIVER](payload, options) {- return await bound.deliver(payload, options);- },};return source;},diff --git a/packages/eve/src/channel/compiled-channel.ts b/packages/eve/src/channel/compiled-channel.tsindex 0b531f2a1..6d29db811 100644--- a/packages/eve/src/channel/compiled-channel.ts+++ b/packages/eve/src/channel/compiled-channel.ts@@ -81,9 +81,11 @@ export function setChannelBuildMetadata(factory: ChannelBuildMetadataFactory,): void {if (!isCompiledChannel(channel)) throw new TypeError("Expected a compiled channel.");+ // Enumerable so `{ ...channel, routes }` keeps build metadata when an app+ // wraps a channel's routes.Object.defineProperty(channel, CHANNEL_BUILD_METADATA, {configurable: true,- enumerable: false,+ enumerable: true,value: factory,});}diff --git a/packages/eve/src/channel/schedule-auth.ts b/packages/eve/src/channel/schedule-auth.tsindex 9eef65476..2526af15b 100644--- a/packages/eve/src/channel/schedule-auth.ts+++ b/packages/eve/src/channel/schedule-auth.ts@@ -9,3 +9,26 @@ export const SCHEDULE_APP_AUTH: SessionAuthContext = {principalId: "eve:app",principalType: "runtime",};++/**+ * Returns true when `auth` is the default app principal that schedules pass+ * as `appAuth`. It identifies that principal, not how a turn started: a+ * schedule handler may send with a user's auth instead, and any code can+ * reuse `appAuth`.+ *+ * @example+ * ```ts+ * import { isScheduleAuth } from "eve/schedules";+ *+ * if (isScheduleAuth(ctx.session.auth.current)) {+ * // Work the agent does on its own behalf.+ * }+ * ```+ */+export function isScheduleAuth(auth: SessionAuthContext | null | undefined): boolean {+ return (+ auth?.authenticator === SCHEDULE_APP_AUTH.authenticator &&+ auth.principalId === SCHEDULE_APP_AUTH.principalId &&+ auth.principalType === SCHEDULE_APP_AUTH.principalType+ );+}diff --git a/packages/eve/src/channel/schedule.test.ts b/packages/eve/src/channel/schedule.test.tsindex 7f4ebfeb1..a5f114b76 100644--- a/packages/eve/src/channel/schedule.test.ts+++ b/packages/eve/src/channel/schedule.test.ts@@ -11,8 +11,9 @@ import {} from "#channel/schedule.js";import { contextStorage } from "#context/container.js";import { ScheduleIdKey } from "#context/keys.js";-import type { RunHandle, Runtime } from "#channel/types.js";+import type { RunHandle, Runtime, SessionAuthContext } from "#channel/types.js";import { slackChannel } from "#public/channels/slack/slackChannel.js";+import { isScheduleAuth } from "#public/schedules/index.js";import type { ResolvedChannelDefinition } from "#runtime/types.js";function createMockRunHandle(): RunHandle {@@ -209,6 +210,32 @@ describe("ScheduleDispatcher", () => {});});+ it("isScheduleAuth recognizes the app principal schedules dispatch with, and only it", async () => {+ const runtime = createMockRuntime();+ const dispatcher = new ScheduleDispatcher({ runtime, channels: [] });+ let appAuth: SessionAuthContext | undefined;++ await dispatcher.trigger({ scheduleId: "heartbeat", markdown: "Run heartbeat task." });+ await dispatcher.trigger({+ scheduleId: "digest",+ async run(args) {+ appAuth = args.appAuth;+ },+ });++ expect(isScheduleAuth(vi.mocked(runtime.createSession).mock.calls[0]![0].auth)).toBe(true);+ expect(isScheduleAuth(appAuth)).toBe(true);+ const alice: SessionAuthContext = {+ attributes: {},+ authenticator: "okta",+ principalId: "okta|alice",+ principalType: "user",+ };+ expect(isScheduleAuth(alice)).toBe(false);+ expect(isScheduleAuth({ ...alice, principalId: "eve:app" })).toBe(false);+ expect(isScheduleAuth(null)).toBe(false);+ });+it("throws when neither run nor markdown is provided", async () => {const runtime = createMockRuntime();const dispatcher = new ScheduleDispatcher({ runtime, channels: [] });diff --git a/packages/eve/src/cli/commands/info.test.ts b/packages/eve/src/cli/commands/info.test.tsindex c591f3b23..3885398d3 100644--- a/packages/eve/src/cli/commands/info.test.ts+++ b/packages/eve/src/cli/commands/info.test.ts@@ -1,4 +1,5 @@import { describe, expect, test, vi } from "vitest";+import { z } from "zod";import { COMPILE_METADATA_KIND, COMPILE_METADATA_VERSION } from "#compiler/artifacts.js";import type { CompileAgentResult } from "#compiler/compile-agent.js";@@ -7,6 +8,7 @@ import { defineInstructions } from "#public/definitions/instructions.js";import { defineSchedule } from "#public/definitions/schedule.js";import { getApplicationInfo } from "#internal/application/paths.js";import { inspectApplication } from "#services/inspect-application.js";+import { defineTool } from "#tools/definition.js";import { buildApplicationInfoJson, printApplicationInfo } from "./info.js";@@ -38,6 +40,16 @@ async function makeCompiledState(): Promise<CompileAgentResult> {}),logicalPath: "schedules/morning-digest.ts",},+ {+ loadNamespace: async () => ({+ default: defineTool({+ description: "Look up an order.",+ execute: () => null,+ inputSchema: z.object({ id: z.string() }),+ }),+ }),+ logicalPath: "tools/lookup_order.ts",+ },],name: "triage-bot",tools: [{ description: "Create a triage ticket.", name: "create_ticket" }],@@ -90,6 +102,35 @@ describe("buildApplicationInfoJson", () => {status: "ready",});expect(json.tools).toContain("create_ticket");+ // Library schemas are closed for the model; plain JSON Schema is sent as written.+ expect(json.toolInputSchemas.root.lookup_order).toEqual({+ additionalProperties: false,+ properties: { id: { type: "string" } },+ required: ["id"],+ type: "object",+ });+ expect(json.toolInputSchemas.root.create_ticket).toEqual({+ additionalProperties: true,+ type: "object",+ });+ });++ test("keys each subagent's tool input schemas by subagent name", async () => {+ const compiledState = await makeCompiledState();+ const lookupOrder = compiledState.manifest.tools.find((tool) => tool.name === "lookup_order")!;+ const researcher = { agent: { tools: [lookupOrder] }, name: "researcher" };+ const json = buildApplicationInfoJson({+ application: getApplicationInfo(APP_ROOT),+ compiledState: {+ ...compiledState,+ manifest: { ...compiledState.manifest, subagents: [researcher as never] },+ },+ messaging: MESSAGING,+ });++ expect(json.toolInputSchemas.subagents).toEqual({+ researcher: { lookup_order: lookupOrder.modelInputSchema },+ });expect(json.channels).toContainEqual(expect.objectContaining({ method: "GET", urlPath: "/eve/v1/health" }),);diff --git a/packages/eve/src/cli/commands/info.ts b/packages/eve/src/cli/commands/info.tsindex 49fdddbc3..d6be3138c 100644--- a/packages/eve/src/cli/commands/info.ts+++ b/packages/eve/src/cli/commands/info.ts@@ -1,5 +1,6 @@import { type ApplicationInspection, inspectApplication } from "#services/inspect-application.js";-import type { CompiledInstructionsDefinition } from "#compiler/manifest.js";+import type { CompiledInstructionsDefinition, CompiledToolDefinition } from "#compiler/manifest.js";+import type { JsonObject } from "#shared/json.js";import { type CliRow, createCliTheme, renderCliSection } from "#cli/ui/output.js";interface CliInfoLogger {@@ -23,6 +24,13 @@ export interface ApplicationInfoJson {instructions: string | null;skills: string[];tools: string[];+ /** Each static tool's input schema as eve sends it to a model, keyed by tool name. */+ toolInputSchemas: {+ /** The root agent's tools, including tools from mounted extensions. */+ root: Record<string, JsonObject>;+ /** Each declared subagent's own tools, keyed by subagent name. */+ subagents: Record<string, Record<string, JsonObject>>;+ };subagents: string[];schedules: string[];channels: { name: string; kind: string | null; method: string | null; urlPath: string | null }[];@@ -67,6 +75,15 @@ export function buildApplicationInfoJson(inspection: ApplicationInspection): App: formatInstructions(compiledState.manifest.instructions),skills: (compiledState?.manifest.skills ?? []).map((skill) => skill.name),tools: (compiledState?.manifest.tools ?? []).map((tool) => tool.name),+ toolInputSchemas: {+ root: modelInputSchemas(compiledState?.manifest.tools ?? []),+ subagents: Object.fromEntries(+ (compiledState?.manifest.subagents ?? []).map((subagent) => [+ subagent.name,+ modelInputSchemas(subagent.agent.tools),+ ]),+ ),+ },subagents: (compiledState?.manifest.subagents ?? []).map((subagent) => subagent.name),schedules: (compiledState?.manifest.schedules ?? []).map((schedule) => schedule.name),channels: (compiledState?.manifest.channelRoutes.effective ?? []).map((channel) => ({@@ -92,6 +109,15 @@ export function buildApplicationInfoJson(inspection: ApplicationInspection): App};}+/** Provider-managed tools, such as `web_search`, have no eve input schema and are omitted. */+function modelInputSchemas(tools: readonly CompiledToolDefinition[]): Record<string, JsonObject> {+ return Object.fromEntries(+ tools.flatMap((tool) =>+ tool.modelInputSchema === undefined ? [] : [[tool.name, tool.modelInputSchema]],+ ),+ );+}+function pluralize(count: number, noun: string): string {return `${count} ${noun}${count === 1 ? "" : "s"}`;}diff --git a/packages/eve/src/client/message-reducer.test.ts b/packages/eve/src/client/message-reducer.test.tsindex 6f6b644c4..04d4b4844 100644--- a/packages/eve/src/client/message-reducer.test.ts+++ b/packages/eve/src/client/message-reducer.test.ts@@ -18,7 +18,6 @@ import {createReasoningCompletedEvent,createResultCompletedEvent,createStepStartedEvent,- createTaskSettledEvent,createTurnCancelledEvent,createTurnCompletedEvent,createTurnFailedEvent,@@ -1283,6 +1282,7 @@ describe("defaultMessageReducer", () => {});describe("task tool parts", () => {+ // Built without `name` and `kind`, as events recorded by older eve versions are.function settleResearchTask(settled: TaskSettledStreamEvent["data"]) {const reducer = defaultMessageReducer();const data = reduceServerEvents(reducer, reducer.initial(), [@@ -1298,7 +1298,7 @@ describe("defaultMessageReducer", () => {turnId: "turn_1",}),createTurnCompletedEvent({ sequence: 0, turnId: "turn_1" }),- createTaskSettledEvent(settled),+ { data: settled, type: "task.settled" },]);const [message] = data.messages;return { status: message?.metadata?.status, toolPart: message?.parts[1] };diff --git a/packages/eve/src/compiler/extension-compatibility.ts b/packages/eve/src/compiler/extension-compatibility.tsindex 2543f9671..4b2a12cdd 100644--- a/packages/eve/src/compiler/extension-compatibility.ts+++ b/packages/eve/src/compiler/extension-compatibility.ts@@ -22,9 +22,10 @@ interface ExtensionCapabilityContract {const EXTENSION_CAPABILITY_CONTRACTS = {extension: { current: 1, supported: [1], dropped: {} },tool: {- current: 66,+ current: 68,supported: [- 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 29, 30, 31, 32, 34, 35, 54, 55, 63, 64, 65, 66,+ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 29, 30, 31, 32, 34, 35, 54, 55, 63, 64, 65, 66, 67,+ 68,],dropped: {14: "TaskExec.delegated was removed; migrate to workflow-backed background tools",@@ -71,10 +72,10 @@ const EXTENSION_CAPABILITY_CONTRACTS = {},},dynamicTool: {- current: 64,+ current: 65,supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 22, 31, 32, 33, 52, 54,- 60, 61, 62, 63, 64,+ 60, 61, 62, 63, 64, 65,],dropped: {21: "Message and reasoning append events now expose deltas instead of cumulative snapshots.",@@ -113,8 +114,10 @@ const EXTENSION_CAPABILITY_CONTRACTS = {},},channel: {- current: 39,- supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 29, 31, 36, 37, 38, 39],+ current: 41,+ supported: [+ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 29, 31, 36, 37, 38, 39, 40, 41,+ ],dropped: {12: "Message and reasoning append events now expose deltas instead of cumulative snapshots.",19: "Continuation rekey was removed; channel extensions must use additive continuation.alias instead.",@@ -135,8 +138,8 @@ const EXTENSION_CAPABILITY_CONTRACTS = {},},schedule: {- current: 21,- supported: [1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 18, 19, 20, 21],+ current: 23,+ supported: [1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 18, 19, 20, 21, 22, 23],dropped: {5: "Message and reasoning append events now expose deltas instead of cumulative snapshots.",16: 'Background task delivery was removed: sends no longer accept taskDeliveryPolicy and message.completed always carries text. input.resolved reports outcome "cancelled" when a workflow tool withdraws a ctx.ask() request, and stream events gained agent.started, published when a workflow run opens a ctx.agent session, and turn.waiting, which parks the open turn instead of emitting turn.completed and session.waiting.',@@ -144,8 +147,8 @@ const EXTENSION_CAPABILITY_CONTRACTS = {},},subagent: {- current: 25,- supported: [3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 19, 23, 24, 25],+ current: 26,+ supported: [3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 19, 23, 24, 25, 26],dropped: {1: "Persistent subagent sessions are now the default and the experimental opt-in was removed",2: "Persistent subagent sessions are now the default and the experimental opt-in was removed",@@ -158,9 +161,10 @@ const EXTENSION_CAPABILITY_CONTRACTS = {},},connection: {- current: 34,+ current: 35,supported: [1, 2, 3, 4, 5, 6, 7, 8, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 24, 26, 32, 33, 34,+ 35,],dropped: {9: "Dynamic connection resolvers no longer receive conversation or channel continuation data",@@ -175,8 +179,8 @@ const EXTENSION_CAPABILITY_CONTRACTS = {},},hook: {- current: 33,- supported: [20, 21, 22, 23, 25, 27, 31, 32, 33],+ current: 34,+ supported: [20, 21, 22, 23, 25, 27, 31, 32, 33, 34],dropped: {1: "Model identity moved from session.started runtime metadata to step.started call attribution.",2: "Model identity moved from session.started runtime metadata to step.started call attribution.",@@ -206,8 +210,10 @@ const EXTENSION_CAPABILITY_CONTRACTS = {},skill: { current: 2, supported: [1, 2], dropped: {} },dynamicSkill: {- current: 27,- supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 25, 26, 27],+ current: 28,+ supported: [+ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 25, 26, 27, 28,+ ],dropped: {13: "Message and reasoning append events now expose deltas instead of cumulative snapshots.",22: "Run mode was removed; sessions always park and ConversationContext no longer carries mode.",@@ -217,9 +223,9 @@ const EXTENSION_CAPABILITY_CONTRACTS = {},instructions: { current: 2, supported: [1, 2], dropped: {} },dynamicInstructions: {- current: 28,+ current: 29,supported: [- 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17, 18, 19, 20, 21, 22, 26, 27, 28,+ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17, 18, 19, 20, 21, 22, 26, 27, 28, 29,],dropped: {14: "Message and reasoning append events now expose deltas instead of cumulative snapshots.",diff --git a/packages/eve/src/compiler/manifest.ts b/packages/eve/src/compiler/manifest.tsindex d383d5186..635311570 100644--- a/packages/eve/src/compiler/manifest.ts+++ b/packages/eve/src/compiler/manifest.ts@@ -237,6 +237,8 @@ export type CompiledToolDefinition = InternalToolDefinition &readonly behavior?: CompiledToolBehavior;readonly hasExecute: boolean;readonly hasModelOutputProjection: boolean;+ /** The input schema as eve sends it to a model; absent for provider-managed tools. */+ readonly modelInputSchema?: JsonObject;readonly requiresApproval: boolean;readonly workflowProgram?: {readonly maxSubagents: number;@@ -862,6 +864,7 @@ const compiledToolDefinitionSchema = zhasModelOutputProjection: z.boolean(),inputSchema: jsonObjectSchema.nullable(),logicalPath: z.string(),+ modelInputSchema: jsonObjectSchema.optional(),name: z.string(),outputSchema: jsonObjectSchema.optional(),requiresApproval: z.boolean(),diff --git a/packages/eve/src/compiler/normalize-tool.ts b/packages/eve/src/compiler/normalize-tool.tsindex c0648f025..ec94831ea 100644--- a/packages/eve/src/compiler/normalize-tool.ts+++ b/packages/eve/src/compiler/normalize-tool.ts@@ -127,6 +127,7 @@ export async function compileToolEntry(hasModelOutputProjection: entry.definition.hasModelOutputProjection,inputSchema: entry.definition.inputSchema ?? null,logicalPath: source.logicalPath,+ modelInputSchema: entry.definition.modelInputSchema,name: toolName,outputSchema: entry.definition.outputSchema,requiresApproval: entry.definition.hasApproval,diff --git a/packages/eve/src/execution/tasks/session.test.ts b/packages/eve/src/execution/tasks/session.test.tsindex eb6abd169..7d27f668d 100644--- a/packages/eve/src/execution/tasks/session.test.ts+++ b/packages/eve/src/execution/tasks/session.test.ts@@ -79,6 +79,8 @@ describe("answerTaskCancel", () => {{data: {callId: "research-call",+ kind: "tool",+ name: "research",status: "cancelled",taskId: research.taskId,turnId: "turn_1",diff --git a/packages/eve/src/execution/tasks/steps.ts b/packages/eve/src/execution/tasks/steps.tsindex 77cbd4479..617c1743b 100644--- a/packages/eve/src/execution/tasks/steps.ts+++ b/packages/eve/src/execution/tasks/steps.ts@@ -16,6 +16,7 @@ import {writeTaskTable,type TaskCall,type TaskOutcome,+ type TaskRecord,type TaskRunCommand,type TaskRunCommands,type TaskTable,@@ -80,9 +81,10 @@ async function applyTaskRunMessage(case "reply": {({ session, table } = countTaskRunUsage(session, table, taskId, message));const outcome: TaskOutcome = { output: message.output, status: "completed" };+ const record = findTask(table, taskId);const settled = settleTaskCalls(table, { callIds: message.callIds, outcome, taskId });table = settled.table;- events.push(...settled.settled.map((call) => taskSettledEvent(taskId, call, outcome)));+ events.push(...taskSettledEvents(record, settled.settled, outcome));break;}case "usage":@@ -91,8 +93,9 @@ async function applyTaskRunMessage(case "outcome": {({ session, table } = countTaskRunUsage(session, table, taskId, message));const outcome = toOutcome(message);+ const record = findTask(table, taskId);const settled = settleRemainingTaskCalls(table, taskId, outcome);- events.push(...settled.settled.map((call) => taskSettledEvent(taskId, call, outcome)));+ events.push(...taskSettledEvents(record, settled.settled, outcome));table = finishTaskRun(settled.table, taskId, message.from.runId);session = forgetRunQuestions(session, message.from.runId);break;@@ -126,12 +129,12 @@ async function cancelTasks(const events: TaskSettledStreamEvent[] = [];const stoppedRunIds = new Set<string>();for (const taskId of input.taskIds) {- const resumable = findTask(table, taskId)?.resumable;+ const record = findTask(table, taskId);const cancelled = cancelTask(table, taskId);table = cancelled.table;- events.push(...cancelled.settled.map((call) => taskSettledEvent(taskId, call, CANCELLED)));+ events.push(...taskSettledEvents(record, cancelled.settled, CANCELLED));if (cancelled.send === undefined) continue;- if (resumable === false) stoppedRunIds.add(cancelled.send.run.runId);+ if (record?.resumable === false) stoppedRunIds.add(cancelled.send.run.runId);await sendTaskRunCommands(cancelled.send);}const withdrawn = withdrawWorkflowAsks(session, (_requestId, runId) => stoppedRunIds.has(runId));@@ -144,13 +147,28 @@ async function cancelTasks(const CANCELLED: TaskOutcome = { status: "cancelled" };-/** The `task.settled` event for one settled call. */+/** The `task.settled` events for a task's settled calls; calls only settle on a known task. */+function taskSettledEvents(+ record: TaskRecord | undefined,+ settled: readonly TaskCall[],+ outcome: TaskOutcome,+): TaskSettledStreamEvent[] {+ if (record === undefined) return [];+ return settled.map((call) => taskSettledEvent(record, call, outcome));+}+function taskSettledEvent(- taskId: string,+ record: TaskRecord,call: TaskCall,outcome: TaskOutcome,): TaskSettledStreamEvent {- const base = { callId: call.callId, taskId, turnId: call.turnId };+ const base = {+ callId: call.callId,+ kind: record.kind,+ name: record.name,+ taskId: record.id,+ turnId: call.turnId,+ };switch (outcome.status) {case "completed":return createTaskSettledEvent({ ...base, output: outcome.output, status: "completed" });diff --git a/packages/eve/src/execution/tasks/task-id-input.ts b/packages/eve/src/execution/tasks/task-id-input.tsindex 95c470daa..2639183fb 100644--- a/packages/eve/src/execution/tasks/task-id-input.ts+++ b/packages/eve/src/execution/tasks/task-id-input.ts@@ -8,7 +8,7 @@ import type { HarnessToolDefinition } from "#harness/execute-tool.js";import type { JsonObject } from "#shared/json.js";import { firstSentence } from "#shared/presentation-text.js";import { AGENT_TOOL_NAME } from "#tools/framework/agent-contract.js";-import { isToolSchema, withOptionalStringProperty } from "#tools/schema.js";+import { isToolSchema, type ToolSchema, withOptionalStringProperty } from "#tools/schema.js";// A `serve` tool's model input is the tool's own input plus an optional// `taskId`, which sends the call to the running task it names.@@ -16,6 +16,14 @@ import { isToolSchema, withOptionalStringProperty } from "#tools/schema.js";/** The model input property eve adds to every `serve` tool. */export const TASK_ID_INPUT = "taskId";+/** A `serve` tool's input schema as the model sees it, with the optional `taskId`. */+export function withTaskIdSchema(schema: ToolSchema): ToolSchema {+ return withOptionalStringProperty(schema, {+ description: TASK_ID_INPUT_DESCRIPTION,+ name: TASK_ID_INPUT,+ });+}+/*** The tool as the model sees it: its input gains `taskId`, and its description* explains it. An agent tool also gets its activity label, the agent and the@@ -33,10 +41,7 @@ export function withTaskIdInput(definition: HarnessToolDefinition): HarnessToolDdefinition.description,agent ? AGENT_SERVE_TOOL_DESCRIPTION : SERVE_TOOL_DESCRIPTION,),- inputSchema: withOptionalStringProperty(schema, {- description: TASK_ID_INPUT_DESCRIPTION,- name: TASK_ID_INPUT,- }),+ inputSchema: withTaskIdSchema(schema),};if (!agent || definition.label?.start !== undefined) return described;return {diff --git a/packages/eve/src/internal/authored-definition/schema-backed.test.ts b/packages/eve/src/internal/authored-definition/schema-backed.test.tsindex fd01ec3da..6d7ed0396 100644--- a/packages/eve/src/internal/authored-definition/schema-backed.test.ts+++ b/packages/eve/src/internal/authored-definition/schema-backed.test.ts@@ -6,6 +6,7 @@ import { defineDynamic } from "#dynamic/definition.js";import { defineTool, disableTool } from "#tools/definition.js";import { once } from "#tools/approval/policies.js";import { webSearch } from "#tools/provided/web-search.js";+import { defineWorkflowTool } from "#tools/workflow-definition.js";import { normalizeToolDefinition } from "#internal/authored-definition/schema-backed.js";const FAILURE_MESSAGE = "Expected the tool export to match the public eve shape.";@@ -66,6 +67,27 @@ describe("normalizeToolDefinition", () => {});});+ it("captures a serve tool's model input schema with the taskId eve adds", () => {+ async function serve() {}+ Reflect.set(serve, "workflowId", "workflow//test//review");+ const tool = defineWorkflowTool({+ description: "Reviews a pull request.",+ inputSchema: z.object({ pr: z.number() }),+ serve,+ });++ const entry = normalizeToolDefinition(tool, FAILURE_MESSAGE);++ if (entry.kind !== "tool") throw new Error("expected tool kind");+ expect(entry.definition.inputSchema).not.toHaveProperty("properties.taskId");+ expect(entry.definition.modelInputSchema).toMatchObject({+ additionalProperties: false,+ properties: { pr: { type: "number" }, taskId: { type: "string" } },+ required: ["pr"],+ type: "object",+ });+ });+it("returns a disabled entry for a disableTool sentinel", () => {const sentinel = disableTool();diff --git a/packages/eve/src/internal/authored-definition/schema-backed.ts b/packages/eve/src/internal/authored-definition/schema-backed.tsindex 26746240e..4fe359aa6 100644--- a/packages/eve/src/internal/authored-definition/schema-backed.ts+++ b/packages/eve/src/internal/authored-definition/schema-backed.ts@@ -4,7 +4,7 @@ import {type WorkflowToolEntryPoint,} from "#tools/workflow-definition.js";import { readWorkflowFunctionId } from "#internal/workflow/reference.js";-import { TASK_ID_INPUT } from "#execution/tasks/task-id-input.js";+import { TASK_ID_INPUT, withTaskIdSchema } from "#execution/tasks/task-id-input.js";import { isObject } from "#shared/guards.js";import type { JsonObject } from "#shared/json.js";import { isDisabledToolSentinel } from "#tools/definition.js";@@ -24,8 +24,11 @@ import {} from "#tools/workflow-program-input.js";import {serializeInputSchema,+ serializeModelInputSchema,serializeOutputSchema,+ toInputSchema,type ToolSchemaSource,+ UNSPECIFIED_INPUT_SCHEMA,} from "#tools/schema.js";import { normalizeApproval } from "#internal/authored-definition/approval.js";import { shouldRebindDynamicCallbacks } from "#internal/dynamic-tool-rebind.js";@@ -48,6 +51,8 @@ type NormalizedAuthoredTool = Readonly<readonly hasApproval: boolean;readonly hasExecute: boolean;readonly hasModelOutputProjection: boolean;+ /** The input schema as eve sends it to a model, from the live authored schema. */+ readonly modelInputSchema: JsonObject;readonly workflow?: CompiledWorkflowEntry;readonly workflowProgram?: WorkflowProgramOptions;}@@ -157,6 +162,11 @@ export function normalizeToolDefinition(value: unknown, message: string): NormalhasExecute,hasModelOutputProjection: record.toModelOutput !== undefined,inputSchema,+ modelInputSchema: modelInputSchemaOf(+ record.inputSchema,+ // An agent dispatch runs as a `serve` task, as a `serve` workflow tool does.+ workflow?.entryPoint === "serve" || behavior?.handling?.kind === "dispatch",+ ),};if (behavior !== undefined) {definition.behavior = behavior;@@ -226,6 +236,15 @@ function readCompiledWorkflowEntry(return { entryPoint, workflowId };}+/**+ * Only the live authored schema tells whether eve closes its objects for the+ * model, so the model-facing form is captured while the module is loaded.+ */+function modelInputSchemaOf(source: unknown, serve: boolean): JsonObject {+ const schema = toInputSchema(source as ToolSchemaSource | undefined) ?? UNSPECIFIED_INPUT_SCHEMA;+ return serializeModelInputSchema(serve ? withTaskIdSchema(schema) : schema);+}+/** eve adds `taskId` to a `serve` tool's model input, so the tool's own input can't use it. */function assertNoOwnTaskIdInput(inputSchema: JsonObject | null, message: string): void {const properties = inputSchema?.properties;diff --git a/packages/eve/src/internal/invocation/workflow-execution.test.ts b/packages/eve/src/internal/invocation/workflow-execution.test.tsindex a87d8e397..72954ee72 100644--- a/packages/eve/src/internal/invocation/workflow-execution.test.ts+++ b/packages/eve/src/internal/invocation/workflow-execution.test.ts@@ -1,7 +1,6 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import type { SessionAuthContext } from "#channel/types.js";-import { INTERNAL_CHANNEL_DELIVER } from "#channel/channel-operations.js";import {buildInvocationAttributes,INVOCATION_OWNER_ATTRIBUTE,@@ -30,8 +29,8 @@ const auth: SessionAuthContext = {};const createSession = vi.fn<RouteSessionCreator>();-const deliver = vi.fn();-const from = vi.fn(() => ({ [INTERNAL_CHANNEL_DELIVER]: deliver }) as never);+const respond = vi.fn();+const from = vi.fn(() => ({ respond }) as never);describe("WorkflowAgentInvocationExecution", () => {afterEach(() => {@@ -194,7 +193,7 @@ describe("WorkflowAgentInvocationExecution", () => {} as HandleMessageStreamEvent,];getReadable.mockImplementation(() => eventStream(events));- deliver.mockResolvedValue({ sessionId: "wrun_invocation" });+ respond.mockResolvedValue({ sessionId: "wrun_invocation" });await expect(execution().update({@@ -207,10 +206,7 @@ describe("WorkflowAgentInvocationExecution", () => {type: "success",});expect(from).toHaveBeenCalledWith("invocation:token");- expect(deliver).toHaveBeenCalledWith(- { inputResponses: [{ optionId: "yes", requestId: "question" }] },- { auth },- );+ expect(respond).toHaveBeenCalledWith([{ optionId: "yes", requestId: "question" }], { auth });expect(getReadable).toHaveBeenCalledWith({ startIndex: -64 });});@@ -220,7 +216,7 @@ describe("WorkflowAgentInvocationExecution", () => {getReadable.mockImplementation(() =>eventStream([inputRequestedEvent("event_split", ["one", "two"])]),);- deliver.mockResolvedValue({ sessionId: "wrun_invocation" });+ respond.mockResolvedValue({ sessionId: "wrun_invocation" });const one = invocationInputRequestId("event_split", "one");const two = invocationInputRequestId("event_split", "two");@@ -244,13 +240,11 @@ describe("WorkflowAgentInvocationExecution", () => {],}),).resolves.toMatchObject({ type: "success" });- expect(deliver).toHaveBeenCalledExactlyOnceWith(- {- inputResponses: [- { optionId: "yes", requestId: "one" },- { optionId: "yes", requestId: "two" },- ],- },+ expect(respond).toHaveBeenCalledExactlyOnceWith(+ [+ { optionId: "yes", requestId: "one" },+ { optionId: "yes", requestId: "two" },+ ],expect.objectContaining({ auth }),);});@@ -260,7 +254,7 @@ describe("WorkflowAgentInvocationExecution", () => {runsGet.mockResolvedValue(pendingRun);let events: HandleMessageStreamEvent[] = [inputRequestedEvent("event_first", ["question"])];getReadable.mockImplementation(() => eventStream(events));- deliver.mockResolvedValue({ sessionId: "wrun_invocation" });+ respond.mockResolvedValue({ sessionId: "wrun_invocation" });const firstRequestId = invocationInputRequestId("event_first", "question");await execution().update({@@ -296,7 +290,7 @@ describe("WorkflowAgentInvocationExecution", () => {}),).resolves.toMatchObject({ type: "success" });- expect(deliver).toHaveBeenCalledTimes(2);+ expect(respond).toHaveBeenCalledTimes(2);});it("stops reporting input_required once the answer is resolved", async () => {@@ -330,7 +324,7 @@ describe("WorkflowAgentInvocationExecution", () => {responses: [{ optionId: "yes", requestId }],}),).resolves.toMatchObject({ invocation: { status: "working" }, type: "success" });- expect(deliver).not.toHaveBeenCalled();+ expect(respond).not.toHaveBeenCalled();await expect(execution().update({@@ -346,7 +340,7 @@ describe("WorkflowAgentInvocationExecution", () => {responses: [{ requestId, text: "yes" }],}),).resolves.toMatchObject({ type: "conflict" });- expect(deliver).not.toHaveBeenCalled();+ expect(respond).not.toHaveBeenCalled();});it("acknowledges a repeated answer after the turn completes", async () => {@@ -371,7 +365,7 @@ describe("WorkflowAgentInvocationExecution", () => {invocation: { result: "done", status: "completed" },type: "success",});- expect(deliver).not.toHaveBeenCalled();+ expect(respond).not.toHaveBeenCalled();});it("projects and clears pending connection authorization", async () => {diff --git a/packages/eve/src/internal/invocation/workflow-execution.ts b/packages/eve/src/internal/invocation/workflow-execution.tsindex 15bb24c77..bc5b96461 100644--- a/packages/eve/src/internal/invocation/workflow-execution.ts+++ b/packages/eve/src/internal/invocation/workflow-execution.ts@@ -2,11 +2,7 @@ import type { UserContent } from "ai";import { RunExpiredError, WorkflowRunNotFoundError } from "#compiled/@workflow/errors/index.js";import type { SessionAuthContext } from "#channel/types.js";-import {- INTERNAL_CHANNEL_DELIVER,- type ChannelFrom,- type InternalChannelSource,-} from "#channel/channel-operations.js";+import type { ChannelFrom } from "#channel/channel-operations.js";import { parseNdjsonStream } from "#execution/ndjson-stream.js";import type {AgentInvocation,@@ -23,7 +19,7 @@ import {import type { RouteSessionCreator } from "#internal/nitro/routes/channel-route-context.js";import { getRun, getWorld } from "#internal/workflow/runtime.js";import type { HandleMessageStreamEvent, InputResolution } from "#protocol/message.js";-import type { InputRequest, InputResponse } from "#shared/input.js";+import { type InputRequest, type InputResponse, parseInputResponses } from "#shared/input.js";import type { JsonValue } from "#shared/json.js";import { parseJsonValue } from "#shared/json.js";@@ -121,11 +117,9 @@ export class WorkflowAgentInvocationExecution {const token = run.attributes[INVOCATION_TOKEN_ATTRIBUTE];if (token === undefined) return { type: "not_found" };try {- const source = this.#from(token) as InternalChannelSource;- await source[INTERNAL_CHANNEL_DELIVER](- { inputResponses: deliveredResponses },- { auth: input.auth },- );+ await this.#from(token).respond(parseInputResponses(deliveredResponses), {+ auth: input.auth,+ });} catch (error) {if (RunExpiredError.is(error)) return { type: "not_found" };throw error;diff --git a/packages/eve/src/internal/testing/mocks/mock-channel-operations.ts b/packages/eve/src/internal/testing/mocks/mock-channel-operations.tsindex 20a869e35..1d198c5e1 100644--- a/packages/eve/src/internal/testing/mocks/mock-channel-operations.ts+++ b/packages/eve/src/internal/testing/mocks/mock-channel-operations.ts@@ -4,9 +4,8 @@ import type {ChannelReceiveContext,ChannelRespondOptions,ChannelSendOptions,- InternalChannelSource,+ ChannelSource,} from "#channel/channel-operations.js";-import { INTERNAL_CHANNEL_DELIVER } from "#channel/channel-operations.js";import { type InputResponse, inputResponseSchema } from "#shared/input.js";export type ObservedChannelDelivery<TState> =@@ -24,7 +23,7 @@ export function mockChannelContext<TState = undefined>(): ChannelReceiveContext<TState> {return {from(continuationToken) {- const source: InternalChannelSource<TState> = {+ const source: ChannelSource<TState> = {async send(message, options) {return (await observeDelivery(continuationToken, { ...options, message })) as never;},@@ -46,25 +45,6 @@ export function mockChannelContext<TState = undefined>(async reset() {return { status: "no_active_session" } as never;},- async [INTERNAL_CHANNEL_DELIVER](payload, options) {- const validatedPayload =- payload.inputResponses === undefined- ? payload- : {- ...payload,- inputResponses: inputResponseSchema.array().parse(payload.inputResponses),- };- const optionsState = (options as { readonly state?: Partial<TState> }).state;- const state =- payload.state === undefined- ? optionsState- : { ...optionsState, ...(payload.state as Partial<TState>) };- return (await observeDelivery(continuationToken, {- ...options,- ...validatedPayload,- state,- } as ObservedChannelDelivery<TState>)) as never;- },};return source;},diff --git a/packages/eve/src/protocol/message.ts b/packages/eve/src/protocol/message.tsindex 928b70760..a4e5a892d 100644--- a/packages/eve/src/protocol/message.ts+++ b/packages/eve/src/protocol/message.ts@@ -418,14 +418,24 @@ export interface TaskStartedStreamEvent {/*** Stream event emitted once when a task's call settles: by the run's return- * or failure, or by a cancel. `turnId` is the call's turn, the same as on its- * `task.started`.+ * or failure, or by a cancel. `turnId`, `name`, and `kind` are the same as on+ * the call's `task.started`.*/export interface TaskSettledStreamEvent {data: {callId: string;/** Why the call failed; present only when `status` is `"failed"`. */error?: { message: string };+ /**+ * The task's kind, as on `task.started`. Absent on events recorded by eve+ * versions before it was added.+ */+ kind?: TaskStartedStreamEvent["data"]["kind"];+ /**+ * The tool whose call started the task, as on `task.started`. Absent on+ * events recorded by eve versions before it was added.+ */+ name?: string;/** The call's result; present only when `status` is `"completed"`. */output?: JsonValue;status: "completed" | "failed" | "cancelled";@@ -1405,10 +1415,12 @@ export function createTaskStartedEvent(/** Creates the `task.settled` event for one settled task call. */export function createTaskSettledEvent(- input: TaskSettledStreamEvent["data"],+ input: TaskSettledStreamEvent["data"] & Pick<TaskStartedStreamEvent["data"], "kind" | "name">,): TaskSettledStreamEvent {const data: TaskSettledStreamEvent["data"] = {callId: input.callId,+ kind: input.kind,+ name: input.name,status: input.status,taskId: input.taskId,turnId: input.turnId,diff --git a/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.test.ts b/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.test.tsindex 2a0ac75ec..52c311729 100644--- a/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.test.ts+++ b/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.test.ts@@ -142,6 +142,14 @@ async function firePost(return { cancel, response, send, waitUntil };}+function bridgeSendTypeChecks(bridge: ReturnType<typeof chatSdkChannel>, thread: Thread): void {+ // @ts-expect-error bridge.send takes a message; answer input with bridge.respond.+ void bridge.send({ inputResponses: [{ optionId: "approve", requestId: "r1" }] }, { thread });+ void bridge.send("hello", { context: ["extra"], outputSchema: { type: "object" }, thread });+}++void bridgeSendTypeChecks;+describe("chatSdkChannel", () => {it.each([[{ isDM: true, channelVisibility: "unknown" }, "private"],@@ -300,7 +308,7 @@ describe("chatSdkChannel", () => {});});- it("does not cancel for a steering response without a message", async () => {+ it("answers pending input through bridge.respond without cancelling", async () => {const bridge = chatSdkChannel({adapters: { test: testAdapter() },concurrency: "concurrent",@@ -310,10 +318,7 @@ describe("chatSdkChannel", () => {});bridge.bot.onNewMention(async (thread: Thread) => {- await bridge.send(- { inputResponses: [{ optionId: "approve", requestId: "request-1" }] },- { thread, turnPolicy: "steer" },- );+ await bridge.respond([{ optionId: "approve", requestId: "request-1" }], { thread });});const { cancel, response, send } = await firePost(bridge.channel, "/eve/v1/test", {@@ -785,12 +790,6 @@ describe("chatSdkChannel", () => {expect(send).toHaveBeenCalledWith(THREAD_ID, {auth: null,inputResponses: [{ optionId: "approve", requestId: "request-1" }],- state: {- thread: expect.objectContaining({- adapterName: "test",- id: THREAD_ID,- }),- },});});});diff --git a/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.ts b/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.tsindex fbb3d1ca8..0f427daac 100644--- a/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.ts+++ b/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.ts@@ -1,38 +1,31 @@import type { UserContent } from "ai";-import type { ChannelAddressDeliveryOptions } from "#channel/channel-address.js";-import {- INTERNAL_CHANNEL_DELIVER,- type ChannelFrom,- type InternalChannelSource,+import type {+ ChannelFrom,+ ChannelRespondOptions,+ ChannelSendOptions,} from "#channel/channel-operations.js";-import { normalizeSendInput } from "#channel/send-input.js";-import type { SendPayload } from "#channel/routes.js";import type { SessionAuthContext, TurnPolicy } from "#channel/types.js";import { ContextContainer, contextStorage } from "#context/container.js";import { ContextKey } from "#context/key.js";import { createLogger, extractErrorId, formatErrorHint } from "#internal/logging.js";import type { UnstampedMessageStreamEvent } from "#protocol/message.js";-import type { InputRequest } from "#shared/input.js";+import {+ type InputResponse,+ parseInputResponses,+ type StrictInputResponses,+} from "#shared/input.js";import type {ActionEvent,Adapter,- CardChild,ChatConfig,SerializedThread,Thread,WebhookOptions,} from "#compiled/chat/index.js";-import {- Actions,- Button,- Card,- CardText,- Chat,- Message,- ThreadImpl,-} from "#compiled/chat/index.js";+import { Chat, Message, ThreadImpl } from "#compiled/chat/index.js";import { defaultAuthorizationEvents } from "#public/channels/chat-sdk/authorization.js";+import { decodeInputAction, renderInputRequests } from "#public/channels/chat-sdk/input-actions.js";import { isNotImplemented } from "#public/channels/chat-sdk/notImplemented.js";import {defineChannel,@@ -54,12 +47,6 @@ const MAX_TYPING_STATUS = 80;const streamTextByState = new WeakMap<ChatSdkChannelState, string>();type ChatSdkAdapters = Record<string, Adapter>;-type ChatSdkSendInput = string | UserContent | SendPayload;-type MutableDeliveryOptions<TState> = {- -readonly [- Key in keyof ChannelAddressDeliveryOptions<TState>- ]: ChannelAddressDeliveryOptions<TState>[Key];-};type EventData<T extends UnstampedMessageStreamEvent["type"]> =Extract<UnstampedMessageStreamEvent, { type: T }> extends { data: infer D } ? D : undefined;@@ -136,17 +123,10 @@ export interface ChatSdkEventContext<TAdapters extends ChatSdkAdapters = ChatSdkexport type ChatSdkChannelEvents<TAdapters extends ChatSdkAdapters = ChatSdkAdapters> =ChannelEvents<ChatSdkChannelContext<TAdapters>>;-/** The thread determines the eve continuation token and persisted channel state. */-export interface ChatSdkSendOptions {+/** Selects the Chat SDK thread that owns the eve continuation token. */+interface ChatSdkThreadOptions {readonly auth?: SessionAuthContext | null;- readonly callback?: ChannelAddressDeliveryOptions<ChatSdkChannelState>["callback"];readonly thread: SerializedThread | Thread | string;- readonly title?: string;- /**- * Controls how this input interacts with an active eve turn on the same- * thread. Defaults to `"steer"`.- */- readonly turnPolicy?: TurnPolicy;/*** Required when `thread` is a string that does not include the Chat SDK* adapter prefix. Prefer passing the `Thread` object from the Chat SDK handler@@ -155,6 +135,22 @@ export interface ChatSdkSendOptions {readonly adapterName?: string;}+/**+ * Options for `bridge.send`: channel send options plus the thread. The thread+ * determines the eve continuation token and persisted channel state.+ */+export interface ChatSdkSendOptions extends ChatSdkThreadOptions, Omit<ChannelSendOptions, "auth"> {+ /**+ * Controls how this input interacts with an active eve turn on the same+ * thread. Defaults to the channel's `turnPolicy`, then `"steer"`.+ */+ readonly turnPolicy?: TurnPolicy;+}++/** Options for `bridge.respond`: channel respond options plus the thread. */+export interface ChatSdkRespondOptions+ extends ChatSdkThreadOptions, Omit<ChannelRespondOptions, "auth" | "state"> {}+/*** Configuration for {@link chatSdkChannel}. It accepts normal Chat SDK* `ChatConfig` fields, plus eve route and event settings.@@ -227,7 +223,15 @@ export interface ChatSdkChannelBridge<TAdapters extends ChatSdkAdapters = ChatSd* Use `channel.receive(...)` for proactive sends that are not handling an* inbound Chat SDK webhook.*/- send(input: ChatSdkSendInput, options: ChatSdkSendOptions): Promise<Session>;+ send(message: string | UserContent, options: ChatSdkSendOptions): Promise<Session>;+ /**+ * Answers pending input requests on the thread's session from inside a Chat+ * SDK webhook handler. Never creates a session.+ */+ respond<const TResponses extends readonly InputResponse[]>(+ inputResponses: StrictInputResponses<TResponses>,+ options: ChatSdkRespondOptions,+ ): Promise<Session>;}/**@@ -271,14 +275,10 @@ export function chatSdkChannel<TAdapters extends ChatSdkAdapters>("chatSdkChannel input actions require a thread on the Chat SDK action event.",);}- await bridgeSend(- bot,- { inputResponses: [response] },- {- auth: config.resolveInputAuth ? await config.resolveInputAuth(event) : null,- thread: event.thread.toJSON(),- },- );+ await bridgeRespond(bot, [response], {+ auth: config.resolveInputAuth ? await config.resolveInputAuth(event) : null,+ thread: event.thread.toJSON(),+ });});const channel = defineChannel<@@ -336,8 +336,11 @@ export function chatSdkChannel<TAdapters extends ChatSdkAdapters>(return {bot,channel,- send(input, options) {- return bridgeSend(bot, input, options);+ send(message, options) {+ return bridgeSend(bot, message, options);+ },+ respond(inputResponses, options) {+ return bridgeRespond(bot, inputResponses, options);},};}@@ -511,35 +514,6 @@ function truncate(text: string, max = MAX_TYPING_STATUS): string {return text.length <= max ? text : `${text.slice(0, max - 1)}\u2026`;}-function renderInputRequests(requests: readonly InputRequest[], inputActionPrefix: string) {- return Card({- children: requests.flatMap((request) => renderInputRequest(request, inputActionPrefix)),- });-}--function renderInputRequest(request: InputRequest, inputActionPrefix: string) {- const children: CardChild[] = [CardText(request.prompt)];- if (request.options && request.options.length > 0) {- children.push(- Actions(- request.options.map((option) =>- Button({- id: encodeInputAction(inputActionPrefix, request.requestId, option.id),- label: option.label,- style: option.style,- value: option.id,- }),- ),- ),- );- return children;- }- children.push(- CardText("This request needs a freeform answer. Continue from the eve session UI."),- );- return children;-}-async function postFailure(thread: Thread | null,prefix: string,@@ -559,26 +533,41 @@ async function postFailure(async function bridgeSend<TAdapters extends ChatSdkAdapters>(bot: Chat<TAdapters>,- input: ChatSdkSendInput,+ message: string | UserContent,options: ChatSdkSendOptions,): Promise<Session> {+ const from = activeFrom("send");+ const { adapterName, auth, thread: threadInput, ...sendOptions } = options;+ const thread = serializeThread(bot, threadInput, adapterName);+ return from(thread.id).send(message, {+ ...sendOptions,+ auth: auth ?? null,+ state: { thread },+ });+}++async function bridgeRespond<TAdapters extends ChatSdkAdapters>(+ bot: Chat<TAdapters>,+ inputResponses: readonly InputResponse[],+ options: ChatSdkRespondOptions,+): Promise<Session> {+ const from = activeFrom("respond");+ const { adapterName, auth, thread: threadInput, ...respondOptions } = options;+ const thread = serializeThread(bot, threadInput, adapterName);+ return from(thread.id).respond(parseInputResponses(inputResponses), {+ ...respondOptions,+ auth: auth ?? null,+ });+}++function activeFrom(operation: "respond" | "send"): ChannelFrom<ChatSdkChannelState> {const active = contextStorage.getStore()?.get(ActiveWebhookKey);if (!active) {throw new Error(- "chatSdkChannel().send can only run during a Chat SDK webhook handler for this bridge.",+ `chatSdkChannel().${operation} can only run during a Chat SDK webhook handler for this bridge.`,);}- const thread = serializeThread(bot, options.thread, options.adapterName);- const payload = normalizeSendInput(input);- const deliveryOptions: MutableDeliveryOptions<ChatSdkChannelState> = {- auth: options.auth ?? null,- state: { thread },- };- if (options.callback !== undefined) deliveryOptions.callback = options.callback;- if (options.title !== undefined) deliveryOptions.title = options.title;- if (options.turnPolicy !== undefined) deliveryOptions.turnPolicy = options.turnPolicy;- const source = active.from(thread.id) as InternalChannelSource<ChatSdkChannelState>;- return source[INTERNAL_CHANNEL_DELIVER](payload, deliveryOptions);+ return active.from;}function initialState(): ChatSdkChannelState {@@ -668,25 +657,3 @@ function routeForAdapter<TAdapters extends ChatSdkAdapters>(const route = config.route ?? DEFAULT_ROUTE;return `${route.replace(/\/$/u, "")}/${adapterName}`;}--function encodeInputAction(prefix: string, requestId: string, optionId: string): string {- return `${prefix}${encodeURIComponent(requestId)}:${encodeURIComponent(optionId)}`;-}--function decodeInputAction(- actionId: string,- prefix: string,- value: string | undefined,-): { optionId: string; requestId: string } | null {- if (!actionId.startsWith(prefix)) return null;- const encoded = actionId.slice(prefix.length);- const separator = encoded.indexOf(":");- if (separator <= 0) return null;- try {- const requestId = decodeURIComponent(encoded.slice(0, separator));- const optionId = value ?? decodeURIComponent(encoded.slice(separator + 1));- return { optionId, requestId };- } catch {- return null;- }-}diff --git a/packages/eve/src/public/channels/chat-sdk/index.ts b/packages/eve/src/public/channels/chat-sdk/index.tsindex 2d397cc6a..4895e2102 100644--- a/packages/eve/src/public/channels/chat-sdk/index.ts+++ b/packages/eve/src/public/channels/chat-sdk/index.ts@@ -9,6 +9,7 @@ export {type ChatSdkEventContext,type ChatSdkInstrumentationMetadata,type ChatSdkReceiveTarget,+ type ChatSdkRespondOptions,type ChatSdkSendOptions,} from "#public/channels/chat-sdk/chatSdkChannel.js";export { messageToUserContent } from "#public/channels/chat-sdk/messageToUserContent.js";diff --git a/packages/eve/src/public/channels/chat-sdk/input-actions.ts b/packages/eve/src/public/channels/chat-sdk/input-actions.tsnew file mode 100644index 000000000..0708fb903--- /dev/null+++ b/packages/eve/src/public/channels/chat-sdk/input-actions.ts@@ -0,0 +1,56 @@+import type { InputRequest } from "#shared/input.js";+import type { CardChild } from "#compiled/chat/index.js";+import { Actions, Button, Card, CardText } from "#compiled/chat/index.js";++/** Renders pending input requests as a Chat SDK card with one button per option. */+export function renderInputRequests(requests: readonly InputRequest[], inputActionPrefix: string) {+ return Card({+ children: requests.flatMap((request) => renderInputRequest(request, inputActionPrefix)),+ });+}++function renderInputRequest(request: InputRequest, inputActionPrefix: string) {+ const children: CardChild[] = [CardText(request.prompt)];+ if (request.options && request.options.length > 0) {+ children.push(+ Actions(+ request.options.map((option) =>+ Button({+ id: encodeInputAction(inputActionPrefix, request.requestId, option.id),+ label: option.label,+ style: option.style,+ value: option.id,+ }),+ ),+ ),+ );+ return children;+ }+ children.push(+ CardText("This request needs a freeform answer. Continue from the eve session UI."),+ );+ return children;+}++function encodeInputAction(prefix: string, requestId: string, optionId: string): string {+ return `${prefix}${encodeURIComponent(requestId)}:${encodeURIComponent(optionId)}`;+}++/** Decodes a default eve HITL button action back into an input response. */+export function decodeInputAction(+ actionId: string,+ prefix: string,+ value: string | undefined,+): { optionId: string; requestId: string } | null {+ if (!actionId.startsWith(prefix)) return null;+ const encoded = actionId.slice(prefix.length);+ const separator = encoded.indexOf(":");+ if (separator <= 0) return null;+ try {+ const requestId = decodeURIComponent(encoded.slice(0, separator));+ const optionId = value ?? decodeURIComponent(encoded.slice(separator + 1));+ return { optionId, requestId };+ } catch {+ return null;+ }+}diff --git a/packages/eve/src/public/channels/linq/linqChannel.test.ts b/packages/eve/src/public/channels/linq/linqChannel.test.tsindex a3c3fd240..de1f1b919 100644--- a/packages/eve/src/public/channels/linq/linqChannel.test.ts+++ b/packages/eve/src/public/channels/linq/linqChannel.test.ts@@ -59,21 +59,19 @@ describe("linqChannel", () => {await handler(thread, message);expect(markRead).toHaveBeenCalledWith(thread.id, message.id);- expect(send).toHaveBeenCalledWith(- { context: [], message: "Hello Linq" },- {- auth: {- attributes: { user_name: "user" },- authenticator: "linq-message",- issuer: "linq",- principalId: "linq:user",- principalType: "user",- subject: "user",- },- thread,- title: undefined,+ expect(send).toHaveBeenCalledWith("Hello Linq", {+ auth: {+ attributes: { user_name: "user" },+ authenticator: "linq-message",+ issuer: "linq",+ principalId: "linq:user",+ principalType: "user",+ subject: "user",},- );+ context: [],+ thread,+ title: undefined,+ });});it("uses lazy credentials and the managed credential verifier", async () => {diff --git a/packages/eve/src/public/channels/linq/linqChannel.ts b/packages/eve/src/public/channels/linq/linqChannel.tsindex 297bda8af..f5e0efd8a 100644--- a/packages/eve/src/public/channels/linq/linqChannel.ts+++ b/packages/eve/src/public/channels/linq/linqChannel.ts@@ -182,10 +182,12 @@ async function dispatchMessage(await markReadBestEffort(bridge.bot.getAdapter("linq"), thread, message);const content = linqInboundContent(message);if (content === undefined) return;- await bridge.send(- { context: [...(result.context ?? [])], message: content },- { auth: result.auth, thread, title: result.title },- );+ await bridge.send(content, {+ auth: result.auth,+ context: [...(result.context ?? [])],+ thread,+ title: result.title,+ });}async function markReadBestEffort(diff --git a/packages/eve/src/public/channels/photon/photonIMessageChannel.test.ts b/packages/eve/src/public/channels/photon/photonIMessageChannel.test.tsindex a45573e38..6bb76ce94 100644--- a/packages/eve/src/public/channels/photon/photonIMessageChannel.test.ts+++ b/packages/eve/src/public/channels/photon/photonIMessageChannel.test.ts@@ -55,10 +55,12 @@ describe("photonIMessageChannel", () => {await handler(thread, message);- expect(send).toHaveBeenCalledWith(- { context: [], message: "Steer this response" },- { auth: null, thread, title: "Photon run" },- );+ expect(send).toHaveBeenCalledWith("Steer this response", {+ auth: null,+ context: [],+ thread,+ title: "Photon run",+ });});it("derives user auth for default direct-message dispatch", async () => {@@ -81,21 +83,19 @@ describe("photonIMessageChannel", () => {await handler(thread, message);- expect(send).toHaveBeenCalledWith(- { context: [], message: "Hello Photon" },- {- auth: {- attributes: { user_name: "user" },- authenticator: "photon-imessage",- issuer: "photon",- principalId: "photon:user",- principalType: "user",- subject: "user",- },- thread,- title: undefined,+ expect(send).toHaveBeenCalledWith("Hello Photon", {+ auth: {+ attributes: { user_name: "user" },+ authenticator: "photon-imessage",+ issuer: "photon",+ principalId: "photon:user",+ principalType: "user",+ subject: "user",},- );+ context: [],+ thread,+ title: undefined,+ });});it("drops blank inbound messages without cancelling or sending", async () => {@@ -144,20 +144,18 @@ describe("photonIMessageChannel", () => {expect(pattern.test(message.text)).toBe(true);await handler(thread, message);- expect(send).toHaveBeenCalledWith(- { context: [], message: "Hello group" },- {- auth: {- attributes: { user_name: "user" },- authenticator: "photon-imessage",- issuer: "photon",- principalId: "photon:user",- principalType: "user",- subject: "user",- },- thread,- title: undefined,+ expect(send).toHaveBeenCalledWith("Hello group", {+ auth: {+ attributes: { user_name: "user" },+ authenticator: "photon-imessage",+ issuer: "photon",+ principalId: "photon:user",+ principalType: "user",+ subject: "user",},- );+ context: [],+ thread,+ title: undefined,+ });});});diff --git a/packages/eve/src/public/channels/photon/photonIMessageChannel.ts b/packages/eve/src/public/channels/photon/photonIMessageChannel.tsindex ddc63f866..3955433e1 100644--- a/packages/eve/src/public/channels/photon/photonIMessageChannel.ts+++ b/packages/eve/src/public/channels/photon/photonIMessageChannel.ts@@ -139,13 +139,12 @@ async function dispatchMessage(await markReadBestEffort(bridge.bot.getAdapter("imessage"), thread, message);const content = photonInboundContent(message);if (content === undefined) return;- await bridge.send(- {- context: [...(result.context ?? [])],- message: content,- },- { auth: result.auth, thread, title: result.title },- );+ await bridge.send(content, {+ auth: result.auth,+ context: [...(result.context ?? [])],+ thread,+ title: result.title,+ });}async function markReadBestEffort(diff --git a/packages/eve/src/public/channels/slack/hitl.test.ts b/packages/eve/src/public/channels/slack/hitl.test.tsindex 107a3b9eb..621a3a09a 100644--- a/packages/eve/src/public/channels/slack/hitl.test.ts+++ b/packages/eve/src/public/channels/slack/hitl.test.ts@@ -6,17 +6,19 @@ import {buildFreeformModalView,decodeFreeformHitlActionId,decodeHitlActionId,- deriveHitlResponse,formatInputRequestFallbackText,- HITL_ACTION_PREFIX,HITL_FREEFORM_ACTION_PREFIX,HITL_FREEFORM_MODAL_ACTION_ID,HITL_FREEFORM_MODAL_BLOCK_ID,HITL_FREEFORM_MODAL_CALLBACK_ID,isFreeformAction,isHitlAction,- renderInputRequestBlocks,} from "#public/channels/slack/hitl.js";+import {+ deriveHitlResponse,+ HITL_ACTION_PREFIX,+ renderInputRequestBlocks,+} from "#public/channels/slack/index.js";import {SLACK_CARD_BODY_TEXT_MAX_LENGTH,SLACK_SECTION_TEXT_MAX_LENGTH,diff --git a/packages/eve/src/public/channels/slack/hitl.ts b/packages/eve/src/public/channels/slack/hitl.tsindex 33f526f0b..ae70a87c3 100644--- a/packages/eve/src/public/channels/slack/hitl.ts+++ b/packages/eve/src/public/channels/slack/hitl.ts@@ -19,8 +19,10 @@ import {truncatePlainText,truncateSectionText,} from "#public/channels/slack/limits.js";+import type { BlockKitBlock } from "#public/channels/slack/blocks.js";import {type InputRequest,+ type InputResponse,parseInputResponse,type ValidatedInputResponse,} from "#shared/input.js";@@ -60,6 +62,7 @@ export const HITL_FREEFORM_MODAL_ACTION_ID = "eve_freeform_text";const HITL_ROUTE_PREFIX = `${HITL_ACTION_PREFIX}route:`;+/** Slack thread a routed HITL widget answers back to. */export interface SlackHitlRoute {readonly channelId: string;readonly threadTs: string;@@ -85,7 +88,7 @@ type CardButtonOption = Pick<InputRequestOption, "id" | "label" | "style">;* Subset of one Slack interactivity action the HITL decoder reads.* Mirrors the relevant fields of `SlackInteractionAction`.*/-interface SlackHitlAction {+export interface SlackHitlAction {readonly actionId: string;/** `value` field on Slack `button` payloads. */readonly value?: string;@@ -95,13 +98,18 @@ interface SlackHitlAction {/*** Resolved HITL response derived from one Slack interactivity action.- * Slack-local classification stays beside the typed eve input response so+ * Slack-local classification stays beside the eve input response so* presentation metadata cannot cross the durable session-inbox boundary.*/-interface DerivedHitlResponse {- kind?: "tool-approval";- response: ValidatedInputResponse;- route?: SlackHitlRoute;+export interface DerivedHitlResponse {+ readonly kind?: "tool-approval";+ readonly response: InputResponse;+ readonly route?: SlackHitlRoute;+}++/** A derived response whose input response already passed schema validation. */+interface ValidatedHitlResponse extends DerivedHitlResponse {+ readonly response: ValidatedInputResponse;}interface DecodedHitlActionId {@@ -112,20 +120,25 @@ interface DecodedHitlActionId {}/**- * Decodes one Slack interactivity action into an HITL response, or- * returns `null` when the action does not match an HITL widget the- * framework rendered.+ * Decodes one Slack interactivity action on a widget from+ * {@link renderInputRequestBlocks} into an HITL response, or returns `null`+ * when the action does not match an HITL widget eve rendered.*/-export function deriveHitlResponse(action: SlackHitlAction): DerivedHitlResponse | null {- if (!action.actionId.startsWith(HITL_ACTION_PREFIX)) return null;+export const deriveHitlResponse: (action: SlackHitlAction) => DerivedHitlResponse | null = (+ action,+) => decodeHitlResponse(action);+/** {@link deriveHitlResponse}, keeping the validated type `respond()` accepts. */+export function decodeHitlResponse(action: SlackHitlAction): ValidatedHitlResponse | null {const decoded = decodeHitlActionId(action.actionId);if (decoded === null) return null;const optionId = action.selectedOptionValue ?? action.value;if (optionId === undefined || (action.value !== undefined && !decoded.button)) return null;- const derived: DerivedHitlResponse = {- response: parseInputResponse({ optionId, requestId: decoded.requestId }),- };+ const derived: {+ kind?: "tool-approval";+ response: ValidatedInputResponse;+ route?: SlackHitlRoute;+ } = { response: parseInputResponse({ optionId, requestId: decoded.requestId }) };if (decoded.kind !== undefined) derived.kind = decoded.kind;if (decoded.route !== undefined) derived.route = decoded.route;return derived;@@ -184,7 +197,8 @@ function encodeHitlActionId(request: InputRequest, route?: SlackHitlRoute): stri}/**- * Renders one `InputRequest` as Block Kit blocks:+ * Renders one `InputRequest` as Block Kit blocks. Clicks on the rendered+ * widgets decode with {@link deriveHitlResponse}:** - `display === "select"` with ≤ {@link RADIO_SELECT_OPTION_LIMIT}* options → `radio_buttons`. Single-click answer, options stay@@ -201,7 +215,10 @@ function encodeHitlActionId(request: InputRequest, route?: SlackHitlRoute): stri** Always emits at least the prompt section.*/-export function renderInputRequestBlocks(request: InputRequest, route?: SlackHitlRoute): unknown[] {+export function renderInputRequestBlocks(+ request: InputRequest,+ route?: SlackHitlRoute,+): BlockKitBlock[] {const prompt = {text: { text: truncateSectionText(request.prompt), type: "mrkdwn" },type: "section",@@ -476,7 +493,7 @@ export function buildAnsweredBlocks(input: {return blocks;}-function renderInputRequestDetailBlocks(request: InputRequest): unknown[] {+function renderInputRequestDetailBlocks(request: InputRequest): BlockKitBlock[] {const details = formatToolInputDetails(request);return details === undefined? []diff --git a/packages/eve/src/public/channels/slack/index.ts b/packages/eve/src/public/channels/slack/index.tsindex 69ef2c6b0..22ad41bef 100644--- a/packages/eve/src/public/channels/slack/index.ts+++ b/packages/eve/src/public/channels/slack/index.ts@@ -104,6 +104,15 @@ export {type BlockKitBlock,} from "#public/channels/slack/blocks.js";+export {+ deriveHitlResponse,+ HITL_ACTION_PREFIX,+ renderInputRequestBlocks,+ type DerivedHitlResponse,+ type SlackHitlAction,+ type SlackHitlRoute,+} from "#public/channels/slack/hitl.js";+/*** Card builders and element types re-exported from the vendored chat* SDK module. These are pure data factories. They return plain typeddiff --git a/packages/eve/src/public/channels/slack/interactions.ts b/packages/eve/src/public/channels/slack/interactions.tsindex 6b9c6f2e3..d9c658b5d 100644--- a/packages/eve/src/public/channels/slack/interactions.ts+++ b/packages/eve/src/public/channels/slack/interactions.ts@@ -26,7 +26,7 @@ import { buildSlackAuthContext } from "#public/channels/slack/auth.js";import {buildFreeformModalView,decodeFreeformHitlActionId,- deriveHitlResponse,+ decodeHitlResponse,HITL_FREEFORM_MODAL_ACTION_ID,HITL_FREEFORM_MODAL_BLOCK_ID,HITL_FREEFORM_MODAL_CALLBACK_ID,@@ -302,7 +302,7 @@ export async function handleInteractionPost(}const hitlActions = interaction.actions.flatMap((action) => {- const derived = deriveHitlResponse(action);+ const derived = decodeHitlResponse(action);return derived === null ? [] : [{ action, derived }];});@@ -503,7 +503,7 @@ async function dispatchBlockInputResponses(input: {}if (- input.submission.actions.some((action) => deriveHitlResponse(action)?.kind === "tool-approval")+ input.submission.actions.some((action) => decodeHitlResponse(action)?.kind === "tool-approval")) {return;}diff --git a/packages/eve/src/public/channels/slack/session-operations.ts b/packages/eve/src/public/channels/slack/session-operations.tsindex 15488b579..634dd48b0 100644--- a/packages/eve/src/public/channels/slack/session-operations.ts+++ b/packages/eve/src/public/channels/slack/session-operations.ts@@ -1,11 +1,9 @@-import {- INTERNAL_CHANNEL_DELIVER,- type ChannelFrom,- type ChannelResolveSession,- type ChannelRespondOptions,- type ChannelSendOptions,- type ChannelSource,- type InternalChannelSource,+import type {+ ChannelFrom,+ ChannelResolveSession,+ ChannelRespondOptions,+ ChannelSendOptions,+ ChannelSource,} from "#channel/channel-operations.js";import type { SessionAuthContext } from "#channel/types.js";import type { InputResponse, StrictInputResponses } from "#shared/input.js";@@ -46,13 +44,13 @@ export function bindSlackSessionOperations(input: {readonly resolveSession: ChannelResolveSession;readonly state: SlackChannelState;}): SlackSessionOperations {- const source = input.from(input.address) as InternalChannelSource<SlackChannelState>;+ const source = input.from(input.address);const auth = (value: SessionAuthContext | null | undefined) =>value === undefined ? input.defaultAuth : value;return {async send(message, options = {}) {- return await sendAsSlackUser(source, message, {+ return await source.send(message, {...options,auth: auth(options.auth),state: input.state,@@ -83,25 +81,6 @@ export function bindSlackSessionOperations(input: {};}-/**- * Sends a message and stamps its Slack author on the payload, so `deliver` can- * map a custom-auth principal to the Slack user who wrote the message.- */-export async function sendAsSlackUser(- source: InternalChannelSource<SlackChannelState>,- message: string | UserContent,- options: ChannelSendOptions<SlackChannelState>,-): ReturnType<SlackSource["send"]> {- return await source[INTERNAL_CHANNEL_DELIVER](- {- context: options.context,- message,- state: { triggeringUserId: options.state?.triggeringUserId ?? null },- },- options,- );-}-/*** Stamps the verified Slack user behind an input response, so `deliver` can map* a custom-auth responder's principal to them. The verified user wins over anydiff --git a/packages/eve/src/public/channels/slack/slackChannel.test.ts b/packages/eve/src/public/channels/slack/slackChannel.test.tsindex b208dcd91..6bb0c8658 100644--- a/packages/eve/src/public/channels/slack/slackChannel.test.ts+++ b/packages/eve/src/public/channels/slack/slackChannel.test.ts@@ -522,6 +522,18 @@ describe("slackChannel()", () => {});});+ it("keeps build metadata when spread with replaced routes", () => {+ const channel = slackChannel({ botName: "Support Bot" });+ const wrapped = { ...channel, routes: [...channel.routes] };++ expect(getChannelBuildMetadata(wrapped, "support")).toEqual(+ getChannelBuildMetadata(channel, "support"),+ );+ expect(getChannelBuildMetadata(wrapped, "support")?.manifest).toMatchObject({+ display_information: { name: "Support Bot" },+ });+ });+it("classifies from durable state through the audience hook", () => {const adapter = withState(getAdapter(slackChannel()), { audience: "private" });@@ -1346,7 +1358,8 @@ describe("slackChannel() default event handlers", () => {}),);- await adapter.deliver!({ message: "hello" }, ctx);+ // Slack-derived auth wins over the author stamped in delivery state.+ await adapter.deliver!({ message: "hello", state: { triggeringUserId: "U_OTHER" } }, ctx);expect(ctx.state.slackUsersByPrincipal).toEqual({ "slack:T01:U_ALICE": "U_ALICE" });});@@ -2088,6 +2101,57 @@ describe("slackChannel() inbound mention pipeline", () => {});});+ it("routes every inbound message through a route wrapper's from(address).send", async () => {+ const channel = asCompiled<SlackChannelState>(+ slackChannel({+ credentials: { botToken: "xoxb-test" },+ onAppMention: () => ({ auth: null }),+ onDirectMessage: () => ({ auth: null }),+ }),+ );+ const seen: string[] = [];+ const failures: unknown[] = [];+ const wrapped = {+ ...channel,+ routes: channel.routes.map((route) =>+ isHttpRouteDefinition(route)+ ? {+ ...route,+ handler: (request: Request, args: Parameters<typeof route.handler>[1]) =>+ route.handler(request, {+ ...args,+ from: (address) => {+ const source = args.from(address);+ return {+ ...source,+ async send(message, options) {+ seen.push(address);+ try {+ return await source.send(message, options);+ } catch (error) {+ failures.push(error);+ throw error;+ }+ },+ };+ },+ }),+ }+ : route,+ ),+ };+ const rejection = new Error("delivery rejected");+ const send = vi.fn().mockResolvedValueOnce({ id: "s1" }).mockRejectedValueOnce(rejection);++ const mention = buildMentionBody({ channel: "C_WRAP" });+ await firePost(wrapped, buildSignedRequest({ body: mention.body }), { send });+ const dm = buildDirectMessageBody({ channel: "D_WRAP" });+ await firePost(wrapped, buildSignedRequest({ body: dm.body }), { send });++ expect(seen).toEqual([`C_WRAP:${mention.ts}`, `D_WRAP:${dm.ts}`]);+ expect(failures).toEqual([rejection]);+ });+it("uses the app installation workspace for mention credentials", async () => {const botToken = vi.fn((_context: { readonly teamId?: string }) => "xoxb-test");const channel = slackChannel({@@ -2173,6 +2237,7 @@ describe("slackChannel() inbound mention pipeline", () => {const { body } = buildMentionBody({channel: "C_BOUND",threadTs: "1700000000.000300",+ ts: "1700000000.000005",});const { send } = await firePost(channel, buildSignedRequest({ body }));diff --git a/packages/eve/src/public/channels/slack/slackChannel.ts b/packages/eve/src/public/channels/slack/slackChannel.tsindex 81adfabe0..d6979e3bc 100644--- a/packages/eve/src/public/channels/slack/slackChannel.ts+++ b/packages/eve/src/public/channels/slack/slackChannel.ts@@ -5,7 +5,6 @@ import type {ChannelFrom,ChannelResolveSession,ChannelSource,- InternalChannelSource,} from "#channel/channel-operations.js";import { defaultDeliverResult } from "#channel/adapter.js";import type { Session, SessionHandle } from "#channel/session.js";@@ -86,7 +85,6 @@ import { defineSlackAppManifest } from "#public/channels/slack/app-manifest.js";import { handleInteractionPost } from "#public/channels/slack/interactions.js";import {bindSlackSessionOperations,- sendAsSlackUser,withSlackResponder,type SlackSendOptions,type SlackSessionOperations,@@ -875,10 +873,6 @@ export function slackChannel(config: SlackChannelConfig = {}): SlackChannel {// The runtime hands `deliver` the full adapter context; `session.auth.current`// is the caller of this delivery.deliver(payload, channel: SlackChannelContext & { readonly session: SessionHandle }) {- const cards = payload.pendingApprovalCards;- if (typeof cards === "object" && cards !== null) {- channel.state.pendingApprovalCards = { ...channel.state.pendingApprovalCards, ...cards };- }recordSlackPrincipal(channel.state, channel.session.auth.current, payload);return defaultDeliverResult(payload);},@@ -1022,10 +1016,9 @@ async function receiveOnSlack(state.audience = audience;}- const source = deps.from(- slackContinuationToken(channelId, continuationThreadTs),- ) as InternalChannelSource<SlackChannelState>;- return sendAsSlackUser(source, input.message, { auth: input.auth, state, title: input.title });+ return deps+ .from(slackContinuationToken(channelId, continuationThreadTs))+ .send(input.message, { auth: input.auth, state, title: input.title });}function shouldDropSlackHttpTimeoutRetry(headers: Headers): boolean {diff --git a/packages/eve/src/public/channels/slack/task-card.test.ts b/packages/eve/src/public/channels/slack/task-card.test.tsindex ceed2eaa2..27374a620 100644--- a/packages/eve/src/public/channels/slack/task-card.test.ts+++ b/packages/eve/src/public/channels/slack/task-card.test.ts@@ -133,6 +133,8 @@ const TWO_TASKS_STARTED: readonly UnstampedMessageStreamEvent[] = [const BOTH_TASKS_SETTLED: readonly UnstampedMessageStreamEvent[] = [createTaskSettledEvent({callId: DEPLOY_CALL,+ kind: "tool",+ name: "deploy",output:"The 14:02 deploy changed the cache TTL for every storefront route, so checkout requests missed the cache and queued at the origin. Full log attached.",status: "completed",@@ -142,6 +144,8 @@ const BOTH_TASKS_SETTLED: readonly UnstampedMessageStreamEvent[] = [createTaskSettledEvent({callId: RESEARCH_CALL,error: { message: "Rate limited by the incidents API\nRetry after 60s." },+ kind: "agent",+ name: "researcher",status: "failed",taskId: "researcher-7k2m9q",turnId: TURN_ID,diff --git a/packages/eve/src/public/channels/teams/teamsChannel.test.ts b/packages/eve/src/public/channels/teams/teamsChannel.test.tsindex 8bf648255..8c67844b4 100644--- a/packages/eve/src/public/channels/teams/teamsChannel.test.ts+++ b/packages/eve/src/public/channels/teams/teamsChannel.test.ts@@ -519,6 +519,39 @@ describe("teamsChannel", () => {expect(initialToken).toBe("TENANT:CONV:THREAD_ROOT");});+ it("keeps approval bookkeeping when a sent message carries its channel state", async () => {+ const channel = teamsChannel({ credentials: { tokenProvider: () => "token" } });+ const send = vi.fn(async () => ({ id: "SESSION" }));+ await channel.receive!(+ {+ target: {+ conversationId: "CONV",+ conversationType: "channel",+ replyToActivityId: "THREAD_ROOT",+ serviceUrl: "https://service.example/teams",+ tenantId: "TENANT",+ },+ auth: null,+ message: "Begin",+ },+ mockChannelContext<TeamsChannelState>(send as never),+ );+ const delivery = (+ send.mock.calls[0] as unknown[]+ )[1] as ObservedChannelDelivery<TeamsChannelState>;+ const teamsAdapter = adapter(channel);+ const ctx = buildAdapterContext(teamsAdapter, stubAccessor());+ const card = { activityId: "approval-card", prompt: "Approve deployment?" };+ const responder = { id: "USER", name: "Ada" };+ ctx.state.pendingApprovalCards = { approval_1: card };+ ctx.state.approvalResponderAccounts = { "teams:TENANT:USER": responder };++ await teamsAdapter.deliver!({ message: "Begin", state: delivery.state }, ctx);++ expect(ctx.state.pendingApprovalCards).toEqual({ approval_1: card });+ expect(ctx.state.approvalResponderAccounts).toEqual({ "teams:TENANT:USER": responder });+ });+it("receive starts proactive sessions and anchors initial channel messages", async () => {const requests: Array<{ body: unknown; url: string }> = [];const channel = teamsChannel({diff --git a/packages/eve/src/public/channels/telegram/hitl.ts b/packages/eve/src/public/channels/telegram/hitl.tsindex 192ff72fe..1c769d13e 100644--- a/packages/eve/src/public/channels/telegram/hitl.ts+++ b/packages/eve/src/public/channels/telegram/hitl.ts@@ -6,6 +6,8 @@* them back to full input responses inside the channel deliver hook.*/+import type { UserContent } from "ai";+import {type InputRequest,type InputResponse,@@ -20,7 +22,7 @@ export const TELEGRAM_HITL_CALLBACK_PREFIX = "eve:";/** Synthetic request id prefix sent through `send()` for callback queries. */export const TELEGRAM_CALLBACK_RESPONSE_PREFIX = "telegram_callback:";-/** Synthetic request id prefix sent through `send()` for replies to ForceReply prompts. */+/** Synthetic request id prefix the deliver hook uses for replies to ForceReply prompts. */export const TELEGRAM_REPLY_RESPONSE_PREFIX = "telegram_reply:";const TELEGRAM_BUTTON_LABEL_MAX_LENGTH = 64;@@ -120,6 +122,23 @@ export function telegramReplyInputResponse(input: {});}+/**+ * Wraps a text message that replied to a bot message as a synthetic response,+ * so the deliver hook can match it to a pending ForceReply prompt.+ */+export function telegramReplyInputResponses(+ replyToBotMessageId: unknown,+ message: string | UserContent | undefined,+): ValidatedInputResponse[] {+ if (typeof replyToBotMessageId !== "string") return [];+ const text =+ typeof message === "string"+ ? message+ : (message ?? []).flatMap((part) => (part.type === "text" ? [part.text] : [])).join("\n");+ if (text.trim().length === 0) return [];+ return [telegramReplyInputResponse({ messageId: replyToBotMessageId, text })];+}+/** True when an input response needs Telegram-specific durable-state remapping. */export function isTelegramSyntheticResponse(response: InputResponse): boolean {return (diff --git a/packages/eve/src/public/channels/telegram/state.ts b/packages/eve/src/public/channels/telegram/state.tsindex dfe29db50..6a7bf75c6 100644--- a/packages/eve/src/public/channels/telegram/state.ts+++ b/packages/eve/src/public/channels/telegram/state.ts@@ -13,6 +13,8 @@ export function stateFromTelegramMessage(chatType: message.chat.type,conversationId: privateChat ? null : conversationIdForMessage(message),messageThreadId: message.messageThreadId ?? null,+ replyToBotMessageId:+ message.replyToMessage?.from?.isBot === true ? message.replyToMessage.messageId : null,triggeringUserId: message.from?.id ?? null,};}diff --git a/packages/eve/src/public/channels/telegram/telegramChannel.test.ts b/packages/eve/src/public/channels/telegram/telegramChannel.test.tsindex 5dab51a0c..8ef596aba 100644--- a/packages/eve/src/public/channels/telegram/telegramChannel.test.ts+++ b/packages/eve/src/public/channels/telegram/telegramChannel.test.ts@@ -346,7 +346,7 @@ describe("telegramChannel() inbound route", () => {);});- it("keeps direct approval replies as fallback text for option prompts", async () => {+ it("sends a reply to a bot prompt as a message carrying the replied-to id", async () => {const channel = telegramChannel({api: { fetch: fakeTelegramFetch() },credentials: { botToken: "bot-token", webhookSecretToken: SECRET },@@ -368,9 +368,10 @@ describe("telegramChannel() inbound route", () => {const [, input] = send.mock.calls[0]!;expect(input).toMatchObject({- inputResponses: [{ requestId: "telegram_reply:55", text: "approve" }],message: expect.stringContaining("approve"),+ state: { replyToBotMessageId: "55" },});+ expect(input).not.toHaveProperty("inputResponses");});it("rejects requests with invalid webhook verification", async () => {@@ -421,19 +422,17 @@ describe("telegramChannel() deliver hook", () => {expect(await adapter.deliver!(- {- inputResponses: [- { optionId: "selected", requestId: "telegram_callback:eve:0" },- { requestId: "telegram_reply:55", text: "because" },- ],- },+ { inputResponses: [{ optionId: "selected", requestId: "telegram_callback:eve:0" }] },ctx,),).toEqual({- inputResponses: [- { optionId: "approve", requestId: "call_1" },- { requestId: "call_2", text: "because" },- ],+ inputResponses: [{ optionId: "approve", requestId: "call_1" }],+ context: undefined,+ });+ expect(+ await adapter.deliver!({ message: "because", state: { replyToBotMessageId: "55" } }, ctx),+ ).toEqual({+ inputResponses: [{ requestId: "call_2", text: "because" }],context: undefined,});});@@ -443,13 +442,7 @@ describe("telegramChannel() deliver hook", () => {const ctx = buildAdapterContext(adapter, { get: () => undefined, set: () => {} } as any);expect(- await adapter.deliver!(- {- inputResponses: [{ requestId: "telegram_reply:55", text: "hello" }],- message: "hello",- },- ctx,- ),+ await adapter.deliver!({ message: "hello", state: { replyToBotMessageId: "55" } }, ctx),).toEqual({ message: "hello", context: undefined });});});diff --git a/packages/eve/src/public/channels/telegram/telegramChannel.ts b/packages/eve/src/public/channels/telegram/telegramChannel.tsindex d6ff7ac66..e5d8787c6 100644--- a/packages/eve/src/public/channels/telegram/telegramChannel.ts+++ b/packages/eve/src/public/channels/telegram/telegramChannel.ts@@ -1,11 +1,6 @@import type { TelegramInstrumentationMetadata } from "#public/channels/telegram/index.js";import { defaultDeliverResult, type ChannelAdapterContext } from "#channel/adapter.js";-import {- INTERNAL_CHANNEL_DELIVER,- type ChannelFrom,- type ChannelResolveSession,- type InternalChannelSource,-} from "#channel/channel-operations.js";+import type { ChannelFrom, ChannelResolveSession } from "#channel/channel-operations.js";import type { SessionHandle } from "#channel/session.js";import type { DeliverPayload, SessionAuthContext, TurnPolicy } from "#channel/types.js";import type { SessionContext } from "#public/definitions/callback-context.js";@@ -45,7 +40,7 @@ import {isTelegramSyntheticResponse,resolveTelegramInputResponses,telegramCallbackInputResponse,- telegramReplyInputResponse,+ telegramReplyInputResponses,type TelegramHitlState,} from "#public/channels/telegram/hitl.js";import {@@ -107,6 +102,11 @@ export interface TelegramChannelState extends TelegramHitlState {messageThreadId: number | null;/** Telegram user id that triggered the current session/turn. */triggeringUserId?: string | null;+ /**+ * Bot message id that the triggering message replied to. The deliver hook+ * reads it from delivery state to answer a pending ForceReply prompt.+ */+ replyToBotMessageId?: string | null;/** Public authorization status messages, keyed by connection name. */pendingAuthMessageIds?: Record<string, string>;}@@ -583,29 +583,14 @@ async function dispatchMessage(input: {username: input.message.from?.username,});const channelContext = result.context ?? [];- const replyText = input.message.text || input.message.caption;- const replyInputResponses =- input.message.replyToMessage?.from?.isBot === true && replyText.trim().length > 0- ? [- telegramReplyInputResponse({- messageId: input.message.replyToMessage.messageId,- text: replyText,- }),- ]- : undefined;try {- const source = input.from(- telegramContinuationTokenFromState(state),- ) as InternalChannelSource<TelegramChannelState>;- await source[INTERNAL_CHANNEL_DELIVER](- {- context: [contextBlock, ...channelContext],- inputResponses: replyInputResponses,- message: turnMessage,- },- { auth: result.auth, state, title: result.title },- );+ await input.from(telegramContinuationTokenFromState(state)).send(turnMessage, {+ auth: result.auth,+ context: [contextBlock, ...channelContext],+ state,+ title: result.title,+ });} catch (error) {log.error("message delivery failed", { error });}@@ -678,7 +663,11 @@ function attachTelegramDeliver(channel: TelegramChannel): void {if (!isCompiledChannel(channel)) return;const adapter = channel.adapter;adapter.deliver = (payload: DeliverPayload, ctx: ChannelAdapterContext<TelegramChannelState>) => {- const responses = payload.inputResponses ?? [];+ const state = payload.state as Partial<TelegramChannelState> | undefined;+ const responses = [+ ...(payload.inputResponses ?? []),+ ...telegramReplyInputResponses(state?.replyToBotMessageId, payload.message),+ ];if (responses.some(isTelegramSyntheticResponse)) {const resolved = resolveTelegramInputResponses(ctx.state, responses);if (resolved.length > 0) {diff --git a/packages/eve/src/public/schedules/index.ts b/packages/eve/src/public/schedules/index.tsindex d9aac20a0..e5f6ab2d1 100644--- a/packages/eve/src/public/schedules/index.ts+++ b/packages/eve/src/public/schedules/index.ts@@ -10,3 +10,4 @@ export {type ScheduleToFn,type TypedReceiveTarget,} from "#public/definitions/schedule.js";+export { isScheduleAuth } from "#channel/schedule-auth.js";diff --git a/packages/eve/src/public/tools/index.ts b/packages/eve/src/public/tools/index.tsindex ecafa6e60..f427fe9c5 100644--- a/packages/eve/src/public/tools/index.ts+++ b/packages/eve/src/public/tools/index.ts@@ -17,6 +17,7 @@ export {} from "#tools/definition.js";export { defineDynamic } from "#dynamic/definition.js";export { defineDurableSchema } from "#tools/durable-schema.js";+export { serializeModelInputSchema } from "#tools/schema.js";export { defineDurableCallback } from "#tools/durable-callbacks.js";export { toolOutput, toolOutputPart } from "#tools/model-output.js";export type { DynamicEvents, DynamicResolveContext, DynamicSentinel } from "#dynamic/definition.js";diff --git a/packages/eve/src/tools/schema.test.ts b/packages/eve/src/tools/schema.test.tsindex f158ae7a1..c3da6cc83 100644--- a/packages/eve/src/tools/schema.test.ts+++ b/packages/eve/src/tools/schema.test.ts@@ -13,6 +13,7 @@ import {toModelSchema,toOutputSchema,} from "#tools/schema.js";+import { serializeModelInputSchema } from "#public/tools/index.js";const AI_SDK_SCHEMA = Symbol.for("vercel.ai.schema");@@ -410,6 +411,10 @@ describe("toModelSchema", () => {expect(await asSchema(toModelSchema(defineJsonSchema(jsonSource), "input")).jsonSchema).toEqual(jsonSource,);+ // The public serializer reports the same model-facing JSON, from live or plain sources.+ expect(serializeModelInputSchema(zodSchema)).toEqual(aiSdkJsonSchema);+ expect(serializeModelInputSchema(jsonSource)).toEqual(jsonSource);+ expect(serializeModelInputSchema(null)).toBeNull();});it("emits the requested direction of a transforming schema", async () => {diff --git a/packages/eve/src/tools/schema.ts b/packages/eve/src/tools/schema.tsindex b712acae0..476b8659a 100644--- a/packages/eve/src/tools/schema.ts+++ b/packages/eve/src/tools/schema.ts@@ -76,6 +76,24 @@ export function serializeInputSchema<T extends ToolSchemaSource | null | undefinreturn serializeSchema(source, "input") as SchemaResult<T, JsonObject>;}+/**+ * Serializes an input schema into the JSON Schema eve sends a model for it.+ * A schema from a validation library such as Zod, Valibot, or ArkType gets+ * `additionalProperties: false` on every object that allows no other keys, as+ * the AI SDK applies to library schemas. Plain JSON Schema is sent exactly as+ * written. `null` and `undefined` pass through untouched.+ *+ * Providers can transform the schema further before the model reads it.+ */+export function serializeModelInputSchema<T extends ToolSchemaSource | null | undefined>(+ source: T,+): SchemaResult<T, JsonObject> {+ const schema = toSchema(source, "input");+ return (+ schema === null || schema === undefined ? schema : toModelJsonSchema(schema, "input")+ ) as SchemaResult<T, JsonObject>;+}+/*** Returns whether a value implements the full {@link ToolSchema} contract:* Standard Schema validation plus JSON Schema emission.@@ -225,21 +243,19 @@ export function toModelSchema(return schema;}const source = schema as StandardSchemaV1;- const verbatim = plainJsonSchemas.has(source);- return jsonSchema(- () => {- const json = serializeSchema(source, direction);- return (verbatim ? json : closeObjectSchemas(json)) as JSONSchema7;- },- {- validate: async (value) => {- const result = await source["~standard"].validate(value);- return result.issues === undefined- ? { success: true, value: result.value }- : { success: false, error: new TypeValidationError({ value, cause: result.issues }) };- },+ return jsonSchema(() => toModelJsonSchema(source, direction) as JSONSchema7, {+ validate: async (value) => {+ const result = await source["~standard"].validate(value);+ return result.issues === undefined+ ? { success: true, value: result.value }+ : { success: false, error: new TypeValidationError({ value, cause: result.issues }) };},- ) satisfies Schema;+ }) satisfies Schema;+}++function toModelJsonSchema(source: StandardSchemaV1, direction: SchemaDirection): JsonObject {+ const json = serializeSchema(source, direction) as JsonObject;+ return plainJsonSchemas.has(source) ? json : (closeObjectSchemas(json) as JsonObject);}/**