The Open Framework for Building Agents
fix(eve): settle agent task activity when the agent turn ends (#3980)
Andrew Barba0ec0381d7cae
diff --git a/.changeset/agent-activity-settles.md b/.changeset/agent-activity-settles.mdnew file mode 100644index 000000000..fbe785699--- /dev/null+++ b/.changeset/agent-activity-settles.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Channel activity, such as Slack, now shows each agent task or `ctx.agent` session as its own row under the call that opened it. The row settles as completed, failed, or cancelled when the agent's first turn ends, and a turn cancelled while it waits for an answer, including the caller's own, now settles as cancelled unless its own approval or sign-in can still be answered. Before, a local agent's activity merged into the caller's row and marked it done early, a remote agent's row stayed running until the caller's turn ended, and a later message to a remote agent, such as continuing its task by `taskId`, failed while activity was on. Later turns of the same session, such as a second `send` or a task continued by `taskId`, still appear under its first row.diff --git a/packages/eve/src/execution/activity-cohort.ts b/packages/eve/src/execution/activity-cohort.tsindex c2c1579fa..50e8c0871 100644--- a/packages/eve/src/execution/activity-cohort.ts+++ b/packages/eve/src/execution/activity-cohort.ts@@ -1,6 +1,6 @@import type { DeliverHookPayload } from "#channel/types.js";import type { MatchedAuthorizationCallback } from "#execution/authorization-callback-match.js";-import type { PendingAuthorizationState } from "#harness/authorization.js";+import { getPendingAuthorization, type PendingAuthorizationState } from "#harness/authorization.js";import type { ContextContainer } from "#context/container.js";import {ActivityObserverKey,@@ -8,9 +8,11 @@ import {ActivityRootTurnIdKey,ActivityTaskCallsKey,} from "#context/keys.js";+import { isSessionLimitPromptBatch } from "#harness/hitl/session-limit-input-requests.js";import {activityRequestIdsForRootTurn,activityRootTurnIdForInputResponses,+ getPendingInputBatches,} from "#harness/pending-input-batches.js";import type { SessionStateMap } from "#harness/types.js";import type { UnstampedMessageStreamEvent } from "#protocol/message.js";@@ -99,6 +101,31 @@ export function updateActivityState(}}+/**+ * Keeps only the blockers a cancel leaves answerable: the session's own input+ * requests and sign-ins. The cancel withdraws a session-limit prompt and what+ * a child asked through the session, so those no longer hold its work open.+ */+export function retainAnswerableActivityBlockers(+ ctx: ContextContainer,+ sessionState: SessionStateMap | undefined,+): void {+ const pending = ctx.get(ActivityPendingBlockersKey);+ if (pending === undefined) return;+ const answerable = new Set([+ ...getPendingInputBatches(sessionState).flatMap((batch) =>+ isSessionLimitPromptBatch(batch) ? [] : batch.requests.map((request) => request.requestId),+ ),+ ...(getPendingAuthorization(sessionState)?.challenges ?? []).flatMap(+ (challenge) => challenge.attemptId ?? challenge.candidateId ?? [],+ ),+ ]);+ clearActivityBlockers(+ ctx,+ pending.filter((id) => !answerable.has(id)),+ );+}+export function clearActivityBlockers(ctx: ContextContainer, ids: readonly string[]): void {const cleared = new Set(ids);const remaining = (ctx.get(ActivityPendingBlockersKey) ?? []).filter((id) => !cleared.has(id));diff --git a/packages/eve/src/execution/activity-events.ts b/packages/eve/src/execution/activity-events.tsindex 1c4bb7d1d..91609f78e 100644--- a/packages/eve/src/execution/activity-events.ts+++ b/packages/eve/src/execution/activity-events.ts@@ -69,6 +69,8 @@ export function projectActivityEvents(input: {}if (event.type === "action.result") {const result = event.data.result;+ // Only a child a call started before agents ran as tasks reports its+ // result on the caller's stream, under its unkeyed work id.if (result.kind === "subagent-result") {const workId = deriveChildActivityWorkId({callId: result.callId,@@ -229,11 +231,12 @@ export function projectActivityEvents(input: {};});}+ // Delegated work settles here too: an agent session's result reaches its+ // caller's reply hook, not the caller's stream.if (- lineage.kind === "root-turn" &&- (event.type === "turn.completed" ||- event.type === "turn.failed" ||- event.type === "turn.cancelled")+ event.type === "turn.completed" ||+ event.type === "turn.failed" ||+ event.type === "turn.cancelled") {const outcome =event.type === "turn.completed"diff --git a/packages/eve/src/execution/activity-work-id.ts b/packages/eve/src/execution/activity-work-id.tsindex eab2d4ee6..2ab9e30ee 100644--- a/packages/eve/src/execution/activity-work-id.ts+++ b/packages/eve/src/execution/activity-work-id.ts@@ -11,9 +11,15 @@ export function deriveChildActivityWorkId(input: {readonly callId: string;readonly parentSessionId: string;readonly parentTurnId: string;+ /**+ * Tells apart the sessions one call opens. Only the legacy `subagent-result`+ * settle omits it, for a child a call started before agents ran as tasks.+ */+ readonly sessionKey?: string;}): string {+ const session = input.sessionKey === undefined ? "" : `\0${input.sessionKey}`;const digest = createHash("sha256")- .update(`${input.parentSessionId}\0${input.parentTurnId}\0${input.callId}`)+ .update(`${input.parentSessionId}\0${input.parentTurnId}\0${input.callId}${session}`).digest("hex");return `work:${digest}`;}diff --git a/packages/eve/src/execution/activity-work.test.ts b/packages/eve/src/execution/activity-work.test.tsindex e08d22c54..50fd636c0 100644--- a/packages/eve/src/execution/activity-work.test.ts+++ b/packages/eve/src/execution/activity-work.test.ts@@ -36,6 +36,7 @@ describe("activity work identity", () => {parentSessionId: "root",parentTurnId: "turn-1",parentWork: root,+ sessionKey: "run-1:0",});const grandchild = deriveChildWorkIdentity({callId: "call-b",@@ -44,6 +45,7 @@ describe("activity work identity", () => {parentSessionId: "child-a",parentTurnId: "child-turn",parentWork: child,+ sessionKey: "run-2:0",});expect(grandchild).toMatchObject({@@ -83,6 +85,7 @@ describe("activity work identity", () => {parentSessionId: "a:b",parentTurnId: "c",parentWork,+ sessionKey: "run-1:0",});const second = deriveChildWorkIdentity({callId: "d",@@ -91,6 +94,7 @@ describe("activity work identity", () => {parentSessionId: "a",parentTurnId: "b:c",parentWork,+ sessionKey: "run-1:0",});expect(first.id).not.toBe(second.id);diff --git a/packages/eve/src/execution/activity-work.ts b/packages/eve/src/execution/activity-work.tsindex fd6006c0e..12ee75870 100644--- a/packages/eve/src/execution/activity-work.ts+++ b/packages/eve/src/execution/activity-work.ts@@ -26,6 +26,7 @@ export function deriveChildActivityObserverConfig(input: {readonly name: string;readonly parentSessionId: string;readonly parentTurnId: string;+ readonly sessionKey: string;readonly activityObserver: ActivityObserverConfig | undefined;}): ActivityObserverConfig | undefined {if (input.activityObserver?.workIdentity === undefined) return undefined;@@ -46,6 +47,7 @@ export function deriveChildWorkIdentity(input: {readonly parentSessionId: string;readonly parentTurnId: string;readonly parentWork: ActivityWorkIdentityV1;+ readonly sessionKey: string;}): ActivityWorkIdentityV1 {return {callId: input.callId,diff --git a/packages/eve/src/execution/agent-sessions/session.ts b/packages/eve/src/execution/agent-sessions/session.tsindex 8a88557a9..b43ae9fbf 100644--- a/packages/eve/src/execution/agent-sessions/session.ts+++ b/packages/eve/src/execution/agent-sessions/session.ts@@ -228,7 +228,7 @@ class RunAgentSession implements AgentSession {key: this.#key,name: this.#name,});- const opened = { address, context };+ const opened = { address, context, key: this.#key };this.#sessions.push(opened);await this.#run.owner.send({ from, kind: "agent-started", session: address });return opened;diff --git a/packages/eve/src/execution/agent-sessions/steps.test.ts b/packages/eve/src/execution/agent-sessions/steps.test.tsnew file mode 100644index 000000000..24ef39023--- /dev/null+++ b/packages/eve/src/execution/agent-sessions/steps.test.ts@@ -0,0 +1,304 @@+import { afterEach, describe, expect, it, vi } from "vitest";++import type { ActivityObserverConfig } from "#channel/types.js";+import type { AgentSessionContext } from "#execution/agent-sessions/context.js";+import {+ openAgentSessionStep,+ sendAgentSessionMessageStep,+} from "#execution/agent-sessions/steps.js";+import { deriveRootTurnActivityWorkId } from "#execution/activity-work-id.js";+import { projectSessionActivity } from "#execution/session-activity-projection.js";+import { createActivitySnapshot, reduceActivityBatch } from "#execution/session-activity.js";+import {+ createWorkflowRuntime,+ dispatchWorkflowSessionCommand,+} from "#execution/workflow-runtime.js";+import { parseSessionMessageBody } from "#eve-channel/request.js";+import type { MessageStreamEvent } from "#protocol/message.js";+import { REMOTE_AGENT_PROTOCOL_VERSION } from "#protocol/remote-agent-protocol.js";++const researcher = {+ description: "Researches a topic.",+ kind: "subagent",+ name: "researcher",+ nodeId: "agents/researcher",+};+const writer = {+ description: "Writes a summary.",+ kind: "subagent",+ name: "writer",+ nodeId: "agents/writer",+};+const remoteResearcher = {+ description: "Researches a topic remotely.",+ kind: "remote",+ logicalPath: "agents/remote-research.ts",+ name: "remote_research",+ nodeId: "agents/remote-research",+ path: "/eve/v1/session",+ sourceId: "agents/remote-research.ts",+ sourceKind: "module",+ url: "https://remote.example.com",+};++vi.mock("#compiled/@workflow/core/index.js", async (importOriginal) => ({+ ...(await importOriginal()),+ getWorkflowMetadata: () => ({ url: "https://parent.example.com" }),+}));++vi.mock("#runtime/sessions/compiled-agent-cache.js", () => ({+ getCompiledRuntimeAgentBundle: async () => {+ const definitions = [researcher, writer, remoteResearcher];+ return {+ compiledArtifactsSource: { kind: "test" },+ subagentRegistry: {+ subagentsByName: new Map(+ definitions.map((definition) => [definition.name, { definition }]),+ ),+ subagentsByNodeId: new Map(+ definitions.map((definition) => [definition.nodeId, { definition }]),+ ),+ },+ };+ },+}));++vi.mock("#execution/workflow-runtime.js", () => ({+ createWorkflowRuntime: vi.fn(),+ dispatchWorkflowSessionCommand: vi.fn(async () => ({ status: "accepted" })),+ requestWorkflowTurnCancellation: vi.fn(),+ waitForCommandHookOwner: vi.fn(async () => ({ runId: "child" })),+}));++const at = "2026-01-01T00:00:00.000Z";+const rootWorkId = deriveRootTurnActivityWorkId({ sessionId: "parent", turnId: "turn-1" });+const auth = { current: null, initiator: null };++function callerContext(): AgentSessionContext {+ return {+ activityObserver: {+ sink: {+ url: "https://parent.example.com/eve/v1/activity/abcdefghijklmnopqrstuvwxyz123456",+ version: 1,+ },+ workIdentity: {+ id: rootWorkId,+ kind: "root-turn",+ rootSessionId: "parent",+ rootTurnId: "turn-1",+ sessionId: "parent",+ turnId: "turn-1",+ },+ },+ agents: {},+ bundle: { source: { kind: "test" } as never },+ dynamicSelections: {},+ limits: {},+ parent: {+ callId: "call-1",+ rootSessionId: "parent",+ sessionId: "parent",+ turn: { id: "turn-1", sequence: 0 },+ },+ sandbox: { sessionId: "parent" },+ trace: { originAudience: { kind: "unknown" } } as never,+ };+}++function childTurn(turnId: string): MessageStreamEvent[] {+ const coordinates = { sequence: 0, stepIndex: 0, turnId };+ return [+ { data: { sequence: 0, turnId }, meta: { at, id: `${turnId}:started` }, type: "turn.started" },+ {+ data: {+ ...coordinates,+ actions: [{ callId: "search-1", input: {}, kind: "tool-call", toolName: "search" }],+ },+ meta: { at, id: `${turnId}:actions` },+ type: "actions.requested",+ },+ {+ data: { sequence: 0, turnId },+ meta: { at, id: `${turnId}:completed` },+ type: "turn.completed",+ },+ ];+}++function rootTurnStarted() {+ return projectSessionActivity({+ event: {+ data: { sequence: 0, turnId: "turn-1" },+ meta: { at, id: "parent:started" },+ type: "turn.started",+ },+ sessionId: "parent",+ });+}++function childSessionActivity(+ sessionId: string,+ observer: ActivityObserverConfig | undefined,+ events: readonly MessageStreamEvent[],+) {+ return events.flatMap((event) =>+ projectSessionActivity({ event, sessionId, workIdentity: observer?.workIdentity }),+ );+}++function localChildRuntime() {+ const createSession = vi.fn(async (_input: { activityObserver?: ActivityObserverConfig }) => ({+ sessionId: "child",+ }));+ vi.mocked(createWorkflowRuntime).mockReturnValue({ createSession } as never);+ return createSession;+}++afterEach(() => {+ vi.clearAllMocks();+ vi.unstubAllGlobals();+});++describe("agent session activity", () => {+ it("reports a local agent's turns as its own work that settles when the turn ends", async () => {+ const createSession = localChildRuntime();+ const context = callerContext();++ const address = await openAgentSessionStep({+ auth,+ context,+ key: "run-1:0",+ message: "Research the topic.",+ name: "researcher",+ replyTo: "reply-1",+ });+ await sendAgentSessionMessageStep({+ address,+ auth,+ context,+ key: "run-1:0",+ message: "Go deeper.",+ replyTo: "reply-2",+ });++ const opened = createSession.mock.calls[0]?.[0].activityObserver;+ const sent = vi.mocked(dispatchWorkflowSessionCommand).mock.calls[0]?.[0].command;+ expect(sent).toMatchObject({ caller: { activityObserver: opened } });+ const events = [+ ...rootTurnStarted(),+ ...childSessionActivity("child", opened, [+ { data: {}, meta: { at, id: "child:session" }, type: "session.started" },+ ...childTurn("turn_0"),+ ]),+ ];+ const snapshot = reduceActivityBatch(createActivitySnapshot(), { events, version: 1 });++ const childWorkId = opened?.workIdentity?.id ?? "";+ expect(snapshot.work).toEqual({+ [rootWorkId]: expect.objectContaining({ kind: "root-turn", phase: "running" }),+ [childWorkId]: expect.objectContaining({+ callId: "call-1",+ kind: "subagent",+ name: "researcher",+ parentId: rootWorkId,+ phase: "completed",+ }),+ });+ expect(Object.values(snapshot.actions)).toEqual([+ expect.objectContaining({ name: "search", parentWorkId: childWorkId }),+ ]);+ });++ it("reports each session one call opens as its own work that settles with its own turn", async () => {+ const createSession = localChildRuntime();+ const context = callerContext();+ for (const [index, name] of ["researcher", "writer"].entries()) {+ await openAgentSessionStep({+ auth,+ context,+ key: `run-1:${String(index)}`,+ message: "Work on the topic.",+ name,+ replyTo: `reply-${String(index)}`,+ });+ }+ const [research, write] = createSession.mock.calls.map(([input]) => input.activityObserver);+ const researchId = research?.workIdentity?.id ?? "";+ const writeId = write?.workIdentity?.id ?? "";+ const started: MessageStreamEvent = {+ data: {},+ meta: { at, id: "session" },+ type: "session.started",+ };++ const researchDone = reduceActivityBatch(createActivitySnapshot(), {+ events: [+ ...rootTurnStarted(),+ ...childSessionActivity("research-child", research, [started, ...childTurn("turn_0")]),+ ...childSessionActivity("write-child", write, [started, childTurn("turn_0")[0]!]),+ ],+ version: 1,+ });+ expect(researchDone.work).toEqual({+ [rootWorkId]: expect.objectContaining({ phase: "running" }),+ [researchId]: expect.objectContaining({ name: "researcher", phase: "completed" }),+ [writeId]: expect.objectContaining({ name: "writer", phase: "running" }),+ });++ const [, writeActions, writeEnd] = childTurn("turn_0");+ const writing = reduceActivityBatch(researchDone, {+ events: childSessionActivity("write-child", write, [writeActions!]),+ version: 1,+ });+ expect(Object.values(writing.actions)).toContainEqual(+ expect.objectContaining({ parentWorkId: writeId, phase: "running" }),+ );++ const bothDone = reduceActivityBatch(writing, {+ events: childSessionActivity("write-child", write, [writeEnd!]),+ version: 1,+ });+ expect(bothDone.work[writeId]).toMatchObject({ phase: "completed" });+ expect(bothDone.work[rootWorkId]).toMatchObject({ phase: "running" });+ });++ it("opens and continues a remote agent with one activity identity the remote accepts", async () => {+ const fetchMock = vi.fn(async (_url: string, _init: RequestInit) =>+ Response.json({+ ok: true,+ protocolVersion: REMOTE_AGENT_PROTOCOL_VERSION,+ sessionId: "remote-session",+ status: "accepted",+ }),+ );+ vi.stubGlobal("fetch", fetchMock);+ const context = callerContext();++ const address = await openAgentSessionStep({+ auth,+ context,+ key: "run-1:0",+ message: "Research the topic.",+ name: "remote_research",+ replyTo: "reply-1",+ });+ await sendAgentSessionMessageStep({+ address,+ auth,+ context,+ key: "run-1:0",+ message: "Go deeper.",+ replyTo: "reply-2",+ });++ const [opened, continued] = fetchMock.mock.calls.map(+ ([, init]) => JSON.parse(String(init.body)) as Record<string, unknown>,+ );+ expect(continued?.activityObserver).toEqual(opened?.activityObserver);+ expect(parseSessionMessageBody(continued ?? {})).toMatchObject({+ activityObserver: {+ workIdentity: { callId: "call-1", kind: "remote-agent", parentId: rootWorkId },+ },+ });+ });+});diff --git a/packages/eve/src/execution/agent-sessions/steps.ts b/packages/eve/src/execution/agent-sessions/steps.tsindex 9a2506fa7..d5a3a0f1d 100644--- a/packages/eve/src/execution/agent-sessions/steps.ts+++ b/packages/eve/src/execution/agent-sessions/steps.ts@@ -1,4 +1,5 @@import { getWorkflowMetadata } from "#compiled/@workflow/core/index.js";+import type { ActivityObserverConfig } from "#channel/types.js";import { ContextContainer, contextStorage } from "#context/container.js";import type { SessionAuth } from "#context/session-context.js";import type { AgentSessionContext } from "#execution/agent-sessions/context.js";@@ -65,6 +66,8 @@ export type AgentSessionAddress =export interface OpenedAgentSession {readonly address: AgentSessionAddress;readonly context: AgentSessionContext;+ /** Names the session within its run, as when it opened. */+ readonly key: string;}/**@@ -127,7 +130,7 @@ export async function sendAgentSessionMessageStep(if (address.kind === "remote") {const remote = await resolveSessionRemote(context, address);await continueRemoteAgentSession({- activityObserver: context.activityObserver,+ activityObserver: sessionActivityObserver(context, { ...address, key: input.key }),auth: input.auth.current,callback: {callId: context.parent.callId,@@ -149,7 +152,7 @@ export async function sendAgentSessionMessageStep(command: {auth: input.auth.current,caller: {- activityObserver: context.activityObserver,+ activityObserver: sessionActivityObserver(context, { ...address, key: input.key }),callId: context.parent.callId,replyTo: { kind: "hook", token: input.replyTo },subagentName: address.name,@@ -232,7 +235,11 @@ async function startLocalSession(const { action } = target;const { childContinuationToken, runInput } = buildSubagentRunInput({action,- activityObserver: context.activityObserver,+ activityObserver: sessionActivityObserver(context, {+ key: input.key,+ kind: "local",+ name: action.name,+ }),auth: auth.current,capabilities: context.capabilities,channelMetadata: context.channelMetadata,@@ -277,13 +284,10 @@ async function startRemoteSession(const callbackBaseUrl = resolveWorkflowCallbackBaseUrl(getWorkflowMetadata().url);const child = await startRemoteAgentSession({action,- activityObserver: deriveChildActivityObserverConfig({- activityObserver: context.activityObserver,- callId: action.callId,- kind: "remote-agent",+ activityObserver: sessionActivityObserver(context, {+ key: input.key,+ kind: "remote",name: action.remoteAgentName,- parentSessionId: context.parent.sessionId,- parentTurnId: context.parent.turn.id,}),auth: auth.current,callbackBaseUrl,@@ -307,6 +311,27 @@ async function startRemoteSession(};}+/**+ * The session's turns report their activity as its own work, beneath the+ * opening call's turn, never as the caller's. Every message carries the same+ * identity: its call id is the one steering and remote binding check, and the+ * session's key tells apart the sessions one call opens.+ */+function sessionActivityObserver(+ context: AgentSessionContext,+ session: Pick<AgentSessionAddress, "kind" | "name"> & { readonly key: string },+): ActivityObserverConfig | undefined {+ return deriveChildActivityObserverConfig({+ activityObserver: context.activityObserver,+ callId: context.parent.callId,+ kind: session.kind === "remote" ? "remote-agent" : "subagent",+ name: session.name,+ parentSessionId: context.parent.sessionId,+ parentTurnId: context.parent.turn.id,+ sessionKey: session.key,+ });+}+function createParentContext(context: AgentSessionContext, replyTo: string): SubagentParentContext {return {continuationToken: replyTo,diff --git a/packages/eve/src/execution/session-activity-projection.test.ts b/packages/eve/src/execution/session-activity-projection.test.tsindex 102203574..f4c554a1d 100644--- a/packages/eve/src/execution/session-activity-projection.test.ts+++ b/packages/eve/src/execution/session-activity-projection.test.ts@@ -1,7 +1,14 @@import { afterEach, describe, expect, it, vi } from "vitest";-import { ActivityObserverKey, ActivityTaskCallsKey } from "#context/keys.js";-import { updateActivityState } from "#execution/activity-cohort.js";+import {+ ActivityObserverKey,+ ActivityPendingBlockersKey,+ ActivityTaskCallsKey,+} from "#context/keys.js";+import {+ retainAnswerableActivityBlockers,+ updateActivityState,+} from "#execution/activity-cohort.js";import { ContextContainer } from "#context/container.js";import {observeSessionActivity,@@ -12,6 +19,8 @@ import { createActivitySnapshot, reduceActivityBatch } from "#execution/session-import type { ActivitySnapshotV1, ActivityWorkIdentityV1 } from "#protocol/activity.js";import type { MessageStreamEvent } from "#protocol/message.js";import { captureLogRecords } from "#internal/testing/log-records.js";+import { appendPendingInputBatch } from "#harness/pending-input-batches.js";+import type { HarnessSession, SessionStateMap } from "#harness/types.js";const at = "2026-01-01T00:00:00.000Z";@@ -37,20 +46,96 @@ function context(): ContextContainer {function reduceProjection(input: {readonly events: readonly MessageStreamEvent[];readonly sessionId: string;+ /** The session state a `turn.cancelled` settles, as `settleCancelledTurnStep` reads it. */+ readonly cancelledState?: SessionStateMap;readonly workIdentity?: ActivityWorkIdentityV1;}): ActivitySnapshotV1 {- return input.events.reduce(- (snapshot, event) =>- reduceActivityBatch(snapshot, {- events: projectSessionActivity({- event,- sessionId: input.sessionId,- workIdentity: input.workIdentity,- }),- version: 1,+ const ctx = context();+ return input.events.reduce((snapshot, event) => {+ if (event.type === "turn.cancelled") {+ retainAnswerableActivityBlockers(ctx, input.cancelledState);+ }+ updateActivityState(ctx, event);+ return reduceActivityBatch(snapshot, {+ events: projectSessionActivity({+ event,+ sessionId: input.sessionId,+ suppressSettlement: ctx.has(ActivityPendingBlockersKey),+ workIdentity: input.workIdentity,}),- createActivitySnapshot(),- );+ version: 1,+ });+ }, createActivitySnapshot());+}++const delegatedWork: ActivityWorkIdentityV1 = {+ callId: "call-1",+ id: "work:parent:turn-1:call-1",+ kind: "subagent",+ name: "researcher",+ parentId: "root:parent:turn-1",+ rootSessionId: "parent",+ rootTurnId: "turn-1",+};+const questionBlockerId = `input:${delegatedWork.id}:request-1`;++function inputRequested(+ requestId: string,+ kind: "question" | "tool-approval",+ turnId = "child-turn",+): MessageStreamEvent {+ return {+ data: {+ requests: [+ {+ action: { callId: `${requestId}-call`, input: {}, kind: "tool-call", toolName: "search" },+ kind,+ prompt: "Which region?",+ requestId,+ },+ ],+ sequence: 1,+ stepIndex: 0,+ turnId,+ },+ meta: { at, id: `input-requested:${requestId}` },+ type: "input.requested",+ };+}++const turnCancelled: MessageStreamEvent = {+ data: { sequence: 1, turnId: "child-turn" },+ meta: { at, id: "turn.cancelled:child-turn" },+ type: "turn.cancelled",+};++/** A delegated session whose running turn asked a question. */+const askedQuestion: readonly MessageStreamEvent[] = [+ { data: {}, meta: { at, id: "session-started" }, type: "session.started" },+ inputRequested("request-1", "question"),+];++/** The same session after its turn parked awaiting the answer. */+const parkedOnQuestion: readonly MessageStreamEvent[] = [+ ...askedQuestion,+ turnEvent("turn.completed", "child-turn"),+ {+ data: { continuationToken: "child-token", wait: "next-user-message" },+ meta: { at, id: "session-waiting" },+ type: "session.waiting",+ },+];++function projectDelegated(+ events: readonly MessageStreamEvent[],+ cancelledState?: SessionStateMap,+): ActivitySnapshotV1 {+ return reduceProjection({+ cancelledState,+ events,+ sessionId: "child-session",+ workIdentity: delegatedWork,+ });}describe("projectSessionActivity", () => {@@ -111,7 +196,7 @@ describe("projectSessionActivity", () => {event,rootTurnId: "turn-1",sessionId: "session-1",- suppressRootSettlement: true,+ suppressSettlement: true,}),).toEqual([]);});@@ -253,49 +338,53 @@ describe("projectSessionActivity", () => {]);});- 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",+ it("keeps delegated work open while its turn waits on a person, then settles it with the resumed turn", () => {+ const resumed: MessageStreamEvent[] = [+ {+ data: {+ resolutions: [{ kind: "question", outcome: "answered", requestId: "request-1" }],+ sequence: 2,+ stepIndex: 0,+ turnId: "child-turn-2",},- ],- sessionId: "child-session",- workIdentity,+ meta: { at, id: "input-resolved" },+ type: "input.resolved",+ },+ turnEvent("turn.started", "child-turn-2"),+ turnEvent("turn.completed", "child-turn-2"),+ ];++ const whileParked = projectDelegated(parkedOnQuestion);+ expect(whileParked.work[delegatedWork.id]).toMatchObject({ phase: "running" });+ expect(whileParked.blockers[questionBlockerId]).toMatchObject({ phase: "blocked" });++ expect(+ projectDelegated([...parkedOnQuestion, ...resumed]).work[delegatedWork.id],+ ).toMatchObject({ phase: "completed" });+ });++ it("settles work and its question when the turn waiting on the question is cancelled", () => {+ const snapshot = projectDelegated([...askedQuestion, turnCancelled]);++ expect(snapshot.work[delegatedWork.id]).toMatchObject({ phase: "cancelled" });+ expect(snapshot.blockers[questionBlockerId]).toMatchObject({ phase: "cancelled" });+ });++ it("keeps work open after a cancel while its own approval can still be answered", () => {+ const approval = inputRequested("approval-1", "tool-approval");+ const stillAwaitingApproval = appendPendingInputBatch({+ requests: approval.type === "input.requested" ? approval.data.requests : [],+ responseMessages: [],+ session: {} as HarnessSession,});- expect(snapshot.work[workIdentity.id]).toMatchObject({ phase: "running" });- expect(snapshot.blockers[`input:${workIdentity.id}:request-1`]).toMatchObject({+ const snapshot = projectDelegated(+ [...askedQuestion, approval, turnEvent("turn.completed", "child-turn"), turnCancelled],+ stillAwaitingApproval.state,+ );++ expect(snapshot.work[delegatedWork.id]).toMatchObject({ phase: "running" });+ expect(snapshot.blockers[`approval:${delegatedWork.id}:approval-1`]).toMatchObject({phase: "blocked",});});diff --git a/packages/eve/src/execution/session-activity-projection.ts b/packages/eve/src/execution/session-activity-projection.tsindex 169adc88d..1f2c73199 100644--- a/packages/eve/src/execution/session-activity-projection.ts+++ b/packages/eve/src/execution/session-activity-projection.ts@@ -24,7 +24,7 @@ export async function observeSessionActivity(input: {event: input.event,rootTurnId: input.ctx.get(ActivityRootTurnIdKey),sessionId: input.sessionId,- suppressRootSettlement: (input.ctx.get(ActivityPendingBlockersKey)?.length ?? 0) > 0,+ suppressSettlement: (input.ctx.get(ActivityPendingBlockersKey)?.length ?? 0) > 0,taskCallIds: input.ctx.get(ActivityTaskCallsKey),workIdentity: observer.workIdentity,}),@@ -36,7 +36,8 @@ export function projectSessionActivity(input: {readonly event: MessageStreamEvent;readonly rootTurnId?: string;readonly sessionId: string;- readonly suppressRootSettlement?: boolean;+ /** A turn that ends waiting on a person leaves its work open until it resumes. */+ readonly suppressSettlement?: boolean;readonly taskCallIds?: readonly string[];readonly workIdentity?: ActivityWorkIdentityV1;}): readonly ActivityEventV1[] {@@ -57,8 +58,7 @@ export function projectSessionActivity(input: {});}if (- input.suppressRootSettlement === true &&- work.kind === "root-turn" &&+ input.suppressSettlement === true &&(input.event.type === "turn.completed" ||input.event.type === "turn.failed" ||input.event.type === "turn.cancelled")diff --git a/packages/eve/src/execution/settle-cancelled-turn-step.test.ts b/packages/eve/src/execution/settle-cancelled-turn-step.test.tsindex 482a84148..7a861a163 100644--- a/packages/eve/src/execution/settle-cancelled-turn-step.test.ts+++ b/packages/eve/src/execution/settle-cancelled-turn-step.test.ts@@ -1,7 +1,12 @@import { describe, expect, it, vi } from "vitest";+import { ContextContainer } from "#context/container.js";+import { ActivityPendingBlockersKey } from "#context/keys.js";+import { deserializeContext } from "#context/serialize.js";import type { HarnessSession, SessionStateMap } from "#harness/types.js";import { readDurableSession } from "#execution/durable-session-store.js";+import { appendPendingInputBatch } from "#harness/pending-input-batches.js";+import type { InputRequest } from "#shared/input.js";import { settleCancelledTurnStep } from "#execution/settle-cancelled-turn-step.js";import {accumulateTurnUsage,@@ -15,7 +20,7 @@ import { runSessionStateStep } from "#internal/testing/session-state-step.js";// The turn's stream events and channel context are not under test; the usage// the step reports and the session it persists are.vi.mock("#context/serialize.js", () => ({- deserializeContext: async () => ({ get: () => undefined }),+ deserializeContext: vi.fn(async () => new ContextContainer()),serializeContext: () => ({}),}));vi.mock("#execution/publish-session-events.js", () => ({@@ -45,7 +50,43 @@ function spend<T extends { readonly state?: SessionStateMap }>();}+function request(requestId: string, kind: InputRequest["kind"]): InputRequest {+ return {+ action: { callId: requestId, input: {}, kind: "tool-call", toolName: "deploy" },+ kind,+ prompt: "Continue?",+ requestId,+ };+}+describe("settleCancelledTurnStep", () => {+ it("leaves only the requests the session can still answer holding its activity open", async () => {+ const base = createTestSessionState({+ emissionState: { sequence: 1, sessionStarted: true, stepIndex: 0, turnId: "turn_1" },+ sessionId: "deploy-session",+ });+ // Alice's turn waits on its own deploy approval, a session-limit prompt,+ // and a question a child asked through it when Bob cancels the turn.+ const parked = [request("approval-1", "tool-approval"), request("limit-1", "session-limit")]+ .map((pending) => [pending])+ .reduce(+ (session, requests) => appendPendingInputBatch({ requests, responseMessages: [], session }),+ { state: base.snapshot.session.state } as HarnessSession,+ );+ const ctx = new ContextContainer();+ ctx.set(ActivityPendingBlockersKey, ["child-question-1", "approval-1", "limit-1"]);+ vi.mocked(deserializeContext).mockResolvedValueOnce(ctx);++ await settleCancelledTurnStep({+ reportUsage: false,+ serializedContext: {},+ sessionState: { ...base, snapshot: { session: { ...base.snapshot.session, ...parked } } },+ sessionWritable: new WritableStream<Uint8Array>(),+ });++ expect(ctx.get(ActivityPendingBlockersKey)).toEqual(["approval-1"]);+ });+it.each([{ reportUsage: true, reported: 50, nextSettled: 0 },{ reportUsage: false, reported: undefined, nextSettled: 50 },diff --git a/packages/eve/src/execution/settle-cancelled-turn-step.ts b/packages/eve/src/execution/settle-cancelled-turn-step.tsindex 5787280c5..a36af5f2e 100644--- a/packages/eve/src/execution/settle-cancelled-turn-step.ts+++ b/packages/eve/src/execution/settle-cancelled-turn-step.ts@@ -3,6 +3,7 @@ import {getPendingCoordinationBatch,} from "#harness/coordination.js";import { deserializeContext, serializeContext } from "#context/serialize.js";+import { retainAnswerableActivityBlockers } from "#execution/activity-cohort.js";import {createDurableSessionState,type DurableSessionState,@@ -59,6 +60,8 @@ export async function settleCancelledTurn(): Promise<CancelledTurnSettleResult> {const durableSession = readDurableSession(input.sessionState);const ctx = await deserializeContext(input.serializedContext);+ // Before `turn.cancelled` projects, so only what stays answerable holds the work open.+ retainAnswerableActivityBlockers(ctx, durableSession.state);const emitted = await withSessionEventEmitter({ ctx, durableSession, origin: "own", sessionWritable: input.sessionWritable },async (emit, scopedSession) => ({diff --git a/packages/eve/src/harness/hitl/session-limit-input-requests.ts b/packages/eve/src/harness/hitl/session-limit-input-requests.tsindex 100605497..ac67efa08 100644--- a/packages/eve/src/harness/hitl/session-limit-input-requests.ts+++ b/packages/eve/src/harness/hitl/session-limit-input-requests.ts@@ -75,13 +75,17 @@ export function resolveSessionLimitInput(});}+/** A batch of only harness-authored session-limit prompts, which a cancel drops. */+export function isSessionLimitPromptBatch(batch: PendingInputBatch): boolean {+ return (+ batch.requests.length > 0 &&+ batch.requests.every((request) => isSessionLimitContinuationRequest(request))+ );+}+/** Drops only harness-authored session-limit prompts from a parked session. */export function clearPendingSessionLimitPrompt(session: HarnessSession): HarnessSession {- const dropped = getPendingInputBatches(session.state).filter(- (batch) =>- batch.requests.length > 0 &&- batch.requests.every((request) => isSessionLimitContinuationRequest(request)),- );+ const dropped = getPendingInputBatches(session.state).filter(isSessionLimitPromptBatch);if (dropped.length === 0) {return session;}