Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat(slack)!: live task cards and composable renderers (#4028)

Andrew Barba9c36b7c280fd
diff --git a/.changeset/slack-task-cards.md b/.changeset/slack-task-cards.md
new file mode 100644
index 000000000..f3bac7526
--- /dev/null
+++ b/.changeset/slack-task-cards.md
@@ -0,0 +1,7 @@
+---
+"eve": minor
+---
+
+Slack now shows each turn's tasks in a live task card: one message, updated in place, with a row per task that shows whether it is working or waiting on a person, and how it ended. Slack also acknowledges a mention or DM with `Thinking...` right away, even with a custom `onAppMention` or `onDirectMessage`, and clears it if the hook drops the message. While a turn waits on its tasks, the status names them. Outside DMs and private channels, the card shows a failed task as `Failed` without its error text, and a blocked task without the request's prompt. Channels can now handle `input.resolved` to learn when each question or approval ends, however it ended.
+
+`slackChannel({ events })` is replaced by `renderers`, which wrap eve's default rendering instead of replacing it; without `renderers`, eve renders with its default. Move `events: { … }` to `renderers: [{ events: { … } }]` and handlers behave as before; call the new `next` argument to keep eve's default; `next` also replaces `input.requested`'s `defaultDeliver`. A renderer can also shape the task card with `taskCard(view, next)`, whose view includes the turn's other tool calls and their input, so your own tools, such as a checklist, can appear on the card. The experimental `activity` option, the `experimental_slackActivity*` renderers, and the activity collector behind them are removed, along with the `activityObserver` field on delegated and remote-agent sessions; remote agents ignore it when an older caller still sends it.
diff --git a/docs/channels/custom.mdx b/docs/channels/custom.mdx
index f3919ee18..bc26be647 100644
--- a/docs/channels/custom.mdx
+++ b/docs/channels/custom.mdx
@@ -74,6 +74,11 @@ the exact session, while `channel.continuation` exposes the current address and
receives only `(eventData, channel)` because it runs outside session context;
its event data contains `sessionId` directly.
+A channel that renders questions and approvals from `input.requested` can handle
+`input.resolved` to learn when each request ends, however it ended: answered from
+the channel, answered by a plain-text reply, or withdrawn. Each resolution carries
+the `requestId` and an `outcome` such as `answered`, `approved`, or `cancelled`.
+
`channel.continuation.token` is always the channel-local address accepted by
`from()`, `resolveSession()`, and `alias()`. Framework namespace prefixes are not
part of the authored channel API.
diff --git a/docs/channels/slack.mdx b/docs/channels/slack.mdx
index 41d674e50..5272bb8c9 100644
--- a/docs/channels/slack.mdx
+++ b/docs/channels/slack.mdx
@@ -152,7 +152,7 @@ controls observability content capture, not access to the channel. See
Message hooks return `{ auth }` to dispatch, `null` to drop, or `{ auth, context }` to inject background into history. Public conversations use the returned `title`, or the triggering message text when `title` is omitted. DMs and private channels always use `Private message` so the run title does not expose message details.
- `onMessage(ctx, message)` handles Slack `message` events. eve drops messages authored by the installed app before this hook runs, preventing self-reply loops. Messages from other bots remain visible; check `message.author?.isBot` when those should also be ignored. `ctx.isBotMentioned()` and `ctx.isSubscribed()` support mention and active-thread policies.
-- `onAppMention(ctx, message)` handles only `app_mention` and takes precedence over `onMessage`. Its default derives workspace-scoped auth and posts `Thinking…`.
+- `onAppMention(ctx, message)` handles only `app_mention` and takes precedence over `onMessage`. Its default derives workspace-scoped auth.
- `onDirectMessage(ctx, message)` handles only DMs and takes precedence over `onMessage`. Bot-authored messages and edits are filtered first; Slack requires `message.im` and `im:history`.
| Incoming event | Handler order |
@@ -164,6 +164,8 @@ Message hooks return `{ auth }` to dispatch, `null` to drop, or `{ auth, context
Only the first available handler runs. A message hook returning `null` drops the message; it does not continue down the table.
+Message hooks only decide whether and how a message starts a turn. They don't render anything, so replacing one never changes what people see: eve still acknowledges the message, shows progress, and posts the reply. To change what the agent posts, add [renderers](#customize-rendering).
+
`onInteraction(action, ctx)` separately handles user-owned `block_actions` callbacks. eve-owned HITL buttons and modal submissions go through `onInputResponse(ctx, submission)` instead. eve attaches the triggering Slack user id to the same model message as its text, preserving speaker attribution without profile lookups.
Use `onShortcut(shortcut, ctx)` for message shortcuts and global shortcuts configured under **Interactivity & Shortcuts** in your Slack app. The handler receives the shortcut callback ID, user, workspace, and trigger ID. Message shortcuts also include the selected message and channel. The context exposes workspace-scoped Slack API access because global shortcuts have no channel or message. eve acknowledges shortcut requests immediately and keeps their handlers alive in the background.
@@ -397,7 +399,7 @@ const session = await ctx.resolveSession({ target });
### Slack API calls outside a handler
-Inside inbound webhook handlers such as `onAppMention`, `onEvent`, `onInteraction`, `onShortcut`, `onSlashCommand`, and `onInputResponse`, `ctx.slack.request(operation, body)` is the raw-API escape hatch. Inside an `events` handler, use `channel.slack.request(...)` instead. Outside those contexts there is no handle — a schedule resolving reactions on old
+Inside inbound webhook handlers such as `onAppMention`, `onEvent`, `onInteraction`, `onShortcut`, `onSlashCommand`, and `onInputResponse`, `ctx.slack.request(operation, body)` is the raw-API escape hatch. Inside a [renderer](#customize-rendering)'s event handler, use `channel.slack.request(...)` instead. Outside those contexts there is no handle — a schedule resolving reactions on old
messages, for example, has no inbound Slack request. For that, call the
same primitive the handle uses directly:
@@ -450,27 +452,177 @@ The bases say where a call may go. `apiBaseUrl` is the base Slack Web API method
### Delivery
-The default handlers reply in-thread and show activity. Typing indicators post automatically: `Thinking…` on inbound, `Working…` on `turn.started`, a truncated reasoning snippet on `reasoning.appended`, and an action label on `actions.requested` — the tool name plus its most telling argument (`grep useEveAgent`, `read_file agent/agent.ts`), the subagent or remote-agent name for dispatched calls, and `+N more` when the model requests several actions at once. Labels leave out the model's own `task_wait` and `task_cancel` calls. The model's own pre-tool narration, when present, takes precedence over the derived label. Reasoning snippets build progressively: extensions of at least four characters appear immediately, while smaller streamed deltas use the five-second refresh interval to avoid one Slack request per token. Override `events["reasoning.appended"]` if you prefer generic wording. Override an inbound handler or the `events` handlers to customize.
+eve shows an agent's progress in two places. Short work, such as thinking or a tool call, appears in the thread status and never posts a message. [Tasks](/docs/tools/tasks), which keep working while the conversation continues, appear in a task card: one message per turn that eve updates in place. Replies post as ordinary messages, so the thread holds the conversation, the task card, and nothing else.
+
+| Moment | Thread status |
+| ---------------------------------- | ----------------------------------------------------------------------------- |
+| A mention or DM arrives | `Thinking...`, right away, while the message hook is still deciding |
+| The message hook drops the message | Cleared |
+| The turn starts | `Working...` |
+| The model reasons | The first line of its reasoning |
+| The model calls tools | Its narration before the calls, or an action label such as `grep useEveAgent` |
+| The turn waits on its tasks | `Waiting on researcher...`, or `Waiting on researcher and 2 more tasks...` |
+| A reply posts | Cleared by Slack |
+
+Slack clears a thread status after two minutes without a message, so during a long wait the task card is what shows the work is still going.
+
+Action labels are the tool name plus its most telling argument, the agent name for agent calls, and `+N more` when the model requests several actions at once. They leave out the model's own `task_wait` and `task_cancel` calls. Reasoning snippets build progressively: extensions of at least four characters appear immediately, while smaller streamed deltas use a five-second refresh interval to avoid one Slack request per token.
-The built-in `message.completed` handler renders responses up to 12,000 characters inline. Longer responses are uploaded unchanged as a Markdown snippet named `eve-response.md` with a short in-thread note, which requires the `files:write` bot scope. Upload failures are logged by the channel dispatcher; they do not trigger a model retry. An authored `events["message.completed"]` handler replaces this behavior and owns its own delivery limits.
+Replies up to 12,000 characters render inline. Longer replies are uploaded unchanged as a Markdown snippet named `eve-response.md` with a short in-thread note, which requires the `files:write` bot scope. Upload failures are logged by the channel dispatcher; they do not trigger a model retry.
-When the model replies while its [tasks](/docs/tools/tasks) keep working, that reply posts like any other, and the reply after the results posts as another message. A schedule's session posts only the final reply.
+When the model replies while its tasks keep working, that reply posts like any other, and the reply after the results posts as another message. A schedule's session posts only the final reply.
Outbound text preserves bare `@` tokens as literal text. To mention a user, embed Slack's `<@USER_ID>` syntax directly or use `channel.thread.mentionUser(userId)`.
-The example below overrides `onAppMention` to gate on an authored message. The built-in completion handler still posts the reply and uploads long responses as snippets. Event handlers receive `(eventData, channel, ctx)`, with Slack platform handles on `channel.thread` and `channel.slack`:
+### Task card
-```ts
-import { defaultSlackAuth, slackChannel } from "eve/channels/slack";
+When a turn starts its first task, eve posts a task card in the thread and keeps it current until the turn and its tasks finish. One task renders as a Slack `task_card` block; two or more render as a `plan` block with one row per task the turn started. What an agent task does on its own, including the tasks it starts, stays inside that task and does not add rows. The card needs no configuration beyond the `chat:write` scope the channel already uses.
+
+Each row shows:
+
+- **Title:** the tool's [`label.start`](/docs/tools#label-tool-activity), the agent name and the first line of its brief for an agent task (`researcher: Find the incidents behind the checkout spike`), or the tool name.
+- **Waiting:** while the task waits on an approval, an answer, or a sign-in, the row says so, as in `Waiting for approval`. In a DM or private channel it also shows the request's prompt; elsewhere it shows only what kind of request is waiting, since `approvalChannel` can send the request to one person. The request itself posts wherever `approvalChannel` sends it, and the row goes back to working once the request resolves.
+- **How it ended:** the first line of the result or the agent's reply, `Failed` for a failure, or `Stopped` for a cancelled task. Failed and stopped rows never show a success check. In a DM or private channel, a failure also shows the first line of its error, as in `Failed: Rate limited`. Error text can carry internal details, so everywhere else, including proactive sessions without a known `audience`, shows `Failed` alone.
+
+The plan title summarizes the turn: `Working on 2 tasks`, `1 of 2 tasks done`, `Waiting for approval`, then `Finished 2 tasks` or `Finished 3 tasks: 1 failed, 1 stopped`. A resumable task continued in a later turn appears in that turn's card.
+
+eve writes the card from the session's own events as they happen, and only when it changed. A failed Slack call never fails the turn: eve tries a failed write once more after a second, then again on the turn's next change. If someone deletes the card, eve posts it again on its next change. Card posts never unfurl links. Schedule sessions and sessions without a Slack thread get no card.
+
+### Customize rendering
+
+Without `renderers`, eve renders everything above with its default renderer. Pass `renderers` to change what the agent posts without replacing that default. Each renderer wraps the ones after it, ending with eve's default renderer, and has three optional parts:
+
+- `received(message, channel, next)` acknowledges a mention or DM the moment it arrives, and another channel message once `onMessage` dispatches it. eve's default sets `Thinking...`.
+- `events` handles session events such as `message.completed` or `input.requested`. Each handler receives `(eventData, channel, ctx, next)`, with Slack platform handles on `channel.thread` and `channel.slack`; a `session.failed` handler receives `(eventData, channel, next)`.
+- `taskCard(view, next)` returns the task card's blocks and notification text, or `null` for no card.
+
+Call `next()` to run the rest of the chain, ending with eve's default. Call it after your own work, before it, or with changed data, as in `next({ ...event, message })`; the rest of the chain runs at most once. Skip `next` to replace the default for that event. This renderer adds feedback buttons below each final reply and a context row to the finished task card:
+
+```ts title="agent/channels/slack.ts"
import { connectSlackCredentials } from "@vercel/connect/eve";
+import { defineSlackRenderer, slackChannel } from "eve/channels/slack";
+
+const feedback = defineSlackRenderer({
+ events: {
+ async "message.completed"(event, channel, _ctx, next) {
+ await next(); // eve posts the reply, or uploads a long one as a snippet
+ if (event.finishReason === "tool-calls") return;
+ await channel.thread.post({
+ blocks: [
+ {
+ type: "context_actions",
+ elements: [
+ {
+ type: "feedback_buttons",
+ action_id: "reply_feedback",
+ positive_button: { text: { type: "plain_text", text: "Helpful" }, value: "up" },
+ negative_button: {
+ text: { type: "plain_text", text: "Not helpful" },
+ value: "down",
+ },
+ },
+ ],
+ },
+ ],
+ text: "Was this helpful?",
+ });
+ },
+ },
+ taskCard(view, next) {
+ const card = next(view);
+ if (card === null || view.state !== "finished") return card;
+ const note = {
+ type: "context",
+ elements: [{ type: "mrkdwn", text: "Results are in the reply below." }],
+ };
+ return { ...card, blocks: [...card.blocks, note] };
+ },
+});
export default slackChannel({
credentials: connectSlackCredentials("slack/my-agent"),
- onAppMention: (ctx, message) =>
- message.author ? { auth: defaultSlackAuth(message, ctx) } : null,
+ renderers: [feedback],
});
```
+`taskCard` runs for every turn that calls a tool, and receives the same view eve's default renders from:
+
+- `state`: `blocked` while any task waits on a person, `working` while the turn or any other task works, then `finished`.
+- `tasks`: the tasks the turn started, each with a `title`, `status`, `blockedOn`, and `summary`. A failed task's `summary` and a blocked task's `blockedOn.label` are present only in a DM or private channel.
+- `actions`: the turn's other tool calls, each with its tool `name`, `title`, `status`, and `input`. `input` is left out when its JSON is longer than 4,096 characters.
+
+`taskCard` is synchronous and pure: eve posts the card and updates it as the view changes. eve's default returns `null` for a turn that started no tasks. To change a row's title in every channel, give the tool a [label](/docs/tools#label-tool-activity) instead.
+
+Renderers run in the order you list them, and the first one is outermost. `onInteraction` receives clicks on buttons a renderer posts, such as the feedback buttons above.
+
+### Show your own tool on the task card
+
+A renderer can draw any of the turn's tool calls from their input. For example, give the agent a `plan` tool that records a checklist, and show the checklist ahead of eve's task rows:
+
+```ts title="agent/tools/plan.ts"
+import { defineTool } from "eve/tools";
+import { z } from "zod";
+
+export default defineTool({
+ description:
+ "Show the steps of a multi-step request as a checklist. Pass the complete list on every call.",
+ inputSchema: z.object({
+ items: z.array(
+ z.object({
+ status: z.enum(["pending", "working", "completed", "failed"]),
+ title: z.string(),
+ }),
+ ),
+ }),
+ async execute() {
+ return { updated: true };
+ },
+});
+```
+
+```ts title="agent/channels/slack.ts"
+import { type BlockKitBlock, defineSlackRenderer, slackChannel } from "eve/channels/slack";
+
+interface PlanItem {
+ readonly status: "pending" | "working" | "completed" | "failed";
+ readonly title: string;
+}
+
+const SLACK_STATUS = {
+ completed: "complete",
+ failed: "error",
+ pending: "pending",
+ working: "in_progress",
+} as const;
+
+const plan = defineSlackRenderer({
+ taskCard(view, next) {
+ const card = next(view);
+ const calls = view.actions.filter((action) => action.name === "plan");
+ const items = calls.at(-1)?.input?.items as PlanItem[] | undefined;
+ if (items === undefined) return card;
+ // eve's card is one `plan` block, or one `task_card` block for a single task.
+ const [block] = card?.blocks ?? [];
+ const taskRows: BlockKitBlock[] =
+ block === undefined ? [] : block.type === "plan" ? (block.tasks as BlockKitBlock[]) : [block];
+ const planRows = items.map((item, index) => ({
+ status: SLACK_STATUS[item.status],
+ task_id: `plan_${index}`,
+ title: item.title,
+ }));
+ const tasks = [...planRows, ...taskRows.map(({ type: _type, ...row }) => row)];
+ return {
+ blocks: [{ type: "plan", title: "Plan", tasks }],
+ text: `Plan: ${items.map((item) => item.title).join(", ")}`,
+ };
+ },
+});
+
+export default slackChannel({ renderers: [plan] });
+```
+
+A turn that only plans gets a card too, because `taskCard` runs for every turn that calls a tool.
+
### Human-in-the-loop (HITL)
HITL renders as Slack buttons and selects. Fixed-choice actions and freeform modal submissions pass through `onInputResponse` before the parked session resumes. The initial **Type your answer** action only opens eve's modal; the hook runs when the user submits an answer.
@@ -490,7 +642,7 @@ export default slackChannel({
The callback receives the `InputRequest` and current `SessionContext`, so it can switch on `kind`, `action`, or presentation properties. Omit it to keep every request in the thread, or return `"direct-message"` unconditionally to make every request private. If eve cannot resolve the triggering Slack user for a direct message, it logs the undelivered request and posts no fallback, so private delivery fails closed. The existing `onInputResponse` or tool approval response policy still decides whether the person who clicks may respond.
-An authored `input.requested` handler can extend delivery and then hand the requests back to eve through `defaultDeliver()`. For example, an application can add non-sensitive context to the Slack thread before eve renders the actionable controls. The configured `approvalChannel` still sends sensitive reviews to a DM and keeps ordinary requests in the thread:
+A renderer's `input.requested` handler can extend delivery and then hand the requests on to eve with `next()`. For example, an application can add non-sensitive context to the Slack thread before eve renders the actionable controls. The configured `approvalChannel` still sends sensitive reviews to a DM and keeps ordinary requests in the thread:
```ts title="agent/channels/slack.ts"
import { slackChannel } from "eve/channels/slack";
@@ -500,41 +652,49 @@ export default slackChannel({
approvalChannel(request) {
return isPrivate(request) ? "direct-message" : "thread";
},
- events: {
- async "input.requested"(event, channel, _ctx, defaultDeliver) {
- await channel.thread.post({
- blocks: [
- {
- type: "context",
- elements: [
+ renderers: [
+ {
+ events: {
+ async "input.requested"(_event, channel, _ctx, next) {
+ await channel.thread.post({
+ blocks: [
{
- type: "mrkdwn",
- text: "A review is needed before this work can continue.",
+ type: "context",
+ elements: [
+ {
+ type: "mrkdwn",
+ text: "A review is needed before this work can continue.",
+ },
+ ],
},
],
- },
- ],
- text: "A review is needed before this work can continue.",
- });
- await defaultDeliver(event);
+ text: "A review is needed before this work can continue.",
+ });
+ await next();
+ },
+ },
},
- },
+ ],
});
```
-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. The 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. `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.
+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.
```ts
-events: {
- "authorization.required"(eventData, channel) {
- const userId =
- eventData.principalId === undefined
- ? undefined
- : channel.state.slackUsersByPrincipal?.[eventData.principalId];
- if (!userId || !eventData.authorization?.url) return;
- return channel.postDirectMessage(userId, `Sign in to continue: ${eventData.authorization.url}`);
+renderers: [
+ {
+ events: {
+ "authorization.required"(eventData, channel) {
+ const userId =
+ eventData.principalId === undefined
+ ? undefined
+ : channel.state.slackUsersByPrincipal?.[eventData.principalId];
+ if (!userId || !eventData.authorization?.url) return;
+ return channel.postDirectMessage(userId, `Sign in to continue: ${eventData.authorization.url}`);
+ },
+ },
},
-},
+],
```
The private authorization button uses the label **Sign in**, so long connection display names do not make the button invalid. The public status identifies the connection.
@@ -554,7 +714,7 @@ Pass `{ channelId }` as the target to start a new thread. The agent's first post
The default mention handler lets teammates continue the session by mentioning the app in the thread. To accept replies without a mention, [configure an `onMessage` hook and the required Slack subscriptions and scopes](#continue-conversations-without-repeated-mentions).
-For a Slack post without an agent turn, use `ctx.thread.post(...)` in an inbound handler or `channel.thread.post(...)` in an `events` handler. Outside a handler, use [`callSlackApi(...)`](#slack-api-calls-outside-a-handler).
+For a Slack post without an agent turn, use `ctx.thread.post(...)` in an inbound handler or `channel.thread.post(...)` in a renderer's event handler. Outside a handler, use [`callSlackApi(...)`](#slack-api-calls-outside-a-handler).
### Attachments
diff --git a/docs/guides/hooks.md b/docs/guides/hooks.md
index 09d2fe9e9..3b281021f 100644
--- a/docs/guides/hooks.md
+++ b/docs/guides/hooks.md
@@ -48,7 +48,7 @@ export default githubChannel({
});
```
-A GitHub channel event handler cannot fire for a Slack-owned session, so platform-specific side effects do not depend on an early-return guard. On a built-in channel, an authored handler replaces that channel's default handler for the same event key. Check the channel page before overriding events that deliver replies, progress, errors, or human-input prompts.
+A GitHub channel event handler cannot fire for a Slack-owned session, so platform-specific side effects do not depend on an early-return guard. On a built-in channel, an authored handler replaces that channel's default handler for the same event key. Check the channel page before overriding events that deliver replies, progress, errors, or human-input prompts. The [Slack channel](/docs/channels/slack#customize-rendering) takes renderers instead: a renderer's handler keeps Slack's default by calling `next()` and replaces it by skipping `next`.
Use `ctx.channel.kind` inside a global hook only when the operation is otherwise agent-wide and conditional handling is intentional. For typed channel metadata in dynamic resolvers or instrumentation, import the channel definition and narrow with `isChannel`; see [OpenTelemetry runtime context](../observability/otel#add-runtime-context).
diff --git a/docs/tools/tasks.md b/docs/tools/tasks.md
index ca16a3f42..c81bacb5e 100644
--- a/docs/tools/tasks.md
+++ b/docs/tools/tasks.md
@@ -236,7 +236,8 @@ final reply rather than the text written before the wait. `result()` stops at `t
while a question is pending, and returns `status: "waiting"` with it; `respond()` then reads the
same turn to its end. See [Aggregate a turn](/docs/guides/client/streaming#aggregate-a-turn).
Channels such as [Slack](/docs/channels/slack) post a root session's text before the wait as an
-ordinary reply, then post the reply after the results as another message.
+ordinary reply, then post the reply after the results as another message. Slack also shows each
+turn's tasks in a live [task card](/docs/channels/slack#task-card).
A steering message from the turn's own caller, one sent with `turnPolicy: "steer"`, the default,
ends a `task_wait` and aborts the `abortSignal` of any `execute` call the turn waits on, but it
diff --git a/packages/eve/extension-contracts/compatibility/channel/v37.ts b/packages/eve/extension-contracts/compatibility/channel/v37.ts
new file mode 100644
index 000000000..b5ee1780d
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/channel/v37.ts
@@ -0,0 +1,15 @@
+import { defineChannel } from "#public/channels/index.js";
+
+// Epoch 37 channels had no `task.started`, `task.settled`, `turn.waiting`, or `input.resolved`
+// handlers, which are additive, and could pass an `activityObserver` that eve now ignores.
+export default defineChannel({
+ routes: [],
+ events: {
+ "turn.started"(event) {
+ console.info("turn started", { turnId: event.turnId });
+ },
+ "turn.completed"(event) {
+ console.info("turn completed", { turnId: event.turnId });
+ },
+ },
+});
diff --git a/packages/eve/extension-contracts/compatibility/schedule/v19.ts b/packages/eve/extension-contracts/compatibility/schedule/v19.ts
new file mode 100644
index 000000000..c9ab4ef4d
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/schedule/v19.ts
@@ -0,0 +1,9 @@
+import { defineSchedule } from "#public/schedules/index.js";
+
+// Epoch 19 run inputs could carry an `activityObserver`; eve now ignores it.
+export default defineSchedule({
+ cron: "0 9 * * *",
+ async run({ appAuth, waitUntil }) {
+ waitUntil(Promise.resolve(appAuth.principalId));
+ },
+});
diff --git a/packages/eve/extension-contracts/reports/channel/v38.json b/packages/eve/extension-contracts/reports/channel/v38.json
new file mode 100644
index 000000000..76890d869
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/channel/v38.json
@@ -0,0 +1,21 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "channel",
+ "epoch": 38,
+ "sha256": "3eeee88e4d716b44f4f42f0f04b8f07c0596e0644761436db4a48af6b5877ea7",
+ "exports": [
+ "DELETE",
+ "GET",
+ "HEAD",
+ "OPTIONS",
+ "PATCH",
+ "POST",
+ "PUT",
+ "WS",
+ "createWebSocketUpgradeServer",
+ "defineChannel",
+ "disableRoute",
+ "isChannel",
+ "isDisabledRouteSentinel"
+ ]
+}
diff --git a/packages/eve/extension-contracts/reports/schedule/v20.json b/packages/eve/extension-contracts/reports/schedule/v20.json
new file mode 100644
index 000000000..86786e772
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/schedule/v20.json
@@ -0,0 +1,14 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "schedule",
+ "epoch": 20,
+ "sha256": "bcdfaa846716c0b2ee3af7e5f1e0c2ac70edc47d69ddcbeaeaa175ae6375bbbe",
+ "exports": [
+ "ScheduleDefinition",
+ "ScheduleHandlerArgs",
+ "ScheduleRunHandler",
+ "ScheduleToFn",
+ "TypedReceiveTarget",
+ "defineSchedule"
+ ]
+}
diff --git a/packages/eve/src/channel/activity-renderer.ts b/packages/eve/src/channel/activity-renderer.ts
deleted file mode 100644
index 2afd30272..000000000
--- a/packages/eve/src/channel/activity-renderer.ts
+++ /dev/null
@@ -1,55 +0,0 @@
-import type { ChannelAdapter } from "#channel/adapter.js";
-import type { ActivitySnapshotV1 } from "#protocol/activity.js";
-
-const CHANNEL_ACTIVITY_PRESENTATION = Symbol.for("eve.channel.activityPresentation");
-
-export interface ChannelActivityRenderer {
- readonly id: string;
- render(input: {
- readonly destination: Readonly<Record<string, unknown>>;
- readonly snapshot: ActivitySnapshotV1;
- readonly state: unknown;
- }): Promise<unknown>;
- dispose?(input: {
- readonly destination: Readonly<Record<string, unknown>>;
- readonly state: unknown;
- }): Promise<void>;
-}
-
-export interface ChannelActivityPresentation {
- readonly destination: (
- state: Record<string, unknown> | undefined,
- ) => Readonly<Record<string, unknown>>;
- readonly renderers: readonly ChannelActivityRenderer[];
-}
-
-type ActivityChannelAdapter = ChannelAdapter & {
- readonly [CHANNEL_ACTIVITY_PRESENTATION]?: ChannelActivityPresentation;
-};
-
-export function attachChannelActivityPresentation(
- adapter: ChannelAdapter,
- presentation: ChannelActivityPresentation,
-): void {
- Object.defineProperty(adapter, CHANNEL_ACTIVITY_PRESENTATION, {
- configurable: true,
- enumerable: false,
- value: presentation,
- });
-}
-
-export function copyChannelActivityPresentation(
- source: ChannelAdapter,
- target: ChannelAdapter,
-): void {
- const descriptor = Object.getOwnPropertyDescriptor(source, CHANNEL_ACTIVITY_PRESENTATION);
- if (descriptor !== undefined) {
- Object.defineProperty(target, CHANNEL_ACTIVITY_PRESENTATION, descriptor);
- }
-}
-
-export function getChannelActivityPresentation(
- adapter: ChannelAdapter,
-): ChannelActivityPresentation | undefined {
- return (adapter as ActivityChannelAdapter)[CHANNEL_ACTIVITY_PRESENTATION];
-}
diff --git a/packages/eve/src/channel/activity-sink.test.ts b/packages/eve/src/channel/activity-sink.test.ts
deleted file mode 100644
index 297ea1203..000000000
--- a/packages/eve/src/channel/activity-sink.test.ts
+++ /dev/null
@@ -1,32 +0,0 @@
-import { describe, expect, it } from "vitest";
-
-import { parseActivitySink } from "#channel/activity-sink.js";
-
-const token = "abcdefghijklmnopqrstuvwxyz123456";
-
-describe("parseActivitySink", () => {
- it("accepts an absolute public activity capability URL", () => {
- const sink = {
- url: `https://agent.example.com/eve/v1/activity/${token}`,
- version: 1 as const,
- };
- expect(parseActivitySink(sink)).toEqual(sink);
- });
-
- it("accepts a compact named-agent activity capability URL", () => {
- const sink = {
- url: `https://agent.example.com/eve/support/v1/activity/${token}`,
- version: 1 as const,
- };
- expect(parseActivitySink(sink)).toEqual(sink);
- });
-
- it("rejects missing opaque tokens and reserved sink hosts", () => {
- expect(() =>
- parseActivitySink({ url: "https://agent.example.com/eve/v1/activity/short", version: 1 }),
- ).toThrow("opaque activity token");
- expect(() =>
- parseActivitySink({ url: `http://169.254.169.254/eve/v1/activity/${token}`, version: 1 }),
- ).toThrow("private or reserved");
- });
-});
diff --git a/packages/eve/src/channel/activity-sink.ts b/packages/eve/src/channel/activity-sink.ts
deleted file mode 100644
index 1acdf3023..000000000
--- a/packages/eve/src/channel/activity-sink.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-import { z } from "#compiled/zod/index.js";
-
-import type { ActivitySinkV1 } from "#channel/types.js";
-import { EVE_ACTIVITY_ROUTE_PATTERN } from "#protocol/routes.js";
-import { normalizePublicEveRoutePath } from "#shared/eve-route-path.js";
-import { isReservedIpAddress } from "#shared/network-address.js";
-
-const schema = z.object({ url: z.string().min(1), version: z.literal(1) }).strict();
-
-export function parseActivitySink(value: unknown): ActivitySinkV1 | undefined {
- if (value === undefined) return undefined;
- const parsed = schema.safeParse(value);
- if (!parsed.success) throw new Error("Expected activitySink version 1.");
- let url: URL;
- try {
- url = new URL(parsed.data.url);
- } catch {
- throw new Error("Activity sink url must be absolute.");
- }
- const routePrefix = EVE_ACTIVITY_ROUTE_PATTERN.slice(0, -":token".length);
- const pathname = normalizePublicEveRoutePath(url.pathname);
- const routeIndex = pathname.lastIndexOf(routePrefix);
- const token = pathname.slice(routeIndex + routePrefix.length);
- if (routeIndex < 0 || token.length < 32) {
- throw new Error("Activity sink url must contain an opaque activity token.");
- }
- if (isReservedIpAddress(url.hostname)) {
- throw new Error("Activity sink url host must not be a private or reserved address.");
- }
- return parsed.data;
-}
diff --git a/packages/eve/src/channel/channel-address.test.ts b/packages/eve/src/channel/channel-address.test.ts
index a8cc3808d..6ed63f55f 100644
--- a/packages/eve/src/channel/channel-address.test.ts
+++ b/packages/eve/src/channel/channel-address.test.ts
@@ -1,10 +1,6 @@
import { describe, expect, it, vi } from "vitest";
import { createChannelAddress } from "#channel/channel-address.js";
-import {
- attachChannelActivityPresentation,
- getChannelActivityPresentation,
-} from "#channel/activity-renderer.js";
import type { Runtime } from "#channel/types.js";
function createRuntime(): Runtime {
@@ -120,47 +116,6 @@ describe("createChannelAddress", () => {
);
});
- it("enables activity only for a newly created session with configured renderers", async () => {
- const runtime = createRuntime();
- vi.mocked(runtime.dispatchContinuation).mockResolvedValue({ status: "session_not_active" });
- vi.mocked(runtime.createSession).mockResolvedValue({
- events: new ReadableStream(),
- sessionId: "sess_activity",
- });
- const adapter = { kind: "slack" };
- attachChannelActivityPresentation(adapter, {
- destination: () => ({}),
- renderers: [{ id: "status", render: vi.fn() }],
- });
- const address = createChannelAddress<{ channelId: string; threadTs: string }>({
- adapter,
- channelName: "slack",
- continuationToken: "C1:T1",
- runtime,
- });
-
- await address.send("hello", {
- auth: null,
- state: { channelId: "C1", threadTs: "T1" },
- });
-
- expect(runtime.createSession).toHaveBeenCalledWith(
- expect.objectContaining({
- adapter: expect.objectContaining({ state: { channelId: "C1", threadTs: "T1" } }),
- capabilities: { requestInput: true },
- continuationConflictCommand: expect.objectContaining({
- kind: "send",
- payload: { message: "hello" },
- }),
- }),
- );
- const created = vi.mocked(runtime.createSession).mock.calls[0]?.[0].adapter;
- expect(created).toBeDefined();
- expect(getChannelActivityPresentation(created!)?.renderers).toEqual([
- expect.objectContaining({ id: "status" }),
- ]);
- });
-
it("binds every control directly to the namespaced continuation token", async () => {
const runtime = createRuntime();
const address = createChannelAddress({
diff --git a/packages/eve/src/channel/channel-address.ts b/packages/eve/src/channel/channel-address.ts
index 99af78893..0385928ea 100644
--- a/packages/eve/src/channel/channel-address.ts
+++ b/packages/eve/src/channel/channel-address.ts
@@ -1,7 +1,6 @@
import type { UserContent } from "ai";
import type { ChannelAdapter } from "#channel/adapter.js";
-import { copyChannelActivityPresentation } from "#channel/activity-renderer.js";
import {
createChannelDeliveryMetadata,
type ChannelDeliverySource,
@@ -131,7 +130,6 @@ export function createChannelAddress<TState = undefined>(input: {
...input.adapter,
state: { ...input.adapter.state, ...(state as Record<string, unknown>) },
};
- if (adapter !== input.adapter) copyChannelActivityPresentation(input.adapter, adapter);
const runInput: RunInput = {
adapter,
auth: options.auth,
diff --git a/packages/eve/src/channel/compiled-channel.ts b/packages/eve/src/channel/compiled-channel.ts
index 7dae800b9..0b531f2a1 100644
--- a/packages/eve/src/channel/compiled-channel.ts
+++ b/packages/eve/src/channel/compiled-channel.ts
@@ -1,8 +1,4 @@
import type { ChannelAdapter } from "#channel/adapter.js";
-import {
- attachChannelActivityPresentation,
- type ChannelActivityPresentation,
-} from "#channel/activity-renderer.js";
import type { UserContent } from "ai";
import type { ChannelReceiveContext } from "#channel/channel-operations.js";
import type { NormalizedChannelCorsOptions } from "#channel/cors.js";
@@ -111,14 +107,6 @@ export function getChannelInstrumentationKind(value: unknown): string | undefine
return routeSignature === undefined ? undefined : channelInstrumentationKinds.get(routeSignature);
}
-export function setChannelActivityRenderers(
- channel: unknown,
- input: ChannelActivityPresentation,
-): void {
- if (!isCompiledChannel(channel)) throw new TypeError("Expected a compiled channel.");
- attachChannelActivityPresentation(channel.adapter, input);
-}
-
export function setChannelInstrumentationKind(channel: CompiledChannel, kind: string): void {
Object.defineProperty(channel, CHANNEL_INSTRUMENTATION_KIND, {
configurable: true,
diff --git a/packages/eve/src/channel/session.ts b/packages/eve/src/channel/session.ts
index 9497fabbf..7817fe17e 100644
--- a/packages/eve/src/channel/session.ts
+++ b/packages/eve/src/channel/session.ts
@@ -6,7 +6,6 @@ import {
import type { MessageStreamEvent } from "#protocol/message.js";
import type { UserContent } from "ai";
import type {
- ActivityObserverConfig,
CancelTurnResult,
ClearSessionResult,
CompactSessionResult,
@@ -63,7 +62,6 @@ export interface Session {
}
interface SessionDeliveryOptions {
- readonly activityObserver?: ActivityObserverConfig;
readonly auth: SessionAuthContext | null;
/** Public callback destination for a delegated continuation turn. */
readonly callback?: SessionCallback;
@@ -107,7 +105,7 @@ export function createSession(
id,
async send(message, options) {
const delivery = createDelivery(metadata);
- const caller = sessionCallbackToTurnCaller(options.callback, options.activityObserver);
+ const caller = sessionCallbackToTurnCaller(options.callback);
const payload = attachClientContext<{
context?: readonly string[];
message: string | UserContent | undefined;
@@ -134,7 +132,7 @@ export function createSession(
throw new Error("respond() requires at least one input response.");
}
const validatedInputResponses = parseInputResponses(inputResponses);
- const caller = sessionCallbackToTurnCaller(options.callback, options.activityObserver);
+ const caller = sessionCallbackToTurnCaller(options.callback);
const delivery = createDelivery(metadata);
const payload = attachClientContext<{
context?: readonly string[];
@@ -252,12 +250,10 @@ function namespaceContinuationToken(currentToken: string, rawToken: string): str
/** @internal Converts validated public callback metadata into runtime turn routing. */
export function sessionCallbackToTurnCaller(
callback: SessionCallback | undefined,
- activityObserver?: ActivityObserverConfig,
): TurnCaller | undefined {
return callback === undefined
? undefined
: {
- activityObserver,
callId: callback.callId,
replyTo: { kind: "callback", token: callback.token, url: callback.url },
subagentName: callback.subagentName,
diff --git a/packages/eve/src/channel/task-card.ts b/packages/eve/src/channel/task-card.ts
new file mode 100644
index 000000000..2e478c8d5
--- /dev/null
+++ b/packages/eve/src/channel/task-card.ts
@@ -0,0 +1,450 @@
+import { isTaskControlTool } from "#protocol/task-tools.js";
+import type { UnstampedMessageStreamEvent } from "#protocol/message.js";
+import type { RuntimeActionRequest } from "#shared/action-types.js";
+import type { ChannelAudience } from "#shared/channel-audience.js";
+import type { JsonObject, JsonValue } from "#shared/json.js";
+import { normalizePresentationText } from "#shared/presentation-text.js";
+
+/** A call's input travels to renderers only up to this many characters of JSON. */
+const MAX_ACTION_INPUT_LENGTH = 4_096;
+/** Calls kept per turn; the oldest settled ones drop first. */
+const MAX_CALLS_PER_TURN = 100;
+const MAX_BLOCKER_LABEL_LENGTH = 200;
+
+/** How one of the turn's calls stands. */
+export type TaskCardStatus = "working" | "completed" | "failed" | "cancelled";
+
+/** What a blocked task waits on: a person's approval, answer, or sign-in. */
+export interface TaskCardBlocker {
+ readonly kind: "approval" | "authorization" | "input";
+ /**
+ * The request's prompt or the connection's name. Only in a private
+ * conversation, since a request can be sent to one person alone.
+ */
+ readonly label?: string;
+}
+
+/** One task call in a turn's task card. */
+export interface TaskCardTask {
+ /** The call's id; a resumable task called twice in a turn has two rows. */
+ readonly id: string;
+ readonly taskId: string;
+ readonly kind: "agent" | "tool";
+ /** The tool or agent name. */
+ readonly name: string;
+ /** The tool's start label, `agent: brief` for an agent, or the name. */
+ readonly title: string;
+ /** `blocked` while the task waits on a person; see {@link TaskCardTask.blockedOn}. */
+ readonly status: TaskCardStatus | "blocked";
+ readonly blockedOn?: TaskCardBlocker;
+ /**
+ * One line describing the result once settled. A failure's line appears
+ * only in a private conversation, since error text can carry internals.
+ */
+ readonly summary?: string;
+ readonly startedAt: string;
+ readonly settledAt?: string;
+}
+
+/**
+ * One of the turn's own tool calls that doesn't run as a task, such as a call
+ * to an app's `plan` tool whose input a renderer shows as rows.
+ */
+export interface TaskCardAction {
+ /** The call's id. */
+ readonly id: string;
+ /** The tool name. */
+ readonly name: string;
+ /** The tool's start label, or the name. */
+ readonly title: string;
+ readonly status: TaskCardStatus;
+ /** The call's input, when its JSON is at most 4,096 characters. */
+ readonly input?: Readonly<Record<string, unknown>>;
+ readonly startedAt: string;
+ readonly settledAt?: string;
+}
+
+/**
+ * One turn's own tool calls: the tasks it started, and its other actions,
+ * each in call order. `blocked` while any task waits on a person, `working`
+ * while the turn or any other task works, then `finished`.
+ */
+export interface TaskCardView {
+ readonly turnId: string;
+ readonly state: "working" | "blocked" | "finished";
+ readonly tasks: readonly TaskCardTask[];
+ readonly actions: readonly TaskCardAction[];
+}
+
+/** One call as a channel tracks it: plain JSON, kept in the channel's state. */
+interface TrackedCall {
+ readonly callId: string;
+ readonly name: string;
+ readonly title: string;
+ readonly status: TaskCardStatus;
+ readonly startedAt: string;
+ readonly input?: JsonObject;
+ readonly settledAt?: string;
+ readonly task?: {
+ readonly id: string;
+ readonly kind: "agent" | "tool";
+ readonly summary?: string;
+ /** Open requests and sign-ins the task waits on, oldest first. */
+ readonly blockers?: readonly (TaskCardBlocker & { readonly id: string })[];
+ };
+}
+
+/** One turn's calls as a channel tracks them from its session's own events. */
+export interface TaskCardTurn {
+ readonly calls: readonly TrackedCall[];
+ readonly ended: boolean;
+}
+
+type TurnChanges = Readonly<Record<string, TaskCardTurn>>;
+
+/**
+ * Folds one of the session's events into the turns' tracked calls, including
+ * the requests a task's run relays through the session. Returns each turn it
+ * changed, by turn id; none when the event changes no card.
+ */
+export function trackTaskCardEvent(
+ turns: Readonly<Record<string, TaskCardTurn>>,
+ event: UnstampedMessageStreamEvent,
+ at: string,
+): TurnChanges {
+ switch (event.type) {
+ case "input.requested": {
+ const { requests, taskId } = event.data;
+ if (taskId === undefined) return {};
+ const requested = requests.map((request) =>
+ blocker(
+ request.requestId,
+ request.kind === "question" ? "input" : "approval",
+ request.prompt,
+ ),
+ );
+ return updateBlockers(turns, taskId, (open) => [...open, ...requested]);
+ }
+ case "input.resolved": {
+ const resolved = new Set(event.data.resolutions.map((resolution) => resolution.requestId));
+ return updateBlockers(turns, undefined, (open) =>
+ open.filter((item) => !resolved.has(item.id)),
+ );
+ }
+ case "authorization.required": {
+ const { taskId } = event.data;
+ if (taskId === undefined) return {};
+ const id = authorizationId(event.data);
+ const label = event.data.authorization?.displayName ?? event.data.name;
+ return updateBlockers(turns, taskId, (open) => [
+ ...open.filter((item) => item.id !== id),
+ blocker(id, "authorization", label),
+ ]);
+ }
+ case "authorization.completed": {
+ const id = authorizationId(event.data);
+ return updateBlockers(turns, event.data.taskId, (open) =>
+ open.filter((item) => item.id !== id),
+ );
+ }
+ default: {
+ const changed = trackTurnEvent(turns, event, at);
+ return changed === undefined ? {} : { [changed.turnId]: changed.turn };
+ }
+ }
+}
+
+type TrackedBlocker = NonNullable<NonNullable<TrackedCall["task"]>["blockers"]>[number];
+
+function blocker(id: string, kind: TaskCardBlocker["kind"], text: string): TrackedBlocker {
+ const label = presentationText(text)?.slice(0, MAX_BLOCKER_LABEL_LENGTH);
+ return label === undefined ? { id, kind } : { id, kind, label };
+}
+
+function authorizationId(data: {
+ readonly attemptId?: string;
+ readonly candidateId?: string;
+ readonly name: string;
+}): string {
+ return data.attemptId ?? data.candidateId ?? data.name;
+}
+
+/** Applies `update` to the open blockers of each working task call, or only `taskId`'s. */
+function updateBlockers(
+ turns: Readonly<Record<string, TaskCardTurn>>,
+ taskId: string | undefined,
+ update: (open: readonly TrackedBlocker[]) => readonly TrackedBlocker[],
+): TurnChanges {
+ const changes: Record<string, TaskCardTurn> = {};
+ for (const [turnId, turn] of Object.entries(turns)) {
+ for (const call of turn.calls) {
+ if (call.task === undefined || call.status !== "working") continue;
+ if (taskId !== undefined && call.task.id !== taskId) continue;
+ const open = call.task.blockers ?? [];
+ const next = update(open);
+ if (next.length === open.length && next.every((item, index) => item.id === open[index]!.id)) {
+ continue;
+ }
+ const task = { ...call.task, blockers: next };
+ changes[turnId] = replaceCall(changes[turnId] ?? turn, { ...call, task });
+ }
+ }
+ return changes;
+}
+
+function trackTurnEvent(
+ turns: Readonly<Record<string, TaskCardTurn>>,
+ event: UnstampedMessageStreamEvent,
+ at: string,
+): { readonly turnId: string; readonly turn: TaskCardTurn } | undefined {
+ switch (event.type) {
+ case "actions.requested": {
+ const { turnId } = event.data;
+ const current = turns[turnId] ?? { calls: [], ended: false };
+ const known = new Set(current.calls.map((call) => call.callId));
+ const requested = event.data.actions.filter(
+ (action) =>
+ !known.has(action.callId) &&
+ !(action.kind === "tool-call" && isTaskControlTool(action.toolName)),
+ );
+ if (requested.length === 0) return undefined;
+ const calls = requested.map((action) =>
+ requestedCall(action, event.data.presentation?.[action.callId]?.label, at),
+ );
+ return { turn: { ...current, calls: bounded([...current.calls, ...calls]) }, turnId };
+ }
+ case "action.result": {
+ const { turnId } = event.data;
+ const current = turns[turnId];
+ const call = current?.calls.find(
+ (candidate) => candidate.callId === event.data.result.callId,
+ );
+ // A task call's result is its receipt; the task settles with `task.settled`.
+ if (current === undefined || call === undefined || call.task !== undefined) return undefined;
+ const status = actionStatus(event.data.status);
+ return { turn: replaceCall(current, { ...call, settledAt: at, status }), turnId };
+ }
+ case "task.started": {
+ const { callId, kind, name, taskId, turnId } = event.data;
+ const current = turns[turnId] ?? { calls: [], ended: false };
+ const call = current.calls.find((candidate) => candidate.callId === callId) ?? {
+ callId,
+ name,
+ startedAt: at,
+ status: "working",
+ title: name,
+ };
+ const started: TrackedCall = {
+ callId: call.callId,
+ name: call.name,
+ startedAt: call.startedAt,
+ status: "working",
+ task: { id: taskId, kind },
+ title: call.title,
+ };
+ return { turn: replaceCall(current, started), turnId };
+ }
+ case "task.settled": {
+ const { callId, status, turnId } = event.data;
+ const current = turns[turnId];
+ const call = current?.calls.find((candidate) => candidate.callId === callId);
+ if (current === undefined || call?.task === undefined) return undefined;
+ const task: {
+ -readonly [K in keyof NonNullable<TrackedCall["task"]>]: NonNullable<
+ TrackedCall["task"]
+ >[K];
+ } = {
+ id: call.task.id,
+ kind: call.task.kind,
+ };
+ const summary = taskSummary(event.data);
+ if (summary !== undefined) task.summary = summary;
+ return { turn: replaceCall(current, { ...call, settledAt: at, status, task }), turnId };
+ }
+ case "turn.completed":
+ case "turn.failed":
+ case "turn.cancelled": {
+ const current = turns[event.data.turnId];
+ if (current === undefined || current.ended) return undefined;
+ return { turn: { ...current, ended: true }, turnId: event.data.turnId };
+ }
+ default:
+ return undefined;
+ }
+}
+
+/** The view a renderer draws one turn's card from. */
+export function taskCardView(
+ turnId: string,
+ turn: TaskCardTurn,
+ options: { readonly audience: ChannelAudience },
+): TaskCardView {
+ const tasks: TaskCardTask[] = [];
+ const actions: TaskCardAction[] = [];
+ for (const call of turn.calls) {
+ if (call.task === undefined) actions.push(toAction(call));
+ else tasks.push(toTask(call, call.task, options.audience));
+ }
+ const state = tasks.some((task) => task.status === "blocked")
+ ? "blocked"
+ : !turn.ended || tasks.some((task) => task.status === "working")
+ ? "working"
+ : "finished";
+ return { actions, state, tasks, turnId };
+}
+
+/** The names of a turn's working tasks, for a status such as `Waiting on researcher...`. */
+export function workingTaskNames(turn: TaskCardTurn | undefined): readonly string[] {
+ return (turn?.calls ?? [])
+ .filter((call) => call.task !== undefined && call.status === "working")
+ .map((call) => call.name);
+}
+
+function requestedCall(
+ action: RuntimeActionRequest,
+ label: string | undefined,
+ at: string,
+): TrackedCall {
+ const name = actionName(action);
+ const call: { -readonly [K in keyof TrackedCall]: TrackedCall[K] } = {
+ callId: action.callId,
+ name,
+ startedAt: at,
+ status: "working",
+ title: presentationText(label) ?? name,
+ };
+ const input = boundedInput(action.input);
+ if (input !== undefined) call.input = input;
+ return call;
+}
+
+function toAction(call: TrackedCall): TaskCardAction {
+ const action: { -readonly [K in keyof TaskCardAction]: TaskCardAction[K] } = {
+ id: call.callId,
+ name: call.name,
+ startedAt: call.startedAt,
+ status: call.status,
+ title: call.title,
+ };
+ if (call.input !== undefined) action.input = call.input;
+ if (call.settledAt !== undefined) action.settledAt = call.settledAt;
+ return action;
+}
+
+function toTask(
+ call: TrackedCall,
+ task: NonNullable<TrackedCall["task"]>,
+ audience: ChannelAudience,
+): TaskCardTask {
+ const row: { -readonly [K in keyof TaskCardTask]: TaskCardTask[K] } = {
+ id: call.callId,
+ kind: task.kind,
+ name: call.name,
+ startedAt: call.startedAt,
+ status: call.status,
+ taskId: task.id,
+ title: call.title,
+ };
+ const shareable = audience === "private";
+ const waitingOn = call.status === "working" ? task.blockers?.at(-1) : undefined;
+ if (waitingOn !== undefined) {
+ row.status = "blocked";
+ row.blockedOn =
+ shareable && waitingOn.label !== undefined
+ ? { kind: waitingOn.kind, label: waitingOn.label }
+ : { kind: waitingOn.kind };
+ }
+ const shown = call.status !== "failed" || shareable;
+ if (task.summary !== undefined && shown) row.summary = task.summary;
+ if (call.settledAt !== undefined) row.settledAt = call.settledAt;
+ return row;
+}
+
+function replaceCall(turn: TaskCardTurn, call: TrackedCall): TaskCardTurn {
+ const known = turn.calls.some((candidate) => candidate.callId === call.callId);
+ const calls = known
+ ? turn.calls.map((candidate) => (candidate.callId === call.callId ? call : candidate))
+ : [...turn.calls, call];
+ return { ...turn, calls: bounded(calls) };
+}
+
+/** Keeps a turn within {@link MAX_CALLS_PER_TURN} by dropping its oldest settled calls. */
+function bounded(calls: readonly TrackedCall[]): readonly TrackedCall[] {
+ let overflow = calls.length - MAX_CALLS_PER_TURN;
+ if (overflow <= 0) return calls;
+ return calls.filter((call) => {
+ if (overflow > 0 && call.status !== "working") {
+ overflow -= 1;
+ return false;
+ }
+ return true;
+ });
+}
+
+function actionName(action: RuntimeActionRequest): string {
+ switch (action.kind) {
+ case "load-skill":
+ return "load_skill";
+ case "subagent-call":
+ return action.subagentName;
+ case "remote-agent-call":
+ return action.remoteAgentName;
+ default:
+ return action.toolName;
+ }
+}
+
+function actionStatus(status: string): TaskCardStatus {
+ switch (status) {
+ case "completed":
+ case "cancelled":
+ return status;
+ default:
+ return "failed";
+ }
+}
+
+function boundedInput(value: unknown): JsonObject | undefined {
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return undefined;
+ return JSON.stringify(value).length <= MAX_ACTION_INPUT_LENGTH
+ ? (value as JsonObject)
+ : undefined;
+}
+
+function taskSummary(data: {
+ readonly error?: { readonly message: string };
+ readonly output?: JsonValue;
+ readonly status: TaskCardStatus;
+}): string | undefined {
+ switch (data.status) {
+ case "completed":
+ return firstLine(resultText(data.output));
+ case "failed":
+ return firstLine(data.error?.message);
+ default:
+ return undefined;
+ }
+}
+
+/** The text a result leads with: a string result, or an agent reply's message. */
+function resultText(output: JsonValue | undefined): unknown {
+ if (typeof output === "string") return output;
+ if (output === null || typeof output !== "object" || Array.isArray(output)) return undefined;
+ const fields = output as JsonObject;
+ return fields.message ?? fields.text ?? fields.summary;
+}
+
+function firstLine(value: unknown): string | undefined {
+ if (typeof value !== "string") return undefined;
+ const line = value
+ .split(/\r?\n/u)
+ .map((candidate) => candidate.trim())
+ .find((candidate) => candidate.length > 0);
+ return presentationText(line);
+}
+
+function presentationText(value: string | undefined): string | undefined {
+ if (value === undefined) return undefined;
+ const normalized = normalizePresentationText(value);
+ return normalized === "" ? undefined : normalized;
+}
diff --git a/packages/eve/src/channel/types.ts b/packages/eve/src/channel/types.ts
index 616e86c60..7037724b9 100644
--- a/packages/eve/src/channel/types.ts
+++ b/packages/eve/src/channel/types.ts
@@ -136,7 +136,6 @@ export interface SessionAuthContext {
/** Framework-internal caller waiting for one delegated conversation turn. */
export interface TurnCaller {
- readonly activityObserver?: ActivityObserverConfig;
readonly callId: string;
readonly subagentName: string;
readonly replyTo:
@@ -367,16 +366,6 @@ export type HookPayload =
* this as its first turn's caller; each continuation supplies the caller for
* that turn.
*/
-export interface ActivitySinkV1 {
- readonly url: string;
- readonly version: 1;
-}
-
-export interface ActivityObserverConfig {
- readonly sink: ActivitySinkV1;
- readonly workIdentity?: import("#protocol/activity.js").ActivityWorkIdentityV1;
-}
-
export interface SessionCallback {
readonly callId: string;
readonly subagentName: string;
@@ -465,8 +454,6 @@ export interface RunInput {
readonly callback?: SessionCallback;
/** Set when {@link callback} belongs to a remote agent protocol 1 caller. */
readonly legacyRemoteAgentCaller?: LegacyRemoteAgentCaller;
- /** Private collector capability and current work lineage. */
- readonly activityObserver?: ActivityObserverConfig;
/**
* Session continuation token for delivery and hook creation. Channels can
* add a continuation address during the first turn via
diff --git a/packages/eve/src/compiler/extension-compatibility.ts b/packages/eve/src/compiler/extension-compatibility.ts
index a8f2a855a..523eef1f5 100644
--- a/packages/eve/src/compiler/extension-compatibility.ts
+++ b/packages/eve/src/compiler/extension-compatibility.ts
@@ -113,8 +113,8 @@ const EXTENSION_CAPABILITY_CONTRACTS = {
},
},
channel: {
- current: 37,
- supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 29, 31, 36, 37],
+ current: 38,
+ supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 29, 31, 36, 37, 38],
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 +135,8 @@ const EXTENSION_CAPABILITY_CONTRACTS = {
},
},
schedule: {
- current: 19,
- supported: [1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 18, 19],
+ current: 20,
+ supported: [1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 18, 19, 20],
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.',
diff --git a/packages/eve/src/context/keys.ts b/packages/eve/src/context/keys.ts
index 055d48118..d0d090981 100644
--- a/packages/eve/src/context/keys.ts
+++ b/packages/eve/src/context/keys.ts
@@ -7,7 +7,6 @@
import type { LanguageModel, ModelMessage, SystemModelMessage } from "ai";
import type {
- ActivityObserverConfig,
ChannelDeliveryMetadata,
ChannelInstrumentationProjection,
SessionAuthContext,
@@ -138,20 +137,6 @@ export const OtelTraceEnabledKey = new ContextKey<boolean>("eve.otelTraceEnabled
* dispatch so HITL readiness flows through a conversation chain.
*/
export const CapabilitiesKey = new ContextKey<SessionCapabilities>("eve.capabilities");
-export const ActivityObserverKey = new ContextKey<ActivityObserverConfig>("eve.activityObserver");
-/** Originating root turn that owns the current user-visible activity artifact. */
-export const ActivityRootTurnIdKey = new ContextKey<string>("eve.activityRootTurnId");
-/** Pending HITL request identities that keep the current activity artifact open. */
-export const ActivityPendingBlockersKey = new ContextKey<readonly string[]>(
- "eve.activityPendingBlockers",
-);
-/**
- * Call IDs that got `task.started` this turn, so their `action.result` is a
- * receipt that leaves the activity running. Not read from the task table: a
- * call leaves it once it settles, which can happen before its receipt is
- * published. Cleared at turn end.
- */
-export const ActivityTaskCallsKey = new ContextKey<readonly string[]>("eve.activityTaskCalls");
/**
* Optional framework-owned caller callback captured when the session is created.
diff --git a/packages/eve/src/eve-channel/activity-observer-request.ts b/packages/eve/src/eve-channel/activity-observer-request.ts
deleted file mode 100644
index fff4d9932..000000000
--- a/packages/eve/src/eve-channel/activity-observer-request.ts
+++ /dev/null
@@ -1,55 +0,0 @@
-import { parseActivitySink } from "#channel/activity-sink.js";
-import type { ActivityObserverConfig, SessionCallback } from "#channel/types.js";
-import { parseActivityWorkIdentityV1 } from "#protocol/activity.js";
-
-type BoundActivityObserverConfig = ActivityObserverConfig & {
- readonly workIdentity: NonNullable<ActivityObserverConfig["workIdentity"]>;
-};
-
-export function parseActivityObserverField(
- value: unknown,
-): BoundActivityObserverConfig | Response | undefined {
- if (value === undefined) return undefined;
- if (value === null || typeof value !== "object") {
- return invalidActivityObserver();
- }
- try {
- const sink = parseActivitySink(Reflect.get(value, "sink"));
- const workIdentity = parseActivityWorkIdentityV1(Reflect.get(value, "workIdentity"));
- if (sink === undefined || workIdentity === undefined) {
- return invalidActivityObserver();
- }
- return { sink, workIdentity };
- } catch (error) {
- return invalidActivityObserver(
- error instanceof Error ? error.message : "Invalid activity observer configuration.",
- );
- }
-}
-
-export function validateActivityObserverBinding(
- activityObserver: BoundActivityObserverConfig,
- callback: SessionCallback | undefined,
-): Response | undefined {
- if (callback === undefined) {
- return invalidBinding("Activity observer configuration requires a delegated session callback.");
- }
- if (activityObserver.workIdentity.callId !== callback.callId) {
- return invalidBinding("Activity observer callId must match the delegated session callback.");
- }
- if (activityObserver.workIdentity.name !== callback.subagentName) {
- return invalidBinding("Activity observer name must match the delegated session callback.");
- }
- if (new URL(activityObserver.sink.url).origin !== new URL(callback.url).origin) {
- return invalidBinding("Activity observer sink must share the delegated callback origin.");
- }
- return undefined;
-}
-
-function invalidActivityObserver(error = "Invalid activity observer configuration."): Response {
- return Response.json({ error, ok: false }, { status: 400 });
-}
-
-function invalidBinding(error: string): Response {
- return Response.json({ error, ok: false }, { status: 400 });
-}
diff --git a/packages/eve/src/eve-channel/create-request.ts b/packages/eve/src/eve-channel/create-request.ts
index bc9fdcedd..9f8c238c8 100644
--- a/packages/eve/src/eve-channel/create-request.ts
+++ b/packages/eve/src/eve-channel/create-request.ts
@@ -1,15 +1,10 @@
import type { UserContent } from "ai";
-import type {
- ActivityObserverConfig,
- SessionCallback,
- SessionCapabilities,
-} from "#channel/types.js";
+import type { SessionCallback, SessionCapabilities } from "#channel/types.js";
import type { LegacyRemoteAgentCaller } from "#execution/legacy-remote-agent/protocol.js";
import type { JsonObject } from "#shared/json.js";
export interface ParsedCreateBody {
- activityObserver?: ActivityObserverConfig;
callback?: SessionCallback;
capabilities?: SessionCapabilities;
message?: string | UserContent;
@@ -23,7 +18,6 @@ export interface ParsedCreateBody {
/** Enforces the fields that only make sense when creation also starts a turn. */
export function validateMessageFreeCreate(input: {
- readonly activityObserver: ActivityObserverConfig | undefined;
readonly callback: SessionCallback | undefined;
readonly hasClientContext: boolean;
readonly hasMessageField: boolean;
@@ -37,16 +31,11 @@ export function validateMessageFreeCreate(input: {
);
}
if (input.message !== undefined) return undefined;
- if (
- input.hasClientContext ||
- input.callback !== undefined ||
- input.activityObserver !== undefined ||
- input.outputSchema !== undefined
- ) {
+ if (input.hasClientContext || input.callback !== undefined || input.outputSchema !== undefined) {
return Response.json(
{
error:
- "Creating a session without a message does not accept 'clientContext', 'callback', 'activityObserver', or 'outputSchema'.",
+ "Creating a session without a message does not accept 'clientContext', 'callback', or 'outputSchema'.",
ok: false,
},
{ status: 400 },
diff --git a/packages/eve/src/eve-channel/index.ts b/packages/eve/src/eve-channel/index.ts
index 8b4e6b562..5df1d28b1 100644
--- a/packages/eve/src/eve-channel/index.ts
+++ b/packages/eve/src/eve-channel/index.ts
@@ -4,7 +4,6 @@ import type { SessionAuthContext, SessionParent, SessionTraceContext } from "#ch
import type { Session } from "#channel/session.js";
import { resolveForwardedPrincipal } from "#channel/forwarded-principal.js";
import { handleConnectionCallbackRequest } from "#execution/connections/callback-route.js";
-import { handleActivityRequest } from "#execution/activity-route.js";
import { handleSessionCallbackRequest } from "#subagents/callback-route.js";
import {
handleWorkflowWebhookRequest,
@@ -25,7 +24,6 @@ import {
} from "#protocol/message.js";
import { legacyTaskInputRoute } from "#execution/legacy-remote-agent/protocol.js";
import {
- EVE_ACTIVITY_ROUTE_PATTERN,
EVE_CALLBACK_ROUTE_PATTERN,
EVE_CONNECTION_CALLBACK_ROUTE_PATTERN,
EVE_HEALTH_ROUTE_PATH,
@@ -150,7 +148,6 @@ export function eveChannel(input: EveChannelInput): EveChannel {
),
GET(EVE_CONNECTION_CALLBACK_ROUTE_PATTERN, handleConnectionCallbackRequest),
POST(EVE_CONNECTION_CALLBACK_ROUTE_PATTERN, handleConnectionCallbackRequest),
- POST(EVE_ACTIVITY_ROUTE_PATTERN, handleActivityRequest),
POST(EVE_CALLBACK_ROUTE_PATTERN, handleSessionCallbackRequest),
POST(legacyTaskInputRoute.path, legacyTaskInputRoute.handler),
GET(WORKFLOW_WEBHOOK_ROUTE_PATTERN, handleWorkflowWebhookRequest),
@@ -327,7 +324,6 @@ export function eveChannel(input: EveChannelInput): EveChannel {
let handle: Awaited<ReturnType<typeof createSession>>;
try {
handle = await createSession({
- activityObserver: body.activityObserver,
audienceAuth: authResult,
auth: messageResult.auth,
capabilities: body.capabilities ?? { requestInput: true },
@@ -410,7 +406,6 @@ export function eveChannel(input: EveChannelInput): EveChannel {
const session = attachSession(sessionId);
const options = attachClientContext(
{
- activityObserver: body.activityObserver,
auth: dispatchAuth,
callback: body.callback,
context,
diff --git a/packages/eve/src/eve-channel/request.activity.test.ts b/packages/eve/src/eve-channel/request.activity.test.ts
deleted file mode 100644
index c3b0c1ca8..000000000
--- a/packages/eve/src/eve-channel/request.activity.test.ts
+++ /dev/null
@@ -1,71 +0,0 @@
-import { describe, expect, it } from "vitest";
-
-import { parseCreateBody } from "#eve-channel/request.js";
-import { REMOTE_AGENT_PROTOCOL_VERSION } from "#protocol/remote-agent-protocol.js";
-
-const sink = {
- url: "https://parent.example.com/eve/v1/activity/abcdefghijklmnopqrstuvwxyz123456",
- version: 1 as const,
-};
-const callback = {
- callId: "call-1",
- subagentName: "researcher",
- token: "parent-callback-token",
- url: "https://parent.example.com/eve/v1/callback/parent-callback-token",
-};
-const workIdentity = {
- callId: "call-1",
- id: "work:parent:turn-1:call-1",
- kind: "remote-agent" as const,
- name: "researcher",
- parentId: "root:parent:turn-1",
- rootSessionId: "parent",
- rootTurnId: "turn-1",
-};
-
-describe("parseCreateBody activity relay", () => {
- it("accepts activity observer configuration bound to a delegated callback", () => {
- expect(
- parseCreateBody({
- callback,
- activityObserver: { sink, workIdentity },
- message: "research this",
- protocolVersion: REMOTE_AGENT_PROTOCOL_VERSION,
- }),
- ).toMatchObject({ callback, activityObserver: { sink, workIdentity } });
- });
-
- it("rejects activity observer configuration without a delegated callback", () => {
- const response = parseCreateBody({ activityObserver: { sink, workIdentity }, message: "hi" });
- expect(response).toBeInstanceOf(Response);
- expect((response as Response).status).toBe(400);
- });
-
- it.each([
- ["callId", { ...workIdentity, callId: "other" }],
- ["name", { ...workIdentity, name: "other" }],
- ])("rejects a mismatched %s", (_field, identity) => {
- const response = parseCreateBody({
- callback,
- activityObserver: { sink, workIdentity: identity },
- message: "hi",
- protocolVersion: REMOTE_AGENT_PROTOCOL_VERSION,
- });
- expect(response).toBeInstanceOf(Response);
- expect((response as Response).status).toBe(400);
- });
-
- it("rejects a sink on a different callback origin", () => {
- const response = parseCreateBody({
- callback,
- activityObserver: {
- sink: { ...sink, url: sink.url.replace("parent.example.com", "other.example.com") },
- workIdentity,
- },
- message: "hi",
- protocolVersion: REMOTE_AGENT_PROTOCOL_VERSION,
- });
- expect(response).toBeInstanceOf(Response);
- expect((response as Response).status).toBe(400);
- });
-});
diff --git a/packages/eve/src/eve-channel/request.test.ts b/packages/eve/src/eve-channel/request.test.ts
index 86f7d39ff..f5f5f37da 100644
--- a/packages/eve/src/eve-channel/request.test.ts
+++ b/packages/eve/src/eve-channel/request.test.ts
@@ -1,11 +1,11 @@
import { describe, expect, it } from "vitest";
import { parseCreateBody } from "#eve-channel/request.js";
+import { REMOTE_AGENT_PROTOCOL_VERSION } from "#protocol/remote-agent-protocol.js";
describe("parseCreateBody", () => {
it("accepts a conversation session without a message", () => {
expect(parseCreateBody({})).toEqual({
- activityObserver: undefined,
callback: undefined,
capabilities: undefined,
context: undefined,
@@ -13,6 +13,26 @@ describe("parseCreateBody", () => {
});
});
+ it("accepts a delegated call from an older eve that still sends an activity observer", () => {
+ const callback = {
+ callId: "call-1",
+ subagentName: "researcher",
+ token: "parent-callback-token",
+ url: "https://parent.example.com/eve/v1/callback/parent-callback-token",
+ };
+ const body = parseCreateBody({
+ activityObserver: {
+ sink: { url: "https://parent.example.com/eve/v1/activity/x", version: 1 },
+ },
+ callback,
+ message: "research this",
+ protocolVersion: REMOTE_AGENT_PROTOCOL_VERSION,
+ });
+
+ expect(body).toEqual(expect.objectContaining({ callback, message: "research this" }));
+ expect(body).not.toHaveProperty("activityObserver");
+ });
+
it("rejects an explicitly empty message", async () => {
const response = parseCreateBody({ message: "" });
expect(response).toBeInstanceOf(Response);
diff --git a/packages/eve/src/eve-channel/request.ts b/packages/eve/src/eve-channel/request.ts
index b001694e2..df9c8f3b8 100644
--- a/packages/eve/src/eve-channel/request.ts
+++ b/packages/eve/src/eve-channel/request.ts
@@ -1,7 +1,6 @@
import type { FilePart, TextPart, UserContent } from "ai";
import type {
- ActivityObserverConfig,
SessionAuthContext,
SessionCallback,
SessionCapabilities,
@@ -9,10 +8,6 @@ import type {
} from "#channel/types.js";
import type { Session } from "#channel/session.js";
import { parseSessionCallback } from "#channel/session-callback.js";
-import {
- parseActivityObserverField,
- validateActivityObserverBinding,
-} from "#eve-channel/activity-observer-request.js";
import { hasInternalRefScheme } from "#internal/attachments/url-refs.js";
import {
EVE_MESSAGE_STREAM_CONTENT_TYPE,
@@ -92,18 +87,10 @@ export function parseCreateBody(input: Record<string, unknown>): ParsedCreateBod
const capabilities = parseCapabilitiesField(payload.capabilities);
if (capabilities instanceof Response) return capabilities;
- const activityObserver = parseActivityObserverField(payload.activityObserver);
- if (activityObserver instanceof Response) return activityObserver;
- if (activityObserver !== undefined) {
- const observerRejection = validateActivityObserverBinding(activityObserver, callback);
- if (observerRejection !== undefined) return observerRejection;
- }
-
const outputSchema = parseOutputSchemaField(payload.outputSchema);
if (outputSchema instanceof Response) return outputSchema;
const messageFreeRejection = validateMessageFreeCreate({
- activityObserver,
callback,
hasClientContext: payload.clientContext !== undefined,
hasMessageField: "message" in payload,
@@ -121,7 +108,6 @@ export function parseCreateBody(input: Record<string, unknown>): ParsedCreateBod
}
const result: ParsedCreateBody = {
- activityObserver,
callback,
capabilities,
context,
@@ -137,7 +123,6 @@ export function parseCreateBody(input: Record<string, unknown>): ParsedCreateBod
}
interface ParsedSessionMessageBody {
- activityObserver?: ActivityObserverConfig;
callback?: SessionCallback;
message?: string | UserContent;
inputResponses?: readonly ValidatedInputResponse[];
@@ -157,12 +142,6 @@ export function parseSessionMessageBody(
if (message instanceof Response) return message;
const callback = parseCallbackField(payload.callback);
if (callback instanceof Response) return callback;
- const activityObserver = parseActivityObserverField(payload.activityObserver);
- if (activityObserver instanceof Response) return activityObserver;
- if (activityObserver !== undefined) {
- const observerRejection = validateActivityObserverBinding(activityObserver, callback);
- if (observerRejection !== undefined) return observerRejection;
- }
const inputResponses = parseInputResponses(payload.inputResponses);
if (inputResponses instanceof Response) return inputResponses;
const context = parseClientContextField(payload.clientContext);
@@ -190,7 +169,6 @@ export function parseSessionMessageBody(
}
return {
- activityObserver,
callback,
message,
inputResponses,
diff --git a/packages/eve/src/execution/activity-cohort.test.ts b/packages/eve/src/execution/activity-cohort.test.ts
deleted file mode 100644
index f6d01f5d4..000000000
--- a/packages/eve/src/execution/activity-cohort.test.ts
+++ /dev/null
@@ -1,40 +0,0 @@
-import { describe, expect, it } from "vitest";
-
-import { ContextContainer } from "#context/container.js";
-import { ActivityPendingBlockersKey, ActivityRootTurnIdKey } from "#context/keys.js";
-import { restoreAuthorizationActivity } from "#execution/activity-cohort.js";
-import { matchAuthorizationCallbacks } from "#execution/authorization-callback-match.js";
-
-describe("restoreAuthorizationActivity", () => {
- it("restores authorization activity by attempt ID", () => {
- const ctx = new ContextContainer();
- const pending = {
- activityRootTurnIds: { "attempt-1": "turn-origin" },
- challenges: [
- {
- attemptId: "attempt-1",
- candidateId: "candidate-1",
- challenge: { url: "https://auth.example.com" },
- hookUrl: "https://app.example.com/callback",
- name: "github",
- principal: { type: "app" as const },
- },
- ],
- };
- const { matches } = matchAuthorizationCallbacks(pending, [
- {
- authorizationCallback: {
- attemptId: "attempt-1",
- callback: { params: { code: "callback-code" } },
- connectionName: "github",
- },
- },
- ]);
-
- const ids = restoreAuthorizationActivity({ ctx, matches, pending });
-
- expect(ids).toEqual(["attempt-1"]);
- expect(ctx.get(ActivityRootTurnIdKey)).toBe("turn-origin");
- expect(ctx.get(ActivityPendingBlockersKey)).toBeUndefined();
- });
-});
diff --git a/packages/eve/src/execution/activity-cohort.ts b/packages/eve/src/execution/activity-cohort.ts
deleted file mode 100644
index 50e8c0871..000000000
--- a/packages/eve/src/execution/activity-cohort.ts
+++ /dev/null
@@ -1,157 +0,0 @@
-import type { DeliverHookPayload } from "#channel/types.js";
-import type { MatchedAuthorizationCallback } from "#execution/authorization-callback-match.js";
-import { getPendingAuthorization, type PendingAuthorizationState } from "#harness/authorization.js";
-import type { ContextContainer } from "#context/container.js";
-import {
- ActivityObserverKey,
- ActivityPendingBlockersKey,
- ActivityRootTurnIdKey,
- ActivityTaskCallsKey,
-} from "#context/keys.js";
-import { isSessionLimitPromptBatch } from "#harness/hitl/session-limit-input-requests.js";
-import {
- activityRequestIdsForRootTurn,
- activityRootTurnIdForInputResponses,
- getPendingInputBatches,
-} from "#harness/pending-input-batches.js";
-import type { SessionStateMap } from "#harness/types.js";
-import type { UnstampedMessageStreamEvent } from "#protocol/message.js";
-
-export function updateActivityRootForDelivery(input: {
- readonly activeTurnId: string;
- readonly ctx: ContextContainer;
- readonly delivery?: DeliverHookPayload;
- readonly sessionState: SessionStateMap | undefined;
-}): void {
- if (!input.ctx.has(ActivityObserverKey)) return;
- const delivery = input.delivery;
- if (delivery === undefined) return;
- const hasMessage = delivery.payloads.some((payload) => payload.message !== undefined);
- if (hasMessage) {
- input.ctx.set(ActivityRootTurnIdKey, input.activeTurnId);
- input.ctx.delete(ActivityPendingBlockersKey);
- return;
- }
- const responseIds = new Set(
- delivery.payloads.flatMap((payload) =>
- (payload.inputResponses ?? []).map((response) => response.requestId),
- ),
- );
- if (responseIds.size === 0) return;
- const rootTurnId =
- activityRootTurnIdForInputResponses(input.sessionState, responseIds) ??
- input.ctx.get(ActivityRootTurnIdKey) ??
- input.activeTurnId;
- input.ctx.set(ActivityRootTurnIdKey, rootTurnId);
- input.ctx.set(
- ActivityPendingBlockersKey,
- activityRequestIdsForRootTurn(input.sessionState, rootTurnId),
- );
-}
-
-export function restoreAuthorizationActivity(input: {
- readonly ctx: ContextContainer;
- readonly matches: readonly MatchedAuthorizationCallback[];
- readonly pending: PendingAuthorizationState;
-}): readonly string[] {
- const ids = input.matches.map((match) => match.result.attemptId);
- const rootTurnId = ids.map((id) => input.pending.activityRootTurnIds?.[id]).find(Boolean);
- if (rootTurnId !== undefined) {
- input.ctx.set(ActivityRootTurnIdKey, rootTurnId);
- input.ctx.set(
- ActivityPendingBlockersKey,
- Object.entries(input.pending.activityRootTurnIds ?? {}).flatMap(([id, candidateRoot]) =>
- candidateRoot === rootTurnId ? [id] : [],
- ),
- );
- }
- clearActivityBlockers(input.ctx, ids);
- return ids;
-}
-
-/** Tracks the pending blockers and task calls that activity projection reads. */
-export function updateActivityState(
- ctx: ContextContainer,
- event: UnstampedMessageStreamEvent,
-): void {
- if (!ctx.has(ActivityObserverKey)) return;
- if (event.type === "task.started") {
- addActivityTaskCall(ctx, event.data.callId);
- } else if (
- event.type === "turn.completed" ||
- event.type === "turn.failed" ||
- event.type === "turn.cancelled"
- ) {
- // Every receipt of the turn's task calls is published before the turn ends.
- ctx.delete(ActivityTaskCallsKey);
- } else if (event.type === "input.requested") {
- addActivityBlockers(
- ctx,
- event.data.requests.map((request) => request.requestId),
- );
- } else if (event.type === "input.resolved") {
- clearActivityBlockers(
- ctx,
- event.data.resolutions.map((resolution) => resolution.requestId),
- );
- } else if (event.type === "authorization.required") {
- addActivityBlockers(ctx, [authorizationBlockerId(event)]);
- } else if (event.type === "authorization.completed") {
- clearActivityBlockers(ctx, [authorizationBlockerId(event)]);
- }
-}
-
-/**
- * Keeps only the blockers a cancel leaves answerable: the session's own input
- * requests and sign-ins. The cancel withdraws a session-limit prompt and what
- * a child asked through the session, so those no longer hold its work open.
- */
-export function retainAnswerableActivityBlockers(
- ctx: ContextContainer,
- sessionState: SessionStateMap | undefined,
-): void {
- const pending = ctx.get(ActivityPendingBlockersKey);
- if (pending === undefined) return;
- const answerable = new Set([
- ...getPendingInputBatches(sessionState).flatMap((batch) =>
- isSessionLimitPromptBatch(batch) ? [] : batch.requests.map((request) => request.requestId),
- ),
- ...(getPendingAuthorization(sessionState)?.challenges ?? []).flatMap(
- (challenge) => challenge.attemptId ?? challenge.candidateId ?? [],
- ),
- ]);
- clearActivityBlockers(
- ctx,
- pending.filter((id) => !answerable.has(id)),
- );
-}
-
-export function clearActivityBlockers(ctx: ContextContainer, ids: readonly string[]): void {
- const cleared = new Set(ids);
- const remaining = (ctx.get(ActivityPendingBlockersKey) ?? []).filter((id) => !cleared.has(id));
- if (remaining.length === 0) ctx.delete(ActivityPendingBlockersKey);
- else ctx.set(ActivityPendingBlockersKey, remaining);
-}
-
-function addActivityTaskCall(ctx: ContextContainer, callId: string): void {
- ctx.set(ActivityTaskCallsKey, [...(ctx.get(ActivityTaskCallsKey) ?? []), callId]);
-}
-
-function addActivityBlockers(ctx: ContextContainer, ids: readonly string[]): void {
- ctx.set(ActivityPendingBlockersKey, [
- ...new Set([...(ctx.get(ActivityPendingBlockersKey) ?? []), ...ids]),
- ]);
-}
-
-function authorizationBlockerId(
- event: Extract<
- UnstampedMessageStreamEvent,
- { readonly type: "authorization.required" | "authorization.completed" }
- >,
-): string {
- return (
- event.data.attemptId ??
- event.data.candidateId ??
- `${event.data.turnId}:${String(event.data.stepIndex)}:${event.data.name}`
- );
-}
diff --git a/packages/eve/src/execution/activity-collector.test.ts b/packages/eve/src/execution/activity-collector.test.ts
deleted file mode 100644
index aee659e94..000000000
--- a/packages/eve/src/execution/activity-collector.test.ts
+++ /dev/null
@@ -1,167 +0,0 @@
-import { beforeEach, describe, expect, it, vi } from "vitest";
-
-import {
- activityCollectorWorkflow,
- reduceCollectorActivity,
-} from "#execution/activity-collector.js";
-import { createActivitySnapshot } from "#execution/session-activity.js";
-import type { ActivityBatchV1 } from "#protocol/activity.js";
-
-const mocks = vi.hoisted(() => ({
- createHook: vi.fn(),
- disposeSessionActivityStep: vi.fn(),
- renderSessionActivityStep: vi.fn(),
- sleep: vi.fn(),
-}));
-
-vi.mock("#compiled/@workflow/core/index.js", async (importOriginal) => ({
- ...(await importOriginal<typeof import("#compiled/@workflow/core/index.js")>()),
- createHook: mocks.createHook,
- sleep: mocks.sleep,
-}));
-vi.mock("#execution/session-activity-renderer-step.js", () => ({
- disposeSessionActivityStep: mocks.disposeSessionActivityStep,
- renderSessionActivityStep: mocks.renderSessionActivityStep,
-}));
-
-beforeEach(() => {
- vi.resetAllMocks();
- mocks.disposeSessionActivityStep.mockResolvedValue(undefined);
-});
-
-const work = {
- id: "root:work",
- kind: "root-turn" as const,
- rootSessionId: "session",
- rootTurnId: "turn",
-};
-
-describe("activityCollectorWorkflow", () => {
- it("flushes the final buffered snapshot when the activity stream closes", async () => {
- mocks.sleep.mockImplementation(() => new Promise<void>(() => {}));
- mocks.createHook.mockReturnValue({
- token: "activity",
- getConflict: async () => null,
- async *[Symbol.asyncIterator]() {
- yield {
- events: [{ eventId: "start", kind: "work.started", startedAt: "1", work }],
- version: 1,
- } satisfies ActivityBatchV1;
- yield {
- events: [
- {
- eventId: "settled",
- kind: "work.settled",
- outcome: "completed",
- settledAt: "2",
- workId: work.id,
- },
- ],
- version: 1,
- } satisfies ActivityBatchV1;
- },
- });
- mocks.renderSessionActivityStep.mockResolvedValue({ rendererStates: { slack: "rendered" } });
-
- await expect(
- activityCollectorWorkflow({
- expiresAt: "2026-09-04T00:00:00Z",
- serializedContext: {},
- token: "activity",
- }),
- ).resolves.toBeUndefined();
-
- expect(mocks.renderSessionActivityStep).toHaveBeenCalledExactlyOnceWith({
- rendererStates: {},
- serializedContext: {},
- snapshot: expect.objectContaining({
- work: expect.objectContaining({
- [work.id]: expect.objectContaining({ phase: "completed", settledAt: "2" }),
- }),
- }),
- });
- expect(mocks.disposeSessionActivityStep).toHaveBeenCalledExactlyOnceWith({
- rendererStates: { slack: "rendered" },
- serializedContext: {},
- });
- });
-
- it.each([false, true])(
- "expires with a pending hook read (debouncing: %s)",
- async (debouncing) => {
- const expiry = Promise.withResolvers<void>();
- const reading = Promise.withResolvers<void>();
- mocks.sleep.mockImplementation((duration: Date | number) =>
- duration instanceof Date ? expiry.promise : new Promise<void>(() => {}),
- );
- mocks.createHook.mockReturnValue({
- token: "activity",
- getConflict: async () => null,
- async *[Symbol.asyncIterator]() {
- if (debouncing) {
- yield {
- events: [{ eventId: "start", kind: "work.started", startedAt: "1", work }],
- version: 1,
- } satisfies ActivityBatchV1;
- }
- reading.resolve();
- yield await new Promise<ActivityBatchV1>(() => {});
- },
- });
-
- const result = activityCollectorWorkflow({
- expiresAt: "2026-09-04T00:00:00Z",
- serializedContext: {},
- token: "activity",
- });
- await reading.promise;
- expiry.resolve();
-
- await expect(result).resolves.toBeUndefined();
- expect(mocks.disposeSessionActivityStep).toHaveBeenCalledExactlyOnceWith({
- rendererStates: {},
- serializedContext: {},
- });
- },
- 1_000,
- );
-});
-
-describe("reduceCollectorActivity", () => {
- it("marks only presentation revision advances as changed", () => {
- const visible = reduceCollectorActivity(createActivitySnapshot(), {
- events: [{ eventId: "start", kind: "work.started", startedAt: "1", work }],
- version: 1,
- });
- expect(visible.presentationChanged).toBe(true);
-
- const bookkeeping = reduceCollectorActivity(visible.snapshot, {
- events: [
- {
- blockerId: "missing",
- eventId: "settled-before-start",
- kind: "blocker.settled",
- outcome: "completed",
- settledAt: "2",
- },
- ],
- version: 1,
- });
- expect(bookkeeping.presentationChanged).toBe(false);
- expect(bookkeeping.snapshot.revision).toBe(visible.snapshot.revision);
-
- const settled = reduceCollectorActivity(bookkeeping.snapshot, {
- events: [
- {
- eventId: "work-settled",
- kind: "work.settled",
- outcome: "completed",
- settledAt: "3",
- workId: work.id,
- },
- ],
- version: 1,
- });
- expect(settled.presentationChanged).toBe(true);
- });
-});
diff --git a/packages/eve/src/execution/activity-collector.ts b/packages/eve/src/execution/activity-collector.ts
deleted file mode 100644
index 04aa402de..000000000
--- a/packages/eve/src/execution/activity-collector.ts
+++ /dev/null
@@ -1,87 +0,0 @@
-import { createHook, sleep } from "#compiled/@workflow/core/index.js";
-
-import { claimHookOwnership, isHookConflictError } from "#execution/hook-ownership.js";
-import { createActivitySnapshot, reduceActivityBatch } from "#execution/session-activity.js";
-import type { ActivityBatchV1, ActivitySnapshotV1 } from "#protocol/activity.js";
-import {
- disposeSessionActivityStep,
- renderSessionActivityStep,
-} from "#execution/session-activity-renderer-step.js";
-
-const RENDER_DEBOUNCE_MS = 350;
-
-export interface ActivityCollectorInput {
- readonly expiresAt: string;
- readonly serializedContext: Record<string, unknown>;
- readonly token: string;
-}
-
-/** Independently owns activity reduction and provider presentation for one root session. */
-export async function activityCollectorWorkflow(input: ActivityCollectorInput): Promise<void> {
- "use workflow";
-
- const batches = createHook<ActivityBatchV1>({ token: input.token });
- const iterator = batches[Symbol.asyncIterator]();
- let pendingRead: Promise<IteratorResult<ActivityBatchV1>> | undefined;
- const expiry = sleep(new Date(input.expiresAt)).then(() => ({ kind: "expired" as const }));
- let snapshot = createActivitySnapshot();
- let rendererStates: Readonly<Record<string, unknown>> = {};
-
- try {
- await claimHookOwnership(batches);
- } catch (error) {
- if (isHookConflictError(error)) return;
- throw error;
- }
-
- try {
- while (true) {
- pendingRead ??= iterator.next();
- const next = await Promise.race([
- pendingRead.then((value) => ({ kind: "batch" as const, value })),
- expiry,
- ]);
- if (next.kind === "expired" || next.value.done === true) break;
- pendingRead = undefined;
- const reduced = reduceCollectorActivity(snapshot, next.value.value);
- snapshot = reduced.snapshot;
- if (!reduced.presentationChanged) continue;
-
- const debounce = sleep(RENDER_DEBOUNCE_MS).then(() => ({ kind: "render" as const }));
- while (true) {
- pendingRead ??= iterator.next();
- const buffered = await Promise.race([
- pendingRead.then((value) => ({ kind: "batch" as const, value })),
- debounce,
- expiry,
- ]);
- if (buffered.kind === "expired") return;
- if (buffered.kind === "render") break;
- if (buffered.value.done === true) break;
- pendingRead = undefined;
- snapshot = reduceActivityBatch(snapshot, buffered.value.value);
- }
-
- const rendered = await renderSessionActivityStep({
- rendererStates,
- serializedContext: input.serializedContext,
- snapshot,
- });
- rendererStates = rendered.rendererStates;
- }
- } finally {
- await disposeSessionActivityStep({
- rendererStates,
- serializedContext: input.serializedContext,
- }).catch(() => {});
- }
-}
-
-export function reduceCollectorActivity(
- snapshot: ActivitySnapshotV1,
- batch: ActivityBatchV1,
-): { readonly presentationChanged: boolean; readonly snapshot: ActivitySnapshotV1 } {
- const previousRevision = snapshot.revision;
- const next = reduceActivityBatch(snapshot, batch);
- return { presentationChanged: next.revision !== previousRevision, snapshot: next };
-}
diff --git a/packages/eve/src/execution/activity-events.test.ts b/packages/eve/src/execution/activity-events.test.ts
deleted file mode 100644
index 133be1a83..000000000
--- a/packages/eve/src/execution/activity-events.test.ts
+++ /dev/null
@@ -1,321 +0,0 @@
-import { describe, expect, it } from "vitest";
-
-import { projectActivityEvents } from "#execution/activity-events.js";
-import { deriveChildActivityWorkId } from "#execution/activity-work-id.js";
-import { MAX_ACTIVITY_TEXT_LENGTH } from "#shared/presentation-text.js";
-
-const lineage = {
- id: "work:root:turn",
- kind: "root-turn" as const,
- rootSessionId: "root",
- rootTurnId: "turn",
-};
-
-describe("projectActivityEvents", () => {
- it("projects tools and skills without inputs", () => {
- expect(
- projectActivityEvents({
- at: "2026-01-01T00:00:00Z",
- event: {
- data: {
- actions: [
- {
- callId: "tool-1",
- input: { secret: "hidden" },
- kind: "tool-call",
- toolName: "search",
- },
- { callId: "skill-1", input: { skill: "private" }, kind: "load-skill" },
- ],
- presentation: { "tool-1": { label: "Search issues" } },
- sequence: 0,
- stepIndex: 0,
- turnId: "turn",
- },
- type: "actions.requested",
- },
- lineage,
- }),
- ).toEqual([
- expect.objectContaining({
- action: expect.objectContaining({
- id: "action:work:root:turn:tool-1",
- kind: "tool",
- name: "search",
- stepIndex: 0,
- }),
- kind: "action.started",
- }),
- expect.objectContaining({
- actionId: "action:work:root:turn:tool-1",
- kind: "action.label.updated",
- label: "Search issues",
- }),
- expect.objectContaining({
- action: expect.objectContaining({
- id: "action:work:root:turn:skill-1",
- kind: "skill",
- name: "load_skill",
- stepIndex: 0,
- }),
- kind: "action.started",
- }),
- ]);
- });
-
- it("projects no activity for the model's own task calls", () => {
- const at = "2026-01-01T00:00:00Z";
- const turn = { sequence: 0, stepIndex: 0, turnId: "turn" };
- expect(
- [
- projectActivityEvents({
- at,
- event: {
- data: {
- ...turn,
- actions: [
- { callId: "wait-1", input: {}, kind: "tool-call", toolName: "task_wait" },
- {
- callId: "cancel-1",
- input: { taskId: "t1" },
- kind: "tool-call",
- toolName: "task_cancel",
- },
- ],
- },
- type: "actions.requested",
- },
- lineage,
- }),
- projectActivityEvents({
- at,
- event: {
- data: {
- ...turn,
- result: {
- callId: "wait-1",
- kind: "tool-result",
- output: "done",
- toolName: "task_wait",
- },
- status: "completed",
- },
- type: "action.result",
- },
- lineage,
- }),
- ].flat(),
- ).toEqual([]);
- });
-
- it("normalizes and bounds authorization blocker labels", () => {
- const [event] = projectActivityEvents({
- at: "2026-01-01T00:00:00Z",
- event: {
- data: {
- attemptId: "attempt-1",
- authorization: { displayName: `Sign\u0000 in ${"x".repeat(600)}` },
- description: "Authorize",
- name: "provider",
- sequence: 0,
- stepIndex: 0,
- turnId: "turn",
- },
- type: "authorization.required",
- },
- lineage,
- });
-
- expect(event?.kind).toBe("blocker.started");
- if (event?.kind !== "blocker.started") return;
- expect(event.blocker.label).not.toContain("\u0000");
- expect(event.blocker.label).toHaveLength(MAX_ACTIVITY_TEXT_LENGTH);
- });
-
- it("normalizes and bounds input blocker labels", () => {
- const [event] = projectActivityEvents({
- at: "2026-01-01T00:00:00Z",
- event: {
- data: {
- requests: [
- {
- action: { callId: "tool-1", input: {}, kind: "tool-call", toolName: "search" },
- kind: "question",
- prompt: `Choose\u0007 ${"y".repeat(600)}`,
- requestId: "request-1",
- },
- ],
- sequence: 0,
- stepIndex: 0,
- turnId: "turn",
- },
- type: "input.requested",
- },
- lineage,
- });
-
- expect(event?.kind).toBe("blocker.started");
- if (event?.kind !== "blocker.started") return;
- expect(event.blocker.label).not.toContain("\u0007");
- expect(event.blocker.label).toHaveLength(MAX_ACTIVITY_TEXT_LENGTH);
- });
-
- it("projects safe tool updates from partial events", () => {
- expect(
- projectActivityEvents({
- at: "2026-01-01T00:00:01Z",
- event: {
- data: {
- presentation: { "tool-1": { label: "Collecting sources" } },
- result: {
- callId: "tool-1",
- kind: "tool-result",
- output: { secret: "hidden" },
- toolName: "search",
- },
- sequence: 0,
- stepIndex: 0,
- turnId: "turn",
- },
- type: "action.partial",
- },
- eventId: "partial-1",
- lineage,
- }),
- ).toEqual([
- {
- actionId: "action:work:root:turn:tool-1",
- eventId: "action:work:root:turn:tool-1:update:partial-1",
- kind: "action.label.updated",
- label: "Collecting sources",
- },
- ]);
- });
-
- it("projects successful result text before tool settlement", () => {
- expect(
- projectActivityEvents({
- at: "2026-01-01T00:00:02Z",
- event: {
- data: {
- presentation: { "tool-1": { label: "Report ready" } },
- result: {
- callId: "tool-1",
- kind: "tool-result",
- output: { report: "hidden" },
- toolName: "build_report",
- },
- sequence: 0,
- status: "completed",
- stepIndex: 0,
- turnId: "turn",
- },
- type: "action.result",
- },
- eventId: "result-1",
- lineage,
- }),
- ).toEqual([
- {
- actionId: "action:work:root:turn:tool-1",
- eventId: "action:work:root:turn:tool-1:result:result-1",
- kind: "action.label.updated",
- label: "Report ready",
- },
- {
- actionId: "action:work:root:turn:tool-1",
- eventId: "action:work:root:turn:tool-1:settled:completed",
- kind: "action.settled",
- outcome: "completed",
- settledAt: "2026-01-01T00:00:02Z",
- },
- ]);
- });
-
- it("projects safe failed tool settlement", () => {
- expect(
- projectActivityEvents({
- at: "2026-01-01T00:00:01Z",
- event: {
- data: {
- error: { code: "FAILED", message: "private detail" },
- result: {
- callId: "tool-1",
- isError: true,
- kind: "tool-result",
- output: { secret: "hidden" },
- toolName: "search",
- },
- sequence: 0,
- status: "failed",
- stepIndex: 0,
- turnId: "turn",
- },
- type: "action.result",
- },
- lineage,
- }),
- ).toEqual([
- {
- actionId: "action:work:root:turn:tool-1",
- eventId: "action:work:root:turn:tool-1:settled:failed",
- kind: "action.settled",
- outcome: "failed",
- settledAt: "2026-01-01T00:00:01Z",
- },
- ]);
- });
-
- it("settles delegated work from its parent action result", () => {
- const workId = deriveChildActivityWorkId({
- callId: "child-1",
- parentSessionId: "root",
- parentTurnId: "turn",
- });
- const parentLineage = {
- ...lineage,
- sessionId: "root",
- turnId: "turn",
- };
- expect(
- projectActivityEvents({
- at: "2026-01-01T00:00:02Z",
- event: {
- data: {
- result: {
- callId: "child-1",
- kind: "subagent-result",
- origin: "child",
- outcome: {
- kind: "terminal",
- result: { kind: "succeeded", output: "done" },
- usageDelta: {
- cacheReadTokens: 0,
- cacheWriteTokens: 0,
- inputTokens: 0,
- outputTokens: 0,
- },
- },
- output: "done",
- subagentName: "researcher",
- },
- sequence: 0,
- status: "completed",
- stepIndex: 0,
- turnId: "turn",
- },
- type: "action.result",
- },
- lineage: parentLineage,
- }),
- ).toEqual([
- {
- eventId: `${workId}:settled:completed`,
- kind: "work.settled",
- outcome: "completed",
- settledAt: "2026-01-01T00:00:02Z",
- workId,
- },
- ]);
- });
-});
diff --git a/packages/eve/src/execution/activity-events.ts b/packages/eve/src/execution/activity-events.ts
deleted file mode 100644
index 91609f78e..000000000
--- a/packages/eve/src/execution/activity-events.ts
+++ /dev/null
@@ -1,290 +0,0 @@
-import { normalizePresentationText } from "#shared/presentation-text.js";
-import { deriveChildActivityWorkId } from "#execution/activity-work-id.js";
-import type {
- ActivityActionPhase,
- ActivityEventV1,
- ActivityWorkIdentityV1,
-} from "#protocol/activity.js";
-import type { UnstampedMessageStreamEvent } from "#protocol/message.js";
-import { isTaskControlTool } from "#protocol/task-tools.js";
-
-export function projectActivityEvents(input: {
- readonly at: string;
- readonly event: UnstampedMessageStreamEvent;
- readonly eventId?: string;
- readonly lineage: ActivityWorkIdentityV1;
- /** Calls to tasks: their `action.result` is a receipt, and `task.settled` settles them. */
- readonly taskCallIds?: readonly string[];
-}): readonly ActivityEventV1[] {
- const { event, lineage } = input;
- if (event.type === "actions.requested") {
- return event.data.actions.flatMap((action) => {
- if (action.kind === "subagent-call" || action.kind === "remote-agent-call") return [];
- if (action.kind === "tool-call" && isTaskControlTool(action.toolName)) return [];
- const kind = action.kind === "load-skill" ? ("skill" as const) : ("tool" as const);
- const rawName = action.kind === "load-skill" ? "load_skill" : action.toolName;
- const name = normalizePresentationText(rawName) || (kind === "skill" ? "Skill" : "Tool");
- const id = actionId(lineage.id, action.callId);
- const label = activityLabel(event.data.presentation?.[action.callId]?.label);
- return [
- {
- action: {
- id,
- kind,
- name,
- parentWorkId: lineage.id,
- rootTurnId: lineage.rootTurnId,
- stepIndex: event.data.stepIndex,
- },
- eventId: `${id}:started`,
- kind: "action.started" as const,
- startedAt: input.at,
- },
- ...(label === undefined
- ? []
- : [
- {
- actionId: id,
- eventId: `${id}:label`,
- kind: "action.label.updated" as const,
- label,
- },
- ]),
- ];
- });
- }
- if (event.type === "action.partial") {
- const id = actionId(lineage.id, event.data.result.callId);
- const label = activityLabel(event.data.presentation?.[event.data.result.callId]?.label);
- return label === undefined
- ? []
- : [
- {
- actionId: id,
- eventId: `${id}:update:${input.eventId ?? input.at}`,
- kind: "action.label.updated",
- label,
- },
- ];
- }
- if (event.type === "action.result") {
- const result = event.data.result;
- // Only a child a call started before agents ran as tasks reports its
- // result on the caller's stream, under its unkeyed work id.
- if (result.kind === "subagent-result") {
- const workId = deriveChildActivityWorkId({
- callId: result.callId,
- parentSessionId: lineage.sessionId ?? lineage.rootSessionId,
- parentTurnId: lineage.turnId ?? lineage.rootTurnId,
- });
- const outcome =
- result.origin === "dispatch"
- ? "failed"
- : result.outcome.result.kind === "succeeded"
- ? "completed"
- : result.outcome.result.kind === "cancelled"
- ? "cancelled"
- : "failed";
- return [
- {
- eventId: `${workId}:settled:${outcome}`,
- kind: "work.settled",
- outcome,
- settledAt: input.at,
- workId,
- },
- ];
- }
- if (result.kind === "tool-result" && isTaskControlTool(result.toolName)) return [];
- const id = actionId(lineage.id, result.callId);
- const label = activityLabel(event.data.presentation?.[result.callId]?.label);
- const labelUpdates =
- label === undefined
- ? []
- : [
- {
- actionId: id,
- eventId: `${id}:result:${input.eventId ?? input.at}`,
- kind: "action.label.updated" as const,
- label,
- },
- ];
- const isTaskReceipt = input.taskCallIds?.includes(result.callId) === true;
- if (isTaskReceipt) return labelUpdates;
- return [...labelUpdates, actionSettled(id, event.data.status, input.at)];
- }
- if (event.type === "task.settled") {
- const id = actionId(lineage.id, event.data.callId);
- return [actionSettled(id, event.data.status, input.at)];
- }
- if (event.type === "authorization.required") {
- const id = blockerId(
- "authorization",
- lineage.id,
- event.data.attemptId ??
- event.data.candidateId ??
- `${event.data.turnId}:${String(event.data.stepIndex)}:${event.data.name}`,
- );
- return [
- {
- blocker: {
- id,
- kind: "authorization",
- label: activityLabel(event.data.authorization?.displayName ?? event.data.name),
- parentWorkId: lineage.id,
- rootTurnId: lineage.rootTurnId,
- },
- eventId: `${id}:started`,
- kind: "blocker.started",
- startedAt: input.at,
- },
- ];
- }
- if (event.type === "authorization.completed") {
- const id = blockerId(
- "authorization",
- lineage.id,
- event.data.attemptId ??
- event.data.candidateId ??
- `${event.data.turnId}:${String(event.data.stepIndex)}:${event.data.name}`,
- );
- const outcome =
- event.data.outcome === "authorized"
- ? "completed"
- : event.data.outcome === "failed"
- ? "failed"
- : "cancelled";
- return [
- {
- blockerId: id,
- eventId: `${id}:settled:${outcome}`,
- kind: "blocker.settled",
- outcome,
- settledAt: input.at,
- },
- ];
- }
- if (event.type === "approval.candidate" && event.data.outcome === "pending") {
- const id = blockerId("approval", lineage.id, event.data.requestId);
- return [
- {
- blocker: {
- id,
- kind: "approval",
- parentWorkId: lineage.id,
- rootTurnId: lineage.rootTurnId,
- },
- eventId: `${id}:started`,
- kind: "blocker.started",
- startedAt: input.at,
- },
- ];
- }
- if (event.type === "approval.settled") {
- const id = blockerId("approval", lineage.id, event.data.requestId);
- const outcome = event.data.outcome === "approved" ? "completed" : "cancelled";
- return [
- {
- blockerId: id,
- eventId: `${id}:settled:${outcome}`,
- kind: "blocker.settled",
- outcome,
- settledAt: input.at,
- },
- ];
- }
- if (event.type === "input.requested") {
- return event.data.requests.map((request) => {
- const kind = request.kind === "tool-approval" ? ("approval" as const) : ("input" as const);
- const id = blockerId(kind, lineage.id, request.requestId);
- return {
- blocker: {
- id,
- kind,
- label: activityLabel(request.prompt),
- parentActionId: actionId(lineage.id, request.action.callId),
- parentWorkId: lineage.id,
- rootTurnId: lineage.rootTurnId,
- },
- eventId: `${id}:started`,
- kind: "blocker.started" as const,
- startedAt: input.at,
- };
- });
- }
- if (event.type === "input.resolved") {
- return event.data.resolutions.map((resolution) => {
- const kind = resolution.kind === "tool-approval" ? "approval" : "input";
- const id = blockerId(kind, lineage.id, resolution.requestId);
- const outcome =
- resolution.outcome === "answered" || resolution.outcome === "approved"
- ? "completed"
- : resolution.outcome === "invalid"
- ? "failed"
- : "cancelled";
- return {
- blockerId: id,
- eventId: `${id}:settled:${outcome}`,
- kind: "blocker.settled" as const,
- outcome,
- settledAt: input.at,
- };
- });
- }
- // Delegated work settles here too: an agent session's result reaches its
- // caller's reply hook, not the caller's stream.
- if (
- event.type === "turn.completed" ||
- event.type === "turn.failed" ||
- event.type === "turn.cancelled"
- ) {
- const outcome =
- event.type === "turn.completed"
- ? "completed"
- : event.type === "turn.failed"
- ? "failed"
- : "cancelled";
- return [
- {
- eventId: `${lineage.id}:settled:${outcome}`,
- kind: "work.settled",
- outcome,
- settledAt: input.at,
- workId: lineage.id,
- },
- ];
- }
- return [];
-}
-
-function actionSettled(
- id: string,
- outcome: Exclude<ActivityActionPhase, "running">,
- settledAt: string,
-): ActivityEventV1 {
- return {
- actionId: id,
- eventId: `${id}:settled:${outcome}`,
- kind: "action.settled",
- outcome,
- settledAt,
- };
-}
-
-function activityLabel(value: string | undefined): string | undefined {
- if (value === undefined) return undefined;
- const normalized = normalizePresentationText(value);
- return normalized === "" ? undefined : normalized;
-}
-
-function actionId(parentWorkId: string, callId: string): string {
- return `action:${parentWorkId}:${callId}`;
-}
-
-function blockerId(
- kind: "approval" | "authorization" | "input",
- parentWorkId: string,
- requestId: string,
-): string {
- return `${kind}:${parentWorkId}:${requestId}`;
-}
diff --git a/packages/eve/src/execution/activity-route.test.ts b/packages/eve/src/execution/activity-route.test.ts
deleted file mode 100644
index ad3415eda..000000000
--- a/packages/eve/src/execution/activity-route.test.ts
+++ /dev/null
@@ -1,80 +0,0 @@
-import { beforeEach, describe, expect, it, vi } from "vitest";
-
-const resumeHookMock = vi.fn();
-vi.mock("#internal/workflow/runtime.js", () => ({
- resumeHook: (...args: unknown[]) => resumeHookMock(...args),
-}));
-
-import { handleActivityRequest } from "#execution/activity-route.js";
-
-const token = "abcdefghijklmnopqrstuvwxyz123456";
-const context = {
- params: { token },
- requestIp: null,
- waitUntil: vi.fn(),
-} as Parameters<typeof handleActivityRequest>[1];
-
-describe("activity route", () => {
- beforeEach(() => {
- resumeHookMock.mockReset();
- resumeHookMock.mockResolvedValue(undefined);
- });
-
- it("accepts a valid batch through the collector hook", async () => {
- const batch = {
- events: [
- {
- eventId: "work:started",
- kind: "work.started",
- startedAt: "now",
- work: {
- id: "work",
- kind: "root-turn",
- rootSessionId: "session",
- rootTurnId: "turn",
- },
- },
- ],
- version: 1,
- };
- const response = await handleActivityRequest(
- new Request(`https://example.com/eve/v1/activity/${token}`, {
- body: JSON.stringify(batch),
- headers: { "content-type": "application/json" },
- method: "POST",
- }),
- context,
- );
- expect(response.status).toBe(202);
- expect(resumeHookMock).toHaveBeenCalledWith(token, batch);
- });
-
- it("rejects malformed known events before resuming", async () => {
- const response = await handleActivityRequest(
- new Request(`https://example.com/eve/v1/activity/${token}`, {
- body: JSON.stringify({
- events: [{ eventId: "work:started", kind: "work.started" }],
- version: 1,
- }),
- headers: { "content-type": "application/json" },
- method: "POST",
- }),
- context,
- );
- expect(response.status).toBe(400);
- expect(resumeHookMock).not.toHaveBeenCalled();
- });
-
- it("returns not found when collector ownership ended", async () => {
- resumeHookMock.mockRejectedValue(new Error("missing"));
- const response = await handleActivityRequest(
- new Request(`https://example.com/eve/v1/activity/${token}`, {
- body: JSON.stringify({ events: [], version: 1 }),
- headers: { "content-type": "application/json" },
- method: "POST",
- }),
- context,
- );
- expect(response.status).toBe(404);
- });
-});
diff --git a/packages/eve/src/execution/activity-route.ts b/packages/eve/src/execution/activity-route.ts
deleted file mode 100644
index 52abb995b..000000000
--- a/packages/eve/src/execution/activity-route.ts
+++ /dev/null
@@ -1,50 +0,0 @@
-import { resumeHook } from "#internal/workflow/runtime.js";
-
-import { parseActivityBatchV1 } from "#protocol/activity.js";
-import type { RouteContext } from "#public/definitions/channel.js";
-
-const MAX_ACTIVITY_REQUEST_BYTES = 128 * 1024;
-
-export async function handleActivityRequest(
- request: Request,
- ctx: RouteContext,
-): Promise<Response> {
- const token = ctx.params.token;
- if (typeof token !== "string" || token.length < 32 || token.length > 500) {
- return Response.json({ error: "Invalid activity sink.", ok: false }, { status: 400 });
- }
- if (!request.headers.get("content-type")?.toLowerCase().startsWith("application/json")) {
- return Response.json({ error: "Activity sinks require JSON.", ok: false }, { status: 400 });
- }
- const declaredLength = Number(request.headers.get("content-length"));
- if (Number.isFinite(declaredLength) && declaredLength > MAX_ACTIVITY_REQUEST_BYTES) {
- return Response.json({ error: "Activity sink body is too large.", ok: false }, { status: 400 });
- }
-
- let text: string;
- try {
- text = await request.text();
- } catch {
- return Response.json({ error: "Invalid activity sink body.", ok: false }, { status: 400 });
- }
- if (new TextEncoder().encode(text).byteLength > MAX_ACTIVITY_REQUEST_BYTES) {
- return Response.json({ error: "Activity sink body is too large.", ok: false }, { status: 400 });
- }
-
- let value: unknown;
- try {
- value = JSON.parse(text);
- } catch {
- return Response.json({ error: "Invalid JSON body.", ok: false }, { status: 400 });
- }
- const batch = parseActivityBatchV1(value);
- if (batch === undefined) {
- return Response.json({ error: "Invalid activity batch.", ok: false }, { status: 400 });
- }
- try {
- await resumeHook(token, batch);
- } catch {
- return Response.json({ error: "Activity collector not found.", ok: false }, { status: 404 });
- }
- return Response.json({ ok: true }, { status: 202 });
-}
diff --git a/packages/eve/src/execution/activity-work-id.ts b/packages/eve/src/execution/activity-work-id.ts
deleted file mode 100644
index 2ab9e30ee..000000000
--- a/packages/eve/src/execution/activity-work-id.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-import { createHash } from "node:crypto";
-
-export function deriveRootTurnActivityWorkId(input: {
- readonly sessionId: string;
- readonly turnId: string;
-}): string {
- return `root:${hashTuple([input.sessionId, input.turnId])}`;
-}
-
-export function deriveChildActivityWorkId(input: {
- readonly callId: string;
- readonly parentSessionId: string;
- readonly parentTurnId: string;
- /**
- * Tells apart the sessions one call opens. Only the legacy `subagent-result`
- * settle omits it, for a child a call started before agents ran as tasks.
- */
- readonly sessionKey?: string;
-}): string {
- const session = input.sessionKey === undefined ? "" : `\0${input.sessionKey}`;
- const digest = createHash("sha256")
- .update(`${input.parentSessionId}\0${input.parentTurnId}\0${input.callId}${session}`)
- .digest("hex");
- return `work:${digest}`;
-}
-
-function hashTuple(values: readonly string[]): string {
- return createHash("sha256").update(JSON.stringify(values)).digest("hex");
-}
diff --git a/packages/eve/src/execution/activity-work.test.ts b/packages/eve/src/execution/activity-work.test.ts
deleted file mode 100644
index 50fd636c0..000000000
--- a/packages/eve/src/execution/activity-work.test.ts
+++ /dev/null
@@ -1,102 +0,0 @@
-import { describe, expect, it } from "vitest";
-
-import { deriveChildWorkIdentity, deriveRootTurnWorkIdentity } from "#execution/activity-work.js";
-
-describe("activity work identity", () => {
- it("derives root work from the active root turn", () => {
- expect(
- deriveRootTurnWorkIdentity({
- auth: { current: null, initiator: null },
- sessionId: "root",
- turn: { id: "turn-1", sequence: 0 },
- }),
- ).toEqual({
- id: expect.stringMatching(/^root:[a-f0-9]{64}$/),
- kind: "root-turn",
- rootSessionId: "root",
- rootTurnId: "turn-1",
- sessionId: "root",
- turnId: "turn-1",
- });
- });
-
- it("preserves immediate parent and root-turn lineage for nested work", () => {
- const root = {
- id: "root:fixture",
- kind: "root-turn" as const,
- rootSessionId: "root",
- rootTurnId: "turn-1",
- sessionId: "root",
- turnId: "turn-1",
- };
- const child = deriveChildWorkIdentity({
- callId: "call-a",
- kind: "subagent",
- name: "research",
- parentSessionId: "root",
- parentTurnId: "turn-1",
- parentWork: root,
- sessionKey: "run-1:0",
- });
- const grandchild = deriveChildWorkIdentity({
- callId: "call-b",
- kind: "subagent",
- name: "tester",
- parentSessionId: "child-a",
- parentTurnId: "child-turn",
- parentWork: child,
- sessionKey: "run-2:0",
- });
-
- expect(grandchild).toMatchObject({
- id: expect.stringMatching(/^work:[a-f0-9]{64}$/),
- parentId: child.id,
- rootSessionId: "root",
- rootTurnId: "turn-1",
- });
- });
-
- it("keeps colon-containing root tuples distinct", () => {
- const first = deriveRootTurnWorkIdentity({
- auth: { current: null, initiator: null },
- sessionId: "a:b",
- turn: { id: "c", sequence: 0 },
- });
- const second = deriveRootTurnWorkIdentity({
- auth: { current: null, initiator: null },
- sessionId: "a",
- turn: { id: "b:c", sequence: 0 },
- });
-
- expect(first.id).not.toBe(second.id);
- });
-
- it("keeps colon-containing child tuples distinct", () => {
- const parentWork = {
- id: "root:fixture",
- kind: "root-turn" as const,
- rootSessionId: "root",
- rootTurnId: "turn",
- };
- const first = deriveChildWorkIdentity({
- callId: "d",
- kind: "subagent",
- name: "first",
- parentSessionId: "a:b",
- parentTurnId: "c",
- parentWork,
- sessionKey: "run-1:0",
- });
- const second = deriveChildWorkIdentity({
- callId: "d",
- kind: "subagent",
- name: "second",
- parentSessionId: "a",
- parentTurnId: "b:c",
- parentWork,
- sessionKey: "run-1:0",
- });
-
- expect(first.id).not.toBe(second.id);
- });
-});
diff --git a/packages/eve/src/execution/activity-work.ts b/packages/eve/src/execution/activity-work.ts
deleted file mode 100644
index 12ee75870..000000000
--- a/packages/eve/src/execution/activity-work.ts
+++ /dev/null
@@ -1,62 +0,0 @@
-import type { ActivityObserverConfig } from "#channel/types.js";
-import type { Session } from "#context/keys.js";
-import {
- deriveChildActivityWorkId,
- deriveRootTurnActivityWorkId,
-} from "#execution/activity-work-id.js";
-import type { ActivityWorkIdentityV1, ActivityWorkKind } from "#protocol/activity.js";
-
-export function deriveRootTurnWorkIdentity(session: Session): ActivityWorkIdentityV1 {
- return {
- id: deriveRootTurnActivityWorkId({
- sessionId: session.sessionId,
- turnId: session.turn.id,
- }),
- kind: "root-turn",
- rootSessionId: session.sessionId,
- rootTurnId: session.turn.id,
- sessionId: session.sessionId,
- turnId: session.turn.id,
- };
-}
-
-export function deriveChildActivityObserverConfig(input: {
- readonly callId: string;
- readonly kind: Exclude<ActivityWorkKind, "root-turn">;
- readonly name: string;
- readonly parentSessionId: string;
- readonly parentTurnId: string;
- readonly sessionKey: string;
- readonly activityObserver: ActivityObserverConfig | undefined;
-}): ActivityObserverConfig | undefined {
- if (input.activityObserver?.workIdentity === undefined) return undefined;
- return {
- sink: input.activityObserver.sink,
- workIdentity: deriveChildWorkIdentity({
- ...input,
- parentWork: input.activityObserver.workIdentity,
- }),
- };
-}
-
-export function deriveChildWorkIdentity(input: {
- readonly callId: string;
- readonly kind: Exclude<ActivityWorkKind, "root-turn">;
- readonly label?: string;
- readonly name: string;
- readonly parentSessionId: string;
- readonly parentTurnId: string;
- readonly parentWork: ActivityWorkIdentityV1;
- readonly sessionKey: string;
-}): ActivityWorkIdentityV1 {
- return {
- callId: input.callId,
- id: deriveChildActivityWorkId(input),
- kind: input.kind,
- label: input.label,
- name: input.name,
- parentId: input.parentWork.id,
- rootSessionId: input.parentWork.rootSessionId,
- rootTurnId: input.parentWork.rootTurnId,
- };
-}
diff --git a/packages/eve/src/execution/agent-sessions/context.ts b/packages/eve/src/execution/agent-sessions/context.ts
index 49394a952..78e0aa49a 100644
--- a/packages/eve/src/execution/agent-sessions/context.ts
+++ b/packages/eve/src/execution/agent-sessions/context.ts
@@ -1,5 +1,4 @@
import type {
- ActivityObserverConfig,
ChannelInstrumentationProjection,
RunSessionLimits,
SessionCapabilities,
@@ -8,7 +7,6 @@ import type {
import type { LocalDevRequestProvenance } from "#context/keys.js";
import type { DynamicSubagentSelections } from "#execution/agent-sessions/target.js";
import type { PreparedCoordinationDispatch } from "#execution/coordination-dispatch-shared.js";
-import type { ActivityWorkIdentityV1 } from "#protocol/activity.js";
import {
serializeDurableCompiledArtifactsSource,
type DurableCompiledArtifactsSource,
@@ -34,9 +32,6 @@ import {
* of it: each message carries the auth of the call that sends it.
*/
export interface AgentSessionContext {
- readonly activityObserver?: ActivityObserverConfig & {
- readonly workIdentity: ActivityWorkIdentityV1;
- };
/** The agents the call may open, by name, which `ctx.agents` lists. */
readonly agents: Readonly<Record<string, WorkflowAgentMetadata>>;
readonly bundle: AgentSessionBundle;
@@ -69,7 +64,6 @@ export interface AgentSessionSandbox {
type CallerDispatch = Pick<
PreparedCoordinationDispatch<unknown>,
- | "activityObserver"
| "batch"
| "bundle"
| "capabilities"
@@ -109,7 +103,6 @@ export function captureAgentSessionContext(
): AgentSessionContext {
const { batch, session } = caller;
return {
- activityObserver: caller.activityObserver,
agents: caller.workflowAgents,
bundle: {
nodeId: caller.bundle.nodeId,
diff --git a/packages/eve/src/execution/agent-sessions/remote.test.ts b/packages/eve/src/execution/agent-sessions/remote.test.ts
index 6f7f76e13..2dcf4e808 100644
--- a/packages/eve/src/execution/agent-sessions/remote.test.ts
+++ b/packages/eve/src/execution/agent-sessions/remote.test.ts
@@ -864,20 +864,6 @@ describe("continueRemoteAgentSession", () => {
vi.stubGlobal("fetch", fetchMock);
await continueRemoteAgentSession({
- activityObserver: {
- sink: {
- url: "https://caller.example.com/eve/v1/activity/abcdefghijklmnopqrstuvwxyz123456",
- version: 1,
- },
- workIdentity: {
- callId: "call-next",
- id: "work:next",
- kind: "remote-agent",
- name: "research",
- rootSessionId: "root",
- rootTurnId: "turn",
- },
- },
auth: null,
callback: {
callId: "call-next",
@@ -895,20 +881,6 @@ describe("continueRemoteAgentSession", () => {
"https://remote.example.com/eve/v1/session/remote-session",
{
body: JSON.stringify({
- activityObserver: {
- sink: {
- url: "https://caller.example.com/eve/v1/activity/abcdefghijklmnopqrstuvwxyz123456",
- version: 1,
- },
- workIdentity: {
- callId: "call-next",
- id: "work:next",
- kind: "remote-agent",
- name: "research",
- rootSessionId: "root",
- rootTurnId: "turn",
- },
- },
callback: {
callId: "call-next",
subagentName: "research",
diff --git a/packages/eve/src/execution/agent-sessions/remote.ts b/packages/eve/src/execution/agent-sessions/remote.ts
index ee4aeac80..3b43525c4 100644
--- a/packages/eve/src/execution/agent-sessions/remote.ts
+++ b/packages/eve/src/execution/agent-sessions/remote.ts
@@ -15,7 +15,6 @@ import {
createEveSessionRoutePath,
} from "#protocol/routes.js";
import type {
- ActivityObserverConfig,
CancelTurnResult,
SessionAuthContext,
SessionCapabilities,
@@ -63,7 +62,6 @@ export async function startRemoteAgentSession(input: {
readonly callbackBaseUrl: string | undefined;
readonly capabilities?: SessionCapabilities;
readonly originAudience?: ChannelAudience;
- readonly activityObserver?: ActivityObserverConfig;
/** The root initiator's principal, forwarded alongside {@link auth}. */
readonly initiatorAuth?: SessionAuthContext | null;
/**
@@ -95,7 +93,6 @@ export async function startRemoteAgentSession(input: {
token: string;
url: string;
};
- activityObserver?: ActivityObserverConfig;
forwardedPrincipal?: ForwardedPrincipal;
message: string;
operationId?: string;
@@ -120,7 +117,6 @@ export async function startRemoteAgentSession(input: {
outputSchema: input.action.input.outputSchema as JsonObject | undefined,
protocolVersion: REMOTE_AGENT_PROTOCOL_VERSION,
};
- if (input.activityObserver !== undefined) requestBody.activityObserver = input.activityObserver;
if (forwardedPrincipal !== undefined) {
requestBody.forwardedPrincipal = forwardedPrincipal;
}
@@ -257,7 +253,6 @@ export async function respondToRemoteAgentSession(input: {
/** Continues one remote-agent session by its immutable session ID. */
export async function continueRemoteAgentSession(input: {
- readonly activityObserver?: ActivityObserverConfig;
/** The dispatching turn's session principal, forwarded when `remote.forwardPrincipal` is set. */
readonly auth: SessionAuthContext | null;
readonly callback: {
@@ -273,13 +268,11 @@ export async function continueRemoteAgentSession(input: {
}): Promise<void> {
const forwardedPrincipal = buildForwardedPrincipalField(input);
const requestBody: {
- activityObserver?: ActivityObserverConfig;
callback: typeof input.callback;
forwardedPrincipal?: ForwardedPrincipal;
message: string;
outputSchema?: JsonObject;
} = {
- activityObserver: input.activityObserver,
callback: input.callback,
message: input.message,
outputSchema: input.outputSchema,
diff --git a/packages/eve/src/execution/agent-sessions/steps.test.ts b/packages/eve/src/execution/agent-sessions/steps.test.ts
deleted file mode 100644
index 24ef39023..000000000
--- a/packages/eve/src/execution/agent-sessions/steps.test.ts
+++ /dev/null
@@ -1,304 +0,0 @@
-import { afterEach, describe, expect, it, vi } from "vitest";
-
-import type { ActivityObserverConfig } from "#channel/types.js";
-import type { AgentSessionContext } from "#execution/agent-sessions/context.js";
-import {
- openAgentSessionStep,
- sendAgentSessionMessageStep,
-} from "#execution/agent-sessions/steps.js";
-import { deriveRootTurnActivityWorkId } from "#execution/activity-work-id.js";
-import { projectSessionActivity } from "#execution/session-activity-projection.js";
-import { createActivitySnapshot, reduceActivityBatch } from "#execution/session-activity.js";
-import {
- createWorkflowRuntime,
- dispatchWorkflowSessionCommand,
-} from "#execution/workflow-runtime.js";
-import { parseSessionMessageBody } from "#eve-channel/request.js";
-import type { MessageStreamEvent } from "#protocol/message.js";
-import { REMOTE_AGENT_PROTOCOL_VERSION } from "#protocol/remote-agent-protocol.js";
-
-const researcher = {
- description: "Researches a topic.",
- kind: "subagent",
- name: "researcher",
- nodeId: "agents/researcher",
-};
-const writer = {
- description: "Writes a summary.",
- kind: "subagent",
- name: "writer",
- nodeId: "agents/writer",
-};
-const remoteResearcher = {
- description: "Researches a topic remotely.",
- kind: "remote",
- logicalPath: "agents/remote-research.ts",
- name: "remote_research",
- nodeId: "agents/remote-research",
- path: "/eve/v1/session",
- sourceId: "agents/remote-research.ts",
- sourceKind: "module",
- url: "https://remote.example.com",
-};
-
-vi.mock("#compiled/@workflow/core/index.js", async (importOriginal) => ({
- ...(await importOriginal()),
- getWorkflowMetadata: () => ({ url: "https://parent.example.com" }),
-}));
-
-vi.mock("#runtime/sessions/compiled-agent-cache.js", () => ({
- getCompiledRuntimeAgentBundle: async () => {
- const definitions = [researcher, writer, remoteResearcher];
- return {
- compiledArtifactsSource: { kind: "test" },
- subagentRegistry: {
- subagentsByName: new Map(
- definitions.map((definition) => [definition.name, { definition }]),
- ),
- subagentsByNodeId: new Map(
- definitions.map((definition) => [definition.nodeId, { definition }]),
- ),
- },
- };
- },
-}));
-
-vi.mock("#execution/workflow-runtime.js", () => ({
- createWorkflowRuntime: vi.fn(),
- dispatchWorkflowSessionCommand: vi.fn(async () => ({ status: "accepted" })),
- requestWorkflowTurnCancellation: vi.fn(),
- waitForCommandHookOwner: vi.fn(async () => ({ runId: "child" })),
-}));
-
-const at = "2026-01-01T00:00:00.000Z";
-const rootWorkId = deriveRootTurnActivityWorkId({ sessionId: "parent", turnId: "turn-1" });
-const auth = { current: null, initiator: null };
-
-function callerContext(): AgentSessionContext {
- return {
- activityObserver: {
- sink: {
- url: "https://parent.example.com/eve/v1/activity/abcdefghijklmnopqrstuvwxyz123456",
- version: 1,
- },
- workIdentity: {
- id: rootWorkId,
- kind: "root-turn",
- rootSessionId: "parent",
- rootTurnId: "turn-1",
- sessionId: "parent",
- turnId: "turn-1",
- },
- },
- agents: {},
- bundle: { source: { kind: "test" } as never },
- dynamicSelections: {},
- limits: {},
- parent: {
- callId: "call-1",
- rootSessionId: "parent",
- sessionId: "parent",
- turn: { id: "turn-1", sequence: 0 },
- },
- sandbox: { sessionId: "parent" },
- trace: { originAudience: { kind: "unknown" } } as never,
- };
-}
-
-function childTurn(turnId: string): MessageStreamEvent[] {
- const coordinates = { sequence: 0, stepIndex: 0, turnId };
- return [
- { data: { sequence: 0, turnId }, meta: { at, id: `${turnId}:started` }, type: "turn.started" },
- {
- data: {
- ...coordinates,
- actions: [{ callId: "search-1", input: {}, kind: "tool-call", toolName: "search" }],
- },
- meta: { at, id: `${turnId}:actions` },
- type: "actions.requested",
- },
- {
- data: { sequence: 0, turnId },
- meta: { at, id: `${turnId}:completed` },
- type: "turn.completed",
- },
- ];
-}
-
-function rootTurnStarted() {
- return projectSessionActivity({
- event: {
- data: { sequence: 0, turnId: "turn-1" },
- meta: { at, id: "parent:started" },
- type: "turn.started",
- },
- sessionId: "parent",
- });
-}
-
-function childSessionActivity(
- sessionId: string,
- observer: ActivityObserverConfig | undefined,
- events: readonly MessageStreamEvent[],
-) {
- return events.flatMap((event) =>
- projectSessionActivity({ event, sessionId, workIdentity: observer?.workIdentity }),
- );
-}
-
-function localChildRuntime() {
- const createSession = vi.fn(async (_input: { activityObserver?: ActivityObserverConfig }) => ({
- sessionId: "child",
- }));
- vi.mocked(createWorkflowRuntime).mockReturnValue({ createSession } as never);
- return createSession;
-}
-
-afterEach(() => {
- vi.clearAllMocks();
- vi.unstubAllGlobals();
-});
-
-describe("agent session activity", () => {
- it("reports a local agent's turns as its own work that settles when the turn ends", async () => {
- const createSession = localChildRuntime();
- const context = callerContext();
-
- const address = await openAgentSessionStep({
- auth,
- context,
- key: "run-1:0",
- message: "Research the topic.",
- name: "researcher",
- replyTo: "reply-1",
- });
- await sendAgentSessionMessageStep({
- address,
- auth,
- context,
- key: "run-1:0",
- message: "Go deeper.",
- replyTo: "reply-2",
- });
-
- const opened = createSession.mock.calls[0]?.[0].activityObserver;
- const sent = vi.mocked(dispatchWorkflowSessionCommand).mock.calls[0]?.[0].command;
- expect(sent).toMatchObject({ caller: { activityObserver: opened } });
- const events = [
- ...rootTurnStarted(),
- ...childSessionActivity("child", opened, [
- { data: {}, meta: { at, id: "child:session" }, type: "session.started" },
- ...childTurn("turn_0"),
- ]),
- ];
- const snapshot = reduceActivityBatch(createActivitySnapshot(), { events, version: 1 });
-
- const childWorkId = opened?.workIdentity?.id ?? "";
- expect(snapshot.work).toEqual({
- [rootWorkId]: expect.objectContaining({ kind: "root-turn", phase: "running" }),
- [childWorkId]: expect.objectContaining({
- callId: "call-1",
- kind: "subagent",
- name: "researcher",
- parentId: rootWorkId,
- phase: "completed",
- }),
- });
- expect(Object.values(snapshot.actions)).toEqual([
- expect.objectContaining({ name: "search", parentWorkId: childWorkId }),
- ]);
- });
-
- it("reports each session one call opens as its own work that settles with its own turn", async () => {
- const createSession = localChildRuntime();
- const context = callerContext();
- for (const [index, name] of ["researcher", "writer"].entries()) {
- await openAgentSessionStep({
- auth,
- context,
- key: `run-1:${String(index)}`,
- message: "Work on the topic.",
- name,
- replyTo: `reply-${String(index)}`,
- });
- }
- const [research, write] = createSession.mock.calls.map(([input]) => input.activityObserver);
- const researchId = research?.workIdentity?.id ?? "";
- const writeId = write?.workIdentity?.id ?? "";
- const started: MessageStreamEvent = {
- data: {},
- meta: { at, id: "session" },
- type: "session.started",
- };
-
- const researchDone = reduceActivityBatch(createActivitySnapshot(), {
- events: [
- ...rootTurnStarted(),
- ...childSessionActivity("research-child", research, [started, ...childTurn("turn_0")]),
- ...childSessionActivity("write-child", write, [started, childTurn("turn_0")[0]!]),
- ],
- version: 1,
- });
- expect(researchDone.work).toEqual({
- [rootWorkId]: expect.objectContaining({ phase: "running" }),
- [researchId]: expect.objectContaining({ name: "researcher", phase: "completed" }),
- [writeId]: expect.objectContaining({ name: "writer", phase: "running" }),
- });
-
- const [, writeActions, writeEnd] = childTurn("turn_0");
- const writing = reduceActivityBatch(researchDone, {
- events: childSessionActivity("write-child", write, [writeActions!]),
- version: 1,
- });
- expect(Object.values(writing.actions)).toContainEqual(
- expect.objectContaining({ parentWorkId: writeId, phase: "running" }),
- );
-
- const bothDone = reduceActivityBatch(writing, {
- events: childSessionActivity("write-child", write, [writeEnd!]),
- version: 1,
- });
- expect(bothDone.work[writeId]).toMatchObject({ phase: "completed" });
- expect(bothDone.work[rootWorkId]).toMatchObject({ phase: "running" });
- });
-
- it("opens and continues a remote agent with one activity identity the remote accepts", async () => {
- const fetchMock = vi.fn(async (_url: string, _init: RequestInit) =>
- Response.json({
- ok: true,
- protocolVersion: REMOTE_AGENT_PROTOCOL_VERSION,
- sessionId: "remote-session",
- status: "accepted",
- }),
- );
- vi.stubGlobal("fetch", fetchMock);
- const context = callerContext();
-
- const address = await openAgentSessionStep({
- auth,
- context,
- key: "run-1:0",
- message: "Research the topic.",
- name: "remote_research",
- replyTo: "reply-1",
- });
- await sendAgentSessionMessageStep({
- address,
- auth,
- context,
- key: "run-1:0",
- message: "Go deeper.",
- replyTo: "reply-2",
- });
-
- const [opened, continued] = fetchMock.mock.calls.map(
- ([, init]) => JSON.parse(String(init.body)) as Record<string, unknown>,
- );
- expect(continued?.activityObserver).toEqual(opened?.activityObserver);
- expect(parseSessionMessageBody(continued ?? {})).toMatchObject({
- activityObserver: {
- workIdentity: { callId: "call-1", kind: "remote-agent", parentId: rootWorkId },
- },
- });
- });
-});
diff --git a/packages/eve/src/execution/agent-sessions/steps.ts b/packages/eve/src/execution/agent-sessions/steps.ts
index d5a3a0f1d..4b6325311 100644
--- a/packages/eve/src/execution/agent-sessions/steps.ts
+++ b/packages/eve/src/execution/agent-sessions/steps.ts
@@ -1,5 +1,4 @@
import { getWorkflowMetadata } from "#compiled/@workflow/core/index.js";
-import type { ActivityObserverConfig } from "#channel/types.js";
import { ContextContainer, contextStorage } from "#context/container.js";
import type { SessionAuth } from "#context/session-context.js";
import type { AgentSessionContext } from "#execution/agent-sessions/context.js";
@@ -8,7 +7,6 @@ import {
resolveAgentStartTarget,
type SubagentStartTarget,
} from "#execution/agent-sessions/target.js";
-import { deriveChildActivityObserverConfig } from "#execution/activity-work.js";
import { sessionInboxHookToken } from "#execution/session-inbox/address.js";
import {
createWorkflowCallbackUrl,
@@ -130,7 +128,6 @@ export async function sendAgentSessionMessageStep(
if (address.kind === "remote") {
const remote = await resolveSessionRemote(context, address);
await continueRemoteAgentSession({
- activityObserver: sessionActivityObserver(context, { ...address, key: input.key }),
auth: input.auth.current,
callback: {
callId: context.parent.callId,
@@ -152,7 +149,6 @@ export async function sendAgentSessionMessageStep(
command: {
auth: input.auth.current,
caller: {
- activityObserver: sessionActivityObserver(context, { ...address, key: input.key }),
callId: context.parent.callId,
replyTo: { kind: "hook", token: input.replyTo },
subagentName: address.name,
@@ -235,11 +231,6 @@ async function startLocalSession(
const { action } = target;
const { childContinuationToken, runInput } = buildSubagentRunInput({
action,
- activityObserver: sessionActivityObserver(context, {
- key: input.key,
- kind: "local",
- name: action.name,
- }),
auth: auth.current,
capabilities: context.capabilities,
channelMetadata: context.channelMetadata,
@@ -284,11 +275,6 @@ async function startRemoteSession(
const callbackBaseUrl = resolveWorkflowCallbackBaseUrl(getWorkflowMetadata().url);
const child = await startRemoteAgentSession({
action,
- activityObserver: sessionActivityObserver(context, {
- key: input.key,
- kind: "remote",
- name: action.remoteAgentName,
- }),
auth: auth.current,
callbackBaseUrl,
capabilities: context.capabilities,
@@ -311,27 +297,6 @@ async function startRemoteSession(
};
}
-/**
- * The session's turns report their activity as its own work, beneath the
- * opening call's turn, never as the caller's. Every message carries the same
- * identity: its call id is the one steering and remote binding check, and the
- * session's key tells apart the sessions one call opens.
- */
-function sessionActivityObserver(
- context: AgentSessionContext,
- session: Pick<AgentSessionAddress, "kind" | "name"> & { readonly key: string },
-): ActivityObserverConfig | undefined {
- return deriveChildActivityObserverConfig({
- activityObserver: context.activityObserver,
- callId: context.parent.callId,
- kind: session.kind === "remote" ? "remote-agent" : "subagent",
- name: session.name,
- parentSessionId: context.parent.sessionId,
- parentTurnId: context.parent.turn.id,
- sessionKey: session.key,
- });
-}
-
function createParentContext(context: AgentSessionContext, replyTo: string): SubagentParentContext {
return {
continuationToken: replyTo,
diff --git a/packages/eve/src/execution/continuation-conflict-step.test.ts b/packages/eve/src/execution/continuation-conflict-step.test.ts
index ef6c6a23b..233cf89b2 100644
--- a/packages/eve/src/execution/continuation-conflict-step.test.ts
+++ b/packages/eve/src/execution/continuation-conflict-step.test.ts
@@ -3,20 +3,12 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
import { HookNotFoundError } from "#compiled/@workflow/errors/index.js";
import { settleContinuationConflictStep } from "#execution/continuation-conflict-step.js";
-const cancelRunMock = vi.fn();
-const getWorldMock = vi.fn();
-const world = {};
const resumeSessionInboxMock = vi.fn();
vi.mock("#execution/session-inbox/resume.js", () => ({
resumeSessionInbox: (...args: unknown[]) => resumeSessionInboxMock(...args),
}));
-vi.mock("#internal/workflow/runtime.js", () => ({
- cancelRun: (...args: unknown[]) => cancelRunMock(...args),
- getWorld: (...args: unknown[]) => getWorldMock(...args),
-}));
-
const command = {
auth: null,
kind: "send" as const,
@@ -27,35 +19,21 @@ const command = {
describe("settleContinuationConflictStep", () => {
beforeEach(() => {
vi.clearAllMocks();
- getWorldMock.mockResolvedValue(world);
resumeSessionInboxMock.mockResolvedValue({ runId: "wrun_owner" });
- cancelRunMock.mockResolvedValue(undefined);
});
- it("forwards a losing channel delivery and retires its activity collector", async () => {
- await settleContinuationConflictStep({
- activityCollectorRunId: "wrun_collector",
- command,
- continuationToken: "slack:C1:T1",
- });
+ it("forwards a losing channel delivery to the continuation owner", async () => {
+ await settleContinuationConflictStep({ command, continuationToken: "slack:C1:T1" });
expect(resumeSessionInboxMock).toHaveBeenCalledWith("slack:C1:T1", command);
- expect(cancelRunMock).toHaveBeenCalledWith(world, "wrun_collector", {
- cancelReason: "Session candidate did not acquire continuation ownership",
- });
});
- it("surfaces a vanished alias and still retires the losing collector", async () => {
+ it("surfaces a vanished alias", async () => {
const error = new HookNotFoundError("slack:C1:T1");
resumeSessionInboxMock.mockRejectedValue(error);
+
await expect(
- settleContinuationConflictStep({
- activityCollectorRunId: "wrun_collector",
- command,
- continuationToken: "slack:C1:T1",
- }),
+ settleContinuationConflictStep({ command, continuationToken: "slack:C1:T1" }),
).rejects.toBe(error);
- expect(resumeSessionInboxMock).toHaveBeenCalledExactlyOnceWith("slack:C1:T1", command);
- expect(cancelRunMock).toHaveBeenCalledOnce();
});
});
diff --git a/packages/eve/src/execution/continuation-conflict-step.ts b/packages/eve/src/execution/continuation-conflict-step.ts
index 426134ea3..98254b52e 100644
--- a/packages/eve/src/execution/continuation-conflict-step.ts
+++ b/packages/eve/src/execution/continuation-conflict-step.ts
@@ -1,34 +1,12 @@
-import { isInactiveWorkflowRunError } from "#internal/workflow/is-inactive-workflow-run-error.js";
-
import type { SessionCommand } from "#channel/types.js";
import { resumeSessionInbox } from "#execution/session-inbox/resume.js";
-import { cancelRun, getWorld } from "#internal/workflow/runtime.js";
-/** Settles side effects owned by a session candidate that lost its continuation claim. */
+/** Hands a losing session candidate's command to the session that owns the continuation. */
export async function settleContinuationConflictStep(input: {
- readonly activityCollectorRunId?: string;
- readonly command?: Extract<SessionCommand, { readonly kind: "send" }>;
+ readonly command: Extract<SessionCommand, { readonly kind: "send" }>;
readonly continuationToken: string;
}): Promise<void> {
"use step";
- try {
- if (input.command !== undefined) {
- await resumeSessionInbox(input.continuationToken, input.command);
- }
- } finally {
- if (input.activityCollectorRunId !== undefined) {
- await cancelCollector(input.activityCollectorRunId);
- }
- }
-}
-
-async function cancelCollector(runId: string): Promise<void> {
- try {
- await cancelRun(await getWorld(), runId, {
- cancelReason: "Session candidate did not acquire continuation ownership",
- });
- } catch (error) {
- if (!isInactiveWorkflowRunError(error)) throw error;
- }
+ await resumeSessionInbox(input.continuationToken, input.command);
}
diff --git a/packages/eve/src/execution/coordination-dispatch-shared.ts b/packages/eve/src/execution/coordination-dispatch-shared.ts
index c87e795a0..af9cbdd44 100644
--- a/packages/eve/src/execution/coordination-dispatch-shared.ts
+++ b/packages/eve/src/execution/coordination-dispatch-shared.ts
@@ -1,10 +1,8 @@
/** Shared owner-side dispatch context preparation. */
import { buildAdapterContext } from "#channel/adapter-context.js";
-import type { ActivityObserverConfig } from "#channel/types.js";
import { type ChannelAdapter, type ChannelAdapterContext } from "#channel/adapter.js";
import {
- ActivityObserverKey,
AuthKey,
CapabilitiesKey,
ChannelInstrumentationKey,
@@ -22,14 +20,12 @@ import {
} from "#runtime/sessions/runtime-context-keys.js";
import { deserializeContext } from "#context/serialize.js";
import type { HarnessSession } from "#harness/types.js";
-import { deriveRootTurnActivityWorkId } from "#execution/activity-work-id.js";
import {
assertUniqueCoordinationCallIds,
getPendingCoordinationBatch,
setPendingCoordinationBatch,
} from "#harness/coordination.js";
import { activeTurnId } from "#harness/active-turn-id.js";
-import type { ActivityWorkIdentityV1 } from "#protocol/activity.js";
import type { RuntimeActionResult, RuntimeWorkflowTaskRequest } from "#shared/action-types.js";
import type { SessionParent } from "#channel/types.js";
import {
@@ -79,9 +75,6 @@ export interface PreparedCoordinationDispatch<PlanEntry = RuntimeWorkflowTaskReq
readonly localDevRequest?: LocalDevRequestProvenance;
/** Lineage of the session running this dispatch, when it is itself a delegated child. */
readonly parentSession: SessionParent | undefined;
- readonly activityObserver?: ActivityObserverConfig & {
- readonly workIdentity: ActivityWorkIdentityV1;
- };
readonly sandboxSessionId: string;
readonly serializedContext: Record<string, unknown>;
readonly plan: readonly PlanEntry[];
@@ -195,11 +188,6 @@ export async function prepareActionDispatch<PlanEntry>(input: {
localDevRequest: ctx.get(LocalDevRequestKey),
parentSession: ctx.get(ParentSessionKey),
plan,
- activityObserver: resolvePreparedActivity(
- ctx.get(ActivityObserverKey),
- session,
- batch.event.turnId,
- ),
sandboxSessionId,
serializedContext: input.serializedContext,
session,
@@ -207,25 +195,6 @@ export async function prepareActionDispatch<PlanEntry>(input: {
};
}
-function resolvePreparedActivity(
- activityObserver: ActivityObserverConfig | undefined,
- session: HarnessSession,
- turnId: string,
-): (ActivityObserverConfig & { readonly workIdentity: ActivityWorkIdentityV1 }) | undefined {
- if (activityObserver === undefined) return undefined;
- return {
- sink: activityObserver.sink,
- workIdentity: activityObserver.workIdentity ?? {
- id: deriveRootTurnActivityWorkId({ sessionId: session.sessionId, turnId }),
- kind: "root-turn",
- rootSessionId: session.rootSessionId ?? session.sessionId,
- rootTurnId: turnId,
- sessionId: session.sessionId,
- turnId,
- },
- };
-}
-
function resolveActiveSandboxSessionId(adapterState: unknown, sessionId: string): string {
if (typeof adapterState !== "object" || adapterState === null) return sessionId;
const value = (adapterState as Record<string, unknown>).sandboxSessionId;
diff --git a/packages/eve/src/execution/legacy-remote-agent/protocol.ts b/packages/eve/src/execution/legacy-remote-agent/protocol.ts
index d39c2d28d..a4bb7436b 100644
--- a/packages/eve/src/execution/legacy-remote-agent/protocol.ts
+++ b/packages/eve/src/execution/legacy-remote-agent/protocol.ts
@@ -36,29 +36,19 @@ export interface LegacyRemoteAgentCaller {
}
/**
- * Removes the fields a protocol-1 caller adds when it delegates from a
- * background task: `callback.taskId` and a `task` activity work identity.
- * Current callers send neither. The task id is returned so the session can
- * name it back to the caller.
+ * Removes the `callback.taskId` a protocol-1 caller adds when it delegates
+ * from a background task. Current callers don't send it. The task id is
+ * returned so the session can name it back to the caller. The caller's
+ * `activityObserver` needs no removal: eve ignores that field from any caller.
*/
export function splitLegacyTaskFields(input: Record<string, unknown>): {
readonly payload: Record<string, unknown>;
readonly taskId?: string;
} {
- const { activityObserver, callback } = input;
- const hasTaskId = isObject(callback) && "taskId" in callback;
- const hasTaskObserver =
- isObject(activityObserver) &&
- isObject(activityObserver.workIdentity) &&
- activityObserver.workIdentity.kind === "task";
- if (!hasTaskId && !hasTaskObserver) return { payload: input };
-
- const payload = { ...input };
- // Nested activity isn't relayed: current activity has no `task` work kind.
- if (hasTaskObserver) delete payload.activityObserver;
- if (!hasTaskId) return { payload };
+ const { callback } = input;
+ if (!isObject(callback) || !("taskId" in callback)) return { payload: input };
const { taskId, ...rest } = callback;
- payload.callback = rest;
+ const payload = { ...input, callback: rest };
return typeof taskId === "string" && taskId.length > 0 ? { payload, taskId } : { payload };
}
diff --git a/packages/eve/src/execution/legacy-session/inbox.ts b/packages/eve/src/execution/legacy-session/inbox.ts
index ccde4e6b4..fccc07cda 100644
--- a/packages/eve/src/execution/legacy-session/inbox.ts
+++ b/packages/eve/src/execution/legacy-session/inbox.ts
@@ -82,19 +82,7 @@ export function encodeLegacyCommand(command: Command, declaredVersion: unknown):
return { ...command, version };
}
const payloads = command.kind === "send" ? [command.payload] : command.payloads;
- let caller = command.caller;
- if (caller?.activityObserver !== undefined && version < 7) {
- const { activityObserver, ...rest } = caller;
- if (version < 2) caller = rest;
- else {
- const workIdentity =
- activityObserver.workIdentity === undefined
- ? undefined
- : { ...activityObserver.workIdentity };
- if (workIdentity !== undefined) delete workIdentity.label;
- caller = { ...rest, activityObserver: { ...activityObserver, workIdentity } };
- }
- }
+ const caller = command.caller;
let deliveryMetadata =
command.kind === "send"
? command.delivery === undefined
diff --git a/packages/eve/src/execution/publish-session-events.ts b/packages/eve/src/execution/publish-session-events.ts
index 931cb881e..8337693f4 100644
--- a/packages/eve/src/execution/publish-session-events.ts
+++ b/packages/eve/src/execution/publish-session-events.ts
@@ -5,7 +5,6 @@ import { dispatchStreamEventHooks } from "#context/hook-lifecycle.js";
import { ParentSessionKey, TurnDeliveryIdsKey } from "#context/keys.js";
import { withContextScope } from "#context/run-step.js";
import { deserializeContext, serializeContext } from "#context/serialize.js";
-import * as activityCohort from "#execution/activity-cohort.js";
import { setChannelContext } from "#execution/channel-context.js";
import { forwardSessionInput } from "#execution/forward-session-input.js";
import {
@@ -16,7 +15,6 @@ import {
} from "#execution/durable-session-store.js";
import { resolveEffectiveAgentRuntime } from "#execution/effective-agent-config.js";
import { reconcileSessionContinuationToken } from "#execution/reconcile-session-continuation-token.js";
-import { observeSessionActivity } from "#execution/session-activity-projection.js";
import { hydrateDurableSession } from "#execution/session.js";
import { activeTurnId } from "#harness/active-turn-id.js";
import { getHarnessEmissionState } from "#harness/emission.js";
@@ -36,14 +34,14 @@ const log = createLogger("execution.publish-session-events");
/**
* Whose event a session publishes. Every event reaches the channel adapter, the
* session stream, and stream-event hooks. The session's own events also reach
- * its instrumentation and activity and carry its turn's delivery ids.
+ * its instrumentation and carry its turn's delivery ids.
*
* A relayed event belongs to an exchange this session carries for a child
* session or a workflow run: the question or sign-in it raised, the turn
* boundary that question causes here, and the `input.resolved` for the answer
- * this session routes back. This session's instrumentation and activity never
- * track that pending input, so no event of the exchange reaches them; the
- * child records its side as its own.
+ * this session routes back. This session's instrumentation never tracks that
+ * pending input, so no event of the exchange reaches it; the child records its
+ * side as its own.
*/
export type SessionEventOrigin = "own" | "relayed";
@@ -186,7 +184,6 @@ async function publishInSessionScope<T>(
ctx,
inputSource: publication.inputSource,
origin: publication.origin,
- sessionId: session.sessionId,
sessionWritable: step.sessionWritable,
});
try {
@@ -220,7 +217,7 @@ interface StreamWriter extends SessionEventWriter {
write(event: UnstampedMessageStreamEvent): Promise<MessageStreamEvent>;
}
-/** Dispatches a session's events to its channel, activity, and stream-event hooks. */
+/** Dispatches a session's events to its channel and stream-event hooks. */
export interface SessionEventDispatcher {
/** The context delivery hands the channel adapter; a turn step also hands it to `adapter.deliver`. */
readonly adapterCtx: ChannelAdapterContext;
@@ -233,13 +230,10 @@ export interface SessionEventDispatcher {
interface EventDispatcher extends SessionEventDispatcher {
/**
- * Channel delivery: the activity state update, then `forwardSessionInput` or
- * the channel adapter's handler, then the channel context. Returns the event
- * as the handler left it.
+ * Channel delivery: `forwardSessionInput` or the channel adapter's handler,
+ * then the channel context. Returns the event as the handler left it.
*/
deliver(event: UnstampedMessageStreamEvent): Promise<UnstampedMessageStreamEvent>;
- /** Projects a written event onto the session's activity. */
- projectActivity(event: MessageStreamEvent): void;
}
/** A session's stream held by one step, with the dispatch of the events that step publishes. */
@@ -247,7 +241,7 @@ export interface SessionEventPublisher {
readonly dispatcher: SessionEventDispatcher;
readonly writer: SessionEventWriter;
/**
- * Delivers, writes, and projects one event the step produced, and returns it
+ * Delivers and writes one event the step produced, and returns it
* as written for its hooks. Delivery comes first so the channel adapter's
* handler shapes what is written.
*/
@@ -259,7 +253,6 @@ export interface SessionEventPublisher {
export function openSessionEventPublisher(input: {
readonly ctx: ContextContainer;
readonly origin: SessionEventOrigin;
- readonly sessionId: string;
readonly sessionWritable: WritableStream<Uint8Array>;
readonly inputSource?: string;
}): SessionEventPublisher {
@@ -272,9 +265,7 @@ export function openSessionEventPublisher(input: {
sessionWritable: input.sessionWritable,
});
const emit = async (event: UnstampedMessageStreamEvent): Promise<MessageStreamEvent> => {
- const written = await writer.write(await dispatcher.deliver(event));
- dispatcher.projectActivity(written);
- return written;
+ return await writer.write(await dispatcher.deliver(event));
};
return {
dispatcher,
@@ -288,18 +279,15 @@ export function openSessionEventPublisher(input: {
function createSessionEventDispatcher(input: {
readonly ctx: ContextContainer;
- readonly origin: SessionEventOrigin;
- readonly sessionId: string;
readonly inputSource?: string;
}): EventDispatcher {
- const { ctx, inputSource, origin } = input;
+ const { ctx, inputSource } = input;
const adapter = ctx.require(ChannelKey);
const adapterCtx = buildAdapterContext(adapter, ctx);
return {
adapterCtx,
async deliver(event) {
- if (origin === "own") activityCohort.updateActivityState(ctx, event);
const forwarded = await forwardSessionInput(ctx, event, inputSource);
const routed = forwarded
? event
@@ -311,9 +299,6 @@ function createSessionEventDispatcher(input: {
setChannelContext(ctx, { ...adapter, state: { ...adapterCtx.state } });
return routed;
},
- projectActivity(event) {
- if (origin === "own") void observeSessionActivity({ ctx, event, sessionId: input.sessionId });
- },
async runHooks(event, cancelTurn) {
// Read here rather than when the dispatcher is built: terminal delivery
// runs no hooks and must not require the bundle.
@@ -390,7 +375,6 @@ export async function publishTerminalSessionEvent(input: {
publisher = openSessionEventPublisher({
ctx,
origin: "own",
- sessionId,
sessionWritable: input.sessionWritable,
});
} catch (error) {
diff --git a/packages/eve/src/execution/runtime-context.test.ts b/packages/eve/src/execution/runtime-context.test.ts
index aba52b063..74958f321 100644
--- a/packages/eve/src/execution/runtime-context.test.ts
+++ b/packages/eve/src/execution/runtime-context.test.ts
@@ -9,7 +9,6 @@ import {
ParentTraceContextKey,
type Session,
type SessionAuthContext,
- ActivityObserverKey,
SessionIdKey,
SessionKey,
ScheduleIdKey,
@@ -314,31 +313,6 @@ describe("buildRunContext", () => {
expect(ctx.get(SessionIdKey)).toBeUndefined();
});
- it("seeds inherited private activity observer configuration", () => {
- const sink = {
- url: "https://root.example.com/eve/v1/activity/abcdefghijklmnopqrstuvwxyz123456",
- version: 1 as const,
- };
- const workIdentity = {
- id: "work:root:turn:call",
- kind: "subagent" as const,
- parentId: "work:root:turn",
- rootSessionId: "root",
- rootTurnId: "turn",
- };
- const ctx = buildRunContext({
- bundle: createMinimalBundle(),
- run: {
- auth: null,
- adapter: { kind: "subagent" },
- input: { message: "hi" },
- activityObserver: { sink, workIdentity },
- },
- });
-
- expect(ctx.get(ActivityObserverKey)).toEqual({ sink, workIdentity });
- });
-
it("grafts parent custom metadata and inherits the conversation audience", () => {
const parentProjection = {
kind: "channel:slack",
diff --git a/packages/eve/src/execution/runtime-context.ts b/packages/eve/src/execution/runtime-context.ts
index f0d755f37..1c69a1f5f 100644
--- a/packages/eve/src/execution/runtime-context.ts
+++ b/packages/eve/src/execution/runtime-context.ts
@@ -14,7 +14,6 @@ import {
InitiatorAuthKey,
ParentSessionKey,
ParentTraceContextKey,
- ActivityObserverKey,
ScheduleIdKey,
SessionCallbackKey,
LegacyRemoteAgentCallerKey,
@@ -98,9 +97,6 @@ export function buildRunContext(input: {
if (run.legacyRemoteAgentCaller !== undefined) {
ctx.set(LegacyRemoteAgentCallerKey, run.legacyRemoteAgentCaller);
}
- if (run.activityObserver !== undefined) {
- ctx.set(ActivityObserverKey, run.activityObserver);
- }
if (run.parent !== undefined) {
ctx.set(ParentSessionKey, run.parent);
diff --git a/packages/eve/src/execution/session-activity-projection.test.ts b/packages/eve/src/execution/session-activity-projection.test.ts
deleted file mode 100644
index f4c554a1d..000000000
--- a/packages/eve/src/execution/session-activity-projection.test.ts
+++ /dev/null
@@ -1,432 +0,0 @@
-import { afterEach, describe, expect, it, vi } from "vitest";
-
-import {
- ActivityObserverKey,
- ActivityPendingBlockersKey,
- ActivityTaskCallsKey,
-} from "#context/keys.js";
-import {
- retainAnswerableActivityBlockers,
- updateActivityState,
-} from "#execution/activity-cohort.js";
-import { ContextContainer } from "#context/container.js";
-import {
- observeSessionActivity,
- projectSessionActivity,
-} from "#execution/session-activity-projection.js";
-import { deriveRootTurnActivityWorkId } from "#execution/activity-work-id.js";
-import { createActivitySnapshot, reduceActivityBatch } from "#execution/session-activity.js";
-import type { ActivitySnapshotV1, ActivityWorkIdentityV1 } from "#protocol/activity.js";
-import type { MessageStreamEvent } from "#protocol/message.js";
-import { captureLogRecords } from "#internal/testing/log-records.js";
-import { appendPendingInputBatch } from "#harness/pending-input-batches.js";
-import type { HarnessSession, SessionStateMap } from "#harness/types.js";
-
-const at = "2026-01-01T00:00:00.000Z";
-
-function turnEvent(type: "turn.started" | "turn.completed", turnId = "turn-1"): MessageStreamEvent {
- return {
- data: { sequence: 0, turnId },
- meta: { at, id: `${type}:${turnId}` },
- type,
- };
-}
-
-function context(): ContextContainer {
- const ctx = new ContextContainer();
- ctx.set(ActivityObserverKey, {
- sink: {
- url: "https://agent.example.com/eve/v1/activity/abcdefghijklmnopqrstuvwxyz123456",
- version: 1,
- },
- });
- return ctx;
-}
-
-function reduceProjection(input: {
- readonly events: readonly MessageStreamEvent[];
- readonly sessionId: string;
- /** The session state a `turn.cancelled` settles, as `settleCancelledTurnStep` reads it. */
- readonly cancelledState?: SessionStateMap;
- readonly workIdentity?: ActivityWorkIdentityV1;
-}): ActivitySnapshotV1 {
- const ctx = context();
- return input.events.reduce((snapshot, event) => {
- if (event.type === "turn.cancelled") {
- retainAnswerableActivityBlockers(ctx, input.cancelledState);
- }
- updateActivityState(ctx, event);
- return reduceActivityBatch(snapshot, {
- events: projectSessionActivity({
- event,
- sessionId: input.sessionId,
- suppressSettlement: ctx.has(ActivityPendingBlockersKey),
- workIdentity: input.workIdentity,
- }),
- version: 1,
- });
- }, createActivitySnapshot());
-}
-
-const delegatedWork: ActivityWorkIdentityV1 = {
- callId: "call-1",
- id: "work:parent:turn-1:call-1",
- kind: "subagent",
- name: "researcher",
- parentId: "root:parent:turn-1",
- rootSessionId: "parent",
- rootTurnId: "turn-1",
-};
-const questionBlockerId = `input:${delegatedWork.id}:request-1`;
-
-function inputRequested(
- requestId: string,
- kind: "question" | "tool-approval",
- turnId = "child-turn",
-): MessageStreamEvent {
- return {
- data: {
- requests: [
- {
- action: { callId: `${requestId}-call`, input: {}, kind: "tool-call", toolName: "search" },
- kind,
- prompt: "Which region?",
- requestId,
- },
- ],
- sequence: 1,
- stepIndex: 0,
- turnId,
- },
- meta: { at, id: `input-requested:${requestId}` },
- type: "input.requested",
- };
-}
-
-const turnCancelled: MessageStreamEvent = {
- data: { sequence: 1, turnId: "child-turn" },
- meta: { at, id: "turn.cancelled:child-turn" },
- type: "turn.cancelled",
-};
-
-/** A delegated session whose running turn asked a question. */
-const askedQuestion: readonly MessageStreamEvent[] = [
- { data: {}, meta: { at, id: "session-started" }, type: "session.started" },
- inputRequested("request-1", "question"),
-];
-
-/** The same session after its turn parked awaiting the answer. */
-const parkedOnQuestion: readonly MessageStreamEvent[] = [
- ...askedQuestion,
- turnEvent("turn.completed", "child-turn"),
- {
- data: { continuationToken: "child-token", wait: "next-user-message" },
- meta: { at, id: "session-waiting" },
- type: "session.waiting",
- },
-];
-
-function projectDelegated(
- events: readonly MessageStreamEvent[],
- cancelledState?: SessionStateMap,
-): ActivitySnapshotV1 {
- return reduceProjection({
- cancelledState,
- events,
- sessionId: "child-session",
- workIdentity: delegatedWork,
- });
-}
-
-describe("projectSessionActivity", () => {
- it("maps turn.started and turn.completed to root work lifecycle", () => {
- const sessionId = "session-1";
- const workId = deriveRootTurnActivityWorkId({ sessionId, turnId: "turn-1" });
- expect(
- [turnEvent("turn.started"), turnEvent("turn.completed")].flatMap((event) =>
- projectSessionActivity({ event, sessionId }),
- ),
- ).toEqual([
- {
- eventId: `${workId}:started`,
- kind: "work.started",
- startedAt: at,
- work: {
- id: workId,
- kind: "root-turn",
- rootSessionId: "session-1",
- rootTurnId: "turn-1",
- sessionId: "session-1",
- turnId: "turn-1",
- },
- },
- {
- eventId: `${workId}:settled:completed`,
- kind: "work.settled",
- outcome: "completed",
- settledAt: at,
- workId,
- },
- ]);
- });
-
- it("groups a resumed turn with its originating root work", () => {
- const sessionId = "session-1";
- const started = projectSessionActivity({
- event: turnEvent("turn.started", "turn-2"),
- rootTurnId: "turn-1",
- sessionId,
- });
- expect(started).toEqual([
- expect.objectContaining({
- kind: "work.started",
- work: expect.objectContaining({
- id: deriveRootTurnActivityWorkId({ sessionId, turnId: "turn-1" }),
- rootTurnId: "turn-1",
- turnId: "turn-2",
- }),
- }),
- ]);
- });
-
- it("keeps an originating root open while HITL or subagent work is pending", () => {
- const event = turnEvent("turn.completed", "turn-1");
- expect(
- projectSessionActivity({
- event,
- rootTurnId: "turn-1",
- sessionId: "session-1",
- suppressSettlement: true,
- }),
- ).toEqual([]);
- });
-
- it("reduces replayed root events to one completed work summary", () => {
- const sequence = [turnEvent("turn.started"), turnEvent("turn.completed")];
- const snapshot = reduceProjection({
- events: [...sequence, ...sequence],
- sessionId: "session-1",
- });
-
- const workId = deriveRootTurnActivityWorkId({ sessionId: "session-1", turnId: "turn-1" });
- expect(snapshot.work).toEqual({
- [workId]: expect.objectContaining({ id: workId, phase: "completed" }),
- });
- expect(snapshot.pendingSettlements).toEqual({});
- });
-
- it("keeps a task call running from its receipt until task.settled", () => {
- const ctx = context();
- const coordinates = { sequence: 0, stepIndex: 0, turnId: "turn-1" };
- const call = { callId: "call-1", taskId: "task-1", turnId: "turn-1" };
- const receipt: MessageStreamEvent = {
- data: {
- ...coordinates,
- result: { callId: "call-1", kind: "tool-result", output: "Started", toolName: "report" },
- status: "completed",
- },
- meta: { at, id: "receipt" },
- type: "action.result",
- };
- const settled: MessageStreamEvent = {
- data: { ...call, error: { message: "Source unavailable." }, status: "failed" },
- meta: { at, id: "task-settled" },
- type: "task.settled",
- };
- const events: MessageStreamEvent[] = [
- {
- data: {
- ...coordinates,
- actions: [{ callId: "call-1", input: {}, kind: "tool-call", toolName: "report" }],
- },
- meta: { at, id: "actions" },
- type: "actions.requested",
- },
- {
- data: { ...call, kind: "tool", name: "report" },
- meta: { at, id: "task-started" },
- type: "task.started",
- },
- receipt,
- ];
- const reduce = (snapshot: ActivitySnapshotV1, event: MessageStreamEvent) => {
- updateActivityState(ctx, event);
- return reduceActivityBatch(snapshot, {
- events: projectSessionActivity({
- event,
- sessionId: "session-1",
- taskCallIds: ctx.get(ActivityTaskCallsKey),
- }),
- version: 1,
- });
- };
- const actionId = `action:${deriveRootTurnActivityWorkId({ sessionId: "session-1", turnId: "turn-1" })}:call-1`;
-
- const afterReceipt = events.reduce(reduce, createActivitySnapshot());
- expect(afterReceipt.actions[actionId]).toMatchObject({ phase: "running" });
-
- const afterSettled = reduce(afterReceipt, settled);
- expect(afterSettled.actions[actionId]).toMatchObject({ phase: "failed" });
- });
-
- it("uses the durable partial event id for activity updates", () => {
- const event: MessageStreamEvent = {
- data: {
- presentation: { "tool-1": { label: "Collecting sources" } },
- result: {
- callId: "tool-1",
- kind: "tool-result",
- output: { phase: "Collecting" },
- toolName: "build_report",
- },
- sequence: 0,
- stepIndex: 0,
- turnId: "turn-1",
- },
- meta: { at, id: "partial-1" },
- type: "action.partial",
- };
-
- expect(
- projectSessionActivity({
- event,
- sessionId: "session-1",
- }),
- ).toEqual([
- expect.objectContaining({
- eventId: expect.stringContaining(":update:partial-1"),
- kind: "action.label.updated",
- label: "Collecting sources",
- }),
- ]);
- });
-
- it("maps session and later turn starts to the active delegated work", () => {
- const first: ActivityWorkIdentityV1 = {
- callId: "call-1",
- id: "work:first",
- kind: "subagent",
- name: "researcher",
- rootSessionId: "parent",
- rootTurnId: "root-turn",
- };
- const second = { ...first, callId: "call-2", id: "work:second" };
-
- expect(
- projectSessionActivity({
- event: { data: {}, meta: { at, id: "session-started" }, type: "session.started" },
- sessionId: "child",
- workIdentity: first,
- }),
- ).toEqual([
- expect.objectContaining({
- kind: "work.started",
- work: expect.objectContaining({ id: first.id }),
- }),
- ]);
- expect(
- projectSessionActivity({
- event: turnEvent("turn.started", "child-turn-2"),
- sessionId: "child",
- workIdentity: second,
- }),
- ).toEqual([
- expect.objectContaining({
- kind: "work.started",
- work: expect.objectContaining({ id: second.id }),
- }),
- ]);
- });
-
- it("keeps delegated work open while its turn waits on a person, then settles it with the resumed turn", () => {
- const resumed: MessageStreamEvent[] = [
- {
- data: {
- resolutions: [{ kind: "question", outcome: "answered", requestId: "request-1" }],
- sequence: 2,
- stepIndex: 0,
- turnId: "child-turn-2",
- },
- meta: { at, id: "input-resolved" },
- type: "input.resolved",
- },
- turnEvent("turn.started", "child-turn-2"),
- turnEvent("turn.completed", "child-turn-2"),
- ];
-
- const whileParked = projectDelegated(parkedOnQuestion);
- expect(whileParked.work[delegatedWork.id]).toMatchObject({ phase: "running" });
- expect(whileParked.blockers[questionBlockerId]).toMatchObject({ phase: "blocked" });
-
- expect(
- projectDelegated([...parkedOnQuestion, ...resumed]).work[delegatedWork.id],
- ).toMatchObject({ phase: "completed" });
- });
-
- it("settles work and its question when the turn waiting on the question is cancelled", () => {
- const snapshot = projectDelegated([...askedQuestion, turnCancelled]);
-
- expect(snapshot.work[delegatedWork.id]).toMatchObject({ phase: "cancelled" });
- expect(snapshot.blockers[questionBlockerId]).toMatchObject({ phase: "cancelled" });
- });
-
- it("keeps work open after a cancel while its own approval can still be answered", () => {
- const approval = inputRequested("approval-1", "tool-approval");
- const stillAwaitingApproval = appendPendingInputBatch({
- requests: approval.type === "input.requested" ? approval.data.requests : [],
- responseMessages: [],
- session: {} as HarnessSession,
- });
-
- const snapshot = projectDelegated(
- [...askedQuestion, approval, turnEvent("turn.completed", "child-turn"), turnCancelled],
- stillAwaitingApproval.state,
- );
-
- expect(snapshot.work[delegatedWork.id]).toMatchObject({ phase: "running" });
- expect(snapshot.blockers[`approval:${delegatedWork.id}:approval-1`]).toMatchObject({
- phase: "blocked",
- });
- });
-});
-
-describe("observeSessionActivity", () => {
- afterEach(() => vi.unstubAllGlobals());
-
- it("does not submit events with no activity projection", async () => {
- const fetchMock = vi.fn();
- vi.stubGlobal("fetch", fetchMock);
- const event: MessageStreamEvent = {
- data: {
- messageDelta: "hello",
- sequence: 0,
- stepIndex: 0,
- turnId: "turn-1",
- },
- meta: { at, id: "message" },
- type: "message.appended",
- };
-
- await observeSessionActivity({ ctx: context(), event, sessionId: "session-1" });
-
- expect(fetchMock).not.toHaveBeenCalled();
- });
-
- it("submits projected activity and swallows transport failure", async () => {
- const logs = captureLogRecords();
- const fetchMock = vi.fn().mockRejectedValue(new Error("network down"));
- vi.stubGlobal("fetch", fetchMock);
-
- await expect(
- observeSessionActivity({
- ctx: context(),
- event: turnEvent("turn.started"),
- sessionId: "session-1",
- }),
- ).resolves.toBeUndefined();
- expect(fetchMock).toHaveBeenCalledOnce();
- expect(logs.records).toContainEqual(
- expect.objectContaining({ level: "warn", message: "activity sink request failed" }),
- );
- });
-});
diff --git a/packages/eve/src/execution/session-activity-projection.ts b/packages/eve/src/execution/session-activity-projection.ts
deleted file mode 100644
index 1f2c73199..000000000
--- a/packages/eve/src/execution/session-activity-projection.ts
+++ /dev/null
@@ -1,111 +0,0 @@
-import type { ContextContainer } from "#context/container.js";
-import {
- ActivityObserverKey,
- ActivityPendingBlockersKey,
- ActivityRootTurnIdKey,
- ActivityTaskCallsKey,
-} from "#context/keys.js";
-import { projectActivityEvents } from "#execution/activity-events.js";
-import { deriveRootTurnActivityWorkId } from "#execution/activity-work-id.js";
-import { submitActivity } from "#execution/submit-activity.js";
-import type { ActivityEventV1, ActivityWorkIdentityV1 } from "#protocol/activity.js";
-import type { MessageStreamEvent } from "#protocol/message.js";
-
-/** Projects one canonical session event into best-effort activity presentation. */
-export async function observeSessionActivity(input: {
- readonly ctx: ContextContainer;
- readonly event: MessageStreamEvent;
- readonly sessionId: string;
-}): Promise<void> {
- const observer = input.ctx.get(ActivityObserverKey);
- if (observer === undefined) return;
- await submitActivity({
- events: projectSessionActivity({
- event: input.event,
- rootTurnId: input.ctx.get(ActivityRootTurnIdKey),
- sessionId: input.sessionId,
- suppressSettlement: (input.ctx.get(ActivityPendingBlockersKey)?.length ?? 0) > 0,
- taskCallIds: input.ctx.get(ActivityTaskCallsKey),
- workIdentity: observer.workIdentity,
- }),
- sink: observer.sink,
- });
-}
-
-export function projectSessionActivity(input: {
- readonly event: MessageStreamEvent;
- readonly rootTurnId?: string;
- readonly sessionId: string;
- /** A turn that ends waiting on a person leaves its work open until it resumes. */
- readonly suppressSettlement?: boolean;
- readonly taskCallIds?: readonly string[];
- readonly workIdentity?: ActivityWorkIdentityV1;
-}): readonly ActivityEventV1[] {
- const work = workFor(input);
- if (work === undefined) return [];
-
- const events: ActivityEventV1[] = [];
- if (
- (work.kind === "root-turn" && input.event.type === "turn.started") ||
- (work.kind !== "root-turn" &&
- (input.event.type === "session.started" || input.event.type === "turn.started"))
- ) {
- events.push({
- eventId: `${work.id}:started`,
- kind: "work.started",
- startedAt: input.event.meta.at,
- work,
- });
- }
- if (
- input.suppressSettlement === true &&
- (input.event.type === "turn.completed" ||
- input.event.type === "turn.failed" ||
- input.event.type === "turn.cancelled")
- ) {
- return events;
- }
- events.push(
- ...projectActivityEvents({
- at: input.event.meta.at,
- event: input.event,
- eventId: input.event.meta.id,
- lineage: work,
- taskCallIds: input.taskCallIds,
- }),
- );
- return events;
-}
-
-function workFor(input: {
- readonly event: MessageStreamEvent;
- readonly rootTurnId?: string;
- readonly sessionId: string;
- readonly workIdentity?: ActivityWorkIdentityV1;
-}): ActivityWorkIdentityV1 | undefined {
- const turnId = eventTurnId(input.event);
- if (input.workIdentity !== undefined) {
- return {
- ...input.workIdentity,
- sessionId: input.sessionId,
- turnId: turnId ?? input.workIdentity.turnId,
- };
- }
- if (turnId === undefined) return undefined;
- const rootTurnId = input.rootTurnId ?? turnId;
- return {
- id: deriveRootTurnActivityWorkId({ sessionId: input.sessionId, turnId: rootTurnId }),
- kind: "root-turn",
- rootSessionId: input.sessionId,
- rootTurnId,
- sessionId: input.sessionId,
- turnId,
- };
-}
-
-function eventTurnId(event: MessageStreamEvent): string | undefined {
- if ("data" in event && "turnId" in event.data && typeof event.data.turnId === "string") {
- return event.data.turnId;
- }
- return undefined;
-}
diff --git a/packages/eve/src/execution/session-activity-renderer-step.test.ts b/packages/eve/src/execution/session-activity-renderer-step.test.ts
deleted file mode 100644
index 98bdf0200..000000000
--- a/packages/eve/src/execution/session-activity-renderer-step.test.ts
+++ /dev/null
@@ -1,58 +0,0 @@
-import { describe, expect, it, vi } from "vitest";
-
-import { attachChannelActivityPresentation } from "#channel/activity-renderer.js";
-import { deserializeContext } from "#context/serialize.js";
-import { createActivitySnapshot } from "#execution/session-activity.js";
-import { renderSessionActivityStep } from "#execution/session-activity-renderer-step.js";
-
-vi.mock("#context/serialize.js", () => ({ deserializeContext: vi.fn() }));
-
-vi.mock("#internal/logging.js", () => ({
- createLogger: () => ({ error: vi.fn() }),
- logError: vi.fn(),
-}));
-
-describe("renderSessionActivityStep", () => {
- it("isolates renderer state and continues after a renderer failure", async () => {
- const failed = vi.fn().mockRejectedValue(new Error("provider unavailable"));
- const rendered = vi.fn().mockResolvedValue({ status: "Working..." });
- const adapter = {
- kind: "slack",
- state: { channelId: "C1", secret: "hidden", threadTs: "T1" },
- };
- attachChannelActivityPresentation(adapter, {
- destination: () => ({ channelId: "C1", threadTs: "T1" }),
- renderers: [
- { id: "failed", render: failed },
- { id: "status", render: rendered },
- ],
- });
- vi.mocked(deserializeContext).mockResolvedValue({ require: () => adapter } as never);
- const snapshot = createActivitySnapshot();
-
- await expect(
- renderSessionActivityStep({
- rendererStates: { failed: { attempt: 1 }, status: { status: "Thinking..." } },
- serializedContext: {},
- snapshot,
- }),
- ).resolves.toEqual({
- rendererStates: {
- failed: { attempt: 1 },
- status: { status: "Working..." },
- },
- });
-
- expect(failed).toHaveBeenCalledTimes(2);
- expect(failed).toHaveBeenLastCalledWith({
- destination: { channelId: "C1", threadTs: "T1" },
- snapshot,
- state: { attempt: 1 },
- });
- expect(rendered).toHaveBeenCalledWith({
- destination: { channelId: "C1", threadTs: "T1" },
- snapshot,
- state: { status: "Thinking..." },
- });
- });
-});
diff --git a/packages/eve/src/execution/session-activity-renderer-step.ts b/packages/eve/src/execution/session-activity-renderer-step.ts
deleted file mode 100644
index 3980427f5..000000000
--- a/packages/eve/src/execution/session-activity-renderer-step.ts
+++ /dev/null
@@ -1,81 +0,0 @@
-import { getChannelActivityPresentation } from "#channel/activity-renderer.js";
-import { deserializeContext } from "#context/serialize.js";
-import type { ActivitySnapshotV1 } from "#protocol/activity.js";
-import { createLogger, logError } from "#internal/logging.js";
-import { ChannelKey } from "#runtime/sessions/runtime-context-keys.js";
-
-const log = createLogger("execution.session-activity-renderer");
-
-export interface SessionActivityRenderState {
- readonly rendererStates: Readonly<Record<string, unknown>>;
-}
-
-/** Runs channel-owned activity effects from collector-owned immutable context. */
-export async function renderSessionActivityStep(input: {
- readonly rendererStates: Readonly<Record<string, unknown>>;
- readonly serializedContext: Record<string, unknown>;
- readonly snapshot: ActivitySnapshotV1;
-}): Promise<SessionActivityRenderState> {
- "use step";
-
- const { adapter, destination, presentation } = await resolveActivityPresentation(
- input.serializedContext,
- );
- const rendererStates: Record<string, unknown> = { ...input.rendererStates };
- for (const renderer of presentation.renderers) {
- for (let attempt = 0; attempt < 2; attempt += 1) {
- try {
- rendererStates[renderer.id] = await renderer.render({
- destination,
- snapshot: input.snapshot,
- state: rendererStates[renderer.id],
- });
- break;
- } catch (error) {
- logError(log, "activity renderer failed", error, {
- adapterKind: adapter.kind,
- attempt: attempt + 1,
- rendererId: renderer.id,
- revision: input.snapshot.revision,
- });
- if (attempt === 0) await new Promise((resolve) => setTimeout(resolve, 250));
- }
- }
- }
- return { rendererStates };
-}
-
-/** Best-effort cleanup of transient provider state when collector ownership expires. */
-export async function disposeSessionActivityStep(input: {
- readonly rendererStates: Readonly<Record<string, unknown>>;
- readonly serializedContext: Record<string, unknown>;
-}): Promise<void> {
- "use step";
-
- const { adapter, destination, presentation } = await resolveActivityPresentation(
- input.serializedContext,
- );
- for (const renderer of presentation.renderers) {
- if (renderer.dispose === undefined) continue;
- try {
- await renderer.dispose({ destination, state: input.rendererStates[renderer.id] });
- } catch (error) {
- logError(log, "activity renderer disposal failed", error, {
- adapterKind: adapter.kind,
- rendererId: renderer.id,
- });
- }
- }
-}
-
-async function resolveActivityPresentation(serializedContext: Record<string, unknown>) {
- const ctx = await deserializeContext(serializedContext);
- const adapter = ctx.require(ChannelKey);
- const presentation = getChannelActivityPresentation(adapter);
- if (presentation === undefined) throw new Error("Channel has no activity presentation.");
- return {
- adapter,
- destination: presentation.destination(adapter.state),
- presentation,
- };
-}
diff --git a/packages/eve/src/execution/session-activity.test.ts b/packages/eve/src/execution/session-activity.test.ts
deleted file mode 100644
index 015596f6c..000000000
--- a/packages/eve/src/execution/session-activity.test.ts
+++ /dev/null
@@ -1,296 +0,0 @@
-import { describe, expect, it } from "vitest";
-
-import { createActivitySnapshot, reduceActivityBatch } from "#execution/session-activity.js";
-import { parseActivityBatchV1, type ActivityEventV1 } from "#protocol/activity.js";
-
-const work = {
- id: "root:session:turn",
- kind: "root-turn" as const,
- rootSessionId: "session",
- rootTurnId: "turn",
-};
-
-function reduce(events: readonly ActivityEventV1[]) {
- return reduceActivityBatch(createActivitySnapshot(), { events, version: 1 });
-}
-
-describe("activity protocol and reducer", () => {
- it("retains known siblings while ignoring additive unknown events", () => {
- expect(
- parseActivityBatchV1({
- events: [
- { eventId: "future", kind: "detail.updated", message: "working" },
- { eventId: "started", kind: "work.started", startedAt: "2026-01-01", work },
- ],
- version: 1,
- }),
- ).toEqual({
- events: [{ eventId: "started", kind: "work.started", startedAt: "2026-01-01", work }],
- version: 1,
- });
- });
-
- it("applies additive action labels without changing the action start shape", () => {
- const batch = parseActivityBatchV1({
- events: [
- {
- action: {
- id: "action",
- kind: "tool",
- name: "search",
- parentWorkId: work.id,
- rootTurnId: "turn",
- stepIndex: 0,
- },
- eventId: "action:start",
- kind: "action.started",
- startedAt: "now",
- },
- {
- actionId: "action",
- eventId: "action:label",
- kind: "action.label.updated",
- label: "Search issues",
- },
- {
- actionId: "action",
- eventId: "action:update",
- kind: "action.label.updated",
- label: "Found 3 issues",
- },
- ],
- version: 1,
- });
-
- expect(batch).toBeDefined();
- expect(reduceActivityBatch(createActivitySnapshot(), batch!).actions.action?.label).toBe(
- "Found 3 issues",
- );
- });
-
- it("rejects malformed known events", () => {
- expect(
- parseActivityBatchV1({
- events: [{ eventId: "started", kind: "work.started", work }],
- version: 1,
- }),
- ).toBeUndefined();
- });
-
- it("deduplicates only by event id", () => {
- const event = { eventId: "started", kind: "work.started" as const, startedAt: "now", work };
- const first = reduce([event]);
- const duplicate = reduceActivityBatch(first, { events: [event], version: 1 });
- expect(duplicate).toBe(first);
- });
-
- it("applies settlement before start and never reopens terminal work", () => {
- const settled = reduce([
- {
- eventId: "settled",
- kind: "work.settled",
- outcome: "completed",
- settledAt: "later",
- workId: work.id,
- },
- ]);
- const started = reduceActivityBatch(settled, {
- events: [{ eventId: "started", kind: "work.started", startedAt: "earlier", work }],
- version: 1,
- });
- const duplicateStart = reduceActivityBatch(started, {
- events: [{ eventId: "started-again", kind: "work.started", startedAt: "latest", work }],
- version: 1,
- });
- expect(started.work[work.id]?.phase).toBe("completed");
- expect(duplicateStart.work[work.id]).toBe(started.work[work.id]);
- });
-
- it.each([
- ["child before parent", ["child", "root-settled", "root"]],
- ["parent before child", ["root-settled", "root", "child"]],
- ["ordered", ["root", "child", "root-settled"]],
- ] as const)("converges work settlement for %s delivery", (_name, order) => {
- const child = {
- id: "work:child",
- kind: "subagent" as const,
- parentId: work.id,
- rootSessionId: "session",
- rootTurnId: "turn",
- };
- const events: Record<string, ActivityEventV1> = {
- root: { eventId: "root", kind: "work.started", startedAt: "1", work },
- child: { eventId: "child", kind: "work.started", startedAt: "2", work: child },
- "root-settled": {
- eventId: "root-settled",
- kind: "work.settled",
- outcome: "failed",
- settledAt: "3",
- workId: work.id,
- },
- };
-
- const snapshot = reduce(order.map((key) => events[key]!));
-
- expect(snapshot.work[work.id]?.phase).toBe("failed");
- expect(snapshot.work[child.id]?.phase).toBe("cancelled");
- expect(snapshot.pendingSettlements).toEqual({});
- });
-
- it("cancels early actions and blockers when their parent starts terminal", () => {
- const snapshot = reduce([
- {
- action: {
- id: "action",
- kind: "tool",
- name: "search",
- parentWorkId: work.id,
- rootTurnId: "turn",
- stepIndex: 0,
- },
- eventId: "action",
- kind: "action.started",
- startedAt: "1",
- },
- {
- blocker: {
- id: "input",
- kind: "input",
- parentWorkId: work.id,
- rootTurnId: "turn",
- },
- eventId: "input",
- kind: "blocker.started",
- startedAt: "1",
- },
- {
- eventId: "settled",
- kind: "work.settled",
- outcome: "completed",
- settledAt: "2",
- workId: work.id,
- },
- { eventId: "root", kind: "work.started", startedAt: "0", work },
- ]);
-
- expect(snapshot.work[work.id]?.phase).toBe("completed");
- expect(snapshot.actions.action?.phase).toBe("cancelled");
- expect(snapshot.blockers.input?.phase).toBe("cancelled");
- });
-
- it("retains unmatched settlement without changing revision", () => {
- const initial = createActivitySnapshot();
- const next = reduceActivityBatch(initial, {
- events: [
- {
- blockerId: "authorization:work:attempt",
- eventId: "settled",
- kind: "blocker.settled",
- outcome: "completed",
- settledAt: "now",
- },
- ],
- version: 1,
- });
- expect(next.revision).toBe(0);
- expect(next.pendingSettlements).toHaveProperty("blocker:authorization:work:attempt");
- });
-
- it("recursively cancels active descendant work and its owned entities", () => {
- const child = {
- id: "work:child",
- kind: "subagent" as const,
- parentId: work.id,
- rootSessionId: "session",
- rootTurnId: "turn",
- };
- const grandchild = {
- id: "work:grandchild",
- kind: "subagent" as const,
- parentId: child.id,
- rootSessionId: "session",
- rootTurnId: "turn",
- };
- const snapshot = reduce([
- { eventId: "root", kind: "work.started", startedAt: "1", work },
- { eventId: "child", kind: "work.started", startedAt: "2", work: child },
- { eventId: "grandchild", kind: "work.started", startedAt: "3", work: grandchild },
- {
- action: {
- id: "grandchild-action",
- kind: "tool",
- name: "search",
- parentWorkId: grandchild.id,
- rootTurnId: "turn",
- stepIndex: 0,
- },
- eventId: "grandchild-action",
- kind: "action.started",
- startedAt: "4",
- },
- {
- blocker: {
- id: "child-input",
- kind: "input",
- parentWorkId: child.id,
- rootTurnId: "turn",
- },
- eventId: "child-input",
- kind: "blocker.started",
- startedAt: "5",
- },
- {
- eventId: "root-settled",
- kind: "work.settled",
- outcome: "failed",
- settledAt: "6",
- workId: work.id,
- },
- ]);
-
- expect(snapshot.work[work.id]?.phase).toBe("failed");
- expect(snapshot.work[child.id]?.phase).toBe("cancelled");
- expect(snapshot.work[grandchild.id]?.phase).toBe("cancelled");
- expect(snapshot.actions["grandchild-action"]?.phase).toBe("cancelled");
- expect(snapshot.blockers["child-input"]?.phase).toBe("cancelled");
- });
-
- it("cancels running owned actions and blockers when work settles", () => {
- const snapshot = reduce([
- { eventId: "work", kind: "work.started", startedAt: "1", work },
- {
- action: {
- id: "action",
- kind: "tool",
- name: "search",
- parentWorkId: work.id,
- rootTurnId: "turn",
- stepIndex: 0,
- },
- eventId: "action",
- kind: "action.started",
- startedAt: "2",
- },
- {
- blocker: {
- id: "input",
- kind: "input",
- parentWorkId: work.id,
- rootTurnId: "turn",
- },
- eventId: "input",
- kind: "blocker.started",
- startedAt: "3",
- },
- {
- eventId: "settled",
- kind: "work.settled",
- outcome: "failed",
- settledAt: "4",
- workId: work.id,
- },
- ]);
- expect(snapshot.actions.action?.phase).toBe("cancelled");
- expect(snapshot.blockers.input?.phase).toBe("cancelled");
- });
-});
diff --git a/packages/eve/src/execution/session-activity.ts b/packages/eve/src/execution/session-activity.ts
deleted file mode 100644
index 2960b856a..000000000
--- a/packages/eve/src/execution/session-activity.ts
+++ /dev/null
@@ -1,340 +0,0 @@
-import { normalizePresentationText } from "#shared/presentation-text.js";
-import {
- type PendingActivitySettlementV1,
- type ActivityActionPhase,
- type ActivityBatchV1,
- type ActivityBlockerPhase,
- type ActivityEventV1,
- type ActivitySnapshotV1,
- type ActivityWorkPhase,
- type ActivityWorkStateV1,
-} from "#protocol/activity.js";
-
-const MAX_ACTIVITY_EVENT_IDS = 1_000;
-const MAX_ACTIVITY_PENDING_SETTLEMENTS = 500;
-const MAX_ACTIVITY_ENTITIES = 500;
-
-export function createActivitySnapshot(): ActivitySnapshotV1 {
- return {
- actions: {},
- blockers: {},
- pendingSettlements: {},
- revision: 0,
- seenEventIds: [],
- version: 1,
- work: {},
- };
-}
-
-export function reduceActivityBatch(
- snapshot: ActivitySnapshotV1,
- batch: ActivityBatchV1,
-): ActivitySnapshotV1 {
- let state = snapshot;
- let seenEventIds = snapshot.seenEventIds;
- let presentationChanged = false;
- let accepted = false;
-
- for (const event of batch.events) {
- if (seenEventIds.includes(event.eventId)) continue;
- const next = reduceEvent(state, event);
- if (next === state) continue;
- accepted = true;
- seenEventIds = appendBounded(seenEventIds, event.eventId, MAX_ACTIVITY_EVENT_IDS);
- presentationChanged ||= presentationDiffers(state, next);
- state = next;
- }
-
- if (!accepted) return snapshot;
- if (!presentationChanged) return { ...state, revision: snapshot.revision, seenEventIds };
- return { ...state, revision: snapshot.revision + 1, seenEventIds };
-}
-
-function presentationDiffers(left: ActivitySnapshotV1, right: ActivitySnapshotV1): boolean {
- return (
- left.actions !== right.actions || left.blockers !== right.blockers || left.work !== right.work
- );
-}
-
-function reduceEvent(snapshot: ActivitySnapshotV1, event: ActivityEventV1): ActivitySnapshotV1 {
- switch (event.kind) {
- case "work.started":
- return startWork(snapshot, event);
- case "work.settled":
- return settleWork(snapshot, event);
- case "action.started":
- return startAction(snapshot, event);
- case "action.settled":
- return settleAction(snapshot, event);
- case "action.label.updated":
- return updateActionLabel(snapshot, event);
- case "blocker.started":
- return startBlocker(snapshot, event);
- case "blocker.settled":
- return settleBlocker(snapshot, event);
- }
-}
-
-function startWork(
- snapshot: ActivitySnapshotV1,
- event: Extract<ActivityEventV1, { readonly kind: "work.started" }>,
-): ActivitySnapshotV1 {
- const current = snapshot.work[event.work.id];
- if (current !== undefined) return snapshot;
- const pending = pendingFor(snapshot, "work", event.work.id);
- const parent = event.work.parentId === undefined ? undefined : snapshot.work[event.work.parentId];
- const phase =
- pending?.outcome ??
- (parent !== undefined && parent.phase !== "running" ? "cancelled" : "running");
- const work: ActivityWorkStateV1 = {
- ...event.work,
- label: event.work.label === undefined ? undefined : normalizePresentationText(event.work.label),
- name: event.work.name === undefined ? undefined : normalizePresentationText(event.work.name),
- phase: phase as ActivityWorkPhase,
- settledAt: pending?.settledAt ?? (phase === "cancelled" ? parent?.settledAt : undefined),
- startedAt: event.startedAt,
- };
- const started = {
- ...snapshot,
- pendingSettlements: removeKey(snapshot.pendingSettlements, pendingKey("work", work.id)),
- work: replaceBounded(snapshot.work, work.id, work),
- };
- return work.phase === "running"
- ? started
- : settleWorkTree(started, {
- outcome: work.phase,
- settledAt: work.settledAt ?? event.startedAt,
- workId: work.id,
- });
-}
-
-function settleWork(
- snapshot: ActivitySnapshotV1,
- event: Extract<ActivityEventV1, { readonly kind: "work.settled" }>,
-): ActivitySnapshotV1 {
- const current = snapshot.work[event.workId];
- if (current === undefined) return retainPending(snapshot, "work", event.workId, event);
- if (current.phase !== "running") return snapshot;
- return settleWorkTree(snapshot, {
- outcome: event.outcome,
- settledAt: event.settledAt,
- workId: event.workId,
- });
-}
-
-function startAction(
- snapshot: ActivitySnapshotV1,
- event: Extract<ActivityEventV1, { readonly kind: "action.started" }>,
-): ActivitySnapshotV1 {
- if (snapshot.actions[event.action.id] !== undefined) return snapshot;
- const pending = pendingFor(snapshot, "action", event.action.id);
- const parent = snapshot.work[event.action.parentWorkId];
- const phase =
- pending?.outcome ??
- (parent !== undefined && parent.phase !== "running" ? "cancelled" : "running");
- return {
- ...snapshot,
- actions: replaceBounded(snapshot.actions, event.action.id, {
- ...event.action,
- name: normalizePresentationText(event.action.name),
- phase: phase as ActivityActionPhase,
- settledAt: pending?.settledAt ?? (phase === "cancelled" ? parent?.settledAt : undefined),
- startedAt: event.startedAt,
- }),
- pendingSettlements: removeKey(
- snapshot.pendingSettlements,
- pendingKey("action", event.action.id),
- ),
- };
-}
-
-function updateActionLabel(
- snapshot: ActivitySnapshotV1,
- event: Extract<ActivityEventV1, { readonly kind: "action.label.updated" }>,
-): ActivitySnapshotV1 {
- const current = snapshot.actions[event.actionId];
- if (current === undefined) return snapshot;
- const label = normalizePresentationText(event.label);
- if (current.label === label) return snapshot;
- return {
- ...snapshot,
- actions: replaceBounded(snapshot.actions, event.actionId, { ...current, label }),
- };
-}
-
-function settleAction(
- snapshot: ActivitySnapshotV1,
- event: Extract<ActivityEventV1, { readonly kind: "action.settled" }>,
-): ActivitySnapshotV1 {
- const current = snapshot.actions[event.actionId];
- if (current === undefined) return retainPending(snapshot, "action", event.actionId, event);
- if (current.phase !== "running") return snapshot;
- return {
- ...snapshot,
- actions: replaceBounded(snapshot.actions, event.actionId, {
- ...current,
- phase: event.outcome,
- settledAt: event.settledAt,
- }),
- };
-}
-
-function startBlocker(
- snapshot: ActivitySnapshotV1,
- event: Extract<ActivityEventV1, { readonly kind: "blocker.started" }>,
-): ActivitySnapshotV1 {
- if (snapshot.blockers[event.blocker.id] !== undefined) return snapshot;
- const pending = pendingFor(snapshot, "blocker", event.blocker.id);
- const parent = snapshot.work[event.blocker.parentWorkId];
- const phase =
- pending?.outcome ??
- (parent !== undefined && parent.phase !== "running" ? "cancelled" : "blocked");
- return {
- ...snapshot,
- blockers: replaceBounded(snapshot.blockers, event.blocker.id, {
- ...event.blocker,
- label:
- event.blocker.label === undefined
- ? undefined
- : normalizePresentationText(event.blocker.label),
- phase: phase as ActivityBlockerPhase,
- settledAt: pending?.settledAt ?? (phase === "cancelled" ? parent?.settledAt : undefined),
- startedAt: event.startedAt,
- }),
- pendingSettlements: removeKey(
- snapshot.pendingSettlements,
- pendingKey("blocker", event.blocker.id),
- ),
- };
-}
-
-function settleBlocker(
- snapshot: ActivitySnapshotV1,
- event: Extract<ActivityEventV1, { readonly kind: "blocker.settled" }>,
-): ActivitySnapshotV1 {
- const current = snapshot.blockers[event.blockerId];
- if (current === undefined) return retainPending(snapshot, "blocker", event.blockerId, event);
- if (current.phase !== "blocked") return snapshot;
- return {
- ...snapshot,
- blockers: replaceBounded(snapshot.blockers, event.blockerId, {
- ...current,
- phase: event.outcome,
- settledAt: event.settledAt,
- }),
- };
-}
-
-function retainPending(
- snapshot: ActivitySnapshotV1,
- entityKind: PendingActivitySettlementV1["entityKind"],
- entityId: string,
- event: Extract<ActivityEventV1, { readonly kind: `${string}.settled` }>,
-): ActivitySnapshotV1 {
- const key = pendingKey(entityKind, entityId);
- if (snapshot.pendingSettlements[key] !== undefined) return snapshot;
- return {
- ...snapshot,
- pendingSettlements: replaceBounded(
- snapshot.pendingSettlements,
- key,
- { entityKind, eventId: event.eventId, outcome: event.outcome, settledAt: event.settledAt },
- MAX_ACTIVITY_PENDING_SETTLEMENTS,
- ),
- };
-}
-
-function pendingFor(
- snapshot: ActivitySnapshotV1,
- kind: PendingActivitySettlementV1["entityKind"],
- id: string,
-): PendingActivitySettlementV1 | undefined {
- return snapshot.pendingSettlements[pendingKey(kind, id)];
-}
-
-function pendingKey(kind: PendingActivitySettlementV1["entityKind"], id: string): string {
- return `${kind}:${id}`;
-}
-
-function settleWorkTree(
- snapshot: ActivitySnapshotV1,
- input: {
- readonly outcome: Exclude<ActivityWorkPhase, "running">;
- readonly settledAt: string;
- readonly workId: string;
- },
-): ActivitySnapshotV1 {
- const subtree = new Set([input.workId]);
- let discovered = true;
- while (discovered) {
- discovered = false;
- for (const work of Object.values(snapshot.work)) {
- if (work.parentId === undefined || !subtree.has(work.parentId) || subtree.has(work.id))
- continue;
- subtree.add(work.id);
- discovered = true;
- }
- }
-
- return {
- ...snapshot,
- actions: mapActivityStates(snapshot.actions, (action) =>
- subtree.has(action.parentWorkId) && action.phase === "running"
- ? { ...action, phase: "cancelled", settledAt: input.settledAt }
- : action,
- ),
- blockers: mapActivityStates(snapshot.blockers, (blocker) =>
- subtree.has(blocker.parentWorkId) && blocker.phase === "blocked"
- ? { ...blocker, phase: "cancelled", settledAt: input.settledAt }
- : blocker,
- ),
- work: mapActivityStates(snapshot.work, (work) => {
- if (work.id === input.workId) {
- return { ...work, phase: input.outcome, settledAt: input.settledAt };
- }
- return subtree.has(work.id) && work.phase === "running"
- ? { ...work, phase: "cancelled", settledAt: input.settledAt }
- : work;
- }),
- };
-}
-
-function mapActivityStates<T>(
- values: Readonly<Record<string, T>>,
- transform: (value: T) => T,
-): Readonly<Record<string, T>> {
- let next = values;
- for (const [id, value] of Object.entries(values)) {
- const transformed = transform(value);
- if (transformed === value) continue;
- if (next === values) next = { ...values };
- (next as Record<string, T>)[id] = transformed;
- }
- return next;
-}
-
-function replaceBounded<T>(
- values: Readonly<Record<string, T>>,
- key: string,
- value: T,
- max = MAX_ACTIVITY_ENTITIES,
-): Readonly<Record<string, T>> {
- const next = { ...values, [key]: value };
- const overflow = Object.keys(next).length - max;
- for (const oldKey of Object.keys(next).slice(0, Math.max(0, overflow))) delete next[oldKey];
- return next;
-}
-
-function removeKey<T>(
- values: Readonly<Record<string, T>>,
- key: string,
-): Readonly<Record<string, T>> {
- if (values[key] === undefined) return values;
- const next = { ...values };
- delete next[key];
- return next;
-}
-
-function appendBounded<T>(values: readonly T[], value: T, max: number): readonly T[] {
- return [...values, value].slice(-max);
-}
diff --git a/packages/eve/src/execution/session/entry-input.ts b/packages/eve/src/execution/session/entry-input.ts
index 09ff5d4a2..3a897eb14 100644
--- a/packages/eve/src/execution/session/entry-input.ts
+++ b/packages/eve/src/execution/session/entry-input.ts
@@ -12,7 +12,6 @@ export const SESSION_HANDOFF_VERSION = 2;
* and deserialized at each `"use step"` boundary.
*/
export interface InitialWorkflowEntryInput {
- readonly activityCollectorRunId?: string;
readonly continuationConflictCommand?: Extract<SessionCommand, { readonly kind: "send" }>;
readonly input: RunInput["input"];
readonly kind: "initial";
diff --git a/packages/eve/src/execution/session/entry.ts b/packages/eve/src/execution/session/entry.ts
index 1a580d50b..0a863a941 100644
--- a/packages/eve/src/execution/session/entry.ts
+++ b/packages/eve/src/execution/session/entry.ts
@@ -109,12 +109,8 @@ async function bootInitialOwner(
if (stableClaim.status === "rejected") throw stableClaim.reason;
if (aliasClaim.status === "rejected") {
if (!isHookConflictError(aliasClaim.reason)) throw aliasClaim.reason;
- if (
- input.activityCollectorRunId !== undefined ||
- input.continuationConflictCommand !== undefined
- ) {
+ if (input.continuationConflictCommand !== undefined) {
await settleContinuationConflictStep({
- activityCollectorRunId: input.activityCollectorRunId,
command: input.continuationConflictCommand,
continuationToken,
});
diff --git a/packages/eve/src/execution/session/turn-step.ts b/packages/eve/src/execution/session/turn-step.ts
index 4d822044a..12c911cc2 100644
--- a/packages/eve/src/execution/session/turn-step.ts
+++ b/packages/eve/src/execution/session/turn-step.ts
@@ -88,7 +88,6 @@ import {
createCancelledModelCallBatchResult,
type CompletedModelCallCheckpoint,
} from "#execution/cancelled-model-call-batch.js";
-import * as activityCohort from "#execution/activity-cohort.js";
function channelDeliveryErrorCode(error: unknown): string {
if (typeof error === "object" && error !== null && "code" in error) {
@@ -143,11 +142,7 @@ async function runSessionStep(input: TurnStepInput): Promise<DurableStepResult>
);
delivery = { ...delivery, payloads: remainingPayloads };
if (matches.length > 0) {
- const matchedAttemptIds = activityCohort.restoreAuthorizationActivity({
- ctx,
- matches,
- pending: pendingAuth,
- });
+ const matchedAttemptIds = matches.map((match) => match.result.attemptId);
const authResults = matches.map((match) => match.result);
ctx.set(PendingAuthorizationResultKey, authResults);
durableSession = {
@@ -234,7 +229,6 @@ async function runSessionStep(input: TurnStepInput): Promise<DurableStepResult>
ctx,
origin: "own",
sessionWritable: input.sessionWritable,
- sessionId: initialSession.sessionId,
});
const { adapterCtx } = publisher.dispatcher;
// A hook's `ctx.cancel()` aborts the same signal the harness already honors
@@ -316,13 +310,6 @@ async function runSessionStep(input: TurnStepInput): Promise<DurableStepResult>
resolved = { ...resolved, runtimeActionResults: runtimeResults.results };
}
- activityCohort.updateActivityRootForDelivery({
- activeTurnId: activeTurnId(initialEmissionState),
- ctx,
- delivery: ignoredActiveDelivery ? undefined : rawDelivery,
- sessionState: durableSession.state,
- });
-
if (rawDelivery !== undefined) {
const updatedAdapter = { ...adapter, state: { ...adapterCtx.state } };
setChannelContext(ctx, updatedAdapter);
diff --git a/packages/eve/src/execution/settle-cancelled-turn-step.integration.test.ts b/packages/eve/src/execution/settle-cancelled-turn-step.integration.test.ts
index b3e510e59..6e717538f 100644
--- a/packages/eve/src/execution/settle-cancelled-turn-step.integration.test.ts
+++ b/packages/eve/src/execution/settle-cancelled-turn-step.integration.test.ts
@@ -1,9 +1,7 @@
import { describe, expect, it } from "vitest";
-import type { HarnessSession, SessionStateMap } from "#harness/types.js";
+import type { SessionStateMap } from "#harness/types.js";
import { readDurableSession } from "#execution/durable-session-store.js";
-import { appendPendingInputBatch } from "#harness/pending-input-batches.js";
-import type { InputRequest } from "#shared/input.js";
import { settleCancelledTurnStep } from "#execution/settle-cancelled-turn-step.js";
import {
accumulateTurnUsage,
@@ -52,41 +50,7 @@ function spend<T extends { readonly state?: SessionStateMap }>(
);
}
-function request(requestId: string, kind: InputRequest["kind"]): InputRequest {
- return {
- action: { callId: requestId, input: {}, kind: "tool-call", toolName: "deploy" },
- kind,
- prompt: "Continue?",
- requestId,
- };
-}
-
describe("settleCancelledTurnStep", () => {
- it("leaves only the requests the session can still answer holding its activity open", async () => {
- const base = createTestSessionState({
- emissionState: { sequence: 1, sessionStarted: true, stepIndex: 0, turnId: "turn_1" },
- sessionId: "deploy-session",
- });
- // Alice's turn waits on its own deploy approval, a session-limit prompt,
- // and a question a child asked through it when Bob cancels the turn.
- const parked = [request("approval-1", "tool-approval"), request("limit-1", "session-limit")]
- .map((pending) => [pending])
- .reduce(
- (session, requests) => appendPendingInputBatch({ requests, responseMessages: [], session }),
- { state: base.snapshot.session.state } as HarnessSession,
- );
- const result = await settleCancelledTurn({
- reportUsage: false,
- serializedContext: {
- ...serializedContext,
- "eve.activityPendingBlockers": ["child-question-1", "approval-1", "limit-1"],
- },
- sessionState: { ...base, snapshot: { session: { ...base.snapshot.session, ...parked } } },
- });
-
- expect(result.serializedContext["eve.activityPendingBlockers"]).toEqual(["approval-1"]);
- });
-
it.each([
{ reportUsage: true, reported: 50, nextSettled: 0 },
{ reportUsage: false, reported: undefined, nextSettled: 50 },
diff --git a/packages/eve/src/execution/settle-cancelled-turn-step.ts b/packages/eve/src/execution/settle-cancelled-turn-step.ts
index 7b429118d..3268e65e5 100644
--- a/packages/eve/src/execution/settle-cancelled-turn-step.ts
+++ b/packages/eve/src/execution/settle-cancelled-turn-step.ts
@@ -2,7 +2,6 @@ import {
commitCancelledCoordinationBatch,
getPendingCoordinationBatch,
} from "#harness/coordination.js";
-import { retainAnswerableActivityBlockers } from "#execution/activity-cohort.js";
import type { DurableSessionState } from "#execution/durable-session-store.js";
import { publishFromSessionStep, restoreSessionStep } from "#execution/publish-session-events.js";
import {
@@ -54,8 +53,6 @@ export async function settleCancelledTurn(
): Promise<CancelledTurnSettleResult> {
const step = await restoreSessionStep(input);
const durableState = step.durableSession.state;
- // Before `turn.cancelled` projects, so only what stays answerable holds the work open.
- retainAnswerableActivityBlockers(step.ctx, durableState);
const { published, result: usage } = await publishFromSessionStep(step, {
origin: "own",
publish: (emit) => emitCancelledTurn(emit, getHarnessEmissionState(durableState)),
diff --git a/packages/eve/src/execution/stable-workflow-names.ts b/packages/eve/src/execution/stable-workflow-names.ts
index e001d78aa..1e6da0f64 100644
--- a/packages/eve/src/execution/stable-workflow-names.ts
+++ b/packages/eve/src/execution/stable-workflow-names.ts
@@ -7,12 +7,10 @@ const TURN_WORKFLOW_NAME = "turnWorkflow";
export const WORKFLOW_ENTRY_NAME = "workflowEntry";
export const SESSION_TIMEOUT_WORKFLOW_NAME = "sessionTimeoutWorkflow";
export const WORKFLOW_TOOL_RUN_WORKFLOW_NAME = "workflowToolRunWorkflow";
-export const ACTIVITY_COLLECTOR_WORKFLOW_NAME = "activityCollectorWorkflow";
export const STABLE_WORKFLOW_NAMES: ReadonlySet<string> = new Set([
WORKFLOW_ENTRY_NAME,
TURN_WORKFLOW_NAME,
SESSION_TIMEOUT_WORKFLOW_NAME,
WORKFLOW_TOOL_RUN_WORKFLOW_NAME,
- ACTIVITY_COLLECTOR_WORKFLOW_NAME,
]);
diff --git a/packages/eve/src/execution/submit-activity.test.ts b/packages/eve/src/execution/submit-activity.test.ts
deleted file mode 100644
index df99c3bca..000000000
--- a/packages/eve/src/execution/submit-activity.test.ts
+++ /dev/null
@@ -1,87 +0,0 @@
-import { afterEach, describe, expect, it, vi } from "vitest";
-
-import { submitActivity } from "#execution/submit-activity.js";
-import { captureLogRecords } from "#internal/testing/log-records.js";
-
-const event = {
- eventId: "root:session:turn:started",
- kind: "work.started" as const,
- startedAt: "now",
- work: {
- id: "root:session:turn",
- kind: "root-turn" as const,
- rootSessionId: "session",
- rootTurnId: "turn",
- },
-};
-
-describe("submitActivity", () => {
- afterEach(() => {
- vi.unstubAllGlobals();
- vi.unstubAllEnvs();
- vi.restoreAllMocks();
- });
-
- it.each(["http", "transport", "timeout"])(
- "logs a %s failure once at warning severity and does not fail the session",
- async (failure) => {
- vi.stubEnv("EVE_LOG_LEVEL", "warn");
- const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
- const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
- const fetchMock = vi.fn();
- if (failure === "http") {
- fetchMock.mockResolvedValue(new Response(null, { status: 404 }));
- } else {
- if (failure === "timeout") {
- vi.spyOn(AbortSignal, "timeout").mockReturnValue(AbortSignal.abort());
- }
- fetchMock.mockRejectedValue(new Error("activity delivery failed"));
- }
- vi.stubGlobal("fetch", fetchMock);
-
- await expect(
- submitActivity({
- sink: {
- url: "https://agent.example.com/eve/v1/activity/abcdefghijklmnopqrstuvwxyz123456",
- version: 1,
- },
- events: [event],
- }),
- ).resolves.toBeUndefined();
-
- expect(warnSpy).toHaveBeenCalledExactlyOnceWith(
- "[eve:execution.activity-submit] activity sink request failed",
- );
- expect(errorSpy).not.toHaveBeenCalled();
- },
- );
-
- it("does nothing without a sink", async () => {
- const fetchMock = vi.fn();
- vi.stubGlobal("fetch", fetchMock);
- await expect(submitActivity({ sink: undefined, events: [event] })).resolves.toBeUndefined();
- expect(fetchMock).not.toHaveBeenCalled();
- });
-
- it("posts one versioned batch and swallows transport failure", async () => {
- const logs = captureLogRecords();
- const fetchMock = vi
- .fn()
- .mockResolvedValueOnce(new Response(null, { status: 202 }))
- .mockRejectedValueOnce(new Error("network failure"));
- vi.stubGlobal("fetch", fetchMock);
- const sink = {
- url: "https://agent.example.com/eve/v1/activity/abcdefghijklmnopqrstuvwxyz123456",
- version: 1 as const,
- };
- await submitActivity({ sink, events: [event] });
- await expect(submitActivity({ sink, events: [event] })).resolves.toBeUndefined();
- expect(JSON.parse(String(fetchMock.mock.calls[0]?.[1]?.body))).toEqual({
- events: [event],
- version: 1,
- });
- expect(logs.records).toContainEqual(
- expect.objectContaining({ level: "warn", message: "activity sink request failed" }),
- );
- });
-});
diff --git a/packages/eve/src/execution/submit-activity.ts b/packages/eve/src/execution/submit-activity.ts
deleted file mode 100644
index a143ac6c6..000000000
--- a/packages/eve/src/execution/submit-activity.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-import type { ActivitySinkV1 } from "#channel/types.js";
-import { postSessionCallbackRequest } from "#execution/session-callback-request.js";
-import type { ActivityEventV1 } from "#protocol/activity.js";
-import { parseActivityBatchV1 } from "#protocol/activity.js";
-import { createLogger } from "#internal/logging.js";
-
-const log = createLogger("execution.activity-submit");
-const ACTIVITY_SUBMIT_TIMEOUT_MS = 2_000;
-
-/** Submits activity to its sink without affecting the observed session. */
-export async function submitActivity(input: {
- readonly sink: ActivitySinkV1 | undefined;
- readonly events: readonly ActivityEventV1[];
-}): Promise<void> {
- if (input.sink === undefined || input.events.length === 0) return;
- try {
- const batch = parseActivityBatchV1({ events: input.events, version: 1 });
- if (batch === undefined) return;
- const response = await postSessionCallbackRequest({
- body: batch,
- logFailures: false,
- timeoutMs: ACTIVITY_SUBMIT_TIMEOUT_MS,
- url: input.sink.url,
- });
- if (!response.ok) throw new Error(`Activity sink failed with HTTP ${response.status}.`);
- } catch {
- log.warn("activity sink request failed");
- }
-}
diff --git a/packages/eve/src/execution/tasks/task-id-input.ts b/packages/eve/src/execution/tasks/task-id-input.ts
index b39ecd9a2..0ec736a9c 100644
--- a/packages/eve/src/execution/tasks/task-id-input.ts
+++ b/packages/eve/src/execution/tasks/task-id-input.ts
@@ -6,6 +6,7 @@ import {
import { isAgentTool } from "#execution/tasks/tool-entry-point.js";
import type { HarnessToolDefinition } from "#harness/execute-tool.js";
import type { JsonObject } from "#shared/json.js";
+import { normalizePresentationText } from "#shared/presentation-text.js";
import { isToolSchema, withOptionalStringProperty } from "#tools/schema.js";
// A `serve` tool's model input is the tool's own input plus an optional
@@ -14,21 +15,51 @@ import { isToolSchema, withOptionalStringProperty } from "#tools/schema.js";
/** The model input property eve adds to every `serve` tool. */
export const TASK_ID_INPUT = "taskId";
-/** The tool as the model sees it: its input gains `taskId`, and its description explains it. */
+/**
+ * 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
+ * first line of its message: `researcher: Find the March incidents`.
+ */
export function withTaskIdInput(definition: HarnessToolDefinition): HarnessToolDefinition {
const schema = definition.inputSchema;
if (!isToolSchema(schema)) {
throw new Error(`Tool "${definition.name}" has no input schema eve can add taskId to.`);
}
- const sentence = isAgentTool(definition) ? AGENT_SERVE_TOOL_DESCRIPTION : SERVE_TOOL_DESCRIPTION;
- return {
+ const agent = isAgentTool(definition);
+ const described: HarnessToolDefinition = {
...definition,
- description: appendSentence(definition.description, sentence),
+ description: appendSentence(
+ definition.description,
+ agent ? AGENT_SERVE_TOOL_DESCRIPTION : SERVE_TOOL_DESCRIPTION,
+ ),
inputSchema: withOptionalStringProperty(schema, {
description: TASK_ID_INPUT_DESCRIPTION,
name: TASK_ID_INPUT,
}),
};
+ if (!agent || definition.label?.start !== undefined) return described;
+ return {
+ ...described,
+ label: { ...definition.label, start: (input) => agentCallLabel(definition.name, input) },
+ };
+}
+
+/** `researcher: Find the March incidents`, or the agent's name when the message is empty. */
+function agentCallLabel(name: string, input: unknown): string {
+ const message =
+ typeof input === "object" && input !== null
+ ? (input as { message?: unknown }).message
+ : undefined;
+ const line = typeof message === "string" ? firstLine(message) : undefined;
+ return line === undefined ? name : `${name}: ${line}`;
+}
+
+function firstLine(text: string): string | undefined {
+ for (const line of text.split(/\r?\n/u)) {
+ const normalized = normalizePresentationText(line);
+ if (normalized !== "") return normalized;
+ }
+ return undefined;
}
/** A `serve` tool call's model input, split into the task it names and the tool's own input. */
diff --git a/packages/eve/src/execution/workflow-runtime.test.ts b/packages/eve/src/execution/workflow-runtime.test.ts
index a2b54d4bc..6c3ffe5c4 100644
--- a/packages/eve/src/execution/workflow-runtime.test.ts
+++ b/packages/eve/src/execution/workflow-runtime.test.ts
@@ -10,13 +10,11 @@ import {
} from "#compiled/@opentelemetry/api/index.js";
import { HookNotFoundError } from "#compiled/@workflow/errors/index.js";
import type { ChannelAdapter } from "#channel/adapter.js";
-import { attachChannelActivityPresentation } from "#channel/activity-renderer.js";
-import { ActivityObserverKey, ChannelRequestIdKey, SessionTitleKey } from "#context/keys.js";
+import { ChannelRequestIdKey, SessionTitleKey } from "#context/keys.js";
import { resolveInstalledPackageInfo } from "#internal/application/package.js";
import {
createWorkflowRuntime,
waitForCommandHookOwner,
- activityCollectorWorkflowReference,
sessionTimeoutWorkflowReference,
startSessionOwnerStep,
startWorkflowOnCurrentDeployment,
@@ -95,9 +93,6 @@ describe("workflowEntryReference", () => {
);
expect(sessionTimeoutWorkflowReference.workflowId).not.toContain("/src/execution/");
expect(sessionTimeoutWorkflowReference.workflowId).not.toContain("@");
- expect(activityCollectorWorkflowReference.workflowId).toBe(
- `workflow//${packageInfo.name}//activityCollectorWorkflow`,
- );
expect(workflowToolRunWorkflowReference.workflowId).toBe(
`workflow//${packageInfo.name}//workflowToolRunWorkflow`,
);
@@ -538,15 +533,6 @@ describe("createWorkflowRuntime#createSession", () => {
return createWorkflowRuntime({ compiledArtifactsSource });
}
- function activityAdapter(): ChannelAdapter {
- const adapter: ChannelAdapter = { kind: "slack" };
- attachChannelActivityPresentation(adapter, {
- destination: () => ({}),
- renderers: [{ id: "status", render: vi.fn() }],
- });
- return adapter;
- }
-
function mockBundleAndRun(
compiledArtifactsSource: RuntimeCompiledArtifactsSource,
sessionTimeoutMs?: number | false,
@@ -711,126 +697,6 @@ describe("createWorkflowRuntime#createSession", () => {
});
});
- it("starts one collector and injects its opaque sink for a root channel with renderers", async () => {
- vi.stubEnv("VERCEL_URL", "agent.example.com");
- const compiledArtifactsSource = {} as RuntimeCompiledArtifactsSource;
- mockBundleAndRun(compiledArtifactsSource, 60_000);
- startMock
- .mockResolvedValueOnce({ runId: "collector-run" })
- .mockResolvedValueOnce({ runId: "owner-run" });
-
- await buildRuntime(compiledArtifactsSource).createSession({
- adapter: activityAdapter(),
- auth: null,
- input: { message: "hello" },
- });
-
- expect(startMock.mock.calls[0]?.[0]).toBe(activityCollectorWorkflowReference);
- const collectorInput = startMock.mock.calls[0]?.[1][0];
- expect(collectorInput).toMatchObject({
- serializedContext: expect.any(Object),
- token: expect.any(String),
- });
- expect(collectorInput.token).toHaveLength(43);
- const workflowInput = startMock.mock.calls[1]?.[1][0];
- expect(workflowInput.activityCollectorRunId).toBe("collector-run");
- expect(workflowInput.serializedContext[ActivityObserverKey.name]).toEqual({
- sink: {
- url: `https://agent.example.com/eve/v1/activity/${collectorInput.token}`,
- version: 1,
- },
- });
- });
-
- it("uses independent collector retention when session timeout is disabled", async () => {
- vi.useFakeTimers();
- vi.setSystemTime(new Date("2026-01-01T00:00:00.000Z"));
- try {
- const compiledArtifactsSource = {} as RuntimeCompiledArtifactsSource;
- mockBundleAndRun(compiledArtifactsSource, false);
- startMock
- .mockResolvedValueOnce({ runId: "collector-run" })
- .mockResolvedValueOnce({ runId: "owner-run" });
-
- await buildRuntime(compiledArtifactsSource).createSession({
- adapter: activityAdapter(),
- auth: null,
- input: { message: "hello" },
- });
-
- expect(startMock.mock.calls[0]?.[0]).toBe(activityCollectorWorkflowReference);
- expect(startMock.mock.calls[0]?.[1][0]).toMatchObject({
- expiresAt: "2026-01-02T00:00:00.000Z",
- });
- expect(startMock.mock.calls[1]?.[1][0]).toMatchObject({ sessionTimeoutMs: false });
- } finally {
- vi.useRealTimers();
- }
- });
-
- it("starts the root without activity when collector launch fails", async () => {
- const logs = captureLogRecords();
- const compiledArtifactsSource = {} as RuntimeCompiledArtifactsSource;
- mockBundleAndRun(compiledArtifactsSource);
- startMock
- .mockRejectedValueOnce(new Error("collector failed"))
- .mockResolvedValueOnce({ runId: "owner-run" });
-
- await buildRuntime(compiledArtifactsSource).createSession({
- adapter: activityAdapter(),
- auth: null,
- input: { message: "hello" },
- });
-
- const workflowInput = startMock.mock.calls[1]?.[1][0];
- expect(workflowInput.serializedContext[ActivityObserverKey.name]).toBeUndefined();
- expect(logs.records).toContainEqual(
- expect.objectContaining({ level: "warn", message: "failed to start activity collector" }),
- );
- });
-
- it("cancels the collector when root workflow startup fails", async () => {
- const logs = captureLogRecords();
- const compiledArtifactsSource = {} as RuntimeCompiledArtifactsSource;
- mockBundleAndRun(compiledArtifactsSource);
- const failure = new Error("root start failed");
- startMock.mockResolvedValueOnce({ runId: "collector-run" }).mockRejectedValueOnce(failure);
-
- await expect(
- buildRuntime(compiledArtifactsSource).createSession({
- adapter: activityAdapter(),
- auth: null,
- input: { message: "hello" },
- }),
- ).rejects.toBe(failure);
-
- expect(cancelRunMock).toHaveBeenCalledWith(world, "collector-run", {
- cancelReason: "Root session creation did not complete",
- });
- expect(logs.records).toContainEqual(
- expect.objectContaining({ level: "error", message: "failed to start workflow run" }),
- );
- });
-
- it("does not inspect continuation ownership after accepting a root candidate", async () => {
- const compiledArtifactsSource = {} as RuntimeCompiledArtifactsSource;
- mockBundleAndRun(compiledArtifactsSource);
- startMock
- .mockResolvedValueOnce({ runId: "collector-run" })
- .mockResolvedValueOnce({ runId: "owner-run" });
- await expect(
- buildRuntime(compiledArtifactsSource).createSession({
- adapter: activityAdapter(),
- auth: null,
- continuationToken: "slack:thread",
- input: { message: "hello" },
- }),
- ).resolves.toMatchObject({ sessionId: "owner-run" });
-
- expect(getHookByTokenMock).not.toHaveBeenCalled();
- expect(cancelRunMock).not.toHaveBeenCalled();
- });
-
it("serializes the selected dynamic subagent config for the child workflow", async () => {
const compiledArtifactsSource = {} as RuntimeCompiledArtifactsSource;
mockBundleAndRun(compiledArtifactsSource, 86_400_000);
diff --git a/packages/eve/src/execution/workflow-runtime.ts b/packages/eve/src/execution/workflow-runtime.ts
index d0e755710..50081e054 100644
--- a/packages/eve/src/execution/workflow-runtime.ts
+++ b/packages/eve/src/execution/workflow-runtime.ts
@@ -1,5 +1,3 @@
-import { randomBytes } from "node:crypto";
-
import { context, trace } from "#compiled/@opentelemetry/api/index.js";
import {
EntityConflictError,
@@ -8,7 +6,6 @@ import {
WorkflowRunNotFoundError,
} from "#compiled/@workflow/errors/index.js";
-import { getChannelActivityPresentation } from "#channel/activity-renderer.js";
import type {
CancelTurnInput,
CancelTurnResult,
@@ -22,7 +19,6 @@ import type {
SessionCommand,
SessionCommandResult,
} from "#channel/types.js";
-import { ActivityObserverKey } from "#context/keys.js";
import { serializeContext } from "#context/serialize.js";
import {
buildSessionAttributes,
@@ -32,7 +28,6 @@ import {
import { resolveInstalledPackageInfo } from "#internal/application/package.js";
import { createLogger, logError } from "#internal/logging.js";
import {
- cancelRun,
getHookByToken,
getRun,
getWorld,
@@ -61,12 +56,6 @@ import {
type InitialWorkflowEntryInput,
} from "#execution/session/entry-input.js";
import type { SessionCheckpoint } from "#execution/session/handoff.js";
-import type { ActivityCollectorInput } from "#execution/activity-collector.js";
-import { createEveActivityRoutePath } from "#protocol/routes.js";
-import {
- createWorkflowCallbackUrl,
- resolveWorkflowCallbackBaseUrl,
-} from "#execution/workflow-callback-url.js";
import { walkCauseChain } from "#shared/errors.js";
import { buildInvocationAttributes } from "#internal/invocation/metadata.js";
import { isAgentTraceContext } from "#tracing/agent-trace-context.js";
@@ -83,14 +72,12 @@ import type { SessionInboxAddress } from "#execution/session-inbox/address.js";
import type { DynamicSubagentAgentConfig } from "#runtime/subagents/dynamic-agent-config.js";
import { initializeSessionInstrumentation } from "#instrumentation/runtime.js";
import {
- ACTIVITY_COLLECTOR_WORKFLOW_NAME,
SESSION_TIMEOUT_WORKFLOW_NAME,
WORKFLOW_TOOL_RUN_WORKFLOW_NAME,
WORKFLOW_ENTRY_NAME,
} from "#execution/stable-workflow-names.js";
const EVE_PACKAGE_INFO = resolveInstalledPackageInfo();
const COMMAND_HOOK_READY_TIMEOUT_MS = 30_000;
-const DEFAULT_ACTIVITY_COLLECTOR_RETENTION_MS = 24 * 60 * 60 * 1_000;
const STABLE_ID_BASE = EVE_PACKAGE_INFO.name;
@@ -119,11 +106,6 @@ export const sessionTimeoutWorkflowReference = {
workflowId: `workflow//${STABLE_ID_BASE}//${SESSION_TIMEOUT_WORKFLOW_NAME}`,
};
-/** Stable workflow reference for root-session activity collectors. */
-export const activityCollectorWorkflowReference = {
- workflowId: `workflow//${STABLE_ID_BASE}//${ACTIVITY_COLLECTOR_WORKFLOW_NAME}`,
-};
-
/** Stable workflow reference for authored workflow tool runs. */
export const workflowToolRunWorkflowReference = {
workflowId: `workflow//${STABLE_ID_BASE}//${WORKFLOW_TOOL_RUN_WORKFLOW_NAME}`,
@@ -158,49 +140,6 @@ export function createWorkflowRuntime(config: {
// Retention is always the authored value: `experimental` cannot be
// selected by a dynamic subagent config, so there is nothing to resolve.
const retention = bundle.resolvedAgent.config?.experimental?.workflow?.retention;
- let collectorRunId: string | undefined;
- let activityObserver = input.activityObserver;
- if (
- input.parent === undefined &&
- activityObserver === undefined &&
- (getChannelActivityPresentation(input.adapter)?.renderers.length ?? 0) > 0
- ) {
- const collectorContext = serializeContext(ctx);
- const token = randomBytes(32).toString("base64url");
- const collectorInput: ActivityCollectorInput = {
- expiresAt: new Date(
- Date.now() +
- (typeof sessionTimeoutMs === "number"
- ? sessionTimeoutMs
- : DEFAULT_ACTIVITY_COLLECTOR_RETENTION_MS),
- ).toISOString(),
- serializedContext: collectorContext,
- token,
- };
- try {
- const collector = await startWorkflowOnCurrentDeployment(
- activityCollectorWorkflowReference,
- [collectorInput],
- { experimental_retention: retention },
- );
- collectorRunId = collector.runId;
- const fallbackOrigin = process.env.VERCEL_URL
- ? `https://${process.env.VERCEL_URL}`
- : "http://localhost:3000";
- const baseUrl = resolveWorkflowCallbackBaseUrl(fallbackOrigin);
- activityObserver = {
- sink: {
- url: createWorkflowCallbackUrl(baseUrl, createEveActivityRoutePath(token)),
- version: 1,
- },
- };
- ctx.set(ActivityObserverKey, activityObserver);
- } catch {
- await cancelActivityCollector(collectorRunId);
- collectorRunId = undefined;
- log.warn("failed to start activity collector");
- }
- }
const serializedContext = serializeContext(ctx);
const parentLineage = readParentLineage(serializedContext);
const workflowInput: {
@@ -212,9 +151,6 @@ export function createWorkflowRuntime(config: {
serializedContext,
};
if (input.limits !== undefined) workflowInput.limits = input.limits;
- if (collectorRunId !== undefined) {
- workflowInput.activityCollectorRunId = collectorRunId;
- }
if (input.continuationConflictCommand !== undefined) {
workflowInput.continuationConflictCommand = input.continuationConflictCommand;
}
@@ -258,7 +194,6 @@ export function createWorkflowRuntime(config: {
startOptions,
);
} catch (error) {
- await cancelActivityCollector(collectorRunId);
logError(log, "failed to start workflow run", error, {
continuationToken: input.continuationToken,
});
@@ -370,17 +305,6 @@ function normalizePersistedEvent(value: unknown): MessageStreamEvent {
);
}
-async function cancelActivityCollector(runId: string | undefined): Promise<void> {
- if (runId === undefined) return;
- try {
- await cancelRun(await getWorld(), runId, {
- cancelReason: "Root session creation did not complete",
- });
- } catch {
- log.warn("failed to cancel unowned activity collector");
- }
-}
-
async function dispatchWorkflowCommand<TCommand extends SessionCommand>(
token: string | SessionInboxAddress,
command: TCommand,
diff --git a/packages/eve/src/harness/authorization.test.ts b/packages/eve/src/harness/authorization.test.ts
index 842024a27..5467fb725 100644
--- a/packages/eve/src/harness/authorization.test.ts
+++ b/packages/eve/src/harness/authorization.test.ts
@@ -1,7 +1,7 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { ContextContainer, contextStorage } from "#context/container.js";
-import { ActivityObserverKey, ActivityRootTurnIdKey, SessionIdKey } from "#context/keys.js";
+import { SessionIdKey } from "#context/keys.js";
import {
CallbackBaseUrlKey,
clearPendingAuthorization,
@@ -107,23 +107,6 @@ function candidateChallenge(name: string, candidateId: string) {
}
describe("pending authorization state", () => {
- it("captures the originating activity turn", () => {
- const ctx = new ContextContainer();
- ctx.set(ActivityObserverKey, {
- sink: { url: "https://agent.example/eve/v1/activity/abcdefghijklmnopqrstuvwxyz", version: 1 },
- });
- ctx.set(ActivityRootTurnIdKey, "turn-origin");
- const state = contextStorage.run(ctx, () =>
- setPendingAuthorization(undefined, {
- challenges: [candidateChallenge("github", "candidate-1")],
- }),
- );
-
- expect(getPendingAuthorization(state)?.activityRootTurnIds).toEqual({
- "candidate-1": "turn-origin",
- });
- });
-
it("merges concurrent candidate challenges by authorization name", () => {
const first = setPendingAuthorization(undefined, {
challenges: [candidateChallenge("candidate-1:github", "candidate-1")],
diff --git a/packages/eve/src/harness/authorization.ts b/packages/eve/src/harness/authorization.ts
index 8f0a7bb18..8a7444fbd 100644
--- a/packages/eve/src/harness/authorization.ts
+++ b/packages/eve/src/harness/authorization.ts
@@ -35,9 +35,9 @@ import {
* nonce that re-derives it) from start to finish.
*/
-import { contextStorage, loadContext } from "#context/container.js";
+import { loadContext } from "#context/container.js";
import { ContextKey } from "#context/key.js";
-import { ActivityRootTurnIdKey, SessionIdKey } from "#context/keys.js";
+import { SessionIdKey } from "#context/keys.js";
import { createWorkflowCallbackUrl } from "#execution/workflow-callback-url.js";
import type { ConnectionAuthorizationChallenge } from "#connections/errors.js";
import type { AuthorizationCallback, ConnectionPrincipal } from "#shared/connection-types.js";
@@ -292,7 +292,6 @@ export const AuthorizationHookKey = new ContextKey<string>("eve.authorizationHoo
const PENDING_AUTHORIZATION_KEY = "eve.runtime.pendingAuthorization";
export interface PendingAuthorizationState {
- readonly activityRootTurnIds?: Readonly<Record<string, string>>;
readonly challenges: readonly AuthorizationChallenge[];
}
@@ -304,18 +303,9 @@ export function setPendingAuthorization(
const pending = getPendingAuthorization(sessionState);
const previous = pending?.challenges ?? [];
const superseded = getSupersededAuthorizationChallenges(sessionState, active);
- const rootTurnId = contextStorage.getStore()?.get(ActivityRootTurnIdKey);
- const activityRootTurnIds = { ...pending?.activityRootTurnIds };
- for (const challenge of superseded)
- delete activityRootTurnIds[authorizationAttemptKey(challenge)];
- if (rootTurnId !== undefined) {
- for (const challenge of active)
- activityRootTurnIds[authorizationAttemptKey(challenge)] = rootTurnId;
- }
return {
...sessionState,
[PENDING_AUTHORIZATION_KEY]: {
- ...(Object.keys(activityRootTurnIds).length === 0 ? {} : { activityRootTurnIds }),
challenges: [...previous.filter((challenge) => !superseded.includes(challenge)), ...active],
},
};
@@ -381,7 +371,7 @@ export function clearPendingAuthorization(
if (challenges.length > 0) {
return {
...sessionState,
- [PENDING_AUTHORIZATION_KEY]: pendingAuthorizationValue(pending, challenges),
+ [PENDING_AUTHORIZATION_KEY]: { challenges },
};
}
}
@@ -392,23 +382,6 @@ export function clearPendingAuthorization(
return Object.keys(state).length > 0 ? state : undefined;
}
-function pendingAuthorizationValue(
- pending: PendingAuthorizationState,
- challenges: readonly AuthorizationChallenge[],
-): PendingAuthorizationState {
- const activityRootTurnIds = Object.fromEntries(
- challenges.flatMap((challenge) => {
- const key = authorizationAttemptKey(challenge);
- const rootTurnId = pending.activityRootTurnIds?.[key];
- return rootTurnId === undefined ? [] : [[key, rootTurnId]];
- }),
- );
- return {
- ...(Object.keys(activityRootTurnIds).length === 0 ? {} : { activityRootTurnIds }),
- challenges,
- };
-}
-
function authorizationAttemptKey(challenge: AuthorizationChallenge): string {
return challenge.attemptId ?? challenge.candidateId ?? challenge.name;
}
diff --git a/packages/eve/src/harness/pending-input-batches.test.ts b/packages/eve/src/harness/pending-input-batches.test.ts
index acaf11ee0..bb34cec5f 100644
--- a/packages/eve/src/harness/pending-input-batches.test.ts
+++ b/packages/eve/src/harness/pending-input-batches.test.ts
@@ -1,14 +1,8 @@
import { describe, expect, it } from "vitest";
-import { ContextContainer, contextStorage } from "#context/container.js";
-import { ActivityObserverKey, ActivityRootTurnIdKey } from "#context/keys.js";
import type { InputRequest } from "#shared/input.js";
import { resolvePendingInput } from "#harness/input-requests.js";
-import {
- activityRequestIdsForRootTurn,
- appendPendingInputBatch,
- getPendingInputBatches,
-} from "#harness/pending-input-batches.js";
+import { appendPendingInputBatch, getPendingInputBatches } from "#harness/pending-input-batches.js";
import type { HarnessSession } from "#harness/types.js";
const DUPLICATE_ID_ERROR =
@@ -44,26 +38,6 @@ function question(requestId: string, callId: string): InputRequest {
};
}
-describe("pending input activity provenance", () => {
- it("captures the originating turn with a parked request", () => {
- const ctx = new ContextContainer();
- ctx.set(ActivityObserverKey, {
- sink: { url: "https://agent.example/eve/v1/activity/abcdefghijklmnopqrstuvwxyz", version: 1 },
- });
- ctx.set(ActivityRootTurnIdKey, "turn-origin");
- const parked = contextStorage.run(ctx, () =>
- appendPendingInputBatch({
- requests: [approval("approval-1", "call-1")],
- responseMessages: [],
- session: session(),
- }),
- );
-
- expect(getPendingInputBatches(parked.state)[0]?.activityRootTurnId).toBe("turn-origin");
- expect(activityRequestIdsForRootTurn(parked.state, "turn-origin")).toEqual(["approval-1"]);
- });
-});
-
describe("pending input request ID uniqueness", () => {
it("rejects duplicate IDs within a newly appended batch", () => {
expect(() =>
diff --git a/packages/eve/src/harness/pending-input-batches.ts b/packages/eve/src/harness/pending-input-batches.ts
index 1c13d874a..2c47bed97 100644
--- a/packages/eve/src/harness/pending-input-batches.ts
+++ b/packages/eve/src/harness/pending-input-batches.ts
@@ -2,7 +2,7 @@ import type { ModelMessage } from "ai";
import { contextStorage } from "#context/container.js";
import type { SessionAuthContext } from "#channel/types.js";
-import { ActivityRootTurnIdKey, AuthKey, SessionKey } from "#context/keys.js";
+import { AuthKey, SessionKey } from "#context/keys.js";
import type { InputRequest } from "#shared/input.js";
import type { HarnessSession, SessionStateMap, StepInput } from "#harness/types.js";
import { coalesceTurnInputs } from "#harness/messages.js";
@@ -31,7 +31,6 @@ export interface PendingInputBatchEvent {
export interface PendingInputBatch {
readonly toolReplayIdentities?: Readonly<Record<string, string>>;
readonly event?: PendingInputBatchEvent;
- readonly activityRootTurnId?: string;
readonly requests: readonly InputRequest[];
/**
* Auth of the caller whose turn parked the batch, captured when it parked;
@@ -143,7 +142,6 @@ function setPendingInputBatches(
} else {
state[PENDING_INPUT_BATCHES_KEY] = batches.map((batch) => ({
event: batch.event,
- activityRootTurnId: batch.activityRootTurnId,
requester: batch.requester,
responseAuthRequiredRequestIds: batch.responseAuthRequiredRequestIds,
toolReplayIdentities: batch.toolReplayIdentities,
@@ -162,7 +160,6 @@ function setPendingInputBatches(
export function appendPendingInputBatch(input: {
readonly toolReplayIdentities?: Readonly<Record<string, string>>;
readonly event?: PendingInputBatchEvent;
- readonly activityRootTurnId?: string;
readonly requests: readonly InputRequest[];
readonly responseAuthRequiredRequestIds?: readonly string[];
readonly responseMessages: readonly ModelMessage[];
@@ -172,8 +169,6 @@ export function appendPendingInputBatch(input: {
...getPendingInputBatches(input.session.state),
{
event: input.event,
- activityRootTurnId:
- input.activityRootTurnId ?? contextStorage.getStore()?.get(ActivityRootTurnIdKey),
requester: currentRequester(),
responseAuthRequiredRequestIds: input.responseAuthRequiredRequestIds,
toolReplayIdentities: input.toolReplayIdentities,
@@ -204,26 +199,6 @@ export function pendingInputRequester(
return batch?.requester ?? null;
}
-export function activityRootTurnIdForInputResponses(
- state: SessionStateMap | undefined,
- requestIds: ReadonlySet<string>,
-): string | undefined {
- return getPendingInputBatches(state).find((batch) =>
- batch.requests.some((request) => requestIds.has(request.requestId)),
- )?.activityRootTurnId;
-}
-
-export function activityRequestIdsForRootTurn(
- state: SessionStateMap | undefined,
- rootTurnId: string,
-): readonly string[] {
- return getPendingInputBatches(state).flatMap((batch) =>
- batch.activityRootTurnId === rootTurnId
- ? batch.requests.map((request) => request.requestId)
- : [],
- );
-}
-
// ---------------------------------------------------------------------------
// Deferred step input
// ---------------------------------------------------------------------------
diff --git a/packages/eve/src/internal/testing/scenario-apps/index.ts b/packages/eve/src/internal/testing/scenario-apps/index.ts
index d93fcf6bc..08beda141 100644
--- a/packages/eve/src/internal/testing/scenario-apps/index.ts
+++ b/packages/eve/src/internal/testing/scenario-apps/index.ts
@@ -4,7 +4,6 @@ export { EXTENSION_AGENT_DESCRIPTOR } from "#internal/testing/scenario-apps/exte
export { GITHUB_ROUTE_PORTABILITY_DESCRIPTOR } from "#internal/testing/scenario-apps/github-route-portability.js";
export { EVE_ROUTE_PORTABILITY_DESCRIPTOR } from "#internal/testing/scenario-apps/eve-route-portability.js";
export { SANDBOX_WORKSPACES_DESCRIPTOR } from "#internal/testing/scenario-apps/sandbox-workspaces.js";
-export { SLACK_CUSTOM_CHANNEL_PORTABILITY_DESCRIPTOR } from "#internal/testing/scenario-apps/slack-custom-channel-portability.js";
export { SLACK_ROUTE_PORTABILITY_DESCRIPTOR } from "#internal/testing/scenario-apps/slack-route-portability.js";
export { TEAMS_ROUTE_PORTABILITY_DESCRIPTOR } from "#internal/testing/scenario-apps/teams-route-portability.js";
export { TELEGRAM_ROUTE_PORTABILITY_DESCRIPTOR } from "#internal/testing/scenario-apps/telegram-route-portability.js";
diff --git a/packages/eve/src/internal/testing/scenario-apps/slack-custom-channel-portability.ts b/packages/eve/src/internal/testing/scenario-apps/slack-custom-channel-portability.ts
deleted file mode 100644
index 61e99899c..000000000
--- a/packages/eve/src/internal/testing/scenario-apps/slack-custom-channel-portability.ts
+++ /dev/null
@@ -1,49 +0,0 @@
-import type { ScenarioAppDescriptor } from "#internal/testing/scenario-app.js";
-
-export const SLACK_CUSTOM_CHANNEL_PORTABILITY_DESCRIPTOR: ScenarioAppDescriptor = {
- files: {
- "agent/channels/slack.ts": `import { Actions, Button, Card, CardText, slackChannel } from "eve/channels/slack";
-
-const ALLOWED = new Set(["C0123ABC"]);
-
-export default slackChannel({
- onAppMention(ctx, message) {
- if (!ALLOWED.has(ctx.slack.channelId)) return null;
- return {
- auth: {
- attributes: {},
- authenticator: "slack",
- principalId: message.author?.userId ?? "unknown",
- principalType: "user",
- },
- };
- },
-
- events: {
- "message.completed"(event, ctx) {
- if (event.finishReason === "tool-calls") return;
- if (event.message) {
- ctx.thread.post(event.message);
- ctx.thread.post(
- Card({
- children: [
- CardText("Was this helpful?"),
- Actions([
- Button({ id: "yes", label: "Yes", style: "primary" }),
- Button({ id: "no", label: "No" }),
- ]),
- ],
- }),
- );
- }
- },
- },
-
- onInteraction(action, _ctx) {
- console.log("Feedback:", action.actionId);
- },
-});
-`,
- },
- name: "slack-custom-channel-portability",
-};
diff --git a/packages/eve/src/protocol/activity.ts b/packages/eve/src/protocol/activity.ts
deleted file mode 100644
index 5a33378df..000000000
--- a/packages/eve/src/protocol/activity.ts
+++ /dev/null
@@ -1,355 +0,0 @@
-const MAX_ACTIVITY_EVENTS_PER_BATCH = 100;
-
-export type ActivityWorkKind = "root-turn" | "subagent" | "remote-agent";
-export type ActivityWorkPhase = "running" | "completed" | "failed" | "cancelled";
-type ActivityActionKind = "tool" | "skill";
-export type ActivityActionPhase = "running" | "completed" | "failed" | "rejected" | "cancelled";
-type ActivityBlockerKind = "approval" | "authorization" | "input";
-export type ActivityBlockerPhase = "blocked" | "completed" | "cancelled" | "failed";
-
-export interface ActivityWorkIdentityV1 {
- readonly callId?: string;
- readonly id: string;
- readonly kind: ActivityWorkKind;
- readonly label?: string;
- readonly name?: string;
- readonly parentId?: string;
- readonly rootSessionId: string;
- readonly rootTurnId: string;
- readonly sessionId?: string;
- readonly turnId?: string;
-}
-
-export interface PendingActivitySettlementV1 {
- readonly entityKind: "action" | "blocker" | "work";
- readonly eventId: string;
- readonly outcome: ActivityActionPhase | ActivityBlockerPhase | ActivityWorkPhase;
- readonly settledAt: string;
-}
-
-export interface ActivityWorkStateV1 extends ActivityWorkIdentityV1 {
- readonly phase: ActivityWorkPhase;
- readonly settledAt?: string;
- readonly startedAt: string;
-}
-
-export interface ActivityActionIdentityV1 {
- readonly id: string;
- readonly kind: ActivityActionKind;
- readonly name: string;
- readonly parentWorkId: string;
- readonly rootTurnId: string;
- readonly stepIndex: number;
-}
-
-export interface ActivityActionStateV1 extends ActivityActionIdentityV1 {
- readonly label?: string;
- readonly phase: ActivityActionPhase;
- readonly settledAt?: string;
- readonly startedAt: string;
-}
-
-export interface ActivityBlockerIdentityV1 {
- readonly id: string;
- readonly kind: ActivityBlockerKind;
- readonly label?: string;
- readonly parentActionId?: string;
- readonly parentWorkId: string;
- readonly rootTurnId: string;
-}
-
-export interface ActivityBlockerStateV1 extends ActivityBlockerIdentityV1 {
- readonly phase: ActivityBlockerPhase;
- readonly settledAt?: string;
- readonly startedAt: string;
-}
-
-export type ActivityEventV1 =
- | {
- readonly eventId: string;
- readonly kind: "work.started";
- readonly startedAt: string;
- readonly work: ActivityWorkIdentityV1;
- }
- | {
- readonly eventId: string;
- readonly kind: "work.settled";
- readonly outcome: Exclude<ActivityWorkPhase, "running">;
- readonly settledAt: string;
- readonly workId: string;
- }
- | {
- readonly action: ActivityActionIdentityV1;
- readonly eventId: string;
- readonly kind: "action.started";
- readonly startedAt: string;
- }
- | {
- readonly actionId: string;
- readonly eventId: string;
- readonly kind: "action.settled";
- readonly outcome: Exclude<ActivityActionPhase, "running">;
- readonly settledAt: string;
- }
- | {
- readonly actionId: string;
- readonly eventId: string;
- readonly kind: "action.label.updated";
- readonly label: string;
- }
- | {
- readonly blocker: ActivityBlockerIdentityV1;
- readonly eventId: string;
- readonly kind: "blocker.started";
- readonly startedAt: string;
- }
- | {
- readonly blockerId: string;
- readonly eventId: string;
- readonly kind: "blocker.settled";
- readonly outcome: Exclude<ActivityBlockerPhase, "blocked">;
- readonly settledAt: string;
- };
-
-export interface ActivityBatchV1 {
- readonly events: readonly ActivityEventV1[];
- readonly version: 1;
-}
-
-export interface ActivitySnapshotV1 {
- readonly actions: Readonly<Record<string, ActivityActionStateV1>>;
- readonly blockers: Readonly<Record<string, ActivityBlockerStateV1>>;
- readonly pendingSettlements: Readonly<Record<string, PendingActivitySettlementV1>>;
- readonly revision: number;
- readonly seenEventIds: readonly string[];
- readonly version: 1;
- readonly work: Readonly<Record<string, ActivityWorkStateV1>>;
-}
-
-export function parseActivityWorkIdentityV1(value: unknown): ActivityWorkIdentityV1 | undefined {
- if (!isRecord(value)) return undefined;
- const kind = value.kind;
- if (
- !isOneOf(kind, ["root-turn", "subagent", "remote-agent"] as const) ||
- !isIdentity(value.id) ||
- !isIdentity(value.rootSessionId) ||
- !isIdentity(value.rootTurnId) ||
- !isOptionalIdentity(value.callId) ||
- !isOptionalBoundedString(value.label) ||
- !isOptionalBoundedString(value.name) ||
- !isOptionalIdentity(value.parentId) ||
- !isOptionalIdentity(value.sessionId) ||
- !isOptionalIdentity(value.turnId)
- )
- return undefined;
- return {
- ...value,
- callId: value.callId,
- id: value.id,
- kind,
- label: value.label,
- name: value.name,
- parentId: value.parentId,
- rootSessionId: value.rootSessionId,
- rootTurnId: value.rootTurnId,
- sessionId: value.sessionId,
- turnId: value.turnId,
- };
-}
-
-/** Parses known lifecycle events while ignoring additive unknown event kinds. */
-export function parseActivityBatchV1(value: unknown): ActivityBatchV1 | undefined {
- if (
- !isRecord(value) ||
- !hasOnlyKeys(value, ["events", "version"]) ||
- value.version !== 1 ||
- !Array.isArray(value.events) ||
- value.events.length > MAX_ACTIVITY_EVENTS_PER_BATCH
- )
- return undefined;
-
- const events: ActivityEventV1[] = [];
- for (const candidate of value.events) {
- if (!isRecord(candidate) || !isBoundedString(candidate.kind)) return undefined;
- const event = parseKnownEvent(candidate);
- if (event === null) continue;
- if (event === undefined) return undefined;
- events.push(event);
- }
- return { events, version: 1 };
-}
-
-function parseKnownEvent(value: Record<string, unknown>): ActivityEventV1 | null | undefined {
- switch (value.kind) {
- case "work.started": {
- if (!hasOnlyKeys(value, ["eventId", "kind", "startedAt", "work"])) return undefined;
- const work = parseActivityWorkIdentityV1(value.work);
- if (!isIdentity(value.eventId) || !isBoundedString(value.startedAt) || work === undefined)
- return undefined;
- return { eventId: value.eventId, kind: "work.started", startedAt: value.startedAt, work };
- }
- case "work.settled": {
- if (!hasOnlyKeys(value, ["eventId", "kind", "outcome", "settledAt", "workId"]))
- return undefined;
- if (
- !isIdentity(value.eventId) ||
- !isOneOf(value.outcome, ["completed", "failed", "cancelled"] as const) ||
- !isBoundedString(value.settledAt) ||
- !isIdentity(value.workId)
- )
- return undefined;
- return {
- eventId: value.eventId,
- kind: "work.settled",
- outcome: value.outcome,
- settledAt: value.settledAt,
- workId: value.workId,
- };
- }
- case "action.started": {
- if (!hasOnlyKeys(value, ["action", "eventId", "kind", "startedAt"])) return undefined;
- const action = parseActionIdentity(value.action);
- if (!isIdentity(value.eventId) || !isBoundedString(value.startedAt) || action === undefined)
- return undefined;
- return { action, eventId: value.eventId, kind: "action.started", startedAt: value.startedAt };
- }
- case "action.settled": {
- if (!hasOnlyKeys(value, ["actionId", "eventId", "kind", "outcome", "settledAt"]))
- return undefined;
- if (
- !isIdentity(value.actionId) ||
- !isIdentity(value.eventId) ||
- !isOneOf(value.outcome, ["completed", "failed", "rejected", "cancelled"] as const) ||
- !isBoundedString(value.settledAt)
- )
- return undefined;
- return {
- actionId: value.actionId,
- eventId: value.eventId,
- kind: "action.settled",
- outcome: value.outcome,
- settledAt: value.settledAt,
- };
- }
- case "action.label.updated": {
- if (!hasOnlyKeys(value, ["actionId", "eventId", "kind", "label"])) return undefined;
- if (
- !isIdentity(value.actionId) ||
- !isIdentity(value.eventId) ||
- !isBoundedString(value.label)
- )
- return undefined;
- return {
- actionId: value.actionId,
- eventId: value.eventId,
- kind: "action.label.updated",
- label: value.label,
- };
- }
- case "blocker.started": {
- if (!hasOnlyKeys(value, ["blocker", "eventId", "kind", "startedAt"])) return undefined;
- const blocker = parseBlockerIdentity(value.blocker);
- if (!isIdentity(value.eventId) || !isBoundedString(value.startedAt) || blocker === undefined)
- return undefined;
- return {
- blocker,
- eventId: value.eventId,
- kind: "blocker.started",
- startedAt: value.startedAt,
- };
- }
- case "blocker.settled": {
- if (!hasOnlyKeys(value, ["blockerId", "eventId", "kind", "outcome", "settledAt"]))
- return undefined;
- if (
- !isIdentity(value.blockerId) ||
- !isIdentity(value.eventId) ||
- !isOneOf(value.outcome, ["completed", "cancelled", "failed"] as const) ||
- !isBoundedString(value.settledAt)
- )
- return undefined;
- return {
- blockerId: value.blockerId,
- eventId: value.eventId,
- kind: "blocker.settled",
- outcome: value.outcome,
- settledAt: value.settledAt,
- };
- }
- default:
- return null;
- }
-}
-
-function parseActionIdentity(value: unknown): ActivityActionIdentityV1 | undefined {
- if (
- !isRecord(value) ||
- !hasOnlyKeys(value, ["id", "kind", "name", "parentWorkId", "rootTurnId", "stepIndex"])
- )
- return undefined;
- if (
- !isIdentity(value.id) ||
- !isOneOf(value.kind, ["tool", "skill"] as const) ||
- !isBoundedString(value.name) ||
- !isIdentity(value.parentWorkId) ||
- !isIdentity(value.rootTurnId) ||
- !Number.isInteger(value.stepIndex) ||
- (value.stepIndex as number) < 0
- )
- return undefined;
- return {
- id: value.id,
- kind: value.kind,
- name: value.name,
- parentWorkId: value.parentWorkId,
- rootTurnId: value.rootTurnId,
- stepIndex: value.stepIndex as number,
- };
-}
-
-function parseBlockerIdentity(value: unknown): ActivityBlockerIdentityV1 | undefined {
- if (
- !isRecord(value) ||
- !hasOnlyKeys(value, ["id", "kind", "label", "parentActionId", "parentWorkId", "rootTurnId"])
- )
- return undefined;
- if (
- !isIdentity(value.id) ||
- !isOneOf(value.kind, ["approval", "authorization", "input"] as const) ||
- !isOptionalBoundedString(value.label) ||
- !isOptionalIdentity(value.parentActionId) ||
- !isIdentity(value.parentWorkId) ||
- !isIdentity(value.rootTurnId)
- )
- return undefined;
- return {
- id: value.id,
- kind: value.kind,
- label: value.label,
- parentActionId: value.parentActionId,
- parentWorkId: value.parentWorkId,
- rootTurnId: value.rootTurnId,
- };
-}
-
-function isRecord(value: unknown): value is Record<string, unknown> {
- return value !== null && typeof value === "object" && !Array.isArray(value);
-}
-function hasOnlyKeys(value: Record<string, unknown>, keys: readonly string[]): boolean {
- return Object.keys(value).every((key) => keys.includes(key));
-}
-function isBoundedString(value: unknown): value is string {
- return typeof value === "string" && value.length > 0 && value.length <= 500;
-}
-function isIdentity(value: unknown): value is string {
- return typeof value === "string" && value.length > 0 && value.length <= 1_000;
-}
-function isOptionalIdentity(value: unknown): value is string | undefined {
- return value === undefined || isIdentity(value);
-}
-function isOptionalBoundedString(value: unknown): value is string | undefined {
- return value === undefined || isBoundedString(value);
-}
-function isOneOf<const T extends readonly string[]>(value: unknown, values: T): value is T[number] {
- return typeof value === "string" && values.includes(value);
-}
diff --git a/packages/eve/src/protocol/routes.ts b/packages/eve/src/protocol/routes.ts
index c41b9a402..1ebd02dbf 100644
--- a/packages/eve/src/protocol/routes.ts
+++ b/packages/eve/src/protocol/routes.ts
@@ -115,9 +115,6 @@ export const EVE_CONNECTION_CALLBACK_ROUTE_PATTERN = `${EVE_ROUTE_PREFIX}/connec
*/
export const EVE_CALLBACK_ROUTE_PATTERN = `${EVE_ROUTE_PREFIX}/callback/:token`;
-/** Capability route for best-effort activity batches. */
-export const EVE_ACTIVITY_ROUTE_PATTERN = `${EVE_ROUTE_PREFIX}/activity/:token`;
-
/** Builds the ID-addressed message route for one session. */
export function createEveSessionRoutePath(sessionId: string): string {
return `${EVE_SESSION_ROUTE_PATH}/${encodeURIComponent(sessionId)}`;
@@ -186,8 +183,3 @@ export function createEveCallbackRoutePath(token: string): string {
export function createEveTaskInputRoutePath(token: string): string {
return `${EVE_ROUTE_PREFIX}/task-input/${encodeURIComponent(token)}`;
}
-
-/** Builds the capability path for one root activity collector. */
-export function createEveActivityRoutePath(token: string): string {
- return `${EVE_ROUTE_PREFIX}/activity/${encodeURIComponent(token)}`;
-}
diff --git a/packages/eve/src/public/channels/eve.test.ts b/packages/eve/src/public/channels/eve.test.ts
index 4b4d23d05..4f413545a 100644
--- a/packages/eve/src/public/channels/eve.test.ts
+++ b/packages/eve/src/public/channels/eve.test.ts
@@ -58,13 +58,7 @@ const OVERRIDE_AUTH: SessionAuthContext = {
type MockSendOptions = Pick<
RunInput,
- | "auth"
- | "callback"
- | "capabilities"
- | "continuationToken"
- | "activityObserver"
- | "initiatorAuth"
- | "title"
+ "auth" | "callback" | "capabilities" | "continuationToken" | "initiatorAuth" | "title"
>;
function createJsonMessageRequest(body: unknown): Request {
@@ -143,7 +137,6 @@ function createEveCreateHandler(
callback: runInput.callback,
capabilities: runInput.capabilities,
continuationToken: runInput.continuationToken,
- activityObserver: runInput.activityObserver,
initiatorAuth: runInput.initiatorAuth,
title: runInput.title,
} satisfies MockSendOptions);
@@ -1424,7 +1417,6 @@ describe("eveChannel — remote agent protocol 1 callers", () => {
});
const runInput = handler.createSession.mock.calls[0]?.[0];
expect(runInput?.callback).toEqual(callback);
- expect(runInput?.activityObserver).toBeUndefined();
expect(runInput?.legacyRemoteAgentCaller).toEqual(legacyCaller);
expect(logs.records).toContainEqual(
expect.objectContaining({
@@ -1445,7 +1437,6 @@ describe("eveChannel — remote agent protocol 1 callers", () => {
expect(response.status).toBe(202);
const options = handler.send.mock.calls[0]?.[1];
expect(options?.callback).toEqual(callback);
- expect(options?.activityObserver).toBeUndefined();
});
it("rejects a delegating caller on a protocol this deployment does not serve", async () => {
diff --git a/packages/eve/src/public/channels/slack/action-status.ts b/packages/eve/src/public/channels/slack/action-status.ts
index 533e83b9c..7582282e5 100644
--- a/packages/eve/src/public/channels/slack/action-status.ts
+++ b/packages/eve/src/public/channels/slack/action-status.ts
@@ -90,3 +90,11 @@ export function describeActionRequests(actions: readonly RuntimeActionRequest[])
const label = describeActionRequest(first);
return actions.length === 1 ? label : `${label} +${actions.length - 1} more`;
}
+
+/** `Waiting on researcher...`, `Waiting on researcher and deploy...`, or `... and 2 more tasks...`. */
+export function waitingOnTasks(names: readonly string[]): string {
+ const [first, second] = names;
+ if (names.length === 1) return `Waiting on ${first!}...`;
+ if (names.length === 2) return `Waiting on ${first!} and ${second!}...`;
+ return `Waiting on ${first!} and ${String(names.length - 1)} more tasks...`;
+}
diff --git a/packages/eve/src/public/channels/slack/activity-plan.test.ts b/packages/eve/src/public/channels/slack/activity-plan.test.ts
deleted file mode 100644
index 17a4106f5..000000000
--- a/packages/eve/src/public/channels/slack/activity-plan.test.ts
+++ /dev/null
@@ -1,187 +0,0 @@
-import { afterEach, describe, expect, it, vi } from "vitest";
-import { createActivitySnapshot, reduceActivityBatch } from "#execution/session-activity.js";
-import {
- buildSlackActivityRenderers,
- experimental_slackActivityPlan,
-} from "#public/channels/slack/activity.js";
-
-const root = {
- id: "root",
- kind: "root-turn" as const,
- rootSessionId: "session",
- rootTurnId: "turn",
-};
-const verifier = {
- id: "verifier",
- kind: "subagent" as const,
- name: "verifier",
- parentId: root.id,
- rootSessionId: "session",
- rootTurnId: "turn",
-};
-const stage = {
- id: "stage",
- kind: "subagent" as const,
- name: "verify_stage",
- parentId: verifier.id,
- rootSessionId: "session",
- rootTurnId: "turn",
-};
-const reviewer = {
- id: "reviewer",
- kind: "subagent" as const,
- name: "reviewer",
- parentId: root.id,
- rootSessionId: "session",
- rootTurnId: "turn",
-};
-const reviewStage = {
- id: "review-stage",
- kind: "subagent" as const,
- name: "review_stage",
- parentId: reviewer.id,
- rootSessionId: "session",
- rootTurnId: "turn",
-};
-
-describe("Slack activity plan", () => {
- afterEach(() => vi.unstubAllGlobals());
- it("streams descendant lifecycle once, then replaces the final plan with top-level work", async () => {
- const requests: Array<{ operation: string; body: URLSearchParams }> = [];
- vi.stubGlobal(
- "fetch",
- vi.fn(async (url: string | URL | Request, init?: RequestInit) => {
- const operation = String(url).split("/").at(-1)!;
- requests.push({ operation, body: new URLSearchParams(String(init?.body ?? "")) });
- return Response.json({ ok: true, ts: "1700.1" });
- }),
- );
- const renderer = buildSlackActivityRenderers({
- botToken: "xoxb-test",
- renderers: [experimental_slackActivityPlan()],
- })[0]!;
- const started = reduceActivityBatch(createActivitySnapshot(), {
- version: 1,
- events: [
- { eventId: "root", kind: "work.started", startedAt: "1", work: root },
- { eventId: "verifier", kind: "work.started", startedAt: "2", work: verifier },
- { eventId: "stage", kind: "work.started", startedAt: "3", work: stage },
- {
- action: {
- id: "verify-action",
- kind: "tool",
- name: "verify",
- parentWorkId: verifier.id,
- rootTurnId: "turn",
- stepIndex: 0,
- },
- eventId: "verify-action",
- kind: "action.started",
- startedAt: "3",
- },
- {
- actionId: "verify-action",
- eventId: "verify-action-label",
- kind: "action.label.updated",
- label: "Verify release",
- },
- ],
- });
- const state = await renderer.render({
- destination: { channelId: "C1", threadTs: "T1", teamId: "TEAM", triggeringUserId: "USER" },
- snapshot: started,
- state: undefined,
- });
- const updated = reduceActivityBatch(started, {
- version: 1,
- events: [
- {
- actionId: "verify-action",
- eventId: "verify-action-delta",
- kind: "action.label.updated",
- label: "Verifying tests",
- },
- ],
- });
- const updatedState = await renderer.render({
- destination: { channelId: "C1", threadTs: "T1", teamId: "TEAM", triggeringUserId: "USER" },
- snapshot: updated,
- state,
- });
- const expanded = reduceActivityBatch(updated, {
- version: 1,
- events: [
- { eventId: "reviewer", kind: "work.started", startedAt: "3", work: reviewer },
- { eventId: "review-stage", kind: "work.started", startedAt: "3", work: reviewStage },
- ],
- });
- const expandedState = await renderer.render({
- destination: { channelId: "C1", threadTs: "T1", teamId: "TEAM", triggeringUserId: "USER" },
- snapshot: expanded,
- state: updatedState,
- });
- const settled = reduceActivityBatch(expanded, {
- version: 1,
- events: [
- {
- eventId: "stage-done",
- kind: "work.settled",
- outcome: "completed",
- settledAt: "4",
- workId: stage.id,
- },
- {
- eventId: "review-stage-done",
- kind: "work.settled",
- outcome: "completed",
- settledAt: "4",
- workId: reviewStage.id,
- },
- {
- eventId: "verifier-done",
- kind: "work.settled",
- outcome: "completed",
- settledAt: "5",
- workId: verifier.id,
- },
- {
- eventId: "reviewer-done",
- kind: "work.settled",
- outcome: "completed",
- settledAt: "5",
- workId: reviewer.id,
- },
- {
- eventId: "root-done",
- kind: "work.settled",
- outcome: "completed",
- settledAt: "6",
- workId: root.id,
- },
- ],
- });
- await renderer.render({
- destination: { channelId: "C1", threadTs: "T1", teamId: "TEAM", triggeringUserId: "USER" },
- snapshot: settled,
- state: expandedState,
- });
- expect(requests.map((r) => r.operation)).toEqual([
- "chat.startStream",
- "chat.appendStream",
- "chat.appendStream",
- "chat.appendStream",
- "chat.appendStream",
- "chat.stopStream",
- "chat.update",
- ]);
- expect(requests[1]!.body.get("chunks")).toContain("• verify_stage\\n");
- expect(requests[1]!.body.get("chunks")).toContain("• Verify release\\n");
- expect(requests[2]!.body.get("chunks")).toContain("• Verifying tests\\n");
- expect(requests[3]!.body.get("chunks")).toContain('"id":"reviewer"');
- expect(requests[3]!.body.get("chunks")).toContain("• review_stage\\n");
- expect(requests[4]!.body.get("chunks")).toContain("✓ verify_stage\\n");
- expect(requests[4]!.body.get("chunks")).toContain("✓ review_stage\\n");
- expect(requests[6]!.body.get("blocks")).not.toContain("verify_stage");
- expect(requests[6]!.body.get("blocks")).toContain("verifier");
- });
-});
diff --git a/packages/eve/src/public/channels/slack/activity-plan.ts b/packages/eve/src/public/channels/slack/activity-plan.ts
deleted file mode 100644
index 4bb29c375..000000000
--- a/packages/eve/src/public/channels/slack/activity-plan.ts
+++ /dev/null
@@ -1,271 +0,0 @@
-import type { ChannelActivityRenderer } from "#channel/activity-renderer.js";
-import type { ActivitySnapshotV1, ActivityWorkStateV1 } from "#protocol/activity.js";
-import { callSlackApi, type SlackBotToken } from "#public/channels/slack/api.js";
-import type { SlackTransportOptions } from "#public/channels/slack/transport.js";
-
-export const SLACK_ACTIVITY_PLAN_RENDERER_ID = "slack.experimental.plan.v1";
-type Phase = "running" | "completed" | "failed" | "rejected" | "cancelled" | "blocked";
-interface PlanState {
- readonly streams: Readonly<
- Record<
- string,
- {
- readonly ts: string;
- readonly seen: Readonly<Record<string, string>>;
- readonly stopped: boolean;
- }
- >
- >;
-}
-
-export function createSlackPlanRenderer(
- apiOptions: SlackTransportOptions | undefined,
- botToken: SlackBotToken | undefined,
-): ChannelActivityRenderer {
- return {
- id: SLACK_ACTIVITY_PLAN_RENDERER_ID,
- async dispose() {},
- async render({ destination, snapshot, state }) {
- const channel = destination["channelId"],
- thread = destination["threadTs"],
- team = destination["teamId"],
- user = destination["triggeringUserId"],
- installation = destination["installationTeamId"];
- if (
- typeof channel !== "string" ||
- typeof thread !== "string" ||
- !thread ||
- typeof team !== "string" ||
- typeof user !== "string"
- )
- return state;
- const previous = isState(state) ? state.streams : {};
- const streams: Record<
- string,
- { ts: string; seen: Readonly<Record<string, string>>; stopped: boolean }
- > = { ...previous };
- for (const rootTurnId of new Set(
- Object.values(snapshot.work).map((work) => work.rootTurnId),
- )) {
- const view = project(snapshot, rootTurnId);
- let current = previous[rootTurnId];
- if (!current) {
- const response = await api(
- "chat.startStream",
- {
- channel,
- thread_ts: thread,
- recipient_team_id: team,
- recipient_user_id: user,
- task_display_mode: "plan",
- chunks: [
- { type: "plan_update", title: "Agent activity" },
- ...view.parents.map(taskChunk),
- ],
- },
- apiOptions,
- botToken,
- installation,
- );
- if (!response.ok || typeof response.ts !== "string")
- throw new Error(`Slack activity plan failed: ${response.error ?? "missing ts"}`);
- current = {
- ts: response.ts,
- seen: Object.fromEntries(view.parents.map((parent) => [parent.id, parent.phase])),
- stopped: false,
- };
- }
- if (current.stopped) {
- streams[rootTurnId] = current;
- continue;
- }
- const updates = detailUpdates(view, current.seen);
- if (updates.length)
- await checked(
- "chat.appendStream",
- { channel, ts: current.ts, chunks: updates },
- apiOptions,
- botToken,
- installation,
- );
- const seen = Object.fromEntries([
- ...view.parents.map((parent) => [parent.id, parent.phase]),
- ...view.entities.map((entity) => [entity.id, entityVersion(entity)]),
- ]);
- if (view.settled) {
- await checked(
- "chat.stopStream",
- { channel, ts: current.ts },
- apiOptions,
- botToken,
- installation,
- );
- const blocks = [
- {
- type: "plan",
- title: "Agent activity",
- tasks: view.parents.map((parent) => ({
- type: "task_card",
- task_id: safeId(parent.id),
- title: parent.name,
- status: status(parent.phase),
- })),
- },
- ];
- await checked(
- "chat.update",
- { channel, ts: current.ts, text: view.parents.map((p) => p.name).join(", "), blocks },
- apiOptions,
- botToken,
- installation,
- );
- streams[rootTurnId] = { ts: current.ts, seen, stopped: true };
- } else streams[rootTurnId] = { ts: current.ts, seen, stopped: false };
- }
- return { streams } satisfies PlanState;
- },
- };
-}
-
-interface Entity {
- id: string;
- name: string;
- phase: Phase;
- parent: string;
-}
-interface View {
- parents: ActivityWorkStateV1[];
- entities: Entity[];
- settled: boolean;
-}
-function project(snapshot: ActivitySnapshotV1, rootTurnId: string): View {
- const work = Object.values(snapshot.work).filter((w) => w.rootTurnId === rootTurnId);
- const roots = work.filter((w) => w.kind === "root-turn");
- const rootIds = new Set(roots.map((w) => w.id));
- let parents = work.filter((w) => w.parentId && rootIds.has(w.parentId));
- if (!parents.length) parents = roots;
- const owner = (workId: string): ActivityWorkStateV1 | undefined => {
- let item = work.find((w) => w.id === workId);
- while (item?.parentId && !parents.some((p) => p.id === item!.id))
- item = work.find((w) => w.id === item!.parentId);
- return item && parents.find((p) => p.id === item!.id);
- };
- const entities: Entity[] = [];
- for (const child of work)
- if (!parents.some((p) => p.id === child.id) && !rootIds.has(child.id)) {
- const p = owner(child.id);
- if (p)
- entities.push({
- id: child.id,
- name: child.name ?? "Agent work",
- phase: child.phase,
- parent: p.id,
- });
- }
- for (const action of Object.values(snapshot.actions).filter((a) => a.rootTurnId === rootTurnId)) {
- const p = owner(action.parentWorkId);
- if (p)
- entities.push({
- id: action.id,
- name: action.label ?? action.name,
- phase: action.phase,
- parent: p.id,
- });
- }
- for (const blocker of Object.values(snapshot.blockers).filter(
- (b) => b.rootTurnId === rootTurnId,
- )) {
- const p = owner(blocker.parentWorkId);
- if (p)
- entities.push({
- id: blocker.id,
- name: blocker.label ?? "Waiting",
- phase: blocker.phase,
- parent: p.id,
- });
- }
- const settled = [
- ...work,
- ...Object.values(snapshot.actions).filter((a) => a.rootTurnId === rootTurnId),
- ...Object.values(snapshot.blockers).filter((b) => b.rootTurnId === rootTurnId),
- ].every((e) => e.phase !== "running" && e.phase !== "blocked");
- return { parents, entities, settled };
-}
-function detailUpdates(view: View, seen: Readonly<Record<string, string>>) {
- const parentUpdates = view.parents
- .filter((parent) => seen[parent.id] !== parent.phase)
- .map(taskChunk);
- const descendantUpdates = view.entities
- .filter((entity) => seen[entity.id] !== entityVersion(entity))
- .map((entity) => ({
- type: "task_update",
- id: safeId(entity.parent),
- title: view.parents.find((parent) => parent.id === entity.parent)?.name ?? "Agent work",
- status: status(
- view.parents.find((parent) => parent.id === entity.parent)?.phase ?? "running",
- ),
- details: `${icon(entity.phase)} ${entity.name}\n`,
- }));
- return [...parentUpdates, ...descendantUpdates];
-}
-function entityVersion(entity: Entity): string {
- return `${entity.phase}:${entity.name}`;
-}
-function taskChunk(work: ActivityWorkStateV1) {
- return {
- type: "task_update",
- id: safeId(work.id),
- title: work.kind === "root-turn" ? "Agent turn" : (work.label ?? work.name ?? "Agent work"),
- status: status(work.phase),
- };
-}
-function status(phase: Phase) {
- return phase === "running" || phase === "blocked"
- ? "in_progress"
- : phase === "completed"
- ? "complete"
- : "error";
-}
-function icon(phase: Phase) {
- return phase === "running" || phase === "blocked"
- ? "•"
- : phase === "completed"
- ? "✓"
- : phase === "cancelled"
- ? "–"
- : "✗";
-}
-function safeId(id: string) {
- return id.replace(/[^a-zA-Z0-9_-]/g, "_").slice(-200);
-}
-async function api(
- operation: string,
- body: unknown,
- apiOptions: SlackTransportOptions | undefined,
- botToken: SlackBotToken | undefined,
- installation: unknown,
-) {
- return callSlackApi({
- api: apiOptions,
- operation,
- body,
- botToken,
- context: { teamId: typeof installation === "string" ? installation : undefined },
- });
-}
-async function checked(
- operation: string,
- body: unknown,
- apiOptions: SlackTransportOptions | undefined,
- token: SlackBotToken | undefined,
- installation: unknown,
-) {
- const response = await api(operation, body, apiOptions, token, installation);
- if (!response.ok)
- throw new Error(`Slack ${operation} failed: ${response.error ?? "unknown_error"}`);
-}
-function isState(value: unknown): value is PlanState {
- return (
- typeof value === "object" && value !== null && typeof Reflect.get(value, "streams") === "object"
- );
-}
diff --git a/packages/eve/src/public/channels/slack/activity-progress.test.ts b/packages/eve/src/public/channels/slack/activity-progress.test.ts
deleted file mode 100644
index b5f57d6ab..000000000
--- a/packages/eve/src/public/channels/slack/activity-progress.test.ts
+++ /dev/null
@@ -1,445 +0,0 @@
-import { afterEach, describe, expect, it, vi } from "vitest";
-
-import { createActivitySnapshot, reduceActivityBatch } from "#execution/session-activity.js";
-import {
- activityMessages,
- buildSlackActivityRenderers,
- experimental_slackActivityTree,
- experimental_slackActivityStatus,
- selectSlackActivityStatus,
-} from "#public/channels/slack/activity.js";
-
-const root = {
- id: "work:root:turn",
- kind: "root-turn" as const,
- rootSessionId: "root",
- rootTurnId: "turn",
-};
-const child = {
- id: "work:root:turn:child",
- kind: "subagent" as const,
- name: "research <team>",
- parentId: root.id,
- rootSessionId: "root",
- rootTurnId: "turn",
-};
-const grandchild = {
- id: "work:child:turn:grandchild",
- kind: "remote-agent" as const,
- name: "tester & reviewer",
- parentId: child.id,
- rootSessionId: "root",
- rootTurnId: "turn",
-};
-
-function snapshot() {
- return reduceActivityBatch(createActivitySnapshot(), {
- events: [
- { eventId: "root", kind: "work.started", startedAt: "2026-01-01T00:00:00Z", work: root },
- { eventId: "child", kind: "work.started", startedAt: "2026-01-01T00:00:01Z", work: child },
- {
- eventId: "grandchild",
- kind: "work.started",
- startedAt: "2026-01-01T00:00:02Z",
- work: grandchild,
- },
- {
- action: {
- id: `${grandchild.id}:search`,
- kind: "tool",
- name: "search <web>",
- parentWorkId: grandchild.id,
- rootTurnId: "turn",
- stepIndex: 1,
- },
- eventId: "search-started",
- kind: "action.started",
- startedAt: "2026-01-01T00:00:03Z",
- },
- ],
- version: 1,
- });
-}
-
-describe("Slack activity activity", () => {
- afterEach(() => vi.unstubAllGlobals());
-
- it("derives one nested artifact per root turn and escapes untrusted text", () => {
- expect(activityMessages(snapshot())).toEqual(
- new Map([
- [
- "turn",
- [
- "```",
- "• Working",
- "└── • research &lt;team&gt;",
- " └── • tester &amp; reviewer",
- " └── • search &lt;web&gt;",
- "```",
- ].join("\n"),
- ],
- ]),
- );
- });
-
- it("uses action labels in the activity tree and status", () => {
- const labeled = reduceActivityBatch(snapshot(), {
- events: [
- {
- actionId: `${grandchild.id}:search`,
- eventId: "search-label",
- kind: "action.label.updated",
- label: "Search Slack docs",
- },
- ],
- version: 1,
- });
-
- expect(activityMessages(labeled).get("turn")).toContain("Search Slack docs");
- expect(selectSlackActivityStatus(labeled)).toBe("Search Slack docs");
-
- const completed = reduceActivityBatch(labeled, {
- events: [
- {
- actionId: `${grandchild.id}:search`,
- eventId: "search-complete-label",
- kind: "action.label.updated",
- label: "Found Slack docs",
- },
- ],
- version: 1,
- });
- expect(activityMessages(completed).get("turn")).toContain("Found Slack docs");
- expect(selectSlackActivityStatus(completed)).toBe("Found Slack docs");
- });
-
- it("keeps task-reporting activity in the originating tree", () => {
- const reportingAction = {
- action: {
- id: "action:work:root:turn:report",
- kind: "tool" as const,
- name: "compose_result",
- parentWorkId: root.id,
- rootTurnId: "turn",
- stepIndex: 0,
- },
- eventId: "report",
- kind: "action.started" as const,
- startedAt: "4",
- };
- const activity = reduceActivityBatch(snapshot(), {
- events: [reportingAction],
- version: 1,
- });
-
- expect(activityMessages(activity)).toEqual(
- new Map([["turn", expect.stringContaining("compose_result")]]),
- );
- });
-
- it("renders inherited child tool activity beneath an existing subagent row", () => {
- const task = {
- id: "work:task",
- kind: "subagent" as const,
- name: "slack",
- parentId: root.id,
- rootSessionId: "root",
- rootTurnId: "turn",
- };
- const activity = reduceActivityBatch(createActivitySnapshot(), {
- events: [
- { eventId: "root", kind: "work.started", startedAt: "1", work: root },
- { eventId: "task", kind: "work.started", startedAt: "2", work: task },
- {
- action: {
- id: "action:work:task:search",
- kind: "tool",
- name: "search_slack",
- parentWorkId: task.id,
- rootTurnId: "turn",
- stepIndex: 0,
- },
- eventId: "search",
- kind: "action.started",
- startedAt: "3",
- },
- ],
- version: 1,
- });
-
- expect(activityMessages(activity).get("turn")).toBe(
- "```\n• Working\n└── • slack\n └── • search_slack\n```",
- );
- });
-
- it("renders a delegated child instead of its duplicate initiating tool action", () => {
- const child = {
- callId: "call-researcher",
- id: "work:researcher",
- kind: "subagent" as const,
- name: "researcher",
- parentId: root.id,
- rootSessionId: "root",
- rootTurnId: "turn",
- };
- const delegated = reduceActivityBatch(createActivitySnapshot(), {
- events: [
- { eventId: "root", kind: "work.started", startedAt: "1", work: root },
- {
- action: {
- id: `action:${root.id}:call-researcher`,
- kind: "tool",
- name: "researcher",
- parentWorkId: root.id,
- rootTurnId: "turn",
- stepIndex: 0,
- },
- eventId: "action",
- kind: "action.started",
- startedAt: "2",
- },
- { eventId: "child", kind: "work.started", startedAt: "3", work: child },
- ],
- version: 1,
- });
-
- expect(activityMessages(delegated).get("turn")).toBe("```\n• Working\n└── • researcher\n```");
- });
-
- it("keeps temporarily orphaned nested work renderable", () => {
- const orphan = reduceActivityBatch(createActivitySnapshot(), {
- events: [
- {
- eventId: "grandchild",
- kind: "work.started",
- startedAt: "2026-01-01T00:00:02Z",
- work: grandchild,
- },
- ],
- version: 1,
- });
- expect(activityMessages(orphan).get("turn")).toContain("tester &amp; reviewer");
- });
-
- it("creates a metadata-tagged message and updates it in place", async () => {
- const requests: Array<{ body: URLSearchParams; operation: string }> = [];
- vi.stubGlobal(
- "fetch",
- vi.fn(async (url: string | URL | Request, init?: RequestInit) => {
- const operation = String(url).split("/").at(-1)!;
- requests.push({ body: new URLSearchParams(String(init?.body ?? "")), operation });
- if (operation === "conversations.replies") return Response.json({ ok: true, messages: [] });
- return Response.json({ ok: true, ts: "1700.1" });
- }),
- );
- const renderer = buildSlackActivityRenderers({
- botToken: "xoxb-test",
- renderers: [experimental_slackActivityTree()],
- })[0]!;
- const state = await renderer.render({
- destination: { channelId: "C1", threadTs: "T1" },
- snapshot: snapshot(),
- state: undefined,
- });
- const settled = reduceActivityBatch(snapshot(), {
- events: [
- {
- eventId: "settled",
- kind: "work.settled",
- outcome: "completed",
- settledAt: "2026-01-01T00:00:05Z",
- workId: grandchild.id,
- },
- ],
- version: 1,
- });
- await renderer.render({
- destination: { channelId: "C1", threadTs: "T1" },
- snapshot: settled,
- state,
- });
-
- expect(activityMessages(settled).get("turn")).toContain("✓ tester &amp; reviewer");
- expect(activityMessages(settled).get("turn")).toContain("⊘ search &lt;web&gt;");
- expect(requests.map((request) => request.operation)).toEqual([
- "conversations.replies",
- "chat.postMessage",
- "chat.update",
- ]);
- expect(requests[1]?.body.get("metadata")).toContain('"root_turn_id":"turn"');
- expect(requests[2]?.body.get("ts")).toBe("1700.1");
- });
-
- it("recreates a deleted activity message", async () => {
- const operations: string[] = [];
- vi.stubGlobal(
- "fetch",
- vi.fn(async (url: string | URL | Request) => {
- const operation = String(url).split("/").at(-1)!;
- operations.push(operation);
- return operation === "chat.update"
- ? Response.json({ error: "message_not_found", ok: false })
- : Response.json({ ok: true, ts: "1700.2" });
- }),
- );
- const renderer = buildSlackActivityRenderers({
- botToken: "xoxb-test",
- renderers: [experimental_slackActivityTree()],
- })[0]!;
- const state = await renderer.render({
- destination: { channelId: "C1", threadTs: "T1" },
- snapshot: snapshot(),
- state: { messages: { turn: { text: "old", ts: "1700.1" } } },
- });
- expect(operations).toEqual(["chat.update", "chat.postMessage"]);
- expect(state).toMatchObject({ messages: { turn: { ts: "1700.2" } } });
- });
-
- it("passes the installation team to activity message token resolution", async () => {
- const tokenContext = vi.fn(() => "xoxb-team");
- vi.stubGlobal(
- "fetch",
- vi.fn(async () => Response.json({ ok: true, ts: "1700.1" })),
- );
- const renderer = buildSlackActivityRenderers({
- botToken: tokenContext,
- renderers: [experimental_slackActivityTree()],
- })[0]!;
-
- await renderer.render({
- destination: { channelId: "C1", installationTeamId: "T_INSTALL", threadTs: "T1" },
- snapshot: snapshot(),
- state: undefined,
- });
-
- expect(tokenContext).toHaveBeenCalledWith({ teamId: "T_INSTALL" });
- });
-
- it("recovers provider identity from message metadata", async () => {
- const operations: string[] = [];
- vi.stubGlobal(
- "fetch",
- vi.fn(async (url: string | URL | Request) => {
- const operation = String(url).split("/").at(-1)!;
- operations.push(operation);
- if (operation === "conversations.replies") {
- return Response.json({
- messages: [
- {
- metadata: {
- event_payload: { root_turn_id: "turn" },
- event_type: "eve_progress",
- },
- text: "old",
- ts: "1700.1",
- },
- ],
- ok: true,
- });
- }
- return Response.json({ ok: true, ts: "1700.1" });
- }),
- );
- const renderer = buildSlackActivityRenderers({
- botToken: "xoxb-test",
- renderers: [experimental_slackActivityTree()],
- })[0]!;
- await renderer.render({
- destination: { channelId: "C1", threadTs: "T1" },
- snapshot: snapshot(),
- state: undefined,
- });
- expect(operations).toEqual(["conversations.replies", "chat.update"]);
- });
-
- it("paginates metadata recovery until a matching activity message is found", async () => {
- const repliesBodies: URLSearchParams[] = [];
- vi.stubGlobal(
- "fetch",
- vi.fn(async (url: string | URL | Request, init?: RequestInit) => {
- const operation = String(url).split("/").at(-1)!;
- if (operation === "conversations.replies") {
- const body = new URLSearchParams(String(init?.body ?? ""));
- repliesBodies.push(body);
- if (body.get("cursor") === null) {
- return Response.json({
- messages: [],
- ok: true,
- response_metadata: { next_cursor: "page-2" },
- });
- }
- return Response.json({
- messages: [
- {
- metadata: {
- event_payload: { root_turn_id: "turn" },
- event_type: "eve_progress",
- },
- text: "old",
- ts: "1700.1",
- },
- ],
- ok: true,
- response_metadata: { next_cursor: "" },
- });
- }
- return Response.json({ ok: true, ts: "1700.1" });
- }),
- );
- const renderer = buildSlackActivityRenderers({
- botToken: "xoxb-test",
- renderers: [experimental_slackActivityTree()],
- })[0]!;
- await renderer.render({
- destination: { channelId: "C1", threadTs: "T1" },
- snapshot: snapshot(),
- state: undefined,
- });
-
- expect(repliesBodies.map((body) => body.get("cursor"))).toEqual([null, "page-2"]);
- });
-
- it("stops recovery when Slack repeats a cursor", async () => {
- const operations: string[] = [];
- vi.stubGlobal(
- "fetch",
- vi.fn(async (url: string | URL | Request) => {
- const operation = String(url).split("/").at(-1)!;
- operations.push(operation);
- return operation === "conversations.replies"
- ? Response.json({
- messages: [],
- ok: true,
- response_metadata: { next_cursor: "same" },
- })
- : Response.json({ ok: true, ts: "1700.2" });
- }),
- );
- const renderer = buildSlackActivityRenderers({
- botToken: "xoxb-test",
- renderers: [experimental_slackActivityTree()],
- })[0]!;
- await renderer.render({
- destination: { channelId: "C1", threadTs: "T1" },
- snapshot: snapshot(),
- state: undefined,
- });
-
- expect(operations).toEqual([
- "conversations.replies",
- "conversations.replies",
- "chat.postMessage",
- ]);
- });
-
- it("composes activity and status with isolated renderer state", () => {
- const renderers = buildSlackActivityRenderers({
- botToken: "xoxb-test",
- renderers: [experimental_slackActivityStatus(), experimental_slackActivityTree()],
- });
- expect(renderers.map((renderer) => renderer.id)).toEqual([
- "slack.status.v1",
- "slack.experimental.tree.v1",
- ]);
- });
-});
diff --git a/packages/eve/src/public/channels/slack/activity.test.ts b/packages/eve/src/public/channels/slack/activity.test.ts
deleted file mode 100644
index 1b1323b6f..000000000
--- a/packages/eve/src/public/channels/slack/activity.test.ts
+++ /dev/null
@@ -1,299 +0,0 @@
-import { afterEach, describe, expect, it, vi } from "vitest";
-
-import { isCompiledChannel } from "#channel/compiled-channel.js";
-import { getChannelActivityPresentation } from "#channel/activity-renderer.js";
-import { createActivitySnapshot, reduceActivityBatch } from "#execution/session-activity.js";
-import {
- buildSlackActivityRenderers,
- experimental_slackActivityRenderer,
- selectSlackActivityStatus,
- experimental_slackActivityStatus,
-} from "#public/channels/slack/activity.js";
-import { slackChannel } from "#public/channels/slack/slackChannel.js";
-
-const root = {
- id: "work:root:turn",
- kind: "root-turn" as const,
- rootSessionId: "root",
- rootTurnId: "turn",
- sessionId: "root",
- turnId: "turn",
-};
-const child = {
- callId: "child",
- id: "work:root:turn:child",
- kind: "subagent" as const,
- name: "research",
- parentId: root.id,
- rootSessionId: "root",
- rootTurnId: "turn",
-};
-
-function snapshot(events: Parameters<typeof reduceActivityBatch>[1]["events"]) {
- return reduceActivityBatch(createActivitySnapshot(), { events, version: 1 });
-}
-
-describe("Slack status activity", () => {
- afterEach(() => {
- vi.unstubAllEnvs();
- vi.unstubAllGlobals();
- });
-
- it("installs renderer configuration with a narrow destination", () => {
- const channel = slackChannel({ activity: { renderers: [experimental_slackActivityStatus()] } });
- expect(isCompiledChannel(channel)).toBe(true);
- if (!isCompiledChannel(channel)) return;
- const presentation = getChannelActivityPresentation(channel.adapter);
- expect(presentation?.renderers).toHaveLength(1);
- expect(
- presentation?.destination({ channelId: "C1", secret: "hidden", threadTs: "T1" }),
- ).toEqual({
- channelId: "C1",
- installationTeamId: null,
- teamId: null,
- threadTs: "T1",
- triggeringUserId: null,
- });
- });
-
- it("installs an experimental custom renderer", async () => {
- const render = vi.fn(async ({ state }: { readonly state: number | undefined }) =>
- state === undefined ? 1 : state + 1,
- );
- const dispose = vi.fn(async () => undefined);
- const custom = experimental_slackActivityRenderer<number>({
- id: "custom.activity.v1",
- render,
- dispose,
- });
- const [renderer] = buildSlackActivityRenderers({ botToken: undefined, renderers: [custom] });
- const activitySnapshot = snapshot([
- { eventId: "root", kind: "work.started", startedAt: "2026-01-01T00:00:00Z", work: root },
- ]);
-
- await expect(
- renderer?.render({
- destination: {
- channelId: "C1",
- installationTeamId: "T1",
- teamId: null,
- threadTs: "M1",
- triggeringUserId: null,
- },
- snapshot: activitySnapshot,
- state: undefined,
- }),
- ).resolves.toBe(1);
- await renderer?.dispose?.({
- destination: {
- channelId: "C1",
- installationTeamId: "T1",
- teamId: null,
- threadTs: "M1",
- triggeringUserId: null,
- },
- state: 1,
- });
-
- expect(render).toHaveBeenCalledWith({
- destination: {
- channelId: "C1",
- installationTeamId: "T1",
- teamId: null,
- threadTs: "M1",
- triggeringUserId: null,
- },
- snapshot: activitySnapshot,
- state: undefined,
- });
- expect(dispose).toHaveBeenCalledWith({
- destination: {
- channelId: "C1",
- installationTeamId: "T1",
- teamId: null,
- threadTs: "M1",
- triggeringUserId: null,
- },
- state: 1,
- });
- });
-
- it("rejects invalid experimental custom renderers", () => {
- expect(() =>
- experimental_slackActivityRenderer({ id: "", render: async () => undefined }),
- ).toThrow("ids must be non-empty");
- expect(() =>
- experimental_slackActivityRenderer({
- id: experimental_slackActivityStatus().id,
- render: async () => undefined,
- }),
- ).toThrow("reserved by eve");
- });
-
- it("rejects duplicate renderer configuration", () => {
- expect(() =>
- slackChannel({
- activity: {
- renderers: [experimental_slackActivityStatus(), experimental_slackActivityStatus()],
- },
- }),
- ).toThrow("Duplicate Slack activity renderer");
- });
-
- it("prioritizes active actions, then falls back to delegated and root work", () => {
- expect(
- selectSlackActivityStatus(
- snapshot([
- { eventId: "root", kind: "work.started", startedAt: "2026-01-01T00:00:00Z", work: root },
- {
- action: {
- id: `${root.id}:search`,
- kind: "tool",
- name: "search",
- parentWorkId: root.id,
- rootTurnId: root.rootTurnId,
- stepIndex: 0,
- },
- eventId: "search",
- kind: "action.started",
- startedAt: "2026-01-01T00:00:01Z",
- },
- ]),
- ),
- ).toBe("search");
- expect(
- selectSlackActivityStatus(
- snapshot([
- { eventId: "root", kind: "work.started", startedAt: "2026-01-01T00:00:00Z", work: root },
- {
- eventId: "child",
- kind: "work.started",
- startedAt: "2026-01-01T00:00:01Z",
- work: child,
- },
- ]),
- ),
- ).toBe("research");
- expect(
- selectSlackActivityStatus(
- snapshot([
- { eventId: "root", kind: "work.started", startedAt: "2026-01-01T00:00:00Z", work: root },
- ]),
- ),
- ).toBe("Working…");
- });
-
- it("prioritizes blockers over active actions", () => {
- expect(
- selectSlackActivityStatus(
- snapshot([
- { eventId: "root", kind: "work.started", startedAt: "2026-01-01T00:00:00Z", work: root },
- {
- action: {
- id: `${root.id}:search`,
- kind: "tool",
- name: "search",
- parentWorkId: root.id,
- rootTurnId: root.rootTurnId,
- stepIndex: 0,
- },
- eventId: "search",
- kind: "action.started",
- startedAt: "2026-01-01T00:00:01Z",
- },
- {
- blocker: {
- id: "authorization:attempt",
- kind: "authorization",
- parentWorkId: root.id,
- rootTurnId: root.rootTurnId,
- },
- eventId: "authorization",
- kind: "blocker.started",
- startedAt: "2026-01-01T00:00:02Z",
- },
- ]),
- ),
- ).toBe("Waiting for sign-in…");
- });
-
- it("clears when represented work settles", () => {
- expect(
- selectSlackActivityStatus(
- snapshot([
- { eventId: "root", kind: "work.started", startedAt: "2026-01-01T00:00:00Z", work: root },
- {
- eventId: "settled",
- kind: "work.settled",
- outcome: "completed",
- settledAt: "2026-01-01T00:00:01Z",
- workId: root.id,
- },
- ]),
- ),
- ).toBe("");
- });
-
- it("passes the installation team to function bot tokens", async () => {
- const tokenContext = vi.fn(() => "xoxb-team");
- vi.stubGlobal(
- "fetch",
- vi.fn(async () => Response.json({ ok: true })),
- );
- const renderer = buildSlackActivityRenderers({
- botToken: tokenContext,
- renderers: [experimental_slackActivityStatus()],
- })[0]!;
-
- await renderer.render({
- destination: { channelId: "C1", installationTeamId: "T_INSTALL", threadTs: "T1" },
- snapshot: snapshot([
- { eventId: "root", kind: "work.started", startedAt: "2026-01-01T00:00:00Z", work: root },
- ]),
- state: undefined,
- });
-
- expect(tokenContext).toHaveBeenCalledWith({ teamId: "T_INSTALL" });
- });
-
- it("suppresses duplicate provider writes", async () => {
- vi.stubEnv("SLACK_BOT_TOKEN", "xoxb-test");
- const fetchMock = vi.fn(async () => Response.json({ ok: true }));
- vi.stubGlobal("fetch", fetchMock);
- const renderer = buildSlackActivityRenderers({
- botToken: undefined,
- renderers: [experimental_slackActivityStatus()],
- })[0]!;
- const active = snapshot([
- { eventId: "root", kind: "work.started", startedAt: "2026-01-01T00:00:00Z", work: root },
- ]);
- const state = await renderer.render({
- destination: { channelId: "C1", threadTs: "T1" },
- snapshot: active,
- state: undefined,
- });
- await renderer.render({
- destination: { channelId: "C1", threadTs: "T1" },
- snapshot: active,
- state,
- });
- expect(fetchMock).toHaveBeenCalledOnce();
- });
-
- it("clears transient status on disposal", async () => {
- vi.stubEnv("SLACK_BOT_TOKEN", "xoxb-test");
- const fetchMock = vi.fn(async (_url: string | URL | Request, _init?: RequestInit) =>
- Response.json({ ok: true }),
- );
- vi.stubGlobal("fetch", fetchMock);
- const renderer = buildSlackActivityRenderers({
- botToken: undefined,
- renderers: [experimental_slackActivityStatus()],
- })[0]!;
- await renderer.dispose?.({
- destination: { channelId: "C1", threadTs: "T1" },
- state: { status: "Working…" },
- });
- expect(new URLSearchParams(String(fetchMock.mock.calls[0]?.[1]?.body)).get("status")).toBe("");
- });
-});
diff --git a/packages/eve/src/public/channels/slack/activity.ts b/packages/eve/src/public/channels/slack/activity.ts
deleted file mode 100644
index 2a671cdaa..000000000
--- a/packages/eve/src/public/channels/slack/activity.ts
+++ /dev/null
@@ -1,600 +0,0 @@
-import type { ChannelActivityRenderer } from "#channel/activity-renderer.js";
-import type {
- ActivityActionStateV1,
- ActivityBlockerStateV1,
- ActivitySnapshotV1,
- ActivityWorkStateV1,
-} from "#protocol/activity.js";
-import { callSlackApi, type SlackBotToken } from "#public/channels/slack/api.js";
-import type { SlackTransportOptions } from "#public/channels/slack/transport.js";
-import {
- createSlackPlanRenderer,
- SLACK_ACTIVITY_PLAN_RENDERER_ID,
-} from "#public/channels/slack/activity-plan.js";
-import { truncateTypingStatus } from "#public/channels/slack/limits.js";
-
-const SLACK_ACTIVITY_STATUS_RENDERER_ID = "slack.status.v1";
-const SLACK_ACTIVITY_MESSAGE_RENDERER_ID = "slack.experimental.tree.v1";
-const SLACK_ACTIVITY_RENDERER = Symbol("eve.slack.activity-renderer");
-
-export interface SlackActivityRenderer {
- readonly id: string;
- readonly [SLACK_ACTIVITY_RENDERER]: true;
-}
-
-/**
- * Activity snapshot passed to an experimental Slack activity renderer.
- *
- * This contract is unstable and may change or be removed in any release.
- */
-export type ExperimentalSlackActivitySnapshot = ActivitySnapshotV1;
-
-/** Slack destination passed to an experimental activity renderer. */
-export interface ExperimentalSlackActivityDestination {
- readonly channelId: string | null;
- readonly installationTeamId: string | null;
- readonly teamId: string | null;
- readonly threadTs: string | null;
- readonly triggeringUserId: string | null;
-}
-
-/**
- * Experimental custom Slack activity renderer.
- *
- * Renderer state is retained by renderer id between snapshots. This contract
- * is unstable and may change or be removed in any release.
- */
-export interface ExperimentalSlackActivityRenderer<State = unknown> {
- readonly id: string;
- render(input: {
- readonly destination: ExperimentalSlackActivityDestination;
- readonly snapshot: ExperimentalSlackActivitySnapshot;
- readonly state: State | undefined;
- }): Promise<State | undefined>;
- dispose?(input: {
- readonly destination: ExperimentalSlackActivityDestination;
- readonly state: State | undefined;
- }): Promise<void>;
-}
-
-interface SlackActivityStatusState {
- readonly status: string;
-}
-
-interface SlackActivityMessageState {
- readonly messages: Readonly<Record<string, { readonly text: string; readonly ts: string }>>;
-}
-
-/** Creates the compact Slack assistant-thread activity renderer. */
-export function experimental_slackActivityStatus(): SlackActivityRenderer {
- return { [SLACK_ACTIVITY_RENDERER]: true, id: SLACK_ACTIVITY_STATUS_RENDERER_ID };
-}
-
-/** Creates one experimental update-in-place Unicode activity tree per root turn. */
-export function experimental_slackActivityTree(): SlackActivityRenderer {
- return { [SLACK_ACTIVITY_RENDERER]: true, id: SLACK_ACTIVITY_MESSAGE_RENDERER_ID };
-}
-
-/** Creates one experimental native Slack plan stream per root turn. */
-export function experimental_slackActivityPlan(): SlackActivityRenderer {
- return { [SLACK_ACTIVITY_RENDERER]: true, id: SLACK_ACTIVITY_PLAN_RENDERER_ID };
-}
-
-/**
- * Registers an experimental custom Slack activity renderer.
- *
- * The renderer contract is unstable and may change or be removed in any
- * release.
- */
-export function experimental_slackActivityRenderer<State>(
- renderer: ExperimentalSlackActivityRenderer<State>,
-): SlackActivityRenderer {
- validateCustomSlackActivityRenderer(renderer);
- return {
- [SLACK_ACTIVITY_RENDERER]: true,
- id: renderer.id,
- render: renderer.render,
- dispose: renderer.dispose,
- } as SlackActivityRenderer;
-}
-
-export function hasSlackActivityStatus(
- renderers: readonly SlackActivityRenderer[] | undefined,
-): boolean {
- return renderers?.some((renderer) => renderer.id === SLACK_ACTIVITY_STATUS_RENDERER_ID) === true;
-}
-
-export function buildSlackActivityRenderers(input: {
- readonly api?: SlackTransportOptions;
- readonly botToken: SlackBotToken | undefined;
- readonly renderers: readonly SlackActivityRenderer[];
-}): readonly ChannelActivityRenderer[] {
- const ids = new Set<string>();
- return input.renderers.map((renderer) => {
- if (renderer[SLACK_ACTIVITY_RENDERER] !== true) {
- throw new TypeError("Slack activity renderers must be created by an eve renderer factory.");
- }
- if (ids.has(renderer.id))
- throw new TypeError(`Duplicate Slack activity renderer "${renderer.id}".`);
- ids.add(renderer.id);
- if (renderer.id === SLACK_ACTIVITY_MESSAGE_RENDERER_ID) {
- return createSlackActivityRenderer(input.api, input.botToken);
- }
- if (renderer.id === SLACK_ACTIVITY_PLAN_RENDERER_ID) {
- return createSlackPlanRenderer(input.api, input.botToken);
- }
- if (renderer.id === SLACK_ACTIVITY_STATUS_RENDERER_ID) {
- return createSlackStatusRenderer(input.api, input.botToken);
- }
- assertCustomSlackActivityRenderer(renderer);
- return createCustomSlackActivityRenderer(renderer);
- });
-}
-
-function assertCustomSlackActivityRenderer(
- renderer: SlackActivityRenderer,
-): asserts renderer is SlackActivityRenderer & ExperimentalSlackActivityRenderer {
- validateCustomSlackActivityRenderer(renderer);
-}
-
-function validateCustomSlackActivityRenderer(
- renderer: unknown,
-): asserts renderer is ExperimentalSlackActivityRenderer {
- if (
- typeof renderer !== "object" ||
- renderer === null ||
- !("id" in renderer) ||
- typeof renderer.id !== "string" ||
- renderer.id.trim() === ""
- ) {
- throw new TypeError("Slack activity renderer ids must be non-empty strings.");
- }
- if (
- renderer.id === SLACK_ACTIVITY_STATUS_RENDERER_ID ||
- renderer.id === SLACK_ACTIVITY_MESSAGE_RENDERER_ID ||
- renderer.id === SLACK_ACTIVITY_PLAN_RENDERER_ID
- ) {
- throw new TypeError(`Slack activity renderer id "${renderer.id}" is reserved by eve.`);
- }
- if (!("render" in renderer) || typeof renderer.render !== "function") {
- throw new TypeError("Custom Slack activity renderers must define a render function.");
- }
- if (
- "dispose" in renderer &&
- renderer.dispose !== undefined &&
- typeof renderer.dispose !== "function"
- ) {
- throw new TypeError("Custom Slack activity renderer dispose must be a function.");
- }
-}
-
-function createCustomSlackActivityRenderer(
- renderer: ExperimentalSlackActivityRenderer,
-): ChannelActivityRenderer {
- return {
- id: renderer.id,
- async render({ destination, snapshot, state }) {
- return renderer.render({
- destination: experimentalSlackActivityDestination(destination),
- snapshot,
- state,
- });
- },
- async dispose({ destination, state }) {
- await renderer.dispose?.({
- destination: experimentalSlackActivityDestination(destination),
- state,
- });
- },
- };
-}
-
-function experimentalSlackActivityDestination(
- destination: Readonly<Record<string, unknown>>,
-): ExperimentalSlackActivityDestination {
- return {
- channelId: typeof destination["channelId"] === "string" ? destination["channelId"] : null,
- installationTeamId:
- typeof destination["installationTeamId"] === "string"
- ? destination["installationTeamId"]
- : null,
- teamId: typeof destination["teamId"] === "string" ? destination["teamId"] : null,
- threadTs: typeof destination["threadTs"] === "string" ? destination["threadTs"] : null,
- triggeringUserId:
- typeof destination["triggeringUserId"] === "string" ? destination["triggeringUserId"] : null,
- };
-}
-
-function createSlackStatusRenderer(
- api: SlackTransportOptions | undefined,
- botToken: SlackBotToken | undefined,
-): ChannelActivityRenderer {
- return {
- id: SLACK_ACTIVITY_STATUS_RENDERER_ID,
- async dispose({ destination, state }) {
- if (!isSlackStatusState(state) || state.status === "") return;
- const channelId = destination["channelId"];
- const installationTeamId = destination["installationTeamId"];
- const threadTs = destination["threadTs"];
- if (typeof channelId !== "string" || typeof threadTs !== "string" || threadTs === "") return;
- const response = await callSlackApi({
- api,
- body: { channel_id: channelId, status: "", thread_ts: threadTs },
- botToken,
- context: {
- teamId: typeof installationTeamId === "string" ? installationTeamId : undefined,
- },
- operation: "assistant.threads.setStatus",
- });
- if (response.ok !== true)
- throw new Error(`Slack status disposal failed: ${response.error ?? "unknown_error"}`);
- },
- async render({ destination, snapshot, state }) {
- const channelId = destination["channelId"];
- const installationTeamId = destination["installationTeamId"];
- const threadTs = destination["threadTs"];
- if (typeof channelId !== "string" || typeof threadTs !== "string" || threadTs === "")
- return state;
- const status = selectSlackActivityStatus(snapshot);
- if (isSlackStatusState(state) && state.status === status) return state;
- const body: Record<string, unknown> = { channel_id: channelId, status, thread_ts: threadTs };
- if (status !== "") body.loading_messages = [status];
- const response = await callSlackApi({
- api,
- body,
- botToken,
- context: {
- teamId: typeof installationTeamId === "string" ? installationTeamId : undefined,
- },
- operation: "assistant.threads.setStatus",
- });
- if (response.ok !== true) {
- throw new Error(
- `Slack assistant.threads.setStatus failed: ${response.error ?? "unknown_error"}`,
- );
- }
- return { status } satisfies SlackActivityStatusState;
- },
- };
-}
-
-function createSlackActivityRenderer(
- api: SlackTransportOptions | undefined,
- botToken: SlackBotToken | undefined,
-): ChannelActivityRenderer {
- return {
- id: SLACK_ACTIVITY_MESSAGE_RENDERER_ID,
- async dispose() {},
- async render({ destination, snapshot, state }) {
- const channelId = destination["channelId"];
- const installationTeamId = destination["installationTeamId"];
- const threadTs = destination["threadTs"];
- if (typeof channelId !== "string" || typeof threadTs !== "string" || threadTs === "") {
- return state;
- }
- const previous = isActivityState(state) ? state.messages : {};
- const desired = activityMessages(snapshot);
- const messages: Record<string, { readonly text: string; readonly ts: string }> =
- Object.fromEntries(
- Object.entries(previous).filter(([rootTurnId]) => desired.has(rootTurnId)),
- );
- for (const [rootTurnId, text] of desired) {
- const current =
- previous[rootTurnId] ??
- (await recoverActivityMessage({
- api,
- botToken,
- channelId,
- installationTeamId,
- rootTurnId,
- threadTs,
- }));
- if (current?.text === text) {
- messages[rootTurnId] = current;
- continue;
- }
- let response = await writeActivityMessage({
- api,
- botToken,
- channelId,
- current,
- installationTeamId,
- rootTurnId,
- text,
- threadTs,
- });
- if (
- response.ok !== true &&
- current !== undefined &&
- response.error === "message_not_found"
- ) {
- response = await writeActivityMessage({
- api,
- botToken,
- channelId,
- installationTeamId,
- rootTurnId,
- text,
- threadTs,
- });
- }
- if (response.ok !== true) {
- throw new Error(`Slack activity message failed: ${response.error ?? "unknown_error"}`);
- }
- const ts = response.ts ?? current?.ts;
- if (typeof ts !== "string" || ts === "") {
- throw new Error("Slack activity message response did not include ts.");
- }
- messages[rootTurnId] = { text, ts };
- }
- return { messages } satisfies SlackActivityMessageState;
- },
- };
-}
-
-async function writeActivityMessage(input: {
- readonly api: SlackTransportOptions | undefined;
- readonly botToken: SlackBotToken | undefined;
- readonly channelId: string;
- readonly current?: { readonly ts: string };
- readonly installationTeamId: unknown;
- readonly rootTurnId: string;
- readonly text: string;
- readonly threadTs: string;
-}) {
- return await callSlackApi({
- body:
- input.current === undefined
- ? {
- channel: input.channelId,
- metadata: {
- event_payload: { root_turn_id: input.rootTurnId },
- event_type: "eve_progress",
- },
- text: input.text,
- thread_ts: input.threadTs,
- }
- : { channel: input.channelId, text: input.text, ts: input.current.ts },
- api: input.api,
- botToken: input.botToken,
- context: {
- teamId: typeof input.installationTeamId === "string" ? input.installationTeamId : undefined,
- },
- operation: input.current === undefined ? "chat.postMessage" : "chat.update",
- });
-}
-
-async function recoverActivityMessage(input: {
- readonly api: SlackTransportOptions | undefined;
- readonly botToken: SlackBotToken | undefined;
- readonly channelId: string;
- readonly installationTeamId: unknown;
- readonly rootTurnId: string;
- readonly threadTs: string;
-}): Promise<{ readonly text: string; readonly ts: string } | undefined> {
- let cursor: string | undefined;
- const seenCursors = new Set<string>();
- while (true) {
- const body: Record<string, unknown> = {
- channel: input.channelId,
- inclusive: true,
- limit: 100,
- ts: input.threadTs,
- };
- if (cursor !== undefined) body.cursor = cursor;
- const response = await callSlackApi({
- api: input.api,
- body,
- botToken: input.botToken,
- context: {
- teamId: typeof input.installationTeamId === "string" ? input.installationTeamId : undefined,
- },
- operation: "conversations.replies",
- });
- if (response.ok !== true || !Array.isArray(response.messages)) return undefined;
- for (const message of response.messages) {
- if (message === null || typeof message !== "object") continue;
- const metadata = Reflect.get(message, "metadata");
- const payload =
- metadata !== null && typeof metadata === "object"
- ? Reflect.get(metadata, "event_payload")
- : undefined;
- if (
- metadata !== null &&
- typeof metadata === "object" &&
- Reflect.get(metadata, "event_type") === "eve_progress" &&
- payload !== null &&
- typeof payload === "object" &&
- Reflect.get(payload, "root_turn_id") === input.rootTurnId
- ) {
- const ts = Reflect.get(message, "ts");
- const text = Reflect.get(message, "text");
- if (typeof ts === "string") return { text: typeof text === "string" ? text : "", ts };
- }
- }
- const responseMetadata = Reflect.get(response, "response_metadata");
- const nextCursor =
- responseMetadata !== null && typeof responseMetadata === "object"
- ? Reflect.get(responseMetadata, "next_cursor")
- : undefined;
- if (typeof nextCursor !== "string" || nextCursor === "" || seenCursors.has(nextCursor)) {
- return undefined;
- }
- seenCursors.add(nextCursor);
- cursor = nextCursor;
- }
-}
-
-export function activityMessages(snapshot: ActivitySnapshotV1): ReadonlyMap<string, string> {
- const grouped = new Map<string, ActivityWorkStateV1[]>();
- for (const work of Object.values(snapshot.work)) {
- const group = grouped.get(work.rootTurnId) ?? [];
- group.push(work);
- grouped.set(work.rootTurnId, group);
- }
- return new Map(
- [...grouped].map(([rootTurnId, work]) => [
- rootTurnId,
- renderWorkTree(
- work,
- Object.values(snapshot.actions).filter((action) => action.rootTurnId === rootTurnId),
- Object.values(snapshot.blockers).filter((blocker) => blocker.rootTurnId === rootTurnId),
- ),
- ]),
- );
-}
-
-function renderWorkTree(
- work: readonly ActivityWorkStateV1[],
- actions: readonly ActivityActionStateV1[],
- blockers: readonly ActivityBlockerStateV1[],
-): string {
- const byParent = new Map<string | undefined, ActivityWorkStateV1[]>();
- const ids = new Set(work.map((item) => item.id));
- for (const item of work) {
- const parentId =
- item.parentId !== undefined && ids.has(item.parentId) ? item.parentId : undefined;
- const children = byParent.get(parentId) ?? [];
- children.push(item);
- byParent.set(parentId, children);
- }
- const delegatedActionIds = new Set(
- work.flatMap((item) =>
- item.parentId !== undefined && item.callId !== undefined
- ? [`action:${item.parentId}:${item.callId}`]
- : [],
- ),
- );
- const actionsByParent = new Map<string, ActivityActionStateV1[]>();
- for (const action of actions) {
- if (action.kind === "tool" && delegatedActionIds.has(action.id)) continue;
- const siblings = actionsByParent.get(action.parentWorkId) ?? [];
- siblings.push(action);
- actionsByParent.set(action.parentWorkId, siblings);
- }
- const blockersByParent = new Map<string, ActivityBlockerStateV1[]>();
- for (const blocker of blockers) {
- const siblings = blockersByParent.get(blocker.parentWorkId) ?? [];
- siblings.push(blocker);
- blockersByParent.set(blocker.parentWorkId, siblings);
- }
- const lines: string[] = [];
- const append = (line: string): void => {
- if (lines.length < 20) lines.push(line);
- };
- const visit = (item: ActivityWorkStateV1, prefix: string, connector: string): void => {
- const label = item.kind === "root-turn" ? "Working" : (item.name ?? "Agent work");
- append(`${prefix}${connector}${phaseIcon(item.phase)} ${escapeSlackText(label)}`);
- const descendants = [
- ...(blockersByParent.get(item.id) ?? []).map((blocker) => ({ blocker })),
- ...(actionsByParent.get(item.id) ?? []).map((action) => ({ action })),
- ...(byParent.get(item.id) ?? []).map((child) => ({ child })),
- ];
- const childPrefix = `${prefix}${connector === "├── " ? "│ " : connector === "└── " ? " " : ""}`;
- descendants.forEach((descendant, index) => {
- const branch = index === descendants.length - 1 ? "└── " : "├── ";
- if ("blocker" in descendant)
- append(
- `${childPrefix}${branch}${blockerIcon(descendant.blocker.phase)} ${escapeSlackText(descendant.blocker.label ?? blockerLabel(descendant.blocker.kind))}`,
- );
- else if ("action" in descendant)
- append(
- `${childPrefix}${branch}${phaseIcon(descendant.action.phase)} ${escapeSlackText(descendant.action.label ?? descendant.action.name)}`,
- );
- else visit(descendant.child, childPrefix, branch);
- });
- };
- for (const root of byParent.get(undefined) ?? []) visit(root, "", "");
- return `\`\`\`\n${lines.join("\n")}\n\`\`\``;
-}
-
-function phaseIcon(phase: ActivityWorkStateV1["phase"] | ActivityActionStateV1["phase"]): string {
- switch (phase) {
- case "completed":
- return "✓";
- case "failed":
- case "rejected":
- return "✗";
- case "cancelled":
- return "⊘";
- case "running":
- return "•";
- }
-}
-
-function escapeSlackText(text: string): string {
- return text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
-}
-
-function isActivityState(value: unknown): value is SlackActivityMessageState {
- return (
- typeof value === "object" &&
- value !== null &&
- typeof Reflect.get(value, "messages") === "object"
- );
-}
-
-export function selectSlackActivityStatus(snapshot: ActivitySnapshotV1): string {
- const active = Object.values(snapshot.work).filter((work) => work.phase === "running");
- if (active.length === 0) return "";
- const blocker = newestBlocker(
- Object.values(snapshot.blockers).filter((candidate) => candidate.phase === "blocked"),
- );
- if (blocker !== undefined) return blockerLabel(blocker.kind);
- const action = newestAction(
- Object.values(snapshot.actions).filter((candidate) => candidate.phase === "running"),
- );
- if (action !== undefined) return truncateTypingStatus(action.label ?? action.name);
- const delegated = newestWork(active.filter((work) => work.kind !== "root-turn"));
- if (delegated !== undefined) return truncateTypingStatus(delegated.name ?? "Working with agent");
- return "Working…";
-}
-
-function blockerLabel(kind: ActivityBlockerStateV1["kind"]): string {
- switch (kind) {
- case "approval":
- return "Waiting for approval…";
- case "authorization":
- return "Waiting for sign-in…";
- case "input":
- return "Waiting for input…";
- }
-}
-
-function blockerIcon(phase: ActivityBlockerStateV1["phase"]): string {
- return phase === "blocked" ? "◌" : phase === "completed" ? "✓" : phase === "failed" ? "✗" : "–";
-}
-
-function newestBlocker(
- blockers: readonly ActivityBlockerStateV1[],
-): ActivityBlockerStateV1 | undefined {
- return blockers.reduce<ActivityBlockerStateV1 | undefined>(
- (newest, candidate) =>
- newest === undefined || candidate.startedAt >= newest.startedAt ? candidate : newest,
- undefined,
- );
-}
-
-function newestAction(
- actions: readonly ActivityActionStateV1[],
-): ActivityActionStateV1 | undefined {
- return actions.reduce<ActivityActionStateV1 | undefined>(
- (newest, candidate) =>
- newest === undefined || candidate.startedAt >= newest.startedAt ? candidate : newest,
- undefined,
- );
-}
-
-function newestWork(work: readonly ActivityWorkStateV1[]): ActivityWorkStateV1 | undefined {
- return work.reduce<ActivityWorkStateV1 | undefined>(
- (newest, candidate) =>
- newest === undefined || candidate.startedAt >= newest.startedAt ? candidate : newest,
- undefined,
- );
-}
-
-function isSlackStatusState(value: unknown): value is SlackActivityStatusState {
- return (
- typeof value === "object" && value !== null && typeof Reflect.get(value, "status") === "string"
- );
-}
diff --git a/packages/eve/src/public/channels/slack/defaults.ts b/packages/eve/src/public/channels/slack/defaults.ts
index d31744859..51be58abe 100644
--- a/packages/eve/src/public/channels/slack/defaults.ts
+++ b/packages/eve/src/public/channels/slack/defaults.ts
@@ -1,7 +1,8 @@
+import { workingTaskNames } from "#channel/task-card.js";
import type { SessionAuthContext } from "#channel/types.js";
import { createLogger, extractErrorId, formatErrorHint, logError } from "#internal/logging.js";
-import { describeActionRequests } from "#public/channels/slack/action-status.js";
+import { describeActionRequests, waitingOnTasks } from "#public/channels/slack/action-status.js";
import { isTaskControlTool } from "#protocol/task-tools.js";
import {
buildSlackAuthContext,
@@ -31,10 +32,10 @@ import {
} from "#public/channels/slack/limits.js";
import type {
SlackApprovalChannelResolver,
- SlackChannelEvents,
SlackChannelInternalEvents,
SlackChannelState,
SlackContext,
+ SlackEventContext,
SlackMentionResult,
} from "#public/channels/slack/slackChannel.js";
import type { InputRequest } from "#shared/input.js";
@@ -144,7 +145,7 @@ function blockContainsRequestAction(block: unknown, requestId: string): boolean
/**
* Workspace-scoped projection of the Slack actor that produced
* `message`, derived into a {@link SessionAuthContext}. Used by both
- * {@link defaultOnAppMention} and {@link defaultOnDirectMessage} when
+ * {@link defaultOnMessage} when
* the customer hasn't supplied their own `onAppMention` /
* `onDirectMessage`. Returns `null` when the message has no author.
*/
@@ -167,29 +168,17 @@ export function defaultSlackAuth(
}
/**
- * Default `onAppMention` — derives auth from the Slack actor and posts
- * a `"Thinking…"` typing indicator before the workflow runtime starts.
+ * Default `onAppMention` and `onDirectMessage`: dispatches with auth derived
+ * from the Slack actor. Acknowledging the message is the renderer chain's
+ * `received`, so replacing a message hook never drops it.
*/
-export async function defaultOnAppMention(
- ctx: SlackContext,
- message: SlackMessage,
-): Promise<SlackMentionResult> {
- await ctx.thread.startTyping("Thinking...");
+export function defaultOnMessage(ctx: SlackContext, message: SlackMessage): SlackMentionResult {
return { auth: defaultSlackAuth(message, ctx) };
}
-/**
- * Default `onDirectMessage` — derives auth from the Slack actor and
- * posts a `"Thinking…"` typing indicator before the workflow runtime
- * starts. Matches the default mention behavior; replace the option to
- * customize gating, auth derivation, or pre-dispatch side effects.
- */
-export async function defaultOnDirectMessage(
- ctx: SlackContext,
- message: SlackMessage,
-): Promise<SlackMentionResult> {
+/** eve's default `received`: the `Thinking...` status, set the moment a message arrives. */
+export async function defaultReceived(_message: SlackMessage, ctx: SlackContext): Promise<void> {
await ctx.thread.startTyping("Thinking...");
- return { auth: defaultSlackAuth(message, ctx) };
}
/**
@@ -210,8 +199,7 @@ function firstNonEmptyLine(text: string): string | undefined {
* request as Slack `block_actions`. Buttons by default; radio for
* ≤6-option select requests; static_select for >6-option select
* requests. Batches split into multiple posts when they would exceed
- * Slack's 50-block message cap. Override by declaring
- * `events["input.requested"]`.
+ * Slack's 50-block message cap.
*/
export function defaultInputRequestedHandler(
approvalChannel?: SlackApprovalChannelResolver,
@@ -259,7 +247,7 @@ export function defaultInputRequestedHandler(
async function postPublicInputRequests(
requests: readonly InputRequest[],
- channel: Parameters<NonNullable<SlackChannelEvents["input.requested"]>>[1],
+ channel: SlackEventContext,
): Promise<void> {
for (const post of buildInputRequestPosts(requests)) {
const message = await channel.thread.post({ blocks: post.blocks, text: post.text });
@@ -358,12 +346,11 @@ export async function postCompletedSlackReply(
}
/**
- * Built-in Slack event handlers — typing indicators, error replies,
- * and the connection-authorization status flow. Each is overridable
- * per-event by passing the same key under `slackChannel({ events })`.
- * Typed as the internal full-context map because the default
- * `authorization.required` handler owns the public link-free status,
- * which user overrides cannot express.
+ * eve's default Slack event rendering: status lines, replies, errors, and the
+ * connection-authorization flow. It is the innermost link of every channel's
+ * renderer chain. Typed as the internal full-context map because the default
+ * `authorization.required` handler owns the public link-free status, which
+ * authored renderers cannot express.
*/
export const defaultEvents: SlackChannelInternalEvents = {
async "approval.candidate"(event, channel, _ctx) {
@@ -422,6 +409,11 @@ export const defaultEvents: SlackChannelInternalEvents = {
channel.state.pendingApprovalCards = next;
},
+ async "turn.waiting"(event, channel, _ctx) {
+ const working = workingTaskNames(channel.state.taskCards?.[event.turnId]?.turn);
+ if (working.length > 0) await channel.thread.startTyping(waitingOnTasks(working));
+ },
+
async "turn.started"(_event, channel, _ctx) {
channel.state.pendingToolCallMessage = null;
channel.state.lastReasoningTypingAtMs = null;
diff --git a/packages/eve/src/public/channels/slack/index.ts b/packages/eve/src/public/channels/slack/index.ts
index f129439d7..7f5ad4965 100644
--- a/packages/eve/src/public/channels/slack/index.ts
+++ b/packages/eve/src/public/channels/slack/index.ts
@@ -10,12 +10,10 @@ export {
slackChannel,
type SlackApiResponse,
type SlackAuthorizationEventContext,
- type SlackAuthorizationRequiredHandler,
type SlackBotToken,
type SlackChannel,
type SlackChannelConfig,
type SlackChannelCredentials,
- type SlackChannelEvents,
type SlackChannelState,
type SlackContext,
type SlackEventContext,
@@ -29,9 +27,6 @@ export {
type SlackInboundResult,
type SlackInboundResultOrPromise,
type SlackInitialMessage,
- type SlackInputRequestedDefaultDeliver,
- type SlackInputRequestedEvent,
- type SlackInputRequestedHandler,
type SlackInputResponseContext,
type SlackInputResponseResult,
type SlackInputResponseSubmission,
@@ -81,15 +76,21 @@ export { type SlackFetch, type SlackTransportOptions } from "#public/channels/sl
export { defaultSlackAuth } from "#public/channels/slack/defaults.js";
export {
- experimental_slackActivityPlan,
- experimental_slackActivityRenderer,
- experimental_slackActivityTree,
- experimental_slackActivityStatus,
- type ExperimentalSlackActivityDestination,
- type ExperimentalSlackActivityRenderer,
- type ExperimentalSlackActivitySnapshot,
- type SlackActivityRenderer,
-} from "#public/channels/slack/activity.js";
+ defineSlackRenderer,
+ type SlackRenderer,
+ type SlackRendererEvents,
+ type SlackRenderHandler,
+ type SlackRenderNext,
+ type SlackTaskCard,
+} from "#public/channels/slack/renderers.js";
+
+export type {
+ TaskCardAction,
+ TaskCardBlocker,
+ TaskCardStatus,
+ TaskCardTask,
+ TaskCardView,
+} from "#channel/task-card.js";
export {
describeActionRequest,
diff --git a/packages/eve/src/public/channels/slack/renderers.ts b/packages/eve/src/public/channels/slack/renderers.ts
new file mode 100644
index 000000000..2f87919c5
--- /dev/null
+++ b/packages/eve/src/public/channels/slack/renderers.ts
@@ -0,0 +1,254 @@
+import type { TaskCardView } from "#channel/task-card.js";
+import type { SessionContext } from "#public/definitions/callback-context.js";
+import type { UnstampedMessageStreamEvent } from "#protocol/message.js";
+import type { BlockKitBlock } from "#public/channels/slack/blocks.js";
+import type { SlackMessage } from "#public/channels/slack/inbound.js";
+import type {
+ SlackAuthorizationEventContext,
+ SlackChannelInternalEvents,
+ SlackContext,
+ SlackEventContext,
+} from "#public/channels/slack/slackChannel.js";
+
+type EventData<T extends UnstampedMessageStreamEvent["type"]> =
+ Extract<UnstampedMessageStreamEvent, { type: T }> extends { data: infer D } ? D : undefined;
+
+/** The session events a Slack renderer can handle, in no particular order. */
+const SLACK_RENDERED_EVENTS = [
+ "action.partial",
+ "action.result",
+ "actions.requested",
+ "approval.candidate",
+ "approval.settled",
+ "authorization.completed",
+ "authorization.required",
+ "input.requested",
+ "input.resolved",
+ "message.appended",
+ "message.completed",
+ "reasoning.appended",
+ "reasoning.completed",
+ "session.completed",
+ "session.failed",
+ "session.waiting",
+ "task.settled",
+ "task.started",
+ "turn.cancelled",
+ "turn.completed",
+ "turn.failed",
+ "turn.started",
+ "turn.waiting",
+] as const;
+
+export type SlackRenderedEvent = (typeof SLACK_RENDERED_EVENTS)[number];
+type SlackSessionEvent = Exclude<SlackRenderedEvent, "authorization.required" | "session.failed">;
+
+/**
+ * Runs the rest of the chain, ending with eve's default. Pass changed data to
+ * hand it on instead of the event; the rest of the chain runs at most once.
+ * Await it, so the rest of the chain finishes before the event does.
+ */
+export type SlackRenderNext<T extends SlackRenderedEvent> = (data?: EventData<T>) => Promise<void>;
+
+/** Renders one session event, before, after, around, or instead of the rest of the chain. */
+export type SlackRenderHandler<T extends SlackSessionEvent> = (
+ data: EventData<T>,
+ channel: SlackEventContext,
+ ctx: SessionContext,
+ next: SlackRenderNext<T>,
+) => void | Promise<void>;
+
+/**
+ * Session event handlers of one {@link SlackRenderer}. `authorization.required`
+ * receives the private delivery surface, because the challenge is a
+ * credential; its `next` reaches eve's default, which posts the public,
+ * link-free status. `session.failed` has no session context.
+ */
+export type SlackRendererEvents = {
+ readonly [T in SlackSessionEvent]?: SlackRenderHandler<T>;
+} & {
+ readonly "authorization.required"?: (
+ data: EventData<"authorization.required">,
+ channel: SlackAuthorizationEventContext,
+ ctx: SessionContext,
+ next: SlackRenderNext<"authorization.required">,
+ ) => void | Promise<void>;
+ readonly "session.failed"?: (
+ data: EventData<"session.failed">,
+ channel: SlackEventContext,
+ next: SlackRenderNext<"session.failed">,
+ ) => void | Promise<void>;
+};
+
+/** The message eve posts for a turn's tasks: Block Kit blocks and notification text. */
+export interface SlackTaskCard {
+ readonly blocks: readonly BlockKitBlock[];
+ readonly text: string;
+}
+
+/**
+ * One link in a Slack channel's rendering chain. Every part is optional and
+ * wraps the renderers after it, ending with eve's default renderer.
+ */
+export interface SlackRenderer {
+ /**
+ * Acknowledges a mention or DM as soon as it arrives, while the message hook
+ * is still deciding, and another channel message once `onMessage`
+ * dispatches it. eve's default sets the `Thinking...` status. If the hook
+ * drops the message, eve clears the thread status.
+ */
+ readonly received?: (
+ message: SlackMessage,
+ channel: SlackContext,
+ next: () => Promise<void>,
+ ) => void | Promise<void>;
+ /** Handlers for session events, such as posting replies and questions. */
+ readonly events?: SlackRendererEvents;
+ /**
+ * Returns the message for a turn's task card, or `null` for none. Runs for
+ * every turn that calls a tool; the view carries the turn's tasks and its
+ * other tool calls with their input. Pure and synchronous: eve posts the
+ * card, updates it as the turn changes, and handles Slack's rate limits.
+ * `next` returns eve's default card, which is `null` for a turn without tasks.
+ */
+ readonly taskCard?: (
+ view: TaskCardView,
+ next: (view: TaskCardView) => SlackTaskCard | null,
+ ) => SlackTaskCard | null;
+}
+
+/** Types a Slack renderer. */
+export function defineSlackRenderer(renderer: SlackRenderer): SlackRenderer {
+ return renderer;
+}
+
+/**
+ * A complete chain, whose handlers take no `next`: eve's default renderer,
+ * which is the innermost link, and the composed chain a channel runs.
+ */
+export interface SlackRenderChain {
+ readonly events: SlackChannelInternalEvents;
+ readonly received: (message: SlackMessage, channel: SlackContext) => Promise<void>;
+ readonly taskCard: (view: TaskCardView) => SlackTaskCard | null;
+}
+
+type AnyHandler = (...args: unknown[]) => void | Promise<void>;
+
+export function composeSlackRenderers(
+ renderers: readonly SlackRenderer[],
+ defaults: SlackRenderChain,
+): SlackRenderChain {
+ return {
+ events: composeEvents(renderers, defaults.events),
+ received: (message, channel) => composeReceived(renderers, defaults, message, channel, 0),
+ taskCard: (view) => composeTaskCard(renderers, defaults, view, 0),
+ };
+}
+
+function composeEvents(
+ renderers: readonly SlackRenderer[],
+ defaults: SlackChannelInternalEvents,
+): SlackChannelInternalEvents {
+ const events: Record<string, AnyHandler> = {};
+ for (const type of SLACK_RENDERED_EVENTS) {
+ const fallback = defaults[type] as AnyHandler | undefined;
+ const handlers = renderers.flatMap((renderer) => {
+ const handler = renderer.events?.[type] as AnyHandler | undefined;
+ return handler === undefined ? [] : [handler];
+ });
+ if (handlers.length === 0 && fallback === undefined) continue;
+ events[type] =
+ type === "session.failed"
+ ? (data, channel) =>
+ runChain(
+ handlers,
+ data,
+ (handler, value, next) => handler(value, channel, next),
+ (value) => fallback?.(value, channel),
+ )
+ : (data, channel, ctx) =>
+ runChain(
+ handlers,
+ data,
+ (handler, value, next) =>
+ handler(value, userChannel(type, channel as SlackEventContext), ctx, next),
+ (value) => fallback?.(value, channel, ctx),
+ );
+ }
+ return events as SlackChannelInternalEvents;
+}
+
+/**
+ * Runs `handlers` in order around `last`. Each handler's `next` runs the rest
+ * once, with the data it passes or the data it received.
+ */
+async function runChain(
+ handlers: readonly AnyHandler[],
+ data: unknown,
+ invoke: (
+ handler: AnyHandler,
+ value: unknown,
+ next: (value?: unknown) => Promise<void>,
+ ) => unknown,
+ last: (value: unknown) => unknown,
+): Promise<void> {
+ const run = async (index: number, value: unknown): Promise<void> => {
+ if (index === handlers.length) {
+ await last(value);
+ return;
+ }
+ let ran: Promise<void> | undefined;
+ const next = (changed?: unknown): Promise<void> =>
+ (ran ??= run(index + 1, changed === undefined ? value : changed));
+ await invoke(handlers[index]!, value, next);
+ };
+ await run(0, data);
+}
+
+/** User renderers see only the private delivery surface for a sign-in challenge. */
+function userChannel(
+ type: SlackRenderedEvent,
+ channel: SlackEventContext,
+): SlackEventContext | SlackAuthorizationEventContext {
+ if (type !== "authorization.required") return channel;
+ return {
+ postDirectMessage: (userId, message) => channel.thread.postDirectMessage(userId, message),
+ postEphemeral: (userId, message) => channel.thread.postEphemeral(userId, message),
+ state: channel.state,
+ };
+}
+
+async function composeReceived(
+ renderers: readonly SlackRenderer[],
+ defaults: SlackRenderChain,
+ message: SlackMessage,
+ channel: SlackContext,
+ index: number,
+): Promise<void> {
+ if (index === renderers.length) {
+ await defaults.received(message, channel);
+ return;
+ }
+ const received = renderers[index]!.received;
+ if (received === undefined) {
+ await composeReceived(renderers, defaults, message, channel, index + 1);
+ return;
+ }
+ let ran: Promise<void> | undefined;
+ await received(message, channel, () => {
+ ran ??= composeReceived(renderers, defaults, message, channel, index + 1);
+ return ran;
+ });
+}
+
+function composeTaskCard(
+ renderers: readonly SlackRenderer[],
+ defaults: SlackRenderChain,
+ view: TaskCardView,
+ index: number,
+): SlackTaskCard | null {
+ if (index === renderers.length) return defaults.taskCard(view);
+ const taskCard = renderers[index]!.taskCard;
+ if (taskCard === undefined) return composeTaskCard(renderers, defaults, view, index + 1);
+ return taskCard(view, (next) => composeTaskCard(renderers, defaults, next, index + 1));
+}
diff --git a/packages/eve/src/public/channels/slack/slackChannel.test.ts b/packages/eve/src/public/channels/slack/slackChannel.test.ts
index a4f6c5ad9..0079f715f 100644
--- a/packages/eve/src/public/channels/slack/slackChannel.test.ts
+++ b/packages/eve/src/public/channels/slack/slackChannel.test.ts
@@ -20,7 +20,6 @@ import {
type ObservedChannelDelivery,
} from "#internal/testing/mocks/mock-channel-operations.js";
import type { UnstampedMessageStreamEvent } from "#protocol/message.js";
-import { experimental_slackActivityStatus } from "#public/channels/slack/activity.js";
import { decodeSlackApiBody } from "#internal/testing/slack-api-body.js";
import {
HITL_ACTION_PREFIX,
@@ -38,7 +37,11 @@ import {
} from "#public/channels/slack/limits.js";
import { defaultSlackAuth } from "#public/channels/slack/index.js";
import {
- constrainAuthorizationRequired,
+ composeSlackRenderers,
+ type SlackRenderChain,
+ type SlackRenderer,
+} from "#public/channels/slack/renderers.js";
+import {
slackChannel,
type SlackAuthorizationEventContext,
type SlackInboundEventContext,
@@ -71,9 +74,13 @@ function slackRespondTypeChecks(
void slackRespondTypeChecks;
slackChannel({
- events: {
- "input.requested"(_event, _channel, _ctx) {},
- },
+ renderers: [
+ {
+ events: {
+ "input.requested"(_event, _channel, _ctx, _next) {},
+ },
+ },
+ ],
});
function getAdapter(channel: unknown): ChannelAdapter<any> {
@@ -122,6 +129,13 @@ function slackOperations(fetchMock: ReturnType<typeof vi.fn>): string[] {
});
}
+// The thread statuses set through `assistant.threads.setStatus`, in order.
+function slackStatuses(fetchMock: ReturnType<typeof vi.fn>): unknown[] {
+ return slackCalls(fetchMock, "assistant.threads.setStatus").map(
+ ([, init]) => parseSlackRequestBody(init).status,
+ );
+}
+
// A response from a gateway in front of Slack: a received non-2xx whose
// body is an HTML error page rather than a Slack JSON envelope.
function htmlGatewayError(): Response {
@@ -681,36 +695,95 @@ describe("slackChannel() default event handlers", () => {
expect(fetchMock).toHaveBeenCalledTimes(method === "files.getUploadURLExternal" ? 1 : 3);
});
- it("activity-owned message.completed uses the same oversized reply snippet", async () => {
- const uploadedBodies = useSuccessfulSlackFileUpload(fetchMock);
+ it("names the working tasks in the status while a turn waits on them", async () => {
+ const adapter = withState(
+ getAdapter(slackChannel({ credentials: { botToken: "xoxb-test" } })),
+ THREAD_STATE,
+ );
+ const ctx = buildAdapterContext(adapter, stubAccessor());
+ const taskStarted = (callId: string, name: string) =>
+ makeEvent("task.started", { callId, kind: "agent", name, taskId: `${name}-1`, turnId: "t1" });
+ const waiting = makeEvent("turn.waiting", { sequence: 1, turnId: "t1" });
+
+ await callEvent(adapter, taskStarted("c1", "researcher"), ctx);
+ await callEvent(adapter, taskStarted("c2", "reviewer"), ctx);
+ await callEvent(adapter, taskStarted("c3", "deploy"), ctx);
+ await callEvent(adapter, waiting, ctx);
+ await callEvent(
+ adapter,
+ makeEvent("task.settled", {
+ callId: "c1",
+ status: "completed",
+ taskId: "researcher-1",
+ turnId: "t1",
+ }),
+ ctx,
+ );
+ await callEvent(
+ adapter,
+ makeEvent("task.settled", {
+ callId: "c3",
+ status: "cancelled",
+ taskId: "deploy-1",
+ turnId: "t1",
+ }),
+ ctx,
+ );
+ await callEvent(adapter, waiting, ctx);
+
+ expect(slackStatuses(fetchMock)).toEqual([
+ "Waiting on researcher and 2 more tasks...",
+ "Waiting on reviewer...",
+ ]);
+ });
+
+ it("forgets a failed turn's tasks even when a renderer replaces its failure reply", async () => {
const adapter = withState(
getAdapter(
slackChannel({
- activity: { renderers: [experimental_slackActivityStatus()] },
credentials: { botToken: "xoxb-test" },
+ renderers: [{ events: { async "turn.failed"() {} } }],
}),
),
THREAD_STATE,
);
const ctx = buildAdapterContext(adapter, stubAccessor());
- const message = "x".repeat(SLACK_MARKDOWN_TEXT_MAX_LENGTH + 1);
await callEvent(
adapter,
- makeEvent("message.completed", {
- finishReason: "stop",
- message,
- sequence: 0,
- stepIndex: 0,
+ makeEvent("task.started", {
+ callId: "c1",
+ kind: "agent",
+ name: "researcher",
+ taskId: "researcher-1",
turnId: "t1",
}),
ctx,
);
-
- expect(uploadedBodies).toEqual([message]);
- expect(fetchMock.mock.calls.map(([input]) => String(input))).not.toContain(
- "https://slack.com/api/chat.postMessage",
+ await callEvent(
+ adapter,
+ makeEvent("turn.failed", {
+ code: "MODEL_CALL_FAILED",
+ message: "x",
+ sequence: 1,
+ turnId: "t1",
+ }),
+ ctx,
);
+ await callEvent(
+ adapter,
+ makeEvent("task.started", {
+ callId: "c2",
+ kind: "agent",
+ name: "reviewer",
+ taskId: "reviewer-1",
+ turnId: "t2",
+ }),
+ ctx,
+ );
+ await callEvent(adapter, makeEvent("turn.waiting", { sequence: 1, turnId: "t2" }), ctx);
+
+ expect(slackStatuses(fetchMock)).toEqual(["Waiting on reviewer..."]);
});
it("message.completed skips post when finishReason is tool-calls", async () => {
@@ -848,19 +921,23 @@ describe("slackChannel() default event handlers", () => {
approvalChannel: (request) =>
request.prompt.startsWith("Sensitive") ? "direct-message" : "thread",
credentials: { botToken: "xoxb-test" },
- events: {
- async "input.requested"(event, _channel, _ctx, defaultDeliver) {
- const privateRequests = event.requests.filter((request) =>
- request.prompt.startsWith("Sensitive"),
- );
- customPrompts.push(
- ...event.requests
- .filter((request) => !privateRequests.includes(request))
- .map((request) => request.prompt),
- );
- await defaultDeliver({ ...event, requests: privateRequests });
+ renderers: [
+ {
+ events: {
+ async "input.requested"(event, _channel, _ctx, next) {
+ const privateRequests = event.requests.filter((request) =>
+ request.prompt.startsWith("Sensitive"),
+ );
+ customPrompts.push(
+ ...event.requests
+ .filter((request) => !privateRequests.includes(request))
+ .map((request) => request.prompt),
+ );
+ await next({ ...event, requests: privateRequests });
+ },
+ },
},
- },
+ ],
}),
),
{
@@ -1267,7 +1344,7 @@ describe("slackChannel() default event handlers", () => {
const adapter = withState(
getAdapter(
slackChannel({
- events: { "turn.started": onTurnStarted },
+ renderers: [{ events: { "turn.started": onTurnStarted } }],
}),
),
{ ...THREAD_STATE, triggeringUserId: "U_FIRST" },
@@ -2033,10 +2110,8 @@ describe("slackChannel() inbound mention pipeline", () => {
});
it("exposes private conversation detection to message handlers", async () => {
- fetchMock.mockResolvedValue(
- new Response(JSON.stringify({ ok: true, channel: { is_private: false } }), {
- headers: { "content-type": "application/json" },
- }),
+ fetchMock.mockImplementation(async () =>
+ Response.json({ ok: true, channel: { is_private: false } }),
);
let isPrivate: boolean | undefined;
const channel = slackChannel({
@@ -2051,11 +2126,9 @@ describe("slackChannel() inbound mention pipeline", () => {
await firePost(channel, buildSignedRequest({ body }));
expect(isPrivate).toBe(false);
- expect(fetchMock).toHaveBeenCalledTimes(1);
- expect(String(fetchMock.mock.calls[0]![0])).toContain("conversations.info");
- expect(parseSlackRequestBody(fetchMock.mock.calls[0]![1] as RequestInit)).toEqual({
- channel: "C_PUBLIC",
- });
+ const lookups = slackCalls(fetchMock, "conversations.info");
+ expect(lookups).toHaveLength(1);
+ expect(parseSlackRequestBody(lookups[0]![1])).toEqual({ channel: "C_PUBLIC" });
});
it("binds onAppMention to flat session operations", async () => {
@@ -2525,17 +2598,68 @@ describe("slackChannel() inbound mention pipeline", () => {
expect(send).toHaveBeenCalledTimes(1);
});
- it("default onAppMention posts a 'Thinking...' typing indicator", async () => {
- const channel = slackChannel({ credentials: { botToken: "xoxb-test" } });
+ it("acknowledges a mention while an authored onAppMention is still deciding", async () => {
+ const deciding = Promise.withResolvers<{ auth: null }>();
+ let statusesWhileDeciding: unknown[] = [];
+ const channel = slackChannel({
+ credentials: { botToken: "xoxb-test" },
+ async onAppMention() {
+ await vi.waitFor(() =>
+ expect(slackCalls(fetchMock, "assistant.threads.setStatus")).toHaveLength(1),
+ );
+ statusesWhileDeciding = slackStatuses(fetchMock);
+ return await deciding.promise;
+ },
+ });
const { body } = buildMentionBody();
+ const fired = firePost(channel, buildSignedRequest({ body }));
+ await vi.waitFor(() => expect(statusesWhileDeciding).toEqual(["Thinking..."]));
+
+ deciding.resolve({ auth: null });
+ const { send } = await fired;
+
+ expect(send).toHaveBeenCalledOnce();
+ expect(slackStatuses(fetchMock)).toEqual(["Thinking..."]);
+ });
+
+ it("clears the acknowledgement when the message hook drops the mention", async () => {
+ const channel = slackChannel({
+ credentials: { botToken: "xoxb-test" },
+ onAppMention: () => null,
+ });
+ const { body } = buildMentionBody();
+
+ const { send } = await firePost(channel, buildSignedRequest({ body }));
+
+ expect(send).not.toHaveBeenCalled();
+ expect(slackStatuses(fetchMock)).toEqual(["Thinking...", ""]);
+ });
+
+ it("runs a renderer's received around eve's acknowledgement", async () => {
+ const channel = slackChannel({
+ credentials: { botToken: "xoxb-test" },
+ renderers: [
+ {
+ async received(message, ctx, next) {
+ await ctx.slack.request("reactions.add", {
+ channel: message.channelId,
+ name: "eyes",
+ timestamp: message.ts,
+ });
+ await next();
+ },
+ },
+ ],
+ });
+ const { body } = buildMentionBody();
+
await firePost(channel, buildSignedRequest({ body }));
- const typingCall = fetchMock.mock.calls.find((call) =>
- String(call[0]).includes("assistant.threads.setStatus"),
- );
- expect(typingCall).toBeDefined();
- const sent = parseSlackRequestBody(typingCall![1] as RequestInit);
- expect(sent.status).toBe("Thinking...");
+ expect(slackOperations(fetchMock).slice(0, 2)).toEqual([
+ "reactions.add",
+ "assistant.threads.setStatus",
+ ]);
+ expect(slackStatuses(fetchMock)).toEqual(["Thinking..."]);
});
it("returns 200 OK without dispatching for non-app_mention events", async () => {
@@ -4882,73 +5006,132 @@ describe("slackChannel().receive", () => {
});
});
-describe("constrainAuthorizationRequired", () => {
- function buildFullContext() {
- const postEphemeral = vi.fn().mockResolvedValue({ id: "eph1" });
- const postDirectMessage = vi.fn().mockResolvedValue({ id: "dm1" });
- const post = vi.fn().mockResolvedValue({ id: "ts1" });
- const request = vi.fn().mockResolvedValue({ ok: true });
- const state: SlackChannelState = {
- channelId: "C123",
- threadTs: "111.222",
- teamId: null,
- triggeringUserId: "U777",
- };
- const channel = {
- thread: { postEphemeral, postDirectMessage, post } as Partial<SlackEventContext["thread"]>,
- slack: { channelId: "C123", request } as Partial<SlackEventContext["slack"]>,
- state,
- } as SlackEventContext;
- return { channel, post, postDirectMessage, postEphemeral, request, state };
+describe("Slack renderer chain", () => {
+ function chainWith(
+ renderers: readonly SlackRenderer[],
+ defaults: Partial<SlackRenderChain["events"]>,
+ ) {
+ return composeSlackRenderers(renderers, {
+ events: defaults,
+ received: vi.fn(),
+ taskCard: () => null,
+ });
}
- const eventData = {
- authorization: { url: "https://connect.example.com/a/sca_1", userCode: "AAA-BBB" },
- description: "Authorization required for notion",
- name: "notion",
+ const channel = {
+ slack: {} as SlackEventContext["slack"],
+ state: { channelId: "C01", teamId: "T01", threadTs: "1.0", triggeringUserId: "U777" },
+ thread: {
+ postDirectMessage: vi.fn(),
+ postEphemeral: vi.fn(),
+ post: vi.fn(),
+ } as Partial<SlackEventContext["thread"]> as SlackEventContext["thread"],
+ } satisfies SlackEventContext;
+ const completed = {
+ finishReason: "stop" as const,
+ message: "Deployed.",
sequence: 0,
stepIndex: 0,
- turnId: "turn_0",
+ turnId: "t1",
};
- it("hands the override only the private-delivery surface", async () => {
- const { channel } = buildFullContext();
- let received: SlackAuthorizationEventContext | undefined;
- const constrained = constrainAuthorizationRequired((_data, authCtx) => {
- received = authCtx;
+ it("runs renderers outermost first and hands changed data inward to eve's default", async () => {
+ const order: string[] = [];
+ const posted = vi.fn(async (data: { readonly message?: string }) => {
+ order.push(`default:${data.message ?? ""}`);
});
+ const chain = chainWith(
+ [
+ {
+ events: {
+ async "message.completed"(data, _channel, _ctx, next) {
+ order.push("outer");
+ await next({ ...data, message: `${data.message ?? ""} [outer]` });
+ order.push("outer:after");
+ },
+ },
+ },
+ {
+ events: {
+ async "message.completed"(data, _channel, _ctx, next) {
+ order.push("inner");
+ await next({ ...data, message: `${data.message ?? ""} [inner]` });
+ },
+ },
+ },
+ ],
+ { "message.completed": posted },
+ );
- await constrained(eventData, channel, {} as SessionContext);
+ await chain.events["message.completed"]!(completed, channel, {} as SessionContext);
- expect(received).toBeDefined();
- expect(Object.keys(received!).sort()).toEqual(["postDirectMessage", "postEphemeral", "state"]);
- expect("thread" in received!).toBe(false);
- expect("slack" in received!).toBe(false);
- expect(received!.state.triggeringUserId).toBe("U777");
+ expect(order).toEqual(["outer", "inner", "default:Deployed. [outer] [inner]", "outer:after"]);
});
- it("delegates private delivery to the underlying thread", async () => {
- const { channel, postDirectMessage, postEphemeral } = buildFullContext();
- const constrained = constrainAuthorizationRequired(async (_data, authCtx) => {
- await authCtx.postEphemeral("U777", "psst");
- await authCtx.postDirectMessage("U777", "psst dm");
+ it("skips eve's default when a handler does not call next", async () => {
+ const posted = vi.fn();
+ const replaced = vi.fn();
+ const chain = chainWith([{ events: { "message.completed": replaced } }], {
+ "message.completed": posted,
});
- await constrained(eventData, channel, {} as SessionContext);
+ await chain.events["message.completed"]!(completed, channel, {} as SessionContext);
- expect(postEphemeral).toHaveBeenCalledWith("U777", "psst");
- expect(postDirectMessage).toHaveBeenCalledWith("U777", "psst dm");
+ expect(replaced).toHaveBeenCalledOnce();
+ expect(posted).not.toHaveBeenCalled();
});
- it("threads the event data and session context through unchanged", async () => {
- const { channel } = buildFullContext();
- const sessionCtx = {} as SessionContext;
- const handler = vi.fn();
+ it("runs the rest of the chain once however often next is called", async () => {
+ const posted = vi.fn();
+ const chain = chainWith(
+ [
+ {
+ events: {
+ async "message.completed"(_data, _channel, _ctx, next) {
+ await Promise.all([next(), next()]);
+ await next();
+ },
+ },
+ },
+ ],
+ { "message.completed": posted },
+ );
+
+ await chain.events["message.completed"]!(completed, channel, {} as SessionContext);
+
+ expect(posted).toHaveBeenCalledOnce();
+ });
+
+ it("gives a sign-in handler only private delivery while eve's default keeps the thread", async () => {
+ let authored: SlackAuthorizationEventContext | undefined;
+ const publicStatus = vi.fn();
+ const chain = chainWith(
+ [
+ {
+ events: {
+ async "authorization.required"(_data, authCtx, _ctx, next) {
+ authored = authCtx;
+ await authCtx.postEphemeral("U777", "Sign in privately");
+ await next();
+ },
+ },
+ },
+ ],
+ { "authorization.required": publicStatus },
+ );
+ const challenge = {
+ authorization: { url: "https://connect.example.com/a/sca_1" },
+ description: "Authorization required for notion",
+ name: "notion",
+ sequence: 0,
+ stepIndex: 0,
+ turnId: "turn_0",
+ };
- await constrainAuthorizationRequired(handler)(eventData, channel, sessionCtx);
+ await chain.events["authorization.required"]!(challenge, channel, {} as SessionContext);
- expect(handler).toHaveBeenCalledTimes(1);
- expect(handler.mock.calls[0]?.[0]).toBe(eventData);
- expect(handler.mock.calls[0]?.[2]).toBe(sessionCtx);
+ expect(Object.keys(authored!).sort()).toEqual(["postDirectMessage", "postEphemeral", "state"]);
+ expect(channel.thread.postEphemeral).toHaveBeenCalledWith("U777", "Sign in privately");
+ expect(publicStatus).toHaveBeenCalledWith(challenge, channel, {});
});
});
diff --git a/packages/eve/src/public/channels/slack/slackChannel.ts b/packages/eve/src/public/channels/slack/slackChannel.ts
index df32ae050..81adfabe0 100644
--- a/packages/eve/src/public/channels/slack/slackChannel.ts
+++ b/packages/eve/src/public/channels/slack/slackChannel.ts
@@ -9,7 +9,7 @@ import type {
} from "#channel/channel-operations.js";
import { defaultDeliverResult } from "#channel/adapter.js";
import type { Session, SessionHandle } from "#channel/session.js";
-import { setChannelActivityRenderers, setChannelBuildMetadata } from "#channel/compiled-channel.js";
+import { setChannelBuildMetadata } from "#channel/compiled-channel.js";
import type { DeliverPayload, SessionAuthContext, TurnPolicy } from "#channel/types.js";
import type { VercelConnectMetadata } from "#shared/vercel-connect-metadata.js";
import type { CardElement } from "#compiled/chat/index.js";
@@ -45,10 +45,20 @@ import {
import {
defaultEvents,
defaultInputRequestedHandler,
- defaultOnAppMention,
- defaultOnDirectMessage,
- postCompletedSlackReply,
+ defaultOnMessage,
+ defaultReceived,
} from "#public/channels/slack/defaults.js";
+import {
+ composeSlackRenderers,
+ type SlackRenderChain,
+ type SlackRenderedEvent,
+ type SlackRenderer,
+} from "#public/channels/slack/renderers.js";
+import {
+ renderDefaultSlackTaskCard,
+ type SlackTaskCardState,
+ withTaskCards,
+} from "#public/channels/slack/task-card.js";
import {
parseMessageEvent,
type SlackEvent,
@@ -90,11 +100,6 @@ import { verifySlackRequest, type SlackWebhookVerifier } from "#public/channels/
import { defineChannel, POST, type Channel } from "#public/definitions/channel.js";
import { normalizeChannelAudience, type ChannelAudience } from "#shared/channel-audience.js";
import { markEventHandled } from "./utils.js";
-import {
- buildSlackActivityRenderers,
- hasSlackActivityStatus,
- type SlackActivityRenderer,
-} from "#public/channels/slack/activity.js";
export type {
SlackRespondOptions,
@@ -153,20 +158,8 @@ type SlackEventHandler<T extends UnstampedMessageStreamEvent["type"]> = (
ctx: SessionContext,
) => void | Promise<void>;
-export type SlackInputRequestedEvent = EventData<"input.requested">;
-
-/** Bound access to eve's standard Slack input delivery. */
-export type SlackInputRequestedDefaultDeliver = (data: SlackInputRequestedEvent) => Promise<void>;
-
-export type SlackInputRequestedHandler = (
- data: SlackInputRequestedEvent,
- channel: SlackEventContext,
- ctx: SessionContext,
- defaultDeliver: SlackInputRequestedDefaultDeliver,
-) => void | Promise<void>;
-
/**
- * Delivery surface handed to `authorization.required` overrides. The
+ * Delivery surface handed to a renderer's `authorization.required` handler. The
* connection challenge is a credential: anyone who completes the sign-in
* binds their identity to this session's connection. So the only
* delivery capabilities here are private ones, an ephemeral reply in the
@@ -193,18 +186,6 @@ export interface SlackAuthorizationEventContext {
readonly state: SlackChannelState;
}
-/**
- * Signature of an `authorization.required` override. Unlike every other
- * event handler, it receives {@link SlackAuthorizationEventContext}
- * instead of the full {@link SlackEventContext} — see the context type
- * for why.
- */
-export type SlackAuthorizationRequiredHandler = (
- data: EventData<"authorization.required">,
- channel: SlackAuthorizationEventContext,
- ctx: SessionContext,
-) => void | Promise<void>;
-
type SlackSessionFailedHandler = (
data: EventData<"session.failed">,
channel: SlackEventContext,
@@ -265,6 +246,11 @@ export interface SlackChannelState {
*/
pendingAuthMessageTs?: Record<string, string>;
pendingApprovalCards?: Record<string, SlackPendingApprovalCard>;
+ /**
+ * Each recent turn's tool calls and the task card eve last wrote for it, by
+ * turn id. The default `turn.waiting` handler names the working tasks.
+ */
+ taskCards?: Record<string, SlackTaskCardState> | null;
/**
* Principal id to Slack user id, recorded as each message or input response
* is delivered. Default handlers use it to address the principal named on
@@ -588,60 +574,16 @@ export type SlackInboundResult = SlackMentionResult;
export type SlackInboundResultOrPromise = SlackMentionResultOrPromise;
/**
- * Per-event Slack handlers keyed by harness stream-event type, passed to
- * `slackChannel({ events })`. Each key is optional; supplying one replaces
- * only that event's built-in default (see {@link defaultEvents}). Handlers
- * receive the event data, the {@link SlackEventContext}, and the session
- * {@link SessionContext}; `session.failed` receives only data and channel
- * context and exposes the ID as `data.sessionId`.
+ * eve's full-context Slack event handlers: the innermost link of every
+ * channel's renderer chain. The default `authorization.required` handler keeps
+ * the full {@link SlackEventContext} because it owns the public link-free
+ * status, which authored renderers, limited to private delivery, can't post.
*/
-export interface SlackChannelEvents {
- readonly "approval.candidate"?: SlackEventHandler<"approval.candidate">;
- readonly "approval.settled"?: SlackEventHandler<"approval.settled">;
- readonly "turn.started"?: SlackEventHandler<"turn.started">;
- readonly "actions.requested"?: SlackEventHandler<"actions.requested">;
- readonly "action.partial"?: SlackEventHandler<"action.partial">;
- readonly "action.result"?: SlackEventHandler<"action.result">;
- readonly "message.completed"?: SlackEventHandler<"message.completed">;
- readonly "message.appended"?: SlackEventHandler<"message.appended">;
- readonly "reasoning.appended"?: SlackEventHandler<"reasoning.appended">;
- readonly "reasoning.completed"?: SlackEventHandler<"reasoning.completed">;
- /**
- * An override may pass selected requests to `defaultDeliver()` while
- * rendering the rest itself. The default delivery honors `approvalChannel`.
- */
- readonly "input.requested"?: SlackInputRequestedHandler;
- readonly "turn.failed"?: SlackEventHandler<"turn.failed">;
- readonly "turn.completed"?: SlackEventHandler<"turn.completed">;
- readonly "turn.cancelled"?: SlackEventHandler<"turn.cancelled">;
+export type SlackChannelInternalEvents = {
+ readonly [T in Exclude<SlackRenderedEvent, "session.failed">]?: SlackEventHandler<T>;
+} & {
readonly "session.failed"?: SlackSessionFailedHandler;
- readonly "session.completed"?: SlackEventHandler<"session.completed">;
- readonly "session.waiting"?: SlackEventHandler<"session.waiting">;
- /**
- * Override receives {@link SlackAuthorizationEventContext}, a
- * private-delivery context (ephemeral or DM), not the full
- * {@link SlackEventContext}. The challenge is a credential, so a
- * public post is not expressible here.
- */
- readonly "authorization.required"?: SlackAuthorizationRequiredHandler;
- readonly "authorization.completed"?: SlackEventHandler<"authorization.completed">;
-}
-
-/**
- * Full-context variant of {@link SlackChannelEvents} consumed by the
- * channel internals. The framework's default `authorization.required`
- * handler keeps the full {@link SlackEventContext} because it owns the
- * public link-free status while user overrides remain private-only. The
- * factory adapts user overrides into this shape with
- * {@link constrainAuthorizationRequired}.
- */
-export interface SlackChannelInternalEvents extends Omit<
- SlackChannelEvents,
- "authorization.required" | "input.requested"
-> {
- readonly "authorization.required"?: SlackEventHandler<"authorization.required">;
- readonly "input.requested"?: SlackEventHandler<"input.requested">;
-}
+};
export type SlackApprovalChannel = "direct-message" | "thread";
@@ -667,11 +609,6 @@ export interface SlackChannelConfig {
*/
readonly approvalChannel?: SlackApprovalChannelResolver;
- /** Optional presentation-only activity rendered without starting parent turns. */
- readonly activity?: {
- readonly renderers: readonly SlackActivityRenderer[];
- };
-
/** Override the default webhook route path (`/eve/v1/slack`). */
readonly route?: string;
/** Policy for accepted messages that arrive while a turn is active. */
@@ -704,16 +641,13 @@ export interface SlackChannelConfig {
/**
* Invoked when a Slack `app_mention` event arrives (only `app_mention`;
* other event types are ignored). Decides whether to dispatch and with
- * what auth, and may run pre-dispatch side effects (e.g.
- * `ctx.thread.startTyping("Thinking...")`) on the inbound webhook side
- * before the runtime cold-starts.
+ * what auth. It renders nothing: the renderer chain's `received`
+ * acknowledges the mention while this hook runs.
*
* Return `{ auth }` to dispatch with that session auth context, or `null`
* to drop the mention. May be sync or async; the result is awaited before
* dispatching. Thrown errors are caught and logged and the mention is
- * dropped; wrap best-effort side effects in `try/catch` to keep them
- * non-fatal. Defaults to a workspace-scoped auth derivation that posts a
- * `"Thinking..."` typing indicator; replacing this replaces both.
+ * dropped. Defaults to a workspace-scoped auth derivation.
*/
onAppMention?(
ctx: SlackInboundMessageContext,
@@ -725,15 +659,13 @@ export interface SlackChannelConfig {
* `channel_type: "im"`. Subtype messages (edits, deletes, joins, etc.)
* and bot messages (`bot_id` set, including the bot's own replies) are
* filtered out first, so handlers only see plain user-authored DMs.
- * Decides whether to dispatch and with what auth, and may run
- * pre-dispatch side effects on the inbound webhook side before cold-start.
+ * Decides whether to dispatch and with what auth. It renders nothing: the
+ * renderer chain's `received` acknowledges the message while this hook runs.
*
* Return `{ auth }` to dispatch with that session auth context, or `null`
* to drop the message. May be sync or async; the result is awaited before
* dispatching. Thrown errors are caught and logged and the message is
- * dropped; wrap best-effort side effects in `try/catch` to keep them
- * non-fatal. Defaults to a workspace-scoped auth derivation that posts a
- * `"Thinking..."` typing indicator; replacing this replaces both.
+ * dropped. Defaults to a workspace-scoped auth derivation.
* Requires the bot's Slack app to subscribe to `message.im` with the
* `im:history` scope.
*/
@@ -816,30 +748,16 @@ export interface SlackChannelConfig {
submission: SlackInputResponseSubmission,
): SlackInputResponseResult | Promise<SlackInputResponseResult>;
- readonly events?: SlackChannelEvents;
+ /**
+ * Renderers that wrap eve's default Slack rendering, outermost first. Omit
+ * it and eve renders with its default alone. Each renderer can acknowledge
+ * messages (`received`), render session events (`events`), and shape the
+ * task card (`taskCard`). A handler runs the rest of the chain, ending with
+ * eve's default, by calling `next`, and skips it by not calling it.
+ */
+ readonly renderers?: readonly SlackRenderer[];
}
-const ignoreSlackActivityEvent = async (): Promise<void> => undefined;
-
-const activityOwnedMessageCompleted: NonNullable<SlackChannelEvents["message.completed"]> = async (
- event,
- channel,
-) => {
- channel.state.pendingToolCallMessage = null;
- if (event.finishReason !== "tool-calls" && event.message) {
- await postCompletedSlackReply(channel, event.message);
- }
-};
-
-const clearSlackTurnState: NonNullable<SlackChannelEvents["turn.started"]> = async (
- _data,
- channel,
-) => {
- channel.state.pendingToolCallMessage = null;
- channel.state.lastReasoningTypingAtMs = null;
- channel.state.lastReasoningTypingStatus = null;
-};
-
function rebuildSlackContext(
state: SlackChannelState,
session: SessionHandle,
@@ -875,14 +793,12 @@ export interface SlackChannel extends Channel<
> {}
/**
- * Slack channel factory. Wires up the webhook route, mention dispatch,
- * interaction handling, and a baseline set of typing / error /
- * connection-auth event handlers. Defaults apply per field: pass
- * `onAppMention` to fully replace the default mention pipeline (auth
- * derivation plus `"Thinking..."` typing), or an `events[type]` handler to
- * replace only that one event. When `onEvent` is authored it becomes the
- * fallback ahead of unsupplied mention and DM defaults; otherwise unsupplied
- * fields keep their defaults.
+ * Slack channel factory. Wires up the webhook route, message dispatch,
+ * interaction handling, and eve's default rendering: the `Thinking...`
+ * acknowledgement, status lines, replies, questions, sign-ins, errors, and a
+ * live task card for each turn that starts tasks. Message hooks decide whether
+ * and how to dispatch; `renderers` wrap the default rendering without
+ * replacing it.
*/
export function slackChannel(config: SlackChannelConfig = {}): SlackChannel {
const api = resolveSlackTransportOptions(config.api);
@@ -891,56 +807,29 @@ export function slackChannel(config: SlackChannelConfig = {}): SlackChannel {
api,
botToken: config.credentials?.botToken,
});
- const activityRenderers = buildSlackActivityRenderers({
- api,
- botToken: config.credentials?.botToken,
- renderers: config.activity?.renderers ?? [],
- });
const onInputResponse = config.onInputResponse ?? defaultOnInputResponse;
- const authorizationRequiredOverride = config.events?.["authorization.required"];
- const activityOwnsTypingStatus = hasSlackActivityStatus(config.activity?.renderers);
- const turnStartedHandler =
- config.events?.["turn.started"] ??
- (activityOwnsTypingStatus ? clearSlackTurnState : defaultEvents["turn.started"]!);
- const reasoningHandler =
- config.events?.["reasoning.appended"] ??
- (activityOwnsTypingStatus ? ignoreSlackActivityEvent : defaultEvents["reasoning.appended"]!);
- const actionsHandler =
- config.events?.["actions.requested"] ??
- (activityOwnsTypingStatus ? ignoreSlackActivityEvent : defaultEvents["actions.requested"]!);
- const messageCompletedHandler =
- config.events?.["message.completed"] ??
- (activityOwnsTypingStatus
- ? activityOwnedMessageCompleted
- : defaultEvents["message.completed"]!);
- const defaultInputRequested = defaultInputRequestedHandler(config.approvalChannel);
- const inputRequestedOverride = config.events?.["input.requested"];
- const inputRequestedHandler =
- inputRequestedOverride === undefined
- ? defaultInputRequested
- : async (data: SlackInputRequestedEvent, channel: SlackEventContext, ctx: SessionContext) =>
- inputRequestedOverride(data, channel, ctx, async (nextData) => {
- await defaultInputRequested(nextData, channel, ctx);
- });
- const mergedEvents: SlackChannelInternalEvents = {
- ...defaultEvents,
- ...config.events,
- async "turn.started"(data, channel, ctx) {
- const triggeringUserId = slackUserIdFromAuthContext(ctx.session.auth.current);
- if (triggeringUserId !== undefined) {
- channel.state.triggeringUserId = triggeringUserId;
- }
- await turnStartedHandler(data, channel, ctx);
+ const rendering = composeSlackRenderers(config.renderers ?? [], {
+ events: {
+ ...defaultEvents,
+ "input.requested": defaultInputRequestedHandler(config.approvalChannel),
},
- "reasoning.appended": reasoningHandler,
- "actions.requested": actionsHandler,
- "message.completed": messageCompletedHandler,
- "input.requested": inputRequestedHandler,
- "authorization.required":
- authorizationRequiredOverride === undefined
- ? defaultEvents["authorization.required"]
- : constrainAuthorizationRequired(authorizationRequiredOverride),
- };
+ received: defaultReceived,
+ taskCard: renderDefaultSlackTaskCard,
+ });
+ const renderTurnStarted = rendering.events["turn.started"];
+ const events = withTaskCards(
+ {
+ ...rendering.events,
+ async "turn.started"(data, channel, ctx) {
+ const triggeringUserId = slackUserIdFromAuthContext(ctx.session.auth.current);
+ if (triggeringUserId !== undefined) {
+ channel.state.triggeringUserId = triggeringUserId;
+ }
+ await renderTurnStarted?.(data, channel, ctx);
+ },
+ },
+ rendering.taskCard,
+ );
// Set of events we've already handled on this process.
// Light weight dedup mechanism - not reliable across multiple invocations.
@@ -1020,6 +909,7 @@ export function slackChannel(config: SlackChannelConfig = {}): SlackChannel {
resolveSession,
waitUntil,
config,
+ received: rendering.received,
uploadPolicy,
handledEvents,
headers: req.headers,
@@ -1031,20 +921,7 @@ export function slackChannel(config: SlackChannelConfig = {}): SlackChannel {
return receiveOnSlack(input, { from, api, credentials: config.credentials });
},
- events: mergedEvents,
- });
- setChannelActivityRenderers(channel, {
- destination(state) {
- const slack = state as Partial<SlackChannelState> | undefined;
- return {
- channelId: slack?.channelId ?? null,
- installationTeamId: slack?.installationTeamId ?? null,
- teamId: slack?.teamId ?? null,
- threadTs: slack?.threadTs ?? null,
- triggeringUserId: slack?.triggeringUserId ?? null,
- };
- },
- renderers: activityRenderers,
+ events,
});
const credentials = config.credentials as { readonly vercelConnect?: unknown } | undefined;
const manifest = defineSlackAppManifest({ botName: config.botName });
@@ -1151,28 +1028,6 @@ async function receiveOnSlack(
return sendAsSlackUser(source, input.message, { auth: input.auth, state, title: input.title });
}
-/**
- * Adapts a user-supplied `authorization.required` override to the full
- * internal event signature while handing it only the private-delivery
- * surface ({@link SlackAuthorizationEventContext}). Override code never
- * receives `thread.post` or the raw `slack.request` escape hatch, so the
- * challenge it renders cannot be addressed to the shared thread.
- */
-export function constrainAuthorizationRequired(
- handler: SlackAuthorizationRequiredHandler,
-): NonNullable<SlackChannelInternalEvents["authorization.required"]> {
- return (data, channel, ctx) =>
- handler(
- data,
- {
- postEphemeral: (userId, message) => channel.thread.postEphemeral(userId, message),
- postDirectMessage: (userId, message) => channel.thread.postDirectMessage(userId, message),
- state: channel.state,
- },
- ctx,
- );
-}
-
function shouldDropSlackHttpTimeoutRetry(headers: Headers): boolean {
const retryNum = Number(headers.get("x-slack-retry-num") ?? "0");
return retryNum >= 1 && headers.get("x-slack-retry-reason") === "http_timeout";
@@ -1192,6 +1047,7 @@ async function handleEventPost(input: {
readonly headers: Headers;
readonly waitUntil: (task: Promise<unknown>) => void;
readonly config: SlackChannelConfig;
+ readonly received: SlackRenderChain["received"];
readonly uploadPolicy: UploadPolicy;
readonly handledEvents: Set<string>;
}): Promise<Response> {
@@ -1226,76 +1082,49 @@ async function handleEventPost(input: {
let dispatch: (() => Promise<void>) | null = null;
let builtinDefault: (() => Promise<void>) | null = null;
+ const dispatchMessage =
+ (
+ kind: "app_mention" | "channel_message" | "direct_message",
+ message: SlackMessage,
+ handler: NonNullable<SlackChannelConfig["onMessage"]>,
+ ) =>
+ () =>
+ dispatchSlackMessage({
+ api: input.api,
+ appId,
+ botUserId,
+ receivingBotUserId,
+ from: input.from,
+ resolveSession: input.resolveSession,
+ credentials: config.credentials,
+ handler,
+ installationTeamId,
+ kind,
+ message,
+ received: input.received,
+ threadContext: config.threadContext,
+ uploadPolicy: input.uploadPolicy,
+ });
+
if (payload.kind === "app_mention" || payload.kind === "direct_message") {
const kind = payload.kind;
const message = slackMessageFromWebhookPayload(payload);
if (message !== null && !isSelfAuthoredSlackMessage({ appId, botUserId }, message)) {
- const dispatchMessageWith =
- (handler: NonNullable<SlackChannelConfig["onAppMention"]>) => () =>
- dispatchSlackMessage({
- api: input.api,
- appId,
- botUserId,
- receivingBotUserId,
- from: input.from,
- resolveSession: input.resolveSession,
- credentials: config.credentials,
- handler,
- installationTeamId,
- kind,
- message,
- threadContext: config.threadContext,
- uploadPolicy: input.uploadPolicy,
- });
const specialized = kind === "app_mention" ? config.onAppMention : config.onDirectMessage;
const handler = specialized ?? config.onMessage;
- if (handler !== undefined) {
- dispatch = () =>
- dispatchSlackMessage({
- api: input.api,
- appId,
- botUserId,
- receivingBotUserId,
- from: input.from,
- resolveSession: input.resolveSession,
- credentials: config.credentials,
- handler,
- installationTeamId,
- kind,
- message,
- threadContext: config.threadContext,
- uploadPolicy: input.uploadPolicy,
- });
- } else {
- builtinDefault = dispatchMessageWith(
- kind === "app_mention" ? defaultOnAppMention : defaultOnDirectMessage,
- );
- }
+ if (handler !== undefined) dispatch = dispatchMessage(kind, message, handler);
+ else builtinDefault = dispatchMessage(kind, message, defaultOnMessage);
}
}
- if (dispatch === null && config.onMessage !== undefined) {
+ const onMessage = config.onMessage;
+ if (dispatch === null && onMessage !== undefined) {
const message = parseMessageEvent(envelope);
if (message !== null && !isSelfAuthoredSlackMessage({ appId, botUserId }, message)) {
// Slack also emits message.channels for an app mention. The app_mention
// callback owns that user action so the generic message is not duplicated.
if (botUserId === undefined || !message.text.includes(`<@${botUserId}`)) {
- dispatch = () =>
- dispatchSlackMessage({
- api: input.api,
- appId,
- botUserId,
- receivingBotUserId,
- from: input.from,
- resolveSession: input.resolveSession,
- credentials: config.credentials,
- handler: config.onMessage!,
- installationTeamId,
- kind: "channel_message",
- message,
- threadContext: config.threadContext,
- uploadPolicy: input.uploadPolicy,
- });
+ dispatch = dispatchMessage("channel_message", message, onMessage);
}
}
}
@@ -1362,6 +1191,7 @@ async function dispatchSlackMessage(input: {
readonly installationTeamId: string | undefined;
readonly kind: "app_mention" | "channel_message" | "direct_message";
readonly message: SlackMessage;
+ readonly received: SlackRenderChain["received"];
readonly threadContext: LoadThreadContextMessagesOptions | undefined;
readonly uploadPolicy: UploadPolicy;
}): Promise<void> {
@@ -1422,6 +1252,13 @@ async function dispatchSlackMessage(input: {
thread,
};
+ // A mention or DM is addressed to the agent, so it is acknowledged while the
+ // hook decides. Other channel messages are mostly dropped, so they are
+ // acknowledged only once the hook dispatches.
+ const acknowledgeFirst = input.kind !== "channel_message";
+ const acknowledged = acknowledgeFirst
+ ? acknowledgeMessage(input.received, input.message, { slack, thread })
+ : undefined;
let result;
try {
result = await input.handler(ctx, input.message);
@@ -1429,9 +1266,15 @@ async function dispatchSlackMessage(input: {
logError(log, `${input.kind} handler failed`, error, {
channelId: input.message.channelId,
});
+ }
+ if (result === null || result === undefined) {
+ if (acknowledged !== undefined) {
+ await acknowledged;
+ await thread.startTyping();
+ }
return;
}
- if (result === null || result === undefined) return;
+ await (acknowledged ?? acknowledgeMessage(input.received, input.message, { slack, thread }));
const isPrivateConversation = await isDMOrPrivateChannel();
channelState.audience =
@@ -1451,6 +1294,19 @@ async function dispatchSlackMessage(input: {
});
}
+/** Runs the renderer chain's `received`; an acknowledgement that fails never fails dispatch. */
+async function acknowledgeMessage(
+ received: SlackRenderChain["received"],
+ message: SlackMessage,
+ channel: SlackContext,
+): Promise<void> {
+ try {
+ await received(message, channel);
+ } catch (error) {
+ logError(log, "received renderer failed", error, { channelId: message.channelId });
+ }
+}
+
/** Runs a generic Events API handler with an imperative Slack operation surface. */
async function dispatchSlackEvent(input: {
readonly api: SlackTransportOptions | undefined;
diff --git a/packages/eve/src/public/channels/slack/task-card.test.ts b/packages/eve/src/public/channels/slack/task-card.test.ts
new file mode 100644
index 000000000..bed6e57e6
--- /dev/null
+++ b/packages/eve/src/public/channels/slack/task-card.test.ts
@@ -0,0 +1,457 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import { buildAdapterContext } from "#channel/adapter-context.js";
+import { callAdapterEventHandler, type ChannelAdapter } from "#channel/adapter.js";
+import { isCompiledChannel } from "#channel/compiled-channel.js";
+import { ContextContainer, contextStorage } from "#context/container.js";
+import { ScheduleIdKey, SessionKey } from "#context/keys.js";
+import { decodeSlackApiBody } from "#internal/testing/slack-api-body.js";
+import {
+ createActionsRequestedEvent,
+ createInputRequestedEvent,
+ createInputResolvedEvent,
+ createTaskSettledEvent,
+ createTaskStartedEvent,
+ createTurnCompletedEvent,
+ type UnstampedMessageStreamEvent,
+} from "#protocol/message.js";
+import type { BlockKitBlock } from "#public/channels/slack/blocks.js";
+import { defineSlackRenderer, type SlackRenderer } from "#public/channels/slack/renderers.js";
+import { slackChannel } from "#public/channels/slack/slackChannel.js";
+
+const TURN_ID = "turn_1";
+const DEPLOY_CALL = "call_deploy";
+const RESEARCH_CALL = "call_research";
+const THREAD = {
+ audience: "private",
+ channelId: "C01",
+ threadTs: "1700000000.000001",
+};
+
+/** Records each Slack call; `reply` answers one call, defaulting to success. */
+function slackApi(
+ reply: (operation: string, index: number) => Record<string, unknown> | undefined = () =>
+ undefined,
+) {
+ const calls: Array<{ readonly body: Record<string, unknown>; readonly operation: string }> = [];
+ const fetch = vi.fn(async (input: URL | string | Request, init?: RequestInit) => {
+ const operation = String(input).split("/").at(-1)!;
+ const contentType = init?.headers ? new Headers(init.headers).get("content-type") : null;
+ calls.push({
+ body: decodeSlackApiBody(init?.body ?? "", contentType) as Record<string, unknown>,
+ operation,
+ });
+ const ts = `1700000009.00010${String(calls.length)}`;
+ return Response.json(reply(operation, calls.length - 1) ?? { ok: true, ts });
+ });
+ return { calls, fetch };
+}
+
+/**
+ * A root session's Slack channel in a thread. `emit` delivers an event the way
+ * the session does, keeping the channel's state between events.
+ */
+function slackThread(
+ input: {
+ readonly renderers?: readonly SlackRenderer[];
+ readonly reply?: Parameters<typeof slackApi>[0];
+ readonly schedule?: boolean;
+ readonly state?: Record<string, unknown>;
+ } = {},
+) {
+ const { calls, fetch } = slackApi(input.reply);
+ const channel = slackChannel({
+ api: { fetch },
+ credentials: { botToken: "xoxb-test" },
+ renderers: input.renderers,
+ });
+ if (!isCompiledChannel(channel)) throw new Error("Expected a compiled channel.");
+ const adapter: ChannelAdapter = {
+ ...channel.adapter,
+ state: { ...channel.adapter.state, ...(input.state ?? THREAD) },
+ };
+ const adapterCtx = buildAdapterContext(adapter, { get: () => undefined, set: () => {} } as never);
+ const session = new ContextContainer();
+ session.setVirtualContext(SessionKey, {
+ auth: { current: null, initiator: null },
+ sessionId: "session_root",
+ turn: { id: TURN_ID, sequence: 0 },
+ });
+ if (input.schedule === true) session.set(ScheduleIdKey, "nightly-report");
+ const emit = async (...events: UnstampedMessageStreamEvent[]) => {
+ for (const event of events) {
+ await contextStorage.run(session, () => callAdapterEventHandler(adapter, event, adapterCtx));
+ }
+ };
+ // Card writes carry a task card or plan block; other posts, such as an approval, don't.
+ const cardCalls = () =>
+ calls.filter((call) => /"type":"(task_card|plan)"/.test(JSON.stringify(call.body["blocks"])));
+ return { calls, cardCalls, emit };
+}
+
+/** A root turn that starts a deploy tool task and a researcher agent task. */
+const TWO_TASKS_STARTED: readonly UnstampedMessageStreamEvent[] = [
+ createActionsRequestedEvent({
+ actions: [
+ {
+ callId: DEPLOY_CALL,
+ input: { service: "storefront" },
+ kind: "tool-call",
+ toolName: "deploy",
+ },
+ {
+ callId: RESEARCH_CALL,
+ input: { message: "Find the incidents behind the checkout spike\nInclude timelines." },
+ kind: "tool-call",
+ toolName: "researcher",
+ },
+ ],
+ presentation: {
+ [DEPLOY_CALL]: { label: "Deploy storefront" },
+ [RESEARCH_CALL]: { label: "researcher: Find the incidents behind the checkout spike" },
+ },
+ sequence: 1,
+ stepIndex: 0,
+ turnId: TURN_ID,
+ }),
+ createTaskStartedEvent({
+ callId: DEPLOY_CALL,
+ kind: "tool",
+ name: "deploy",
+ taskId: "deploy-4hd8sa",
+ turnId: TURN_ID,
+ }),
+ createTaskStartedEvent({
+ callId: RESEARCH_CALL,
+ kind: "agent",
+ name: "researcher",
+ taskId: "researcher-7k2m9q",
+ turnId: TURN_ID,
+ }),
+];
+
+const BOTH_TASKS_SETTLED: readonly UnstampedMessageStreamEvent[] = [
+ createTaskSettledEvent({
+ callId: DEPLOY_CALL,
+ output: "3 deploys; 14:02 changed the cache TTL\nFull log attached.",
+ status: "completed",
+ taskId: "deploy-4hd8sa",
+ turnId: TURN_ID,
+ }),
+ createTaskSettledEvent({
+ callId: RESEARCH_CALL,
+ error: { message: "Rate limited by the incidents API\nRetry after 60s." },
+ status: "failed",
+ taskId: "researcher-7k2m9q",
+ turnId: TURN_ID,
+ }),
+];
+
+const TURN_COMPLETED = createTurnCompletedEvent({ sequence: 2, turnId: TURN_ID });
+
+afterEach(() => {
+ vi.useRealTimers();
+});
+
+describe("Slack task card", () => {
+ it("posts one live card for a turn's tasks, then updates it in place until the turn ends", async () => {
+ const { cardCalls, emit } = slackThread();
+
+ await emit(...TWO_TASKS_STARTED);
+
+ expect(cardCalls().map((call) => call.operation)).toEqual(["chat.postMessage", "chat.update"]);
+ expect(cardCalls()[0]!.body).toMatchObject({
+ channel: "C01",
+ thread_ts: "1700000000.000001",
+ unfurl_links: "false",
+ unfurl_media: "false",
+ });
+ expect(cardCalls()[1]!.body).toMatchObject({
+ blocks: [
+ {
+ tasks: [
+ { status: "in_progress", title: "Deploy storefront" },
+ {
+ status: "in_progress",
+ title: "researcher: Find the incidents behind the checkout spike",
+ },
+ ],
+ title: "Working on 2 tasks",
+ type: "plan",
+ },
+ ],
+ text: "Working on 2 tasks: Deploy storefront, researcher: Find the incidents behind the checkout spike",
+ });
+ const cardTs = cardCalls()[1]!.body["ts"];
+ expect(cardTs).toEqual(expect.any(String));
+
+ await emit(...BOTH_TASKS_SETTLED, TURN_COMPLETED);
+
+ expect(cardCalls().at(-1)!.body).toMatchObject({
+ blocks: [
+ {
+ tasks: [
+ {
+ output: {
+ elements: [{ elements: [{ text: "3 deploys; 14:02 changed the cache TTL" }] }],
+ },
+ status: "complete",
+ },
+ {
+ output: {
+ elements: [{ elements: [{ text: "Failed: Rate limited by the incidents API" }] }],
+ },
+ status: "error",
+ },
+ ],
+ title: "Finished 2 tasks: 1 failed",
+ },
+ ],
+ ts: cardTs,
+ });
+
+ const written = cardCalls().length;
+ await emit(TURN_COMPLETED);
+ expect(cardCalls()).toHaveLength(written);
+ });
+
+ it("shows a failure without its error text outside private conversations", async () => {
+ const { cardCalls, emit } = slackThread({ state: { ...THREAD, audience: "public" } });
+
+ await emit(...TWO_TASKS_STARTED, ...BOTH_TASKS_SETTLED);
+
+ const blocks = JSON.stringify(cardCalls().at(-1)!.body["blocks"]);
+ expect(blocks).not.toContain("Rate limited");
+ expect(cardCalls().at(-1)!.body["blocks"]).toMatchObject([
+ {
+ tasks: [
+ { status: "complete" },
+ { output: { elements: [{ elements: [{ text: "Failed" }] }] } },
+ ],
+ },
+ ]);
+ });
+
+ it("shows a task blocked on a person until its request resolves", async () => {
+ const approval = createInputRequestedEvent({
+ requests: [
+ {
+ action: { callId: "child_deploy", input: {}, kind: "tool-call", toolName: "promote" },
+ kind: "tool-approval",
+ prompt: "Promote storefront to production?",
+ requestId: "approval-1",
+ },
+ ],
+ sequence: 3,
+ stepIndex: 0,
+ taskId: "deploy-4hd8sa",
+ turnId: TURN_ID,
+ });
+ const approved = createInputResolvedEvent({
+ resolutions: [{ kind: "tool-approval", outcome: "approved", requestId: "approval-1" }],
+ sequence: 3,
+ stepIndex: 0,
+ turnId: TURN_ID,
+ });
+ const card = async (audience: string) => {
+ const thread = slackThread({ state: { ...THREAD, audience } });
+ await thread.emit(...TWO_TASKS_STARTED, approval);
+ const blocked = thread.cardCalls().at(-1)!.body["blocks"];
+ await thread.emit(approved);
+ return { blocked, resolved: thread.cardCalls().at(-1)!.body["blocks"] };
+ };
+
+ const shared = await card("public");
+ expect(shared.blocked).toMatchObject([
+ {
+ tasks: [
+ {
+ details: { elements: [{ elements: [{ text: "Waiting for approval" }] }] },
+ status: "in_progress",
+ title: "Deploy storefront",
+ },
+ { status: "in_progress" },
+ ],
+ title: "Waiting for approval",
+ },
+ ]);
+ expect(shared.resolved).toMatchObject([{ title: "Working on 2 tasks" }]);
+ expect(JSON.stringify(shared.resolved)).not.toContain("Waiting for approval");
+
+ const direct = await card("private");
+ expect(JSON.stringify(direct.blocked)).toContain(
+ "Waiting for approval: Promote storefront to production?",
+ );
+ });
+
+ it("posts the card again when someone deleted it", async () => {
+ const { cardCalls, emit } = slackThread({
+ reply: (operation) =>
+ operation === "chat.update" ? { error: "message_not_found", ok: false } : undefined,
+ });
+
+ await emit(TWO_TASKS_STARTED[0]!, TWO_TASKS_STARTED[1]!, BOTH_TASKS_SETTLED[0]!);
+
+ expect(cardCalls().map((call) => call.operation)).toEqual([
+ "chat.postMessage",
+ "chat.update",
+ "chat.postMessage",
+ ]);
+ });
+
+ it("tries a failed write once more, then again on the turn's next change", async () => {
+ vi.useFakeTimers();
+ // The card's first post and its retry both fail.
+ let posts = 0;
+ const { cardCalls, emit } = slackThread({
+ reply: (operation) =>
+ operation === "chat.postMessage" && ++posts <= 2
+ ? { error: "ratelimited", ok: false }
+ : undefined,
+ });
+
+ const starting = emit(TWO_TASKS_STARTED[0]!, TWO_TASKS_STARTED[1]!);
+ await vi.runAllTimersAsync();
+ await starting;
+ await emit(BOTH_TASKS_SETTLED[0]!);
+
+ expect(cardCalls().map((call) => call.operation)).toEqual([
+ "chat.postMessage",
+ "chat.postMessage",
+ "chat.postMessage",
+ ]);
+ });
+
+ it("keeps the card current when a renderer replaces eve's task handlers", async () => {
+ const { cardCalls, emit } = slackThread({
+ renderers: [{ events: { async "task.started"() {}, async "task.settled"() {} } }],
+ });
+
+ await emit(TWO_TASKS_STARTED[0]!, TWO_TASKS_STARTED[1]!, BOTH_TASKS_SETTLED[0]!);
+
+ expect(cardCalls().at(-1)!.body).toMatchObject({
+ blocks: [{ status: "complete", title: "Deploy storefront", type: "task_card" }],
+ });
+ });
+
+ it("builds an authored task card on eve's default card", async () => {
+ const { cardCalls, emit } = slackThread({
+ renderers: [
+ {
+ taskCard(view, next) {
+ const card = next(view);
+ if (card === null) return null;
+ const footer = { elements: [{ text: view.turnId, type: "mrkdwn" }], type: "context" };
+ return { ...card, blocks: [...card.blocks, footer] };
+ },
+ },
+ ],
+ });
+
+ await emit(TWO_TASKS_STARTED[0]!, TWO_TASKS_STARTED[1]!);
+
+ expect(cardCalls()[0]!.body["blocks"]).toMatchObject([
+ { type: "task_card" },
+ { elements: [{ text: TURN_ID }], type: "context" },
+ ]);
+ });
+
+ it("lets an app show its own plan tool's checklist ahead of eve's task rows", async () => {
+ // What an app writes: its own `plan` tool, rendered from the call's input.
+ const status = {
+ completed: "complete",
+ failed: "error",
+ pending: "pending",
+ working: "in_progress",
+ };
+ const planRenderer = defineSlackRenderer({
+ taskCard(view, next) {
+ const card = next(view);
+ const plan = view.actions.filter((action) => action.name === "plan").at(-1);
+ const items = plan?.input?.["items"] as
+ | { status: keyof typeof status; title: string }[]
+ | undefined;
+ if (items === undefined) return card;
+ // eve's card is one `plan` block, or one `task_card` block for a single task.
+ const [block] = card?.blocks ?? [];
+ const taskRows: BlockKitBlock[] =
+ block === undefined
+ ? []
+ : block["type"] === "plan"
+ ? (block["tasks"] as BlockKitBlock[])
+ : [block];
+ const planRows = items.map((item, index) => ({
+ status: status[item.status],
+ task_id: `plan_${String(index)}`,
+ title: item.title,
+ }));
+ const tasks = [...planRows, ...taskRows.map(({ type: _type, ...row }) => row)];
+ return { blocks: [{ tasks, title: "Plan", type: "plan" }], text: "Plan" };
+ },
+ });
+ const { cardCalls, emit } = slackThread({ renderers: [planRenderer] });
+
+ await emit(
+ createActionsRequestedEvent({
+ actions: [
+ {
+ callId: "call_plan",
+ input: {
+ items: [
+ { status: "completed", title: "Read the incident report" },
+ { status: "working", title: "Check recent deploys" },
+ { status: "pending", title: "Write up the cause" },
+ ],
+ },
+ kind: "tool-call",
+ toolName: "plan",
+ },
+ ],
+ sequence: 1,
+ stepIndex: 0,
+ turnId: TURN_ID,
+ }),
+ );
+ expect(cardCalls()[0]!.body["blocks"]).toMatchObject([
+ { tasks: [{ title: "Read the incident report" }, {}, {}], type: "plan" },
+ ]);
+
+ await emit(TWO_TASKS_STARTED[0]!, TWO_TASKS_STARTED[1]!);
+
+ expect(cardCalls().at(-1)!.body["blocks"]).toMatchObject([
+ {
+ tasks: [
+ { status: "complete", title: "Read the incident report" },
+ { status: "in_progress", title: "Check recent deploys" },
+ { status: "pending", title: "Write up the cause" },
+ { status: "in_progress", title: "Deploy storefront" },
+ ],
+ type: "plan",
+ },
+ ]);
+ });
+
+ it("posts no default card for a turn whose tool calls start no task", async () => {
+ const { cardCalls, emit } = slackThread();
+
+ await emit(
+ createActionsRequestedEvent({
+ actions: [{ callId: "call_logs", input: {}, kind: "tool-call", toolName: "logs" }],
+ sequence: 1,
+ stepIndex: 0,
+ turnId: TURN_ID,
+ }),
+ TURN_COMPLETED,
+ );
+
+ expect(cardCalls()).toEqual([]);
+ });
+
+ it("posts no card in a schedule's session, which posts only its final reply", async () => {
+ const { cardCalls, emit } = slackThread({ schedule: true });
+
+ await emit(...TWO_TASKS_STARTED);
+
+ expect(cardCalls()).toEqual([]);
+ });
+});
diff --git a/packages/eve/src/public/channels/slack/task-card.ts b/packages/eve/src/public/channels/slack/task-card.ts
new file mode 100644
index 000000000..229871ae5
--- /dev/null
+++ b/packages/eve/src/public/channels/slack/task-card.ts
@@ -0,0 +1,368 @@
+import { createHash } from "node:crypto";
+
+import {
+ taskCardView,
+ trackTaskCardEvent,
+ type TaskCardBlocker,
+ type TaskCardTask,
+ type TaskCardTurn,
+ type TaskCardView,
+} from "#channel/task-card.js";
+import { contextStorage } from "#context/container.js";
+import { ScheduleIdKey } from "#context/keys.js";
+import { createLogger, logError } from "#internal/logging.js";
+import type { UnstampedMessageStreamEvent } from "#protocol/message.js";
+import type { SlackHandle } from "#public/channels/slack/api.js";
+import type { BlockKitBlock } from "#public/channels/slack/blocks.js";
+import { truncateMessageText } from "#public/channels/slack/limits.js";
+import type { SlackTaskCard } from "#public/channels/slack/renderers.js";
+import type {
+ SlackChannelInternalEvents,
+ SlackChannelState,
+ SlackEventContext,
+} from "#public/channels/slack/slackChannel.js";
+import { normalizeChannelAudience } from "#shared/channel-audience.js";
+
+const log = createLogger("slack.task-card");
+
+/** A plan block holds at most 50 tasks. */
+const MAX_PLAN_ROWS = 50;
+const MAX_TITLE_LENGTH = 80;
+const MAX_LINE_LENGTH = 200;
+/** Unfinished turns eve keeps tracking; the oldest drop first. */
+const MAX_TRACKED_TURNS = 20;
+const WRITE_RETRY_MS = 1_000;
+
+type SlackTaskStatus = "in_progress" | "complete" | "error";
+
+interface SlackTaskObject {
+ details?: BlockKitBlock;
+ output?: BlockKitBlock;
+ readonly status: SlackTaskStatus;
+ readonly task_id: string;
+ readonly title: string;
+}
+
+/**
+ * eve's default task card: a `task_card` block for one task, or a `plan` block
+ * for several, and no card for a turn that started none. A settled task shows
+ * one line about how it ended. A stopped task shows as an error, never as a
+ * success.
+ */
+export function renderDefaultSlackTaskCard(view: TaskCardView): SlackTaskCard | null {
+ if (view.tasks.length === 0) return null;
+ const rows = collapseEarlierRows(view.tasks).map(toSlackTask);
+ const title = planTitle(view);
+ const blocks: BlockKitBlock[] =
+ rows.length === 1
+ ? [{ type: "task_card", ...rows[0]! }]
+ : [{ type: "plan", tasks: rows, title }];
+ const titles = view.tasks.map((task) => task.title).join(", ");
+ return { blocks, text: truncateMessageText(`${title}: ${titles}`) };
+}
+
+function planTitle(view: TaskCardView): string {
+ if (view.state === "blocked") {
+ const blocker = view.tasks.find((task) => task.blockedOn !== undefined)?.blockedOn;
+ return waitingText(blocker?.kind ?? "input");
+ }
+ const statuses = view.tasks.map((task) => task.status);
+ const total = statuses.length;
+ if (view.state === "working") {
+ const done = statuses.filter((status) => status !== "working" && status !== "blocked").length;
+ return done === 0
+ ? `Working on ${countTasks(total)}`
+ : `${String(done)} of ${countTasks(total)} done`;
+ }
+ const failed = statuses.filter((status) => status === "failed").length;
+ const stopped = statuses.filter((status) => status === "cancelled").length;
+ const outcomes: string[] = [];
+ if (failed > 0) outcomes.push(`${String(failed)} failed`);
+ if (stopped > 0) outcomes.push(`${String(stopped)} stopped`);
+ const finished = `Finished ${countTasks(total)}`;
+ return outcomes.length === 0 ? finished : `${finished}: ${outcomes.join(", ")}`;
+}
+
+function countTasks(count: number): string {
+ return count === 1 ? "1 task" : `${String(count)} tasks`;
+}
+
+/** Keeps a plan within Slack's cap by folding the oldest settled rows into one. */
+function collapseEarlierRows(tasks: readonly TaskCardTask[]): readonly TaskCardTask[] {
+ if (tasks.length <= MAX_PLAN_ROWS) return tasks;
+ const overflow = tasks.length - (MAX_PLAN_ROWS - 1);
+ const folded = new Set(
+ tasks
+ .filter((task) => task.status !== "working")
+ .slice(0, overflow)
+ .map((task) => task.id),
+ );
+ const kept = tasks.filter((task) => !folded.has(task.id));
+ if (folded.size === 0) return kept.slice(-MAX_PLAN_ROWS);
+ const foldedFailure = tasks.some(
+ (task) => folded.has(task.id) && (task.status === "failed" || task.status === "cancelled"),
+ );
+ const earlier: TaskCardTask = {
+ id: "earlier",
+ kind: "tool",
+ name: "earlier",
+ startedAt: tasks[0]!.startedAt,
+ status: foldedFailure ? "failed" : "completed",
+ taskId: "earlier",
+ title: `${countTasks(folded.size)} finished earlier`,
+ };
+ return [earlier, ...kept].slice(-MAX_PLAN_ROWS);
+}
+
+function toSlackTask(task: TaskCardTask): SlackTaskObject {
+ const slackTask: SlackTaskObject = {
+ status: slackStatus(task),
+ task_id: slackTaskId(task.id),
+ title: truncate(task.title, MAX_TITLE_LENGTH),
+ };
+ if (task.blockedOn !== undefined) slackTask.details = richText(blockerLine(task.blockedOn));
+ const output = outputLine(task);
+ if (output !== undefined) slackTask.output = richText(output);
+ return slackTask;
+}
+
+function slackStatus(task: TaskCardTask): SlackTaskStatus {
+ switch (task.status) {
+ case "working":
+ case "blocked":
+ return "in_progress";
+ case "completed":
+ return "complete";
+ case "failed":
+ case "cancelled":
+ return "error";
+ }
+}
+
+function outputLine(task: TaskCardTask): string | undefined {
+ switch (task.status) {
+ case "completed":
+ return task.summary;
+ case "failed":
+ return task.summary === undefined ? "Failed" : `Failed: ${task.summary}`;
+ case "cancelled":
+ return "Stopped";
+ default:
+ return undefined;
+ }
+}
+
+function blockerLine(blocker: TaskCardBlocker): string {
+ const waiting = waitingText(blocker.kind);
+ return blocker.label === undefined ? waiting : `${waiting}: ${blocker.label}`;
+}
+
+function waitingText(kind: TaskCardBlocker["kind"]): string {
+ switch (kind) {
+ case "approval":
+ return "Waiting for approval";
+ case "authorization":
+ return "Waiting for sign-in";
+ case "input":
+ return "Waiting for a response";
+ }
+}
+
+function richText(line: string): BlockKitBlock {
+ return {
+ elements: [
+ {
+ elements: [{ text: truncate(line, MAX_LINE_LENGTH), type: "text" }],
+ type: "rich_text_section",
+ },
+ ],
+ type: "rich_text",
+ };
+}
+
+function truncate(text: string, max: number): string {
+ return text.length <= max ? text : `${text.slice(0, max - 1)}…`;
+}
+
+/** Slack task ids must be unique in a plan; call ids are, but can carry characters Slack rejects. */
+function slackTaskId(id: string): string {
+ return id.replace(/[^a-zA-Z0-9_-]/g, "_").slice(-200);
+}
+
+/** A turn's tracked calls, and the card eve last wrote for it. */
+export interface SlackTaskCardState {
+ readonly turn: TaskCardTurn;
+ readonly ts?: string;
+ readonly fingerprint?: string;
+}
+
+const TRACKED_EVENTS = [
+ "actions.requested",
+ "action.result",
+ "task.started",
+ "task.settled",
+ "input.requested",
+ "input.resolved",
+ "authorization.required",
+ "authorization.completed",
+ "turn.completed",
+ "turn.failed",
+ "turn.cancelled",
+] as const;
+
+type TrackedEvent = (typeof TRACKED_EVENTS)[number];
+type TrackedHandler = (
+ data: Extract<UnstampedMessageStreamEvent, { readonly type: TrackedEvent }>["data"],
+ channel: SlackEventContext,
+ ctx: Parameters<NonNullable<SlackChannelInternalEvents["task.started"]>>[2],
+) => Promise<void>;
+
+/**
+ * Keeps each turn's task card current from the session's own events. It runs
+ * around the renderer chain, so the card never depends on which handlers a
+ * renderer keeps: eve tracks the turn's calls first, runs the chain's handler,
+ * then writes the card `taskCard` returns if it changed.
+ */
+export function withTaskCards(
+ events: SlackChannelInternalEvents,
+ taskCard: (view: TaskCardView) => SlackTaskCard | null,
+): SlackChannelInternalEvents {
+ const wrapped: Partial<Record<TrackedEvent, TrackedHandler>> = {};
+ for (const type of TRACKED_EVENTS) {
+ const handler = events[type] as TrackedHandler | undefined;
+ wrapped[type] = async (data, channel, ctx) => {
+ const event = { data, type } as UnstampedMessageStreamEvent;
+ const changed = trackTaskCardEvent(
+ trackedTurns(channel.state),
+ event,
+ new Date().toISOString(),
+ );
+ for (const [turnId, turn] of Object.entries(changed))
+ rememberTurn(channel.state, turnId, turn);
+ try {
+ await handler?.(data, channel, ctx);
+ } finally {
+ for (const turnId of Object.keys(changed)) await writeTaskCard(channel, turnId, taskCard);
+ }
+ };
+ }
+ return { ...events, ...wrapped } as SlackChannelInternalEvents;
+}
+
+function trackedTurns(state: SlackChannelState): Readonly<Record<string, TaskCardTurn>> {
+ return Object.fromEntries(
+ Object.entries(state.taskCards ?? {}).map(([turnId, card]) => [turnId, card.turn]),
+ );
+}
+
+function rememberTurn(state: SlackChannelState, turnId: string, turn: TaskCardTurn): void {
+ const cards = { ...state.taskCards, [turnId]: { ...state.taskCards?.[turnId], turn } };
+ const turnIds = Object.keys(cards);
+ for (const oldest of turnIds.slice(0, Math.max(0, turnIds.length - MAX_TRACKED_TURNS))) {
+ delete cards[oldest];
+ }
+ state.taskCards = cards;
+}
+
+/**
+ * Renders the turn's card and posts or updates it, then forgets a finished
+ * turn, whose card can't change again. A schedule's session posts only its
+ * final reply, and a session without a thread has nowhere to post.
+ */
+async function writeTaskCard(
+ channel: SlackEventContext,
+ turnId: string,
+ taskCard: (view: TaskCardView) => SlackTaskCard | null,
+): Promise<void> {
+ const current = channel.state.taskCards?.[turnId];
+ if (current === undefined) return;
+ const audience = normalizeChannelAudience(channel.state.audience);
+ const view = taskCardView(turnId, current.turn, { audience });
+ const { channelId, threadTs } = channel.state;
+ const scheduled = contextStorage.getStore()?.get(ScheduleIdKey) !== undefined;
+ const thread = channelId && threadTs && !scheduled ? { channelId, threadTs } : undefined;
+ const card = thread === undefined ? null : renderCard(taskCard, view);
+ if (thread !== undefined && card !== null) {
+ const fingerprint = createHash("sha256").update(JSON.stringify(card)).digest("base64url");
+ if (fingerprint !== current.fingerprint) {
+ const ts = await writeCardWithRetry(channel.slack, { ...thread, card, ts: current.ts });
+ // Keep a card that failed to land, so the turn's next change writes it again.
+ if (ts === undefined) return;
+ channel.state.taskCards = {
+ ...channel.state.taskCards,
+ [turnId]: { fingerprint, ts, turn: current.turn },
+ };
+ }
+ }
+ if (view.state === "finished") forgetTurn(channel.state, turnId);
+}
+
+function forgetTurn(state: SlackChannelState, turnId: string): void {
+ const { [turnId]: _finished, ...cards } = state.taskCards ?? {};
+ state.taskCards = cards;
+}
+
+/** An authored card that throws leaves that turn's card as it was. */
+function renderCard(
+ taskCard: (view: TaskCardView) => SlackTaskCard | null,
+ view: TaskCardView,
+): SlackTaskCard | null {
+ try {
+ return taskCard(view);
+ } catch (error) {
+ logError(log, "task card renderer failed", error, { turnId: view.turnId });
+ return null;
+ }
+}
+
+interface CardWrite {
+ readonly card: SlackTaskCard;
+ readonly channelId: string;
+ readonly threadTs: string;
+ readonly ts: string | undefined;
+}
+
+/**
+ * Writes a card, trying once more after a second. A card that still fails
+ * keeps its last fingerprint, so the next change writes it again. Never
+ * throws: a card is never worth failing the turn over.
+ */
+async function writeCardWithRetry(
+ slack: SlackHandle,
+ write: CardWrite,
+): Promise<string | undefined> {
+ for (const attempt of [1, 2]) {
+ try {
+ return await writeCard(slack, write);
+ } catch (error) {
+ logError(log, "task card write failed", error, { attempt });
+ if (attempt === 1) await new Promise((resolve) => setTimeout(resolve, WRITE_RETRY_MS));
+ }
+ }
+ return undefined;
+}
+
+/** Updates the card in place, or posts it again when someone deleted it. */
+async function writeCard(slack: SlackHandle, write: CardWrite): Promise<string> {
+ const message = { blocks: write.card.blocks, channel: write.channelId, text: write.card.text };
+ if (write.ts !== undefined) {
+ const updated = await slack.request("chat.update", { ...message, ts: write.ts });
+ if (updated.ok === true) return write.ts;
+ if (updated.error !== "message_not_found") throw slackError(updated.error);
+ }
+ const posted = await slack.request("chat.postMessage", {
+ ...message,
+ thread_ts: write.threadTs,
+ unfurl_links: false,
+ unfurl_media: false,
+ });
+ if (posted.ok !== true) throw slackError(posted.error);
+ if (typeof posted.ts !== "string" || posted.ts === "") {
+ throw new Error("Slack did not return a ts for the task card.");
+ }
+ return posted.ts;
+}
+
+function slackError(error: string | undefined): Error {
+ return new Error(`Slack task card failed: ${error ?? "unknown_error"}`);
+}
diff --git a/packages/eve/src/public/definitions/channel.ts b/packages/eve/src/public/definitions/channel.ts
index 944e1ae93..36c7421b6 100644
--- a/packages/eve/src/public/definitions/channel.ts
+++ b/packages/eve/src/public/definitions/channel.ts
@@ -209,6 +209,10 @@ export interface ChannelEvents<TCtx = void> {
readonly "reasoning.completed"?: ChannelEventHandler<"reasoning.completed", TCtx>;
readonly "step.completed"?: ChannelEventHandler<"step.completed", TCtx>;
readonly "input.requested"?: ChannelEventHandler<"input.requested", TCtx>;
+ readonly "input.resolved"?: ChannelEventHandler<"input.resolved", TCtx>;
+ readonly "task.started"?: ChannelEventHandler<"task.started", TCtx>;
+ readonly "task.settled"?: ChannelEventHandler<"task.settled", TCtx>;
+ readonly "turn.waiting"?: ChannelEventHandler<"turn.waiting", TCtx>;
readonly "turn.failed"?: ChannelEventHandler<"turn.failed", TCtx>;
readonly "turn.completed"?: ChannelEventHandler<"turn.completed", TCtx>;
readonly "turn.cancelled"?: ChannelEventHandler<"turn.cancelled", TCtx>;
@@ -320,6 +324,10 @@ const channelEventTypes: Record<keyof ChannelEvents, null> = {
"reasoning.completed": null,
"step.completed": null,
"input.requested": null,
+ "input.resolved": null,
+ "task.started": null,
+ "task.settled": null,
+ "turn.waiting": null,
"turn.failed": null,
"turn.completed": null,
"turn.cancelled": null,
diff --git a/packages/eve/src/runtime/channels/registry.test.ts b/packages/eve/src/runtime/channels/registry.test.ts
index 5aacfa3fd..6dbad307b 100644
--- a/packages/eve/src/runtime/channels/registry.test.ts
+++ b/packages/eve/src/runtime/channels/registry.test.ts
@@ -1,11 +1,7 @@
-import { describe, expect, it, vi } from "vitest";
+import { describe, expect, it } from "vitest";
import type { ChannelAdapter } from "#channel/adapter.js";
import { HTTP_ADAPTER, HTTP_ADAPTER_KIND } from "#channel/http.js";
-import {
- attachChannelActivityPresentation,
- getChannelActivityPresentation,
-} from "#channel/activity-renderer.js";
import { SCHEDULE_ADAPTER, SCHEDULE_ADAPTER_KIND } from "#channel/schedule.js";
import { SUBAGENT_ADAPTER_KIND } from "#subagents/adapter-state.js";
import { SUBAGENT_ADAPTER } from "#subagents/adapter.js";
@@ -86,28 +82,6 @@ describe("createRuntimeAdapterRegistry", () => {
});
});
- it("rehydrates non-enumerable activity renderer behavior", () => {
- const adapter: ChannelAdapter = { kind: "slack", state: { channelId: null } };
- const render = vi.fn();
- const destination = vi.fn();
- attachChannelActivityPresentation(adapter, {
- destination,
- renderers: [{ id: "slack.status.v1", render }],
- });
- const registry = createRuntimeAdapterRegistry({ channels: [makeChannelDefinition(adapter)] });
-
- const rehydrated = deserializeRuntimeAdapter(registry, {
- kind: "slack",
- state: { channelId: "C1", threadTs: "T1" },
- });
-
- expect(getChannelActivityPresentation(rehydrated)).toEqual({
- destination,
- renderers: [{ id: "slack.status.v1", render }],
- });
- expect(rehydrated.state).toEqual({ channelId: "C1", threadTs: "T1" });
- });
-
describe("route-declared adapters sharing a framework kind", () => {
it("silently merges a bare pass-through that re-declares a framework kind", () => {
const registry = createRuntimeAdapterRegistry({
diff --git a/packages/eve/src/runtime/channels/registry.ts b/packages/eve/src/runtime/channels/registry.ts
index f3706dbd6..7c1ceda91 100644
--- a/packages/eve/src/runtime/channels/registry.ts
+++ b/packages/eve/src/runtime/channels/registry.ts
@@ -1,9 +1,5 @@
import type { ChannelAdapter } from "#channel/adapter.js";
import { getAdapterKind } from "#channel/adapter.js";
-import {
- copyChannelActivityPresentation,
- getChannelActivityPresentation,
-} from "#channel/activity-renderer.js";
import { HTTP_ADAPTER } from "#channel/http.js";
import { SCHEDULE_ADAPTER } from "#channel/schedule.js";
import { SUBAGENT_ADAPTER } from "#subagents/adapter.js";
@@ -133,9 +129,7 @@ export function deserializeRuntimeAdapter(
);
}
- const rehydrated: ChannelAdapter = { ...adapterConfig, state: serialized.state };
- copyChannelActivityPresentation(adapterConfig, rehydrated);
- return rehydrated;
+ return { ...adapterConfig, state: serialized.state };
}
function requireAdapterKind(
@@ -160,8 +154,6 @@ function requireAdapterKind(
* the bare `kind` discriminator (and initial `state`).
*/
function carriesAdapterBehavior(adapter: ChannelAdapter): boolean {
- if (getChannelActivityPresentation(adapter) !== undefined) return true;
-
if (adapter.deliver !== undefined) {
return true;
}
diff --git a/packages/eve/src/subagents/event-proxy-step.integration.test.ts b/packages/eve/src/subagents/event-proxy-step.integration.test.ts
index 2b1572f50..9db10300c 100644
--- a/packages/eve/src/subagents/event-proxy-step.integration.test.ts
+++ b/packages/eve/src/subagents/event-proxy-step.integration.test.ts
@@ -188,7 +188,6 @@ describe("proxied stream hooks", () => {
const publisher = openSessionEventPublisher({
ctx: f.ctx,
origin: "own",
- sessionId: "parent-session",
sessionWritable: f.sessionWritable,
});
try {
@@ -222,9 +221,9 @@ describe("proxied stream hooks", () => {
Response.json({ ok: true }, { status: 202 }),
);
vi.stubGlobal("fetch", fetchMock);
- const sink = createSessionEventSink({
+ const publisher = openSessionEventPublisher({
ctx: f.ctx,
- sessionId: "parent-session",
+ origin: "own",
sessionWritable: f.sessionWritable,
});
const signIn = createAuthorizationRequiredEvent({
@@ -235,8 +234,8 @@ describe("proxied stream hooks", () => {
turnId: "child-turn",
});
try {
- await sink.emit({ type: "input.requested", data: f.hookPayload.event });
- await sink.emit(signIn);
+ await publisher.emit({ type: "input.requested", data: f.hookPayload.event });
+ await publisher.emit(signIn);
const bodies = fetchMock.mock.calls.map(([, init]) => JSON.parse(init.body as string));
const envelope = {
callId: "remote-call",
@@ -251,7 +250,7 @@ describe("proxied stream hooks", () => {
]);
expect(f.order).not.toContain("channel:input.requested");
} finally {
- sink.release();
+ publisher.writer.release();
vi.unstubAllGlobals();
}
});
@@ -267,17 +266,17 @@ describe("proxied stream hooks", () => {
f.ctx.set(LegacyRemoteAgentCallerKey, {});
const fetchMock = vi.fn(async () => Response.json({ ok: true }, { status: 202 }));
vi.stubGlobal("fetch", fetchMock);
- const sink = createSessionEventSink({
+ const publisher = openSessionEventPublisher({
ctx: f.ctx,
- sessionId: "parent-session",
+ origin: "own",
sessionWritable: f.sessionWritable,
});
try {
- await sink.emit({ type: "input.requested", data: f.hookPayload.event });
+ await publisher.emit({ type: "input.requested", data: f.hookPayload.event });
expect(fetchMock).not.toHaveBeenCalled();
expect(f.order).toContain("channel:input.requested");
} finally {
- sink.release();
+ publisher.writer.release();
vi.unstubAllGlobals();
}
});
@@ -299,7 +298,6 @@ describe("proxied stream hooks", () => {
const publisher = openSessionEventPublisher({
ctx: f.ctx,
origin: "own",
- sessionId: "parent-session",
sessionWritable: f.sessionWritable,
});
try {
diff --git a/packages/eve/src/subagents/parent-notification.ts b/packages/eve/src/subagents/parent-notification.ts
index 7c9af5486..9f30a07a3 100644
--- a/packages/eve/src/subagents/parent-notification.ts
+++ b/packages/eve/src/subagents/parent-notification.ts
@@ -5,7 +5,7 @@ import { deserializeContext } from "#context/serialize.js";
import { parseSessionCallback } from "#channel/session-callback.js";
import type { TurnCaller } from "#channel/types.js";
import type { RuntimeSubagentChildResult } from "#shared/action-types.js";
-import { ActivityObserverKey, SessionCallbackKey } from "#context/keys.js";
+import { SessionCallbackKey } from "#context/keys.js";
import {
isSubagentAdapterState,
SUBAGENT_ADAPTER_KIND,
@@ -224,10 +224,6 @@ function bindTurnCallerContext(
serializedContext: Record<string, unknown>,
): Record<string, unknown> {
if (caller === undefined) return serializedContext;
- const withActivity =
- caller.activityObserver === undefined
- ? serializedContext
- : { ...serializedContext, [ActivityObserverKey.name]: caller.activityObserver };
if (caller.replyTo.kind === "callback") {
const callback = {
callId: caller.callId,
@@ -235,10 +231,10 @@ function bindTurnCallerContext(
token: caller.replyTo.token,
url: caller.replyTo.url,
};
- return { ...withActivity, [SessionCallbackKey.name]: callback };
+ return { ...serializedContext, [SessionCallbackKey.name]: callback };
}
- const adapter = withActivity[ChannelKey.name];
+ const adapter = serializedContext[ChannelKey.name];
if (
adapter === null ||
typeof adapter !== "object" ||
@@ -255,7 +251,7 @@ function bindTurnCallerContext(
subagentName: caller.subagentName,
};
return {
- ...withActivity,
+ ...serializedContext,
[ChannelKey.name]: {
...adapter,
state: nextState,
diff --git a/packages/eve/src/subagents/tool.ts b/packages/eve/src/subagents/tool.ts
index 66fa18558..283381245 100644
--- a/packages/eve/src/subagents/tool.ts
+++ b/packages/eve/src/subagents/tool.ts
@@ -2,7 +2,6 @@ import { SUBAGENT_ADAPTER_KIND } from "#subagents/adapter-state.js";
import { formatSubagentInput, type SubagentParentContext } from "#subagents/invocation.js";
import type { JsonObject } from "#shared/json.js";
import type {
- ActivityObserverConfig,
ChannelInstrumentationProjection,
RunSessionLimits,
SessionAuthContext,
@@ -81,7 +80,6 @@ export function buildSubagentRunInput(input: {
/** Session token limits the child inherits. */
readonly limits: RunSessionLimits;
readonly parent: SubagentParentContext;
- readonly activityObserver?: ActivityObserverConfig;
readonly session: Pick<HarnessSession, "continuationToken" | "sandboxState" | "sessionId">;
readonly source: SubagentInputSource;
}): SubagentRunInputBuild {
@@ -138,7 +136,6 @@ export function buildSubagentRunInput(input: {
conversationId: input.parent.conversationId,
parent: input.parent.lineage,
parentTraceContext: input.parent.traceContext,
- activityObserver: input.activityObserver,
};
return { childContinuationToken, runInput };
}
diff --git a/research/slack-task-cards.md b/research/slack-task-cards.md
new file mode 100644
index 000000000..35b996537
--- /dev/null
+++ b/research/slack-task-cards.md
@@ -0,0 +1,459 @@
+---
+issue: https://github.com/vercel/eve/pull/4028
+status: implemented
+last_updated: "2026-09-30"
+---
+
+# Slack task cards and composable rendering
+
+This plan, implemented in [#4028](https://github.com/vercel/eve/pull/4028), redesigns what a person sees when an eve agent works in a Slack thread, built around
+[tasks](../docs/tools/tasks.md) and Slack's task card and plan blocks. It also separates inbound
+handling (`onAppMention`, `onDirectMessage`, `onMessage`, `onEvent`) from rendering, and replaces
+both the `events` map and the experimental activity renderers with one chain of renderers that
+wraps eve's defaults. Paths are relative to `packages/eve/src/`.
+
+## Summary
+
+1. **Each task a root turn starts gets a live row in a task card.** When a turn starts its first
+ task, eve posts one message in the thread and keeps it updated. One task renders as a
+ `task_card` block, and two or more render as a `plan` block. Each row shows the task's title,
+ its status, and a one-line result when it settles. Tasks that an agent task starts on its own
+ add no rows.
+2. **Short work stays in the status line.** Thinking, ordinary tool calls, and waits use Slack's
+ thread status. They never post messages, so the thread holds only the conversation and the
+ task card.
+3. **The card is a posted message that eve updates, not a stream.** Tasks can run for minutes or
+ days. Slack stops streams after a few minutes, and `chat.update` fails while a stream is open.
+ So eve posts the card with `chat.postMessage` and changes it with `chat.update`.
+4. **eve's default message hooks don't render.** A message hook decides whether to start a turn
+ and with what auth, and eve's rendering no longer depends on which hook ran. A custom hook can
+ still post through its context, but it no longer has to recreate eve's rendering. The `Thinking...` acknowledgement moves from `defaultOnAppMention` into eve's default
+ renderer, so a custom `onAppMention` keeps it. It is optimistic: it appears the moment a
+ mention or DM arrives, while the hook is still deciding, and eve clears it if the hook drops the
+ message.
+5. **Rendering is a chain.** `slackChannel({ renderers: [a, b] })` wraps eve's default renderer.
+ Each event handler receives `next`, so it can run before or after the default, change its
+ input, or skip it. `taskCard(view, next)` is a pure function that returns blocks; eve owns
+ posting and updating. The view carries every tool call of the turn with its
+ input, so an app can put its own tools on the card, such as a checklist, without eve knowing
+ about them.
+6. **The card renders from the root session's own events.** The root session's Slack channel
+ tracks its turns' calls and writes the card itself. The experimental activity renderers and the
+ activity collector behind them are removed: no extra workflow runs per session, and cards
+ follow the session across deploys. A collector may return later, designed from scratch, for
+ what only other sessions can see, such as an agent task's own progress.
+
+## Before this change
+
+Three separate mechanisms write to a Slack thread, and nothing in the default setup shows tasks.
+
+| Mechanism | Runs | Sees | Default |
+| --------------------------------------------------------------- | --------------------------------------------------- | ------------------------------------------------- | ------- |
+| Message hooks (`defaultOnAppMention`, `defaultOnDirectMessage`) | Inbound webhook, before the runtime starts | The Slack message | Yes |
+| `events` handlers (`defaults.ts`) | Inline, while the root session publishes each event | The root session's events, but no `task.*` events | Yes |
+| Activity collector plus renderers (`execution/activity-*.ts`) | Separate durable workflow for each root session | Root, child, and remote agent activity, debounced | No |
+
+**The default experience.** eve posts `Thinking...` from the default mention and DM hooks. Then
+`turn.started`, `reasoning.appended`, and `actions.requested` update the thread status through
+`assistant.threads.setStatus`, and `message.completed` posts replies. `ChannelEvents`
+(`public/definitions/channel.ts`) has no `task.started`, `task.settled`, or `turn.waiting`. A turn
+held on tasks therefore shows its last status until Slack clears it after two minutes, and then
+nothing until the next reply.
+
+**The experimental renderers** (`public/channels/slack/activity.ts`, `activity-plan.ts`) are
+exported but not documented. The first renderer in `activity.renderers` starts the collector.
+Child and remote agent sessions send it activity batches over HTTP, and it re-renders at most every
+350 ms.
+
+- `experimental_slackActivityStatus()` drives the status line from the collector. When it is
+ present, `slackChannel` silently swaps out the default `turn.started`, `reasoning.appended`,
+ `actions.requested`, and `message.completed` handlers (`slackChannel.ts`).
+- `experimental_slackActivityTree()` posts a Unicode tree, one message per root turn, capped at
+ 20 lines. To recover its message it scans `conversations.replies`, which needs history scopes
+ the default manifest doesn't request.
+- `experimental_slackActivityPlan()` opens a `chat.startStream` in plan mode for each root turn
+ and keeps it open until all of the turn's work settles. It appends child steps to the parent
+ row's `details`, then stops the stream and replaces it with a `plan` block through
+ `chat.update`. Its plan title is always `Agent activity`, the root row reads `Agent turn`, and
+ cancelled work renders as `error`.
+- `experimental_slackActivityRenderer({ id, render, dispose })` gives authors the raw
+ `ActivitySnapshotV1`, including `pendingSettlements` and `seenEventIds`. Authors must make every
+ Slack call themselves and track their own message state.
+
+**Coupling problems.**
+
+1. **Routing decides rendering.** The default mention and DM hooks both derive auth and post
+ `Thinking...`. A custom `onAppMention` for gating or auth drops the acknowledgement. The
+ doc comment even says "replacing this replaces both". An authored `onMessage` catches mentions
+ and DMs too, so it drops the acknowledgement for them as well.
+2. **Overriding means replacing.** `events["message.completed"]` replaces reply posting. To add a
+ footer or feedback buttons, an author has to re-implement long-reply snippet uploads.
+ `input.requested`, with its `defaultDeliver`, is the only handler that composes.
+3. **Options interact in hidden ways.** Adding a status renderer changes which event handlers
+ run.
+4. **Custom activity rendering is too low-level.** Authors see eve's internal reduction state.
+ They must handle `ts`, rate limits, streams, and recovery, and can't build on eve's default.
+
+## What Slack offers
+
+A [parallel research pass](#sources) checked Slack's reference pages and SDK source on 2026-09-30.
+These are the facts that shape this design.
+
+- **`task_card` block:** `task_id`, `title`, `status`, optional `details` and `output` (one
+ `rich_text` block each), and `sources` (URL elements). `status` is `pending`, `in_progress`,
+ `complete`, or `error`. There is no `cancelled` status and no nesting.
+- **`plan` block:** a `title` and up to 50 tasks, each a task card without `type`.
+- **Streams** (`chat.startStream`, `appendStream`, `stopStream`) send `task_update` and
+ `plan_update` chunks, whose text is limited to 256 characters. Streams are thread replies. In
+ channels they need `recipient_user_id` and `recipient_team_id`. `chat.update` on a message that
+ is still streaming fails with `streaming_state_conflict`. Slack documents no stream lifetime.
+ Developers report streams being stopped server-side after about 30 seconds idle, or about 5
+ minutes in total. After that, the message shows a permanent error pill.
+- **Posted blocks:** the Node SDK types accept `task_card` and `plan` in `chat.postMessage`, and
+ the removed plan renderer already sent a `plan` block through `chat.update`. No Slack page
+ explicitly confirms that these blocks render outside a stream; confirming it in a workspace is
+ part of this change's manual validation.
+- **Update rate:** `chat.update` is Tier 3 (50+ per minute for each workspace), and Slack's agent
+ design guide says to update at most once every 3 seconds.
+- **Status:** `assistant.threads.setStatus` takes up to 10 `loading_messages`. The status clears
+ when the app replies, or after 2 minutes. Its replacement, `agents.sessions.setStatus`, keeps
+ `processing` for an hour and enables Slack's native stop button.
+- **Design guidance:** plans suit multi-step work where the agent makes decisions. Each step
+ should be one short phrase, and plans should stay visually secondary to the final answer.
+ Failures should keep partial progress visible.
+
+## The default experience
+
+Alice asks in a channel thread. The agent answers one question directly, then delegates two
+long pieces of work as tasks.
+
+```text
+Alice @eve why did checkout latency spike yesterday?
+ [status] eve is thinking...
+ [status] eve is searching logs "checkout p99"...
+eve ┌ Working on 2 tasks ───────────────────────────────────────────────┐
+ │ ◐ Deploy history for storefront │
+ │ ◐ researcher: Find the incidents behind the checkout spike │
+ │ Reading INC-2291 postmortem │
+ └────────────────────────────────────────────────────────────────┘
+eve Checking recent deploys and incident notes in parallel; I'll report back.
+ [status] eve is waiting on deploy and 1 more task...
+```
+
+Later, the same card message has been updated in place, and the answer follows below it:
+
+```text
+eve ┌ Finished 2 tasks ─────────────────────────────────────────────────┐
+ │ ✓ Deploy history for storefront │
+ │ 3 deploys; 14:02 changed the cache TTL │
+ │ ✓ researcher: Find the incidents behind the checkout spike │
+ │ INC-2291: cache stampede after the 14:02 deploy │
+ └───────────────────────────────────────────────────────────────┘
+eve The spike started at 14:04, two minutes after deploy dpl_8f2...
+```
+
+### Status line
+
+The status line shows work that finishes within a step. The default renderer owns it:
+
+| Moment | Status |
+| -------------------------------------- | ------------------------------------------------------ |
+| A mention or DM arrives (webhook side) | `Thinking...`, right away, while the message hook runs |
+| The message hook drops the message | Cleared |
+| `turn.started` | `Working...` |
+| `reasoning.appended` | First line of the reasoning, throttled as before |
+| `actions.requested` | The model's narration, or the action label, as before |
+| `turn.waiting`, tasks working | `Waiting on researcher and 2 more tasks...` |
+| A reply posts | Cleared by Slack |
+
+The status names the waiting turn's working tasks by tool or agent name. Slack clears a status
+after two minutes without a message, and nothing runs in the root session while it waits, so the
+status is short-lived by design: the task card is the long-lived signal during a long wait.
+
+### Task card
+
+- **One card for each root turn that starts a task.** The root session posts it on the turn's
+ first `task.started`, then updates it in place until the turn and its tasks finish. A resumable
+ task continued in a later turn shows up in that turn's card as a new call.
+- **Rows are the root turn's own task calls.** What an agent task or workflow run does on the
+ task's behalf, including tasks it starts, happens in other sessions and adds no rows.
+- **Block choice.** One task renders as a standalone `task_card`, and a second task turns the
+ message into a `plan`. More than 50 calls in one turn collapse the oldest settled ones into a
+ single `N tasks finished earlier` row.
+- **Plan title**, first match wins: `Waiting for approval`, `Waiting for a response`, or
+ `Waiting for sign-in` while any task is blocked on a person; `Working on N tasks`, or
+ `D of N tasks done` once some have settled; `Finished N tasks`, or
+ `Finished N tasks: F failed, S stopped`, naming only the counts that aren't zero.
+- **Rows:**
+
+| Field | Tool task | Agent task |
+| -------- | -------------------------------------------------------------------------------------------- | ------------------------------------------------ |
+| `title` | `label.start(input)`, else the tool name | `name: first line of message` |
+| `status` | `in_progress` while working or blocked; `complete`; `error` for failed or cancelled | Same |
+| `output` | First line of a string result; `Failed`, with the error's first line when private; `Stopped` | First line of the agent's reply; same for errors |
+
+Titles are capped at 80 characters and `output` at 200.
+
+- **Blocked rows.** A request or sign-in a task's run relays through the root carries the task's
+ `taskId`, so its row shows `Waiting for approval`, `Waiting for a response`, or `Waiting for
+sign-in` in `details`. The row goes back to working on the request's `input.resolved`, the
+ sign-in's `authorization.completed`, or the task's `task.settled`. The request itself posts
+ wherever `approvalChannel` sends it.
+- **Requests stay where `approvalChannel` sends them.** A blocked row names the request's prompt
+ only in a DM or private channel. Elsewhere `blockedOn` carries only its kind, since a request
+ sent to one person by DM would otherwise show in the shared thread.
+
+- **Failure text stays private.** In a DM or private channel, a failed row shows `Failed: ` and
+ the first line of `task.settled.error.message`. Error text can carry internal hostnames or
+ identifiers, so other channels show `Failed` alone. The view leaves a failed task's `summary`
+ out there too, so a custom `taskCard` can't leak it by accident.
+- **Stopped is not success.** Slack has no cancelled status. A cancelled row uses `error` with the
+ output `Stopped`, so it never shows a success check. The plan title counts stopped tasks
+ separately from failed ones.
+- **Writes are per card, and only on change.** eve fingerprints the card and writes it only when
+ it changed. A failed post or update is tried once more after a second; if that fails too, the
+ card keeps its last fingerprint, so the turn's next change writes it again. An update that fails
+ with `message_not_found`, because someone deleted the card, posts it again. Posts set
+ `unfurl_links` and `unfurl_media` to `false`.
+- **Where it doesn't appear:** schedule turns, which post only their final reply, and sessions
+ without a Slack thread.
+
+## Authoring API
+
+### Inbound handlers route; renderers render
+
+Message hooks keep their signatures and return values, and eve's default hooks post nothing. `defaultOnMessage`
+only derives auth. Acknowledging a message is rendering, so it belongs to the renderer chain's
+`received` handler:
+
+- **Mentions and DMs** are addressed to the agent. eve runs `received` on the webhook side as soon
+ as the message passes signature and self-message checks, at the same time as the message hook.
+ The default sets `Thinking...`, before the hook's auth work and before the runtime cold-starts.
+- **Other channel messages** reach `onMessage`, which drops most of them. For those, `received`
+ runs only after the hook dispatches, so unrelated messages never flash a status.
+- **A dropped message is cleared.** If the hook returns `null` or throws, eve clears the thread
+ status once `received` finishes. Anything else a custom `received` posted is its own to clean up.
+
+### Renderers
+
+```ts
+import { defineSlackRenderer, slackChannel } from "eve/channels/slack";
+
+const feedback = defineSlackRenderer({
+ events: {
+ async "message.completed"(event, channel, _ctx, next) {
+ await next(); // eve posts the reply, or uploads a long one as a snippet
+ if (event.finishReason !== "tool-calls") await channel.thread.post(feedbackButtons());
+ },
+ },
+ taskCard(view, next) {
+ const card = next(view); // eve's default blocks and fallback text
+ if (card === null || view.state !== "finished") return card;
+ return { ...card, blocks: [...card.blocks, costContext(view)] };
+ },
+});
+
+export default slackChannel({
+ onAppMention(ctx, message) {
+ return isAllowed(message) ? { auth: slackAuth(message) } : null; // routing and auth only
+ },
+ renderers: [feedback],
+});
+```
+
+- **`renderers`** is an ordered list. The first renderer is outermost, and eve's default renderer
+ is always innermost. Omitting `renderers` renders with the default alone, so a channel with no
+ renderers looks exactly like eve's default. `events` is removed.
+- **A renderer** has three optional parts: `received(message, channel, next)`, `events`, and
+ `taskCard(view, next)`. Every message eve writes to Slack goes through one of them.
+- **Event handlers** receive `(data, channel, ctx, next)`; `session.failed` receives
+ `(data, channel, next)`. `next()` runs the rest of the chain with the same data and
+ `next(data)` with changed data. The rest of the chain runs at most once. Not calling `next`
+ skips it, so an old `events` override moves into `renderers: [{ events }]` unchanged.
+- **The private sign-in rule holds.** A renderer's `authorization.required` handler receives only
+ `postEphemeral`, `postDirectMessage`, and `state`. Its `next` reaches eve's default, which keeps
+ the full context and posts the public link-free status.
+- **`taskCard`** is synchronous and pure, and runs for every root turn that calls a tool. It
+ returns `{ blocks, text }`, or `null` for no card; eve's default returns `null` for a turn that
+ started no tasks.
+ eve compares the result with what it last wrote and posts or updates the message. A `taskCard`
+ that throws leaves that turn's card as it was.
+- **New channel events.** `ChannelEvents` gains `task.started`, `task.settled`, `turn.waiting`,
+ and `input.resolved`, so every channel can observe tasks inline and learn when each request
+ ends, however it ended. `input.resolved` already existed for clients and hooks; channels
+ couldn't handle it.
+
+### The task card view
+
+`taskCard` receives the channel-neutral view eve's default renders from
+(`channel/task-card.ts`):
+
+```ts
+interface TaskCardView {
+ readonly turnId: string;
+ readonly state: "working" | "blocked" | "finished";
+ readonly tasks: readonly TaskCardTask[]; // in call order
+ readonly actions: readonly TaskCardAction[]; // the turn's other tool calls, in call order
+}
+
+type TaskCardStatus = "working" | "completed" | "failed" | "cancelled";
+
+interface TaskCardTask {
+ readonly id: string; // the call id; a resumable task called twice has two rows
+ readonly taskId: string;
+ readonly kind: "agent" | "tool";
+ readonly name: string;
+ readonly title: string;
+ readonly status: TaskCardStatus | "blocked";
+ readonly blockedOn?: {
+ readonly kind: "approval" | "input" | "authorization";
+ readonly label?: string; // only in a private conversation
+ };
+ readonly summary?: string; // a failure's only in a private conversation
+ readonly startedAt: string;
+ readonly settledAt?: string;
+}
+
+interface TaskCardAction {
+ readonly id: string;
+ readonly name: string;
+ readonly title: string;
+ readonly status: TaskCardStatus;
+ readonly input?: Readonly<Record<string, unknown>>; // left out past 4,096 characters of JSON
+ readonly startedAt: string;
+ readonly settledAt?: string;
+}
+```
+
+A card is `blocked` while any task waits on a person, `working` while its turn or any other task
+works, then `finished`.
+
+## Architecture
+
+Everything renders in the root session, from the events it already publishes. The same renderer
+chain defines every message.
+
+```text
+Slack webhook ─┬─► renderers.received ─► status: Thinking... (right away)
+ └─► message hook (route, auth) ─► dispatch, or drop and clear status
+
+root session ─ own events ─► renderers.events ─► replies, questions, sign-ins, errors, status
+ │
+ └─► task card tracking (actions.requested, action.result, task.started,
+ task.settled, relayed requests and their resolutions, turn end)
+ ─► renderers.taskCard(view) ─► post, then update
+```
+
+**Invariants:**
+
+1. **No extra work outside the session.** The card is tracked in the Slack channel's state, which
+ the root session persists with every step. No workflow, route, or sink exists for it, so a
+ session that never starts a task pays one `taskCard` call per tool-call event and nothing else.
+2. **One writer per card.** Only the root session writes, and its steps run one after another. The
+ card's `ts` and a fingerprint of what eve last wrote live next to the turn's calls, so there is
+ no `conversations.replies` scan and no history scope.
+3. **Tracking can't be skipped.** Tracking and writing wrap the renderer chain's handlers for
+ those events, so a renderer that replaces eve's default for one of them still gets a card.
+4. **Cards follow the session.** Rendering is session code, so after a deploy a handed-off session
+ renders with the new deployment's code, and there is nothing pinned to the old one.
+5. **Rendering never fails a turn.** A failed write is retried once, then logged; the turn's next
+ change writes the card again.
+6. **State stays bounded.** eve forgets a turn once its card is finished, tracks at most 20
+ unfinished turns and 100 calls per turn, and keeps a call's input only up to 4,096 characters
+ of JSON.
+
+## Alternatives considered
+
+- **A streamed plan for each turn** (the removed plan renderer). This is Slack's native pattern for
+ short turns, but tasks outlive streams, and a stopped stream leaves a permanent error pill.
+- **Render the card in the activity collector,** a separate durable workflow per root session that
+ child and remote sessions report to over HTTP. It is the only way to show an agent task's own
+ steps and to refresh the status during a long wait. It also runs a second
+ workflow per session, stays pinned to the deployment that started it for up to the session
+ timeout (30 days by default), and has to accept activity from newer code after a handoff. The
+ first versions of this change used it; rendering from the root's own events keeps what people
+ asked for with far less. A collector may return, designed from scratch, for what only other
+ sessions can see.
+- **Let subagents call the channel's handlers.** The card's state belongs to the root session, and
+ `chat.update` rewrites the whole message, so parallel agents writing their own rows would
+ overwrite each other with stale rows. Remote agents can't run the app's handlers at all.
+- **Keep custom activity renderers public.** That exposes reduction internals, makes every author
+ handle `ts`, rate limits, and recovery, and offers no way to build on eve's card.
+- **`preventDefault` instead of `next`.** Authors could neither change the default's input nor
+ choose to run before or after it. `next` matches the old `defaultDeliver`.
+
+## Removed and changed
+
+Everything below is breaking, which is allowed before 1.0.
+
+- **Removed:** `slackChannel({ activity })`, `experimental_slackActivityStatus`,
+ `experimental_slackActivityTree`, `experimental_slackActivityPlan`,
+ `experimental_slackActivityRenderer`, the `ExperimentalSlackActivity*` types,
+ `SlackChannelEvents`, `SlackInputRequestedHandler`, `SlackInputRequestedDefaultDeliver`,
+ `SlackInputRequestedEvent`, and `SlackAuthorizationRequiredHandler`.
+- **`events` → `renderers`:** `events: { … }` becomes `renderers: [{ events: { … } }]`, with the
+ same behavior. `input.requested`'s `defaultDeliver` becomes `next`.
+- **Message hooks:** the default mention and DM hooks no longer post `Thinking...`. The default
+ renderer's `received` does, right away for mentions and DMs, whichever hook handles them.
+- **Channel core:** `ChannelEvents` gains `task.started`, `task.settled`, `turn.waiting`, and
+ `input.resolved`.
+- **Removed: the activity collector** and everything that fed it: the `/eve/v1/activity` route,
+ the activity protocol and reducer, the per-step activity posting, and the `activityObserver`
+ field on delegated and remote-agent sessions. A remote-agent request from an older eve that still
+ sends `activityObserver` is accepted, and the field is ignored.
+- **New default output:** task cards, and the `Waiting on ...` status.
+
+## Follow-ups
+
+- **Settlement labels.** `label.complete(input, output)` runs on a task's receipt today, not its
+ result. Running it at settlement needs the tool definition where the call settles; until then,
+ summaries come from the result text.
+- **What only other sessions see.** An agent task's own steps and a status that stays up during a
+ long wait need something besides the root session. Revisit a collector, or another mechanism,
+ designed from scratch for these.
+- **Answered cards from `input.resolved`.** Slack marks a question card answered when someone
+ clicks it. A plain-text answer or a withdrawn question leaves its buttons; the default handler
+ could mark the card from `input.resolved` instead.
+- **Tool task progress.** A task run's `action.partial` carries no `label.delta`, so a tool task
+ row shows no progress.
+- **Agent sessions.** Move status to `agents.sessions.setStatus`, which keeps `processing` for an
+ hour, and map Slack's native stop button (`agent_session_stopped`) to `session.cancel()`.
+- **Streamed replies.** Stream reply text with `chat.startStream` for turns that start no tasks.
+- **Stop controls on the card.** A `context_actions` stop button that cancels the turn.
+- **Templates.** The personal agent template sets `Thinking…` in its message hooks; remove it once
+ the template moves to a release with `received`.
+
+## Decisions
+
+When a choice was open, clarity for the person reading the thread decided it.
+
+1. **Failures show their reason where it's safe.** A bare `Failed` leaves people guessing, but
+ error text can carry internals. Rows show the error's first line in DMs and private channels,
+ and `Failed` alone elsewhere.
+2. **Stopped rows never look successful.** A cancelled task uses `error` with `Stopped`, and the
+ plan title counts it apart from failures.
+3. **The card has one writer.** The root session posts the card and owns every update, so there is
+ never a second message or a stale overwrite.
+4. **Acknowledging is rendering, and it is immediate.** `Thinking...` belongs to `received` in the
+ renderer chain, not to message hooks. It appears right away for mentions and DMs and is cleared
+ if the message is dropped.
+5. **Apps own their tools' presentation.** eve doesn't ship a checklist tool. The view carries the
+ turn's own tool calls with their input, so an app's `plan` tool, or any other, renders through
+ `taskCard` without a change to eve.
+
+## Sources
+
+- Slack: [task card block](https://docs.slack.dev/reference/block-kit/blocks/task-card-block),
+ [plan block](https://docs.slack.dev/reference/block-kit/blocks/plan-block),
+ [chat.startStream](https://docs.slack.dev/reference/methods/chat.startStream),
+ [chat.stopStream](https://docs.slack.dev/reference/methods/chat.stopStream),
+ [chat.update](https://docs.slack.dev/reference/methods/chat.update),
+ [assistant.threads.setStatus](https://docs.slack.dev/reference/methods/assistant.threads.setStatus),
+ [agents.sessions.setStatus](https://docs.slack.dev/reference/methods/agents.sessions.setStatus),
+ [agent design](https://docs.slack.dev/concepts/agent-design),
+ [2026-02-11 changelog](https://docs.slack.dev/changelog/2026/02/11/task-cards-plan-blocks),
+ [python-slack-sdk#1859](https://github.com/slackapi/python-slack-sdk/issues/1859) (stream
+ lifetime reports).
+- eve: `research/eve-tasks.md`, `docs/tools/tasks.md`, `docs/channels/slack.mdx`,
+ `channel/task-card.ts`, `public/channels/slack/{slackChannel,defaults,renderers,task-card}.ts`,
+ `cli/dev/tui/task-activity.ts`.