The Open Framework for Building Agents
feat(eve): conversation-mode children with explicit turn outcomes (#1330)
Ruibd213320f89e
diff --git a/.changeset/cancelled-children-park-handles.md b/.changeset/cancelled-children-park-handles.mdnew file mode 100644index 000000000..8393486ed--- /dev/null+++ b/.changeset/cancelled-children-park-handles.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Cancelling a turn with running delegated children no longer leaks their handles as permanently `running`. The cancellation epilogue now parks each abandoned child as `"(cancelled)"`, so cancelled children stay resumable and later cancellations no longer stall retrying already-dead children.diff --git a/e2e/fixtures/agent-cancellation/agent/agent.ts b/e2e/fixtures/agent-cancellation/agent/agent.tsindex a2715dfff..41a0bd9c1 100644--- a/e2e/fixtures/agent-cancellation/agent/agent.ts+++ b/e2e/fixtures/agent-cancellation/agent/agent.ts@@ -1,6 +1,12 @@import { e2eAgentConfig } from "@eve-e2e/config";import { defineAgent } from "eve";+const base = e2eAgentConfig();+export default defineAgent({- ...e2eAgentConfig(),+ ...base,+ // Persistent children keep the cancelled sleeper in the model-visible+ // [Agents] listing, which the cancel-subagent eval inspects after a+ // cascaded cancellation.+ experimental: { ...base.experimental, subagentPersistentSessions: true },});diff --git a/e2e/fixtures/agent-cancellation/evals/cancellation/cancel-subagent.eval.ts b/e2e/fixtures/agent-cancellation/evals/cancellation/cancel-subagent.eval.tsindex 50375cb59..b76c970fa 100644--- a/e2e/fixtures/agent-cancellation/evals/cancellation/cancel-subagent.eval.ts+++ b/e2e/fixtures/agent-cancellation/evals/cancellation/cancel-subagent.eval.ts@@ -52,6 +52,18 @@ export default defineEval({followUp.notEvent("turn.cancelled");followUp.messageIncludes(/CANCELLATION-SUBAGENT-FOLLOW-UP-OK/i);+ // The cancelled child must survive in the parent's model-visible+ // [Agents] listing as a parked "(cancelled)" handle. A handle leaked as+ // `running` never re-enters the listing, so this catches the abandoned+ // cancelled batch regressing to a permanent leak.+ const listing = await t.send(+ "Look at the [Agents] listing in your context and reply with the sleeper agent's entry verbatim, including its status.",+ );+ listing.expectOk();+ listing.notEvent("turn.cancelled");+ listing.messageIncludes(/sleeper/i);+ listing.messageIncludes(/\(cancelled\)/);+t.event("turn.cancelled", { count: 2 });},});diff --git a/packages/eve/extension-contracts/compatibility/dynamicInstructions/v5.ts b/packages/eve/extension-contracts/compatibility/dynamicInstructions/v5.tsnew file mode 100644index 000000000..02a61cf70--- /dev/null+++ b/packages/eve/extension-contracts/compatibility/dynamicInstructions/v5.ts@@ -0,0 +1,10 @@+import { defineDynamic, defineInstructions } from "#public/instructions/index.js";++export default defineDynamic({+ events: {+ "session.started": (_event, ctx) =>+ defineInstructions({+ markdown: `Use session ${ctx.session.id} when correlating evidence.`,+ }),+ },+});diff --git a/packages/eve/extension-contracts/compatibility/dynamicSkill/v5.ts b/packages/eve/extension-contracts/compatibility/dynamicSkill/v5.tsnew file mode 100644index 000000000..3c6e1498e--- /dev/null+++ b/packages/eve/extension-contracts/compatibility/dynamicSkill/v5.ts@@ -0,0 +1,11 @@+import { defineDynamic, defineSkill } from "#public/skills/index.js";++export default defineDynamic({+ events: {+ "turn.started": (_event, ctx) =>+ defineSkill({+ description: `Review evidence for session ${ctx.session.id}.`,+ markdown: "# Evidence review\n\nCheck every claim against its source.",+ }),+ },+});diff --git a/packages/eve/extension-contracts/compatibility/dynamicTool/v8.ts b/packages/eve/extension-contracts/compatibility/dynamicTool/v8.tsnew file mode 100644index 000000000..81c198d1a--- /dev/null+++ b/packages/eve/extension-contracts/compatibility/dynamicTool/v8.ts@@ -0,0 +1,12 @@+import { defineDynamic, defineTool } from "#public/tools/index.js";++export default defineDynamic({+ events: {+ "session.started": (_event, ctx) =>+ defineTool({+ description: "Return the active session identifier.",+ inputSchema: { type: "object", properties: {} },+ execute: () => ({ sessionId: ctx.session.id }),+ }),+ },+});diff --git a/packages/eve/extension-contracts/compatibility/hook/v6.ts b/packages/eve/extension-contracts/compatibility/hook/v6.tsnew file mode 100644index 000000000..38ecc7e06--- /dev/null+++ b/packages/eve/extension-contracts/compatibility/hook/v6.ts@@ -0,0 +1,13 @@+import { defineHook } from "#public/hooks/index.js";++export default defineHook({+ events: {+ "subagent.completed"(event, ctx) {+ console.info("subagent completed", {+ output: event.data.output,+ sessionId: ctx.session.id,+ subagentName: event.data.subagentName,+ });+ },+ },+});diff --git a/packages/eve/extension-contracts/compatibility/tool/v5.ts b/packages/eve/extension-contracts/compatibility/tool/v5.tsnew file mode 100644index 000000000..2eb635b12--- /dev/null+++ b/packages/eve/extension-contracts/compatibility/tool/v5.ts@@ -0,0 +1,3 @@+import { webSearch } from "#public/tools/index.js";++export default webSearch({ provider: "exa" });diff --git a/packages/eve/extension-contracts/reports/dynamicInstructions/v6.json b/packages/eve/extension-contracts/reports/dynamicInstructions/v6.jsonnew file mode 100644index 000000000..fc44f9ce2--- /dev/null+++ b/packages/eve/extension-contracts/reports/dynamicInstructions/v6.json@@ -0,0 +1,7 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "dynamicInstructions",+ "epoch": 6,+ "sha256": "a05cd00f3ae38e6dca0ffcc9efcd441aefef8d7adf4165494337e7a8d06d3401",+ "exports": ["defineDynamic"]+}diff --git a/packages/eve/extension-contracts/reports/dynamicSkill/v6.json b/packages/eve/extension-contracts/reports/dynamicSkill/v6.jsonnew file mode 100644index 000000000..740be1875--- /dev/null+++ b/packages/eve/extension-contracts/reports/dynamicSkill/v6.json@@ -0,0 +1,7 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "dynamicSkill",+ "epoch": 6,+ "sha256": "a05cd00f3ae38e6dca0ffcc9efcd441aefef8d7adf4165494337e7a8d06d3401",+ "exports": ["defineDynamic"]+}diff --git a/packages/eve/extension-contracts/reports/dynamicTool/v9.json b/packages/eve/extension-contracts/reports/dynamicTool/v9.jsonnew file mode 100644index 000000000..062b74095--- /dev/null+++ b/packages/eve/extension-contracts/reports/dynamicTool/v9.json@@ -0,0 +1,13 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "dynamicTool",+ "epoch": 9,+ "sha256": "08e5aa98e2ad5ab015048f87b1ee3dffabded12f6ba44e6115d123a37a5a5540",+ "exports": [+ "DynamicToolEntry",+ "DynamicToolEvents",+ "DynamicToolResult",+ "DynamicToolSet",+ "defineDynamic"+ ]+}diff --git a/packages/eve/extension-contracts/reports/hook/v7.json b/packages/eve/extension-contracts/reports/hook/v7.jsonnew file mode 100644index 000000000..5468578ab--- /dev/null+++ b/packages/eve/extension-contracts/reports/hook/v7.json@@ -0,0 +1,7 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "hook",+ "epoch": 7,+ "sha256": "613156bdf9f657edc9bf3beeef0e25710c6a483f7e7b85d36a1deb97a84d22f7",+ "exports": ["defineHook"]+}diff --git a/packages/eve/extension-contracts/reports/tool/v6.json b/packages/eve/extension-contracts/reports/tool/v6.jsonnew file mode 100644index 000000000..33cb769fc--- /dev/null+++ b/packages/eve/extension-contracts/reports/tool/v6.json@@ -0,0 +1,22 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "tool",+ "epoch": 6,+ "sha256": "6e7e28ab90833fbf27bee557b991bee04bbd4fe5d1503469b3f82e63b150a32c",+ "exports": [+ "defineBashTool",+ "defineGlobTool",+ "defineGrepTool",+ "defineReadFileTool",+ "defineTool",+ "defineWriteFileTool",+ "disableTool",+ "experimental_workflow",+ "isDisabledToolSentinel",+ "isExperimentalWorkflowToolDefinition",+ "toolOutput",+ "toolOutputPart",+ "toolResultFrom",+ "webSearch"+ ]+}diff --git a/packages/eve/src/client/message-reducer.test.ts b/packages/eve/src/client/message-reducer.test.tsindex e8ae7130f..b6d258180 100644--- a/packages/eve/src/client/message-reducer.test.ts+++ b/packages/eve/src/client/message-reducer.test.ts@@ -129,6 +129,16 @@ describe("defaultMessageReducer", () => {callId: "call_1",kind: "subagent-result",origin: "child",+ outcome: {+ kind: "terminal",+ result: { kind: "succeeded", output: { summary: "done" } },+ usageDelta: {+ cacheReadTokens: 0,+ cacheWriteTokens: 0,+ inputTokens: 0,+ outputTokens: 0,+ },+ },output: { summary: "done" },subagentName: "research",},diff --git a/packages/eve/src/compiler/extension-compatibility.ts b/packages/eve/src/compiler/extension-compatibility.tsindex 5da0ff509..672273ebb 100644--- a/packages/eve/src/compiler/extension-compatibility.ts+++ b/packages/eve/src/compiler/extension-compatibility.ts@@ -21,14 +21,14 @@ interface ExtensionCapabilityContract {const EXTENSION_CAPABILITY_CONTRACTS = {extension: { current: 1, supported: [1], dropped: {} },- tool: { current: 5, supported: [1, 2, 3, 4, 5], dropped: {} },- dynamicTool: { current: 8, supported: [1, 2, 3, 4, 5, 6, 7, 8], dropped: {} },+ tool: { current: 6, supported: [1, 2, 3, 4, 5, 6], dropped: {} },+ dynamicTool: { current: 9, supported: [1, 2, 3, 4, 5, 6, 7, 8, 9], dropped: {} },connection: { current: 2, supported: [1, 2], dropped: {} },- hook: { current: 6, supported: [1, 2, 3, 4, 5, 6], dropped: {} },+ hook: { current: 7, supported: [1, 2, 3, 4, 5, 6, 7], dropped: {} },skill: { current: 1, supported: [1], dropped: {} },- dynamicSkill: { current: 5, supported: [1, 2, 3, 4, 5], dropped: {} },+ dynamicSkill: { current: 6, supported: [1, 2, 3, 4, 5, 6], dropped: {} },instructions: { current: 1, supported: [1], dropped: {} },- dynamicInstructions: { current: 5, supported: [1, 2, 3, 4, 5], dropped: {} },+ dynamicInstructions: { current: 6, supported: [1, 2, 3, 4, 5, 6], dropped: {} },config: { current: 1, supported: [1], dropped: {} },state: { current: 2, supported: [1, 2], dropped: {} },} as const satisfies Record<string, ExtensionCapabilityContract>;diff --git a/packages/eve/src/evals/runner/derive-run-facts.test.ts b/packages/eve/src/evals/runner/derive-run-facts.test.tsindex 805869782..4fb357fa8 100644--- a/packages/eve/src/evals/runner/derive-run-facts.test.ts+++ b/packages/eve/src/evals/runner/derive-run-facts.test.ts@@ -79,6 +79,11 @@ function subagentResult(input: {callId: input.callId,kind: "subagent-result",origin: "child",+ outcome: {+ kind: "terminal",+ result: { kind: "succeeded", output: input.output as never },+ usageDelta: { cacheReadTokens: 0, cacheWriteTokens: 0, inputTokens: 0, outputTokens: 0 },+ },output: input.output as never,subagentName: input.subagentName,},diff --git a/packages/eve/src/execution/agent-continuation-bundle.ts b/packages/eve/src/execution/agent-continuation-bundle.tsnew file mode 100644index 000000000..9849c50d4--- /dev/null+++ b/packages/eve/src/execution/agent-continuation-bundle.ts@@ -0,0 +1,43 @@+import type { RuntimeAgentHandleAction } from "#execution/agent-handle-dispatch.js";+import { resolveRemoteAgentForAction } from "#execution/remote-agent-dispatch.js";+import type { CompiledBundle } from "#runtime/sessions/runtime-context-keys.js";+import type { getDynamicSubagentSelection } from "#context/dynamic-subagent-lifecycle.js";++type DynamicRemoteAgentConfig = NonNullable<+ Extract<+ ReturnType<typeof getDynamicSubagentSelection>,+ { readonly kind: "remote" }+ >["remoteAgent"]+>;++/** Overlays current dynamic credentials without replacing stored delivery coordinates. */+export function createAgentContinuationBundle(input: {+ readonly action: RuntimeAgentHandleAction;+ readonly bundle: CompiledBundle;+ readonly dynamicRemoteAgent?: DynamicRemoteAgentConfig;+}): CompiledBundle {+ const { action, dynamicRemoteAgent } = input;+ if (action.kind !== "remote-agent-call" || dynamicRemoteAgent === undefined) {+ return input.bundle;+ }++ const registry = input.bundle.subagentRegistry.subagentsByNodeId;+ const subagentsByNodeId = Object.assign(new Map(registry), {+ get: (nodeId: string) =>+ nodeId === action.nodeId+ ? {+ definition: resolveRemoteAgentForAction({+ dynamicRemoteAgent,+ nodeId,+ registry,+ remoteAgentName: action.remoteAgentName,+ }),+ }+ : registry.get(nodeId),+ });++ return {+ ...input.bundle,+ subagentRegistry: { ...input.bundle.subagentRegistry, subagentsByNodeId },+ };+}diff --git a/packages/eve/src/execution/agent-handle-dispatch.ts b/packages/eve/src/execution/agent-handle-dispatch.tsindex d57f5ed9c..046a8e528 100644--- a/packages/eve/src/execution/agent-handle-dispatch.ts+++ b/packages/eve/src/execution/agent-handle-dispatch.ts@@ -1,12 +1,56 @@/**- * Shared shapes for the runtime-action dispatch step: the hydrated parent- * session snapshot threaded through dispatch, and the per-action outcome- * every dispatch helper resolves to.+ * Continuation dispatch for stored agent handles.+ *+ * Owns the `agentId` leg of the runtime-action dispatch step: resolving a+ * model-supplied agentId against the session's handle store via+ * `prepareAgentContinuation`, delivering the follow-up message to the+ * address the running handle records, and resolving delivery failures as+ * dead (handle deleted) or retryable (handle restored to `parked`).*/-import type { AgentAddress } from "#harness/handles/store.js";-import type { RuntimeSubagentDispatchFailure } from "#runtime/actions/types.js";+import {+ AGENT_BUSY,+ AGENT_MISMATCH,+ AGENT_UNKNOWN,+ AGENT_UNREACHABLE,+} from "#harness/agent-handle-errors.js";+import { deriveAgentOperationId } from "#harness/handles/operation-id.js";+import type { AgentAddress, AgentHandle, ContinueOperation } from "#harness/handles/store.js";+import { prepareAgentContinuation, rejectAgentEffect } from "#harness/handles/transitions.js";+import type {+ RuntimeActionRequest,+ RuntimeRemoteAgentCallActionRequest,+ RuntimeSubagentCallActionRequest,+ RuntimeSubagentDispatchFailure,+} from "#runtime/actions/types.js";+import type { CompiledBundle } from "#runtime/sessions/runtime-context-keys.js";+import {+ continueRemoteAgentSession,+ isRetryableRemoteAgentContinueError,+ resolveRemoteAgentForAction,+} from "#execution/remote-agent-dispatch.js";+import { isRuntimeNoActiveSessionError } from "#execution/runtime-errors.js";import type { hydrateDurableSession } from "#execution/session.js";+import { normalizeRequestedOutputSchema } from "#execution/subagent-invocation.js";+import { createWorkflowRuntime } from "#execution/workflow-runtime.js";+import { createWorkflowCallbackUrl } from "#execution/workflow-callback-url.js";+import { createLogger, logError } from "#internal/logging.js";+import { createEveCallbackRoutePath } from "#protocol/routes.js";+import { err, ok, type Result } from "#shared/result.js";++const log = createLogger("execution.agent-handle-dispatch");++/** Runtime action kinds that may address an agent handle via `agentId`. */+export type RuntimeAgentHandleAction =+ | RuntimeRemoteAgentCallActionRequest+ | RuntimeSubagentCallActionRequest;++/** Narrows an action to the kinds that may carry an `agentId` continuation. */+export function isAgentHandleAction(+ action: RuntimeActionRequest,+): action is RuntimeAgentHandleAction {+ return action.kind === "subagent-call" || action.kind === "remote-agent-call";+}/** Hydrated parent session snapshot threaded through dispatch. */export type RuntimeSession = ReturnType<typeof hydrateDurableSession>;@@ -35,3 +79,257 @@ export type DispatchOutcome =readonly result: RuntimeSubagentDispatchFailure;readonly session: RuntimeSession;};++/**+ * Delivers one `agentId` continuation to the child the handle names.+ *+ * Unknown ids, name mismatches, and busy handles report `AGENT_UNKNOWN` /+ * `AGENT_MISMATCH` / `AGENT_BUSY` without touching the store. Delivery+ * failures report `AGENT_UNREACHABLE`: permanent ones resolve the handle as+ * dead, transient ones restore it to `parked` so the model can retry the+ * same agentId.+ */+export async function dispatchToAgentHandle(input: {+ readonly action: RuntimeAgentHandleAction;+ readonly agentId: string;+ readonly bundle: CompiledBundle;+ readonly currentSession: RuntimeSession;+ readonly parentToken: string;+ readonly parentTurnId: string;+}): Promise<DispatchOutcome> {+ const { action, agentId, bundle } = input;+ const invokedName =+ action.kind === "remote-agent-call" ? action.remoteAgentName : action.subagentName;+ const operation: ContinueOperation = {+ callId: action.callId,+ id: deriveAgentOperationId({+ callId: action.callId,+ parentSessionId: input.currentSession.sessionId,+ parentTurnId: input.parentTurnId,+ }),+ kind: "continue",+ parentTurnId: input.parentTurnId,+ // Placeholder: prepareAgentContinuation records the handle's actual+ // pre-delivery status so a retryable rejection can restore it.+ previousStatus: "",+ };+ // Prepared against the in-progress session so a handle resolved earlier in+ // this batch is already gone.+ const prepared = prepareAgentContinuation(input.currentSession, {+ agentId,+ invokedName,+ operation,+ });++ switch (prepared.kind) {+ case "unknown":+ return {+ kind: "error",+ result: createAgentErrorResult({+ action,+ code: AGENT_UNKNOWN,+ message: `No agent from the <agents> list found for id "${agentId}".`,+ }),+ session: input.currentSession,+ };+ case "mismatch":+ return {+ kind: "error",+ result: createAgentErrorResult({+ action,+ code: AGENT_MISMATCH,+ message: `Agent "${agentId}" from the <agents> list does not belong to "${invokedName}".`,+ }),+ session: input.currentSession,+ };+ case "busy":+ return {+ kind: "error",+ result: createAgentErrorResult({+ action,+ code: AGENT_BUSY,+ message: `Agent "${agentId}" is still working on its previous request. Wait for its result before continuing it.`,+ }),+ session: input.currentSession,+ };+ case "ready":+ break;+ }++ const { handle } = prepared;+ // Not exactly-once: `prepareAgentContinuation` only moved the handle to+ // `running` on the step's working snapshot, which durably commits when the+ // enclosing dispatch step's result commits. If delivery succeeds and the+ // step dies before that commit, replay starts from `parked` and delivers+ // the same operation again — the same start-effect/step-commit window+ // accepted for child starts. The callee has no receiver-side dedup for+ // this; `prepareAgentContinuation` treating the recorded operation as a+ // replay only makes the parent-side transition idempotent.+ const delivery = await deliverToAgentHandle({+ action,+ bundle,+ handle,+ parentToken: input.parentToken,+ });+ if (!delivery.ok) {+ const { cause, permanent } = delivery.error;+ logError(log, "agent delivery failed", cause, {+ agentId,+ callId: action.callId,+ nodeId: handle.identity.nodeId,+ permanent,+ subagentName: handle.identity.name,+ });+ // Only permanent failures resolve the handle as dead (forfeiting the+ // child's accumulated conversation); a transiently unreachable agent is+ // restored to `parked` so the model can retry the same agentId.+ return {+ kind: "error",+ result: createAgentErrorResult({+ action,+ code: AGENT_UNREACHABLE,+ message: permanent+ ? `Agent "${handle.identity.name}" with id "${agentId}" is no longer reachable.`+ : `Agent "${handle.identity.name}" with id "${agentId}" is temporarily unreachable. Try again.`,+ }),+ session: rejectAgentEffect(prepared.session, {+ disposition: permanent ? "dead" : "retryable",+ operationId: operation.id,+ }),+ };+ }++ return {+ address: handle.address,+ callId: action.callId,+ kind: "called",+ name: action.name,+ session: prepared.session,+ toolName: handle.identity.name,+ };+}++/**+ * Attempts the continuation delivery once and classifies the failure.+ *+ * Transient failures are never retried automatically: the callee may have+ * accepted the message even though the response was lost, so a re-send could+ * deliver the same turn twice. The caller surfaces a retryable+ * AGENT_UNREACHABLE instead and the model decides whether to try again.+ * Throwing is equally unsafe — a durable-step retry would re-dispatch+ * already-started siblings.+ */+async function deliverToAgentHandle(input: {+ readonly action: RuntimeAgentHandleAction;+ readonly bundle: CompiledBundle;+ readonly handle: Extract<AgentHandle, { phase: "running" }>;+ readonly parentToken: string;+}): Promise<Result<void, { readonly cause: unknown; readonly permanent: boolean }>> {+ const { action, bundle, handle } = input;+ const { address, identity } = handle;++ if (address.kind === "agent/remote") {+ // A remote deployment old enough to omit a continuationToken cannot+ // receive continuations; no retry can change that.+ if (address.continuationToken === undefined) {+ return err({+ cause: new Error(+ `Remote agent "${identity.name}" returned no continuationToken at start; its deployment does not support continuations.`,+ ),+ permanent: true,+ });+ }+ let resolvedRemote;+ try {+ resolvedRemote = resolveRemoteAgentForAction({+ nodeId: identity.nodeId,+ remoteAgentName: identity.name,+ registry: bundle.subagentRegistry.subagentsByNodeId,+ });+ } catch (error) {+ // The agent's node is gone from the compiled bundle; no retry can+ // reach this handle again.+ return err({ cause: error, permanent: true });+ }+ try {+ await continueRemoteAgentSession({+ callback: {+ callId: action.callId,+ subagentName: identity.name,+ token: input.parentToken,+ url: createWorkflowCallbackUrl(+ address.callbackBaseUrl,+ createEveCallbackRoutePath(input.parentToken),+ ),+ },+ continuationToken: address.continuationToken,+ message: readSubagentMessage(action),+ outputSchema: normalizeRequestedOutputSchema(action.input.outputSchema),+ remote: { ...resolvedRemote, url: address.url },+ sessionId: address.sessionId,+ });+ } catch (error) {+ return err({+ cause: error,+ permanent: !isRetryableRemoteAgentContinueError(error),+ });+ }+ return ok(undefined);+ }++ const childRuntime = createWorkflowRuntime({+ compiledArtifactsSource: bundle.compiledArtifactsSource,+ nodeId: identity.nodeId,+ });+ try {+ const result = await childRuntime.dispatchSession({+ command: {+ caller: {+ callId: action.callId,+ replyTo: { kind: "hook", token: input.parentToken },+ subagentName: identity.name,+ },+ kind: "send",+ payload: {+ message: readSubagentMessage(action),+ outputSchema: normalizeRequestedOutputSchema(action.input.outputSchema),+ },+ },+ sessionId: address.sessionId,+ });+ if (result.status === "session_not_active") {+ return err({+ cause: new Error(`Agent session "${address.sessionId}" is no longer active.`),+ permanent: true,+ });+ }+ } catch (error) {+ return err({ cause: error, permanent: isRuntimeNoActiveSessionError(error) });+ }+ return ok(undefined);+}++function createAgentErrorResult(input: {+ readonly action: RuntimeAgentHandleAction;+ readonly code: string;+ readonly message: string;+}): RuntimeSubagentDispatchFailure {+ return {+ callId: input.action.callId,+ isError: true,+ kind: "subagent-result",+ origin: "dispatch",+ output: {+ code: input.code,+ message: input.message,+ },+ subagentName:+ input.action.kind === "remote-agent-call"+ ? input.action.remoteAgentName+ : input.action.subagentName,+ };+}++function readSubagentMessage(action: RuntimeAgentHandleAction): string {+ return typeof action.input.message === "string" ? action.input.message : "";+}diff --git a/packages/eve/src/execution/delegated-parent-notification.test.ts b/packages/eve/src/execution/delegated-parent-notification.test.tsindex 0642b6080..a77ae2882 100644--- a/packages/eve/src/execution/delegated-parent-notification.test.ts+++ b/packages/eve/src/execution/delegated-parent-notification.test.ts@@ -1,12 +1,18 @@-import { beforeEach, describe, expect, it, vi } from "vitest";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { ContextContainer } from "#context/container.js";import { serializeContext } from "#context/serialize.js";+import { 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 { notifyDelegatedParentStep } from "#execution/delegated-parent-notification.js";+import {+ notifyDelegatedParentStep,+ notifyTurnCallerStep,+ resolveInitialTurnCallerStep,+} from "#execution/delegated-parent-notification.js";import { SUBAGENT_ADAPTER } from "#execution/subagent-adapter.js";import { SUBAGENT_ADAPTER_KIND } from "#execution/subagent-adapter-state.js";+import { HookNotFoundError } from "#compiled/@workflow/errors/index.js";import { resumeHook } from "#internal/workflow/runtime.js";import type { RuntimeSubagentChildResult } from "#runtime/actions/types.js";@@ -19,14 +25,21 @@ vi.mock("#compiled/@workflow/core/runtime.js", () => ({}));const resumeHookMock = vi.mocked(resumeHook);+const fetchMock = vi.fn();const USAGE = { cacheReadTokens: 10, cacheWriteTokens: 5, inputTokens: 100, outputTokens: 50 };+const ZERO_USAGE = { cacheReadTokens: 0, cacheWriteTokens: 0, inputTokens: 0, outputTokens: 0 };function createSuccessResult(): RuntimeSubagentChildResult {return {callId: "call-1",kind: "subagent-result",origin: "child",+ outcome: {+ kind: "terminal",+ result: { kind: "succeeded", output: "done" },+ usageDelta: ZERO_USAGE,+ },output: "done",subagentName: "research",};@@ -44,6 +57,7 @@ function createSerializedContext(): Record<string, unknown> {const ctx = new ContextContainer();ctx.set(BundleKey, bundle);+ ctx.set(SessionIdKey, "child-session");ctx.set(ChannelKey, {...SUBAGENT_ADAPTER,state: {@@ -62,7 +76,7 @@ describe("notifyDelegatedParentStep", () => {resumeHookMock.mockResolvedValue(undefined as never);});- it("attaches usage to a success result", async () => {+ it("attaches usage to a success result and folds it into the outcome delta", async () => {await notifyDelegatedParentStep({result: createSuccessResult(),serializedContext: createSerializedContext(),@@ -76,6 +90,11 @@ describe("notifyDelegatedParentStep", () => {callId: "call-1",kind: "subagent-result",origin: "child",+ outcome: {+ kind: "terminal",+ result: { kind: "succeeded", output: "done" },+ usageDelta: USAGE,+ },output: "done",subagentName: "research",usage: USAGE,@@ -102,6 +121,14 @@ describe("notifyDelegatedParentStep", () => {isError: true,kind: "subagent-result",origin: "child",+ outcome: {+ kind: "terminal",+ result: {+ error: { code: "SUBAGENT_EXECUTION_FAILED", message: "boom" },+ kind: "failed",+ },+ usageDelta: ZERO_USAGE,+ },output: { code: "SUBAGENT_EXECUTION_FAILED", message: "boom" },subagentName: "research",};@@ -118,3 +145,273 @@ describe("notifyDelegatedParentStep", () => {});});});++describe("turn caller notification", () => {+ beforeEach(() => {+ resumeHookMock.mockReset();+ resumeHookMock.mockResolvedValue(undefined as never);+ fetchMock.mockReset();+ fetchMock.mockResolvedValue(new Response(null, { status: 202 }));+ vi.stubGlobal("fetch", fetchMock);+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it("is a no-op when the conversation has no turn caller", async () => {+ const serializedContext = { "eve.sessionId": "root-session" };+ const caller = await resolveInitialTurnCallerStep({ serializedContext });++ expect(caller).toBeUndefined();+ await expect(+ notifyTurnCallerStep({+ caller,+ lifecycle: "parked",+ sessionId: "root-session",+ settled: { output: "root answer" },+ }),+ ).resolves.toBeUndefined();++ expect(fetchMock).not.toHaveBeenCalled();+ expect(resumeHookMock).not.toHaveBeenCalled();+ });++ it("uses the adapter state for the child's first settled turn", async () => {+ const serializedContext = createSerializedContext();+ const caller = await resolveInitialTurnCallerStep({ serializedContext });+ await notifyTurnCallerStep({+ caller,+ lifecycle: "parked",+ sessionId: "child-session",+ settled: { output: "first answer", usage: USAGE },+ });++ expect(resumeHookMock).toHaveBeenCalledWith("parent-tok", {+ kind: "runtime-action-result",+ results: [+ {+ callId: "call-1",+ kind: "subagent-result",+ origin: "child",+ outcome: {+ kind: "parked",+ result: { kind: "succeeded", output: "first answer" },+ usageDelta: USAGE,+ },+ output: "first answer",+ subagentName: "research",+ usage: USAGE,+ },+ ],+ });+ });++ it("notifies the caller of a continued turn with a zero usage delta", async () => {+ await notifyTurnCallerStep({+ caller: {+ callId: "call-2",+ replyTo: { kind: "hook", token: "parent-turn-2" },+ subagentName: "research",+ },+ lifecycle: "parked",+ sessionId: "child-session",+ settled: { output: "follow-up answer" },+ });++ expect(resumeHookMock).toHaveBeenCalledExactlyOnceWith("parent-turn-2", {+ kind: "runtime-action-result",+ results: [+ {+ callId: "call-2",+ kind: "subagent-result",+ origin: "child",+ outcome: {+ kind: "parked",+ result: { kind: "succeeded", output: "follow-up answer" },+ usageDelta: ZERO_USAGE,+ },+ output: "follow-up answer",+ subagentName: "research",+ },+ ],+ });+ });++ it("reports a parked failure as a parked outcome carrying the usage delta", async () => {+ await notifyTurnCallerStep({+ caller: {+ callId: "call-2",+ replyTo: { kind: "hook", token: "parent-turn-2" },+ subagentName: "research",+ },+ lifecycle: "parked",+ sessionId: "child-session",+ settled: {+ isError: true,+ output: "The agent could not produce a result matching the requested schema.",+ usage: USAGE,+ },+ });++ const error = {+ code: "SUBAGENT_EXECUTION_FAILED",+ message: "The agent could not produce a result matching the requested schema.",+ };+ expect(resumeHookMock).toHaveBeenCalledWith("parent-turn-2", {+ kind: "runtime-action-result",+ results: [+ {+ callId: "call-2",+ isError: true,+ kind: "subagent-result",+ origin: "child",+ outcome: {+ kind: "parked",+ result: { error, kind: "failed" },+ usageDelta: USAGE,+ },+ output: error,+ subagentName: "research",+ },+ ],+ });+ });++ it("marks a crash-path notification terminal", async () => {+ await notifyTurnCallerStep({+ caller: {+ callId: "call-3",+ replyTo: { kind: "hook", token: "parent-turn-3" },+ subagentName: "research",+ },+ lifecycle: "terminal",+ sessionId: "child-session",+ settled: { isError: true, output: new Error("driver crashed") },+ });++ const error = { code: "SUBAGENT_EXECUTION_FAILED", message: "driver crashed" };+ expect(resumeHookMock).toHaveBeenCalledWith("parent-turn-3", {+ kind: "runtime-action-result",+ results: [+ {+ callId: "call-3",+ isError: true,+ kind: "subagent-result",+ origin: "child",+ outcome: {+ kind: "terminal",+ result: { error, kind: "failed" },+ usageDelta: ZERO_USAGE,+ },+ output: error,+ subagentName: "research",+ },+ ],+ });+ });++ it("posts a settled turn with its outcome to the remote callback", async () => {+ const serializedContext = {+ "eve.sessionCallback": {+ callId: "call-remote",+ subagentName: "remote",+ token: "parent-turn",+ url: "https://caller.example/eve/v1/callback/parent-turn",+ },+ "eve.sessionId": "remote-session",+ };+ const caller = await resolveInitialTurnCallerStep({ serializedContext });+ await notifyTurnCallerStep({+ caller,+ lifecycle: "parked",+ sessionId: "remote-session",+ settled: { output: "remote answer" },+ });++ expect(fetchMock).toHaveBeenCalledWith(+ "https://caller.example/eve/v1/callback/parent-turn",+ expect.objectContaining({ method: "POST" }),+ );+ const body: unknown = JSON.parse((fetchMock.mock.calls[0]![1] as { body: string }).body);+ expect(body).toEqual({+ callId: "call-remote",+ kind: "turn.completed",+ outcome: {+ kind: "parked",+ result: { kind: "succeeded", output: "remote answer" },+ usageDelta: ZERO_USAGE,+ },+ output: "remote answer",+ sessionId: "remote-session",+ subagentName: "remote",+ });+ expect(resumeHookMock).not.toHaveBeenCalled();+ });++ it("posts a failed turn with its outcome to a remote callback", async () => {+ await notifyTurnCallerStep({+ caller: {+ callId: "call-remote",+ replyTo: {+ kind: "callback",+ url: "https://caller.example/eve/v1/callback/parent-turn",+ },+ subagentName: "remote",+ },+ lifecycle: "terminal",+ sessionId: "remote-session",+ settled: { isError: true, output: new Error("remote failed"), usage: USAGE },+ });++ const body: unknown = JSON.parse((fetchMock.mock.calls[0]![1] as { body: string }).body);+ expect(body).toEqual({+ callId: "call-remote",+ error: {+ code: "SUBAGENT_EXECUTION_FAILED",+ message: "remote failed",+ },+ kind: "turn.failed",+ outcome: {+ kind: "terminal",+ result: {+ error: { code: "SUBAGENT_EXECUTION_FAILED", message: "remote failed" },+ kind: "failed",+ },+ usageDelta: USAGE,+ },+ sessionId: "remote-session",+ subagentName: "remote",+ });+ });++ it("warns and returns when the caller hook no longer exists", async () => {+ const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});+ resumeHookMock.mockRejectedValue(new HookNotFoundError("parent-tok"));++ try {+ await expect(+ notifyTurnCallerStep({+ caller: {+ callId: "call-1",+ replyTo: { kind: "hook", token: "parent-tok" },+ subagentName: "research",+ },+ lifecycle: "parked",+ sessionId: "child-session",+ settled: { output: "late answer" },+ }),+ ).resolves.toBeUndefined();++ expect(warnSpy).toHaveBeenCalledWith(+ "[eve:execution.delegated-parent-notification] turn caller hook no longer exists",+ expect.objectContaining({+ callId: "call-1",+ callerToken: "parent-tok",+ }),+ );+ } finally {+ warnSpy.mockRestore();+ }+ });+});diff --git a/packages/eve/src/execution/delegated-parent-notification.ts b/packages/eve/src/execution/delegated-parent-notification.tsindex fc78ed649..66b39334a 100644--- a/packages/eve/src/execution/delegated-parent-notification.ts+++ b/packages/eve/src/execution/delegated-parent-notification.ts@@ -1,16 +1,29 @@/**- * Bridges a delegated subagent's terminal outcome back to its parent- * driver via the subagent-result hook. Pure projection helpers live- * in `delegated-parent-result.ts` so the workflow step-proxy transform- * doesn't strip them from this file.+ * Sends delegated task results to their parent and conversation results to+ * the caller of each turn.*/import { ChannelKey } from "#runtime/sessions/runtime-context-keys.js";import { deserializeContext } from "#context/serialize.js";+import { parseSessionCallback } from "#channel/session-callback.js";+import type { TurnCaller } from "#channel/types.js";import type { RuntimeSubagentChildResult } from "#runtime/actions/types.js";-import { SUBAGENT_ADAPTER_KIND } from "#execution/subagent-adapter-state.js";+import { SessionCallbackKey } from "#context/keys.js";+import {+ isSubagentAdapterState,+ SUBAGENT_ADAPTER_KIND,+} from "#execution/subagent-adapter-state.js";+import { HookNotFoundError } from "#compiled/@workflow/errors/index.js";+import { SUBAGENT_EXECUTION_FAILED } from "#harness/agent-handle-errors.js";+import { createLogger } from "#internal/logging.js";+import type { AgentTurnOutcome } from "#shared/agent-turn-outcome.js";+import { toErrorMessage } from "#shared/errors.js";+import { parseJsonValue } from "#shared/json.js";import type { TokenUsage } from "#shared/token-usage.js";import { resumeHook } from "#internal/workflow/runtime.js";+import { postSessionCallbackRequest } from "#execution/session-callback-request.js";++const log = createLogger("execution.delegated-parent-notification");/*** Resumes the parent driver's hook with a delegated subagent result.@@ -43,13 +56,225 @@ export async function notifyDelegatedParentStep(input: {return;}+ // A task child reports its session totals exactly once, so those totals+ // are the turn's usage delta; the terminal envelope carries them so the+ // parent folds spend from the outcome alone.const result =input.usage === undefined || input.result.isError === true? input.result- : { ...input.result, usage: input.usage };+ : {+ ...input.result,+ outcome: { ...input.result.outcome, usageDelta: input.usage },+ usage: input.usage,+ };await resumeHook(parentContinuationToken, {kind: "runtime-action-result",results: [result],});}++/** Settled turn payload forwarded from the driver to the caller. */+export interface SettledTurnNotification {+ readonly output: unknown;+ readonly isError?: boolean;+ /** Usage this turn added; omitted (zero) on crash and expiry paths. */+ readonly usage?: TokenUsage;+}++const ZERO_TOKEN_USAGE: TokenUsage = {+ cacheReadTokens: 0,+ cacheWriteTokens: 0,+ inputTokens: 0,+ outputTokens: 0,+};++/**+ * Sends a settled conversation turn to the caller that started it.+ *+ * `lifecycle` is the child engine's explicit verdict — `parked` when the+ * child session survived the turn and can accept another delivery,+ * `terminal` when it ended with this turn. It is carried on the result as+ * an {@link AgentTurnOutcome} so the caller never infers lifecycle from+ * success or error codes.+ */+export async function notifyTurnCallerStep(input: {+ readonly caller: TurnCaller | undefined;+ readonly lifecycle: AgentTurnOutcome["kind"];+ readonly sessionId: string;+ readonly settled: SettledTurnNotification;+}): Promise<void> {+ "use step";++ if (input.caller === undefined) {+ return;+ }++ const result = createSettledTurnResult({+ caller: input.caller,+ lifecycle: input.lifecycle,+ sessionId: input.sessionId,+ settled: input.settled,+ });++ if (input.caller.replyTo.kind === "callback") {+ await postSettledTurnCallback({+ result,+ sessionId: input.sessionId,+ url: input.caller.replyTo.url,+ });+ return;+ }++ await resumeSettledTurnHook(input.caller.replyTo.token, result);+}++function createSettledTurnResult(input: {+ readonly caller: TurnCaller;+ readonly lifecycle: AgentTurnOutcome["kind"];+ readonly sessionId: string;+ readonly settled: SettledTurnNotification;+}): RuntimeSubagentChildResult {+ const usageDelta = input.settled.usage ?? ZERO_TOKEN_USAGE;++ if (input.settled.isError === true) {+ const error = {+ code: SUBAGENT_EXECUTION_FAILED,+ message: toErrorMessage(input.settled.output),+ };+ return {+ callId: input.caller.callId,+ isError: true,+ kind: "subagent-result",+ origin: "child",+ outcome: {+ kind: input.lifecycle,+ result: { error, kind: "failed" },+ usageDelta,+ },+ output: error,+ subagentName: input.caller.subagentName,+ };+ }++ const output = parseJsonValue(input.settled.output);+ const result: RuntimeSubagentChildResult = {+ callId: input.caller.callId,+ kind: "subagent-result",+ origin: "child",+ outcome: {+ kind: input.lifecycle,+ result: { kind: "succeeded", output },+ usageDelta,+ },+ output,+ subagentName: input.caller.subagentName,+ };+ // Legacy per-result usage projection (usage spans); the parent folds+ // `outcome.usageDelta`, never this field, when an outcome is present.+ return input.settled.usage === undefined ? result : { ...result, usage: input.settled.usage };+}++/** Resolves the caller that created a delegated conversation session. */+export async function resolveInitialTurnCallerStep(input: {+ readonly serializedContext: Record<string, unknown>;+}): Promise<TurnCaller | undefined> {+ "use step";++ const callbackValue = input.serializedContext[SessionCallbackKey.name];+ if (callbackValue !== undefined) {+ const parsed = parseSessionCallback(callbackValue);+ if (!parsed.ok) {+ throw new Error("Serialized session callback is invalid.", {+ cause: parsed.cause,+ });+ }+ return {+ callId: parsed.callback.callId,+ replyTo: { kind: "callback", url: parsed.callback.url },+ subagentName: parsed.callback.subagentName,+ };+ }++ const ctx = await deserializeContext(input.serializedContext);+ const adapter = ctx.get(ChannelKey);+ if (adapter?.kind !== SUBAGENT_ADAPTER_KIND || !isSubagentAdapterState(adapter.state)) {+ return undefined;+ }++ return {+ callId: adapter.state.callId,+ replyTo: { kind: "hook", token: adapter.state.parentContinuationToken },+ subagentName: adapter.state.subagentName,+ };+}++async function postSettledTurnCallback(input: {+ readonly result: RuntimeSubagentChildResult;+ /** Informational on the wire (tracing); the receiver never verifies it. */+ readonly sessionId: string;+ readonly url: string;+}): Promise<void> {+ const { sessionId } = input;+ if (input.result.isError === true) {+ await postCallbackPayload({+ payload: {+ callId: input.result.callId,+ error: input.result.output,+ kind: "turn.failed",+ outcome: input.result.outcome,+ sessionId,+ subagentName: input.result.subagentName,+ },+ url: input.url,+ });+ return;+ }++ await postCallbackPayload({+ payload: {+ callId: input.result.callId,+ kind: "turn.completed",+ outcome: input.result.outcome,+ output: input.result.output,+ sessionId,+ subagentName: input.result.subagentName,+ },+ url: input.url,+ });+}++async function postCallbackPayload(input: {+ readonly payload: unknown;+ readonly url: string;+}): Promise<void> {+ const response = await postSessionCallbackRequest({+ body: input.payload,+ url: input.url,+ });++ if (!response.ok) {+ throw new Error(`Turn callback failed with HTTP ${response.status}.`);+ }+}++async function resumeSettledTurnHook(+ token: string,+ result: RuntimeSubagentChildResult,+): Promise<void> {+ try {+ await resumeHook(token, {+ kind: "runtime-action-result",+ results: [result],+ });+ } catch (error) {+ if (!HookNotFoundError.is(error)) {+ throw error;+ }++ log.warn("turn caller hook no longer exists", {+ callId: result.callId,+ callerToken: token,+ });+ }+}diff --git a/packages/eve/src/execution/delegated-parent-result.ts b/packages/eve/src/execution/delegated-parent-result.tsindex b10928b90..fa0c3c4ad 100644--- a/packages/eve/src/execution/delegated-parent-result.ts+++ b/packages/eve/src/execution/delegated-parent-result.ts@@ -9,8 +9,16 @@ import { SUBAGENT_EXECUTION_FAILED } from "#harness/agent-handle-errors.js";import type { RuntimeSubagentChildResult } from "#runtime/actions/types.js";import type { JsonValue } from "#shared/json.js";import { toErrorMessage } from "#shared/errors.js";+import type { TokenUsage } from "#shared/token-usage.js";import { SUBAGENT_ADAPTER_KIND } from "#execution/subagent-adapter-state.js";+const ZERO_TOKEN_USAGE: TokenUsage = {+ cacheReadTokens: 0,+ cacheWriteTokens: 0,+ inputTokens: 0,+ outputTokens: 0,+};+/*** Builds the success-shaped {@link RuntimeSubagentChildResult}.* Returns `undefined` for root sessions (no parent to notify).@@ -27,10 +35,18 @@ export function createDelegatedSubagentSuccessResult(return undefined;}+ // A task child ends with its result, so the outcome is always terminal.+ // `usageDelta` starts at zero; the notification step folds in the child's+ // session totals when it has them (task children report exactly once).return {callId: String(channel.state?.callId ?? ""),kind: "subagent-result",origin: "child",+ outcome: {+ kind: "terminal",+ result: { kind: "succeeded", output: output as JsonValue },+ usageDelta: ZERO_TOKEN_USAGE,+ },output: output as JsonValue,subagentName: String(channel.state?.subagentName ?? ""),};@@ -47,12 +63,18 @@ export function createDelegatedSubagentErrorResult(return undefined;}+ const output = {+ code: SUBAGENT_EXECUTION_FAILED,+ message: toErrorMessage(error),+ };return {...success,isError: true,- output: {- code: SUBAGENT_EXECUTION_FAILED,- message: toErrorMessage(error),+ outcome: {+ kind: "terminal",+ result: { error: output, kind: "failed" },+ usageDelta: ZERO_TOKEN_USAGE,},+ output,};}diff --git a/packages/eve/src/execution/dispatch-action-failures.ts b/packages/eve/src/execution/dispatch-action-failures.tsnew file mode 100644index 000000000..2aa980b9b--- /dev/null+++ b/packages/eve/src/execution/dispatch-action-failures.ts@@ -0,0 +1,63 @@+import { REMOTE_AGENT_START_FAILED } from "#harness/agent-handle-errors.js";+import type {+ RuntimeRemoteAgentCallActionRequest,+ RuntimeSubagentCallActionRequest,+ RuntimeSubagentDispatchFailure,+} from "#runtime/actions/types.js";+import { toErrorMessage } from "#shared/errors.js";++export function createUnavailableDynamicSubagentResult(+ action: RuntimeSubagentCallActionRequest | RuntimeRemoteAgentCallActionRequest,+): RuntimeSubagentDispatchFailure {+ const subagentName = getSubagentName(action);+ return {+ callId: action.callId,+ isError: true,+ kind: "subagent-result",+ origin: "dispatch",+ output: {+ code: "SUBAGENT_UNAVAILABLE",+ message: `Subagent "${subagentName}" is not available in the current session context.`,+ },+ subagentName,+ };+}++export function getSubagentName(+ action: RuntimeSubagentCallActionRequest | RuntimeRemoteAgentCallActionRequest,+): string {+ return action.kind === "remote-agent-call" ? action.remoteAgentName : action.subagentName;+}++export function createRemoteAgentStartFailureResult(input: {+ readonly action: RuntimeRemoteAgentCallActionRequest;+ readonly error: unknown;+}): RuntimeSubagentDispatchFailure {+ return {+ callId: input.action.callId,+ isError: true,+ kind: "subagent-result",+ origin: "dispatch",+ output: {+ code: REMOTE_AGENT_START_FAILED,+ message: toErrorMessage(input.error),+ },+ subagentName: input.action.remoteAgentName,+ };+}++export function createRecursiveAgentRootOnlyResult(+ action: RuntimeSubagentCallActionRequest,+): RuntimeSubagentDispatchFailure {+ return {+ callId: action.callId,+ isError: true,+ kind: "subagent-result",+ origin: "dispatch",+ output: {+ code: "RECURSIVE_AGENT_ROOT_ONLY",+ message: 'The built-in "agent" tool is only available to the root session.',+ },+ subagentName: action.subagentName,+ };+}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.tsindex 5537adc1e..7c846d480 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@@ -1,6 +1,7 @@import { beforeEach, describe, expect, it, vi } from "vitest";import type { ChannelAdapter } from "#channel/adapter.js";+import { RemoteAgentContinueRequestError } from "#execution/remote-agent-dispatch.js";import type { DurableSessionState } from "#execution/durable-session-store.js";import { dispatchRuntimeActionsStep } from "#execution/dispatch-runtime-actions-step.js";import {@@ -24,8 +25,10 @@ import {import { BundleKey, ChannelKey } from "#runtime/sessions/runtime-context-keys.js";const mocks = vi.hoisted(() => ({+ continueRemoteAgentSession: vi.fn(),createDurableSessionState: vi.fn(),deserializeContext: vi.fn(),+ dispatchSession: vi.fn(),hydrateDurableSession: vi.fn(),readDurableSession: vi.fn(),createSession: vi.fn(),@@ -49,6 +52,7 @@ vi.mock("#execution/session.js", () => ({vi.mock("#execution/workflow-runtime.js", () => ({createWorkflowRuntime: () => ({createSession: mocks.createSession,+ dispatchSession: mocks.dispatchSession,}),workflowEntryReference: { workflowId: "workflow//eve//workflowEntry" },}));@@ -58,6 +62,7 @@ vi.mock("#execution/workflow-runtime.js", () => ({// retry/forfeit policy.vi.mock("#execution/remote-agent-dispatch.js", async (importOriginal) => ({...(await importOriginal<typeof import("#execution/remote-agent-dispatch.js")>()),+ continueRemoteAgentSession: mocks.continueRemoteAgentSession,startRemoteAgentSession: mocks.startRemoteAgentSession,}));@@ -71,6 +76,46 @@ const BASE_STATE: DurableSessionState = {};const CHILD_SESSION_ID = "child-session-123456789012";+const PARKED_START_OPERATION_ID = deriveAgentOperationId({+ callId: "call-0",+ parentSessionId: "parent-session",+ parentTurnId: "turn-0",+});++const LOCAL_CHILD_CONTINUATION_TOKEN = "subagent:parent:child";++const LOCAL_PARKED_HANDLE: AgentHandle = {+ address: {+ continuationToken: LOCAL_CHILD_CONTINUATION_TOKEN,+ kind: "agent/local",+ sessionId: CHILD_SESSION_ID,+ },+ identity: {+ id: deriveAgentId("research", PARKED_START_OPERATION_ID),+ name: "research",+ nodeId: "subagents/research",+ },+ lastStatus: "initial result",+ phase: "parked",+};++const REMOTE_PARKED_HANDLE: AgentHandle = {+ address: {+ callbackBaseUrl: "https://caller.example.com",+ continuationToken: "remote-token",+ kind: "agent/remote",+ sessionId: "remote-session-123456789012",+ url: "https://remote.example.com",+ },+ identity: {+ id: deriveAgentId("research", PARKED_START_OPERATION_ID),+ name: "research",+ nodeId: "remote/research",+ },+ lastStatus: "initial result",+ phase: "parked",+};+const REMOTE_REGISTRY_DEFINITION = {description: "Remote research",kind: "remote",@@ -83,6 +128,8 @@ const REMOTE_REGISTRY_DEFINITION = {beforeEach(() => {vi.clearAllMocks();mocks.createSession.mockResolvedValue({ sessionId: CHILD_SESSION_ID });+ mocks.dispatchSession.mockResolvedValue({ sessionId: CHILD_SESSION_ID, status: "accepted" });+ mocks.continueRemoteAgentSession.mockResolvedValue(undefined);mocks.startRemoteAgentSession.mockResolvedValue({continuationToken: "remote-child-token",sessionId: "remote-session-123456789012",@@ -256,6 +303,16 @@ describe("dispatchRuntimeActionsStep child starts", () => {callId: "call-unknown",kind: "subagent-result",origin: "child",+ outcome: {+ kind: "terminal",+ result: { kind: "succeeded", output: "stray" },+ usageDelta: {+ cacheReadTokens: 0,+ cacheWriteTokens: 0,+ inputTokens: 0,+ outputTokens: 0,+ },+ },output: "stray",subagentName: "research",},@@ -272,6 +329,16 @@ describe("dispatchRuntimeActionsStep child starts", () => {callId: "call-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: "research",},@@ -283,6 +350,252 @@ describe("dispatchRuntimeActionsStep child starts", () => {});});+describe("dispatchRuntimeActionsStep agent delivery", () => {+ const continueOperationId = deriveAgentOperationId({+ callId: "call-1",+ parentSessionId: "parent-session",+ parentTurnId: "turn-1",+ });++ it("delivers the raw message to a parked local handle and records the running operation", async () => {+ const session = createPendingSession({+ handle: LOCAL_PARKED_HANDLE,+ agentId: LOCAL_PARKED_HANDLE.identity.id,+ });+ installContext(session);+ const writes: Uint8Array[] = [];++ const result = await dispatchRuntimeActionsStep({+ parentContinuationToken: "turn-inbox",+ parentWritable: createWritable(writes),+ serializedContext: {},+ sessionState: BASE_STATE,+ });++ expect(result.results).toEqual([]);+ expect(mocks.dispatchSession).toHaveBeenCalledWith({+ command: {+ caller: {+ callId: "call-1",+ replyTo: { kind: "hook", token: "turn-inbox" },+ subagentName: "research",+ },+ kind: "send",+ payload: {+ message: "continue with raw input",+ outputSchema: undefined,+ },+ },+ sessionId: CHILD_SESSION_ID,+ });+ expect(getAgentHandleStore(readResultSessionState(result, session))).toEqual({+ handles: [+ {+ address: LOCAL_PARKED_HANDLE.address,+ identity: LOCAL_PARKED_HANDLE.identity,+ operation: {+ callId: "call-1",+ id: continueOperationId,+ kind: "continue",+ parentTurnId: "turn-1",+ previousStatus: "initial result",+ },+ phase: "running",+ },+ ],+ });+ expect(writes).toHaveLength(1);+ });++ it.each([+ {+ handle: undefined,+ agentId: "ag_research:missing",+ code: "AGENT_UNKNOWN",+ title: "unknown",+ },+ {+ handle: {+ ...LOCAL_PARKED_HANDLE,+ identity: { ...LOCAL_PARKED_HANDLE.identity, name: "writer" },+ },+ agentId: LOCAL_PARKED_HANDLE.identity.id,+ code: "AGENT_MISMATCH",+ title: "mismatched",+ },+ {+ handle: {+ address: LOCAL_PARKED_HANDLE.address,+ identity: LOCAL_PARKED_HANDLE.identity,+ operation: {+ callId: "call-other",+ id: "op-other",+ kind: "start",+ parentTurnId: "turn-0",+ },+ phase: "running",+ } satisfies AgentHandle,+ agentId: LOCAL_PARKED_HANDLE.identity.id,+ code: "AGENT_BUSY",+ title: "busy",+ },+ ])("returns $code for a $title agent", async ({ handle, agentId, code }) => {+ const session = createPendingSession({ handle, agentId });+ installContext(session);++ const result = await dispatchRuntimeActionsStep({+ parentContinuationToken: "turn-inbox",+ parentWritable: createWritable(),+ serializedContext: {},+ sessionState: BASE_STATE,+ });++ expect(result.results).toEqual([+ expect.objectContaining({+ isError: true,+ output: expect.objectContaining({ code }),+ }),+ ]);+ expect(mocks.dispatchSession).not.toHaveBeenCalled();+ expect(mocks.continueRemoteAgentSession).not.toHaveBeenCalled();+ // Addressing mistakes and busy conflicts never touch the store.+ expect(getAgentHandleStore(readResultSessionState(result, session))).toEqual(+ getAgentHandleStore(session.state),+ );+ });++ it("returns AGENT_UNREACHABLE and removes a stale local handle", async () => {+ const session = createPendingSession({+ handle: LOCAL_PARKED_HANDLE,+ agentId: LOCAL_PARKED_HANDLE.identity.id,+ });+ installContext(session);+ mocks.dispatchSession.mockResolvedValue({ status: "session_not_active" });++ const result = await dispatchRuntimeActionsStep({+ parentContinuationToken: "turn-inbox",+ parentWritable: createWritable(),+ serializedContext: {},+ sessionState: BASE_STATE,+ });++ expect(result.results[0]).toMatchObject({+ isError: true,+ output: { code: "AGENT_UNREACHABLE" },+ });+ expect(getAgentHandleStore(result.sessionState.snapshot?.session.state)).toEqual({+ handles: [],+ });+ });++ it("continues a stored remote handle and maps a permanent failure to AGENT_UNREACHABLE", async () => {+ const session = createPendingSession({+ handle: REMOTE_PARKED_HANDLE,+ agentId: REMOTE_PARKED_HANDLE.identity.id,+ });+ installContext(session, {+ definition: REMOTE_REGISTRY_DEFINITION,+ nodeId: REMOTE_PARKED_HANDLE.identity.nodeId,+ });+ mocks.continueRemoteAgentSession.mockRejectedValue(+ new RemoteAgentContinueRequestError(+ "continue-session request failed permanently with HTTP 404.",+ { retryable: false },+ ),+ );++ const result = await dispatchRuntimeActionsStep({+ parentContinuationToken: "turn-inbox",+ parentWritable: createWritable(),+ serializedContext: {},+ sessionState: BASE_STATE,+ });++ expect(mocks.continueRemoteAgentSession).toHaveBeenCalledWith(+ expect.objectContaining({+ continuationToken: REMOTE_PARKED_HANDLE.address.continuationToken,+ message: "continue with raw input",+ remote: expect.objectContaining({+ nodeId: REMOTE_PARKED_HANDLE.identity.nodeId,+ url: "https://remote.example.com",+ }),+ sessionId: REMOTE_PARKED_HANDLE.address.sessionId,+ }),+ );+ expect(result.results[0]).toMatchObject({+ isError: true,+ output: { code: "AGENT_UNREACHABLE" },+ });+ expect(getAgentHandleStore(result.sessionState.snapshot?.session.state)).toEqual({+ handles: [],+ });+ });++ it("surfaces a transient remote continue failure without retrying and restores the parked handle", async () => {+ const session = createPendingSession({+ handle: REMOTE_PARKED_HANDLE,+ agentId: REMOTE_PARKED_HANDLE.identity.id,+ });+ installContext(session, {+ definition: REMOTE_REGISTRY_DEFINITION,+ nodeId: REMOTE_PARKED_HANDLE.identity.nodeId,+ });+ mocks.continueRemoteAgentSession.mockRejectedValue(new Error("HTTP 503"));++ // A rethrow would durably replay the whole step and re-dispatch started+ // siblings, and a re-send could double-deliver a turn the callee already+ // accepted — so the failure settles as a retryable error in one attempt.+ const result = await dispatchRuntimeActionsStep({+ parentContinuationToken: "turn-inbox",+ parentWritable: createWritable(),+ serializedContext: {},+ sessionState: BASE_STATE,+ });++ expect(mocks.continueRemoteAgentSession).toHaveBeenCalledTimes(1);+ expect(result.results[0]).toMatchObject({+ isError: true,+ output: {+ code: "AGENT_UNREACHABLE",+ message: expect.stringContaining("temporarily unreachable"),+ },+ });+ // The child may still be alive: the handle is restored to parked with+ // its pre-delivery status so the model can retry the same agentId.+ expect(getAgentHandleStore(readResultSessionState(result, session))).toEqual({+ handles: [REMOTE_PARKED_HANDLE],+ });+ });++ it("forfeits a remote handle whose agent node is gone from the registry", async () => {+ const session = createPendingSession({+ handle: REMOTE_PARKED_HANDLE,+ agentId: REMOTE_PARKED_HANDLE.identity.id,+ });+ // No remote registry entry installed: resolution fails before delivery.+ installContext(session);++ const result = await dispatchRuntimeActionsStep({+ parentContinuationToken: "turn-inbox",+ parentWritable: createWritable(),+ serializedContext: {},+ sessionState: BASE_STATE,+ });++ expect(mocks.continueRemoteAgentSession).not.toHaveBeenCalled();+ expect(result.results[0]).toMatchObject({+ isError: true,+ output: {+ code: "AGENT_UNREACHABLE",+ message: expect.stringContaining("no longer reachable"),+ },+ });+ expect(getAgentHandleStore(readResultSessionState(result, session))).toEqual({+ handles: [],+ });+ });+});+/*** The step returns the input state unchanged when the session object is* untouched; otherwise the mocked `createDurableSessionState` carries the@@ -337,6 +650,28 @@ function createStartSession(input: { readonly kind: "local" | "remote" }): Harne});}+function createPendingSession(input: {+ readonly handle?: AgentHandle;+ readonly agentId: string;+}): HarnessSession {+ return setPendingRuntimeActionBatch({+ actions: [+ {+ callId: "call-1",+ description: "Research",+ input: { agentId: input.agentId, message: "continue with raw input" },+ kind: "subagent-call",+ name: "research",+ nodeId: "subagents/research",+ subagentName: "research",+ },+ ],+ event: { sequence: 1, stepIndex: 2, turnId: "turn-1" },+ responseMessages: [],+ session: createBaseSession(input.handle),+ });+}+function installContext(session: HarnessSession,remote?: { readonly definition: unknown; readonly nodeId: string },diff --git a/packages/eve/src/execution/dispatch-runtime-actions-step.ts b/packages/eve/src/execution/dispatch-runtime-actions-step.tsindex 03d3b26e7..cf89a57b9 100644--- a/packages/eve/src/execution/dispatch-runtime-actions-step.ts+++ b/packages/eve/src/execution/dispatch-runtime-actions-step.ts@@ -1,12 +1,13 @@/**- * Starts every pending runtime action for the parked parent session.+ * Starts or continues every pending runtime action for the parked parent+ * session.*- * The batch is classified into a dispatch plan first (reject / start), then- * each entry dispatches and emits one parent `subagent.called` control-plane- * event through a single tail. Every start commits an agent handle- * (`starting`) before its side effect and confirms it (`running`) once the- * child reports coordinates, so the returned snapshot-bearing state owns- * every child it may have created.+ * The batch is classified into a dispatch plan first (reject / resume /+ * start), then each entry dispatches and emits one+ * parent `subagent.called` control-plane event through a single tail.+ * Every start commits an agent handle (`starting`) before its side effect+ * and confirms it (`running`) once the child reports coordinates, so the+ * returned snapshot-bearing state owns every child it may have created.*/import { buildAdapterContext } from "#channel/adapter-context.js";@@ -23,15 +24,16 @@ import {type CompiledBundle,} from "#runtime/sessions/runtime-context-keys.js";import { deserializeContext } from "#context/serialize.js";-import type { DispatchOutcome, RuntimeSession } from "#execution/agent-handle-dispatch.js";-import { REMOTE_AGENT_START_FAILED, SUBAGENT_START_FAILED } from "#harness/agent-handle-errors.js";-import { deriveAgentOperationId } from "#harness/handles/operation-id.js";import {- deriveAgentId,- getAgentHandleStore,- type AgentIdentity,- type StartOperation,-} from "#harness/handles/store.js";+ dispatchToAgentHandle,+ isAgentHandleAction,+ type DispatchOutcome,+ type RuntimeAgentHandleAction,+ type RuntimeSession,+} from "#execution/agent-handle-dispatch.js";+import { createAgentContinuationBundle } from "#execution/agent-continuation-bundle.js";+import { SUBAGENT_START_FAILED } from "#harness/agent-handle-errors.js";+import { getAgentHandleStore } from "#harness/handles/store.js";import {confirmAgentStarted,prepareAgentStart,@@ -59,6 +61,13 @@ import {resolveRemoteAgentForAction,startRemoteAgentSession,} from "#execution/remote-agent-dispatch.js";+import {+ createRecursiveAgentRootOnlyResult,+ createRemoteAgentStartFailureResult,+ createUnavailableDynamicSubagentResult,+ getSubagentName,+} from "#execution/dispatch-action-failures.js";+import { mintStartOperation } from "#execution/dispatch-start-operation.js";import { hydrateDurableSession } from "#execution/session.js";import { buildSubagentRunInput, type SubagentInputSource } from "#execution/subagent-tool.js";import { createWorkflowRuntime, workflowEntryReference } from "#execution/workflow-runtime.js";@@ -86,6 +95,12 @@ type DynamicRemoteAgentConfig = NonNullable<>;type DispatchPlanEntry =+ | {+ readonly kind: "resume";+ readonly action: RuntimeAgentHandleAction;+ readonly agentId: string;+ readonly dynamicRemoteAgent?: DynamicRemoteAgentConfig;+ }| { readonly kind: "reject"; readonly result: RuntimeSubagentDispatchFailure }| { readonly kind: "start"; readonly target: DispatchStartTarget };@@ -142,6 +157,8 @@ export async function dispatchRuntimeActionsStep(input: {// Read here, not in the child: trace state is scoped to one session's// context, so this is the last place the parent's window is visible.const parentTraceContext = readSessionTraceContext(input.serializedContext, session.sessionId);+ const persistentSessions =+ bundle.resolvedAgent.config.experimental?.subagentPersistentSessions === true;// A corrupt handle store throws; surface that before anything dispatches.// A mid-loop throw after a sibling started would durably replay the whole// batch and re-dispatch that sibling.@@ -152,8 +169,9 @@ export async function dispatchRuntimeActionsStep(input: {const writer = input.parentWritable.getWriter();// Split the parent's remaining token quota across the batch's freshly// started local subagents, the children that actually receive an enforced- // cap. Remote agents run on their own deployment under their own limits,- // so they do not dilute the local shares.+ // cap. Continuations already run under their own budget, and remote agents+ // run on their own deployment under their own limits, so neither dilutes+ // the local shares.const fanoutSize = plan.filter((entry) => entry.kind === "start" && entry.target.kind === "local",).length;@@ -168,21 +186,41 @@ export async function dispatchRuntimeActionsStep(input: {continue;}- const outcome: DispatchOutcome = await startSubagent({- auth,- batchEvent: batch.event,- bundle,- callbackBaseUrl: input.callbackBaseUrl,- capabilities,- channelMetadata,- currentSession: nextSession,- fanoutSize,- initiatorAuth,- parentContinuationToken: input.parentContinuationToken,- parentTraceContext,- session,- target: entry.target,- });+ let outcome: DispatchOutcome;+ switch (entry.kind) {+ case "resume":+ outcome = await dispatchToAgentHandle({+ action: entry.action,+ agentId: entry.agentId,+ bundle: createAgentContinuationBundle({+ action: entry.action,+ bundle,+ dynamicRemoteAgent: entry.dynamicRemoteAgent,+ }),+ currentSession: nextSession,+ parentToken: input.parentContinuationToken ?? session.continuationToken,+ parentTurnId: batch.event.turnId,+ });+ break;+ case "start":+ outcome = await startSubagent({+ auth,+ batchEvent: batch.event,+ bundle,+ callbackBaseUrl: input.callbackBaseUrl,+ capabilities,+ channelMetadata,+ currentSession: nextSession,+ fanoutSize,+ initiatorAuth,+ parentContinuationToken: input.parentContinuationToken,+ parentTraceContext,+ persistentSessions,+ session,+ target: entry.target,+ });+ break;+ }nextSession = outcome.session;if (outcome.kind === "error") {@@ -256,6 +294,23 @@ function planDispatch(input: {const dynamicSubagentSelection = isDynamicSubagent? getDynamicSubagentSelection(input.ctx, action.nodeId): undefined;+ const agentId = typeof action.input.agentId === "string" ? action.input.agentId : undefined;+ // Resume classification runs before the recursion guard: an agentId+ // continuation resumes an already-adopted child rather than starting a+ // new one, and a non-root session can never own an `agent`-tool handle,+ // so an agentId-carrying recursive call falls through to AGENT_UNKNOWN.+ if (agentId !== undefined && isAgentHandleAction(action)) {+ return {+ action,+ agentId,+ dynamicRemoteAgent:+ action.kind === "remote-agent-call" && dynamicSubagentSelection?.kind === "remote"+ ? dynamicSubagentSelection.remoteAgent+ : undefined,+ kind: "resume",+ };+ }+if (isDynamicSubagent &&(dynamicSubagentSelection === undefined ||@@ -335,6 +390,7 @@ async function startSubagent(input: {readonly initiatorAuth: Parameters<typeof buildSubagentRunInput>[0]["initiatorAuth"];readonly parentContinuationToken: string | undefined;readonly parentTraceContext: Parameters<typeof buildSubagentRunInput>[0]["parentTraceContext"];+ readonly persistentSessions: boolean;readonly session: RuntimeSession;readonly target: DispatchStartTarget;}): Promise<DispatchOutcome> {@@ -353,6 +409,7 @@ async function startSubagent(input: {initiatorAuth: input.initiatorAuth,parentContinuationToken: input.parentContinuationToken,parentTraceContext: input.parentTraceContext,+ persistentSessions: input.persistentSessions,session: input.session,source: input.target.source,});@@ -367,6 +424,7 @@ async function startSubagent(input: {dynamicRemoteAgent: input.target.dynamicRemoteAgent,initiatorAuth: input.initiatorAuth,parentContinuationToken: input.parentContinuationToken,+ persistentSessions: input.persistentSessions,session: input.session,});default: {@@ -376,38 +434,6 @@ async function startSubagent(input: {}}-/**- * Mints the deterministic start operation and identity for one dispatch.- * All inputs are parent-controlled, so both exist before the child does- * and a durable replay of the step re-derives the same ownership record.- */-function mintStartOperation(input: {- readonly callId: string;- readonly name: string;- readonly nodeId: string;- readonly parentSessionId: string;- readonly parentTurnId: string;-}): { readonly identity: AgentIdentity; readonly operation: StartOperation } {- const operationId = deriveAgentOperationId({- callId: input.callId,- parentSessionId: input.parentSessionId,- parentTurnId: input.parentTurnId,- });- return {- identity: {- id: deriveAgentId(input.name, operationId),- name: input.name,- nodeId: input.nodeId,- },- operation: {- callId: input.callId,- id: operationId,- kind: "start",- parentTurnId: input.parentTurnId,- },- };-}-async function startLocalSubagent(input: {readonly action: RuntimeSubagentCallActionRequest;readonly auth: Parameters<typeof buildSubagentRunInput>[0]["auth"];@@ -421,6 +447,7 @@ async function startLocalSubagent(input: {readonly initiatorAuth: Parameters<typeof buildSubagentRunInput>[0]["initiatorAuth"];readonly parentContinuationToken: string | undefined;readonly parentTraceContext: Parameters<typeof buildSubagentRunInput>[0]["parentTraceContext"];+ readonly persistentSessions: boolean;readonly session: RuntimeSession;readonly source: SubagentInputSource;}): Promise<DispatchOutcome> {@@ -440,6 +467,7 @@ async function startLocalSubagent(input: {initiatorAuth: input.initiatorAuth,parentContinuationToken: input.parentContinuationToken,parentTraceContext: input.parentTraceContext,+ persistentSessions: input.persistentSessions,session: input.session,source,});@@ -521,6 +549,7 @@ async function startRemoteSubagent(input: {readonly dynamicRemoteAgent?: DynamicRemoteAgentConfig;readonly initiatorAuth: Parameters<typeof startRemoteAgentSession>[0]["initiatorAuth"];readonly parentContinuationToken: string | undefined;+ readonly persistentSessions: boolean;readonly session: RuntimeSession;}): Promise<DispatchOutcome> {const { action } = input;@@ -573,6 +602,7 @@ async function startRemoteSubagent(input: {callbackBaseUrl,callbackToken: input.parentContinuationToken,initiatorAuth: input.initiatorAuth,+ persistentSessions: input.persistentSessions,remote: resolvedRemote,session: input.session,});@@ -613,62 +643,6 @@ async function startRemoteSubagent(input: {}}-function createUnavailableDynamicSubagentResult(- action: RuntimeSubagentCallActionRequest | RuntimeRemoteAgentCallActionRequest,-): RuntimeSubagentDispatchFailure {- const subagentName = getSubagentName(action);- return {- callId: action.callId,- isError: true,- kind: "subagent-result",- origin: "dispatch",- output: {- code: "SUBAGENT_UNAVAILABLE",- message: `Subagent "${subagentName}" is not available in the current session context.`,- },- subagentName,- };-}--function getSubagentName(- action: RuntimeSubagentCallActionRequest | RuntimeRemoteAgentCallActionRequest,-): string {- return action.kind === "remote-agent-call" ? action.remoteAgentName : action.subagentName;-}--function createRemoteAgentStartFailureResult(input: {- readonly action: RuntimeRemoteAgentCallActionRequest;- readonly error: unknown;-}): RuntimeSubagentDispatchFailure {- return {- callId: input.action.callId,- isError: true,- kind: "subagent-result",- origin: "dispatch",- output: {- code: REMOTE_AGENT_START_FAILED,- message: toErrorMessage(input.error),- },- subagentName: input.action.remoteAgentName,- };-}--function createRecursiveAgentRootOnlyResult(- action: RuntimeSubagentCallActionRequest,-): RuntimeSubagentDispatchFailure {- return {- callId: action.callId,- isError: true,- kind: "subagent-result",- origin: "dispatch",- output: {- code: "RECURSIVE_AGENT_ROOT_ONLY",- message: 'The built-in "agent" tool is only available to the root session.',- },- subagentName: action.subagentName,- };-}-function isRecursiveAgentAction(action: RuntimeActionRequest,subagentsByNodeId: ReadonlyMap<string, unknown>,diff --git a/packages/eve/src/execution/dispatch-start-operation.ts b/packages/eve/src/execution/dispatch-start-operation.tsnew file mode 100644index 000000000..a8149e0b8--- /dev/null+++ b/packages/eve/src/execution/dispatch-start-operation.ts@@ -0,0 +1,33 @@+import { deriveAgentOperationId } from "#harness/handles/operation-id.js";+import { deriveAgentId, type AgentIdentity, type StartOperation } from "#harness/handles/store.js";++/**+ * Mints deterministic parent-controlled ownership data before the child exists,+ * so durable step replays derive the same handle record.+ */+export function mintStartOperation(input: {+ readonly callId: string;+ readonly name: string;+ readonly nodeId: string;+ readonly parentSessionId: string;+ readonly parentTurnId: string;+}): { readonly identity: AgentIdentity; readonly operation: StartOperation } {+ const operationId = deriveAgentOperationId({+ callId: input.callId,+ parentSessionId: input.parentSessionId,+ parentTurnId: input.parentTurnId,+ });+ return {+ identity: {+ id: deriveAgentId(input.name, operationId),+ name: input.name,+ nodeId: input.nodeId,+ },+ operation: {+ callId: input.callId,+ id: operationId,+ kind: "start",+ parentTurnId: input.parentTurnId,+ },+ };+}diff --git a/packages/eve/src/execution/multi-agent-callback-routing.scenario.test.ts b/packages/eve/src/execution/multi-agent-callback-routing.scenario.test.tsindex e80a82bdd..ec99f874b 100644--- a/packages/eve/src/execution/multi-agent-callback-routing.scenario.test.ts+++ b/packages/eve/src/execution/multi-agent-callback-routing.scenario.test.ts@@ -9,6 +9,10 @@ import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitestimport { parseSessionCallback } from "#channel/session-callback.js";import { ContextContainer, contextStorage } from "#context/container.js";import { SessionCallbackKey, SessionIdKey } from "#context/keys.js";+import {+ notifyTurnCallerStep,+ resolveInitialTurnCallerStep,+} from "#execution/delegated-parent-notification.js";import { fireSessionCallbackStep } from "#execution/session-callback-step.js";import { startRemoteAgentSession } from "#execution/remote-agent-dispatch.js";import { resolveWorkflowCallbackBaseUrl } from "#execution/workflow-callback-url.js";@@ -35,8 +39,8 @@ import type { HarnessSession } from "#harness/types.js";* remote-subagent session callback (`startRemoteAgentSession`) and the* connection hook URL (`getHookUrl`);* 3. the remote side validates the callback metadata with the real- * create-session parser (`parseSessionCallback`) and posts the terminal- * result with the real durable step (`fireSessionCallbackStep`);+ * create-session parser (`parseSessionCallback`) and posts the settled turn+ * with the real durable step (`notifyTurnCallerStep`);* 4. each parent service only serves its own prefix-stripped `/eve/v1/*`* callback routes — anything else 404s, matching production.*@@ -305,7 +309,7 @@ describe("multi-agent callback routing", () => {}for (const agent of DEPLOYMENT_AGENTS) {- it(`delivers the remote-subagent session callback for ${agent.name} through its public mount`, async () => {+ it(`delivers the remote-subagent settled turn for ${agent.name} through its public mount`, async () => {stubAgentRuntimeEnvironment(agent.publicRoutePrefix);const { callback, remoteSessionId } = await mintRemoteAgentCallback(agent.name);@@ -320,21 +324,22 @@ describe("multi-agent callback routing", () => {// the prefixed URL must parse, or the remote rejects with HTTP 400.expect(parseSessionCallback(callback)).toMatchObject({ ok: true });- // Remote-side terminal POST (the step that failed with HTTP 404 in- // production) must reach the parent service through the deployment- // router and succeed.+ // The remote conversation's first settled turn must reach the parent+ // service through the deployment router and succeed.+ const serializedContext = {+ [SessionCallbackKey.name]: {+ callId: `call-${agent.name}`,+ subagentName: "research",+ ...callback,+ },+ };+ const caller = await resolveInitialTurnCallerStep({ serializedContext });await expect(- fireSessionCallbackStep({- output: "report done",- serializedContext: {- [SessionIdKey.name]: "remote-session-1",- [SessionCallbackKey.name]: {- callId: `call-${agent.name}`,- subagentName: "research",- ...callback,- },- },- status: "completed",+ notifyTurnCallerStep({+ caller,+ lifecycle: "parked",+ sessionId: "remote-session-1",+ settled: { output: "report done" },}),).resolves.toBeUndefined();diff --git a/packages/eve/src/execution/next-driver-action.ts b/packages/eve/src/execution/next-driver-action.tsindex 9c2f84298..c7f48bf22 100644--- a/packages/eve/src/execution/next-driver-action.ts+++ b/packages/eve/src/execution/next-driver-action.ts@@ -12,6 +12,7 @@* strips unknown fields.*/import type { DurableSessionState } from "#execution/durable-session-store.js";+import type { SettledTurn } from "#harness/types.js";import type { TokenUsage } from "#shared/token-usage.js";/** Discriminated union the driver workflow body dispatches on. */@@ -24,6 +25,12 @@ export type NextDriverAction =readonly serializedContext: Record<string, unknown>;/** Session-total token usage spent by the completed session. */readonly usage?: TokenUsage;+ /**+ * Usage the final turn added beyond what earlier settled turns already+ * reported; forwarded through the same pinned-driver-safe+ * optional-field pattern as `cancelled`.+ */+ readonly usageDelta?: TokenUsage;}| {readonly kind: "park";@@ -37,6 +44,11 @@ export type NextDriverAction =* working.*/readonly cancelled?: true;+ /**+ * Settled user-facing answer forwarded through the same pinned-driver-safe+ * optional-field pattern as `cancelled`.+ */+ readonly settled?: SettledTurn;}| {readonly kind: "dispatch-runtime-actions";diff --git a/packages/eve/src/execution/parked-delivery-wait.ts b/packages/eve/src/execution/parked-delivery-wait.tsnew file mode 100644index 000000000..84c0fb1a2--- /dev/null+++ b/packages/eve/src/execution/parked-delivery-wait.ts@@ -0,0 +1,161 @@+import type { DeliverHookPayload, DeliverPayload, SessionCommand } from "#channel/types.js";+import type { DurableSessionState } from "#execution/durable-session-store.js";+import { routeDeliverToChildren } from "#execution/route-child-delivery.js";+import type { SessionCommandInbox } from "#execution/session-command-inbox.js";+import { coalesceDeliveries } from "#harness/messages.js";++type NextSessionAction =+ | { readonly kind: "clear" }+ | { readonly kind: "compact" }+ | { readonly kind: "expired" }+ | { readonly kind: "reset" }+ | {+ readonly delivery: DeliverHookPayload | null;+ readonly kind: "delivery";+ };++/** What the parked driver should do with the next session activity. */+export type NextTurnInstruction =+ | { readonly kind: "clear" }+ | { readonly kind: "compact" }+ | { readonly kind: "expired" }+ | { readonly kind: "reset" }+ | { readonly kind: "closed" }+ | { readonly kind: "cancel-turn" }+ | {+ readonly kind: "turn";+ readonly deliver: DeliverHookPayload;+ readonly remainder: DeliverPayload;+ };++/**+ * Awaits the next delivery that requires driver action while the session+ * is parked. Deliveries fully routed to a descendant leave the parent with+ * no turn to run, so this keeps waiting until a delivery produces a parent+ * turn, a cancellation, expiry, or hook closure. The wait is unbounded by+ * design: a parked session lives until something addresses it.+ */+export async function nextTurnDelivery(input: {+ readonly bufferedDeliveries: DeliverHookPayload[];+ readonly bufferedSessionControls: Array<"clear" | "compact" | "expired" | "reset">;+ readonly commandInbox: SessionCommandInbox;+ readonly driverWritable: WritableStream<Uint8Array>;+ readonly sessionState: DurableSessionState;+}): Promise<NextTurnInstruction> {+ while (true) {+ const nextAction = await waitForNextSessionAction({+ bufferedDeliveries: input.bufferedDeliveries,+ bufferedSessionControls: input.bufferedSessionControls,+ commandInbox: input.commandInbox,+ });++ if (nextAction.kind !== "delivery") {+ return { kind: nextAction.kind };+ }++ const deliver = nextAction.delivery;+ if (deliver === null) {+ return { kind: "closed" };+ }++ const routed = await routeDeliverToChildren({+ auth: deliver.auth,+ parentWritable: input.driverWritable,+ payloads: deliver.payloads,+ sessionState: input.sessionState,+ });++ if (routed.kind === "cancel-turn") {+ return { kind: "cancel-turn" };+ }++ if (routed.remainder === undefined) {+ // Fully routed to a descendant; keep waiting.+ continue;+ }++ return { deliver, kind: "turn", remainder: routed.remainder };+ }+}++async function waitForNextSessionAction(input: {+ readonly bufferedDeliveries: DeliverHookPayload[];+ readonly bufferedSessionControls: Array<"clear" | "compact" | "expired" | "reset">;+ readonly commandInbox: SessionCommandInbox;+}): Promise<NextSessionAction> {+ const pendingSessionControl = input.bufferedSessionControls.shift();+ if (pendingSessionControl !== undefined) {+ return { kind: pendingSessionControl };+ }++ if (input.bufferedDeliveries.length > 0) {+ return {+ delivery: takeBufferedTurnDelivery(input.bufferedDeliveries),+ kind: "delivery",+ };+ }++ while (true) {+ const first = await input.commandInbox.next();+ input.commandInbox.consumeNext();++ if (first.done) {+ return { delivery: null, kind: "delivery" };+ }++ if (first.value.kind === "session-timeout") {+ return { kind: "expired" };+ }++ if (+ first.value.kind === "clear" ||+ first.value.kind === "compact" ||+ first.value.kind === "reset"+ ) {+ return { kind: first.value.kind };+ }++ if (first.value.kind === "cancel") {+ continue;+ }++ return { delivery: commandToDelivery(first.value), kind: "delivery" };+ }+}++function commandToDelivery(+ command: Extract<SessionCommand, { readonly kind: "send" }>,+): DeliverHookPayload {+ return {+ auth: command.auth,+ caller: command.caller,+ kind: "deliver",+ payloads: [command.payload],+ requestId: command.requestId,+ };+}++function takeBufferedTurnDelivery(bufferedDeliveries: DeliverHookPayload[]): DeliverHookPayload {+ const first = bufferedDeliveries.shift();+ if (first === undefined) {+ throw new Error("Cannot take a turn delivery from an empty buffer.");+ }++ const turnDeliveries = [first];+ let caller = first.caller;+ while (bufferedDeliveries.length > 0) {+ const next = bufferedDeliveries[0];+ if (next === undefined || (caller !== undefined && next.caller !== undefined)) {+ break;+ }++ const delivery = bufferedDeliveries.shift();+ if (delivery === undefined) {+ throw new Error("Buffered turn delivery disappeared while partitioning.");+ }+ turnDeliveries.push(delivery);+ caller ??= delivery.caller;+ }++ return coalesceDeliveries(turnDeliveries);+}diff --git a/packages/eve/src/execution/remote-agent-dispatch.test.ts b/packages/eve/src/execution/remote-agent-dispatch.test.tsindex 2a8004cbf..588049471 100644--- a/packages/eve/src/execution/remote-agent-dispatch.test.ts+++ b/packages/eve/src/execution/remote-agent-dispatch.test.ts@@ -3,7 +3,9 @@ import { afterEach, describe, expect, it, vi } from "vitest";import type { SessionAuthContext } from "#channel/types.js";import {cancelRemoteAgentTurn,+ continueRemoteAgentSession,isRetryableRemoteAgentCancelError,+ isRetryableRemoteAgentContinueError,resolveRemoteAgentForAction,startRemoteAgentSession,} from "#execution/remote-agent-dispatch.js";@@ -538,6 +540,92 @@ describe("startRemoteAgentSession — forwarded principal", () => {});});+describe("continueRemoteAgentSession", () => {+ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it("posts raw continuation input with callback metadata and fresh auth headers", async () => {+ const fetchMock = vi.fn().mockResolvedValue(new Response(null, { status: 200 }));+ vi.stubGlobal("fetch", fetchMock);++ await continueRemoteAgentSession({+ callback: {+ callId: "call-next",+ subagentName: "research",+ token: "parent-inbox",+ url: "https://caller.example.com/eve/v1/callback/parent-inbox",+ },+ continuationToken: "remote-token",+ message: "follow up",+ outputSchema: { type: "object" },+ remote: createRemoteAgent(),+ sessionId: "remote-session",+ });++ expect(fetchMock).toHaveBeenCalledWith(+ "https://remote.example.com/eve/v1/session/remote-session",+ {+ body: JSON.stringify({+ callback: {+ callId: "call-next",+ subagentName: "research",+ token: "parent-inbox",+ url: "https://caller.example.com/eve/v1/callback/parent-inbox",+ },+ continuationToken: "remote-token",+ message: "follow up",+ outputSchema: { type: "object" },+ }),+ headers: {+ authorization: "Bearer remote-token",+ "content-type": "application/json",+ "x-static": "yes",+ },+ method: "POST",+ },+ );+ });++ it("classifies only missing-session continue failures as permanent", async () => {+ const fetchMock = vi+ .fn()+ .mockResolvedValueOnce(new Response(null, { status: 503 }))+ .mockResolvedValueOnce(+ new Response(JSON.stringify({ code: "SESSION_NOT_RESUMABLE" }), { status: 410 }),+ )+ .mockResolvedValueOnce(new Response(null, { status: 404 }));+ vi.stubGlobal("fetch", fetchMock);++ const continueInput = () => ({+ callback: {+ callId: "call-next",+ subagentName: "research",+ token: "parent-inbox",+ url: "https://caller.example.com/eve/v1/callback/parent-inbox",+ },+ continuationToken: "remote-token",+ message: "follow up",+ remote: createRemoteAgent(),+ sessionId: "remote-session",+ });+ const transient = await continueRemoteAgentSession(continueInput()).catch(+ (error: unknown) => error,+ );+ const notResumable = await continueRemoteAgentSession(continueInput()).catch(+ (error: unknown) => error,+ );+ const missing = await continueRemoteAgentSession(continueInput()).catch(+ (error: unknown) => error,+ );++ expect(isRetryableRemoteAgentContinueError(transient)).toBe(true);+ expect(isRetryableRemoteAgentContinueError(notResumable)).toBe(false);+ expect(isRetryableRemoteAgentContinueError(missing)).toBe(false);+ expect(isRetryableRemoteAgentContinueError(new TypeError("network unavailable"))).toBe(true);+ });+});+describe("cancelRemoteAgentTurn", () => {afterEach(() => {vi.unstubAllGlobals();diff --git a/packages/eve/src/execution/remote-agent-dispatch.ts b/packages/eve/src/execution/remote-agent-dispatch.tsindex 8348e4d60..2152bf101 100644--- a/packages/eve/src/execution/remote-agent-dispatch.ts+++ b/packages/eve/src/execution/remote-agent-dispatch.ts@@ -1,6 +1,7 @@import { z } from "#compiled/zod/index.js";import { EVE_SESSION_ID_HEADER } from "#protocol/message.js";import { CancelTurnResponseSchema } from "#protocol/cancel-turn.js";+import { AgentHandleError } from "#protocol/agent-handle-error.js";import { createEveCallbackRoutePath, createEveCancelTurnRoutePath } from "#protocol/routes.js";import type { CancelTurnResult, SessionAuthContext } from "#channel/types.js";import type { ForwardedPrincipal } from "#channel/forwarded-principal.js";@@ -16,6 +17,7 @@ import type { RuntimeSubagentRegistry } from "#runtime/subagents/registry.js";import type { DynamicRemoteAgentConfig } from "#runtime/subagents/dynamic-remote-agent-config.js";import type { ResolvedRuntimeRemoteAgentNode } from "#runtime/types.js";import { expectFunction, expectObjectRecord } from "#internal/authored-module.js";+import type { JsonObject } from "#shared/json.js";const CreateSessionResponseSchema = z.object({// Older eve deployments do not return a continuationToken. Their children@@ -48,6 +50,12 @@ export async function startRemoteAgentSession(input: {readonly callbackToken?: string;/** The root initiator's principal, forwarded alongside {@link auth}. */readonly initiatorAuth?: SessionAuthContext | null;+ /**+ * Whether the dispatching agent opted into+ * `experimental.subagentPersistentSessions`. Persistent remote children run+ * in conversation mode so their sessions accept follow-up messages.+ */+ readonly persistentSessions?: boolean;readonly remote: ResolvedRuntimeRemoteAgentNode;readonly session: HarnessSession;}): Promise<RemoteAgentSessionCoordinates> {@@ -84,9 +92,7 @@ export async function startRemoteAgentSession(input: {),},message: formatRemoteAgentCallInputMessage({ action: input.action, remote: input.remote }),- // Remote children run one turn per delivery in task mode; follow-ups- // arrive as continuations against the child's agent handle.- mode: "task",+ mode: input.persistentSessions === true ? "conversation" : "task",outputSchema:normalizeRequestedOutputSchema(input.action.input.outputSchema) ?? input.remote.outputSchema,};@@ -139,6 +145,89 @@ export async function startRemoteAgentSession(input: {: { continuationToken: parsed.data.continuationToken, sessionId };}+/** Continues one remote-agent session via agentId. */+export async function continueRemoteAgentSession(input: {+ readonly callback: {+ readonly callId: string;+ readonly subagentName: string;+ readonly token: string;+ readonly url: string;+ };+ readonly continuationToken: string;+ readonly message: string;+ readonly outputSchema?: JsonObject;+ readonly remote: ResolvedRuntimeRemoteAgentNode;+ readonly sessionId: string;+}): Promise<void> {+ const response = await fetch(createRemoteAgentContinueUrl(input.remote, input.sessionId), {+ body: JSON.stringify({+ callback: input.callback,+ continuationToken: input.continuationToken,+ message: input.message,+ outputSchema: input.outputSchema,+ }),+ headers: {+ "content-type": "application/json",+ ...(await resolveRemoteAgentRequestHeaders(input.remote)),+ },+ method: "POST",+ });++ if (!response.ok) {+ const responseCode = await readRemoteAgentErrorCode(response);+ const permanent =+ response.status === 404 || responseCode === AgentHandleError.SessionNotResumable.code;+ throw new RemoteAgentContinueRequestError(+ `Remote agent "${input.remote.name}" continue-session request failed${+ permanent ? " permanently" : ""+ } with HTTP ${response.status}.`,+ { retryable: !permanent },+ );+ }+}++/**+ * Failure of a continue-session request, classified at the HTTP boundary.+ * Exported so tests can exercise {@link isRetryableRemoteAgentContinueError}+ * with real instances instead of re-encoding the classification.+ */+export class RemoteAgentContinueRequestError extends Error {+ readonly retryable: boolean;++ constructor(message: string, options: { readonly retryable: boolean }) {+ super(message);+ this.name = "RemoteAgentContinueRequestError";+ this.retryable = options.retryable;+ }+}++/**+ * Returns true when a failed continue request may be retried. Only a+ * session that no longer exists (404 / SESSION_NOT_RESUMABLE) is permanent;+ * transient HTTP and network failures stay retryable so the dispatch step+ * keeps the agent handle and surfaces a retryable error instead of+ * discarding it — the model decides whether to try the same agentId again+ * (the step itself never re-sends: the callee may have accepted a delivery+ * whose response was lost).+ */+export function isRetryableRemoteAgentContinueError(error: unknown): boolean {+ return !(error instanceof RemoteAgentContinueRequestError) || error.retryable;+}++async function readRemoteAgentErrorCode(response: Response): Promise<string | undefined> {+ let body: unknown;+ try {+ body = await response.json();+ } catch {+ return undefined;+ }+ if (body === null || typeof body !== "object") {+ return undefined;+ }+ const code = Reflect.get(body, "code");+ return typeof code === "string" ? code : undefined;+}+function buildForwardedPrincipalField(input: {readonly auth?: SessionAuthContext | null;readonly initiatorAuth?: SessionAuthContext | null;@@ -322,6 +411,13 @@ function createRemoteAgentCancelTurnUrl(return createRemoteAgentRouteUrl(remote.url, createEveCancelTurnRoutePath(sessionId));}+function createRemoteAgentContinueUrl(+ remote: ResolvedRuntimeRemoteAgentNode,+ sessionId: string,+): string {+ return createRemoteAgentRouteUrl(remote.url, `/eve/v1/session/${encodeURIComponent(sessionId)}`);+}+function createRemoteAgentRouteUrl(baseUrl: string, routePath: string): string {return new URL(routePath.replace(/^\/+/, ""), `${trimTrailingSlash(baseUrl)}/`).toString();}diff --git a/packages/eve/src/execution/settle-cancelled-turn-step.integration.test.ts b/packages/eve/src/execution/settle-cancelled-turn-step.integration.test.tsnew file mode 100644index 000000000..ef2610cdf--- /dev/null+++ b/packages/eve/src/execution/settle-cancelled-turn-step.integration.test.ts@@ -0,0 +1,126 @@+import { describe, expect, it } from "vitest";++import { createTestRuntime } from "#internal/testing/app-harness.js";+import { createBundledRuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";+import { createDurableSessionState } from "#execution/durable-session-store.js";+import { settleCancelledTurnStep } from "#execution/settle-cancelled-turn-step.js";+import { setHarnessEmissionState } from "#harness/emission.js";+import { deriveAgentOperationId } from "#harness/handles/operation-id.js";+import {+ AGENT_HANDLES_STATE_KEY,+ deriveAgentId,+ getAgentHandleStore,+ type AgentHandle,+} from "#harness/handles/store.js";+import type { HarnessSession } from "#harness/types.js";++/**+ * The cancellation epilogue is the last write that can move a cancelled+ * child's handle: `cancelDescendantTurnsStep` only requests cancellation,+ * and the turn inbox a child settlement would resume is torn down with the+ * cancelled turn. These tests pin the persisted handle store the epilogue+ * leaves behind — a `running` handle surviving here would be permanent.+ */++const PARENT_SESSION_ID = "parent-session-cancel-handles";+const CONTINUATION_TOKEN = "http:settle-cancel-handles";++const RUNNING_OPERATION_ID = deriveAgentOperationId({+ callId: "call-1",+ parentSessionId: PARENT_SESSION_ID,+ parentTurnId: "turn-1",+});++const RUNNING_HANDLE: AgentHandle = {+ address: {+ continuationToken: "subagent:child-running",+ kind: "agent/local",+ sessionId: "child-session-running",+ },+ identity: {+ id: deriveAgentId("research", RUNNING_OPERATION_ID),+ name: "research",+ nodeId: "subagents/research",+ },+ operation: {+ callId: "call-1",+ id: RUNNING_OPERATION_ID,+ kind: "start",+ parentTurnId: "turn-1",+ },+ phase: "running",+};++const PARKED_OPERATION_ID = deriveAgentOperationId({+ callId: "call-0",+ parentSessionId: PARENT_SESSION_ID,+ parentTurnId: "turn-0",+});++const PARKED_HANDLE: AgentHandle = {+ address: {+ continuationToken: "subagent:child-parked",+ kind: "agent/local",+ sessionId: "child-session-parked",+ },+ identity: {+ id: deriveAgentId("writer", PARKED_OPERATION_ID),+ name: "writer",+ nodeId: "subagents/writer",+ },+ lastStatus: "draft ready",+ phase: "parked",+};++function createCancelledTurnSession(handles: readonly AgentHandle[]): HarnessSession {+ return setHarnessEmissionState(+ {+ agent: { modelReference: { id: "openai/gpt-5.4" }, system: "", tools: [] },+ compaction: { recentWindowSize: 10, threshold: 100_000 },+ continuationToken: CONTINUATION_TOKEN,+ history: [],+ sessionId: PARENT_SESSION_ID,+ state: { [AGENT_HANDLES_STATE_KEY]: { handles } },+ },+ { sequence: 3, sessionStarted: true, stepIndex: 1, turnId: "turn-1" },+ );+}++function buildSerializedContext(): Record<string, unknown> {+ return {+ "eve.auth": null,+ "eve.bundle": { source: createBundledRuntimeCompiledArtifactsSource() },+ "eve.channel": { kind: "http", state: {} },+ "eve.continuationToken": CONTINUATION_TOKEN,+ "eve.mode": "conversation",+ "eve.sessionId": PARENT_SESSION_ID,+ };+}++describe("settleCancelledTurnStep handle store", () => {+ it("parks abandoned running handles as cancelled and keeps parked ones", async () => {+ const runtime = createTestRuntime({ agent: { name: "settle-cancel-handles" } });++ await runtime.run(async () => {+ const result = await settleCancelledTurnStep({+ parentWritable: new WritableStream<Uint8Array>({ write() {} }),+ serializedContext: buildSerializedContext(),+ sessionState: createDurableSessionState({+ session: createCancelledTurnSession([RUNNING_HANDLE, PARKED_HANDLE]),+ }),+ });++ expect(getAgentHandleStore(result.sessionState.snapshot?.session.state)).toEqual({+ handles: [+ {+ address: RUNNING_HANDLE.address,+ identity: RUNNING_HANDLE.identity,+ lastStatus: "(cancelled)",+ phase: "parked",+ },+ PARKED_HANDLE,+ ],+ });+ });+ });+});diff --git a/packages/eve/src/execution/settle-cancelled-turn-step.ts b/packages/eve/src/execution/settle-cancelled-turn-step.tsindex 0978153d8..2c65f258b 100644--- a/packages/eve/src/execution/settle-cancelled-turn-step.ts+++ b/packages/eve/src/execution/settle-cancelled-turn-step.ts@@ -24,6 +24,7 @@ import {getProxyInputRequests,hasProxyInputRequests,} from "#harness/proxy-input-requests.js";+import { abandonRunningAgentTurns } from "#harness/handles/transitions.js";import { clearPendingRuntimeActionBatch } from "#harness/runtime-actions.js";import { createInstrumentationHandleEvent } from "#harness/instrumentation-native-events.js";import { getInstrumentationRuntime } from "#harness/instrumentation-runtime.js";@@ -126,12 +127,19 @@ export async function settleCancelledTurnStep(input: {// discarded turn state). The pre-model gate re-raises the prompt while the// violation holds, so the next delivery gets a fresh prompt instead of// queueing forever behind a stale one.+ //+ // `abandonRunningAgentTurns`: `cancelDescendantTurnsStep` already ran and+ // the cancelled turn's inbox is gone, so a child settlement can never+ // reach this store again. This is the last write that can move those+ // handles out of `running`.const cancelledSession = reconcileSessionContinuationToken(ctx,setHarnessEmissionState(clearPendingSessionLimitPrompt(clearAllProxyInputRequests(- clearPendingWorkflowInterrupt(clearPendingRuntimeActionBatch(session)),+ clearPendingWorkflowInterrupt(+ clearPendingRuntimeActionBatch(abandonRunningAgentTurns(session)),+ ),),),emissionState,diff --git a/packages/eve/src/execution/subagent-tool.test.ts b/packages/eve/src/execution/subagent-tool.test.tsindex 2f059802d..f6e95a6a2 100644--- a/packages/eve/src/execution/subagent-tool.test.ts+++ b/packages/eve/src/execution/subagent-tool.test.ts@@ -89,6 +89,7 @@ describe("buildSubagentRunInput", () => {});expect(runInput.continuationToken).toBe(childContinuationToken);expect(childContinuationToken).toMatch(/^subagent:parent-session:call-1$/);+ expect(runInput.mode).toBe("task");});it("routes parent notifications to an active turn inbox when supplied", () => {diff --git a/packages/eve/src/execution/subagent-tool.ts b/packages/eve/src/execution/subagent-tool.tsindex dc62d7cbb..bd6596c1d 100644--- a/packages/eve/src/execution/subagent-tool.ts+++ b/packages/eve/src/execution/subagent-tool.ts@@ -71,6 +71,13 @@ export function buildSubagentRunInput(input: {/** Hook token owned by the workflow currently waiting for this child. */readonly parentContinuationToken?: string;readonly parentTraceContext?: SessionTraceContext;+ /**+ * Whether the parent agent opted into+ * `experimental.subagentPersistentSessions`. Persistent children run in+ * conversation mode so their sessions survive the first answer; otherwise+ * children run as one-shot task sessions.+ */+ readonly persistentSessions?: boolean;readonly session: HarnessSession;readonly source: SubagentInputSource;}): SubagentRunInputBuild {@@ -128,10 +135,7 @@ export function buildSubagentRunInput(input: {outputSchema: requestedOutputSchema,},limits: inheritedLimits,- // Delegated children always run one turn at a time in task mode; a- // parked persistent child is continued through its agent handle, not by- // holding a conversation session open.- mode: "task",+ mode: input.persistentSessions === true ? "conversation" : "task",parent: {callId: action.callId,rootSessionId,diff --git a/packages/eve/src/execution/subagent-usage-span.test.ts b/packages/eve/src/execution/subagent-usage-span.test.tsindex 936a63051..9c5f2e7ed 100644--- a/packages/eve/src/execution/subagent-usage-span.test.ts+++ b/packages/eve/src/execution/subagent-usage-span.test.ts@@ -28,6 +28,11 @@ function subagentResult(overrides: Partial<RuntimeSubagentChildResult> = {}): RucallId: "call-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: "research",...overrides,diff --git a/packages/eve/src/execution/terminate-child-sessions-step.test.ts b/packages/eve/src/execution/terminate-child-sessions-step.test.tsnew file mode 100644index 000000000..98a5010fe--- /dev/null+++ b/packages/eve/src/execution/terminate-child-sessions-step.test.ts@@ -0,0 +1,194 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++import { AGENT_HANDLES_STATE_KEY, type AgentHandle } from "#harness/handles/store.js";+import type { DurableSessionState } from "#execution/durable-session-store.js";+import { terminateChildSessionsStep } from "#execution/terminate-child-sessions-step.js";++const { dispatchSessionMock } = vi.hoisted(() => ({+ dispatchSessionMock: vi.fn(),+}));++vi.mock("./workflow-runtime.js", () => ({+ createWorkflowRuntime: vi.fn(() => ({+ dispatchSession: dispatchSessionMock,+ })),+}));++describe("terminateChildSessionsStep", () => {+ beforeEach(() => {+ dispatchSessionMock.mockReset();+ dispatchSessionMock.mockResolvedValue({ status: "accepted" });+ });++ it("terminates running and parked local/self children", async () => {+ const handles = [+ runningHandle({ id: "ag_local:1", kind: "agent/local", sessionId: "session-local" }),+ parkedHandle({ id: "ag_self:1", kind: "agent/self", sessionId: "session-self" }),+ ];++ await terminateChildSessionsStep({+ sessionState: makeSessionState(handles),+ });++ expect(dispatchSessionMock).toHaveBeenCalledTimes(2);+ expect(dispatchSessionMock).toHaveBeenNthCalledWith(1, {+ command: { kind: "reset", reason: "Parent session ended" },+ sessionId: "session-local",+ });+ expect(dispatchSessionMock).toHaveBeenNthCalledWith(2, {+ command: { kind: "reset", reason: "Parent session ended" },+ sessionId: "session-self",+ });+ });++ it("skips remote handles: remote children survive parent termination (documented gap)", async () => {+ await terminateChildSessionsStep({+ sessionState: makeSessionState([+ parkedHandle({ id: "ag_remote:1", kind: "agent/remote", sessionId: "session-remote" }),+ runningHandle({ id: "ag_local:1", kind: "agent/local", sessionId: "session-local" }),+ ]),+ });++ expect(dispatchSessionMock).toHaveBeenCalledExactlyOnceWith({+ command: { kind: "reset", reason: "Parent session ended" },+ sessionId: "session-local",+ });+ });++ it("skips a starting handle that has no session id yet", async () => {+ await terminateChildSessionsStep({+ sessionState: makeSessionState([+ startingHandle({ id: "ag_local:starting", kind: "agent/local" }),+ parkedHandle({ id: "ag_self:1", kind: "agent/self", sessionId: "session-self" }),+ ]),+ });++ expect(dispatchSessionMock).toHaveBeenCalledExactlyOnceWith({+ command: { kind: "reset", reason: "Parent session ended" },+ sessionId: "session-self",+ });+ });++ it("continues terminating children after one termination fails", async () => {+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});+ dispatchSessionMock+ .mockRejectedValueOnce(new Error("termination unavailable"))+ .mockResolvedValueOnce({ status: "accepted" });++ try {+ await expect(+ terminateChildSessionsStep({+ sessionState: makeSessionState([+ runningHandle({ id: "ag_child:1", kind: "agent/local", sessionId: "session-1" }),+ parkedHandle({ id: "ag_child:2", kind: "agent/self", sessionId: "session-2" }),+ ]),+ }),+ ).resolves.toBeUndefined();++ expect(dispatchSessionMock).toHaveBeenCalledTimes(2);+ expect(errorSpy).toHaveBeenCalledWith(+ "[eve:execution.terminate-child-sessions] failed to terminate child session",+ expect.objectContaining({+ agentId: "ag_child:1",+ childSessionId: "session-1",+ }),+ );+ } finally {+ errorSpy.mockRestore();+ }+ });+});++type LocalAddressKind = "agent/local" | "agent/self";+type AddressKind = LocalAddressKind | "agent/remote";++function makeIdentity(id: string): { id: string; name: string; nodeId: string } {+ return { id, name: "research", nodeId: "subagents/research" };+}++function makeAddress(kind: AddressKind, sessionId: string) {+ const base = { continuationToken: `${sessionId}:token`, sessionId };+ return kind === "agent/remote"+ ? {+ ...base,+ callbackBaseUrl: "https://parent.example.com",+ kind,+ url: "https://remote.example.com",+ }+ : { ...base, kind };+}++function runningHandle(input: {+ readonly id: string;+ readonly kind: AddressKind;+ readonly sessionId: string;+}): AgentHandle {+ return {+ address: makeAddress(input.kind, input.sessionId),+ identity: makeIdentity(input.id),+ operation: {+ callId: "call-1",+ id: `op-${input.id}`,+ kind: "start",+ parentTurnId: "turn-1",+ },+ phase: "running",+ };+}++function parkedHandle(input: {+ readonly id: string;+ readonly kind: AddressKind;+ readonly sessionId: string;+}): AgentHandle {+ return {+ address: makeAddress(input.kind, input.sessionId),+ identity: makeIdentity(input.id),+ lastStatus: "ready",+ phase: "parked",+ };+}++function startingHandle(input: {+ readonly id: string;+ readonly kind: LocalAddressKind;+}): AgentHandle {+ return {+ identity: makeIdentity(input.id),+ operation: {+ callId: "call-1",+ id: `op-${input.id}`,+ kind: "start",+ parentTurnId: "turn-1",+ },+ phase: "starting",+ target: { continuationToken: "pending:token", kind: input.kind },+ };+}++function makeSessionState(handles: readonly AgentHandle[]): DurableSessionState {+ return {+ continuationToken: "parent-token",+ emissionState: {+ sequence: 0,+ sessionStarted: true,+ stepIndex: 0,+ turnId: "turn-1",+ },+ hasProxyInputRequests: false,+ sessionId: "parent-session",+ snapshot: {+ session: {+ agent: { system: "" },+ continuationToken: "parent-token",+ history: [],+ sessionId: "parent-session",+ state: {+ [AGENT_HANDLES_STATE_KEY]: { handles },+ },+ },+ version: 1,+ },+ version: 1,+ };+}diff --git a/packages/eve/src/execution/terminate-child-sessions-step.ts b/packages/eve/src/execution/terminate-child-sessions-step.tsnew file mode 100644index 000000000..1c095597f--- /dev/null+++ b/packages/eve/src/execution/terminate-child-sessions-step.ts@@ -0,0 +1,71 @@+import { readDurableSession, type DurableSessionState } from "#execution/durable-session-store.js";+import { createWorkflowRuntime } from "#execution/workflow-runtime.js";+import { getAgentHandleStore, type AgentHandle } from "#harness/handles/store.js";+import { createLogger, logError } from "#internal/logging.js";++const log = createLogger("execution.terminate-child-sessions");++/**+ * Terminates same-deployment children the parent holds handles to when the+ * parent session ends.+ *+ * Every nonterminal `agent/local`/`agent/self` handle is covered: `running`+ * and `parked` handles carry a confirmed address; a `starting` handle has+ * no session id yet (the child may not exist), so it is skipped with a+ * debug log rather than guessed at. Remote handles are out of scope —+ * documented gap: remote children survive parent termination until a+ * remote-termination protocol exists.+ */+export async function terminateChildSessionsStep(input: {+ readonly sessionState: DurableSessionState;+}): Promise<void> {+ "use step";++ let session;+ try {+ session = await readDurableSession(input.sessionState);+ } catch (error) {+ logError(log, "failed to read child sessions for termination", error, {+ parentSessionId: input.sessionState.sessionId,+ });+ return;+ }++ const handles = (getAgentHandleStore(session.state)?.handles ?? []).filter(isLocalChildHandle);+ if (handles.length === 0) {+ return;+ }++ const runtime = createWorkflowRuntime({+ compiledArtifactsSource: { kind: "bundled" },+ });++ for (const handle of handles) {+ if (handle.phase === "starting") {+ log.debug("skipping starting child without a session id", {+ agentId: handle.identity.id,+ kind: handle.target.kind,+ parentSessionId: session.sessionId,+ });+ continue;+ }+ try {+ await runtime.dispatchSession({+ command: { kind: "reset", reason: "Parent session ended" },+ sessionId: handle.address.sessionId,+ });+ } catch (error) {+ logError(log, "failed to terminate child session", error, {+ agentId: handle.identity.id,+ childSessionId: handle.address.sessionId,+ kind: handle.address.kind,+ parentSessionId: session.sessionId,+ });+ }+ }+}++function isLocalChildHandle(handle: AgentHandle): boolean {+ const kind = handle.phase === "starting" ? handle.target.kind : handle.address.kind;+ return kind === "agent/local" || kind === "agent/self";+}diff --git a/packages/eve/src/execution/turn-execution-cursor.ts b/packages/eve/src/execution/turn-execution-cursor.tsindex 2b4e63e0b..c3c4b085a 100644--- a/packages/eve/src/execution/turn-execution-cursor.ts+++ b/packages/eve/src/execution/turn-execution-cursor.ts@@ -6,6 +6,7 @@ import type {TurnStepInput,TurnStepPayload,} from "#execution/durable-session-migrations/turn-workflow.js";+import type { SettledTurn } from "#harness/types.js";import type { TokenUsage } from "#shared/token-usage.js";interface TurnTransition {@@ -19,11 +20,13 @@ type TurnTerminalAction =readonly kind: "done";readonly output: unknown;readonly usage?: TokenUsage;+ readonly usageDelta?: TokenUsage;}| {readonly authorizationNames?: readonly string[];readonly cancelled?: true;readonly kind: "park";+ readonly settled?: SettledTurn;};/** Owns the mutable durable state cursor for one active turn workflow. */diff --git a/packages/eve/src/execution/turn-workflow.ts b/packages/eve/src/execution/turn-workflow.tsindex 24cf9fef5..1e7b52039 100644--- a/packages/eve/src/execution/turn-workflow.ts+++ b/packages/eve/src/execution/turn-workflow.ts@@ -151,6 +151,7 @@ async function runTurnOwnedWorkflow(input: TurnWorkflowInput): Promise<void> {output: result.output ?? "",isError: result.isError,usage: result.usage,+ usageDelta: result.usageDelta,},bufferedDeliveries,);@@ -213,6 +214,7 @@ async function runTurnOwnedWorkflow(input: TurnWorkflowInput): Promise<void> {{authorizationNames: result.authorizationNames,kind: "park",+ settled: result.settled,},bufferedDeliveries,);@@ -402,6 +404,7 @@ async function runLegacyTurnWorkflow(input: TurnWorkflowInput): Promise<void> {serializedContext: result.serializedContext,sessionState: result.sessionState,usage: result.usage,+ usageDelta: result.usageDelta,},kind: "turn-result",},@@ -448,6 +451,7 @@ async function runLegacyTurnWorkflow(input: TurnWorkflowInput): Promise<void> {serializedContext: result.serializedContext,sessionState: result.sessionState,authorizationNames: result.authorizationNames,+ settled: result.settled,};await sendTurnControlStep({diff --git a/packages/eve/src/execution/workflow-entry.integration.test.ts b/packages/eve/src/execution/workflow-entry.integration.test.tsindex e144bddd6..75394dcfd 100644--- a/packages/eve/src/execution/workflow-entry.integration.test.ts+++ b/packages/eve/src/execution/workflow-entry.integration.test.ts@@ -1,5 +1,6 @@import { describe, expect, it } from "vitest";import { getWorld, resumeHook, start } from "#internal/workflow/runtime.js";+import { hydrateWorkflowArguments } from "@workflow/core/serialization";import { createSendFn } from "#channel/send.js";import { captureTurnEvents, filterEventsByType } from "#internal/testing/events.js";@@ -26,6 +27,7 @@ import { toInputSchema } from "#shared/tool-schema.js";function buildSerializedContext(overrides: {auth?: Record<string, unknown>;channelKind: string;+ channelState?: Record<string, unknown>;continuationToken: string;mode: string;parent?: {@@ -41,7 +43,7 @@ function buildSerializedContext(overrides: {const context: Record<string, unknown> = {"eve.auth": overrides.auth ?? null,"eve.bundle": { source: createBundledRuntimeCompiledArtifactsSource() },- "eve.channel": { kind: overrides.channelKind, state: {} },+ "eve.channel": { kind: overrides.channelKind, state: overrides.channelState ?? {} },"eve.continuationToken": overrides.continuationToken,"eve.mode": overrides.mode,};@@ -311,7 +313,6 @@ describe("workflowEntry integration", () => {}),},]);-const stream = captureTurnEvents(run);let firstTurn: readonly MessageStreamEvent[];try {@@ -417,6 +418,85 @@ describe("workflowEntry integration", () => {});});+ it("notifies each delegated conversation turn and remains available via agentId", async () => {+ const runtime = createTestRuntime({ agent: { name: "workflow-entry-delegated-conversation" } });+ const workflowRuntime = createWorkflowRuntime({+ compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),+ });+ const childContinuationToken = "subagent:parent-session:call-1";++ await runtime.run(async () => {+ const child = await start(workflowEntry, [+ {+ input: { message: "delegated first turn" },+ serializedContext: buildSerializedContext({+ channelKind: "subagent",+ channelState: {+ callId: "call-1",+ parentContinuationToken: childContinuationToken,+ parentSessionId: "parent-session",+ subagentName: "researcher",+ },+ continuationToken: childContinuationToken,+ mode: "conversation",+ }),+ },+ ]);+ const stream = captureTurnEvents(child);++ try {+ const firstTurn = await withTimeout(stream.nextTurn(), "delegated first turn");+ expect(firstTurn.at(-1)?.type).toBe("session.waiting");+ await expect(waitForRuntimeActionResult(child.runId, "call-1")).resolves.toMatchObject({+ kind: "runtime-action-result",+ results: [+ {+ callId: "call-1",+ kind: "subagent-result",+ output: expect.stringContaining("delegated first turn"),+ subagentName: "researcher",+ },+ ],+ });++ await expect(+ workflowRuntime.dispatchSession({+ command: {+ caller: {+ callId: "call-2",+ replyTo: { kind: "hook", token: childContinuationToken },+ subagentName: "researcher",+ },+ kind: "send",+ payload: { message: "delegated follow-up turn" },+ },+ sessionId: child.runId,+ }),+ ).resolves.toEqual({+ sessionId: child.runId,+ status: "accepted",+ });++ const secondTurn = await withTimeout(stream.nextTurn(), "delegated follow-up turn");+ expect(secondTurn.at(-1)?.type).toBe("session.waiting");+ await expect(waitForRuntimeActionResult(child.runId, "call-2")).resolves.toMatchObject({+ kind: "runtime-action-result",+ results: [+ {+ callId: "call-2",+ kind: "subagent-result",+ output: expect.stringContaining("delegated follow-up turn"),+ subagentName: "researcher",+ },+ ],+ });+ } finally {+ stream.dispose();+ await child.cancel();+ }+ });+ });+it("fails a competing continuation owner before its first turn", async () => {const runtime = createTestRuntime({ agent: { name: "workflow-entry-hook-owner" } });const continuationToken = "http:workflow-entry-hook-owner";@@ -793,3 +873,55 @@ async function withTimeout<T>(promise: Promise<T>, label: string): Promise<T> {}}}++async function waitForRuntimeActionResult(runId: string, callId: string): Promise<unknown> {+ const world = await getWorld();+ const deadline = Date.now() + 10_000;+ let receivedPayloads: unknown[] = [];++ while (Date.now() < deadline) {+ const events = await world.events.list({+ pagination: { limit: 1000 },+ resolveData: "all",+ runId,+ });+ receivedPayloads = [];++ for (const event of events.data) {+ if (event.eventType === "hook_received") {+ const payload = await hydrateWorkflowArguments(event.eventData.payload, runId, undefined);+ receivedPayloads.push(payload);+ if (hasSubagentResult(payload, callId)) {+ return payload;+ }+ }+ }++ await new Promise((resolve) => setTimeout(resolve, 100));+ }++ throw new Error(+ `Timed out waiting for delegated result "${callId}". Received: ${JSON.stringify(receivedPayloads)}`,+ );+}++function hasSubagentResult(value: unknown, callId: string): boolean {+ if (+ typeof value !== "object" ||+ value === null ||+ !("kind" in value) ||+ value.kind !== "runtime-action-result" ||+ !("results" in value) ||+ !Array.isArray(value.results)+ ) {+ return false;+ }++ return value.results.some(+ (result) =>+ typeof result === "object" &&+ result !== null &&+ "callId" in result &&+ result.callId === callId,+ );+}diff --git a/packages/eve/src/execution/workflow-entry.test.ts b/packages/eve/src/execution/workflow-entry.test.tsindex 192f4aace..a4aab7980 100644--- a/packages/eve/src/execution/workflow-entry.test.ts+++ b/packages/eve/src/execution/workflow-entry.test.ts@@ -5,7 +5,11 @@ import { resumeHook } from "#internal/workflow/runtime.js";import type { HookPayload } from "#channel/types.js";import { ChannelRequestIdKey, SubagentDepthKey } from "#context/keys.js";import { createSessionStep } from "#execution/create-session-step.js";-import { notifyDelegatedParentStep } from "#execution/delegated-parent-notification.js";+import {+ notifyDelegatedParentStep,+ notifyTurnCallerStep,+ resolveInitialTurnCallerStep,+} from "#execution/delegated-parent-notification.js";import type { DurableSessionState } from "#execution/durable-session-store.js";import { fireSessionCallbackStep } from "#execution/session-callback-step.js";import { emitTerminalSessionCompletionStep } from "#execution/terminal-session-completion-step.js";@@ -13,6 +17,7 @@ import {createSessionTimeoutControl,type SessionTimeoutControl,} from "#execution/session-timeout-control.js";+import { terminateChildSessionsStep } from "#execution/terminate-child-sessions-step.js";import type { TurnControlPayload } from "#execution/turn-control-protocol.js";import { workflowEntry } from "#execution/workflow-entry.js";import { routeDeliverToChildren } from "#execution/route-child-delivery.js";@@ -61,6 +66,12 @@ vi.mock("./route-child-delivery.js", () => ({vi.mock("./delegated-parent-notification.js", () => ({notifyDelegatedParentStep: vi.fn().mockResolvedValue(undefined),+ notifyTurnCallerStep: vi.fn().mockResolvedValue(undefined),+ resolveInitialTurnCallerStep: vi.fn().mockResolvedValue(undefined),+}));++vi.mock("./terminate-child-sessions-step.js", () => ({+ terminateChildSessionsStep: vi.fn().mockResolvedValue(undefined),}));vi.mock("./workflow-steps.js", () => ({@@ -184,6 +195,7 @@ describe("workflowEntry", () => {expect(getConflict.mock.invocationCallOrder[0]).toBeLessThan(vi.mocked(dispatchTurnStep).mock.invocationCallOrder[0] ?? Number.POSITIVE_INFINITY,);+ expect(terminateChildSessionsStep).toHaveBeenCalledWith({ sessionState });});it("fails a conflicting delivery hook before dispatching the first turn", async () => {@@ -343,6 +355,7 @@ describe("workflowEntry", () => {token: sessionCommandHookToken("wrun_test_123"),});expect(timeoutControl.dispose).toHaveBeenCalledOnce();+ expect(terminateChildSessionsStep).toHaveBeenCalledWith({ sessionState });expect(emitTerminalSessionFailureStep).not.toHaveBeenCalled();expect(emitTerminalSessionCompletionStep).toHaveBeenCalledWith({parentWritable: expect.any(WritableStream),@@ -352,10 +365,12 @@ describe("workflowEntry", () => {vi.mocked(emitTerminalSessionCompletionStep).mock.invocationCallOrder[0] ??Number.POSITIVE_INFINITY,);- expect(fireSessionCallbackStep).toHaveBeenCalledWith({- output: "",- serializedContext: { "eve.sessionId": "wrun_test_123" },- status: "completed",+ expect(fireSessionCallbackStep).not.toHaveBeenCalled();+ expect(notifyTurnCallerStep).toHaveBeenCalledWith({+ caller: undefined,+ lifecycle: "terminal",+ sessionId: "wrun_test_123",+ settled: { output: "" },});});@@ -496,7 +511,13 @@ describe("workflowEntry", () => {it("notifies a delegated parent once when a turn fails terminally", async () => {const sessionState = createBaseSessionState();+ const caller = {+ callId: "call-1",+ replyTo: { kind: "hook" as const, token: "parent-token" },+ subagentName: "researcher",+ };vi.mocked(createSessionStep).mockResolvedValue(createSessionStepResultForMock(sessionState));+ vi.mocked(resolveInitialTurnCallerStep).mockResolvedValueOnce(caller);installHookMocks({turnControls: [{@@ -531,21 +552,266 @@ describe("workflowEntry", () => {error: expect.objectContaining({ message: "persistent recoverable failure" }),}),);- expect(fireSessionCallbackStep).toHaveBeenCalledOnce();- expect(notifyDelegatedParentStep).toHaveBeenCalledOnce();- expect(notifyDelegatedParentStep).toHaveBeenCalledWith({- result: {- callId: "call-1",+ expect(terminateChildSessionsStep).toHaveBeenCalledWith({ sessionState });+ expect(notifyDelegatedParentStep).not.toHaveBeenCalled();+ expect(notifyTurnCallerStep).toHaveBeenCalledOnce();+ expect(notifyTurnCallerStep).toHaveBeenCalledWith({+ caller,+ lifecycle: "terminal",+ sessionId: "wrun_test_123",+ settled: {isError: true,- kind: "subagent-result",- origin: "child",- output: {- code: "SUBAGENT_EXECUTION_FAILED",+ output: expect.objectContaining({message: "persistent recoverable failure",+ name: "Error",+ }),+ },+ });+ expect(fireSessionCallbackStep).not.toHaveBeenCalled();+ // The caller cell was already populated; the crash path must reuse it+ // instead of resolving a second time.+ expect(resolveInitialTurnCallerStep).toHaveBeenCalledOnce();+ });++ it("rejects the delegated caller when the session fails before the caller is resolved", async () => {+ const caller = {+ callId: "call-1",+ replyTo: { kind: "hook" as const, token: "parent-token" },+ subagentName: "researcher",+ };+ // Crash before `resolveInitialTurnCallerStep` ever runs: the cleanup+ // cell is unpopulated, so the catch must re-resolve the caller from the+ // serialized context or the delegated parent's call parks forever.+ vi.mocked(createSessionStep).mockRejectedValueOnce(new Error("session creation failed"));+ vi.mocked(resolveInitialTurnCallerStep).mockResolvedValueOnce(caller);+ const serializedContext = createSerializedContext({+ "eve.channel": {+ kind: "subagent",+ state: {+ callId: "call-1",+ parentContinuationToken: "parent-token",+ subagentName: "researcher",+ },+ },+ });++ await expect(+ workflowEntry({+ input: { message: "delegate" },+ serializedContext,+ }),+ ).rejects.toMatchObject({ name: "EveWorkflowFailure" });++ expect(resolveInitialTurnCallerStep).toHaveBeenCalledOnce();+ expect(notifyTurnCallerStep).toHaveBeenCalledOnce();+ expect(notifyTurnCallerStep).toHaveBeenCalledWith({+ caller,+ lifecycle: "terminal",+ sessionId: "wrun_test_123",+ settled: {+ isError: true,+ output: expect.objectContaining({ message: "session creation failed" }),+ },+ });+ // No snapshot was ever received, so there are no children to terminate.+ expect(terminateChildSessionsStep).not.toHaveBeenCalled();+ });++ it("does not re-resolve a caller the loop already settled and cleared", async () => {+ // A crash after a settled reply cleared the cell must notify no one:+ // `caller: undefined` with the resolution flag set means "nothing left+ // to notify", not "never resolved".+ const sessionState = createBaseSessionState();+ vi.mocked(createSessionStep).mockResolvedValue(createSessionStepResultForMock(sessionState));+ vi.mocked(resolveInitialTurnCallerStep).mockResolvedValueOnce(undefined);+ installHookMocks({+ turnControls: [+ {+ error: { message: "root turn crashed", name: "Error" },+ kind: "turn-error",+ },+ ],+ });++ await expect(+ workflowEntry({+ input: { message: "hello" },+ serializedContext: createSerializedContext(),+ }),+ ).rejects.toMatchObject({ name: "EveWorkflowFailure" });++ expect(resolveInitialTurnCallerStep).toHaveBeenCalledOnce();+ expect(notifyTurnCallerStep).toHaveBeenCalledWith(+ expect.objectContaining({ caller: undefined }),+ );+ });++ it("notifies the latest delegated exchange when a resumed turn fails terminally", async () => {+ const sessionState = createBaseSessionState();+ vi.mocked(createSessionStep).mockResolvedValue(createSessionStepResultForMock(sessionState));+ const serializedContext = createSerializedContext({+ "eve.channel": {+ kind: "subagent",+ state: {+ callId: "call-original",+ parentContinuationToken: "original-parent-turn",+ subagentName: "researcher",+ },+ },+ });+ installHookMocks({+ deliveryHooks: [+ {+ token: "http:test",+ values: [+ {+ caller: {+ callId: "call-latest",+ replyTo: { kind: "hook", token: "latest-parent-turn" },+ subagentName: "researcher",+ },+ kind: "send",+ payload: { message: "follow up" },+ },+ ],},+ ],+ turnControls: [+ turnResult({ action: "park", sessionState }),+ {+ action: {+ isError: true,+ kind: "done",+ output: "follow-up failed",+ serializedContext,+ sessionState,+ },+ kind: "turn-result",+ },+ ],+ });++ await expect(+ workflowEntry({+ input: { message: "delegate" },+ serializedContext,+ }),+ ).resolves.toEqual({ output: "follow-up failed" });++ expect(notifyTurnCallerStep).toHaveBeenCalledWith({+ caller: {+ callId: "call-latest",+ replyTo: { kind: "hook", token: "latest-parent-turn" },subagentName: "researcher",},- serializedContext,+ lifecycle: "terminal",+ sessionId: "wrun_test_123",+ settled: {+ isError: true,+ output: "follow-up failed",+ },+ });+ expect(fireSessionCallbackStep).not.toHaveBeenCalled();+ });++ it("rekeys the delivery hook before notifying a delegated settled turn", async () => {+ const initialState = createBaseSessionState({ continuationToken: "" });+ const parkedState = createBaseSessionState({ continuationToken: "subagent:child" });+ const caller = {+ callId: "call-1",+ replyTo: { kind: "hook" as const, token: "parent-turn" },+ subagentName: "researcher",+ };+ vi.mocked(createSessionStep).mockResolvedValue(createSessionStepResultForMock(initialState));+ vi.mocked(resolveInitialTurnCallerStep).mockResolvedValueOnce(caller);+ const serializedContext = createSerializedContext({+ "eve.channel": {+ kind: "subagent",+ state: {+ callId: "call-1",+ parentContinuationToken: "parent-turn",+ subagentName: "researcher",+ },+ },+ "eve.continuationToken": "",+ });+ installHookMocks({+ deliveryHooks: [{ token: "subagent:child", values: [] }],+ turnControls: [+ turnResult({+ action: "park",+ serializedContext,+ sessionState: parkedState,+ settled: { output: "settled answer" },+ }),+ ],+ });++ await expect(+ workflowEntry({+ input: { message: "delegate" },+ serializedContext,+ }),+ ).resolves.toEqual({ output: "" });++ const rekeyCall = vi+ .mocked(createHook)+ .mock.calls.find((call) => call[0]?.token === "subagent:child");+ expect(rekeyCall).toBeDefined();+ expect(vi.mocked(createHook).mock.invocationCallOrder.at(-1)).toBeLessThan(+ vi.mocked(notifyTurnCallerStep).mock.invocationCallOrder[0] ?? Number.POSITIVE_INFINITY,+ );+ expect(notifyTurnCallerStep).toHaveBeenCalledWith({+ caller,+ lifecycle: "parked",+ sessionId: "wrun_test_123",+ settled: { output: "settled answer" },+ });+ });++ it("keeps the turn caller across a callerless continuation", async () => {+ const sessionState = createBaseSessionState();+ const caller = {+ callId: "call-1",+ replyTo: { kind: "hook" as const, token: "parent-turn" },+ subagentName: "researcher",+ };+ vi.mocked(createSessionStep).mockResolvedValue(createSessionStepResultForMock(sessionState));+ vi.mocked(resolveInitialTurnCallerStep).mockResolvedValueOnce(caller);+ installHookMocks({+ deliveryHooks: [+ {+ token: "http:test",+ values: [+ {+ kind: "send",+ payload: { inputResponses: [{ optionId: "approve", requestId: "req-1" }] },+ },+ ],+ },+ ],+ turnControls: [+ turnResult({ action: "park", sessionState }),+ turnResult({+ action: "park",+ sessionState,+ settled: { output: "approved answer" },+ }),+ ],+ });++ await expect(+ workflowEntry({+ input: { message: "delegate" },+ serializedContext: createSerializedContext(),+ }),+ ).resolves.toEqual({ output: "" });++ expect(notifyTurnCallerStep).toHaveBeenCalledExactlyOnceWith({+ caller,+ lifecycle: "parked",+ sessionId: "wrun_test_123",+ settled: { output: "approved answer" },});});@@ -715,7 +981,20 @@ describe("workflowEntry", () => {});it("settles a cancelled turn in the driver and starts the next turn from the settled state", async () => {- const sessionState = createBaseSessionState();+ const sessionState = createBaseSessionState({+ snapshot: {+ session: {+ agent: { system: "" },+ continuationToken: "http:test",+ history: [],+ sessionId: "wrun_test_123",+ state: {+ "eve.harness.settledTurn": { output: "stale prior answer" },+ },+ },+ version: 1,+ },+ });const settledState = createBaseSessionState({emissionState: { sequence: 1, sessionStarted: true, stepIndex: 0, turnId: "" },});@@ -760,6 +1039,12 @@ describe("workflowEntry", () => {serializedContext: { settled: true },sessionState: settledState,});+ expect(notifyTurnCallerStep).toHaveBeenCalledExactlyOnceWith({+ caller: undefined,+ lifecycle: "terminal",+ sessionId: "wrun_test_123",+ settled: { output: "ok" },+ });});it("does not settle an ordinary park as cancelled", async () => {@@ -779,6 +1064,145 @@ describe("workflowEntry", () => {expect(settleCancelledTurnStep).not.toHaveBeenCalled();});+ it("routes every settled conversation turn without classifying the session", async () => {+ const sessionState = createBaseSessionState();+ vi.mocked(createSessionStep).mockResolvedValue(createSessionStepResultForMock(sessionState));+ installHookMocks({+ deliveryHooks: [{ token: "http:test", values: [] }],+ turnControls: [+ turnResult({+ action: "park",+ sessionState,+ settled: { output: "hello" },+ }),+ ],+ });+ const serializedContext = createSerializedContext();++ await expect(+ workflowEntry({+ input: { message: "hello" },+ serializedContext,+ }),+ ).resolves.toEqual({ output: "" });++ expect(notifyTurnCallerStep).toHaveBeenCalledWith({+ caller: undefined,+ lifecycle: "parked",+ sessionId: "wrun_test_123",+ settled: { output: "hello" },+ });+ });++ it("does not re-send a settled parent turn when a delivery routes to a child", async () => {+ const sessionState = createBaseSessionState({ hasProxyInputRequests: true });+ vi.mocked(createSessionStep).mockResolvedValue(createSessionStepResultForMock(sessionState));+ vi.mocked(routeDeliverToChildren).mockResolvedValueOnce({+ kind: "continue",+ remainder: undefined,+ });+ installHookMocks({+ deliveryHooks: [+ {+ token: "http:test",+ values: [{ kind: "send", payload: { inputResponses: [] } }],+ },+ ],+ turnControls: [+ turnResult({+ action: "park",+ sessionState,+ settled: { output: "already sent" },+ }),+ ],+ });++ await expect(+ workflowEntry({+ input: { message: "hello" },+ serializedContext: createSerializedContext(),+ }),+ ).resolves.toEqual({ output: "" });++ expect(notifyTurnCallerStep).toHaveBeenCalledTimes(1);+ });++ it("runs concurrent caller deliveries as separate turns", async () => {+ const sessionState = createBaseSessionState();+ vi.mocked(createSessionStep).mockResolvedValue(createSessionStepResultForMock(sessionState));+ const firstCaller = {+ callId: "call-1",+ replyTo: { kind: "hook" as const, token: "caller-1" },+ subagentName: "researcher",+ };+ const secondCaller = {+ callId: "call-2",+ replyTo: { kind: "hook" as const, token: "caller-2" },+ subagentName: "researcher",+ };+ installHookMocks({+ deliveryHooks: [+ {+ token: "http:test",+ values: [],+ },+ ],+ turnControls: [+ {+ action: {+ kind: "park",+ serializedContext: { "eve.sessionId": "wrun_test_123" },+ sessionState,+ },+ bufferedDeliveries: [+ {+ caller: firstCaller,+ kind: "deliver",+ payloads: [{ message: "first question" }],+ },+ {+ caller: secondCaller,+ kind: "deliver",+ payloads: [{ message: "second question" }],+ },+ ],+ kind: "turn-result",+ },+ turnResult({+ action: "park",+ sessionState,+ settled: { output: "first answer" },+ }),+ turnResult({+ action: "park",+ sessionState,+ settled: { output: "second answer" },+ }),+ ],+ });++ await expect(+ workflowEntry({+ input: { message: "initial question" },+ serializedContext: createSerializedContext(),+ }),+ ).resolves.toEqual({ output: "" });++ expect(dispatchTurnStep).toHaveBeenCalledTimes(3);+ expect(notifyTurnCallerStep).toHaveBeenNthCalledWith(1, {+ caller: firstCaller,+ lifecycle: "parked",+ sessionId: "wrun_test_123",+ settled: { output: "first answer" },+ });+ expect(notifyTurnCallerStep).toHaveBeenNthCalledWith(2, {+ caller: secondCaller,+ lifecycle: "parked",+ sessionId: "wrun_test_123",+ settled: { output: "second answer" },+ });+ });+it("skips child routing when a turn completes without yielding to a delivery", async () => {const sessionState = createBaseSessionState();vi.mocked(createSessionStep).mockResolvedValue(createSessionStepResultForMock(sessionState));@@ -1050,6 +1474,10 @@ function turnResult(input: {readonly output?: string;readonly serializedContext?: Record<string, unknown>;readonly sessionState: DurableSessionState;+ readonly settled?: {+ readonly output: unknown;+ readonly isError?: boolean;+ };}): TurnControlPayload {const serializedContext = input.serializedContext ?? { "eve.sessionId": "wrun_test_123" };if (input.action === "done") {@@ -1063,12 +1491,13 @@ function turnResult(input: {kind: "turn-result",};}+ const park = {+ kind: "park" as const,+ serializedContext,+ sessionState: input.sessionState,+ };return {- action: {- kind: "park",- serializedContext,- sessionState: input.sessionState,- },+ action: input.settled === undefined ? park : { ...park, settled: input.settled },kind: "turn-result",};}diff --git a/packages/eve/src/execution/workflow-entry.ts b/packages/eve/src/execution/workflow-entry.tsindex 4dedf04ce..7db5ba710 100644--- a/packages/eve/src/execution/workflow-entry.ts+++ b/packages/eve/src/execution/workflow-entry.ts@@ -6,19 +6,23 @@ import type {HookPayload,RunInput,SessionCapabilities,+ TurnCaller,} from "#channel/types.js";-import { coalesceDeliveries } from "#harness/messages.js";import { readChannelRequestId, readRootSessionId } from "#execution/eve-workflow-attributes.js";import type { RunMode } from "#shared/run-mode.js";import type { DurableCompiledArtifactsSource } from "#runtime/durable-compiled-artifacts-source.js";-import { notifyDelegatedParentStep } from "#execution/delegated-parent-notification.js";+import {+ notifyDelegatedParentStep,+ notifyTurnCallerStep,+ resolveInitialTurnCallerStep,+} from "#execution/delegated-parent-notification.js";import {createDelegatedSubagentErrorResult,createDelegatedSubagentSuccessResult,} from "#execution/delegated-parent-result.js";import type { DurableSessionState } from "#execution/durable-session-store.js";import type { NextDriverAction } from "#execution/next-driver-action.js";-import { routeDeliverToChildren } from "#execution/route-child-delivery.js";+import { nextTurnDelivery } from "#execution/parked-delivery-wait.js";import { cancelDescendantTurnsStep } from "#execution/cancel-descendant-turns-step.js";import { dispatchAndAwaitTurn } from "#execution/turn-dispatch.js";import type { TurnDriverAction } from "#execution/turn-control-receiver.js";@@ -28,16 +32,15 @@ import { settleCancelledTurnStep } from "#execution/settle-cancelled-turn-step.jimport { emitTerminalSessionFailureStep } from "#execution/terminal-session-failure-step.js";import { fireSessionCallbackStep } from "#execution/session-callback-step.js";import { disposeHook } from "#execution/hook-ownership.js";-import {- createSessionCommandInbox,- type SessionCommandInbox,-} from "#execution/session-command-inbox.js";+import { createSessionCommandInbox } from "#execution/session-command-inbox.js";import { sessionCommandHookToken } from "#execution/session-command-token.js";import { DEFAULT_SESSION_TIMEOUT_MS } from "#execution/session-timeout.js";import { emitTerminalSessionCompletionStep } from "#execution/terminal-session-completion-step.js";import { createSessionTimeoutControl } from "#execution/session-timeout-control.js";+import { terminateChildSessionsStep } from "#execution/terminate-child-sessions-step.js";import { readSerializedSubagentDepth } from "#harness/subagent-depth.js";import type { DynamicSubagentAgentConfig } from "#runtime/subagents/dynamic-agent-config.js";+import type { TokenUsage } from "#shared/token-usage.js";const SAFE_OUTER_WORKFLOW_FAILURE_MESSAGE ="Agent workflow failed. Inspect the private session trace for details.";@@ -66,21 +69,47 @@ type DriverLoopOutcome =| {readonly kind: "expired";readonly serializedContext: Record<string, unknown>;+ readonly sessionState: DurableSessionState;}| {readonly kind: "result";readonly result: WorkflowEntryResult;};-type NextSessionAction =- | { readonly kind: "clear" }- | { readonly kind: "compact" }- | {- readonly delivery: DeliverHookPayload | null;- readonly kind: "delivery";- }- | { readonly kind: "expired" }- | { readonly kind: "reset" };+/**+ * Write-through cell owned by {@link workflowEntry}: written+ * unconditionally by the driver loop as turns advance, read only by the+ * outer catch. When the loop throws, its locals are unreachable, so this+ * cell is the crash path's only view of values that changed after turn 1.+ *+ * Reach for this cell only when all three hold for a value:+ * 1. it is produced or replaced inside the driver loop, so the entry+ * function's own locals go stale;+ * 2. it travels by value inside Workflow step results — there is no+ * store the catch could re-read it from at crash time;+ * 3. the crash path needs its latest value to discharge a cleanup+ * obligation.+ * If any of the three fails, read the value from where it already lives+ * instead of mirroring it here.+ */+interface CrashCleanupState {+ // The caller whose awaited reply is still unsettled, so the catch can+ // reject it with the error instead of leaving it parked forever.+ // Populated for every session; only conversation-mode paths read it.+ caller: TurnCaller | undefined;+ // Whether `resolveInitialTurnCallerStep` has run. `caller: undefined` is+ // ambiguous on its own: it also means "resolved and later cleared because+ // its reply settled". This flag lets the crash path tell that apart from+ // "crashed before the caller was ever resolved", where a delegated caller+ // may still be parked on this session's reply.+ callerResolved: boolean;+ // The latest snapshot the driver has received, so the catch can+ // terminate children adopted after turn 1. Honest staleness window: the+ // driver only sees state at turn boundaries, so children dispatched by a+ // turn that crashed mid-flight are absent from this snapshot and escape+ // crash cleanup.+ lastSessionState: DurableSessionState | undefined;+}/*** Long-lived workflow entrypoint. Handles both root sessions and@@ -115,6 +144,11 @@ export async function workflowEntry(input: WorkflowEntryInput): Promise<Workflowinput.serializedContext["eve.sessionId"] = sessionId;const driverWritable = getWritable<Uint8Array>();+ const crashCleanupState: CrashCleanupState = {+ caller: undefined,+ callerResolved: false,+ lastSessionState: undefined,+ };try {// Derived once and reused for createSession + tag emission so the@@ -136,6 +170,14 @@ export async function workflowEntry(input: WorkflowEntryInput): Promise<WorkflowsessionId,subagentDepth,});+ crashCleanupState.lastSessionState = sessionState;+ // Resolved for every session so the cell's population never depends+ // on session shape: the step returns undefined for root sessions,+ // and every reader is mode-gated.+ crashCleanupState.caller = await resolveInitialTurnCallerStep({+ serializedContext: input.serializedContext,+ });+ crashCleanupState.callerResolved = true;const outcome = await runDriverLoop({capabilities,@@ -151,6 +193,7 @@ export async function workflowEntry(input: WorkflowEntryInput): Promise<Workflow],requestId: readChannelRequestId(input.serializedContext),},+ crashCleanupState,mode,serializedContext: input.serializedContext,sessionState,@@ -165,32 +208,73 @@ export async function workflowEntry(input: WorkflowEntryInput): Promise<Workflowreturn outcome.result;}return await finalizeExpiredSession({+ caller: crashCleanupState.caller,driverWritable,+ mode,serializedContext: outcome.serializedContext,+ sessionState: outcome.sessionState,});} catch (error) {// Safety net for failures the tool-loop harness does not already// surface as `session.failed` (deserialization, runtime-action// throws, adapter `deliver` throws, staging errors, etc.) so the// channel still sees a terminal event.+ if (crashCleanupState.lastSessionState !== undefined) {+ await terminateChildSessionsStep({+ sessionState: crashCleanupState.lastSessionState,+ });+ }await emitTerminalSessionFailureStep({error: normalizeSerializableError(error),parentWritable: driverWritable,serializedContext: input.serializedContext,});- await fireSessionCallbackStep({- error: normalizeSerializableError(error),- serializedContext: input.serializedContext,- status: "failed",- });- await notifyDelegatedParentStep({- result: createDelegatedSubagentErrorResult(input.serializedContext, error),- serializedContext: input.serializedContext,- });+ if (mode === "task") {+ await fireSessionCallbackStep({+ error: normalizeSerializableError(error),+ serializedContext: input.serializedContext,+ status: "failed",+ });+ await notifyDelegatedParentStep({+ result: createDelegatedSubagentErrorResult(input.serializedContext, error),+ serializedContext: input.serializedContext,+ });+ } else {+ await notifyTurnCallerStep({+ caller: await resolveCallerForCrash(crashCleanupState, input.serializedContext),+ lifecycle: "terminal",+ sessionId,+ settled: { isError: true, output: error },+ });+ }throw createSafeOuterWorkflowError();}}+/**+ * Caller to reject from the crash path. Normally the resolved cell value —+ * including `undefined` after a settled reply cleared it, when there is+ * nothing left to notify. When the crash happened before+ * `resolveInitialTurnCallerStep` ever ran (e.g. `createSessionStep` threw),+ * the cell is empty even though a delegated caller may be parked on this+ * session's reply, so the caller is re-resolved from the serialized context+ * — which needs nothing from the failed steps. Best-effort: when resolution+ * fails again there is no reachable caller to notify.+ */+async function resolveCallerForCrash(+ state: CrashCleanupState,+ serializedContext: Record<string, unknown>,+): Promise<TurnCaller | undefined> {+ if (state.callerResolved) {+ return state.caller;+ }+ try {+ return await resolveInitialTurnCallerStep({ serializedContext });+ } catch {+ return undefined;+ }+}+function createSafeOuterWorkflowError(): Error {const error = new Error(SAFE_OUTER_WORKFLOW_FAILURE_MESSAGE);error.name = "EveWorkflowFailure";@@ -201,6 +285,7 @@ async function runDriverLoop(input: {readonly capabilities?: SessionCapabilities;readonly driverWritable: WritableStream<Uint8Array>;readonly initialInput: HookPayload;+ readonly crashCleanupState: CrashCleanupState;readonly mode: RunMode;readonly serializedContext: Record<string, unknown>;readonly sessionState: DurableSessionState;@@ -268,6 +353,7 @@ async function runDriverLoop(input: {serializedContext: input.serializedContext,sessionState: input.sessionState,});+ input.crashCleanupState.lastSessionState = action.sessionState;while (true) {if (action.kind === "done") {@@ -275,7 +361,8 @@ async function runDriverLoop(input: {kind: "result",result: await finalizeDone({action,- driverWritable: input.driverWritable,+ caller: input.crashCleanupState.caller,+ mode: input.mode,}),};}@@ -298,6 +385,7 @@ async function runDriverLoop(input: {serializedContext: settled.serializedContext,sessionState: settled.sessionState,};+ input.crashCleanupState.lastSessionState = action.sessionState;}// Channel-created sessions may rekey their dynamic alias. Sessions@@ -326,80 +414,98 @@ async function runDriverLoop(input: {serializedContext: action.serializedContext,sessionState: action.sessionState,});+ input.crashCleanupState.lastSessionState = action.sessionState;continue;}- const nextAction = await waitForNextSessionAction({+ // `settled` rides the typed park arm exclusively; `run-step` preserves+ // the full StepResult so no state-key fallback exists anymore.+ const settled = action.settled;+ if (action.cancelled !== true && settled !== undefined) {+ await notifyTurnCallerStep({+ caller: input.crashCleanupState.caller,+ lifecycle: "parked",+ sessionId: action.sessionState.sessionId,+ settled,+ });+ input.crashCleanupState.caller = undefined;+ } else if (action.cancelled === true) {+ input.crashCleanupState.caller = undefined;+ }++ const next = await nextTurnDelivery({bufferedDeliveries,bufferedSessionControls,commandInbox,+ driverWritable: input.driverWritable,+ sessionState: action.sessionState,});- if (nextAction.kind === "expired") {+ if (next.kind === "expired") {return {kind: "expired",serializedContext: action.serializedContext,+ sessionState: action.sessionState,};}- if (nextAction.kind === "reset") {+ if (next.kind === "reset") {+ await terminateChildSessionsStep({ sessionState: action.sessionState });return { kind: "result", result: { output: "" } };}- if (nextAction.kind === "clear" || nextAction.kind === "compact") {+ if (next.kind === "clear" || next.kind === "compact") {action = await runTurn({- delivery: { kind: nextAction.kind },+ delivery: { kind: next.kind },serializedContext: action.serializedContext,sessionState: action.sessionState,});+ input.crashCleanupState.lastSessionState = action.sessionState;continue;}- const nextDeliver = nextAction.delivery;- if (nextDeliver === null) {+ if (next.kind === "closed") {return { kind: "result", result: { output: "" } };}- const routed = await routeDeliverToChildren({- auth: nextDeliver.auth,- parentWritable: input.driverWritable,- payloads: nextDeliver.payloads,- sessionState: action.sessionState,- });-- if (routed.kind === "cancel-turn") {+ if (next.kind === "cancel-turn") {await cancelDescendantTurnsStep({serializedContext: action.serializedContext,sessionState: action.sessionState,});- const settled = await settleCancelledTurnStep({+ const cancelled = await settleCancelledTurnStep({parentWritable: input.driverWritable,serializedContext: action.serializedContext,sessionState: action.sessionState,});+ // Re-enter with `settled` cleared: the parked answer was already+ // delivered to its caller before this wait, so the next iteration+ // must not treat it as a fresh settlement.action = {...action,- serializedContext: settled.serializedContext,- sessionState: settled.sessionState,+ serializedContext: cancelled.serializedContext,+ sessionState: cancelled.sessionState,+ settled: undefined,};+ input.crashCleanupState.caller = undefined;+ input.crashCleanupState.lastSessionState = action.sessionState;continue;}- if (routed.remainder === undefined) {- // Fully routed to a descendant; parent has no turn to run.- continue;+ if (next.deliver.caller !== undefined) {+ input.crashCleanupState.caller = next.deliver.caller;}-action = await runTurn({delivery: {- auth: nextDeliver.auth,+ auth: next.deliver.auth,kind: "deliver",- payloads: [routed.remainder],- requestId: nextDeliver.requestId,+ payloads: [next.remainder],+ requestId: next.deliver.requestId,},serializedContext: action.serializedContext,sessionState: action.sessionState,});+ input.crashCleanupState.lastSessionState = action.sessionState;}} finally {await disposeSettledTurnControl?.();@@ -412,103 +518,83 @@ async function runDriverLoop(input: {}}-async function waitForNextSessionAction(input: {- readonly bufferedDeliveries: DeliverHookPayload[];- readonly bufferedSessionControls: Array<"clear" | "compact" | "expired" | "reset">;- readonly commandInbox: SessionCommandInbox;-}): Promise<NextSessionAction> {- const pendingSessionControl = input.bufferedSessionControls.shift();- if (pendingSessionControl !== undefined) {- return { kind: pendingSessionControl };- }-- if (input.bufferedDeliveries.length > 0) {- return {- delivery: coalesceDeliveries(input.bufferedDeliveries.splice(0)),- kind: "delivery",- };- }-- while (true) {- const first = await input.commandInbox.next();- input.commandInbox.consumeNext();-- if (first.done) {- return { delivery: null, kind: "delivery" };- }-- if (first.value.kind === "session-timeout") {- return { kind: "expired" };- }-- if (- first.value.kind === "clear" ||- first.value.kind === "compact" ||- first.value.kind === "reset"- ) {- return { kind: first.value.kind };- }-- if (first.value.kind === "cancel") {- continue;- }-- return { delivery: commandToDelivery(first.value), kind: "delivery" };- }-}--function commandToDelivery(- command: Extract<import("#channel/types.js").SessionCommand, { readonly kind: "send" }>,-): DeliverHookPayload {- return {- auth: command.auth,- caller: command.caller,- kind: "deliver",- payloads: [command.payload],- requestId: command.requestId,- };-}-async function finalizeExpiredSession(input: {+ readonly caller: TurnCaller | undefined;readonly driverWritable: WritableStream<Uint8Array>;+ readonly mode: RunMode;readonly serializedContext: Record<string, unknown>;+ readonly sessionState: DurableSessionState;}): Promise<WorkflowEntryResult> {+ await terminateChildSessionsStep({+ sessionState: input.sessionState,+ });await emitTerminalSessionCompletionStep({parentWritable: input.driverWritable,serializedContext: input.serializedContext,});- await fireSessionCallbackStep({- output: "",- serializedContext: input.serializedContext,- status: "completed",- });- await notifyDelegatedParentStep({- result: createDelegatedSubagentSuccessResult(input.serializedContext, ""),- serializedContext: input.serializedContext,- });++ if (input.mode === "task") {+ await fireSessionCallbackStep({+ output: "",+ serializedContext: input.serializedContext,+ status: "completed",+ });+ await notifyDelegatedParentStep({+ result: createDelegatedSubagentSuccessResult(input.serializedContext, ""),+ serializedContext: input.serializedContext,+ });+ } else {+ await notifyTurnCallerStep({+ caller: input.caller,+ lifecycle: "terminal",+ sessionId: input.sessionState.sessionId,+ settled: { output: "" },+ });+ }return { output: "" };}async function finalizeDone(input: {readonly action: NextDriverAction & { readonly kind: "done" };- readonly driverWritable: WritableStream<Uint8Array>;+ readonly caller: TurnCaller | undefined;+ readonly mode: RunMode;}): Promise<WorkflowEntryResult> {const { output, serializedContext } = input.action;const failed = input.action.isError === true;- await fireSessionCallbackStep({- error: failed ? output : undefined,- output: failed ? undefined : output,- serializedContext,- status: failed ? "failed" : "completed",- usage: failed ? undefined : input.action.usage,- });- await notifyDelegatedParentStep({- result: failed- ? createDelegatedSubagentErrorResult(serializedContext, output)- : createDelegatedSubagentSuccessResult(serializedContext, output),- serializedContext,- usage: failed ? undefined : input.action.usage,+ await terminateChildSessionsStep({+ sessionState: input.action.sessionState,});+ if (input.mode === "task") {+ await fireSessionCallbackStep({+ error: failed ? output : undefined,+ output: failed ? undefined : output,+ serializedContext,+ status: failed ? "failed" : "completed",+ usage: failed ? undefined : input.action.usage,+ });+ await notifyDelegatedParentStep({+ result: failed+ ? createDelegatedSubagentErrorResult(serializedContext, output)+ : createDelegatedSubagentSuccessResult(serializedContext, output),+ serializedContext,+ usage: failed ? undefined : input.action.usage,+ });+ } else {+ const settled: {+ isError?: boolean;+ output: unknown;+ usage?: TokenUsage;+ } = { output, usage: input.action.usageDelta };+ if (failed) {+ settled.isError = true;+ }+ await notifyTurnCallerStep({+ caller: input.caller,+ lifecycle: "terminal",+ sessionId: input.action.sessionState.sessionId,+ settled,+ });+ }return { output };}diff --git a/packages/eve/src/execution/workflow-runtime.test.ts b/packages/eve/src/execution/workflow-runtime.test.tsindex 214e509e4..ae7090e0a 100644--- a/packages/eve/src/execution/workflow-runtime.test.ts+++ b/packages/eve/src/execution/workflow-runtime.test.ts@@ -77,11 +77,17 @@ describe("createWorkflowRuntime command dispatch", () => {it("dispatches send commands directly through a continuation alias", async () => {resumeHookMock.mockResolvedValue({ runId: "driver-run" });+ const caller = {+ callId: "call-1",+ replyTo: { kind: "hook" as const, token: "parent-turn" },+ subagentName: "research",+ };await expect(buildRuntime().dispatchContinuation({command: {auth: null,+ caller,kind: "send",payload: { message: "hello" },requestId: "req_deliver",@@ -92,6 +98,7 @@ describe("createWorkflowRuntime command dispatch", () => {expect(resumeHookMock).toHaveBeenCalledWith("test:token", {auth: null,+ caller,kind: "send",payload: { message: "hello" },requestId: "req_deliver",diff --git a/packages/eve/src/execution/workflow-steps.test.ts b/packages/eve/src/execution/workflow-steps.test.tsindex 1d5211aa4..c3431ca3e 100644--- a/packages/eve/src/execution/workflow-steps.test.ts+++ b/packages/eve/src/execution/workflow-steps.test.ts@@ -21,6 +21,7 @@ import { getAgentHandleStore } from "#harness/handles/store.js";import { requestTurnSleep } from "#harness/turn-sleep.js";import { getPendingAuthorization, setPendingAuthorization } from "#harness/authorization.js";import { upsertProxyInputRequests } from "#harness/proxy-input-requests.js";+import { setPendingInputBatch } from "#harness/input-requests.js";import type { HarnessSession, StepResult } from "#harness/types.js";import { createEmptyHookRegistry } from "#runtime/hooks/registry.js";import { getCompiledRuntimeAgentBundle } from "#runtime/sessions/compiled-agent-cache.js";@@ -1073,6 +1074,205 @@ describe("turnStep", () => {);});+ it("carries a settled turn through the typed park action when no work remains pending", async () => {+ const session = createStubSession();+ installSessionStoreMocks([session]);+ vi.mocked(createExecutionNodeStep).mockImplementation(() => {+ return async (stepSession): Promise<StepResult> => ({+ next: null,+ session: stepSession,+ settledTurn: { output: "settled answer" },+ });+ });++ const result = await turnStep({+ input: {+ kind: "deliver",+ payloads: [{ message: "hello" }],+ },+ parentWritable: createTestWritable(),+ serializedContext: createSerializedContext(),+ sessionState: createStubSessionState(),+ });++ expect(result).toMatchObject({+ action: "park",+ settled: { output: "settled answer" },+ });+ });++ it("reports each settled turn's usage as a delta, not the cumulative session totals", async () => {+ const usageStateAfterTurn = (+ totals: Readonly<Record<string, number>>,+ ): Record<string, unknown> => ({+ "eve.harness.turnUsage": {+ cacheReadTokens: 0,+ cacheWriteTokens: 0,+ costUsd: 0,+ sawCost: false,+ inputTokens: 0,+ outputTokens: 0,+ session: {+ cacheReadTokens: 0,+ cacheWriteTokens: 0,+ costUsd: 0,+ sawCost: false,+ ...totals,+ },+ turnId: "turn_usage",+ },+ });++ const session = createStubSession();+ installSessionStoreMocks([session]);+ vi.mocked(createExecutionNodeStep).mockImplementation(() => {+ return async (stepSession): Promise<StepResult> => ({+ next: null,+ session: {+ ...stepSession,+ state: {+ ...stepSession.state,+ ...usageStateAfterTurn({ inputTokens: 100, outputTokens: 40 }),+ },+ },+ settledTurn: { output: "first answer" },+ });+ });++ const first = await turnStep({+ input: { kind: "deliver", payloads: [{ message: "hello" }] },+ parentWritable: createTestWritable(),+ serializedContext: createSerializedContext(),+ sessionState: createStubSessionState(),+ });++ expect(first).toMatchObject({+ action: "park",+ settled: {+ output: "first answer",+ usage: { cacheReadTokens: 0, cacheWriteTokens: 0, inputTokens: 100, outputTokens: 40 },+ },+ });+ if (first.action !== "park") throw new Error("expected park");++ // Second turn: session totals are cumulative (150/60), but the settled+ // answer must only report what this turn added (50/20).+ const firstSession = first.sessionState.snapshot?.session as HarnessSession;+ installSessionStoreMocks([firstSession]);+ vi.mocked(createExecutionNodeStep).mockImplementation(() => {+ return async (stepSession): Promise<StepResult> => ({+ next: null,+ session: {+ ...stepSession,+ state: {+ ...stepSession.state,+ ...usageStateAfterTurn({ inputTokens: 150, outputTokens: 60 }),+ },+ },+ settledTurn: { output: "second answer" },+ });+ });++ const second = await turnStep({+ input: { kind: "deliver", payloads: [{ message: "again" }] },+ parentWritable: createTestWritable(),+ serializedContext: createSerializedContext(),+ sessionState: first.sessionState,+ });++ expect(second).toMatchObject({+ action: "park",+ settled: {+ output: "second answer",+ usage: { cacheReadTokens: 0, cacheWriteTokens: 0, inputTokens: 50, outputTokens: 20 },+ },+ });+ });++ it.each([+ {+ name: "authorization",+ withPending: (session: HarnessSession): HarnessSession => ({+ ...session,+ state: setPendingAuthorization(session.state, {+ challenges: [+ {+ challenge: {+ instructions: "Sign in to continue",+ url: "https://idp.example/authorize",+ },+ hookUrl: "https://app.example/callback",+ name: "statuspage",+ },+ ],+ }),+ }),+ },+ {+ name: "input batch",+ withPending: (session: HarnessSession): HarnessSession =>+ setPendingInputBatch({+ requests: [+ {+ action: {+ callId: "call-input",+ input: {},+ kind: "tool-call",+ toolName: "confirm",+ },+ kind: "question",+ prompt: "Continue?",+ requestId: "request-input",+ },+ ],+ responseMessages: [],+ session,+ }),+ },+ {+ name: "runtime action",+ withPending: (session: HarnessSession): HarnessSession =>+ setPendingRuntimeActionBatch({+ actions: [+ {+ callId: "call-runtime",+ input: {},+ kind: "tool-call",+ toolName: "runtime-tool",+ },+ ],+ event: { sequence: 0, stepIndex: 0, turnId: "turn_0" },+ responseMessages: [],+ session,+ }),+ },+ ])("does not attach settled output while a $name remains pending", async ({ withPending }) => {+ const session = createStubSession();+ installSessionStoreMocks([session]);+ vi.mocked(createExecutionNodeStep).mockImplementation(() => {+ return async (stepSession): Promise<StepResult> => ({+ next: null,+ session: withPending(stepSession),+ settledTurn: { output: "must stay gated" },+ });+ });++ const result = await turnStep({+ input: {+ kind: "deliver",+ payloads: [{ message: "hello" }],+ },+ parentWritable: createTestWritable(),+ serializedContext: createSerializedContext(),+ sessionState: createStubSessionState(),+ });++ expect(result.action).toBe("park");+ if (result.action === "park") {+ expect(result.settled).toBeUndefined();+ }+ });+it("reads the durable session from normalized turn-step input", async () => {const session = createStubSession({continuationToken: "http:turn-step",diff --git a/packages/eve/src/execution/workflow-steps.ts b/packages/eve/src/execution/workflow-steps.tsindex 644fd2ae3..9ea211b8e 100644--- a/packages/eve/src/execution/workflow-steps.ts+++ b/packages/eve/src/execution/workflow-steps.ts@@ -36,8 +36,8 @@ import {} from "#harness/workflow-runtime-action-state.js";import { getPendingWorkflowInterrupt } from "#harness/workflow-interrupt-state.js";import { getPendingRuntimeActionBatch } from "#harness/runtime-actions.js";-import type { HarnessSession, StepInput, StepResult } from "#harness/types.js";-import { getTurnUsageState, toUsage } from "#harness/turn-tag-state.js";+import type { HarnessSession, SettledTurn, StepInput, StepResult } from "#harness/types.js";+import { getTurnUsageState, takeSessionUsageDelta, toUsage } from "#harness/turn-tag-state.js";import type { TokenUsage } from "#shared/token-usage.js";import type { JsonObject } from "#shared/json.js";import type { RunMode } from "#shared/run-mode.js";@@ -112,6 +112,12 @@ export type DurableStepResult =readonly sessionState: DurableSessionState;/** Session-total token usage; set on `done` when the session spent any. */readonly usage?: TokenUsage;+ /**+ * Usage the final turn added beyond what earlier settled turns already+ * reported; feeds the terminal `AgentTurnOutcome` for conversation+ * children. Task sessions settle once, so their callers read `usage`.+ */+ readonly usageDelta?: TokenUsage;}| {readonly action: "cancelled";@@ -127,6 +133,7 @@ export type DurableStepResult =readonly sleepDurationMs?: number;readonly serializedContext: Record<string, unknown>;readonly sessionState: DurableSessionState;+ readonly settled?: SettledTurn;}| {readonly action: "dispatch-workflow-runtime-actions";@@ -475,6 +482,7 @@ export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResuserializedContext: nextSerializedContext,sessionState: nextState,usage: sessionTotals === undefined ? undefined : toUsage(sessionTotals),+ usageDelta: takeSessionUsageDelta(stepResult.session).delta,};}@@ -497,9 +505,41 @@ export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResu};}+ const pending = derivePendingState(stepResult.session);++ // A park is idle when the turn stopped because it finished, not because+ // it is blocked on an authorization grant, a queued input batch, or+ // runtime-action dispatch.+ const isIdlePark =+ !pending.hasPendingAuthorization &&+ !pending.hasPendingInputBatch &&+ (pending.pendingRuntimeActionKeys?.length ?? 0) === 0;++ // A settled answer crosses the park boundary only at an idle park: the+ // driver forwards it to the delegated caller (notify-then-park), and+ // forwarding from a blocked park would report the turn as finished while+ // it still waits on pending work. `usage` carries only this turn's+ // delta: the take marks the totals reported, so the next settled turn+ // of a persistent child never re-reports earlier spend.+ if (isIdlePark && stepResult.settledTurn !== undefined) {+ const { delta, session: reportedSession } = takeSessionUsageDelta(stepResult.session);+ return {+ action: "park",+ ...pending,+ ...sleepTransition,+ serializedContext: nextSerializedContext,+ sessionState: createDurableSessionState({ session: reportedSession }),+ settled: {+ output: stepResult.settledTurn.output,+ isError: stepResult.settledTurn.isError,+ usage: delta,+ },+ };+ }+return {action: "park",- ...derivePendingState(stepResult.session),+ ...pending,...sleepTransition,serializedContext: nextSerializedContext,sessionState: nextState,diff --git a/packages/eve/src/harness/handles/transitions.test.ts b/packages/eve/src/harness/handles/transitions.test.tsindex 24dfbf408..9ae42ea72 100644--- a/packages/eve/src/harness/handles/transitions.test.ts+++ b/packages/eve/src/harness/handles/transitions.test.ts@@ -11,6 +11,7 @@ import {type StartOperation,} from "#harness/handles/store.js";import {+ abandonRunningAgentTurns,confirmAgentStarted,prepareAgentContinuation,prepareAgentStart,@@ -270,6 +271,23 @@ describe("rejectAgentEffect", () => {});});+describe("abandonRunningAgentTurns", () => {+ it("parks a running handle as cancelled so it stays resumable", () => {+ const abandoned = abandonRunningAgentTurns(runningSession());+ expect(handlesOf(abandoned)).toEqual([+ { address, identity, lastStatus: "(cancelled)", phase: "parked" },+ ]);+ });++ it("returns the session unchanged when nothing is running", () => {+ const parked = parkedSession();+ expect(abandonRunningAgentTurns(parked)).toBe(parked);++ const empty = createSession();+ expect(abandonRunningAgentTurns(empty)).toBe(empty);+ });+});+describe("settleAgentTurn", () => {it("parks the handle with a truncated status on a parked outcome", () => {const settled = settleAgentTurn(runningSession(), {diff --git a/packages/eve/src/harness/handles/transitions.ts b/packages/eve/src/harness/handles/transitions.tsindex 225845fdc..af30bd74e 100644--- a/packages/eve/src/harness/handles/transitions.ts+++ b/packages/eve/src/harness/handles/transitions.ts@@ -216,6 +216,40 @@ export function rejectAgentEffect();}+/**+ * Parks every running child when the parent abandons a cancelled turn.+ *+ * Cancellation requests each running descendant's cancellation and then+ * tears down the turn inbox — the only hook a child settlement can+ * resume — so no later settlement can move these handles. Without this+ * transition they would stay `running` forever: invisible to the model,+ * unresumable, and retried by every future cancellation.+ *+ * A cancelled child settles its own turn as a park, so `parked` with+ * `"(cancelled)"` mirrors {@link settleAgentTurn}'s cancelled outcome. If+ * the child instead died, a later continuation attempt discovers the dead+ * session and {@link rejectAgentEffect} deletes the handle.+ */+export function abandonRunningAgentTurns(session: HarnessSession): HarnessSession {+ const handles = getAgentHandleStore(session.state)?.handles ?? [];+ if (!handles.some((handle) => handle.phase === "running")) {+ return session;+ }+ return writeHandles(+ session,+ handles.map((handle) =>+ handle.phase === "running"+ ? {+ address: handle.address,+ identity: handle.identity,+ lastStatus: "(cancelled)",+ phase: "parked",+ }+ : handle,+ ),+ );+}+/** Result of applying a settled child turn to the store. */export type SettleAgentTurnResult =| { readonly kind: "settled"; readonly session: HarnessSession }diff --git a/packages/eve/src/harness/messages.test.ts b/packages/eve/src/harness/messages.test.tsindex 579fcb000..daf28ba26 100644--- a/packages/eve/src/harness/messages.test.ts+++ b/packages/eve/src/harness/messages.test.ts@@ -1,6 +1,7 @@import type { FilePart, ModelMessage, UserContent } from "ai";import { describe, expect, it } from "vitest";import {+ coalesceDeliveries,coalesceTurnInputs,normalizeUserContent,resolveAssistantStepText,@@ -19,6 +20,40 @@ function textFilePart(overrides: {};}+describe("coalesceDeliveries", () => {+ const caller = {+ callId: "call-1",+ replyTo: { kind: "hook" as const, token: "turn-caller" },+ subagentName: "research",+ };++ it("preserves the only caller in a delivery batch", () => {+ expect(+ coalesceDeliveries([+ { kind: "deliver", payloads: [{ context: ["background"] }] },+ { caller, kind: "deliver", payloads: [{ message: "question" }] },+ ]),+ ).toEqual({+ caller,+ kind: "deliver",+ payloads: [{ context: ["background"] }, { message: "question" }],+ });+ });++ it("rejects a batch with more than one turn caller", () => {+ expect(() =>+ coalesceDeliveries([+ { caller, kind: "deliver", payloads: [{ message: "first" }] },+ {+ caller: { ...caller, callId: "call-2" },+ kind: "deliver",+ payloads: [{ message: "second" }],+ },+ ]),+ ).toThrow("Cannot coalesce deliveries from different turns.");+ });+});+describe("coalesceTurnInputs", () => {it("joins two messages with a double newline", () => {const result = coalesceTurnInputs({ message: "hello" }, { message: "world" });diff --git a/packages/eve/src/harness/messages.ts b/packages/eve/src/harness/messages.tsindex a70a6c9ef..2479fdb3a 100644--- a/packages/eve/src/harness/messages.ts+++ b/packages/eve/src/harness/messages.ts@@ -1,6 +1,6 @@import type { ModelMessage, TextPart, UserContent } from "ai";-import type { DeliverPayload, SessionAuthContext } from "#channel/types.js";+import type { DeliverPayload, SessionAuthContext, TurnCaller } from "#channel/types.js";import type { InputResponse } from "#runtime/input/types.js";import type { StepInput } from "#harness/types.js";@@ -215,6 +215,7 @@ function toUserContentArray(value: string | UserContent): UserContentArray {*/interface DeliverLike {readonly auth?: SessionAuthContext | null;+ readonly caller?: TurnCaller;readonly kind: "deliver";readonly payloads: readonly DeliverPayload[];}@@ -226,7 +227,8 @@ interface DeliverLike {* Used by the workflow runtime to batch follow-up deliveries that* arrived while a turn or subagent delegation was in progress. Each* payload is later passed to `onDeliver` individually so channel-- * specific fields are never lost.+ * specific fields are never lost. A caller defines a turn boundary, so+ * callers must be partitioned before coalescing.*/export function coalesceDeliveries<T extends DeliverLike>(items: readonly T[]): T {const [first, ...rest] = items;@@ -236,14 +238,21 @@ export function coalesceDeliveries<T extends DeliverLike>(items: readonly T[]):}let auth = first.auth;+ let caller = first.caller;const payloads = [...first.payloads];for (const item of rest) {if (item.auth !== undefined) {auth = item.auth;}+ if (item.caller !== undefined) {+ if (caller !== undefined) {+ throw new Error("Cannot coalesce deliveries from different turns.");+ }+ caller = item.caller;+ }payloads.push(...item.payloads);}- return { ...first, auth, payloads };+ return { ...first, auth, caller, payloads };}diff --git a/packages/eve/src/harness/runtime-actions.test.ts b/packages/eve/src/harness/runtime-actions.test.tsindex 7a719b7a7..89241038f 100644--- a/packages/eve/src/harness/runtime-actions.test.ts+++ b/packages/eve/src/harness/runtime-actions.test.ts@@ -12,13 +12,23 @@ import {} from "#harness/runtime-actions.js";import { deriveAgentOperationId } from "#harness/handles/operation-id.js";import { deriveAgentId, getAgentHandleStore } from "#harness/handles/store.js";-import { confirmAgentStarted, prepareAgentStart } from "#harness/handles/transitions.js";+import {+ confirmAgentStarted,+ prepareAgentContinuation,+ prepareAgentStart,+} from "#harness/handles/transitions.js";import { getProxyInputRequests, upsertProxyInputRequests } from "#harness/proxy-input-requests.js";import { getSessionTokenUsage, setTurnUsageState } from "#harness/turn-tag-state.js";import type { HarnessSession } from "#harness/types.js";const CHILD_SESSION_ID = "local-child-123456789012";const CHILD_CONTINUATION_TOKEN = "subagent:private-token";+const ZERO_USAGE = {+ cacheReadTokens: 0,+ cacheWriteTokens: 0,+ inputTokens: 0,+ outputTokens: 0,+} as const;const OPERATION_ID = deriveAgentOperationId({callId: "call-1",parentSessionId: "test-session",@@ -104,6 +114,11 @@ describe("resolvePendingRuntimeActions", () => {callId: "call-1",kind: "subagent-result",origin: "child",+ outcome: {+ kind: "terminal",+ result: { kind: "succeeded", output: "done" },+ usageDelta: ZERO_USAGE,+ },output: "done",subagentName: "researcher",},@@ -128,6 +143,14 @@ describe("resolvePendingRuntimeActions", () => {isError: true,kind: "subagent-result",origin: "child",+ outcome: {+ kind: "terminal",+ result: {+ error: { code: "SESSION_FAILED", message: "child failed" },+ kind: "failed",+ },+ usageDelta: ZERO_USAGE,+ },output: { code: "SESSION_FAILED", message: "child failed" },subagentName: "researcher",},@@ -156,6 +179,11 @@ describe("resolvePendingRuntimeActions", () => {callId: "call-1",kind: "subagent-result",origin: "child",+ outcome: {+ kind: "terminal",+ result: { kind: "succeeded", output: "done" },+ usageDelta: ZERO_USAGE,+ },output: "done",subagentName: "researcher",},@@ -199,6 +227,16 @@ describe("resolvePendingRuntimeActions", () => {callId: "call-1",kind: "subagent-result",origin: "child",+ outcome: {+ kind: "terminal",+ result: { kind: "succeeded", output: "done" },+ usageDelta: {+ cacheReadTokens: 10,+ cacheWriteTokens: 5,+ inputTokens: 4_000,+ outputTokens: 400,+ },+ },output: "done",subagentName: "researcher",usage: {@@ -219,7 +257,228 @@ describe("resolvePendingRuntimeActions", () => {});});- it("leaves the parent's totals untouched when the child reports no usage", async () => {+ it("keeps a parked handle resumable — even for a failed turn — and deletes a terminal one", async () => {+ const session = createSessionWithRunningChild();+ const agentId = deriveAgentId("researcher", OPERATION_ID);++ const parkedResolve = await resolvePendingRuntimeActions({+ session,+ stepInput: {+ runtimeActionResults: [+ {+ callId: "call-1",+ isError: true,+ kind: "subagent-result",+ origin: "child",+ outcome: {+ kind: "parked",+ result: {+ error: { code: "SUBAGENT_EXECUTION_FAILED", message: "schema not fulfilled" },+ kind: "failed",+ },+ usageDelta: {+ cacheReadTokens: 0,+ cacheWriteTokens: 0,+ inputTokens: 0,+ outputTokens: 0,+ },+ },+ output: { code: "SUBAGENT_EXECUTION_FAILED", message: "schema not fulfilled" },+ subagentName: "researcher",+ },+ ],+ },+ });++ expect(parkedResolve.outcome).toBe("resolved");+ expect(getAgentHandleStore(parkedResolve.session.state)?.handles).toEqual([+ expect.objectContaining({ phase: "parked" }),+ ]);++ // The parked handle stays resumable: a continuation prepares cleanly.+ const continueOperationId = deriveAgentOperationId({+ callId: "call-2",+ parentSessionId: "test-session",+ parentTurnId: "turn_1",+ });+ const continued = prepareAgentContinuation(parkedResolve.session, {+ agentId,+ invokedName: "researcher",+ operation: {+ callId: "call-2",+ id: continueOperationId,+ kind: "continue",+ parentTurnId: "turn_1",+ previousStatus: "",+ },+ });+ expect(continued.kind).toBe("ready");+ if (continued.kind !== "ready") throw new Error("expected ready continuation");++ // A terminal failure on the follow-up turn deletes the handle.+ const secondBatch = setPendingRuntimeActionBatch({+ actions: [+ {+ callId: "call-2",+ description: "research subagent",+ input: { agentId, message: "continue" },+ kind: "subagent-call",+ name: "researcher",+ nodeId: "subagents/researcher",+ subagentName: "researcher",+ },+ ],+ event: { sequence: 1, stepIndex: 0, turnId: "turn_1" },+ responseMessages: [],+ session: continued.session,+ });+ const terminalResolve = await resolvePendingRuntimeActions({+ session: secondBatch,+ stepInput: {+ runtimeActionResults: [+ {+ callId: "call-2",+ isError: true,+ kind: "subagent-result",+ origin: "child",+ outcome: {+ kind: "terminal",+ result: {+ error: { code: "SUBAGENT_EXECUTION_FAILED", message: "child crashed" },+ kind: "failed",+ },+ usageDelta: {+ cacheReadTokens: 0,+ cacheWriteTokens: 0,+ inputTokens: 0,+ outputTokens: 0,+ },+ },+ output: { code: "SUBAGENT_EXECUTION_FAILED", message: "child crashed" },+ subagentName: "researcher",+ },+ ],+ },+ });++ expect(terminalResolve.outcome).toBe("resolved");+ expect(getAgentHandleStore(terminalResolve.session.state)).toEqual({ handles: [] });+ });++ it("folds each turn's usage delta once so a two-turn child never double-counts", async () => {+ // Turn 1: the child spent 4000/400 and parked.+ const session = createSessionWithRunningChild();+ const agentId = deriveAgentId("researcher", OPERATION_ID);+ const firstResolve = await resolvePendingRuntimeActions({+ session,+ stepInput: {+ runtimeActionResults: [+ {+ callId: "call-1",+ kind: "subagent-result",+ origin: "child",+ outcome: {+ kind: "parked",+ result: { kind: "succeeded", output: "first answer" },+ usageDelta: {+ cacheReadTokens: 0,+ cacheWriteTokens: 0,+ inputTokens: 4_000,+ outputTokens: 400,+ },+ },+ output: "first answer",+ subagentName: "researcher",+ // Cumulative child-session totals: folding these instead of the+ // delta would double-count turn 1 on the next settlement.+ usage: {+ cacheReadTokens: 0,+ cacheWriteTokens: 0,+ inputTokens: 4_000,+ outputTokens: 400,+ },+ },+ ],+ },+ });+ expect(getSessionTokenUsage(firstResolve.session)).toMatchObject({+ inputTokens: 5_000,+ outputTokens: 500,+ });++ // Turn 2: the child spent another 1000/100 (cumulative 5000/500).+ const continued = prepareAgentContinuation(firstResolve.session, {+ agentId,+ invokedName: "researcher",+ operation: {+ callId: "call-2",+ id: deriveAgentOperationId({+ callId: "call-2",+ parentSessionId: "test-session",+ parentTurnId: "turn_1",+ }),+ kind: "continue",+ parentTurnId: "turn_1",+ previousStatus: "",+ },+ });+ if (continued.kind !== "ready") throw new Error("expected ready continuation");+ const secondBatch = setPendingRuntimeActionBatch({+ actions: [+ {+ callId: "call-2",+ description: "research subagent",+ input: { agentId, message: "continue" },+ kind: "subagent-call",+ name: "researcher",+ nodeId: "subagents/researcher",+ subagentName: "researcher",+ },+ ],+ event: { sequence: 1, stepIndex: 0, turnId: "turn_1" },+ responseMessages: [],+ session: continued.session,+ });+ const secondResolve = await resolvePendingRuntimeActions({+ session: secondBatch,+ stepInput: {+ runtimeActionResults: [+ {+ callId: "call-2",+ kind: "subagent-result",+ origin: "child",+ outcome: {+ kind: "parked",+ result: { kind: "succeeded", output: "second answer" },+ usageDelta: {+ cacheReadTokens: 0,+ cacheWriteTokens: 0,+ inputTokens: 1_000,+ outputTokens: 100,+ },+ },+ output: "second answer",+ subagentName: "researcher",+ usage: {+ cacheReadTokens: 0,+ cacheWriteTokens: 0,+ inputTokens: 5_000,+ outputTokens: 500,+ },+ },+ ],+ },+ });++ // Own 1000/100 + turn deltas (4000+1000)/(400+100) — never the child's+ // cumulative 5000/500 twice.+ expect(getSessionTokenUsage(secondResolve.session)).toMatchObject({+ inputTokens: 6_000,+ outputTokens: 600,+ });+ });++ it("leaves the parent's totals untouched when the child reports a zero usage delta", async () => {const session = createSessionWithRunningChild();const resolved = await resolvePendingRuntimeActions({@@ -230,6 +489,11 @@ describe("resolvePendingRuntimeActions", () => {callId: "call-1",kind: "subagent-result",origin: "child",+ outcome: {+ kind: "terminal",+ result: { kind: "succeeded", output: "done" },+ usageDelta: ZERO_USAGE,+ },output: "done",subagentName: "researcher",},@@ -250,6 +514,11 @@ describe("result-to-handle binding", () => {callId: "call-1",kind: "subagent-result",origin: "child",+ outcome: {+ kind: "terminal",+ result: { kind: "succeeded", output: "done" },+ usageDelta: ZERO_USAGE,+ },output: "done",subagentName: "researcher",} as const;diff --git a/packages/eve/src/harness/runtime-actions.ts b/packages/eve/src/harness/runtime-actions.tsindex 14893d05b..398f6ac5b 100644--- a/packages/eve/src/harness/runtime-actions.ts+++ b/packages/eve/src/harness/runtime-actions.ts@@ -5,7 +5,7 @@ import { getRuntimeActionRequestKey } from "#runtime/actions/keys.js";import { resolveRuntimeActionResultsForKeys } from "#runtime/actions/results.js";import type { RuntimeActionRequest, RuntimeActionResult } from "#runtime/actions/types.js";import { parseJsonObject, type JsonObject } from "#shared/json.js";-import type { TokenUsage } from "#shared/token-usage.js";+import type { AgentTurnOutcome } from "#shared/agent-turn-outcome.js";import { findRunningAgentHandle, isResultBoundToRunningHandle } from "#harness/handles/query.js";import { settleAgentTurn } from "#harness/handles/transitions.js";import { clearProxyInputRequestsForChild } from "#harness/proxy-input-requests.js";@@ -26,22 +26,15 @@ const PENDING_RUNTIME_ACTION_BATCH_KEY = "eve.runtime.pendingActionBatch";type ToolResponsePart = Extract<ModelMessage, { role: "tool" }>["content"][number];type ToolResultPart = Extract<ToolResponsePart, { type: "tool-result" }>;-const ZERO_TOKEN_USAGE: TokenUsage = {- cacheReadTokens: 0,- cacheWriteTokens: 0,- inputTokens: 0,- outputTokens: 0,-};-/**- * Usage from a subagent result. Only `child`-origin results carry usage;- * parent-synthesized dispatch failures never do, and their type omits the- * field entirely.+ * Lifecycle outcome from a subagent result. Only `child`-origin results+ * carry one; parent-synthesized dispatch failures never do, and their type+ * omits the field entirely.*/-function readSubagentResultUsage(+function readSubagentResultOutcome(result: Extract<RuntimeActionResult, { kind: "subagent-result" }>,-): TokenUsage | undefined {- return result.origin === "child" ? result.usage : undefined;+): AgentTurnOutcome | undefined {+ return result.origin === "child" ? result.outcome : undefined;}/**@@ -231,10 +224,11 @@ export async function resolvePendingRuntimeActions(input: {}}- // Settle each bound child result against its running handle. Task-mode- // children are always terminal, so every settled handle is deleted; the- // proxy-input entry keyed by the child's continuation token is cleared- // first (the handle is the only record of that token) so future+ // Settle each bound child result against its running handle from the+ // outcome the child engine reported: `parked` keeps the handle (the child+ // is idle and resumable), `terminal` deletes it. Before a terminal+ // deletion the proxy-input entry keyed by the child's continuation token+ // is cleared (the handle is the only record of that token) so future// deliveries don't route responses to a dead child.let nextSession: HarnessSession = input.session;for (const result of readyResults) {@@ -247,19 +241,16 @@ export async function resolvePendingRuntimeActions(input: {if (handle === undefined) {continue;}- if (handle.address.continuationToken !== undefined) {+ const outcome = readSubagentResultOutcome(result);+ if (outcome === undefined) {+ continue;+ }+ if (outcome.kind === "terminal" && handle.address.continuationToken !== undefined) {nextSession = clearProxyInputRequestsForChild(nextSession, handle.address.continuationToken);}const settled = settleAgentTurn(nextSession, {operationId: handle.operation.id,- outcome: {- kind: "terminal",- result:- result.isError === true- ? { error: result.output, kind: "failed" }- : { kind: "succeeded", output: result.output },- usageDelta: result.usage ?? ZERO_TOKEN_USAGE,- },+ outcome,});if (settled.kind === "settled") {nextSession = settled.session;@@ -273,24 +264,26 @@ export async function resolvePendingRuntimeActions(input: {state: Object.keys(state).length > 0 ? state : undefined,};- // Draw completed child spend down against the parent's session totals so+ // Draw settled child spend down against the parent's session totals so// the session token limits and the remaining-quota budget granted to later- // delegations account for what the tree has already spent. Only- // child-produced results carry usage; parent-side dispatch failures- // never do.+ // delegations account for what the tree has already spent. Every outcome+ // carries the child turn's `usageDelta`, folded exactly once per settled+ // result (each batch resolves once), so repeated turns of a persistent+ // child never double-count earlier turns. Only child-produced results+ // carry an outcome; parent-side dispatch failures never do.for (const result of readyResults) {if (result.kind !== "subagent-result") {continue;}- const usage = readSubagentResultUsage(result);- if (usage === undefined) {+ const outcome = readSubagentResultOutcome(result);+ if (outcome === undefined) {continue;}nextSession = setTurnUsageState(nextSession,accumulateSessionUsage({previous: getTurnUsageState(nextSession.state),- usage,+ usage: outcome.usageDelta,}),);}diff --git a/packages/eve/src/harness/tool-loop.test.ts b/packages/eve/src/harness/tool-loop.test.tsindex a6c182d39..bbfe76275 100644--- a/packages/eve/src/harness/tool-loop.test.ts+++ b/packages/eve/src/harness/tool-loop.test.ts@@ -1390,6 +1390,7 @@ describe("createToolLoopHarness", () => {expect(vi.mocked(ToolLoopAgent)).not.toHaveBeenCalled();expect(result.next).toBeNull();+ expect(result.settledTurn).toBeUndefined();expect(events.map((event) => event.type)).toEqual(["session.started","turn.started",@@ -1746,6 +1747,7 @@ describe("createToolLoopHarness", () => {const result = await runStep(session, { message: "Hi" });expect(result.next).toBeNull();+ expect(result.settledTurn).toEqual({ output: { title: "Done" } });expect(getCompatibilityEventTypes(events)).toEqual(["session.started","turn.started",@@ -1900,6 +1902,10 @@ describe("createToolLoopHarness", () => {const result = await runStep(session, { message: "Hi" });expect(result.next).toBeNull();+ expect(result.settledTurn).toEqual({+ isError: true,+ output: "The agent could not produce a result matching the requested schema.",+ });expect(getCompatibilityEventTypes(events)).toEqual(["session.started","turn.started",@@ -2109,6 +2115,7 @@ describe("createToolLoopHarness", () => {const result = await runStep(session, { message: "What's the weather in NY?" });expect(result.next).toBeNull();+ expect(result.settledTurn).toEqual({ output: "It is 41 F in New York right now." });expect(result.session.history).toEqual([{ content: "What's the weather in NY?", role: "user" },{@@ -2316,6 +2323,7 @@ describe("createToolLoopHarness", () => {const result = await runStep(session);expect(result.next).toBeNull();+ expect(result.settledTurn).toEqual({ output: "The result is 42." });expect(result.session.history).toEqual([{ content: "prior message", role: "user" },{ content: "The result is 42.", role: "assistant" },@@ -3668,6 +3676,7 @@ describe("createToolLoopHarness", () => {// session parks (`next: null`) so the user can follow up in the// same thread rather than the whole run being torn down.expect(result.next).toBeNull();+ expect(result.settledTurn).toEqual({ isError: true, output: "Model blew up" });const types = events.map((e) => e.type);expect(types).toContain("session.started");@@ -3783,14 +3792,43 @@ describe("createToolLoopHarness", () => {const { emit, events } = createEventCollector();const runStep = createToolLoopHarness(createTestConfig("task", emit));+ const ctx = new ContextContainer();+ setDelegatedParent(ctx);++ const result = await contextStorage.run(ctx, () =>+ runStep(createTestSession(), { message: "Delegated task" }),+ );++ // The terminal result must be marked as an error with the failure+ // message as output, matching the non-terminal task-mode failure shape.+ expect(result.next).toMatchObject({+ done: true,+ isError: true,+ output: expect.stringContaining("No endpoints found for anthropic/claude-3.5-haiku"),+ });++ const types = events.map((e) => e.type);+ expect(types).toContain("step.failed");+ expect(types).toContain("turn.failed");+ expect(types).toContain("session.failed");+ });- const result = await runStep(createTestSession(), { message: "Delegated task" });+ it("surfaces a terminal model-call error to a delegated conversation caller", async () => {+ const error = Object.assign(new Error("No endpoints found for anthropic/claude-3.5-haiku"), {+ name: "AI_APICallError",+ statusCode: 404,+ });+ setupMockAgentError(error);++ const { emit, events } = createEventCollector();+ const runStep = createToolLoopHarness(createTestConfig("conversation", emit));+ const ctx = new ContextContainer();+ setDelegatedParent(ctx);++ const result = await contextStorage.run(ctx, () =>+ runStep(createTestSession(), { message: "Delegated turn" }),+ );- // The task's terminal result must be marked as an error with the- // failure message as output, mirroring the non-terminal task-mode- // failure shape. Today the terminal branch returns- // `{ done: true, output: "" }`, which the parent driver treats as a- // successful delegation with empty output.expect(result.next).toMatchObject({done: true,isError: true,@@ -5250,6 +5288,7 @@ describe("createToolLoopHarness", () => {);expect(result.next).toBeNull();+ expect(result.settledTurn).toBeUndefined();expect(getPendingAuthorization(result.session.state)).toEqual({challenges: full.challenges,});@@ -5348,6 +5387,7 @@ describe("createToolLoopHarness", () => {);expect(result.next).toBeNull();+ expect(result.settledTurn).toBeUndefined();expect(getPendingAuthorization(result.session.state)).toEqual({challenges: full.challenges,});diff --git a/packages/eve/src/harness/tool-loop.ts b/packages/eve/src/harness/tool-loop.tsindex 2ed3a3919..daae23f32 100644--- a/packages/eve/src/harness/tool-loop.ts+++ b/packages/eve/src/harness/tool-loop.ts@@ -30,7 +30,12 @@ import {} from "#internal/logging.js";import { formatLanguageModelGatewayId } from "#internal/runtime-model.js";import { contextStorage } from "#context/container.js";-import { AuthKey, ParentSessionKey, ParentTraceContextKey } from "#context/keys.js";+import {+ AuthKey,+ ParentSessionKey,+ ParentTraceContextKey,+ SessionCallbackKey,+} from "#context/keys.js";import { buildDynamicInstructionMessages } from "#context/dynamic-instruction-lifecycle.js";import { getActiveDynamicModelSelection } from "#context/dynamic-model-lifecycle.js";import { buildDynamicTools } from "#context/build-dynamic-tools.js";@@ -195,6 +200,7 @@ import type {CompactionConfig,HarnessSession,HarnessToolMap,+ SettledTurn,StepFn,StepInput,StepResult,@@ -784,6 +790,8 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {// Direct harness unit tests may run without an ambient context.const ctx = contextStorage.getStore();+ const hasDelegatedCaller =+ ctx?.get(ParentSessionKey) !== undefined || ctx?.get(SessionCallbackKey) !== undefined;if (ctx !== undefined && config.dispatchDynamicModelEvent !== undefined) {await config.dispatchDynamicModelEvent({ctx,@@ -1361,13 +1369,12 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {message: errorMessage,sessionId: session.sessionId,});- // In task mode (delegated subagent runs) the terminal failure- // must be the task's error result so the parent driver resumes- // with a failed `subagent-result` instead of a successful empty- // output (https://github.com/vercel/eve/issues/412).+ // Delegated runs need a failed terminal result so their caller sees a+ // failed `subagent-result`; top-level conversation failures already+ // emit `session.failed` here.return {next:- config.mode === "task"+ config.mode === "task" || hasDelegatedCaller? { done: true, isError: true, output: taskFailureOutput }: { done: true, output: "" },session,@@ -1421,8 +1428,12 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {details,message: errorMessage,});- const parkedSession = setHarnessEmissionState(session, emissionState);- return { next: null, session: parkedSession };+ const settledTurn = { isError: true, output: taskFailureOutput } satisfies SettledTurn;+ return {+ next: null,+ session: setHarnessEmissionState(session, emissionState),+ settledTurn,+ };}}@@ -2247,6 +2258,7 @@ async function handleStepResult(input: {result,schema: nextSession.outputSchema,session: nextSession,+ stepOutput,});}@@ -2371,8 +2383,9 @@ async function finishConversationTurn(input: {readonly result: HarnessStepResult;readonly schema: JsonObject | undefined;readonly session: HarnessSession;+ readonly stepOutput: string | null;}): Promise<StepResult> {- const { emit, history, result, schema } = input;+ const { emit, history, result, schema, stepOutput } = input;let { emissionState, session } = input;if (schema === undefined) {@@ -2385,7 +2398,8 @@ async function finishConversationTurn(input: {);session = setHarnessEmissionState(session, emissionState);}- return { next: null, session };+ const settledTurn = { output: stepOutput ?? "" } satisfies SettledTurn;+ return { next: null, session, settledTurn };}const structured = extractFinalOutput(result);@@ -2397,7 +2411,11 @@ async function finishConversationTurn(input: {});session = setHarnessEmissionState(session, emissionState);}- return { next: null, session };+ const settledTurn = {+ isError: true,+ output: OUTPUT_SCHEMA_NOT_FULFILLED.message,+ } satisfies SettledTurn;+ return { next: null, session, settledTurn };}session = persistStructuredAssistantTurn(session, history, structured);@@ -2411,7 +2429,8 @@ async function finishConversationTurn(input: {);session = setHarnessEmissionState(session, emissionState);}- return { next: null, session };+ const settledTurn = { output: structured } satisfies SettledTurn;+ return { next: null, session, settledTurn };}/** Replays a parked dynamic workflow with completed child-agent results. */diff --git a/packages/eve/src/harness/turn-tag-state.ts b/packages/eve/src/harness/turn-tag-state.tsindex 5c34c6fd9..9d8051daf 100644--- a/packages/eve/src/harness/turn-tag-state.ts+++ b/packages/eve/src/harness/turn-tag-state.ts@@ -36,6 +36,7 @@ import type { TokenUsage } from "#shared/token-usage.js";export type { SessionRuntimeTokenLimits, SessionTokenLimitViolation };const HARNESS_TURN_USAGE_STATE_KEY = "eve.harness.turnUsage";+const REPORTED_SESSION_USAGE_STATE_KEY = "eve.harness.reportedSessionUsage";const SESSION_RUNTIME_TOKEN_LIMIT_KEY = "eve.harness.sessionRuntimeTokenLimit";export interface TokenUsageTotals {@@ -166,6 +167,43 @@ function configuredSessionTokenLimits(};}+/**+ * Takes the session-usage delta accumulated since the previous take and+ * marks it reported.+ *+ * Persisted on `session.state` (not in step-local memory) so the entry+ * snapshot survives `"use step"` boundaries: the totals at the previous+ * settled turn are the totals at this turn's entry, because a parked child+ * runs no model calls in between. Blocked parks (authorization, queued+ * input) between two settlements never lose usage — the delta always+ * measures everything since the last report, so the deltas of a+ * multi-turn persistent child sum exactly to its session totals.+ */+export function takeSessionUsageDelta(session: HarnessSession): {+ readonly delta: TokenUsage;+ readonly session: HarnessSession;+} {+ const totals = getSessionTokenUsage(session);+ const reported =+ (session.state?.[REPORTED_SESSION_USAGE_STATE_KEY] as TokenUsageTotals | undefined) ??+ ZERO_TOKEN_USAGE;+ return {+ delta: {+ cacheReadTokens: totals.cacheReadTokens - reported.cacheReadTokens,+ cacheWriteTokens: totals.cacheWriteTokens - reported.cacheWriteTokens,+ inputTokens: totals.inputTokens - reported.inputTokens,+ outputTokens: totals.outputTokens - reported.outputTokens,+ },+ session: {+ ...session,+ state: {+ ...session.state,+ [REPORTED_SESSION_USAGE_STATE_KEY]: totals,+ },+ },+ };+}+/** Writes per-turn token state onto a new copy of the session. */export function setTurnUsageState(session: HarnessSession, next: TurnUsageState): HarnessSession {return {diff --git a/packages/eve/src/harness/types.ts b/packages/eve/src/harness/types.tsindex b2edbdf71..570766f4f 100644--- a/packages/eve/src/harness/types.ts+++ b/packages/eve/src/harness/types.ts@@ -172,6 +172,11 @@ export type StepNext = StepDone | StepFn | null;export interface SettledTurn {readonly output: unknown;readonly isError?: boolean;+ /**+ * Usage this turn added to the child's session subtree. The harness never+ * sets it; the durable turn step fills it with the per-turn delta before+ * the answer crosses the park boundary to the delegated caller.+ */readonly usage?: TokenUsage;}@@ -283,8 +288,8 @@ export interface ToolLoopHarnessConfig {readonly onCompaction?: () => readonly ModelMessage[];/*** Whether the agent opted into `experimental.subagentPersistentSessions`.- * Gates the model-visible `<agents>` listing of parked delegated-agent- * handles injected into each model call.+ * Gates delegated-agent handle tracking and the model-visible `<agents>`+ * listing appended after runtime-action batches resolve.*/readonly persistentSubagentSessions?: boolean;readonly dispatchDynamicModelEvent?: (input: {diff --git a/packages/eve/src/public/tool-result-narrowing.test.ts b/packages/eve/src/public/tool-result-narrowing.test.tsindex 1640b42c2..44b513bba 100644--- a/packages/eve/src/public/tool-result-narrowing.test.ts+++ b/packages/eve/src/public/tool-result-narrowing.test.ts@@ -34,6 +34,11 @@ function subagentResult(): RuntimeActionResult {callId: "call_2",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: "sub",};diff --git a/packages/eve/src/runtime/actions/keys.test.ts b/packages/eve/src/runtime/actions/keys.test.tsindex 1046dd036..18f37654b 100644--- a/packages/eve/src/runtime/actions/keys.test.ts+++ b/packages/eve/src/runtime/actions/keys.test.ts@@ -29,6 +29,11 @@ describe("runtime action keys", () => {callId: "call_2",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: "reviewer",}),diff --git a/packages/eve/src/runtime/actions/types.ts b/packages/eve/src/runtime/actions/types.tsindex bab7c1a21..aea8964e3 100644--- a/packages/eve/src/runtime/actions/types.ts+++ b/packages/eve/src/runtime/actions/types.ts@@ -1,5 +1,6 @@import { z } from "#compiled/zod/index.js";+import { agentTurnOutcomeSchema } from "#shared/agent-turn-outcome.js";import { jsonObjectSchema, jsonValueSchema } from "#shared/json-schemas.js";import { tokenUsageSchema } from "#shared/token-usage.js";@@ -135,8 +136,16 @@ const runtimeToolResultActionResultSchema = z* dispatch window a replay-orphaned duplicate child holds the same token* and callId and may settle the call in place of the owned child — its* output is computed from the same input, and this is an accepted- * trade-off, not an oversight. `usage` carries the completed child- * session's token totals so the caller can attribute the subagent's spend.+ * trade-off, not an oversight.+ *+ * `outcome` is the child engine's explicit lifecycle verdict for the settled+ * turn. The parent settles the agent handle from `outcome.kind` and folds+ * `outcome.usageDelta` into its session totals; `output`/`isError` remain+ * the tool-result projection shown to the model. Every producer states the+ * envelope explicitly — task-mode boundaries synthesize a terminal one —+ * so the parent never infers lifecycle from an absent field. `usage`+ * carries the turn's token spend so the caller can attribute the+ * subagent's tokens.*/export type RuntimeSubagentChildResult = z.infer<typeof runtimeSubagentChildResultSchema>;@@ -149,6 +158,7 @@ const runtimeSubagentChildResultSchema = zisError: z.boolean().optional(),kind: z.literal("subagent-result"),origin: z.literal("child"),+ outcome: agentTurnOutcomeSchema,output: jsonValueSchema,subagentName: z.string(),usage: tokenUsageSchema.optional(),diff --git a/packages/eve/src/runtime/session-callback-route.test.ts b/packages/eve/src/runtime/session-callback-route.test.tsindex 211b795b8..62aaa7444 100644--- a/packages/eve/src/runtime/session-callback-route.test.ts+++ b/packages/eve/src/runtime/session-callback-route.test.ts@@ -36,7 +36,7 @@ describe("session callback route", () => {expect([...names].some((name) => name.startsWith(".well-known/"))).toBe(false);});- it("resumes a completed remote-agent result", async () => {+ it("synthesizes a terminal outcome envelope for session.completed", async () => {resumeHookMock.mockResolvedValue(undefined);const response = await handleSessionCallbackRequest(@@ -61,6 +61,16 @@ describe("session callback route", () => {callId: "call-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: "research",},@@ -92,6 +102,16 @@ describe("session callback route", () => {callId: "call-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: "research",},@@ -99,9 +119,54 @@ describe("session callback route", () => {});});- it("projects reported usage onto the resumed result", async () => {+ it("synthesizes a terminal failed outcome for session.failed", async () => {resumeHookMock.mockResolvedValue(undefined);+ const error = { code: "REMOTE_AGENT_FAILED", message: "remote crashed" };+ const response = await handleSessionCallbackRequest(+ new Request("https://app.example.com/eve/v1/callback/tok123", {+ body: JSON.stringify({+ callId: "call-1",+ error,+ kind: "session.failed",+ sessionId: "remote-session",+ subagentName: "research",+ }),+ method: "POST",+ }),+ createRouteContext({ token: "tok123" }),+ );++ expect(response.status).toBe(202);+ expect(resumeHookMock).toHaveBeenCalledWith("tok123", {+ kind: "runtime-action-result",+ results: [+ {+ callId: "call-1",+ isError: true,+ kind: "subagent-result",+ origin: "child",+ outcome: {+ kind: "terminal",+ result: { error, kind: "failed" },+ usageDelta: {+ cacheReadTokens: 0,+ cacheWriteTokens: 0,+ inputTokens: 0,+ outputTokens: 0,+ },+ },+ output: error,+ subagentName: "research",+ },+ ],+ });+ });++ it("projects reported usage onto the resumed result and its outcome delta", async () => {+ resumeHookMock.mockResolvedValue(undefined);++ const usage = { cacheReadTokens: 10, cacheWriteTokens: 5, inputTokens: 100, outputTokens: 50 };const response = await handleSessionCallbackRequest(new Request("https://app.example.com/eve/v1/callback/tok123", {body: JSON.stringify({@@ -110,7 +175,7 @@ describe("session callback route", () => {output: "done",sessionId: "remote-session",subagentName: "research",- usage: { cacheReadTokens: 10, cacheWriteTokens: 5, inputTokens: 100, outputTokens: 50 },+ usage,}),method: "POST",}),@@ -125,9 +190,14 @@ describe("session callback route", () => {callId: "call-1",kind: "subagent-result",origin: "child",+ outcome: {+ kind: "terminal",+ result: { kind: "succeeded", output: "done" },+ usageDelta: usage,+ },output: "done",subagentName: "research",- usage: { cacheReadTokens: 10, cacheWriteTokens: 5, inputTokens: 100, outputTokens: 50 },+ usage,},],});@@ -200,6 +270,16 @@ describe("session callback route", () => {callId: "call-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: "research",},@@ -207,14 +287,20 @@ describe("session callback route", () => {});});- it("projects a completed conversation turn like a completed task session", async () => {+ it("resumes a completed conversation turn with its outcome envelope", async () => {resumeHookMock.mockResolvedValue(undefined);+ const outcome = {+ kind: "parked",+ result: { kind: "succeeded", output: "next result" },+ usageDelta: { cacheReadTokens: 0, cacheWriteTokens: 0, inputTokens: 25, outputTokens: 10 },+ };const response = await handleSessionCallbackRequest(new Request("https://app.example.com/eve/v1/callback/tok123", {body: JSON.stringify({callId: "call-2",kind: "turn.completed",+ outcome,output: "next result",sessionId: "remote-session",subagentName: "research",@@ -232,25 +318,53 @@ describe("session callback route", () => {callId: "call-2",kind: "subagent-result",origin: "child",+ outcome,output: "next result",subagentName: "research",+ usage: outcome.usageDelta,},],});});- it("resumes a failed conversation turn as an error result", async () => {+ it("rejects a turn callback without an outcome envelope", async () => {+ const response = await handleSessionCallbackRequest(+ new Request("https://app.example.com/eve/v1/callback/tok123", {+ body: JSON.stringify({+ callId: "call-2",+ kind: "turn.completed",+ output: "next result",+ sessionId: "remote-session",+ subagentName: "research",+ }),+ method: "POST",+ }),+ createRouteContext({ token: "tok123" }),+ );++ expect(response.status).toBe(400);+ expect(resumeHookMock).not.toHaveBeenCalled();+ });++ it("resumes a failed conversation turn as an error result carrying its outcome", async () => {resumeHookMock.mockResolvedValue(undefined);+ const error = {+ code: "SUBAGENT_EXECUTION_FAILED",+ message: "remote failed",+ };+ const outcome = {+ kind: "terminal",+ result: { error, kind: "failed" },+ usageDelta: { cacheReadTokens: 0, cacheWriteTokens: 0, inputTokens: 0, outputTokens: 0 },+ };const response = await handleSessionCallbackRequest(new Request("https://app.example.com/eve/v1/callback/tok123", {body: JSON.stringify({callId: "call-2",- error: {- code: "SUBAGENT_EXECUTION_FAILED",- message: "remote failed",- },+ error,kind: "turn.failed",+ outcome,sessionId: "remote-session",subagentName: "research",}),@@ -268,10 +382,8 @@ describe("session callback route", () => {isError: true,kind: "subagent-result",origin: "child",- output: {- code: "SUBAGENT_EXECUTION_FAILED",- message: "remote failed",- },+ outcome,+ output: error,subagentName: "research",},],diff --git a/packages/eve/src/runtime/session-callback-route.ts b/packages/eve/src/runtime/session-callback-route.tsindex 13342fe0d..a5f9e6ae9 100644--- a/packages/eve/src/runtime/session-callback-route.ts+++ b/packages/eve/src/runtime/session-callback-route.ts@@ -4,6 +4,7 @@ import { EVE_CALLBACK_ROUTE_PATTERN } from "#protocol/routes.js";import type { ChannelMethod, RouteContext } from "#public/definitions/channel.js";import type { ResolvedChannelDefinition } from "#runtime/types.js";import type { RuntimeSubagentChildResult } from "#runtime/actions/types.js";+import { agentTurnOutcomeSchema, type AgentTurnOutcome } from "#shared/agent-turn-outcome.js";import type { JsonValue } from "#shared/json.js";import { tokenUsageSchema, type TokenUsage } from "#shared/token-usage.js";@@ -11,6 +12,13 @@ export const HTTP_SESSION_CALLBACK_CHANNEL_NAME_PREFIX = "eve/v1/callback";const HANDLED_METHODS: readonly ChannelMethod[] = ["POST"];+const ZERO_TOKEN_USAGE: TokenUsage = {+ cacheReadTokens: 0,+ cacheWriteTokens: 0,+ inputTokens: 0,+ outputTokens: 0,+};+/*** Wire payload of the child→parent callback route. Possession of the* callback token is the authorization to settle; results bind to the@@ -38,15 +46,16 @@ type SessionCallbackPayload =| {readonly callId: string;readonly kind: "turn.completed";+ readonly outcome: AgentTurnOutcome;readonly output: JsonValue;readonly sessionId?: string;readonly subagentName: string;- readonly usage?: TokenUsage;}| {readonly callId: string;readonly error: JsonValue;readonly kind: "turn.failed";+ readonly outcome: AgentTurnOutcome;readonly sessionId?: string;readonly subagentName: string;};@@ -121,44 +130,84 @@ function projectSessionCallbackResult(value: unknown): RuntimeSubagentChildResulif (typeof payload.subagentName !== "string" || payload.subagentName.length === 0) {return Response.json({ error: "Missing callback subagentName.", ok: false }, { status: 400 });}- if (payload.kind === "session.completed" || payload.kind === "turn.completed") {+ // Task-session terminal callbacks carry no outcome envelope on the wire;+ // this boundary synthesizes the terminal verdict (a task session always+ // ends with its result) so the parent settles from an explicit outcome.+ if (payload.kind === "session.completed") {+ const output = payload.output ?? "";+ const usage = parseCallbackUsage((payload as { usage?: unknown }).usage);const base: RuntimeSubagentChildResult = {callId: payload.callId,kind: "subagent-result",origin: "child",- output: payload.output ?? "",+ outcome: {+ kind: "terminal",+ result: { kind: "succeeded", output },+ usageDelta: usage ?? ZERO_TOKEN_USAGE,+ },+ output,subagentName: payload.subagentName,};- const usage = parseCallbackUsage((payload as { usage?: unknown }).usage);return usage === undefined ? base : { ...base, usage };}if (payload.kind === "session.failed") {+ const error: JsonValue =+ payload.error === undefined+ ? {+ code: REMOTE_AGENT_FAILED,+ message: "Remote agent failed.",+ }+ : payload.error;+ const usage = parseCallbackUsage((payload as { usage?: unknown }).usage);return {callId: payload.callId,isError: true,kind: "subagent-result",origin: "child",- output:- payload.error === undefined- ? {- code: REMOTE_AGENT_FAILED,- message: "Remote agent failed.",- }- : payload.error,+ outcome: {+ kind: "terminal",+ result: { error, kind: "failed" },+ usageDelta: usage ?? ZERO_TOKEN_USAGE,+ },+ output: error,+ subagentName: payload.subagentName,+ };+ }++ if (payload.kind === "turn.completed") {+ const outcome = parseCallbackOutcome((payload as { outcome?: unknown }).outcome);+ if (outcome instanceof Response) {+ return outcome;+ }+ const result: RuntimeSubagentChildResult = {+ callId: payload.callId,+ kind: "subagent-result",+ origin: "child",+ outcome,+ output: payload.output ?? "",subagentName: payload.subagentName,+ // Per-result usage projection (usage spans); the parent folds+ // `outcome.usageDelta`, never this field, when an outcome is present.+ usage: outcome.usageDelta,};+ return result;}if (payload.kind === "turn.failed") {if (payload.error === undefined) {return Response.json({ error: "Missing callback error.", ok: false }, { status: 400 });}+ const outcome = parseCallbackOutcome((payload as { outcome?: unknown }).outcome);+ if (outcome instanceof Response) {+ return outcome;+ }return {callId: payload.callId,isError: true,kind: "subagent-result",origin: "child",+ outcome,output: payload.error,subagentName: payload.subagentName,};@@ -167,6 +216,23 @@ function projectSessionCallbackResult(value: unknown): RuntimeSubagentChildResulreturn Response.json({ error: "Unsupported callback kind.", ok: false }, { status: 400 });}+/**+ * Turn callbacks must carry the explicit {@link AgentTurnOutcome} envelope:+ * the receiving parent settles the child's handle from `outcome.kind`, so+ * a turn callback that cannot state its lifecycle is rejected rather than+ * guessed at (pre-1.0: no wire compatibility shims).+ */+function parseCallbackOutcome(value: unknown): AgentTurnOutcome | Response {+ const parsed = agentTurnOutcomeSchema.safeParse(value);+ if (!parsed.success) {+ return Response.json(+ { error: "Missing or invalid callback outcome.", ok: false },+ { status: 400 },+ );+ }+ return parsed.data;+}+/*** TokenUsage arrives from a remote callee that may run a different eve version,* so it is validated independently and dropped — never rejected — when