Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

[3/5] feat(eve): relay session events into activity (#2306)

Ben Pankow44c6af248b68
diff --git a/.changeset/gentle-progress-lifecycle.md b/.changeset/gentle-progress-lifecycle.md
new file mode 100644
index 000000000..a588bff96
--- /dev/null
+++ b/.changeset/gentle-progress-lifecycle.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Report root, delegated work, action, and blocker lifecycle to activity collectors.
diff --git a/packages/eve/extension-contracts/compatibility/channel/v11.ts b/packages/eve/extension-contracts/compatibility/channel/v11.ts
new file mode 100644
index 000000000..67e58f0bb
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/channel/v11.ts
@@ -0,0 +1,3 @@
+import { disableRoute } from "#public/channels/index.js";
+
+export default disableRoute();
diff --git a/packages/eve/extension-contracts/compatibility/schedule/v4.ts b/packages/eve/extension-contracts/compatibility/schedule/v4.ts
new file mode 100644
index 000000000..15ba030ed
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/schedule/v4.ts
@@ -0,0 +1,18 @@
+import channel from "../channel/v7.js";
+import { defineSchedule } from "#public/schedules/index.js";
+
+export default defineSchedule({
+ cron: "0 0 * * *",
+ async run({ appAuth, to, waitUntil }) {
+ waitUntil(
+ (async () => {
+ const session = await to(channel, { sessionRef: "daily" }).send("Start review", {
+ auth: appAuth,
+ });
+ await session.respond([{ optionId: "approve", requestId: "approval-1" }], {
+ auth: appAuth,
+ });
+ })(),
+ );
+ },
+});
diff --git a/packages/eve/extension-contracts/reports/channel/v12.json b/packages/eve/extension-contracts/reports/channel/v12.json
new file mode 100644
index 000000000..017948f3c
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/channel/v12.json
@@ -0,0 +1,21 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "channel",
+ "epoch": 12,
+ "sha256": "c223940055c42084d3f8cf572385db0a8339535531a2e7d7495cd99ef02ea9b6",
+ "exports": [
+ "DELETE",
+ "GET",
+ "HEAD",
+ "OPTIONS",
+ "PATCH",
+ "POST",
+ "PUT",
+ "WS",
+ "createWebSocketUpgradeServer",
+ "defineChannel",
+ "disableRoute",
+ "isChannel",
+ "isDisabledRouteSentinel"
+ ]
+}
diff --git a/packages/eve/extension-contracts/reports/schedule/v5.json b/packages/eve/extension-contracts/reports/schedule/v5.json
new file mode 100644
index 000000000..6f968d33f
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/schedule/v5.json
@@ -0,0 +1,14 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "schedule",
+ "epoch": 5,
+ "sha256": "ca258021035a67f3011f433247f2be036520baf6fbcd89bfd8014245e5f7f5b4",
+ "exports": [
+ "ScheduleDefinition",
+ "ScheduleHandlerArgs",
+ "ScheduleRunHandler",
+ "ScheduleToFn",
+ "TypedReceiveTarget",
+ "defineSchedule"
+ ]
+}
diff --git a/packages/eve/src/channel/session.ts b/packages/eve/src/channel/session.ts
index 48dbc3070..daae6c30b 100644
--- a/packages/eve/src/channel/session.ts
+++ b/packages/eve/src/channel/session.ts
@@ -6,6 +6,7 @@ import {
import type { MessageStreamEvent } from "#protocol/message.js";
import type { UserContent } from "ai";
import type {
+ ActivityObserverConfig,
CancelTurnResult,
ClearSessionResult,
CompactSessionResult,
@@ -55,6 +56,7 @@ export interface Session {
}
interface SessionDeliveryOptions {
+ readonly activityObserver?: ActivityObserverConfig;
readonly auth: SessionAuthContext | null;
/** Public callback destination for a delegated continuation turn. */
readonly callback?: SessionCallback;
@@ -93,7 +95,7 @@ export function createSession(
id,
async send(message, options) {
const delivery = createDelivery(metadata);
- const caller = sessionCallbackToTurnCaller(options.callback);
+ const caller = sessionCallbackToTurnCaller(options.callback, options.activityObserver);
const payload: {
context?: readonly string[];
message: string | UserContent | undefined;
@@ -119,7 +121,7 @@ export function createSession(
throw new Error("respond() requires at least one input response.");
}
const validatedInputResponses = parseInputResponses(inputResponses);
- const caller = sessionCallbackToTurnCaller(options.callback);
+ const caller = sessionCallbackToTurnCaller(options.callback, options.activityObserver);
const delivery = createDelivery(metadata);
const payload: {
context?: readonly string[];
@@ -233,10 +235,12 @@ 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/types.ts b/packages/eve/src/channel/types.ts
index 13d67af62..6fff33532 100644
--- a/packages/eve/src/channel/types.ts
+++ b/packages/eve/src/channel/types.ts
@@ -138,6 +138,7 @@ export type EventEmitFn = (event: UnstampedMessageStreamEvent) => Promise<void>;
/** Framework-internal caller waiting for one delegated conversation turn. */
export interface TurnCaller {
+ readonly activityObserver?: ActivityObserverConfig;
readonly callId: string;
readonly subagentName: string;
/** Present when this turn is the executor for a durable background task. */
@@ -378,7 +379,7 @@ export interface ActivitySinkV1 {
readonly version: 1;
}
-export interface ActivityContextV1 {
+export interface ActivityObserverConfig {
readonly sink: ActivitySinkV1;
readonly workIdentity?: import("#protocol/activity.js").ActivityWorkIdentityV1;
}
@@ -467,7 +468,7 @@ export interface RunInput {
*/
readonly callback?: SessionCallback;
/** Private collector capability and current work lineage. */
- readonly activity?: ActivityContextV1;
+ readonly activityObserver?: ActivityObserverConfig;
/**
* 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/compiler/extension-compatibility.ts b/packages/eve/src/compiler/extension-compatibility.ts
index baf1c4c69..5a746641d 100644
--- a/packages/eve/src/compiler/extension-compatibility.ts
+++ b/packages/eve/src/compiler/extension-compatibility.ts
@@ -31,8 +31,8 @@ const EXTENSION_CAPABILITY_CONTRACTS = {
supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21],
dropped: {},
},
- channel: { current: 11, supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], dropped: {} },
- schedule: { current: 4, supported: [1, 2, 3, 4], dropped: {} },
+ channel: { current: 12, supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], dropped: {} },
+ schedule: { current: 5, supported: [1, 2, 3, 4, 5], dropped: {} },
subagent: {
current: 5,
supported: [3, 4, 5],
diff --git a/packages/eve/src/context/keys.ts b/packages/eve/src/context/keys.ts
index 3f50c932c..0483587bb 100644
--- a/packages/eve/src/context/keys.ts
+++ b/packages/eve/src/context/keys.ts
@@ -9,7 +9,7 @@ import type { LanguageModel, ModelMessage, SystemModelMessage } from "ai";
import type { JsonObject } from "#shared/json.js";
import type { InstrumentationDecision } from "#shared/instrumentation-decision.js";
import type {
- ActivityContextV1,
+ ActivityObserverConfig,
ChannelDeliveryMetadata,
ChannelInstrumentationProjection,
SessionAuthContext,
@@ -119,7 +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");
+export const ActivityObserverKey = new ContextKey<ActivityObserverConfig>("eve.activityObserver");
/**
* 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
new file mode 100644
index 000000000..fff4d9932
--- /dev/null
+++ b/packages/eve/src/eve-channel/activity-observer-request.ts
@@ -0,0 +1,55 @@
+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/index.ts b/packages/eve/src/eve-channel/index.ts
index 83288189b..b7656fece 100644
--- a/packages/eve/src/eve-channel/index.ts
+++ b/packages/eve/src/eve-channel/index.ts
@@ -194,6 +194,7 @@ export function eveChannel(input: EveChannelInput): EveChannel {
let handle: Awaited<ReturnType<typeof createSession>>;
try {
handle = await createSession({
+ activityObserver: body.activityObserver,
auth: messageResult.auth,
capabilities:
body.capabilities ?? (body.mode === "task" ? undefined : { requestInput: true }),
@@ -282,6 +283,7 @@ export function eveChannel(input: EveChannelInput): EveChannel {
try {
const session = attachSession(sessionId);
const options = {
+ 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
new file mode 100644
index 000000000..80d1232fc
--- /dev/null
+++ b/packages/eve/src/eve-channel/request.activity.test.ts
@@ -0,0 +1,67 @@
+import { describe, expect, it } from "vitest";
+
+import { parseCreateBody } from "#eve-channel/request.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",
+ }),
+ ).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",
+ });
+ 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",
+ });
+ expect(response).toBeInstanceOf(Response);
+ expect((response as Response).status).toBe(400);
+ });
+});
diff --git a/packages/eve/src/eve-channel/request.ts b/packages/eve/src/eve-channel/request.ts
index 773044f75..bf0804907 100644
--- a/packages/eve/src/eve-channel/request.ts
+++ b/packages/eve/src/eve-channel/request.ts
@@ -1,6 +1,7 @@
import type { FilePart, TextPart, UserContent } from "ai";
import type {
+ ActivityObserverConfig,
SessionAuthContext,
SessionCallback,
SessionCapabilities,
@@ -8,6 +9,10 @@ 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,
@@ -28,6 +33,7 @@ import { parseJsonObject, type JsonObject } from "#shared/json.js";
import type { RunMode } from "#shared/run-mode.js";
interface ParsedCreateBody {
+ activityObserver?: ActivityObserverConfig;
callback?: SessionCallback;
capabilities?: SessionCapabilities;
message: string | UserContent;
@@ -76,6 +82,13 @@ export function parseCreateBody(payload: Record<string, unknown>): ParsedCreateB
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 mode = parseModeField(payload.mode);
if (mode instanceof Response) return mode;
@@ -98,6 +111,7 @@ export function parseCreateBody(payload: Record<string, unknown>): ParsedCreateB
}
const result: ParsedCreateBody = {
+ activityObserver,
callback,
capabilities,
message,
@@ -110,6 +124,7 @@ export function parseCreateBody(payload: Record<string, unknown>): ParsedCreateB
}
interface ParsedSessionMessageBody {
+ activityObserver?: ActivityObserverConfig;
callback?: SessionCallback;
message?: string | UserContent;
inputResponses?: readonly ValidatedInputResponse[];
@@ -128,6 +143,12 @@ 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);
@@ -154,7 +175,15 @@ export function parseSessionMessageBody(
);
}
- return { callback, message, inputResponses, context, outputSchema, turnPolicy };
+ return {
+ activityObserver,
+ callback,
+ message,
+ inputResponses,
+ context,
+ outputSchema,
+ turnPolicy,
+ };
}
interface ParsedCancelTurnBody {
diff --git a/packages/eve/src/execution/activity-events.test.ts b/packages/eve/src/execution/activity-events.test.ts
new file mode 100644
index 000000000..33405bdad
--- /dev/null
+++ b/packages/eve/src/execution/activity-events.test.ts
@@ -0,0 +1,234 @@
+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 "#execution/activity-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" },
+ ],
+ 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({
+ action: expect.objectContaining({
+ id: "action:work:root:turn:skill-1",
+ kind: "skill",
+ name: "load_skill",
+ stepIndex: 0,
+ }),
+ kind: "action.started",
+ }),
+ ]);
+ });
+
+ 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 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,
+ },
+ ]);
+ });
+
+ it("keeps delegated work active for a background receipt", () => {
+ expect(
+ projectActivityEvents({
+ at: "2026-01-01T00:00:02Z",
+ event: {
+ data: {
+ result: {
+ backgroundTask: { status: "working", taskId: "task-1" },
+ callId: "child-1",
+ kind: "subagent-result",
+ origin: "child",
+ outcome: {
+ kind: "parked",
+ result: { kind: "succeeded", output: "working" },
+ usageDelta: {
+ cacheReadTokens: 0,
+ cacheWriteTokens: 0,
+ inputTokens: 0,
+ outputTokens: 0,
+ },
+ },
+ output: "working",
+ subagentName: "researcher",
+ },
+ sequence: 0,
+ status: "completed",
+ stepIndex: 0,
+ turnId: "turn",
+ },
+ type: "action.result",
+ },
+ lineage: { ...lineage, sessionId: "root", turnId: "turn" },
+ }),
+ ).toEqual([]);
+ });
+});
diff --git a/packages/eve/src/execution/activity-events.ts b/packages/eve/src/execution/activity-events.ts
new file mode 100644
index 000000000..78be56c8d
--- /dev/null
+++ b/packages/eve/src/execution/activity-events.ts
@@ -0,0 +1,228 @@
+import { normalizeActivityText } from "#execution/activity-text.js";
+import { deriveChildActivityWorkId } from "#execution/activity-work-id.js";
+import type { ActivityEventV1, ActivityWorkIdentityV1 } from "#protocol/activity.js";
+import type { UnstampedMessageStreamEvent } from "#protocol/message.js";
+
+export function projectActivityEvents(input: {
+ readonly at: string;
+ readonly event: UnstampedMessageStreamEvent;
+ readonly lineage: ActivityWorkIdentityV1;
+}): 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 [];
+ const kind = action.kind === "load-skill" ? ("skill" as const) : ("tool" as const);
+ const rawName = action.kind === "load-skill" ? "load_skill" : action.toolName;
+ const name = normalizeActivityText(rawName) || (kind === "skill" ? "Skill" : "Tool");
+ const id = actionId(lineage.id, action.callId);
+ 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,
+ },
+ ];
+ });
+ }
+ if (event.type === "action.result") {
+ const result = event.data.result;
+ if (result.kind === "subagent-result") {
+ if ("backgroundTask" in result && result.backgroundTask !== undefined) return [];
+ 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,
+ },
+ ];
+ }
+ const id = actionId(lineage.id, result.callId);
+ return [
+ {
+ actionId: id,
+ eventId: `${id}:settled:${event.data.status}`,
+ kind: "action.settled",
+ outcome: event.data.status,
+ settledAt: 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,
+ };
+ });
+ }
+ if (
+ lineage.kind === "root-turn" &&
+ (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 activityLabel(value: string): string | undefined {
+ const normalized = normalizeActivityText(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-work.ts b/packages/eve/src/execution/activity-work.ts
index a7d53dff9..eba8b5e7e 100644
--- a/packages/eve/src/execution/activity-work.ts
+++ b/packages/eve/src/execution/activity-work.ts
@@ -1,3 +1,4 @@
+import type { ActivityObserverConfig } from "#channel/types.js";
import type { Session } from "#context/keys.js";
import {
deriveChildActivityWorkId,
@@ -19,6 +20,24 @@ export function deriveRootTurnWorkIdentity(session: Session): ActivityWorkIdenti
};
}
+export function deriveChildActivityObserverConfig(input: {
+ readonly callId: string;
+ readonly kind: Exclude<ActivityWorkKind, "root-turn">;
+ readonly name: string;
+ readonly parentSessionId: string;
+ readonly parentTurnId: 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">;
diff --git a/packages/eve/src/execution/agent-handle-dispatch.ts b/packages/eve/src/execution/agent-handle-dispatch.ts
index f8156c1a1..449b04e4a 100644
--- a/packages/eve/src/execution/agent-handle-dispatch.ts
+++ b/packages/eve/src/execution/agent-handle-dispatch.ts
@@ -8,7 +8,7 @@
* dead (handle deleted) or retryable (handle restored to `parked`).
*/
-import type { SessionAuthContext } from "#channel/types.js";
+import type { ActivityObserverConfig, SessionAuthContext } from "#channel/types.js";
import { AGENT_BUSY, AGENT_MISMATCH, AGENT_UNREACHABLE } from "#harness/agent-handle-errors.js";
import { deriveAgentOperationId } from "#harness/handles/operation-id.js";
import {
@@ -102,6 +102,7 @@ export type DispatchOutcome =
*/
export async function dispatchToAgentHandle(input: {
readonly action: RuntimeAgentHandleAction;
+ readonly activityObserver?: ActivityObserverConfig;
readonly agentId: string;
readonly auth: SessionAuthContext | null;
readonly bundle: CompiledBundle;
@@ -181,6 +182,7 @@ export async function dispatchToAgentHandle(input: {
// replay only makes the parent-side transition idempotent.
const delivery = await deliverToAgentAddress({
action,
+ activityObserver: input.activityObserver,
address: handle.address,
auth: input.auth,
bundle,
@@ -229,6 +231,7 @@ export async function dispatchToAgentHandle(input: {
/** Delivers a tasks-mode continuation without creating a second lifecycle claim. */
export async function dispatchToTaskAgentAddress(input: {
readonly action: RuntimeAgentHandleAction;
+ readonly activityObserver?: ActivityObserverConfig;
readonly agentId: string;
readonly auth: SessionAuthContext | null;
readonly bundle: CompiledBundle;
@@ -267,6 +270,7 @@ export async function dispatchToTaskAgentAddress(input: {
const delivery = await deliverToAgentAddress({
action,
+ activityObserver: input.activityObserver,
address: record.address,
auth: input.auth,
bundle: input.bundle,
@@ -320,6 +324,7 @@ export async function dispatchToTaskAgentAddress(input: {
*/
async function deliverToAgentAddress(input: {
readonly action: RuntimeAgentHandleAction;
+ readonly activityObserver?: ActivityObserverConfig;
readonly address: AgentAddress;
readonly auth: SessionAuthContext | null;
readonly bundle: CompiledBundle;
@@ -348,6 +353,7 @@ async function deliverToAgentAddress(input: {
}
try {
await continueRemoteAgentSession({
+ activityObserver: input.activityObserver,
auth: input.auth,
callback: {
callId: action.callId,
@@ -383,6 +389,7 @@ async function deliverToAgentAddress(input: {
command: {
auth: input.auth,
caller: {
+ activityObserver: input.activityObserver,
callId: action.callId,
replyTo: { kind: "hook", token: input.parentToken },
subagentName: identity.name,
diff --git a/packages/eve/src/execution/delegated-parent-notification.test.ts b/packages/eve/src/execution/delegated-parent-notification.test.ts
index 2bb80db6b..84e07cc2d 100644
--- a/packages/eve/src/execution/delegated-parent-notification.test.ts
+++ b/packages/eve/src/execution/delegated-parent-notification.test.ts
@@ -2,7 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { ContextContainer } from "#context/container.js";
import { serializeContext } from "#context/serialize.js";
-import { SessionCallbackKey, SessionIdKey } from "#context/keys.js";
+import { ActivityObserverKey, SessionCallbackKey, SessionIdKey } from "#context/keys.js";
import { BundleKey, ChannelKey } from "#runtime/sessions/runtime-context-keys.js";
import { getCompiledRuntimeAgentBundle } from "#runtime/sessions/compiled-agent-cache.js";
import {
@@ -474,6 +474,17 @@ describe("turn caller binding", () => {
await expect(
bindTurnCallerContextStep({
caller: {
+ activityObserver: {
+ sink: { url: "https://parent.example/eve/v1/activity/opaque-token", version: 1 },
+ workIdentity: {
+ callId: "call-new",
+ id: "work:new",
+ kind: "subagent",
+ name: "research",
+ rootSessionId: "root",
+ rootTurnId: "root-turn",
+ },
+ },
callId: "call-new",
replyTo: { kind: "hook", token: "turn-new" },
subagentName: "research",
@@ -491,6 +502,9 @@ describe("turn caller binding", () => {
},
}),
).resolves.toMatchObject({
+ [ActivityObserverKey.name]: {
+ workIdentity: { id: "work:new" },
+ },
[ChannelKey.name]: {
state: { callId: "call-new", parentContinuationToken: "turn-new" },
},
diff --git a/packages/eve/src/execution/delegated-parent-notification.ts b/packages/eve/src/execution/delegated-parent-notification.ts
index 41157d815..a65915ea7 100644
--- a/packages/eve/src/execution/delegated-parent-notification.ts
+++ b/packages/eve/src/execution/delegated-parent-notification.ts
@@ -8,7 +8,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 { SessionCallbackKey } from "#context/keys.js";
+import { ActivityObserverKey, SessionCallbackKey } from "#context/keys.js";
import {
isSubagentAdapterState,
SUBAGENT_ADAPTER_KIND,
@@ -297,6 +297,10 @@ export async function bindTurnCallerContextStep(input: {
const caller = input.caller;
if (caller === undefined) return input.serializedContext;
+ const withActivity =
+ caller.activityObserver === undefined
+ ? input.serializedContext
+ : { ...input.serializedContext, [ActivityObserverKey.name]: caller.activityObserver };
if (caller.replyTo.kind === "callback") {
const callback = {
callId: caller.callId,
@@ -305,13 +309,13 @@ export async function bindTurnCallerContextStep(input: {
url: caller.replyTo.url,
};
return {
- ...input.serializedContext,
+ ...withActivity,
[SessionCallbackKey.name]:
caller.taskId === undefined ? callback : { ...callback, taskId: caller.taskId },
};
}
- const adapter = input.serializedContext[ChannelKey.name];
+ const adapter = withActivity[ChannelKey.name];
if (
adapter === null ||
typeof adapter !== "object" ||
@@ -322,7 +326,7 @@ export async function bindTurnCallerContextStep(input: {
}
const state = Reflect.get(adapter, "state") as SubagentAdapterState;
return {
- ...input.serializedContext,
+ ...withActivity,
[ChannelKey.name]: {
...adapter,
state: {
diff --git a/packages/eve/src/execution/dispatch-runtime-actions-shared.ts b/packages/eve/src/execution/dispatch-runtime-actions-shared.ts
index a600eb934..43a705a3b 100644
--- a/packages/eve/src/execution/dispatch-runtime-actions-shared.ts
+++ b/packages/eve/src/execution/dispatch-runtime-actions-shared.ts
@@ -8,12 +8,14 @@
*/
import { buildAdapterContext } from "#channel/adapter-context.js";
+import type { ActivityObserverConfig } from "#channel/types.js";
import {
callAdapterEventHandler,
type ChannelAdapter,
type ChannelAdapterContext,
} from "#channel/adapter.js";
import {
+ ActivityObserverKey,
AuthKey,
CapabilitiesKey,
ChannelInstrumentationKey,
@@ -35,6 +37,7 @@ import {
type RuntimeSession,
} from "#execution/agent-handle-dispatch.js";
import { getAgentHandleStore } from "#harness/handles/store.js";
+import { deriveRootTurnActivityWorkId } from "#execution/activity-work-id.js";
import { readActionTraceContext } from "#tracing/agent-trace-context-store.js";
import {
assertUniqueRuntimeActionCallIds,
@@ -45,6 +48,7 @@ import {
encodeMessageStreamEvent,
stampMessageStreamEvent,
} from "#protocol/message.js";
+import type { ActivityWorkIdentityV1 } from "#protocol/activity.js";
import type {
RuntimeActionRequest,
RuntimeActionResult,
@@ -155,6 +159,9 @@ export interface PreparedRuntimeActionDispatch {
readonly fanoutSize: number;
readonly initiatorAuth: Parameters<typeof buildSubagentRunInput>[0]["initiatorAuth"];
readonly parentTraceContext: Parameters<typeof buildSubagentRunInput>[0]["parentTraceContext"];
+ readonly activityObserver?: ActivityObserverConfig & {
+ readonly workIdentity: ActivityWorkIdentityV1;
+ };
readonly sandboxSessionId: string;
readonly serializedContext: Record<string, unknown>;
readonly plan: readonly DispatchPlanEntry[];
@@ -282,12 +289,36 @@ async function prepareActionDispatch(input: {
initiatorAuth: ctx.get(InitiatorAuthKey) ?? null,
parentTraceContext: readSessionTraceContext(input.serializedContext, session.sessionId),
plan,
+ activityObserver: resolvePreparedActivity(
+ ctx.get(ActivityObserverKey),
+ session,
+ batch.event.turnId,
+ ),
sandboxSessionId,
serializedContext: input.serializedContext,
session,
};
}
+function resolvePreparedActivity(
+ activityObserver: ActivityObserverConfig | undefined,
+ session: RuntimeSession,
+ 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 planSharesSandbox(input: {
readonly bundle: CompiledBundle;
readonly plan: readonly DispatchPlanEntry[];
@@ -552,6 +583,9 @@ export async function startSubagent(input: {
readonly initiatorAuth: Parameters<typeof buildSubagentRunInput>[0]["initiatorAuth"];
readonly parentContinuationToken: string | undefined;
readonly parentTraceContext: Parameters<typeof buildSubagentRunInput>[0]["parentTraceContext"];
+ readonly activityObserver?: ActivityObserverConfig & {
+ readonly workIdentity: ActivityWorkIdentityV1;
+ };
readonly sandboxSessionId: string;
readonly serializedContext: Record<string, unknown>;
readonly session: RuntimeSession;
@@ -581,6 +615,7 @@ export async function startSubagent(input: {
initiatorAuth: input.initiatorAuth,
parentContinuationToken: input.parentContinuationToken,
parentTraceContext,
+ activityObserver: input.activityObserver,
sandboxSessionId: input.sandboxSessionId,
session: input.session,
source: input.target.source,
@@ -598,6 +633,7 @@ export async function startSubagent(input: {
initiatorAuth: input.initiatorAuth,
parentContinuationToken: input.parentContinuationToken,
parentTraceContext,
+ activityObserver: input.activityObserver,
session: input.session,
taskOwned: input.taskOwned,
});
diff --git a/packages/eve/src/execution/dispatch-runtime-actions-step.integration.test.ts b/packages/eve/src/execution/dispatch-runtime-actions-step.integration.test.ts
index bb52b4756..aac2dfcf9 100644
--- a/packages/eve/src/execution/dispatch-runtime-actions-step.integration.test.ts
+++ b/packages/eve/src/execution/dispatch-runtime-actions-step.integration.test.ts
@@ -14,6 +14,7 @@ import {
setPendingRuntimeActionBatch,
} from "#harness/runtime-actions.js";
import { deriveAgentOperationId } from "#harness/handles/operation-id.js";
+import { deriveRootTurnActivityWorkId } from "#execution/activity-work-id.js";
import {
AGENT_HANDLES_STATE_KEY,
deriveAgentId,
@@ -25,6 +26,7 @@ import { getSessionTaskIndex } from "#tasks/session-index.js";
import { recordSessionTask } from "#tasks/session-index.js";
import * as taskRunControl from "#execution/tasks/parent/run-parent.js";
import {
+ ActivityObserverKey,
AuthKey,
CapabilitiesKey,
ChannelInstrumentationKey,
@@ -187,6 +189,12 @@ describe("dispatchRuntimeActionsStep child starts", () => {
it("plans an in-step agent call from the live context", async () => {
const session = createBaseSession();
const ctx = new ContextContainer();
+ ctx.set(ActivityObserverKey, {
+ sink: {
+ url: "https://parent.example/eve/v1/activity/abcdefghijklmnopqrstuvwxyz123456",
+ version: 1,
+ },
+ });
ctx.set(AuthKey, null);
ctx.set(ChannelKey, ADAPTER);
ctx.set(BundleKey, {
@@ -233,6 +241,11 @@ describe("dispatchRuntimeActionsStep child starts", () => {
target: expect.objectContaining({ kind: "remote" }),
}),
]);
+ expect(prepared.activityObserver?.workIdentity).toMatchObject({
+ id: deriveRootTurnActivityWorkId({ sessionId: session.sessionId, turnId: "turn-1" }),
+ sessionId: session.sessionId,
+ turnId: "turn-1",
+ });
expect(mocks.deserializeContext).not.toHaveBeenCalled();
});
diff --git a/packages/eve/src/execution/dispatch-runtime-actions-step.ts b/packages/eve/src/execution/dispatch-runtime-actions-step.ts
index 287dbc27d..e31464520 100644
--- a/packages/eve/src/execution/dispatch-runtime-actions-step.ts
+++ b/packages/eve/src/execution/dispatch-runtime-actions-step.ts
@@ -25,6 +25,7 @@ import {
startSubagent,
} from "#execution/dispatch-runtime-actions-shared.js";
import { createDurableSessionState } from "#execution/durable-session-store.js";
+import { deriveChildActivityObserverConfig } from "#execution/activity-work.js";
import type { RuntimeActionResult } from "#shared/action-types.js";
export async function dispatchRuntimeActionsStep(
@@ -65,6 +66,20 @@ export async function dispatchRuntimeActionsStep(
case "resume":
outcome = await dispatchToAgentHandle({
action: entry.action,
+ activityObserver:
+ prepared.activityObserver === undefined
+ ? undefined
+ : deriveChildActivityObserverConfig({
+ activityObserver: prepared.activityObserver,
+ callId: entry.action.callId,
+ kind: entry.action.kind === "remote-agent-call" ? "remote-agent" : "subagent",
+ name:
+ entry.action.kind === "remote-agent-call"
+ ? entry.action.remoteAgentName
+ : entry.action.subagentName,
+ parentSessionId: session.sessionId,
+ parentTurnId: batch.event.turnId,
+ }),
agentId: entry.agentId,
auth: prepared.auth,
bundle: createAgentContinuationBundle({
@@ -90,6 +105,7 @@ export async function dispatchRuntimeActionsStep(
initiatorAuth: prepared.initiatorAuth,
parentContinuationToken: input.parentContinuationToken,
parentTraceContext: prepared.parentTraceContext,
+ activityObserver: prepared.activityObserver,
sandboxSessionId: prepared.sandboxSessionId,
serializedContext: prepared.serializedContext,
session,
diff --git a/packages/eve/src/execution/remote-agent-dispatch.test.ts b/packages/eve/src/execution/remote-agent-dispatch.test.ts
index d368ba413..b9f6ab926 100644
--- a/packages/eve/src/execution/remote-agent-dispatch.test.ts
+++ b/packages/eve/src/execution/remote-agent-dispatch.test.ts
@@ -675,6 +675,20 @@ 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",
@@ -692,6 +706,20 @@ 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/remote-agent-dispatch.ts b/packages/eve/src/execution/remote-agent-dispatch.ts
index c2bc15907..4c97e77af 100644
--- a/packages/eve/src/execution/remote-agent-dispatch.ts
+++ b/packages/eve/src/execution/remote-agent-dispatch.ts
@@ -8,7 +8,12 @@ import {
createEveSessionResetRoutePath,
createEveSessionRoutePath,
} from "#protocol/routes.js";
-import type { CancelTurnResult, SessionAuthContext, SessionTraceContext } from "#channel/types.js";
+import type {
+ ActivityObserverConfig,
+ CancelTurnResult,
+ SessionAuthContext,
+ SessionTraceContext,
+} from "#channel/types.js";
import type { ForwardedPrincipal } from "#channel/forwarded-principal.js";
import type { HeadersValue } from "#client/types.js";
import { createWorkflowCallbackUrl } from "#execution/workflow-callback-url.js";
@@ -54,6 +59,7 @@ export async function startRemoteAgentSession(input: {
readonly auth?: SessionAuthContext | null;
readonly callbackBaseUrl: string | undefined;
readonly callbackToken?: string;
+ readonly activityObserver?: ActivityObserverConfig;
/** The root initiator's principal, forwarded alongside {@link auth}. */
readonly initiatorAuth?: SessionAuthContext | null;
/**
@@ -84,6 +90,7 @@ export async function startRemoteAgentSession(input: {
token: string;
url: string;
};
+ activityObserver?: ActivityObserverConfig;
forwardedPrincipal?: ForwardedPrincipal;
message: string;
mode: "conversation" | "task";
@@ -109,6 +116,7 @@ export async function startRemoteAgentSession(input: {
outputSchema:
normalizeRequestedOutputSchema(input.action.input.outputSchema) ?? input.remote.outputSchema,
};
+ if (input.activityObserver !== undefined) requestBody.activityObserver = input.activityObserver;
if (forwardedPrincipal !== undefined) {
requestBody.forwardedPrincipal = forwardedPrincipal;
}
@@ -160,6 +168,7 @@ export async function startRemoteAgentSession(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: {
@@ -176,11 +185,13 @@ 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/runtime-context.test.ts b/packages/eve/src/execution/runtime-context.test.ts
index e954bfa46..65bc93254 100644
--- a/packages/eve/src/execution/runtime-context.test.ts
+++ b/packages/eve/src/execution/runtime-context.test.ts
@@ -6,7 +6,7 @@ import {
ContinuationTokenKey,
type Session,
type SessionAuthContext,
- ActivityKey,
+ ActivityObserverKey,
SessionIdKey,
SessionKey,
ScheduleIdKey,
@@ -244,7 +244,7 @@ describe("buildRunContext", () => {
expect(ctx.get(SessionIdKey)).toBeUndefined();
});
- it("seeds inherited private activity context", () => {
+ it("seeds inherited private activity observer configuration", () => {
const sink = {
url: "https://root.example.com/eve/v1/activity/abcdefghijklmnopqrstuvwxyz123456",
version: 1 as const,
@@ -263,11 +263,11 @@ describe("buildRunContext", () => {
adapter: { kind: "subagent" },
input: { message: "hi" },
mode: "task",
- activity: { sink, workIdentity },
+ activityObserver: { sink, workIdentity },
},
});
- expect(ctx.get(ActivityKey)).toEqual({ sink, workIdentity });
+ expect(ctx.get(ActivityObserverKey)).toEqual({ sink, workIdentity });
});
it("grafts parent metadata onto the child's own kind", () => {
diff --git a/packages/eve/src/execution/runtime-context.ts b/packages/eve/src/execution/runtime-context.ts
index 161ab4496..c3dfabe89 100644
--- a/packages/eve/src/execution/runtime-context.ts
+++ b/packages/eve/src/execution/runtime-context.ts
@@ -13,7 +13,7 @@ import {
ModeKey,
ParentSessionKey,
ParentTraceContextKey,
- ActivityKey,
+ ActivityObserverKey,
ScheduleIdKey,
SessionCallbackKey,
SubagentDepthKey,
@@ -76,8 +76,8 @@ export function buildRunContext(input: {
if (run.callback !== undefined) {
ctx.set(SessionCallbackKey, run.callback);
}
- if (run.activity !== undefined) {
- ctx.set(ActivityKey, run.activity);
+ if (run.activityObserver !== undefined) {
+ ctx.set(ActivityObserverKey, run.activityObserver);
}
if (run.parent !== undefined) {
diff --git a/packages/eve/src/execution/session-activity-projection.test.ts b/packages/eve/src/execution/session-activity-projection.test.ts
new file mode 100644
index 000000000..6f63aa1a2
--- /dev/null
+++ b/packages/eve/src/execution/session-activity-projection.test.ts
@@ -0,0 +1,221 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import { ActivityObserverKey } from "#context/keys.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";
+
+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 reduceProjection(input: {
+ readonly events: readonly MessageStreamEvent[];
+ readonly sessionId: string;
+ readonly workIdentity?: ActivityWorkIdentityV1;
+}): ActivitySnapshotV1 {
+ return input.events.reduce(
+ (snapshot, event) =>
+ reduceActivityBatch(snapshot, {
+ events: projectSessionActivity({
+ event,
+ sessionId: input.sessionId,
+ workIdentity: input.workIdentity,
+ }),
+ version: 1,
+ }),
+ createActivitySnapshot(),
+ );
+}
+
+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("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("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("maps session.started to delegated work start and keeps HITL active while parked", () => {
+ const workIdentity: 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 snapshot = reduceProjection({
+ events: [
+ { data: {}, meta: { at, id: "session-started" }, type: "session.started" },
+ {
+ data: {
+ requests: [
+ {
+ action: { callId: "tool-1", input: {}, kind: "tool-call", toolName: "search" },
+ kind: "question",
+ prompt: "Which region?",
+ requestId: "request-1",
+ },
+ ],
+ sequence: 1,
+ stepIndex: 0,
+ turnId: "child-turn",
+ },
+ meta: { at, id: "input-requested" },
+ type: "input.requested",
+ },
+ turnEvent("turn.completed", "child-turn"),
+ {
+ data: { continuationToken: "child-token", wait: "next-user-message" },
+ meta: { at, id: "session-waiting" },
+ type: "session.waiting",
+ },
+ ],
+ sessionId: "child-session",
+ workIdentity,
+ });
+
+ expect(snapshot.work[workIdentity.id]).toMatchObject({ phase: "running" });
+ expect(snapshot.blockers[`input:${workIdentity.id}:request-1`]).toMatchObject({
+ phase: "blocked",
+ });
+ });
+});
+
+describe("observeSessionActivity", () => {
+ afterEach(() => vi.unstubAllGlobals());
+
+ function context(): ContextContainer {
+ const ctx = new ContextContainer();
+ ctx.set(ActivityObserverKey, {
+ sink: {
+ url: "https://agent.example.com/eve/v1/activity/abcdefghijklmnopqrstuvwxyz123456",
+ version: 1,
+ },
+ });
+ return ctx;
+ }
+
+ it("does not submit events with no activity projection", async () => {
+ const fetchMock = vi.fn();
+ vi.stubGlobal("fetch", fetchMock);
+ const event: MessageStreamEvent = {
+ data: {
+ messageDelta: "hello",
+ messageSoFar: "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 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();
+ });
+});
diff --git a/packages/eve/src/execution/session-activity-projection.ts b/packages/eve/src/execution/session-activity-projection.ts
new file mode 100644
index 000000000..60ad9c712
--- /dev/null
+++ b/packages/eve/src/execution/session-activity-projection.ts
@@ -0,0 +1,83 @@
+import type { ContextContainer } from "#context/container.js";
+import { ActivityObserverKey } 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,
+ sessionId: input.sessionId,
+ workIdentity: observer.workIdentity,
+ }),
+ sink: observer.sink,
+ });
+}
+
+export function projectSessionActivity(input: {
+ readonly event: MessageStreamEvent;
+ readonly sessionId: 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,
+ });
+ }
+ events.push(
+ ...projectActivityEvents({ at: input.event.meta.at, event: input.event, lineage: work }),
+ );
+ return events;
+}
+
+function workFor(input: {
+ readonly event: MessageStreamEvent;
+ 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;
+ return {
+ id: deriveRootTurnActivityWorkId({ sessionId: input.sessionId, turnId }),
+ kind: "root-turn",
+ rootSessionId: input.sessionId,
+ rootTurnId: turnId,
+ 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-command-inbox.integration.test.ts b/packages/eve/src/execution/session-command-inbox.integration.test.ts
index c4ebbb0a7..30e1415e8 100644
--- a/packages/eve/src/execution/session-command-inbox.integration.test.ts
+++ b/packages/eve/src/execution/session-command-inbox.integration.test.ts
@@ -7,6 +7,7 @@ import { midCohortSessionDeliveryWorkflow } from "#internal/testing/mid-cohort-s
import { waitForHook } from "#internal/testing/workflow-test-helpers.js";
import { getHookByToken, getWorld, resumeHook, start } from "#internal/workflow/runtime.js";
import { sessionCommandHookToken } from "#execution/session-command-token.js";
+import { SESSION_INBOX_WIRE_VERSION } from "#execution/wire/session-inbox-contract.js";
import type { RuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";
describe("session command inbox integration", () => {
@@ -87,7 +88,9 @@ describe("session command inbox integration", () => {
const hook = (await getHookByToken(token)) as {
metadata?: { sessionInboxWireVersion?: unknown };
};
- expect(hook.metadata?.sessionInboxWireVersion, `hook ${token}`).toBe(1);
+ expect(hook.metadata?.sessionInboxWireVersion, `hook ${token}`).toBe(
+ SESSION_INBOX_WIRE_VERSION,
+ );
}
} finally {
const status = await run.status;
diff --git a/packages/eve/src/execution/session-command-inbox.test.ts b/packages/eve/src/execution/session-command-inbox.test.ts
index e10f7fa3f..75791e04f 100644
--- a/packages/eve/src/execution/session-command-inbox.test.ts
+++ b/packages/eve/src/execution/session-command-inbox.test.ts
@@ -2,6 +2,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
import type { SessionInboxPayload } from "#execution/session-command-inbox.js";
import { createSessionCommandInbox } from "#execution/session-command-inbox.js";
+import { SESSION_INBOX_WIRE_VERSION } from "#execution/wire/session-inbox-contract.js";
const createHookMock = vi.fn();
@@ -120,7 +121,7 @@ describe("createSessionCommandInbox", () => {
);
expect(createHookMock).toHaveBeenCalledOnce();
expect(createHookMock).toHaveBeenCalledWith({
- metadata: { sessionInboxWireVersion: 1 },
+ metadata: { sessionInboxWireVersion: SESSION_INBOX_WIRE_VERSION },
token: "stable",
});
await inbox.dispose();
diff --git a/packages/eve/src/execution/settle-cancelled-turn-step.ts b/packages/eve/src/execution/settle-cancelled-turn-step.ts
index 7a7344a6e..ef50c137a 100644
--- a/packages/eve/src/execution/settle-cancelled-turn-step.ts
+++ b/packages/eve/src/execution/settle-cancelled-turn-step.ts
@@ -5,6 +5,7 @@ import { withContextScope } from "#context/run-step.js";
import { deserializeContext, serializeContext } from "#context/serialize.js";
import { ChannelInstrumentationKey } from "#context/keys.js";
import { setChannelContext } from "#execution/channel-context.js";
+import { observeSessionActivity } from "#execution/session-activity-projection.js";
import {
createDurableSessionState,
type DurableSessionState,
@@ -98,6 +99,7 @@ export async function settleCancelledTurnStep(input: {
// Stamp once: the persisted chunk and the hooks must agree on the id.
const stamped = stampMessageStreamEvent(transformed);
await writer.write(encodeMessageStreamEvent(stamped));
+ void observeSessionActivity({ ctx, event: stamped, sessionId: session.sessionId });
await dispatchStreamEventHooks({
ctx,
event: stamped,
diff --git a/packages/eve/src/execution/subagent-start-local.ts b/packages/eve/src/execution/subagent-start-local.ts
index d3001e786..7b9fc7a04 100644
--- a/packages/eve/src/execution/subagent-start-local.ts
+++ b/packages/eve/src/execution/subagent-start-local.ts
@@ -1,4 +1,5 @@
import type { DispatchOutcome, RuntimeSession } from "#execution/agent-handle-dispatch.js";
+import { deriveChildActivityObserverConfig } from "#execution/activity-work.js";
import { mintStartOperation } from "#execution/dispatch-start-operation.js";
import { isRuntimeSessionOwnershipConflictError } from "#execution/runtime-errors.js";
import { buildSubagentRunInput, type SubagentInputSource } from "#execution/subagent-tool.js";
@@ -35,12 +36,21 @@ export async function startLocalSubagent(input: {
readonly initiatorAuth: Parameters<typeof buildSubagentRunInput>[0]["initiatorAuth"];
readonly parentContinuationToken: string | undefined;
readonly parentTraceContext: Parameters<typeof buildSubagentRunInput>[0]["parentTraceContext"];
+ readonly activityObserver?: Parameters<typeof buildSubagentRunInput>[0]["activityObserver"];
readonly sandboxSessionId: string;
readonly session: RuntimeSession;
readonly source: SubagentInputSource;
readonly taskOwned: boolean;
}): Promise<DispatchOutcome> {
const { action, source } = input;
+ const activityObserver = deriveChildActivityObserverConfig({
+ activityObserver: input.activityObserver,
+ callId: action.callId,
+ kind: "subagent",
+ name: action.subagentName,
+ parentSessionId: input.session.sessionId,
+ parentTurnId: input.batchEvent.turnId,
+ });
const childRuntime = createWorkflowRuntime({
compiledArtifactsSource: input.bundle.compiledArtifactsSource,
dynamicSubagentAgentConfig: input.dynamicSubagentAgentConfig,
@@ -57,6 +67,7 @@ export async function startLocalSubagent(input: {
graph: input.bundle.graph,
parentContinuationToken: input.parentContinuationToken,
parentTraceContext: input.parentTraceContext,
+ activityObserver,
sandboxSessionId: input.sandboxSessionId,
session: input.session,
source,
diff --git a/packages/eve/src/execution/subagent-start-remote.ts b/packages/eve/src/execution/subagent-start-remote.ts
index 79b9fd592..00411b8be 100644
--- a/packages/eve/src/execution/subagent-start-remote.ts
+++ b/packages/eve/src/execution/subagent-start-remote.ts
@@ -1,4 +1,5 @@
import type { DispatchOutcome, RuntimeSession } from "#execution/agent-handle-dispatch.js";
+import { deriveChildActivityObserverConfig } from "#execution/activity-work.js";
import { createRemoteAgentStartFailureResult } from "#execution/dispatch-action-failures.js";
import { mintStartOperation } from "#execution/dispatch-start-operation.js";
import {
@@ -31,10 +32,19 @@ export async function startRemoteSubagent(input: {
readonly initiatorAuth: Parameters<typeof startRemoteAgentSession>[0]["initiatorAuth"];
readonly parentContinuationToken: string | undefined;
readonly parentTraceContext: Parameters<typeof startRemoteAgentSession>[0]["parentTraceContext"];
+ readonly activityObserver?: Parameters<typeof startRemoteAgentSession>[0]["activityObserver"];
readonly session: RuntimeSession;
readonly taskOwned: boolean;
}): Promise<DispatchOutcome> {
const { action } = input;
+ const activityObserver = deriveChildActivityObserverConfig({
+ activityObserver: input.activityObserver,
+ callId: action.callId,
+ kind: "remote-agent",
+ name: action.remoteAgentName,
+ parentSessionId: input.session.sessionId,
+ parentTurnId: input.batchEvent.turnId,
+ });
// Preflight resolution failures happen before ownership exists, so they
// reject without touching the handle store.
@@ -92,6 +102,7 @@ export async function startRemoteSubagent(input: {
initiatorAuth: input.initiatorAuth,
operationId: operation.id,
parentTraceContext: input.parentTraceContext,
+ activityObserver,
remote: resolvedRemote,
session: input.session,
});
diff --git a/packages/eve/src/execution/subagent-tool.ts b/packages/eve/src/execution/subagent-tool.ts
index 2515646a3..fc50e1a7d 100644
--- a/packages/eve/src/execution/subagent-tool.ts
+++ b/packages/eve/src/execution/subagent-tool.ts
@@ -4,6 +4,7 @@ import {
normalizeRequestedOutputSchema,
} from "#execution/subagent-invocation.js";
import type {
+ ActivityObserverConfig,
ChannelInstrumentationProjection,
RunInput,
RunSessionLimits,
@@ -98,6 +99,7 @@ export function buildSubagentRunInput(input: {
/** Hook token owned by the workflow currently waiting for this child. */
readonly parentContinuationToken?: string;
readonly parentTraceContext?: SessionTraceContext;
+ readonly activityObserver?: ActivityObserverConfig;
readonly session: HarnessSession;
readonly source: SubagentInputSource;
}): SubagentRunInputBuild {
@@ -176,6 +178,7 @@ export function buildSubagentRunInput(input: {
},
},
parentTraceContext: input.parentTraceContext,
+ activityObserver: input.activityObserver,
subagentDepth: subagentDepth.nextChildDepth,
};
diff --git a/packages/eve/src/execution/tasks/child/steps.test.ts b/packages/eve/src/execution/tasks/child/steps.test.ts
index 413c7eb22..e9d796654 100644
--- a/packages/eve/src/execution/tasks/child/steps.test.ts
+++ b/packages/eve/src/execution/tasks/child/steps.test.ts
@@ -1,6 +1,9 @@
-import { describe, expect, it } from "vitest";
+import { afterEach, describe, expect, it, vi } from "vitest";
-import { formatTaskNotification } from "#execution/tasks/child/steps.js";
+import {
+ formatTaskNotification,
+ projectTaskActivitySettlement,
+} from "#execution/tasks/child/steps.js";
import type { TaskView } from "#tasks/types.js";
const metadata = {
@@ -40,6 +43,43 @@ const notificationCases: readonly { readonly expected: string; readonly view: Ta
},
];
+describe("projectTaskActivitySettlement", () => {
+ afterEach(() => vi.unstubAllGlobals());
+
+ it("projects terminal task settlement", () => {
+ expect(
+ projectTaskActivitySettlement({
+ activityObserver: {
+ sink: {
+ url: "https://parent.example/eve/v1/activity/abcdefghijklmnopqrstuvwxyz123456",
+ version: 1,
+ },
+ workIdentity: {
+ id: "work:task",
+ kind: "task",
+ rootSessionId: "root",
+ rootTurnId: "turn",
+ },
+ },
+ settledAt: "2026-01-01T00:00:00.000Z",
+ view: notificationCases[0]!.view,
+ }),
+ ).toEqual([
+ expect.objectContaining({ kind: "work.settled", outcome: "completed", workId: "work:task" }),
+ ]);
+ });
+
+ it("does nothing for nonterminal task views", () => {
+ expect(
+ projectTaskActivitySettlement({
+ activityObserver: undefined,
+ settledAt: "2026-01-01T00:00:00.000Z",
+ view: { metadata, status: "working", taskId: "task-1" },
+ }),
+ ).toEqual([]);
+ });
+});
+
describe("formatTaskNotification", () => {
it.each(notificationCases)(
"includes terminal output in the parent notification",
diff --git a/packages/eve/src/execution/tasks/child/steps.ts b/packages/eve/src/execution/tasks/child/steps.ts
index 6ab60f612..bab9ab528 100644
--- a/packages/eve/src/execution/tasks/child/steps.ts
+++ b/packages/eve/src/execution/tasks/child/steps.ts
@@ -1,13 +1,16 @@
import { getWritable } from "#compiled/@workflow/core/index.js";
import type {
+ ActivityObserverConfig,
SessionAuthContext,
SessionCommand,
SubagentAuthorizationEventHookPayload,
SubagentInputRequestHookPayload,
} from "#channel/types.js";
+import { submitActivity } from "#execution/submit-activity.js";
import { isTaskWorkflowTargetGone } from "#execution/tasks/workflow-target.js";
import { resumeSessionInbox } from "#execution/wire/session-inbox-resume.js";
import { createLogger } from "#internal/logging.js";
+import type { ActivityEventV1 } from "#protocol/activity.js";
import type { JsonValue } from "#shared/json.js";
import {
isTerminalTaskStatus,
@@ -27,7 +30,10 @@ const log = createLogger("execution.tasks.run");
* stream. Only the task run workflow calls this, which is what makes
* the run the single writer readers can trust without re-validating.
*/
-export async function appendTaskViewStep(input: { readonly view: TaskView }): Promise<void> {
+export async function appendTaskViewStep(input: {
+ readonly activityObserver?: ActivityObserverConfig;
+ readonly view: TaskView;
+}): Promise<void> {
"use step";
const writable = getWritable<TaskView>({ namespace: TASK_VIEW_STREAM_NAMESPACE });
@@ -37,6 +43,36 @@ export async function appendTaskViewStep(input: { readonly view: TaskView }): Pr
} finally {
writer.releaseLock();
}
+
+ const events = projectTaskActivitySettlement({
+ activityObserver: input.activityObserver,
+ settledAt: new Date().toISOString(),
+ view: input.view,
+ });
+ void submitActivity({ events, sink: input.activityObserver?.sink });
+}
+
+export function projectTaskActivitySettlement(input: {
+ readonly activityObserver: ActivityObserverConfig | undefined;
+ readonly settledAt: string;
+ readonly view: TaskView;
+}): readonly ActivityEventV1[] {
+ const work = input.activityObserver?.workIdentity;
+ const status = input.view.status;
+ if (
+ work === undefined ||
+ (status !== "completed" && status !== "failed" && status !== "cancelled")
+ )
+ return [];
+ return [
+ {
+ eventId: `${work.id}:settled:${status}`,
+ kind: "work.settled",
+ outcome: status,
+ settledAt: input.settledAt,
+ workId: work.id,
+ },
+ ];
}
/** Re-emits a task-owned child authorization event through the parent channel. */
diff --git a/packages/eve/src/execution/tasks/child/workflow.ts b/packages/eve/src/execution/tasks/child/workflow.ts
index 93c1510a9..16d030c4a 100644
--- a/packages/eve/src/execution/tasks/child/workflow.ts
+++ b/packages/eve/src/execution/tasks/child/workflow.ts
@@ -1,6 +1,9 @@
import { createHook } from "#compiled/@workflow/core/index.js";
-import type { SubagentAuthorizationEventHookPayload } from "#channel/types.js";
+import type {
+ ActivityObserverConfig,
+ SubagentAuthorizationEventHookPayload,
+} from "#channel/types.js";
import { claimHookOwnership, disposeHook, isHookConflictError } from "#execution/hook-ownership.js";
import {
appendTaskViewStep,
@@ -28,6 +31,8 @@ import {
/** Input for one durable task run. */
export interface TaskRunWorkflowInput {
+ /** Activity sink and work identity for best-effort terminal settlement. */
+ readonly activityObserver?: ActivityObserverConfig;
/** Private task inbox token; a routing credential, never model-visible. */
readonly taskInboxToken: string;
/** The creation view, normally `working`. */
@@ -93,7 +98,7 @@ export async function taskRunWorkflow(input: TaskRunWorkflowInput): Promise<void
let pendingAuthorizationEvents: TaskInboundAuthorizationEvent[] = [];
let pendingUpdates: TaskInboundUpdate[] = [];
let dispatchAcknowledged = false;
- await appendTaskViewStep({ view });
+ await appendTaskViewStep({ activityObserver: input.activityObserver, view });
while (!isTaskRunFinished(view, dispatchAcknowledged)) {
const next = await iterator.next();
@@ -171,7 +176,7 @@ export async function taskRunWorkflow(input: TaskRunWorkflowInput): Promise<void
!isTerminalTaskStatus(view.status) && isTerminalTaskStatus(result.view.status);
const becameReady = !isReadyTaskStatus(view.status) && isReadyTaskStatus(result.view.status);
view = result.view;
- await appendTaskViewStep({ view });
+ await appendTaskViewStep({ activityObserver: input.activityObserver, view });
const routableAuthorizationEvents =
dispatchAcknowledged && !becameTerminal ? pendingAuthorizationEvents : [];
for (const request of routableAuthorizationEvents) {
diff --git a/packages/eve/src/execution/tasks/parent/delegate.ts b/packages/eve/src/execution/tasks/parent/delegate.ts
index 312e9d599..154aa2f68 100644
--- a/packages/eve/src/execution/tasks/parent/delegate.ts
+++ b/packages/eve/src/execution/tasks/parent/delegate.ts
@@ -5,6 +5,7 @@
* Task-run transport (start/command/view) lives in `run-parent.ts`, which
* this module composes and which other non-delegation callers share.
*/
+import type { ActivityObserverConfig } from "#channel/types.js";
import type { RuntimeSession } from "#execution/agent-handle-dispatch.js";
import {
readLatestTaskView,
@@ -50,6 +51,7 @@ export interface DelegatedTask extends BackgroundTask {
* re-derives the same token and the loser exits on the hook claim.
*/
export async function beginDelegatedTask(input: {
+ readonly activityObserver?: ActivityObserverConfig;
readonly agentId: string;
readonly callId: string;
readonly mode: "local" | "remote";
@@ -60,6 +62,7 @@ export async function beginDelegatedTask(input: {
readonly session: RuntimeSession;
}): Promise<DelegatedTask> {
const task = await beginBackgroundTask({
+ activityObserver: input.activityObserver,
callId: input.callId,
metadata: createSubagentTaskMetadata({
agentId: input.agentId,
@@ -83,6 +86,7 @@ export async function beginDelegatedTask(input: {
/** Creates a replay-stable task run before a background tool starts external work. */
export async function beginBackgroundTask(input: {
+ readonly activityObserver?: ActivityObserverConfig;
readonly callId: string;
readonly metadata: DurableTaskMetadata;
readonly parentSessionId: string;
@@ -100,6 +104,7 @@ export async function beginBackgroundTask(input: {
taskId,
});
await startTaskRun({
+ activityObserver: input.activityObserver,
taskInboxToken,
initialView: {
metadata: input.metadata,
diff --git a/packages/eve/src/execution/tasks/parent/dispatch-task-step.ts b/packages/eve/src/execution/tasks/parent/dispatch-task-step.ts
index 7b3048afa..48e0d6d29 100644
--- a/packages/eve/src/execution/tasks/parent/dispatch-task-step.ts
+++ b/packages/eve/src/execution/tasks/parent/dispatch-task-step.ts
@@ -29,6 +29,7 @@ import {
startSubagent,
} from "#execution/dispatch-runtime-actions-shared.js";
import { createDurableSessionState } from "#execution/durable-session-store.js";
+import { deriveChildActivityObserverConfig } from "#execution/activity-work.js";
import {
beginDelegatedTask,
type DelegatedTask,
@@ -104,14 +105,26 @@ export async function dispatchTaskStep(
}
}
+ const action = entry.kind === "resume" ? entry.action : entry.target.action;
const delegated = await beginDelegatedTask({
...describeTaskDispatch({
- action: entry.kind === "resume" ? entry.action : entry.target.action,
+ action,
agentId: entry.kind === "resume" ? entry.agentId : undefined,
parentSessionId: session.sessionId,
parentTurnId: batch.event.turnId,
session: nextSession,
}),
+ activityObserver:
+ prepared.activityObserver === undefined
+ ? undefined
+ : deriveChildActivityObserverConfig({
+ activityObserver: prepared.activityObserver,
+ callId: action.callId,
+ kind: "task",
+ name: entry.kind === "resume" ? entry.action.name : entry.target.action.name,
+ parentSessionId: session.sessionId,
+ parentTurnId: batch.event.turnId,
+ }),
parentSessionId: session.sessionId,
parentStepIndex: batch.event.stepIndex,
parentTurnId: batch.event.turnId,
@@ -133,6 +146,17 @@ export async function dispatchTaskStep(
case "resume":
outcome = await dispatchToTaskAgentAddress({
action: entry.action,
+ activityObserver:
+ prepared.activityObserver === undefined
+ ? undefined
+ : deriveChildActivityObserverConfig({
+ activityObserver: prepared.activityObserver,
+ callId: entry.action.callId,
+ kind: "task",
+ name: entry.action.name,
+ parentSessionId: session.sessionId,
+ parentTurnId: batch.event.turnId,
+ }),
agentId: entry.agentId,
auth: prepared.auth,
bundle: createAgentContinuationBundle({
@@ -157,6 +181,7 @@ export async function dispatchTaskStep(
initiatorAuth: prepared.initiatorAuth,
parentContinuationToken: delegated.taskInboxToken,
parentTraceContext: prepared.parentTraceContext,
+ activityObserver: prepared.activityObserver,
sandboxSessionId: prepared.sandboxSessionId,
serializedContext: prepared.serializedContext,
session,
diff --git a/packages/eve/src/execution/tools/subagent/local.ts b/packages/eve/src/execution/tools/subagent/local.ts
index e70bbe5fb..4219a2e55 100644
--- a/packages/eve/src/execution/tools/subagent/local.ts
+++ b/packages/eve/src/execution/tools/subagent/local.ts
@@ -7,6 +7,7 @@ import {
type RuntimeSession,
} from "#execution/agent-handle-dispatch.js";
import { createAgentContinuationBundle } from "#execution/agent-continuation-bundle.js";
+import { deriveChildActivityObserverConfig } from "#execution/activity-work.js";
import {
prepareAgentActionDispatch,
startSubagent,
@@ -218,6 +219,17 @@ async function dispatchSubagent(input: SubagentDispatchInput): Promise<SubagentD
entry.kind === "resume"
? await dispatchToTaskAgentAddress({
action: entry.action,
+ activityObserver:
+ prepared.activityObserver === undefined
+ ? undefined
+ : deriveChildActivityObserverConfig({
+ activityObserver: prepared.activityObserver,
+ callId: entry.action.callId,
+ kind: "task",
+ name: entry.action.name,
+ parentSessionId: prepared.session.sessionId,
+ parentTurnId: input.event.turnId,
+ }),
agentId: entry.agentId,
auth: prepared.auth,
bundle: createAgentContinuationBundle({
@@ -240,6 +252,7 @@ async function dispatchSubagent(input: SubagentDispatchInput): Promise<SubagentD
initiatorAuth: prepared.initiatorAuth,
parentContinuationToken: input.task.taskInboxToken,
parentTraceContext: prepared.parentTraceContext,
+ activityObserver: prepared.activityObserver,
sandboxSessionId: prepared.sandboxSessionId,
serializedContext: prepared.serializedContext,
session: prepared.session,
diff --git a/packages/eve/src/execution/wire/__snapshots__/session-inbox-wire.v2.test.ts.snap b/packages/eve/src/execution/wire/__snapshots__/session-inbox-wire.v2.test.ts.snap
new file mode 100644
index 000000000..e53761386
--- /dev/null
+++ b/packages/eve/src/execution/wire/__snapshots__/session-inbox-wire.v2.test.ts.snap
@@ -0,0 +1,3 @@
+// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
+
+exports[`session inbox wire v2 > pins the complete schema byte for byte 1`] = `"{"$schema":"https://json-schema.org/draft/2020-12/schema","oneOf":[{"additionalProperties":false,"properties":{"auth":{"anyOf":[{"additionalProperties":false,"properties":{"attributes":{"additionalProperties":{"anyOf":[{"type":"string"},{"items":{"type":"string"},"type":"array"}]},"propertyNames":{"type":"string"},"type":"object"},"authenticator":{"type":"string"},"issuer":{"type":"string"},"principalId":{"type":"string"},"principalType":{"type":"string"},"subject":{"type":"string"}},"required":["attributes","authenticator","principalId","principalType"],"type":"object"},{"type":"null"}]},"caller":{"additionalProperties":false,"properties":{"activityObserver":{"additionalProperties":false,"properties":{"sink":{"additionalProperties":false,"properties":{"url":{"type":"string"},"version":{"const":1,"type":"number"}},"required":["url","version"],"type":"object"},"workIdentity":{"additionalProperties":false,"properties":{"callId":{"type":"string"},"id":{"type":"string"},"kind":{"enum":["root-turn","subagent","remote-agent","task"],"type":"string"},"name":{"type":"string"},"parentId":{"type":"string"},"rootSessionId":{"type":"string"},"rootTurnId":{"type":"string"},"sessionId":{"type":"string"},"turnId":{"type":"string"}},"required":["id","kind","rootSessionId","rootTurnId"],"type":"object"}},"required":["sink"],"type":"object"},"callId":{"type":"string"},"replyTo":{"oneOf":[{"additionalProperties":false,"properties":{"kind":{"const":"hook","type":"string"},"token":{"type":"string"}},"required":["kind","token"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"callback","type":"string"},"token":{"type":"string"},"url":{"type":"string"}},"required":["kind","token","url"],"type":"object"}]},"subagentName":{"type":"string"},"taskId":{"type":"string"}},"required":["callId","replyTo","subagentName"],"type":"object"},"deliveryMetadata":{"items":{"additionalProperties":false,"properties":{"channelKind":{"type":"string"},"channelName":{"type":"string"},"deliveryId":{"type":"string"},"payloadIndex":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"requestId":{"type":"string"},"requestTraceContext":{"additionalProperties":false,"properties":{"spanId":{"type":"string"},"traceFlags":{"type":"number"},"traceId":{"type":"string"}},"required":["spanId","traceFlags","traceId"],"type":"object"}},"required":["channelKind","channelName","deliveryId","payloadIndex"],"type":"object"},"type":"array"},"kind":{"const":"deliver","type":"string"},"payload":{"additionalProperties":{},"properties":{"context":{"items":{"type":"string"},"type":"array"},"inputResponses":{"items":{"additionalProperties":false,"properties":{"optionId":{"type":"string"},"requestId":{"type":"string"},"text":{"type":"string"}},"required":["requestId"],"type":"object"},"type":"array"},"message":{"anyOf":[{"type":"string"},{"items":{"oneOf":[{"additionalProperties":false,"properties":{"providerOptions":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"text":{"type":"string"},"type":{"const":"text","type":"string"}},"required":["text","type"],"type":"object"},{"additionalProperties":false,"properties":{"image":{},"mediaType":{"type":"string"},"providerOptions":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"type":{"const":"image","type":"string"}},"required":["image","type"],"type":"object"},{"additionalProperties":false,"properties":{"data":{},"filename":{"type":"string"},"mediaType":{"type":"string"},"providerOptions":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"type":{"const":"file","type":"string"}},"required":["data","mediaType","type"],"type":"object"}]},"type":"array"}]},"outputSchema":{},"task":{"additionalProperties":false,"properties":{"authorizationEvents":{"items":{"additionalProperties":false,"properties":{"hookPayload":{"additionalProperties":false,"properties":{"callId":{"type":"string"},"childSessionId":{"type":"string"},"event":{},"kind":{"const":"subagent-authorization-event","type":"string"},"subagentName":{"type":"string"}},"required":["callId","childSessionId","event","kind","subagentName"],"type":"object"},"taskId":{"type":"string"}},"required":["hookPayload","taskId"],"type":"object"},"type":"array"},"inputRequests":{"items":{"additionalProperties":false,"properties":{"hookPayload":{"additionalProperties":false,"properties":{"callId":{"type":"string"},"childContinuationToken":{"type":"string"},"childSessionId":{"type":"string"},"event":{"additionalProperties":false,"properties":{"requests":{"items":{"additionalProperties":false,"properties":{"action":{"additionalProperties":false,"properties":{"callId":{"type":"string"},"input":{},"kind":{"const":"tool-call","type":"string"},"toolName":{"type":"string"}},"required":["callId","input","kind","toolName"],"type":"object"},"allowFreeform":{"description":"Whether the user may answer with freeform text instead of selecting one of the provided options.","type":"boolean"},"display":{"description":"Rendering hint: the channel uses this to pick a UX treatment.","enum":["confirmation","select","text"],"type":"string"},"kind":{"description":"Framework-owned request source used to resolve, route, and render the response.","enum":["question","session-limit","tool-approval"],"type":"string"},"options":{"description":"Selectable answer options to present to the user.","items":{"additionalProperties":false,"properties":{"description":{"description":"Optional additional context for this option.","type":"string"},"id":{"description":"Stable identifier for the option.","type":"string"},"label":{"description":"User-facing label for the option.","type":"string"},"style":{"description":"Visual treatment hint for the option.","enum":["primary","danger","default"],"type":"string"}},"required":["id","label"],"type":"object"},"type":"array"},"prompt":{"description":"The prompt to present to the user.","type":"string"},"requestId":{"description":"Stable identifier for this request.","type":"string"}},"required":["action","kind","prompt","requestId"],"type":"object"},"type":"array"},"sequence":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"stepIndex":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"turnId":{"type":"string"}},"required":["requests","sequence","stepIndex","turnId"],"type":"object"},"kind":{"const":"subagent-input-request","type":"string"},"subagentName":{"type":"string"}},"required":["callId","childContinuationToken","childSessionId","event","kind","subagentName"],"type":"object"},"taskId":{"type":"string"}},"required":["hookPayload","taskId"],"type":"object"},"type":"array"},"views":{"items":{"oneOf":[{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"},"childSessionId":{"type":"string"},"childTurnId":{"type":"string"},"lifecycle":{"enum":["parked","terminal"],"type":"string"}},"type":"object"},"metadata":{"anyOf":[{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"const":"subagent","type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["agentId","kind","mode","name"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"}]},"status":{"const":"working","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"},"childSessionId":{"type":"string"},"childTurnId":{"type":"string"},"lifecycle":{"enum":["parked","terminal"],"type":"string"}},"type":"object"},"inputRequests":{"items":{},"type":"array"},"metadata":{"anyOf":[{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"const":"subagent","type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["agentId","kind","mode","name"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"}]},"status":{"const":"input_required","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","inputRequests","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"},"childSessionId":{"type":"string"},"childTurnId":{"type":"string"},"lifecycle":{"enum":["parked","terminal"],"type":"string"}},"type":"object"},"lastOutput":{"additionalProperties":false,"properties":{"data":{},"type":{"const":"result","type":"string"}},"required":["data","type"],"type":"object"},"metadata":{"anyOf":[{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"const":"subagent","type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["agentId","kind","mode","name"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"}]},"status":{"const":"completed","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","lastOutput","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"},"childSessionId":{"type":"string"},"childTurnId":{"type":"string"},"lifecycle":{"enum":["parked","terminal"],"type":"string"}},"type":"object"},"lastOutput":{"additionalProperties":false,"properties":{"data":{},"type":{"const":"error","type":"string"}},"required":["data","type"],"type":"object"},"metadata":{"anyOf":[{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"const":"subagent","type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["agentId","kind","mode","name"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"}]},"status":{"const":"failed","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","lastOutput","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"},"childSessionId":{"type":"string"},"childTurnId":{"type":"string"},"lifecycle":{"enum":["parked","terminal"],"type":"string"}},"type":"object"},"metadata":{"anyOf":[{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"const":"subagent","type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["agentId","kind","mode","name"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"}]},"status":{"const":"cancelled","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","status"],"type":"object"}]},"type":"array"}},"type":"object"}},"type":"object"},"payloads":{"items":{"additionalProperties":{},"properties":{"context":{"items":{"type":"string"},"type":"array"},"inputResponses":{"items":{"additionalProperties":false,"properties":{"optionId":{"type":"string"},"requestId":{"type":"string"},"text":{"type":"string"}},"required":["requestId"],"type":"object"},"type":"array"},"message":{"anyOf":[{"type":"string"},{"items":{"oneOf":[{"additionalProperties":false,"properties":{"providerOptions":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"text":{"type":"string"},"type":{"const":"text","type":"string"}},"required":["text","type"],"type":"object"},{"additionalProperties":false,"properties":{"image":{},"mediaType":{"type":"string"},"providerOptions":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"type":{"const":"image","type":"string"}},"required":["image","type"],"type":"object"},{"additionalProperties":false,"properties":{"data":{},"filename":{"type":"string"},"mediaType":{"type":"string"},"providerOptions":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"type":{"const":"file","type":"string"}},"required":["data","mediaType","type"],"type":"object"}]},"type":"array"}]},"outputSchema":{},"task":{"additionalProperties":false,"properties":{"authorizationEvents":{"items":{"additionalProperties":false,"properties":{"hookPayload":{"additionalProperties":false,"properties":{"callId":{"type":"string"},"childSessionId":{"type":"string"},"event":{},"kind":{"const":"subagent-authorization-event","type":"string"},"subagentName":{"type":"string"}},"required":["callId","childSessionId","event","kind","subagentName"],"type":"object"},"taskId":{"type":"string"}},"required":["hookPayload","taskId"],"type":"object"},"type":"array"},"inputRequests":{"items":{"additionalProperties":false,"properties":{"hookPayload":{"additionalProperties":false,"properties":{"callId":{"type":"string"},"childContinuationToken":{"type":"string"},"childSessionId":{"type":"string"},"event":{"additionalProperties":false,"properties":{"requests":{"items":{"additionalProperties":false,"properties":{"action":{"additionalProperties":false,"properties":{"callId":{"type":"string"},"input":{},"kind":{"const":"tool-call","type":"string"},"toolName":{"type":"string"}},"required":["callId","input","kind","toolName"],"type":"object"},"allowFreeform":{"description":"Whether the user may answer with freeform text instead of selecting one of the provided options.","type":"boolean"},"display":{"description":"Rendering hint: the channel uses this to pick a UX treatment.","enum":["confirmation","select","text"],"type":"string"},"kind":{"description":"Framework-owned request source used to resolve, route, and render the response.","enum":["question","session-limit","tool-approval"],"type":"string"},"options":{"description":"Selectable answer options to present to the user.","items":{"additionalProperties":false,"properties":{"description":{"description":"Optional additional context for this option.","type":"string"},"id":{"description":"Stable identifier for the option.","type":"string"},"label":{"description":"User-facing label for the option.","type":"string"},"style":{"description":"Visual treatment hint for the option.","enum":["primary","danger","default"],"type":"string"}},"required":["id","label"],"type":"object"},"type":"array"},"prompt":{"description":"The prompt to present to the user.","type":"string"},"requestId":{"description":"Stable identifier for this request.","type":"string"}},"required":["action","kind","prompt","requestId"],"type":"object"},"type":"array"},"sequence":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"stepIndex":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"turnId":{"type":"string"}},"required":["requests","sequence","stepIndex","turnId"],"type":"object"},"kind":{"const":"subagent-input-request","type":"string"},"subagentName":{"type":"string"}},"required":["callId","childContinuationToken","childSessionId","event","kind","subagentName"],"type":"object"},"taskId":{"type":"string"}},"required":["hookPayload","taskId"],"type":"object"},"type":"array"},"views":{"items":{"oneOf":[{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"},"childSessionId":{"type":"string"},"childTurnId":{"type":"string"},"lifecycle":{"enum":["parked","terminal"],"type":"string"}},"type":"object"},"metadata":{"anyOf":[{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"const":"subagent","type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["agentId","kind","mode","name"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"}]},"status":{"const":"working","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"},"childSessionId":{"type":"string"},"childTurnId":{"type":"string"},"lifecycle":{"enum":["parked","terminal"],"type":"string"}},"type":"object"},"inputRequests":{"items":{},"type":"array"},"metadata":{"anyOf":[{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"const":"subagent","type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["agentId","kind","mode","name"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"}]},"status":{"const":"input_required","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","inputRequests","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"},"childSessionId":{"type":"string"},"childTurnId":{"type":"string"},"lifecycle":{"enum":["parked","terminal"],"type":"string"}},"type":"object"},"lastOutput":{"additionalProperties":false,"properties":{"data":{},"type":{"const":"result","type":"string"}},"required":["data","type"],"type":"object"},"metadata":{"anyOf":[{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"const":"subagent","type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["agentId","kind","mode","name"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"}]},"status":{"const":"completed","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","lastOutput","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"},"childSessionId":{"type":"string"},"childTurnId":{"type":"string"},"lifecycle":{"enum":["parked","terminal"],"type":"string"}},"type":"object"},"lastOutput":{"additionalProperties":false,"properties":{"data":{},"type":{"const":"error","type":"string"}},"required":["data","type"],"type":"object"},"metadata":{"anyOf":[{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"const":"subagent","type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["agentId","kind","mode","name"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"}]},"status":{"const":"failed","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","lastOutput","status"],"type":"object"},{"additionalProperties":false,"properties":{"executor":{"additionalProperties":false,"properties":{"binding":{"additionalProperties":false,"properties":{"data":{"additionalProperties":{},"propertyNames":{"type":"string"},"type":"object"},"kind":{"type":"string"}},"required":["data","kind"],"type":"object"},"childSessionId":{"type":"string"},"childTurnId":{"type":"string"},"lifecycle":{"enum":["parked","terminal"],"type":"string"}},"type":"object"},"metadata":{"anyOf":[{"additionalProperties":false,"properties":{"agentId":{"type":"string"},"kind":{"const":"subagent","type":"string"},"mode":{"enum":["local","remote"],"type":"string"},"name":{"type":"string"}},"required":["agentId","kind","mode","name"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"type":"string"},"name":{"type":"string"}},"required":["kind","name"],"type":"object"}]},"status":{"const":"cancelled","type":"string"},"taskId":{"type":"string"},"usage":{"properties":{"cacheReadTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"cacheWriteTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"inputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"},"outputTokens":{"maximum":9007199254740991,"minimum":0,"type":"integer"}},"required":["cacheReadTokens","cacheWriteTokens","inputTokens","outputTokens"],"type":"object"}},"required":["metadata","taskId","status"],"type":"object"}]},"type":"array"}},"type":"object"}},"type":"object"},"type":"array"},"requestId":{"type":"string"},"taskDeliveryId":{"type":"string"},"turnPolicy":{"enum":["queue","steer"],"type":"string"},"version":{"const":2,"type":"number"}},"required":["kind","payload","payloads","version"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"session-timeout","type":"string"},"version":{"const":2,"type":"number"}},"required":["kind","version"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"clear","type":"string"},"version":{"const":2,"type":"number"}},"required":["kind","version"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"compact","type":"string"},"version":{"const":2,"type":"number"}},"required":["kind","version"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"reset","type":"string"},"reason":{"type":"string"},"version":{"const":2,"type":"number"}},"required":["kind","version"],"type":"object"},{"additionalProperties":false,"properties":{"kind":{"const":"cancel","type":"string"},"taskId":{"type":"string"},"turnId":{"type":"string"},"version":{"const":2,"type":"number"}},"required":["kind","version"],"type":"object"}]}"`;
diff --git a/packages/eve/src/execution/wire/session-inbox-contract.ts b/packages/eve/src/execution/wire/session-inbox-contract.ts
index 5b65d4ad9..c8b1e0212 100644
--- a/packages/eve/src/execution/wire/session-inbox-contract.ts
+++ b/packages/eve/src/execution/wire/session-inbox-contract.ts
@@ -1,5 +1,5 @@
/** Every explicit session-inbox wire version still supported by producers. */
-export const SESSION_INBOX_WIRE_VERSIONS = [1] as const;
+export const SESSION_INBOX_WIRE_VERSIONS = [1, 2] as const;
export type SessionInboxWireVersion = (typeof SESSION_INBOX_WIRE_VERSIONS)[number];
diff --git a/packages/eve/src/execution/wire/session-inbox-encoder.ts b/packages/eve/src/execution/wire/session-inbox-encoder.ts
index 6ad30c5c7..85c30e8e2 100644
--- a/packages/eve/src/execution/wire/session-inbox-encoder.ts
+++ b/packages/eve/src/execution/wire/session-inbox-encoder.ts
@@ -7,6 +7,10 @@ import {
encodeSessionCommandV1,
type SessionInboxWireV1,
} from "#execution/wire/session-inbox-wire.v1.js";
+import {
+ encodeSessionCommandV2,
+ type SessionInboxWireV2,
+} from "#execution/wire/session-inbox-wire.v2.js";
import {
isSessionInboxWireVersion,
SessionInboxWireError,
@@ -18,17 +22,19 @@ import { encodeSessionCommandV0 } from "#execution/wire/session-inbox-wire.v0.js
type SessionInboxCommand = DeliverHookPayload | SessionCommand | SessionTimeoutHookPayload;
/** Current wire type consumed after migration. */
-export type SessionInboxWire = SessionInboxWireV1;
+export type SessionInboxWire = SessionInboxWireV2;
type LegacySessionInboxWireTarget = Extract<SessionInboxWireTarget, { readonly version: 0 }>;
type VersionedSessionInboxEncoder = (command: SessionInboxCommand) => unknown;
const versionedEncoders = {
- 1: encodeSessionCommandV1,
+ 1: (command: SessionInboxCommand) => encodeSessionCommandV1(withoutActivityObserver(command)),
+ 2: encodeSessionCommandV2,
} satisfies Record<SessionInboxWireVersion, VersionedSessionInboxEncoder>;
/** Encodes a command for the selected session-inbox consumer. */
function encode(command: SessionInboxCommand, target: { readonly version: 1 }): SessionInboxWireV1;
+function encode(command: SessionInboxCommand, target: { readonly version: 2 }): SessionInboxWireV2;
function encode(
command: SessionInboxCommand,
target: { readonly version: SessionInboxWireVersion },
@@ -40,21 +46,30 @@ function encode(
function encode(
command: SessionInboxCommand,
target: SessionInboxWireTarget,
-): SessionInboxWireV1 | Record<string, unknown>;
+): SessionInboxWireV1 | SessionInboxWireV2 | Record<string, unknown>;
function encode(
command: SessionInboxCommand,
target: SessionInboxWireTarget,
-): SessionInboxWireV1 | Record<string, unknown> {
+): SessionInboxWireV1 | SessionInboxWireV2 | Record<string, unknown> {
if (target.version === 0) {
- return encodeSessionCommandV0(encodeSessionCommandV1(command), target.variant);
+ return encodeSessionCommandV0(
+ encodeSessionCommandV1(withoutActivityObserver(command)),
+ target.variant,
+ );
}
if (isSessionInboxWireVersion(target.version)) {
- return versionedEncoders[target.version](command) as SessionInboxWireV1;
+ return versionedEncoders[target.version](command) as SessionInboxWireV1 | SessionInboxWireV2;
}
throw new SessionInboxWireError(
`Cannot encode session inbox payload for unknown wire version ${JSON.stringify((target as { version?: unknown }).version)}.`,
);
}
+function withoutActivityObserver(command: SessionInboxCommand): SessionInboxCommand {
+ if (!("caller" in command) || command.caller?.activityObserver === undefined) return command;
+ const { activityObserver: _activityObserver, ...caller } = command.caller;
+ return { ...command, caller };
+}
+
/** Server/step-safe producer facade. */
export const sessionInboxWire = { encode } as const;
diff --git a/packages/eve/src/execution/wire/session-inbox-wire.ts b/packages/eve/src/execution/wire/session-inbox-wire.ts
index 5146a5f6a..8f8ee6f1d 100644
--- a/packages/eve/src/execution/wire/session-inbox-wire.ts
+++ b/packages/eve/src/execution/wire/session-inbox-wire.ts
@@ -14,6 +14,10 @@ import {
} from "#execution/wire/session-inbox-contract.js";
import type { SessionInboxWire } from "#execution/wire/session-inbox-encoder.js";
import { sessionInboxWireV0Migration } from "#execution/wire/session-inbox-wire.v0.js";
+import {
+ normalizeSessionInboxWireV2,
+ sessionInboxWireV1Migration,
+} from "#execution/wire/session-inbox-wire.v2-migration.js";
/**
* The session inbox wire family: every payload persisted to a session's
@@ -38,7 +42,10 @@ export { SessionInboxWireError } from "#execution/wire/session-inbox-contract.js
/** Prefixes chain and schema failures alike, so messages read as one voice. */
const WIRE_LABEL = "session inbox payload";
-const sessionInboxMigrations: readonly VersionMigration[] = [sessionInboxWireV0Migration];
+const sessionInboxMigrations: readonly VersionMigration[] = [
+ sessionInboxWireV0Migration,
+ sessionInboxWireV1Migration,
+];
/**
* Decodes a persisted inbox payload or throws {@link SessionInboxWireError}.
@@ -48,6 +55,10 @@ const sessionInboxMigrations: readonly VersionMigration[] = [sessionInboxWireV0M
* delivery is the bug this module exists to prevent.
*/
function decode(value: unknown): DecodedSessionInbox {
+ const declaredVersion =
+ typeof value === "object" && value !== null && "version" in value
+ ? (value as { readonly version?: unknown }).version
+ : undefined;
let migrated: unknown;
try {
migrated = runMigrationChain({
@@ -61,12 +72,15 @@ function decode(value: unknown): DecodedSessionInbox {
throw new SessionInboxWireError(error instanceof Error ? error.message : String(error));
}
- const wire = migrated as Partial<SessionInboxWire>;
+ const wire = normalizeSessionInboxWireV2(migrated) as Partial<SessionInboxWire>;
if (wire.version !== SESSION_INBOX_WIRE_VERSION) {
throw new SessionInboxWireError(
`${WIRE_LABEL} declares version ${JSON.stringify(wire.version)}, expected ${SESSION_INBOX_WIRE_VERSION}.`,
);
}
+ if (declaredVersion === 2 && wire.kind === "deliver" && !("payload" in wire)) {
+ throw new SessionInboxWireError(`${WIRE_LABEL} does not match wire version 2.`);
+ }
return normalizeWire(wire as SessionInboxWire);
}
diff --git a/packages/eve/src/execution/wire/session-inbox-wire.v2-migration.ts b/packages/eve/src/execution/wire/session-inbox-wire.v2-migration.ts
new file mode 100644
index 000000000..e0168de57
--- /dev/null
+++ b/packages/eve/src/execution/wire/session-inbox-wire.v2-migration.ts
@@ -0,0 +1,39 @@
+import type { VersionMigration } from "#execution/durable-session-migrations/chain.js";
+import { isObject } from "#shared/guards.js";
+
+export const sessionInboxWireV1Migration: VersionMigration = {
+ from: 1,
+ migrate(prior) {
+ const normalized = normalizeSessionInboxWireV2(prior) as Record<string, unknown>;
+ return {
+ ...normalized,
+ ...(normalized.kind === "deliver" && !("payload" in normalized) ? { payload: {} } : {}),
+ version: 2,
+ };
+ },
+ to: 2,
+};
+
+/** Converts Workflow-VM records into this realm before wire consumption. */
+export function normalizeSessionInboxWireV2(value: unknown, arrayFallback = false): unknown {
+ if (value === undefined) return arrayFallback ? null : undefined;
+ if (Array.isArray(value)) {
+ return value.map((item) => normalizeSessionInboxWireV2(item, true));
+ }
+ if (!isPlainRecord(value)) return value;
+ return Object.fromEntries(
+ Object.entries(value)
+ .filter((entry) => entry[1] !== undefined)
+ .map(([key, item]) => [key, normalizeSessionInboxWireV2(item)]),
+ );
+}
+
+function isPlainRecord(value: unknown): value is Record<string, unknown> {
+ if (!isObject(value)) return false;
+ const prototype = Object.getPrototypeOf(value);
+ return (
+ prototype === null ||
+ prototype === Object.prototype ||
+ Object.getPrototypeOf(prototype) === null
+ );
+}
diff --git a/packages/eve/src/execution/wire/session-inbox-wire.v2.test.ts b/packages/eve/src/execution/wire/session-inbox-wire.v2.test.ts
new file mode 100644
index 000000000..3dcac0a91
--- /dev/null
+++ b/packages/eve/src/execution/wire/session-inbox-wire.v2.test.ts
@@ -0,0 +1,243 @@
+import { runInNewContext } from "node:vm";
+
+import { describe, expect, it } from "vitest";
+import { z } from "#compiled/zod/index.js";
+
+import { sessionInboxWire as sessionInboxWireEncoder } from "#execution/wire/session-inbox-encoder.js";
+import { sessionInboxWire as sessionInboxWireDecoder } from "#execution/wire/session-inbox-wire.js";
+import { sessionInboxWireV2Schema } from "#execution/wire/session-inbox-wire.v2.js";
+
+const activityObserver = {
+ sink: { url: "https://example.com/eve/v1/activity/opaque-token", version: 1 as const },
+ workIdentity: {
+ callId: "call-1",
+ id: "work:call-1",
+ kind: "subagent" as const,
+ name: "researcher",
+ rootSessionId: "root",
+ rootTurnId: "turn",
+ },
+};
+const caller = {
+ activityObserver,
+ callId: "call-1",
+ replyTo: {
+ kind: "callback" as const,
+ token: "callback-token",
+ url: "https://example.com/callback",
+ },
+ subagentName: "researcher",
+};
+
+describe("session inbox wire v2", () => {
+ it("rejects empty deliveries", () => {
+ expect(() =>
+ sessionInboxWireDecoder.decode({ kind: "deliver", payloads: [], version: 2 }),
+ ).toThrowError();
+ });
+
+ it("preserves activity observers for v2 consumers", () => {
+ const wire = sessionInboxWireEncoder.encode(
+ { caller, kind: "send", payload: { message: "observe" } },
+ { version: 2 },
+ );
+
+ expect(wire).toMatchObject({ caller, version: 2 });
+ expect(sessionInboxWireDecoder.decode(JSON.parse(JSON.stringify(wire)))).toMatchObject({
+ caller,
+ kind: "deliver",
+ payloads: [{ message: "observe" }],
+ });
+ });
+
+ it("round-trips task deliveries with activity observers", () => {
+ const task = {
+ views: [
+ {
+ metadata: {
+ agentId: "agent-1",
+ kind: "subagent" as const,
+ mode: "local" as const,
+ name: "researcher",
+ },
+ status: "working" as const,
+ taskId: "task-1",
+ },
+ ],
+ };
+ const wire = sessionInboxWireEncoder.encode(
+ { caller, kind: "deliver", payloads: [{ task }] },
+ { version: 2 },
+ );
+
+ expect(sessionInboxWireDecoder.decode(JSON.parse(JSON.stringify(wire)))).toMatchObject({
+ caller,
+ kind: "deliver",
+ payloads: [{ task }],
+ });
+ });
+
+ it("normalizes omitted task values to their JSON wire representation", () => {
+ const payload = {
+ task: {
+ inputRequests: [
+ {
+ hookPayload: {
+ callId: "call-1",
+ childContinuationToken: "continue-1",
+ childSessionId: "child-1",
+ event: {
+ requests: [
+ {
+ action: {
+ callId: "tool-1",
+ input: { marker: "FIRST", omitted: undefined },
+ kind: "tool-call",
+ toolName: "first_gate",
+ },
+ kind: "tool-approval",
+ prompt: "Approve first_gate?",
+ requestId: "request-1",
+ },
+ ],
+ sequence: 1,
+ stepIndex: 0,
+ turnId: "turn-1",
+ },
+ kind: "subagent-input-request",
+ subagentName: "researcher",
+ },
+ taskId: "task-1",
+ },
+ ],
+ views: [
+ {
+ lastOutput: { data: { omitted: undefined, status: "done" }, type: "result" },
+ metadata: { kind: "tool", name: "export" },
+ status: "completed",
+ taskId: "task-2",
+ },
+ ],
+ },
+ };
+ const wire = sessionInboxWireEncoder.encode({ kind: "send", payload } as never, { version: 2 });
+
+ const expected = {
+ payloads: [
+ {
+ task: {
+ inputRequests: [
+ {
+ hookPayload: {
+ event: { requests: [{ action: { input: { marker: "FIRST" } } }] },
+ },
+ },
+ ],
+ views: [{ lastOutput: { data: { status: "done" } } }],
+ },
+ },
+ ],
+ };
+ expect(wire).toMatchObject(expected);
+ expect(sessionInboxWireDecoder.decode(wire)).toMatchObject(expected);
+ });
+
+ it("normalizes plain records received from another VM realm", () => {
+ const data = runInNewContext(
+ `({ address: { sessionRef: "child" }, identity: { id: "agent" } })`,
+ );
+ const wire = sessionInboxWireEncoder.encode(
+ {
+ kind: "send",
+ payload: {
+ task: {
+ views: [
+ {
+ executor: { binding: { data, kind: "subagent" } },
+ metadata: { kind: "subagent", name: "worker" },
+ status: "working",
+ taskId: "task-1",
+ },
+ ],
+ },
+ },
+ } as never,
+ { version: 2 },
+ );
+
+ expect(sessionInboxWireDecoder.decode(wire)).toMatchObject({
+ payloads: [
+ {
+ task: {
+ views: [
+ {
+ executor: {
+ binding: {
+ data: { address: { sessionRef: "child" }, identity: { id: "agent" } },
+ },
+ },
+ },
+ ],
+ },
+ },
+ ],
+ });
+ });
+
+ it("omits activity observers for v1 consumers", () => {
+ const wire = sessionInboxWireEncoder.encode(
+ { caller, kind: "send", payload: { message: "legacy" } },
+ { version: 1 },
+ );
+
+ expect(wire).toMatchObject({
+ caller: {
+ callId: "call-1",
+ replyTo: caller.replyTo,
+ subagentName: "researcher",
+ },
+ version: 1,
+ });
+ expect(wire).not.toHaveProperty("caller.activityObserver");
+ });
+
+ it("migrates frozen v1 deliveries before decoding", () => {
+ expect(
+ sessionInboxWireDecoder.decode({
+ caller: {
+ callId: "call-1",
+ replyTo: caller.replyTo,
+ subagentName: "researcher",
+ },
+ kind: "deliver",
+ payloads: [{ message: "legacy" }],
+ version: 1,
+ }),
+ ).toMatchObject({
+ caller: {
+ callId: "call-1",
+ replyTo: caller.replyTo,
+ subagentName: "researcher",
+ },
+ kind: "deliver",
+ payloads: [{ message: "legacy" }],
+ });
+ });
+
+ it("pins the complete schema byte for byte", () => {
+ expect(
+ stableStringify(
+ z.toJSONSchema(sessionInboxWireV2Schema, { io: "input", unrepresentable: "any" }),
+ ),
+ ).toMatchSnapshot();
+ });
+});
+
+function stableStringify(value: unknown): string {
+ return JSON.stringify(value, (_key, item) => {
+ if (item === null || typeof item !== "object" || Array.isArray(item)) return item;
+ return Object.fromEntries(
+ Object.entries(item).sort(([left], [right]) => left.localeCompare(right)),
+ );
+ });
+}
diff --git a/packages/eve/src/execution/wire/session-inbox-wire.v2.ts b/packages/eve/src/execution/wire/session-inbox-wire.v2.ts
new file mode 100644
index 000000000..d4508182f
--- /dev/null
+++ b/packages/eve/src/execution/wire/session-inbox-wire.v2.ts
@@ -0,0 +1,91 @@
+import { z } from "#compiled/zod/index.js";
+
+import type {
+ DeliverHookPayload,
+ SessionCommand,
+ SessionTimeoutHookPayload,
+} from "#channel/types.js";
+import { coalesceDeliverPayloads } from "#execution/deliver-payloads.js";
+import { SessionInboxWireError } from "#execution/wire/session-inbox-contract.js";
+import { sessionInboxWireV1Schema } from "#execution/wire/session-inbox-wire.v1.js";
+import { normalizeSessionInboxWireV2 } from "#execution/wire/session-inbox-wire.v2-migration.js";
+import { formatValidationError } from "#runtime/validation.js";
+
+const activityWorkIdentitySchema = z
+ .object({
+ callId: z.string().optional(),
+ id: z.string(),
+ kind: z.enum(["root-turn", "subagent", "remote-agent", "task"]),
+ name: z.string().optional(),
+ parentId: z.string().optional(),
+ rootSessionId: z.string(),
+ rootTurnId: z.string(),
+ sessionId: z.string().optional(),
+ turnId: z.string().optional(),
+ })
+ .strict();
+const activityObserverSchema = z
+ .object({
+ sink: z.object({ url: z.string(), version: z.literal(1) }).strict(),
+ workIdentity: activityWorkIdentitySchema.optional(),
+ })
+ .strict();
+const v1 = sessionInboxWireV1Schema.options;
+const v1Deliver = v1[0];
+const v1Caller = v1Deliver.shape.caller.unwrap();
+const version = z.literal(2);
+
+/** Version 2 adds activity observer metadata to delegated callers. */
+export const sessionInboxWireV2Schema = z.discriminatedUnion("kind", [
+ v1Deliver.extend({
+ caller: v1Caller.extend({ activityObserver: activityObserverSchema.optional() }).optional(),
+ payload: v1Deliver.shape.payload.unwrap(),
+ version,
+ }),
+ v1[1].extend({ version }),
+ v1[2].extend({ version }),
+ v1[3].extend({ version }),
+ v1[4].extend({ version }),
+ v1[5].extend({ version }),
+]);
+
+export type SessionInboxWireV2 = z.infer<typeof sessionInboxWireV2Schema>;
+
+export function parseSessionInboxWireV2(value: unknown) {
+ return sessionInboxWireV2Schema.safeParse(normalizeSessionInboxWireV2(value));
+}
+
+/** Builds and validates one complete version-2 wire value. */
+export function encodeSessionCommandV2(
+ command: DeliverHookPayload | SessionCommand | SessionTimeoutHookPayload,
+): SessionInboxWireV2 {
+ const wire =
+ command.kind === "send"
+ ? {
+ auth: command.auth,
+ caller: command.caller,
+ deliveryMetadata:
+ command.delivery === undefined ? undefined : [{ ...command.delivery, payloadIndex: 0 }],
+ kind: "deliver" as const,
+ payload: command.payload,
+ payloads: [command.payload],
+ requestId: command.requestId,
+ taskDeliveryId: command.taskDeliveryId,
+ turnPolicy: command.turnPolicy,
+ version: 2 as const,
+ }
+ : command.kind === "deliver"
+ ? {
+ ...command,
+ payload: coalesceDeliverPayloads(command.payloads),
+ version: 2 as const,
+ }
+ : { ...command, version: 2 as const };
+ const parsed = parseSessionInboxWireV2(wire);
+ if (!parsed.success) {
+ throw new SessionInboxWireError(
+ `Produced a session inbox payload that does not match wire version 2: ${formatValidationError(parsed.error)}`,
+ );
+ }
+ return parsed.data;
+}
diff --git a/packages/eve/src/execution/workflow-runtime.test.ts b/packages/eve/src/execution/workflow-runtime.test.ts
index 768838f6a..cfe912c1f 100644
--- a/packages/eve/src/execution/workflow-runtime.test.ts
+++ b/packages/eve/src/execution/workflow-runtime.test.ts
@@ -2,7 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { ChannelAdapter } from "#channel/adapter.js";
import { attachChannelActivityPresentation } from "#channel/activity-renderer.js";
-import { ChannelRequestIdKey, ActivityKey } from "#context/keys.js";
+import { ChannelRequestIdKey, ActivityObserverKey } from "#context/keys.js";
import { resolveInstalledPackageInfo } from "#internal/application/package.js";
import {
createWorkflowRuntime,
@@ -454,7 +454,7 @@ describe("createWorkflowRuntime#createSession", () => {
});
expect(collectorInput.token).toHaveLength(43);
const workflowInput = startMock.mock.calls[1]?.[1][0];
- expect(workflowInput.serializedContext[ActivityKey.name]).toEqual({
+ expect(workflowInput.serializedContext[ActivityObserverKey.name]).toEqual({
sink: {
url: `https://agent.example.com/eve/v1/activity/${collectorInput.token}`,
version: 1,
@@ -504,7 +504,7 @@ describe("createWorkflowRuntime#createSession", () => {
});
const workflowInput = startMock.mock.calls[1]?.[1][0];
- expect(workflowInput.serializedContext[ActivityKey.name]).toBeUndefined();
+ expect(workflowInput.serializedContext[ActivityObserverKey.name]).toBeUndefined();
});
it("cancels the collector when root workflow startup fails", async () => {
diff --git a/packages/eve/src/execution/workflow-runtime.ts b/packages/eve/src/execution/workflow-runtime.ts
index e2f558468..7e489df49 100644
--- a/packages/eve/src/execution/workflow-runtime.ts
+++ b/packages/eve/src/execution/workflow-runtime.ts
@@ -21,8 +21,8 @@ import type {
SessionCommandResult,
SessionTraceContext,
} from "#channel/types.js";
+import { ActivityObserverKey } from "#context/keys.js";
import { serializeContext } from "#context/serialize.js";
-import { ActivityKey } from "#context/keys.js";
import {
ChannelInstrumentationKey,
OtelTraceEnabledKey,
@@ -185,9 +185,10 @@ export function createWorkflowRuntime(config: {
ctx.set(OtelTraceEnabledKey, getInstrumentationRuntime()?.prepareSessionTrace !== undefined);
const sessionTimeoutMs = effectiveAgent.limits?.sessionTimeoutMs;
let collectorRunId: string | undefined;
+ let activityObserver = input.activityObserver;
if (
input.parent === undefined &&
- input.activity === undefined &&
+ activityObserver === undefined &&
(getChannelActivityPresentation(input.adapter)?.renderers.length ?? 0) > 0
) {
const collectorContext = serializeContext(ctx);
@@ -211,12 +212,13 @@ export function createWorkflowRuntime(config: {
? `https://${process.env.VERCEL_URL}`
: "http://localhost:3000";
const baseUrl = resolveWorkflowCallbackBaseUrl(fallbackOrigin);
- ctx.set(ActivityKey, {
+ activityObserver = {
sink: {
url: createWorkflowCallbackUrl(baseUrl, createEveActivityRoutePath(token)),
version: 1,
},
- });
+ };
+ ctx.set(ActivityObserverKey, activityObserver);
} catch {
await cancelActivityCollector(collectorRunId);
collectorRunId = undefined;
diff --git a/packages/eve/src/execution/workflow-steps.test.ts b/packages/eve/src/execution/workflow-steps.test.ts
index 03b7cd7ea..2aac23d24 100644
--- a/packages/eve/src/execution/workflow-steps.test.ts
+++ b/packages/eve/src/execution/workflow-steps.test.ts
@@ -10,6 +10,7 @@ import type {
import { ContextContainer, contextStorage, loadContext } from "#context/container.js";
import { ContextKey } from "#context/key.js";
import {
+ ActivityObserverKey,
AuthKey,
ContinuationTokenKey,
DynamicSubagentAgentConfigKey,
@@ -1720,10 +1721,29 @@ describe("turnStep", () => {
return { next: null, session: stepSession };
};
});
- const fetchMock = vi.fn().mockResolvedValue(new Response(null, { status: 202 }));
+ const activityRequest = new Promise<Response>(() => {});
+ const fetchMock = vi.fn((url: string) =>
+ url.includes("/activity/")
+ ? activityRequest
+ : Promise.resolve(new Response(null, { status: 202 })),
+ );
vi.stubGlobal("fetch", fetchMock);
const ctx = new ContextContainer();
+ ctx.set(ActivityObserverKey, {
+ sink: {
+ url: "https://parent.example/eve/v1/activity/abcdefghijklmnopqrstuvwxyz123456",
+ version: 1,
+ },
+ workIdentity: {
+ callId: "parent-call",
+ id: "work:child",
+ kind: "task",
+ name: "remote-worker",
+ rootSessionId: "root",
+ rootTurnId: "turn-root",
+ },
+ });
ctx.set(AuthKey, null);
ctx.set(BundleKey, compiledBundle);
ctx.set(ChannelKey, remoteTaskAdapter);
@@ -1753,6 +1773,10 @@ describe("turnStep", () => {
);
expect(inputRequested).not.toHaveBeenCalled();
expect(workflowWritesByNamespace.get(DEFAULT_WORKFLOW_STREAM_NAMESPACE) ?? []).toEqual([]);
+ expect(fetchMock).toHaveBeenCalledWith(
+ "https://parent.example/eve/v1/activity/abcdefghijklmnopqrstuvwxyz123456",
+ expect.objectContaining({ body: expect.stringContaining('"kind":"blocker.started"') }),
+ );
});
it("keeps a session-scoped dynamic model selection when the first turn is cancelled", async () => {
diff --git a/packages/eve/src/execution/workflow-steps.ts b/packages/eve/src/execution/workflow-steps.ts
index aa514eb17..4d85831ea 100644
--- a/packages/eve/src/execution/workflow-steps.ts
+++ b/packages/eve/src/execution/workflow-steps.ts
@@ -52,6 +52,7 @@ import { matchAuthorizationCallbacks } from "#execution/authorization-callback-m
import { readTurnSleepDurationMs } from "#harness/turn-sleep.js";
import { isTurnCancellation, throwIfTurnAborted } from "#harness/turn-cancellation.js";
import { setChannelContext } from "#execution/channel-context.js";
+import { observeSessionActivity } from "#execution/session-activity-projection.js";
import { hasPendingInputBatch } from "#harness/input-requests.js";
import { activeTurnId } from "#harness/active-turn-id.js";
import { coalesceTurnInputs, normalizeUserContent } from "#harness/messages.js";
@@ -398,6 +399,7 @@ export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResu
messages,
nodeId: bundle.nodeId ?? "__root__",
});
+ void observeSessionActivity({ ctx, event: emitted, sessionId: initialSession.sessionId });
await dispatchStreamEventHooks({ ctx, registry: hookRegistry, event: emitted });
if (emitted.type !== "step.started") {
await dispatchDynamicModelEvent({
diff --git a/packages/eve/src/public/channels/eve.test.ts b/packages/eve/src/public/channels/eve.test.ts
index 1f721abb0..280ec7687 100644
--- a/packages/eve/src/public/channels/eve.test.ts
+++ b/packages/eve/src/public/channels/eve.test.ts
@@ -49,7 +49,14 @@ const OVERRIDE_AUTH: SessionAuthContext = {
type MockSendOptions = Pick<
RunInput,
- "auth" | "callback" | "capabilities" | "continuationToken" | "initiatorAuth" | "mode" | "title"
+ | "auth"
+ | "callback"
+ | "capabilities"
+ | "continuationToken"
+ | "activityObserver"
+ | "initiatorAuth"
+ | "mode"
+ | "title"
>;
function createJsonMessageRequest(body: unknown): Request {
@@ -126,6 +133,7 @@ function createEveCreateHandler(
callback: runInput.callback,
capabilities: runInput.capabilities,
continuationToken: runInput.continuationToken,
+ activityObserver: runInput.activityObserver,
initiatorAuth: runInput.initiatorAuth,
mode: runInput.mode,
title: runInput.title,
diff --git a/packages/eve/test/scenarios/mounted-extension-installed.scenario.test.ts b/packages/eve/test/scenarios/mounted-extension-installed.scenario.test.ts
index a19a5bee3..5e1461624 100644
--- a/packages/eve/test/scenarios/mounted-extension-installed.scenario.test.ts
+++ b/packages/eve/test/scenarios/mounted-extension-installed.scenario.test.ts
@@ -249,7 +249,7 @@ describe("mounted extension installed under node_modules", () => {
);
expect(
JSON.parse(extensionFiles[`node_modules/${PACKAGE_NAME}/dist/extension/_manifest.json`]!),
- ).toMatchObject({ requires: { channel: 11, schedule: 4, subagent: 5 } });
+ ).toMatchObject({ requires: { channel: 12, schedule: 5, subagent: 5 } });
const app = await scenarioApp({
name: "mounted-extension-installed",
installDependencies: true,