The Open Framework for Building Agents
fix(eve): preserve task child activity lineage (#3248)
Ben Pankowd63d6b7fbcf5
diff --git a/.changeset/forward-task-agent-activity.md b/.changeset/forward-task-agent-activity.mdnew file mode 100644index 000000000..30111bfab--- /dev/null+++ b/.changeset/forward-task-agent-activity.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Attribute local and remote background agent tool activity to its task, including when continuing or steering an existing agent. Each task keeps one progress item, and new work no longer reports against the previous task.diff --git a/docs/subagents/index.mdx b/docs/subagents/index.mdxindex d04766a87..5acf92d42 100644--- a/docs/subagents/index.mdx+++ b/docs/subagents/index.mdx@@ -217,6 +217,8 @@ Do not rely on subagent delegation by itself as an approval boundary. Put sensitEach delegated subagent spins up its own child session and stream. The parent stream carries the control-plane events `subagent.called` and `subagent.completed`, plus interactive `input.requested`, `authorization.required`, and `authorization.completed` events proxied from descendants so the root channel can prompt the user. To follow the child's other progress, read `subagent.called.data.childSessionId` and subscribe at `GET /eve/v1/session/:childSessionId/stream`.+Channels with activity reporting attribute the backing agent's tool activity to its background task. Local and remote subagents share the task's progress item rather than adding a separate agent item. Continuing or steering a child with `agentId` attaches its new activity to the new task; the previous task keeps its completed or cancelled status. This applies to the built-in `agent` and declared subagent tools, not to child invocations inside custom workflow tools. Activity reporting is best-effort and does not change task execution or result delivery.+A background task that was already admitted survives cancellation of the turn that started it; background work that has not yet been admitted is rejected with the cancelled step. Use `task_cancel` to stop an admitted task. Cancellation delivers the task's final notification to an active parent even if the task must be stopped forcibly. Parent-session finalization cancels remaining live tasks.Subagent model calls automatically retry classified transient provider failures, including overload errors delivered after a stream starts. eve makes at most three fresh model-call attempts, repeating only the current uncommitted call by default so completed earlier Workflow steps, tool results, and sandbox work remain available to the child. A declared subagent that opts into [Workflow checkpoint batching](./agent-config#workflow-checkpoint-batching) can instead repeat the uncommitted calls and inline tool executions in its current batch. Other recoverable task errors fall back to Workflow's durable step retry from the last committed session snapshot. Exhausting the transient model-call attempts or the dedicated empty-response reissue returns one failed task result instead of stacking both retry budgets; terminal errors fail immediately.diff --git a/packages/eve/src/execution/tasks/child/steps.test.ts b/packages/eve/src/execution/tasks/child/steps.test.tsindex 80c950cea..992dc6184 100644--- a/packages/eve/src/execution/tasks/child/steps.test.ts+++ b/packages/eve/src/execution/tasks/child/steps.test.ts@@ -1,6 +1,7 @@import { afterEach, describe, expect, it, vi } from "vitest";import {+ appendTaskViewStep,deliverTaskInputResponsesStep,formatTaskNotification,projectTaskActivity,@@ -9,6 +10,14 @@ import {import { resumeWorkflowToolRunAnswers } from "#execution/tools/workflow/answer.js";import type { TaskView } from "#tasks/types.js";import { resumeSessionInbox } from "#execution/wire/session-inbox-resume.js";+import { getWritable } from "#compiled/@workflow/core/index.js";+import { submitActivity } from "#execution/submit-activity.js";++vi.mock("#compiled/@workflow/core/index.js", async (importOriginal) => ({+ ...(await importOriginal()),+ getWritable: vi.fn(),+}));+vi.mock("#execution/submit-activity.js", () => ({ submitActivity: vi.fn() }));vi.mock("#execution/wire/session-inbox-resume.js", () => ({ resumeSessionInbox: vi.fn() }));vi.mock("#execution/tools/workflow/answer.js", () => ({@@ -55,6 +64,32 @@ const notificationCases: readonly { readonly expected: string; readonly view: Ta},];+describe("appendTaskViewStep", () => {+ it("waits for best-effort activity submission before the step finishes", async () => {+ const submission = Promise.withResolvers<void>();+ const submitted = Promise.withResolvers<void>();+ const releaseLock = vi.fn();+ vi.mocked(getWritable).mockReturnValue({+ getWriter: () => ({ write: vi.fn().mockResolvedValue(undefined), releaseLock }),+ } as never);+ vi.mocked(submitActivity).mockImplementation(() => {+ submitted.resolve();+ return submission.promise;+ });+ let finished = false;+ const appended = appendTaskViewStep({ view: notificationCases[0]!.view }).then(() => {+ finished = true;+ });+ await submitted.promise;+ await Promise.resolve();+ expect(releaseLock).toHaveBeenCalledOnce();+ expect(finished).toBe(false);+ submission.resolve();+ await appended;+ expect(finished).toBe(true);+ });+});+describe("projectTaskActivity", () => {afterEach(() => vi.unstubAllGlobals());diff --git a/packages/eve/src/execution/tasks/child/steps.ts b/packages/eve/src/execution/tasks/child/steps.tsindex a79e7cee2..59814b2a9 100644--- a/packages/eve/src/execution/tasks/child/steps.ts+++ b/packages/eve/src/execution/tasks/child/steps.ts@@ -54,7 +54,7 @@ export async function appendTaskViewStep(input: {settledAt: new Date().toISOString(),view: input.view,});- void submitActivity({ events, sink: input.activityObserver?.sink });+ await submitActivity({ events, sink: input.activityObserver?.sink });}export function projectTaskActivity(input: {diff --git a/packages/eve/src/execution/tasks/parent/tool-execution.integration.test.ts b/packages/eve/src/execution/tasks/parent/tool-execution.integration.test.tsindex c8c4fd911..a798e3925 100644--- a/packages/eve/src/execution/tasks/parent/tool-execution.integration.test.ts+++ b/packages/eve/src/execution/tasks/parent/tool-execution.integration.test.ts@@ -1,7 +1,8 @@import { beforeEach, describe, expect, it, vi } from "vitest";+import type { ActivityObserverConfig } from "#channel/types.js";import { ContextContainer, contextStorage } from "#context/container.js";-import { SessionKey } from "#context/keys.js";+import { ActivityObserverKey, SessionKey } from "#context/keys.js";import { cancelOwnedTask } from "#execution/tasks/parent/dispatch.js";import { startTaskRun, waitForTaskCommandOwner } from "#execution/tasks/parent/run-parent.js";import {@@ -76,13 +77,16 @@ function createSession(owned = true): HarnessSession {return owned ? recordSessionTask(session, entry) : session;}-async function createScope(session = createSession()) {+async function createScope(session = createSession(), activityObserver?: ActivityObserverConfig) {const ctx = new ContextContainer();ctx.setVirtualContext(SessionKey, {auth: { current: null, initiator: null },sessionId: session.sessionId,turn: { id: "turn-2", sequence: 2 },});+ if (activityObserver !== undefined) {+ ctx.setVirtualContext(ActivityObserverKey, activityObserver);+ }const created = await backgroundToolExecutionProvider.create(ctx, session);if (created === undefined) throw new Error("Expected background executor");const executor = created.value;@@ -93,12 +97,13 @@ async function createScope(session = createSession()) {callId = "steering-call",agentId: string | undefined = identity.id,name = identity.name,+ resultKind: "subagent" | "tool" = "subagent",) {const definition = {execute: vi.fn(),name,nodeId: identity.nodeId,- resultKind: "subagent" as const,+ resultKind,workflowId: "research-workflow",};const toolInput = { agentId, message: "Use the updated instruction" };@@ -150,6 +155,42 @@ describe("background subagent steering", () => {},);+ it.each(["subagent", "tool"] as const)(+ "persists agent-backed activity identity only (%s)",+ async (resultKind) => {+ const activityObserver = {+ sink: { url: "https://parent.example/activity", version: 1 as const },+ workIdentity: {+ id: "work:root",+ kind: "root-turn" as const,+ rootSessionId: "parent",+ rootTurnId: "turn-2",+ },+ };+ const scope = await createScope(createSession(), activityObserver);++ await scope.execute("steering-call", identity.id, identity.name, resultKind);+ const committed = await scope.commit();+ const task = getSessionTaskIndex(committed.state).find(+ (candidate) => candidate.taskId !== entry.taskId,+ );++ expect(task).toBeDefined();+ if (resultKind === "tool") {+ expect(task?.activityWorkIdentity).toBeUndefined();+ return;+ }+ expect(task?.activityWorkIdentity).toMatchObject({+ callId: "steering-call",+ kind: "task",+ name: "research",+ parentId: "work:root",+ rootSessionId: "parent",+ rootTurnId: "turn-2",+ });+ },+ );+it("cancels the old task before starting a new task in the same child", async () => {const scope = await createScope();const cancellation = Promise.withResolvers<typeof cancelledView>();diff --git a/packages/eve/src/execution/tasks/parent/tool-execution.ts b/packages/eve/src/execution/tasks/parent/tool-execution.tsindex 14cc5d339..0bb1267fd 100644--- a/packages/eve/src/execution/tasks/parent/tool-execution.ts+++ b/packages/eve/src/execution/tasks/parent/tool-execution.ts@@ -17,6 +17,7 @@ import {type BackgroundToolExecutor,} from "#harness/background-tools.js";import { deriveBackgroundTaskActivityObserver } from "#execution/activity-work.js";+import type { ActivityWorkIdentityV1 } from "#protocol/activity.js";import { isAsyncIterable } from "#shared/async-iterable.js";import { parseJsonValue } from "#shared/json.js";import type { ToolExecuteOptions } from "#tools/definition.js";@@ -54,6 +55,11 @@ import { cancelBackgroundAgentTask } from "#execution/tools/subagent/task-cancelconst IN_PROCESS_WORKFLOW_EXECUTOR = { data: {}, kind: "workflow-task" } as const;+type ActivityBackgroundTask = BackgroundTask & {+ readonly activityWorkIdentity?: ActivityWorkIdentityV1;+};+type ActivityBackgroundTaskDraft = Omit<ActivityBackgroundTask, "taskRunId">;+interface BackgroundToolExecutionRecord {readonly callId: string;claim?: {@@ -65,7 +71,7 @@ interface BackgroundToolExecutionRecord {readonly operationId: string;};settled: boolean;- task?: BackgroundTask;+ task?: ActivityBackgroundTask;}interface BackgroundToolStepResult {@@ -327,7 +333,10 @@ class BackgroundToolExecutionScope implements BackgroundToolExecutor {readonly toolInput: unknown;};readonly record: BackgroundToolExecutionRecord;- }): Promise<{ readonly receipt?: { readonly agentId: string }; readonly task: BackgroundTask }> {+ }): Promise<{+ readonly receipt?: { readonly agentId: string };+ readonly task: ActivityBackgroundTask;+ }> {const workflow =input.input.definition.workflowId === undefined? undefined@@ -410,7 +419,11 @@ class BackgroundToolExecutionScope implements BackgroundToolExecutor {throw new Error(`Background workflow tool "${input.input.definition.name}" has no input.`);}- const task = prepareBackgroundTask(taskInput);+ const task: ActivityBackgroundTaskDraft = {+ ...prepareBackgroundTask(taskInput),+ activityWorkIdentity:+ workflow.resultKind === "subagent" ? taskInput.activityObserver?.workIdentity : undefined,+ };if (workflow.resultKind === "subagent" &&subagentProjection !== undefined &&diff --git a/packages/eve/src/execution/tools/subagent/invoke-step.test.ts b/packages/eve/src/execution/tools/subagent/invoke-step.test.tsindex 4630d5faf..4fa0f448a 100644--- a/packages/eve/src/execution/tools/subagent/invoke-step.test.ts+++ b/packages/eve/src/execution/tools/subagent/invoke-step.test.ts@@ -2,6 +2,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";import {dispatchAgentInvocation,+ dispatchTaskAgentInvocationStep,releaseAgentInvocationOwnerStep,settleTaskAgentInvocationStep,} from "#execution/tools/subagent/invoke-step.js";@@ -10,7 +11,13 @@ import { startSubagent } from "#execution/tools/subagent/start.js";import { prepareOwnerAgentInvocation } from "#execution/tools/subagent/invoke-preparation.js";import { readDurableSession } from "#execution/durable-session-store.js";import { getAgentHandleStore, setAgentHandleStore } from "#subagents/handles/store.js";+import { readLatestTaskView } from "#execution/tasks/parent/run-parent.js";+import { recordSessionTask } from "#tasks/session-index.js";+vi.mock("#compiled/@workflow/core/index.js", async (importOriginal) => ({+ ...(await importOriginal()),+ getWorkflowMetadata: vi.fn(() => ({ url: "https://parent.example" })),+}));vi.mock("#subagents/handle-dispatch.js", async (importOriginal) => ({...(await importOriginal()),dispatchToClaimedAgentAddress: vi.fn(),@@ -28,6 +35,7 @@ vi.mock("#execution/durable-session-store.js", async (importOriginal) => ({...(await importOriginal()),readDurableSession: vi.fn(),}));+vi.mock("#execution/tasks/parent/run-parent.js", () => ({ readLatestTaskView: vi.fn() }));const action = {callId: "call-1",description: "Research",@@ -192,6 +200,91 @@ describe("owner agent invocation dispatch", () => {).toEqual(["agent-1", "agent-1"]);});+ it.each([+ { dispatchKind: "start", taskKind: "subagent", observed: true },+ { dispatchKind: "resume", taskKind: "subagent", observed: true },+ { dispatchKind: "start", taskKind: "tool", observed: true },+ { dispatchKind: "resume", taskKind: "tool", observed: true },+ { dispatchKind: "start", taskKind: "subagent", observed: false },+ { dispatchKind: "resume", taskKind: "subagent", observed: false },+ ] as const)(+ "resolves task activity for $dispatchKind ($taskKind, observed=$observed)",+ async ({ dispatchKind, taskKind, observed }) => {+ const taskWork = {+ callId: "task-call",+ id: "work:task",+ kind: "task" as const,+ name: "research",+ parentId: "work:root",+ rootSessionId: "root-session",+ rootTurnId: "root-turn",+ };+ const indexedSession = recordSessionTask(session as never, {+ activityWorkIdentity: taskWork,+ createdByTurnId: "turn-1",+ metadata: { kind: taskKind, name: "research" },+ taskId: "task-1",+ taskInboxToken: "task-token",+ taskRunId: "task-run",+ });+ vi.mocked(readDurableSession).mockResolvedValue(indexedSession as never);+ vi.mocked(readLatestTaskView).mockResolvedValue({+ metadata: { kind: "subagent", name: "research" },+ status: "working",+ taskId: "task-1",+ });+ vi.mocked(prepareOwnerAgentInvocation).mockResolvedValue({+ ...prepared,+ activityObserver: observed+ ? {+ sink: { url: "https://parent.example/activity", version: 1 },+ workIdentity: {+ id: "work:root",+ kind: "root-turn",+ rootSessionId: "root-session",+ rootTurnId: "root-turn",+ },+ }+ : undefined,+ plan: [+ dispatchKind === "start"+ ? { kind: "start", target: { action, kind: "local", source: { type: "runtime" } } }+ : { kind: "resume", action, agentId: "agent-1" },+ ],+ session: indexedSession,+ } as never);+ vi.mocked(startSubagent).mockResolvedValue(called);+ vi.mocked(dispatchToClaimedAgentAddress).mockResolvedValue(called);++ await dispatchTaskAgentInvocationStep({+ ownerId: "task-1",+ replyTo: "agent-reply",+ request: {+ input: { message: "Find it", target: "research" },+ invocationId: "call-1",+ kind: "agent-invoke",+ },+ serializedContext: {},+ sessionState: {} as never,+ taskId: "task-1",+ });++ const taskObserver =+ observed && taskKind === "subagent"+ ? { sink: { url: "https://parent.example/activity", version: 1 }, workIdentity: taskWork }+ : undefined;+ if (dispatchKind === "start") {+ expect(startSubagent).toHaveBeenCalledWith(+ expect.objectContaining({ taskActivityObserver: taskObserver }),+ );+ } else {+ expect(dispatchToClaimedAgentAddress).toHaveBeenCalledWith(+ expect.objectContaining({ activityObserver: taskObserver }),+ );+ }+ },+ );+it("starts a fresh agent with task-owned handle semantics", async () => {const reserved = {callId: "call-1",diff --git a/packages/eve/src/execution/tools/subagent/invoke-step.ts b/packages/eve/src/execution/tools/subagent/invoke-step.tsindex fd3b17f4c..98411159f 100644--- a/packages/eve/src/execution/tools/subagent/invoke-step.ts+++ b/packages/eve/src/execution/tools/subagent/invoke-step.ts@@ -9,6 +9,7 @@ import { prepareOwnerAgentInvocation } from "#execution/tools/subagent/invoke-primport type { AgentInvocationRequest } from "#execution/tools/subagent/invoke-agent.js";import type { RuntimeSubagentResult } from "#shared/action-types.js";import type { HandleEventFn } from "#harness/types.js";+import type { ActivityWorkIdentityV1 } from "#protocol/activity.js";import { createSubagentCalledEvent, type SubagentCalledStreamEvent } from "#protocol/message.js";import { workflowEntryReference } from "#execution/workflow-runtime.js";import { getWorkflowMetadata } from "#compiled/@workflow/core/index.js";@@ -77,6 +78,7 @@ export type TaskAgentInvocationDispatchResult =/** Dispatches one owner-scoped local or remote agent invocation. */export async function dispatchAgentInvocation(input: {+ readonly activityWorkIdentity?: ActivityWorkIdentityV1;readonly callbackBaseUrl: string;readonly emit?: HandleEventFn;readonly replyTo: string;@@ -119,6 +121,10 @@ export async function dispatchAgentInvocation(input: {taskId: input.taskId,turnId: prepared.batch.event.turnId,});+ const taskActivityObserver =+ prepared.activityObserver === undefined || input.activityWorkIdentity === undefined+ ? undefined+ : { sink: prepared.activityObserver.sink, workIdentity: input.activityWorkIdentity };let session = prepared.session;const currentAgentHandles = (): readonly AgentHandle[] =>getAgentHandleStore(session.state)?.handles ?? [];@@ -183,6 +189,7 @@ export async function dispatchAgentInvocation(input: {dynamicRemoteAgent: entry.dynamicRemoteAgent,});outcome = await dispatchToClaimedAgentAddress({+ activityObserver: taskActivityObserver,action: entry.action,auth: prepared.auth,bundle,@@ -247,6 +254,7 @@ export async function dispatchAgentInvocation(input: {localDevRequest: prepared.localDevRequest,parentContinuationToken: input.replyTo,activityObserver: prepared.activityObserver,+ taskActivityObserver,sandboxSessionId: prepared.sandboxSessionId,session,taskId: input.taskId,@@ -325,6 +333,7 @@ export async function dispatchTaskAgentInvocationStep(): Promise<TaskAgentInvocationDispatchResult> {"use step";+ let activityWorkIdentity: ActivityWorkIdentityV1 | undefined;if (input.taskId !== undefined) {const session = await readDurableSession(input.sessionState);const entry = findSessionTaskEntry(session.state, input.taskId);@@ -333,9 +342,13 @@ export async function dispatchTaskAgentInvocationStep(if (view === undefined || isTerminalTaskStatus(view.status)) {return { kind: "not-admitted", sessionState: input.sessionState };}+ if (entry.metadata.kind === "subagent") {+ activityWorkIdentity = entry.activityWorkIdentity;+ }}return await dispatchAgentInvocation({...input,+ activityWorkIdentity,callbackBaseUrl: resolveWorkflowCallbackBaseUrl(getWorkflowMetadata().url),});}diff --git a/packages/eve/src/execution/tools/subagent/start.ts b/packages/eve/src/execution/tools/subagent/start.tsindex 8f3eb9cd3..0930d7447 100644--- a/packages/eve/src/execution/tools/subagent/start.ts+++ b/packages/eve/src/execution/tools/subagent/start.ts@@ -48,6 +48,10 @@ export async function startSubagent(input: {readonly activityObserver?: ActivityObserverConfig & {readonly workIdentity: ActivityWorkIdentityV1;};+ /** The backing agent reports as this task, rather than as a separate child work item. */+ readonly taskActivityObserver?: ActivityObserverConfig & {+ readonly workIdentity: ActivityWorkIdentityV1;+ };readonly sandboxSessionId: string;readonly session: RuntimeSession;readonly taskId?: string;@@ -85,7 +89,7 @@ export async function startSubagent(input: {initiatorAuth: input.initiatorAuth,localDevRequest: input.localDevRequest,parent,- activityObserver: input.activityObserver,+ activityObserver: input.taskActivityObserver ?? input.activityObserver,sandboxSessionId: input.sandboxSessionId,session: input.session,source: input.target.source,@@ -102,6 +106,7 @@ export async function startSubagent(input: {initiatorAuth: input.initiatorAuth,parent,activityObserver: input.activityObserver,+ taskActivityObserver: input.taskActivityObserver,session: input.session,taskId: input.taskId,});diff --git a/packages/eve/src/execution/tools/subagent/task-activity.integration.test.ts b/packages/eve/src/execution/tools/subagent/task-activity.integration.test.tsnew file mode 100644index 000000000..9940615b4--- /dev/null+++ b/packages/eve/src/execution/tools/subagent/task-activity.integration.test.ts@@ -0,0 +1,328 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++import type { ActivityObserverConfig, RunInput, TurnCaller } from "#channel/types.js";+import { ActivityObserverKey } from "#context/keys.js";+import {+ parseActivityObserverField,+ validateActivityObserverBinding,+} from "#eve-channel/activity-observer-request.js";+import {+ deriveBackgroundTaskActivityObserver,+ deriveRootTurnWorkIdentity,+} from "#execution/activity-work.js";+import { createActivitySnapshot, reduceActivityBatch } from "#execution/session-activity.js";+import { projectSessionActivity } from "#execution/session-activity-projection.js";+import { projectTaskActivity } from "#execution/tasks/child/steps.js";+import { startSubagent, type SubagentStartTarget } from "#execution/tools/subagent/start.js";+import type { ActivityEventV1, ActivitySnapshotV1 } from "#protocol/activity.js";+import type { MessageStreamEvent } from "#protocol/message.js";+import { ChannelKey } from "#runtime/sessions/runtime-context-keys.js";+import { createRuntimeSubagentRegistry } from "#runtime/subagents/registry.js";+import { SUBAGENT_ADAPTER_KIND } from "#subagents/adapter-state.js";+import { dispatchToClaimedAgentAddress } from "#subagents/handle-dispatch.js";+import type { AgentAddress } from "#subagents/handles/store.js";+import { bindTurnCallerContextStep } from "#subagents/parent-notification.js";+import type {+ continueRemoteAgentSession as ContinueRemote,+ startRemoteAgentSession as StartRemote,+} from "#subagents/remote-dispatch.js";++type Observer = ActivityObserverConfig & {+ workIdentity: NonNullable<ActivityObserverConfig["workIdentity"]>;+};+type Kind = "local" | "remote";+const { createSession, dispatchSession, startRemote, continueRemote } = vi.hoisted(() => ({+ createSession: vi.fn(async (_input: RunInput) => undefined),+ dispatchSession: vi.fn(async (_input: { command: { caller?: TurnCaller } }) => ({+ status: "accepted",+ })),+ startRemote: vi.fn(async (_input: Parameters<typeof StartRemote>[0]) => ({+ sessionId: "remote-session",+ })),+ continueRemote: vi.fn(async (_input: Parameters<typeof ContinueRemote>[0]) => undefined),+}));+vi.mock("#execution/workflow-runtime.js", () => ({+ createWorkflowRuntime: () => ({ createSession, dispatchSession }),+ waitForCommandHookOwner: async () => ({ runId: "child-session" }),+}));+vi.mock("#subagents/remote-dispatch.js", () => ({+ resolveRemoteAgentForAction: () => ({ url: "https://remote.example/eve/v1" }),+ startRemoteAgentSession: startRemote,+ continueRemoteAgentSession: continueRemote,+}));++const at = "2026-01-01T00:00:00.000Z";+const root = deriveRootTurnWorkIdentity({+ sessionId: "parent",+ auth: { current: null, initiator: null },+ turn: { id: "parent-turn", sequence: 0 },+});+const parentObserver: Observer = {+ sink: {+ url: "https://parent.example/eve/v1/activity/abcdefghijklmnopqrstuvwxyz123456",+ version: 1,+ },+ workIdentity: root,+};+const session = {+ sessionId: "parent",+ continuationToken: "parent-token",+ history: [],+ agent: { dynamicModel: true as const, system: "", tools: [] },+ compaction: { recentWindowSize: 5, threshold: 10_000 },+};+const bundle = {+ subagentRegistry: createRuntimeSubagentRegistry({ subagents: [] }),+} as Parameters<typeof startSubagent>[0]["bundle"];++function taskObserver(callId: string): Observer {+ const observer = deriveBackgroundTaskActivityObserver({+ activityObserver: parentObserver,+ callId,+ name: "research",+ parentSessionId: session.sessionId,+ parentTurnId: "parent-turn",+ rootSessionId: session.sessionId,+ });+ if (observer?.workIdentity === undefined) throw new Error("Expected task identity");+ return { ...observer, workIdentity: observer.workIdentity };+}++function target(kind: Kind, callId: string): SubagentStartTarget {+ const action = {+ callId,+ description: "Research",+ input: { message: "Find it" },+ name: "research",+ nodeId: "subagents/research",+ };+ return kind === "local"+ ? {+ kind,+ action: { ...action, kind: "subagent-call", subagentName: "research" },+ source: { type: "runtime" },+ }+ : { kind, action: { ...action, kind: "remote-agent-call", remoteAgentName: "research" } };+}++async function start(kind: Kind, task?: Observer): Promise<ActivityObserverConfig | undefined> {+ const result = await startSubagent({+ auth: null,+ batchEvent: { sequence: 0, turnId: "parent-turn" },+ bundle,+ callbackBaseUrl: "https://parent.example",+ capabilities: undefined,+ channelMetadata: undefined,+ currentSession: session,+ fanoutSize: 1,+ initiatorAuth: null,+ parentContinuationToken: "parent-token",+ activityObserver: task === undefined ? undefined : parentObserver,+ taskActivityObserver: task,+ sandboxSessionId: "sandbox",+ session,+ taskId: "task-a",+ target: target(kind, "task-a"),+ trace: { originAudience: "private", parentTraceContext: undefined },+ });+ expect(result.kind).toBe("called");+ if (kind === "local") return createSession.mock.calls[0]![0].activityObserver;+ const request = startRemote.mock.calls[0]![0];+ if (request.activityObserver !== undefined) {+ const parsed = parseActivityObserverField(request.activityObserver);+ if (parsed === undefined || parsed instanceof Response) throw new Error("Invalid observer");+ expect(+ validateActivityObserverBinding(parsed, {+ callId: request.action.callId,+ subagentName: request.action.remoteAgentName,+ token: "parent-token",+ url: `${request.callbackBaseUrl}/eve/v1/callback/parent-token`,+ }),+ ).toBeUndefined();+ }+ return request.activityObserver;+}++function apply(snapshot: ActivitySnapshotV1, events: readonly ActivityEventV1[]) {+ return reduceActivityBatch(snapshot, { version: 1, events });+}+function project(event: MessageStreamEvent, observer: ActivityObserverConfig, sessionId = "child") {+ return projectSessionActivity({ event, sessionId, workIdentity: observer.workIdentity });+}+function turn(type: "turn.started" | "turn.completed", turnId: string): MessageStreamEvent {+ return { type, data: { sequence: 0, turnId }, meta: { id: `${type}:${turnId}`, at } };+}+function tool(type: "actions.requested" | "action.result", turnId: string): MessageStreamEvent {+ const data = { turnId, sequence: 1, stepIndex: 0 };+ const meta = { id: `${type}:${turnId}`, at };+ return type === "actions.requested"+ ? {+ type,+ meta,+ data: {+ ...data,+ actions: [{ kind: "tool-call", callId: "search-call", toolName: "search", input: {} }],+ },+ }+ : {+ type,+ meta,+ data: {+ ...data,+ status: "completed",+ result: {+ kind: "tool-result",+ callId: "search-call",+ toolName: "search",+ output: "Found it",+ },+ },+ };+}+function taskEvents(observer: Observer, status: "working" | "completed" | "cancelled") {+ return projectTaskActivity({+ activityObserver: observer,+ settledAt: at,+ view: {+ taskId: observer.workIdentity.callId!,+ metadata: { kind: "subagent", name: "research" },+ ...(status === "completed"+ ? { status, lastOutput: { type: "result" as const, data: "Done" } }+ : { status }),+ },+ });+}+function initialSnapshot() {+ return apply(+ createActivitySnapshot(),+ project(turn("turn.started", "parent-turn"), parentObserver, "parent"),+ );+}++describe("task-owned subagent activity", () => {+ beforeEach(() => vi.clearAllMocks());++ it.each(["local", "remote"] as const)(+ "keeps one task item through %s child activity and settlement",+ async (kind) => {+ const task = taskObserver("task-a");+ const captured = await start(kind, task);+ if (captured === undefined) throw new Error("Expected child observer");+ expect(captured).toEqual(task);+ let snapshot = apply(initialSnapshot(), taskEvents(task, "working"));+ snapshot = apply(snapshot, project(turn("turn.started", "child-turn"), captured));+ snapshot = apply(snapshot, project(tool("actions.requested", "child-turn"), captured));+ expect(Object.values(snapshot.work)).toHaveLength(2);+ expect(snapshot.work[task.workIdentity.id]).toMatchObject({+ kind: "task",+ parentId: root.id,+ phase: "running",+ });+ expect(Object.values(snapshot.actions)).toEqual([+ expect.objectContaining({ parentWorkId: task.workIdentity.id, phase: "running" }),+ ]);+ snapshot = apply(snapshot, project(tool("action.result", "child-turn"), captured));+ snapshot = apply(snapshot, project(turn("turn.completed", "child-turn"), captured));+ expect(snapshot.work[task.workIdentity.id]?.phase).toBe("running");+ snapshot = apply(snapshot, taskEvents(task, "completed"));+ snapshot = apply(+ snapshot,+ project(turn("turn.completed", "parent-turn"), parentObserver, "parent"),+ );+ expect(Object.values(snapshot.work).map((work) => work.phase)).toEqual([+ "completed",+ "completed",+ ]);+ expect(Object.values(snapshot.actions).map((action) => action.phase)).toEqual(["completed"]);+ },+ );++ it.each(["local", "remote"] as const)(+ "keeps %s observation disabled without an observer",+ async (kind) => {+ expect(await start(kind)).toBeUndefined();+ },+ );++ it.each([+ ["local", "completed"],+ ["local", "cancelled"],+ ["remote", "completed"],+ ["remote", "cancelled"],+ ] as const)("rebinds %s child progress after task A is %s", async (kind, status) => {+ const a = taskObserver("task-a");+ const original = await start(kind, a);+ const b = taskObserver("task-b");+ const address: AgentAddress =+ kind === "local"+ ? { kind: "agent/local", sessionId: "child-session", continuationToken: "child-token" }+ : {+ kind: "agent/remote",+ sessionId: "remote-session",+ callbackBaseUrl: "https://parent.example",+ url: "https://remote.example/eve/v1",+ credentialResolver: { resolverId: "subagents/research" },+ };+ const result = await dispatchToClaimedAgentAddress({+ activityObserver: b,+ action: target(kind, "task-b").action,+ auth: null,+ bundle,+ currentSession: session,+ handle: {+ address,+ identity: { id: "agent-1", name: "research", nodeId: "subagents/research" },+ callId: "task-b",+ operationId: "operation-b",+ ownerId: "task-b",+ phase: "claimed",+ },+ parentToken: "task-b-reply",+ taskId: "task-b",+ });+ expect(result.kind).toBe("called");+ let caller: TurnCaller | undefined;+ if (kind === "local") caller = dispatchSession.mock.calls[0]![0].command.caller;+ else {+ const request = continueRemote.mock.calls[0]![0];+ const parsed = parseActivityObserverField(request.activityObserver);+ if (parsed === undefined || parsed instanceof Response) throw new Error("Invalid observer");+ expect(validateActivityObserverBinding(parsed, request.callback)).toBeUndefined();+ caller = {+ ...request.callback,+ activityObserver: parsed,+ replyTo: { kind: "callback", token: request.callback.token, url: request.callback.url },+ };+ }+ const context = await bindTurnCallerContextStep({+ caller,+ serializedContext: {+ [ActivityObserverKey.name]: original,+ [ChannelKey.name]: {+ kind: SUBAGENT_ADAPTER_KIND,+ state: {+ callId: "task-a",+ parentContinuationToken: "parent-token",+ parentSessionId: "parent",+ subagentName: "research",+ },+ },+ },+ });+ const rebound = context[ActivityObserverKey.name] as ActivityObserverConfig;+ expect(rebound).toEqual(b);+ let snapshot = apply(initialSnapshot(), taskEvents(a, "working"));+ snapshot = apply(snapshot, project(tool("actions.requested", "first-turn"), a));+ snapshot = apply(snapshot, project(tool("action.result", "first-turn"), a));+ snapshot = apply(snapshot, taskEvents(a, status));+ snapshot = apply(snapshot, taskEvents(b, "working"));+ snapshot = apply(snapshot, project(turn("turn.started", "second-turn"), rebound));+ snapshot = apply(snapshot, project(tool("actions.requested", "second-turn"), rebound));+ expect(snapshot.work[a.workIdentity.id]?.phase).toBe(status);+ expect(snapshot.work[b.workIdentity.id]?.phase).toBe("running");+ expect(Object.values(snapshot.actions)).toEqual([+ expect.objectContaining({ parentWorkId: a.workIdentity.id, phase: "completed" }),+ expect.objectContaining({ parentWorkId: b.workIdentity.id, phase: "running" }),+ ]);+ });+});diff --git a/packages/eve/src/subagents/handle-dispatch.ts b/packages/eve/src/subagents/handle-dispatch.tsindex 886a6bb1d..f1949d57f 100644--- a/packages/eve/src/subagents/handle-dispatch.ts+++ b/packages/eve/src/subagents/handle-dispatch.ts@@ -1,6 +1,6 @@/** Continuation delivery for task-owned agent sessions. */-import type { SessionAuthContext } from "#channel/types.js";+import type { ActivityObserverConfig, SessionAuthContext } from "#channel/types.js";import { AGENT_UNREACHABLE } from "#subagents/agent-handle-errors.js";import type { AgentAddress, AgentIdentity } from "#subagents/handles/store.js";import type {@@ -73,6 +73,7 @@ export type DispatchOutcome =/** Delivers a continuation after the session handle store atomically claimed it for one owner. */export async function dispatchToClaimedAgentAddress(input: {+ readonly activityObserver?: ActivityObserverConfig;readonly action: RuntimeAgentHandleAction;readonly auth: SessionAuthContext | null;readonly bundle: CompiledBundle;@@ -86,6 +87,7 @@ export async function dispatchToClaimedAgentAddress(input: {/** Delivers a continuation to an already-claimed local or remote agent address. */async function dispatchToAgentAddress(input: {+ readonly activityObserver?: ActivityObserverConfig;readonly action: RuntimeAgentHandleAction;readonly auth: SessionAuthContext | null;readonly bundle: CompiledBundle;@@ -98,6 +100,7 @@ async function dispatchToAgentAddress(input: {const agentId = handle.identity.id;const delivery = await deliverToAgentAddress({+ activityObserver: input.activityObserver,action,address: handle.address,auth: input.auth,@@ -151,6 +154,7 @@ async function dispatchToAgentAddress(input: {* already-started siblings.*/async function deliverToAgentAddress(input: {+ readonly activityObserver?: ActivityObserverConfig;readonly action: RuntimeAgentHandleAction;readonly address: AgentAddress;readonly auth: SessionAuthContext | null;@@ -181,6 +185,7 @@ async function deliverToAgentAddress(input: {}try {await continueRemoteAgentSession({+ activityObserver: input.activityObserver,auth: input.auth,callback: {callId: action.callId,@@ -216,6 +221,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/subagents/start-remote.test.ts b/packages/eve/src/subagents/start-remote.test.tsnew file mode 100644index 000000000..d5e7254e3--- /dev/null+++ b/packages/eve/src/subagents/start-remote.test.ts@@ -0,0 +1,81 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++const { resolveRemoteAgentForAction, startRemoteAgentSession } = vi.hoisted(() => ({+ resolveRemoteAgentForAction: vi.fn(() => ({ url: "https://remote.example/eve/v1" })),+ startRemoteAgentSession: vi.fn(async () => ({ sessionId: "remote-session" })),+}));++vi.mock("#subagents/remote-dispatch.js", () => ({+ resolveRemoteAgentForAction,+ startRemoteAgentSession,+}));++import { startRemoteSubagent } from "#subagents/start-remote.js";++const taskObserver = {+ sink: { url: "https://parent.example/activity", version: 1 as const },+ workIdentity: {+ id: "work:task",+ kind: "task" as const,+ name: "research-task",+ parentId: "work:root",+ rootSessionId: "root-session",+ rootTurnId: "root-turn",+ },+};++describe("startRemoteSubagent", () => {+ beforeEach(() => vi.clearAllMocks());++ it("derives a child identity when no task-owned observer is supplied", async () => {+ await startRemoteSubagent({+ action: {+ callId: "call-remote",+ description: "Research remotely",+ input: { message: "Find it" },+ kind: "remote-agent-call",+ name: "remote_research",+ nodeId: "remoteAgents/research",+ remoteAgentName: "research",+ },+ activityObserver: taskObserver,+ auth: null,+ batchEvent: { sequence: 0, turnId: "parent-turn" },+ bundle: { subagentRegistry: { subagentsByNodeId: new Map() } },+ callbackBaseUrl: "https://parent.example",+ currentSession: { sessionId: "parent-session" },+ initiatorAuth: null,+ parent: {+ continuationToken: "parent-token",+ conversationId: "root-session",+ lineage: {+ callId: "call-remote",+ rootSessionId: "root-session",+ sessionId: "parent-session",+ turn: { id: "parent-turn", sequence: 0 },+ },+ originAudience: { kind: "unknown" },+ traceContext: undefined,+ },+ session: { sessionId: "parent-session" },+ taskId: "task-1",+ } as never);++ expect(startRemoteAgentSession).toHaveBeenCalledWith(+ expect.objectContaining({+ activityObserver: {+ sink: taskObserver.sink,+ workIdentity: expect.objectContaining({+ callId: "call-remote",+ kind: "remote-agent",+ name: "research",+ parentId: taskObserver.workIdentity.id,+ rootSessionId: "root-session",+ rootTurnId: "root-turn",+ }),+ },+ taskId: "task-1",+ }),+ );+ });+});diff --git a/packages/eve/src/subagents/start-remote.ts b/packages/eve/src/subagents/start-remote.tsindex 689cf29e7..d8cb95345 100644--- a/packages/eve/src/subagents/start-remote.ts+++ b/packages/eve/src/subagents/start-remote.ts@@ -26,18 +26,22 @@ export async function startRemoteSubagent(input: {readonly initiatorAuth: Parameters<typeof startRemoteAgentSession>[0]["initiatorAuth"];readonly parent: SubagentParentContext;readonly activityObserver?: Parameters<typeof startRemoteAgentSession>[0]["activityObserver"];+ /** Already resolved task-owned work; do not derive another child identity. */+ readonly taskActivityObserver?: Parameters<typeof startRemoteAgentSession>[0]["activityObserver"];readonly session: RuntimeSession;readonly taskId?: string;}): 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.parent.lineage.turn.id,- });+ const activityObserver =+ input.taskActivityObserver ??+ deriveChildActivityObserverConfig({+ activityObserver: input.activityObserver,+ callId: action.callId,+ kind: "remote-agent",+ name: action.remoteAgentName,+ parentSessionId: input.session.sessionId,+ parentTurnId: input.parent.lineage.turn.id,+ });// Preflight resolution failures happen before ownership exists, so they// reject without touching the handle store.diff --git a/packages/eve/src/tasks/session-index.test.ts b/packages/eve/src/tasks/session-index.test.tsindex 7e2024323..d59e0c21d 100644--- a/packages/eve/src/tasks/session-index.test.ts+++ b/packages/eve/src/tasks/session-index.test.ts@@ -56,6 +56,31 @@ describe("session task index", () => {expect(findSessionTaskEntry(session.state, "task_other")).toBeUndefined();});+ it("keeps activity identity in the persisted task index", () => {+ const activityWorkIdentity = {+ callId: "call-1",+ id: "work:task",+ kind: "task" as const,+ name: "research",+ parentId: "work:root",+ rootSessionId: "root-session",+ rootTurnId: "root-turn",+ };+ const session = recordSessionTask(createSession(), {+ activityWorkIdentity,+ taskInboxToken: "task:token-1",+ createdByTurnId: "turn-1",+ metadata,+ taskId: "task_a",+ taskRunId: "run-1",+ });++ const restoredState = JSON.parse(JSON.stringify(session.state));+ expect(findSessionTaskEntry(restoredState, "task_a")?.activityWorkIdentity).toEqual(+ activityWorkIdentity,+ );+ });+it("keeps subagent metadata in the persisted task index", () => {const subagentMetadata = {agentId: "ag_worker",diff --git a/packages/eve/src/tasks/session-index.ts b/packages/eve/src/tasks/session-index.tsindex cbd4c8743..fcab08ace 100644--- a/packages/eve/src/tasks/session-index.ts+++ b/packages/eve/src/tasks/session-index.ts@@ -1,6 +1,7 @@import { z } from "#compiled/zod/index.js";import type { HarnessSession, SessionStateMap } from "#harness/types.js";+import { parseActivityWorkIdentityV1, type ActivityWorkIdentityV1 } from "#protocol/activity.js";import type { JsonValue } from "#shared/json.js";import type { TaskExecutorBinding } from "#tools/task.js";import { sameTaskMetadata, type TaskMetadata, type TaskView } from "#tasks/types.js";@@ -31,6 +32,7 @@ export { SESSION_TASKS_STATE_KEY } from "#tasks/session-task-cohorts.js";* `taskId` only, and lookup verifies ownership through this index.*/export interface SessionTaskIndexEntry {+ readonly activityWorkIdentity?: ActivityWorkIdentityV1;readonly taskId: string;readonly taskRunId: string;/** Immutable fallback once the owning workflow run expires. */@@ -93,6 +95,9 @@ const taskViewSchema: z.ZodType<TaskView> = z.discriminatedUnion("status", []);const sessionTaskIndexEntrySchema: z.ZodType<SessionTaskIndexEntry> = z.strictObject({+ activityWorkIdentity: z+ .custom<ActivityWorkIdentityV1>((value) => parseActivityWorkIdentityV1(value) !== undefined)+ .optional(),taskInboxToken: z.string().min(1),createdByStepIndex: z.number().int().nonnegative().optional(),createdByTurnId: z.string().min(1),