Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

[2/5] feat(eve): collect activity independently (#2294)

Ben Pankow3c8f2fe3d735
diff --git a/.changeset/tender-progress-collector.md b/.changeset/tender-progress-collector.md
new file mode 100644
index 000000000..d3fcda5a3
--- /dev/null
+++ b/.changeset/tender-progress-collector.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Collect and render activity independently from the root agent session.
diff --git a/packages/eve/src/channel/activity-renderer.ts b/packages/eve/src/channel/activity-renderer.ts
new file mode 100644
index 000000000..2afd30272
--- /dev/null
+++ b/packages/eve/src/channel/activity-renderer.ts
@@ -0,0 +1,55 @@
+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
new file mode 100644
index 000000000..7b062d166
--- /dev/null
+++ b/packages/eve/src/channel/activity-sink.test.ts
@@ -0,0 +1,24 @@
+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("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
new file mode 100644
index 000000000..f3d21c04c
--- /dev/null
+++ b/packages/eve/src/channel/activity-sink.ts
@@ -0,0 +1,28 @@
+import { z } from "#compiled/zod/index.js";
+
+import type { ActivitySinkV1 } from "#channel/types.js";
+import { EVE_ACTIVITY_ROUTE_PATTERN } from "#protocol/routes.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 token = url.pathname.slice(url.pathname.lastIndexOf(routePrefix) + routePrefix.length);
+ if (url.pathname.lastIndexOf(routePrefix) < 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 6ed63f55f..af8336d72 100644
--- a/packages/eve/src/channel/channel-address.test.ts
+++ b/packages/eve/src/channel/channel-address.test.ts
@@ -1,6 +1,10 @@
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 {
@@ -116,6 +120,43 @@ 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 },
+ }),
+ );
+ 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 4795fc80f..17cbc2b7c 100644
--- a/packages/eve/src/channel/channel-address.ts
+++ b/packages/eve/src/channel/channel-address.ts
@@ -1,6 +1,7 @@
import type { UserContent } from "ai";
import type { ChannelAdapter } from "#channel/adapter.js";
+import { copyChannelActivityPresentation } from "#channel/activity-renderer.js";
import {
createChannelDeliveryMetadata,
type ChannelDeliverySource,
@@ -135,10 +136,13 @@ 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 capabilities: RunInput["capabilities"] =
+ options.mode === "task" ? undefined : { requestInput: true };
const runInput: RunInput = {
adapter,
auth: options.auth,
- capabilities: options.mode === "task" ? undefined : { requestInput: true },
+ capabilities,
callback: options.callback,
channelName: input.channelName,
continuationToken: namespacedToken,
diff --git a/packages/eve/src/channel/compiled-channel.ts b/packages/eve/src/channel/compiled-channel.ts
index 7124fbe22..e4f71489b 100644
--- a/packages/eve/src/channel/compiled-channel.ts
+++ b/packages/eve/src/channel/compiled-channel.ts
@@ -1,4 +1,8 @@
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";
@@ -75,6 +79,14 @@ 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/types.ts b/packages/eve/src/channel/types.ts
index 522284d6b..13d67af62 100644
--- a/packages/eve/src/channel/types.ts
+++ b/packages/eve/src/channel/types.ts
@@ -373,6 +373,16 @@ export type HookPayload =
* terminal session result. Conversation sessions use this as their first turn's
* caller; each continuation supplies the caller for that turn.
*/
+export interface ActivitySinkV1 {
+ readonly url: string;
+ readonly version: 1;
+}
+
+export interface ActivityContextV1 {
+ readonly sink: ActivitySinkV1;
+ readonly workIdentity?: import("#protocol/activity.js").ActivityWorkIdentityV1;
+}
+
export interface SessionCallback {
readonly callId: string;
readonly subagentName: string;
@@ -456,6 +466,8 @@ export interface RunInput {
* the caller for their own turn.
*/
readonly callback?: SessionCallback;
+ /** Private collector capability and current work lineage. */
+ readonly activity?: ActivityContextV1;
/**
* Session continuation token for delivery and hook creation. Channels can
* re-key the session during the first turn via
diff --git a/packages/eve/src/context/keys.ts b/packages/eve/src/context/keys.ts
index 332c4bd7a..3f50c932c 100644
--- a/packages/eve/src/context/keys.ts
+++ b/packages/eve/src/context/keys.ts
@@ -9,8 +9,9 @@ import type { LanguageModel, ModelMessage, SystemModelMessage } from "ai";
import type { JsonObject } from "#shared/json.js";
import type { InstrumentationDecision } from "#shared/instrumentation-decision.js";
import type {
- ChannelInstrumentationProjection,
+ ActivityContextV1,
ChannelDeliveryMetadata,
+ ChannelInstrumentationProjection,
SessionAuthContext,
SessionCallback,
SessionCapabilities,
@@ -118,6 +119,7 @@ export const SubagentDepthKey = new ContextKey<number>("eve.subagentDepth");
* dispatch so HITL readiness flows through a conversation chain.
*/
export const CapabilitiesKey = new ContextKey<SessionCapabilities>("eve.capabilities");
+export const ActivityKey = new ContextKey<ActivityContextV1>("eve.activity");
/**
* Optional framework-owned caller callback captured when the session is created.
diff --git a/packages/eve/src/eve-channel/index.ts b/packages/eve/src/eve-channel/index.ts
index 33bb58d64..83288189b 100644
--- a/packages/eve/src/eve-channel/index.ts
+++ b/packages/eve/src/eve-channel/index.ts
@@ -6,6 +6,7 @@ import {
handleConnectionCallbackRequest,
handleLegacyConnectionCallbackRequest,
} from "#execution/connections/callback-route.js";
+import { handleActivityRequest } from "#execution/activity-route.js";
import { handleSessionCallbackRequest } from "#execution/session-callback-route.js";
import { handleTaskInputResponseRequest } from "#execution/task-input-response-route.js";
import { createLogger, logError } from "#internal/logging.js";
@@ -22,6 +23,7 @@ import {
type SubagentCalledStreamEvent,
} from "#protocol/message.js";
import {
+ EVE_ACTIVITY_ROUTE_PATTERN,
EVE_CALLBACK_ROUTE_PATTERN,
EVE_CONNECTION_CALLBACK_ROUTE_PATTERN,
EVE_HEALTH_ROUTE_PATH,
@@ -113,6 +115,7 @@ export function eveChannel(input: EveChannelInput): EveChannel {
POST(EVE_CONNECTION_CALLBACK_ROUTE_PATTERN, handleConnectionCallbackRequest),
GET(EVE_LEGACY_CONNECTION_CALLBACK_ROUTE_PATTERN, handleLegacyConnectionCallbackRequest),
POST(EVE_LEGACY_CONNECTION_CALLBACK_ROUTE_PATTERN, handleLegacyConnectionCallbackRequest),
+ POST(EVE_ACTIVITY_ROUTE_PATTERN, handleActivityRequest),
POST(EVE_CALLBACK_ROUTE_PATTERN, handleSessionCallbackRequest),
POST(EVE_TASK_INPUT_ROUTE_PATTERN, handleTaskInputResponseRequest),
diff --git a/packages/eve/src/execution/activity-collector.test.ts b/packages/eve/src/execution/activity-collector.test.ts
new file mode 100644
index 000000000..0bd40e339
--- /dev/null
+++ b/packages/eve/src/execution/activity-collector.test.ts
@@ -0,0 +1,50 @@
+import { describe, expect, it } from "vitest";
+
+import { reduceCollectorActivity } from "#execution/activity-collector.js";
+import { createActivitySnapshot } from "#execution/session-activity.js";
+
+const work = {
+ id: "root:work",
+ kind: "root-turn" as const,
+ rootSessionId: "session",
+ rootTurnId: "turn",
+};
+
+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
new file mode 100644
index 000000000..eabc20f3e
--- /dev/null
+++ b/packages/eve/src/execution/activity-collector.ts
@@ -0,0 +1,98 @@
+import { createHook, sleep } from "#compiled/@workflow/core/index.js";
+
+import {
+ claimHookOwnership,
+ closeHookIterator,
+ disposeHook,
+ 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 ownsHook = false;
+ 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 {
+ try {
+ await claimHookOwnership(batches);
+ ownsHook = true;
+ } catch (error) {
+ if (isHookConflictError(error)) return;
+ throw error;
+ }
+
+ 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) return;
+ pendingRead = undefined;
+ snapshot = reduceActivityBatch(snapshot, buffered.value.value);
+ }
+
+ const rendered = await renderSessionActivityStep({
+ rendererStates,
+ serializedContext: input.serializedContext,
+ snapshot,
+ });
+ rendererStates = rendered.rendererStates;
+ }
+ } finally {
+ if (ownsHook) {
+ await closeHookIterator(iterator).catch(() => {});
+ await disposeHook(batches).catch(() => {});
+ 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-route.test.ts b/packages/eve/src/execution/activity-route.test.ts
new file mode 100644
index 000000000..ad3415eda
--- /dev/null
+++ b/packages/eve/src/execution/activity-route.test.ts
@@ -0,0 +1,80 @@
+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
new file mode 100644
index 000000000..52abb995b
--- /dev/null
+++ b/packages/eve/src/execution/activity-route.ts
@@ -0,0 +1,50 @@
+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/runtime-context.test.ts b/packages/eve/src/execution/runtime-context.test.ts
index d92cb633b..e954bfa46 100644
--- a/packages/eve/src/execution/runtime-context.test.ts
+++ b/packages/eve/src/execution/runtime-context.test.ts
@@ -6,6 +6,7 @@ import {
ContinuationTokenKey,
type Session,
type SessionAuthContext,
+ ActivityKey,
SessionIdKey,
SessionKey,
ScheduleIdKey,
@@ -243,6 +244,32 @@ describe("buildRunContext", () => {
expect(ctx.get(SessionIdKey)).toBeUndefined();
});
+ it("seeds inherited private activity context", () => {
+ 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" },
+ mode: "task",
+ activity: { sink, workIdentity },
+ },
+ });
+
+ expect(ctx.get(ActivityKey)).toEqual({ sink, workIdentity });
+ });
+
it("grafts parent metadata onto the child's own kind", () => {
const parentProjection = {
kind: "channel:slack",
diff --git a/packages/eve/src/execution/runtime-context.ts b/packages/eve/src/execution/runtime-context.ts
index b8a722814..161ab4496 100644
--- a/packages/eve/src/execution/runtime-context.ts
+++ b/packages/eve/src/execution/runtime-context.ts
@@ -13,6 +13,7 @@ import {
ModeKey,
ParentSessionKey,
ParentTraceContextKey,
+ ActivityKey,
ScheduleIdKey,
SessionCallbackKey,
SubagentDepthKey,
@@ -75,6 +76,9 @@ export function buildRunContext(input: {
if (run.callback !== undefined) {
ctx.set(SessionCallbackKey, run.callback);
}
+ if (run.activity !== undefined) {
+ ctx.set(ActivityKey, run.activity);
+ }
if (run.parent !== undefined) {
ctx.set(ParentSessionKey, run.parent);
diff --git a/packages/eve/src/execution/session-activity-renderer-step.test.ts b/packages/eve/src/execution/session-activity-renderer-step.test.ts
new file mode 100644
index 000000000..98bdf0200
--- /dev/null
+++ b/packages/eve/src/execution/session-activity-renderer-step.test.ts
@@ -0,0 +1,58 @@
+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
new file mode 100644
index 000000000..3980427f5
--- /dev/null
+++ b/packages/eve/src/execution/session-activity-renderer-step.ts
@@ -0,0 +1,81 @@
+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-callback-request.test.ts b/packages/eve/src/execution/session-callback-request.test.ts
new file mode 100644
index 000000000..9e06cf7f2
--- /dev/null
+++ b/packages/eve/src/execution/session-callback-request.test.ts
@@ -0,0 +1,82 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import { postSessionCallbackRequest } from "#execution/session-callback-request.js";
+
+const callbackUrl = "https://agent.example.com/eve/v1/activity/opaque-token";
+const requestContextSymbol = Symbol.for("@vercel/request-context");
+const requestContextGlobal = globalThis as typeof globalThis & { [key: symbol]: unknown };
+
+describe("postSessionCallbackRequest", () => {
+ afterEach(() => {
+ delete requestContextGlobal[requestContextSymbol];
+ vi.unstubAllEnvs();
+ vi.unstubAllGlobals();
+ });
+
+ it("uses the request OIDC token for a callback to the current Vercel deployment", async () => {
+ vi.stubEnv("VERCEL", "1");
+ vi.stubEnv("VERCEL_PROJECT_PRODUCTION_URL", "agent.example.com");
+ requestContextGlobal[requestContextSymbol] = {
+ get: () => ({ headers: { "x-vercel-oidc-token": " trusted-token " } }),
+ };
+ const fetchMock = stubFetch();
+
+ await postSessionCallbackRequest({ body: { ok: true }, url: callbackUrl });
+
+ expect(fetchMock).toHaveBeenCalledWith(
+ callbackUrl,
+ expect.objectContaining({
+ headers: {
+ "content-type": "application/json",
+ "x-vercel-trusted-oidc-idp-token": "trusted-token",
+ },
+ }),
+ );
+ });
+
+ it("falls back to the deployment OIDC environment variable", async () => {
+ vi.stubEnv("VERCEL", "1");
+ vi.stubEnv("VERCEL_URL", "agent.example.com");
+ vi.stubEnv("VERCEL_OIDC_TOKEN", "environment-token");
+ const fetchMock = stubFetch();
+
+ await postSessionCallbackRequest({ body: { ok: true }, url: callbackUrl });
+
+ expect(
+ new Headers(fetchMock.mock.calls[0]?.[1]?.headers).get("x-vercel-trusted-oidc-idp-token"),
+ ).toBe("environment-token");
+ });
+
+ it.each([
+ ["a non-Vercel runtime", {}, callbackUrl],
+ [
+ "an external callback",
+ { VERCEL: "1", VERCEL_PROJECT_PRODUCTION_URL: "agent.example.com" },
+ "https://external.example.com/eve/v1/callback/token",
+ ],
+ [
+ "a non-HTTPS callback",
+ { VERCEL: "1", VERCEL_URL: "localhost:3000" },
+ "http://localhost:3000/eve/v1/activity/token",
+ ],
+ ])("does not attach ambient credentials for %s", async (_name, env, url) => {
+ vi.stubEnv("VERCEL_OIDC_TOKEN", "ambient-token");
+ for (const [key, value] of Object.entries(env)) vi.stubEnv(key, value);
+ const fetchMock = stubFetch();
+
+ await postSessionCallbackRequest({ body: { ok: true }, url });
+
+ expect(
+ new Headers(fetchMock.mock.calls[0]?.[1]?.headers).has("x-vercel-trusted-oidc-idp-token"),
+ ).toBe(false);
+ });
+});
+
+function stubFetch() {
+ const fetchMock = vi.fn(
+ async (_url: string | URL | Request, _init?: RequestInit) =>
+ new Response(null, { status: 202 }),
+ );
+ vi.stubGlobal("fetch", fetchMock);
+ return fetchMock;
+}
diff --git a/packages/eve/src/execution/session-callback-request.ts b/packages/eve/src/execution/session-callback-request.ts
index 3a13059f2..a3aa72b40 100644
--- a/packages/eve/src/execution/session-callback-request.ts
+++ b/packages/eve/src/execution/session-callback-request.ts
@@ -1,20 +1,58 @@
const SESSION_CALLBACK_TIMEOUT_MS = 30_000;
+const VERCEL_TRUSTED_OIDC_IDP_TOKEN_HEADER = "x-vercel-trusted-oidc-idp-token";
+const VERCEL_CALLBACK_HOST_ENVS = [
+ "VERCEL_URL",
+ "VERCEL_BRANCH_URL",
+ "VERCEL_PROJECT_PRODUCTION_URL",
+] as const;
+const VERCEL_REQUEST_CONTEXT = Symbol.for("@vercel/request-context");
/** Posts one framework callback payload with the shared callback transport policy. */
export async function postSessionCallbackRequest(input: {
readonly body: unknown;
+ readonly timeoutMs?: number;
readonly url: string;
}): Promise<Response> {
return await fetch(input.url, {
body: JSON.stringify(input.body),
- headers: {
- "content-type": "application/json",
- },
+ headers: await resolveSessionCallbackHeaders(input.url),
method: "POST",
// Do not follow redirects: a validated callback host could otherwise
// 3xx-bounce the framework to an internal/metadata address after the
// path/token check has already passed.
redirect: "error",
- signal: AbortSignal.timeout(SESSION_CALLBACK_TIMEOUT_MS),
+ signal: AbortSignal.timeout(input.timeoutMs ?? SESSION_CALLBACK_TIMEOUT_MS),
});
}
+
+async function resolveSessionCallbackHeaders(urlValue: string): Promise<Record<string, string>> {
+ const headers: Record<string, string> = { "content-type": "application/json" };
+ if (process.env.VERCEL !== "1") return headers;
+
+ let url: URL;
+ try {
+ url = new URL(urlValue);
+ } catch {
+ return headers;
+ }
+ const currentHost = VERCEL_CALLBACK_HOST_ENVS.some(
+ (name) => process.env[name]?.trim().toLowerCase() === url.hostname.toLowerCase(),
+ );
+ if (url.protocol !== "https:" || !currentHost) return headers;
+
+ const token = readAmbientVercelOidcToken();
+ if (token !== undefined) headers[VERCEL_TRUSTED_OIDC_IDP_TOKEN_HEADER] = token;
+ return headers;
+}
+
+function readAmbientVercelOidcToken(): string | undefined {
+ const requestContext = (
+ globalThis as typeof globalThis & {
+ [key: symbol]: { get?(): { headers?: Record<string, string> } } | undefined;
+ }
+ )[VERCEL_REQUEST_CONTEXT];
+ const token =
+ requestContext?.get?.().headers?.["x-vercel-oidc-token"] ?? process.env.VERCEL_OIDC_TOKEN;
+ const trimmed = token?.trim();
+ return trimmed === "" ? undefined : trimmed;
+}
diff --git a/packages/eve/src/execution/submit-activity.test.ts b/packages/eve/src/execution/submit-activity.test.ts
new file mode 100644
index 000000000..6e50c7a5c
--- /dev/null
+++ b/packages/eve/src/execution/submit-activity.test.ts
@@ -0,0 +1,44 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import { submitActivity } from "#execution/submit-activity.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());
+
+ 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 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,
+ });
+ });
+});
diff --git a/packages/eve/src/execution/submit-activity.ts b/packages/eve/src/execution/submit-activity.ts
new file mode 100644
index 000000000..06da84dce
--- /dev/null
+++ b/packages/eve/src/execution/submit-activity.ts
@@ -0,0 +1,28 @@
+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,
+ 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/workflow-runtime.test.ts b/packages/eve/src/execution/workflow-runtime.test.ts
index 102169484..768838f6a 100644
--- a/packages/eve/src/execution/workflow-runtime.test.ts
+++ b/packages/eve/src/execution/workflow-runtime.test.ts
@@ -1,15 +1,18 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { ChannelAdapter } from "#channel/adapter.js";
-import { ChannelRequestIdKey } from "#context/keys.js";
+import { attachChannelActivityPresentation } from "#channel/activity-renderer.js";
+import { ChannelRequestIdKey, ActivityKey } from "#context/keys.js";
import { resolveInstalledPackageInfo } from "#internal/application/package.js";
import {
createWorkflowRuntime,
LATEST_DEPLOYMENT_UNSUPPORTED_MESSAGE,
+ activityCollectorWorkflowReference,
sessionTimeoutWorkflowReference,
turnWorkflowReference,
workflowEntryReference,
} from "#execution/workflow-runtime.js";
+import { RuntimeSessionOwnershipConflictError } from "#execution/runtime-errors.js";
import { sessionCommandHookToken } from "#execution/session-command-token.js";
import { registerInstrumentationRuntime } from "#harness/instrumentation/runtime.js";
import { AgentSpanIdGenerator } from "#tracing/agent-span-id-generator.js";
@@ -37,7 +40,9 @@ vi.mock("#runtime/sessions/compiled-agent-cache.js", () => ({
}));
beforeEach(() => {
+ cancelRunMock.mockResolvedValue(undefined);
getHookByTokenMock.mockImplementation(async (token: string) => currentSessionHook(token));
+ getWorldMock.mockResolvedValue("world");
});
afterEach(() => {
@@ -70,6 +75,9 @@ describe("workflowEntryReference", () => {
);
expect(sessionTimeoutWorkflowReference.workflowId).not.toContain("/src/execution/");
expect(sessionTimeoutWorkflowReference.workflowId).not.toContain("@");
+ expect(activityCollectorWorkflowReference.workflowId).toBe(
+ `workflow//${packageInfo.name}//activityCollectorWorkflow`,
+ );
});
});
@@ -310,6 +318,15 @@ 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,
@@ -414,6 +431,125 @@ 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: "driver-run" });
+
+ await buildRuntime(compiledArtifactsSource).createSession({
+ adapter: activityAdapter(),
+ auth: null,
+ input: { message: "hello" },
+ mode: "conversation",
+ });
+
+ 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.serializedContext[ActivityKey.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: "driver-run" });
+
+ await buildRuntime(compiledArtifactsSource).createSession({
+ adapter: activityAdapter(),
+ auth: null,
+ input: { message: "hello" },
+ mode: "conversation",
+ });
+
+ 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 compiledArtifactsSource = {} as RuntimeCompiledArtifactsSource;
+ mockBundleAndRun(compiledArtifactsSource);
+ startMock
+ .mockRejectedValueOnce(new Error("collector failed"))
+ .mockResolvedValueOnce({ runId: "driver-run" });
+
+ await buildRuntime(compiledArtifactsSource).createSession({
+ adapter: activityAdapter(),
+ auth: null,
+ input: { message: "hello" },
+ mode: "conversation",
+ });
+
+ const workflowInput = startMock.mock.calls[1]?.[1][0];
+ expect(workflowInput.serializedContext[ActivityKey.name]).toBeUndefined();
+ });
+
+ it("cancels the collector when root workflow startup fails", async () => {
+ 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" },
+ mode: "conversation",
+ }),
+ ).rejects.toBe(failure);
+
+ expect(cancelRunMock).toHaveBeenCalledWith("world", "collector-run", {
+ cancelReason: "Root session creation did not complete",
+ });
+ });
+
+ it("cancels the collector when continuation ownership rejects the root candidate", async () => {
+ const compiledArtifactsSource = {} as RuntimeCompiledArtifactsSource;
+ mockBundleAndRun(compiledArtifactsSource);
+ startMock
+ .mockResolvedValueOnce({ runId: "collector-run" })
+ .mockResolvedValueOnce({ runId: "driver-run" });
+ getHookByTokenMock.mockResolvedValue({ runId: "other-run" });
+
+ await expect(
+ buildRuntime(compiledArtifactsSource).createSession({
+ adapter: activityAdapter(),
+ auth: null,
+ continuationToken: "slack:thread",
+ input: { message: "hello" },
+ mode: "conversation",
+ }),
+ ).rejects.toBeInstanceOf(RuntimeSessionOwnershipConflictError);
+
+ expect(cancelRunMock).toHaveBeenCalledWith("world", "collector-run", {
+ cancelReason: "Root session creation did not complete",
+ });
+ });
+
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 fb11419ac..e2f558468 100644
--- a/packages/eve/src/execution/workflow-runtime.ts
+++ b/packages/eve/src/execution/workflow-runtime.ts
@@ -1,3 +1,5 @@
+import { randomBytes } from "node:crypto";
+
import {
EntityConflictError,
HookNotFoundError,
@@ -5,6 +7,7 @@ import {
WorkflowRunNotFoundError,
} from "#compiled/@workflow/errors/index.js";
+import { getChannelActivityPresentation } from "#channel/activity-renderer.js";
import type {
CancelTurnInput,
CancelTurnResult,
@@ -19,6 +22,7 @@ import type {
SessionTraceContext,
} from "#channel/types.js";
import { serializeContext } from "#context/serialize.js";
+import { ActivityKey } from "#context/keys.js";
import {
ChannelInstrumentationKey,
OtelTraceEnabledKey,
@@ -34,8 +38,10 @@ import { resolveInstalledPackageInfo } from "#internal/application/package.js";
import { isEveDevEnvironment } from "#internal/application/dev-environment.js";
import { createLogger, logError } from "#internal/logging.js";
import {
+ cancelRun,
getHookByToken,
getRun,
+ getWorld,
start,
type Run,
type StartOptionsWithoutDeploymentId,
@@ -52,6 +58,12 @@ import { resolveEffectiveAgentRuntime } from "#execution/effective-agent-config.
import { parseNdjsonStream } from "#execution/ndjson-stream.js";
import { RuntimeSessionOwnershipConflictError } from "#execution/runtime-errors.js";
import type { WorkflowEntryInput } from "#execution/workflow-entry.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 { sessionCommandHookToken } from "#execution/session-command-token.js";
@@ -69,8 +81,10 @@ const WORKFLOW_ENTRY_NAME = "workflowEntry";
const TURN_WORKFLOW_NAME = "turnWorkflow";
const SESSION_TIMEOUT_WORKFLOW_NAME = "sessionTimeoutWorkflow";
const TASK_RUN_WORKFLOW_NAME = "taskRunWorkflow";
+const ACTIVITY_COLLECTOR_WORKFLOW_NAME = "activityCollectorWorkflow";
const EVE_PACKAGE_INFO = resolveInstalledPackageInfo();
const COMMAND_HOOK_READY_TIMEOUT_MS = 30_000;
+const DEFAULT_ACTIVITY_COLLECTOR_RETENTION_MS = 24 * 60 * 60 * 1_000;
export const LATEST_DEPLOYMENT_UNSUPPORTED_MESSAGE =
"deploymentId 'latest' requires a World that implements resolveLatestDeploymentId()";
@@ -90,6 +104,7 @@ export const STABLE_WORKFLOW_NAMES: ReadonlySet<string> = new Set([
TURN_WORKFLOW_NAME,
SESSION_TIMEOUT_WORKFLOW_NAME,
TASK_RUN_WORKFLOW_NAME,
+ ACTIVITY_COLLECTOR_WORKFLOW_NAME,
]);
const STABLE_ID_BASE = EVE_PACKAGE_INFO.name;
@@ -131,6 +146,11 @@ export const taskRunWorkflowReference = {
workflowId: `workflow//${STABLE_ID_BASE}//${TASK_RUN_WORKFLOW_NAME}`,
};
+/** Stable workflow reference for root-session activity collectors. */
+export const activityCollectorWorkflowReference = {
+ workflowId: `workflow//${STABLE_ID_BASE}//${ACTIVITY_COLLECTOR_WORKFLOW_NAME}`,
+};
+
/**
* Creates a workflow-backed runtime whose long-lived driver owns the
* event stream and dispatches each turn as a child workflow run.
@@ -163,9 +183,48 @@ export function createWorkflowRuntime(config: {
ctx.set(SessionTraceSeedKey, traceSeed);
}
ctx.set(OtelTraceEnabledKey, getInstrumentationRuntime()?.prepareSessionTrace !== undefined);
+ const sessionTimeoutMs = effectiveAgent.limits?.sessionTimeoutMs;
+ let collectorRunId: string | undefined;
+ if (
+ input.parent === undefined &&
+ input.activity === 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 startWorkflowPreferLatest(activityCollectorWorkflowReference, [
+ collectorInput,
+ ]);
+ collectorRunId = collector.runId;
+ const fallbackOrigin = process.env.VERCEL_URL
+ ? `https://${process.env.VERCEL_URL}`
+ : "http://localhost:3000";
+ const baseUrl = resolveWorkflowCallbackBaseUrl(fallbackOrigin);
+ ctx.set(ActivityKey, {
+ sink: {
+ url: createWorkflowCallbackUrl(baseUrl, createEveActivityRoutePath(token)),
+ version: 1,
+ },
+ });
+ } catch {
+ await cancelActivityCollector(collectorRunId);
+ collectorRunId = undefined;
+ log.warn("failed to start activity collector");
+ }
+ }
const serializedContext = serializeContext(ctx);
const parentLineage = readParentLineage(serializedContext);
- const sessionTimeoutMs = effectiveAgent.limits?.sessionTimeoutMs;
const workflowInput: {
-readonly [K in keyof WorkflowEntryInput]: WorkflowEntryInput[K];
} = {
@@ -204,23 +263,29 @@ export function createWorkflowRuntime(config: {
attributes: normalizeEveAttributes(attributes),
});
} catch (error) {
+ await cancelActivityCollector(collectorRunId);
logError(log, "failed to start workflow run", error, {
continuationToken: input.continuationToken,
});
throw error;
}
- if (input.continuationToken) {
- const owner = await waitForCommandHookOwner(input.continuationToken);
- if (owner.runId !== run.runId) {
- throw new RuntimeSessionOwnershipConflictError({
- continuationToken: input.continuationToken,
- ownerSessionId: owner.runId,
- sessionId: run.runId,
- });
+ try {
+ if (input.continuationToken) {
+ const owner = await waitForCommandHookOwner(input.continuationToken);
+ if (owner.runId !== run.runId) {
+ throw new RuntimeSessionOwnershipConflictError({
+ continuationToken: input.continuationToken,
+ ownerSessionId: owner.runId,
+ sessionId: run.runId,
+ });
+ }
}
+ await waitForOwnedCommandHook(sessionCommandHookToken(run.runId), run.runId);
+ } catch (error) {
+ await cancelActivityCollector(collectorRunId);
+ throw error;
}
- await waitForOwnedCommandHook(sessionCommandHookToken(run.runId), run.runId);
let events: ReadableStream<MessageStreamEvent> | undefined;
const getEvents = () => {
@@ -286,6 +351,17 @@ export function createWorkflowRuntime(config: {
};
}
+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,
command: TCommand,
diff --git a/packages/eve/src/protocol/routes.ts b/packages/eve/src/protocol/routes.ts
index 6de1a9aaa..1119342cf 100644
--- a/packages/eve/src/protocol/routes.ts
+++ b/packages/eve/src/protocol/routes.ts
@@ -121,6 +121,9 @@ export const EVE_CALLBACK_ROUTE_PATTERN = `${EVE_ROUTE_PREFIX}/callback/:token`;
/** Capability route used by a parent task to answer a remote child HITL batch. */
export const EVE_TASK_INPUT_ROUTE_PATTERN = `${EVE_ROUTE_PREFIX}/task-input/: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)}`;
@@ -189,3 +192,8 @@ 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/runtime/channels/registry.test.ts b/packages/eve/src/runtime/channels/registry.test.ts
index f381f779b..a3e22165a 100644
--- a/packages/eve/src/runtime/channels/registry.test.ts
+++ b/packages/eve/src/runtime/channels/registry.test.ts
@@ -1,7 +1,11 @@
-import { describe, expect, it } from "vitest";
+import { describe, expect, it, vi } 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 "#execution/subagent-adapter-state.js";
import { SUBAGENT_ADAPTER } from "#execution/subagent-adapter.js";
@@ -82,6 +86,28 @@ 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 97f47ebb4..c0630902a 100644
--- a/packages/eve/src/runtime/channels/registry.ts
+++ b/packages/eve/src/runtime/channels/registry.ts
@@ -1,5 +1,9 @@
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 "#execution/subagent-adapter.js";
@@ -129,10 +133,9 @@ export function deserializeRuntimeAdapter(
);
}
- // Merge the serialized state onto the adapter config. The behavior
- // functions come from the registry entry; the state comes from the
- // serialized context.
- return { ...adapterConfig, state: serialized.state };
+ const rehydrated: ChannelAdapter = { ...adapterConfig, state: serialized.state };
+ copyChannelActivityPresentation(adapterConfig, rehydrated);
+ return rehydrated;
}
function requireAdapterKind(
@@ -157,6 +160,8 @@ 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;
}