Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat(eve): own delegated children through the agent-handle lifecycle (#1329)

Rui702f37dba23a
diff --git a/packages/eve/extension-contracts/compatibility/dynamicInstructions/v4.ts b/packages/eve/extension-contracts/compatibility/dynamicInstructions/v4.ts
new file mode 100644
index 000000000..e0433660b
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/dynamicInstructions/v4.ts
@@ -0,0 +1,10 @@
+import { defineDynamic, defineInstructions } from "#public/instructions/index.js";
+
+export default defineDynamic({
+ events: {
+ "session.started": () =>
+ defineInstructions({
+ markdown: "Answer with evidence from the current session.",
+ }),
+ },
+});
diff --git a/packages/eve/extension-contracts/compatibility/dynamicSkill/v4.ts b/packages/eve/extension-contracts/compatibility/dynamicSkill/v4.ts
new file mode 100644
index 000000000..942404504
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/dynamicSkill/v4.ts
@@ -0,0 +1,11 @@
+import { defineDynamic, defineSkill } from "#public/skills/index.js";
+
+export default defineDynamic({
+ events: {
+ "session.started": () =>
+ defineSkill({
+ description: "Triage incoming requests.",
+ markdown: "# Triage\n\nInspect the request before acting.",
+ }),
+ },
+});
diff --git a/packages/eve/extension-contracts/compatibility/dynamicTool/v7.ts b/packages/eve/extension-contracts/compatibility/dynamicTool/v7.ts
new file mode 100644
index 000000000..624876617
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/dynamicTool/v7.ts
@@ -0,0 +1,12 @@
+import { defineDynamic, defineTool } from "#public/tools/index.js";
+
+export default defineDynamic({
+ events: {
+ "session.started": () =>
+ defineTool({
+ description: "Return the current status.",
+ inputSchema: { type: "object", properties: {} },
+ execute: () => ({ status: "ready" }),
+ }),
+ },
+});
diff --git a/packages/eve/extension-contracts/compatibility/hook/v5.ts b/packages/eve/extension-contracts/compatibility/hook/v5.ts
new file mode 100644
index 000000000..98cd2e775
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/hook/v5.ts
@@ -0,0 +1,12 @@
+import { defineHook } from "#public/hooks/index.js";
+
+export default defineHook({
+ events: {
+ "input.requested"(event) {
+ console.info(
+ "input requested",
+ event.data.requests.map((request) => request.requestId),
+ );
+ },
+ },
+});
diff --git a/packages/eve/extension-contracts/compatibility/tool/v3.ts b/packages/eve/extension-contracts/compatibility/tool/v3.ts
new file mode 100644
index 000000000..801d59638
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/tool/v3.ts
@@ -0,0 +1,19 @@
+import { defineTool } from "#public/tools/index.js";
+
+export default defineTool({
+ description: "Summarize a report for the model",
+ inputSchema: { type: "object", properties: {} },
+ async execute(_input, ctx) {
+ return {
+ internal: "details",
+ sessionId: ctx.session.id,
+ summary: "Report generated",
+ };
+ },
+ toModelOutput(output) {
+ return {
+ type: "text",
+ value: (output as { summary: string }).summary,
+ };
+ },
+});
diff --git a/packages/eve/extension-contracts/reports/dynamicInstructions/v5.json b/packages/eve/extension-contracts/reports/dynamicInstructions/v5.json
new file mode 100644
index 000000000..6c7a82a4c
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/dynamicInstructions/v5.json
@@ -0,0 +1,7 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "dynamicInstructions",
+ "epoch": 5,
+ "sha256": "90216e9f30ecc7cc59e68016857d939d48bcb7fce13d3269f905f86ec9c4bbb6",
+ "exports": ["defineDynamic"]
+}
diff --git a/packages/eve/extension-contracts/reports/dynamicSkill/v5.json b/packages/eve/extension-contracts/reports/dynamicSkill/v5.json
new file mode 100644
index 000000000..ba1db3259
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/dynamicSkill/v5.json
@@ -0,0 +1,7 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "dynamicSkill",
+ "epoch": 5,
+ "sha256": "90216e9f30ecc7cc59e68016857d939d48bcb7fce13d3269f905f86ec9c4bbb6",
+ "exports": ["defineDynamic"]
+}
diff --git a/packages/eve/extension-contracts/reports/dynamicTool/v8.json b/packages/eve/extension-contracts/reports/dynamicTool/v8.json
new file mode 100644
index 000000000..b472ea8c7
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/dynamicTool/v8.json
@@ -0,0 +1,13 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "dynamicTool",
+ "epoch": 8,
+ "sha256": "73dcd697085190e5c553a12c61cfe0bf75df1ddeab34b2e1d3c2cffa98b20f47",
+ "exports": [
+ "DynamicToolEntry",
+ "DynamicToolEvents",
+ "DynamicToolResult",
+ "DynamicToolSet",
+ "defineDynamic"
+ ]
+}
diff --git a/packages/eve/extension-contracts/reports/hook/v6.json b/packages/eve/extension-contracts/reports/hook/v6.json
new file mode 100644
index 000000000..d51db94e0
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/hook/v6.json
@@ -0,0 +1,7 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "hook",
+ "epoch": 6,
+ "sha256": "3019784a8cb0e14e6c701f3befedea22745f7bceed9a7537b358a24f2136f54d",
+ "exports": ["defineHook"]
+}
diff --git a/packages/eve/extension-contracts/reports/tool/v4.json b/packages/eve/extension-contracts/reports/tool/v4.json
new file mode 100644
index 000000000..e17f74998
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/tool/v4.json
@@ -0,0 +1,21 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "tool",
+ "epoch": 4,
+ "sha256": "ddfbe9cf0a0dda92f8836f21b664c87e11f0fad6410fe52ff11ac5fab3f87744",
+ "exports": [
+ "defineBashTool",
+ "defineGlobTool",
+ "defineGrepTool",
+ "defineReadFileTool",
+ "defineTool",
+ "defineWriteFileTool",
+ "disableTool",
+ "experimental_workflow",
+ "isDisabledToolSentinel",
+ "isExperimentalWorkflowToolDefinition",
+ "toolOutput",
+ "toolOutputPart",
+ "toolResultFrom"
+ ]
+}
diff --git a/packages/eve/src/channel/routes.ts b/packages/eve/src/channel/routes.ts
index eeb5c91e0..f853c9866 100644
--- a/packages/eve/src/channel/routes.ts
+++ b/packages/eve/src/channel/routes.ts
@@ -7,6 +7,8 @@ import type {
CompactSessionResult,
SessionAuthContext,
SessionCallback,
+ SessionCapabilities,
+ TurnCaller,
} from "#channel/types.js";
import type { InputResponse } from "#runtime/input/types.js";
import type { Session } from "#channel/session.js";
@@ -71,9 +73,8 @@ export interface SendPayload {
/**
* Starts or continues a session on this channel. Accepts a plain string,
- * `UserContent`, or a {@link SendPayload}, plus {@link SendOptions} (auth,
- * continuation token, run mode, and an optional seed `state` for stateful
- * channels). Resolves to the resulting {@link Session}.
+ * `UserContent`, or a {@link SendPayload}, plus {@link SendOptions}. Resolves
+ * to the resulting {@link Session}.
*/
export type SendFn<TState = undefined> = (
input: string | UserContent | SendPayload,
@@ -88,7 +89,15 @@ export type ResolveActiveSessionFn = (options: {
type BaseSendOptions = {
auth: SessionAuthContext | null;
callback?: SessionCallback;
+ /** Framework-internal delegated caller waiting on this turn's settled result. */
+ caller?: TurnCaller;
+ capabilities?: SessionCapabilities;
continuationToken: string;
+ /**
+ * `"resume"` requires an active session and propagates a typed no-active-session
+ * error. `"resume-or-start"` preserves the default channel behavior.
+ */
+ intent?: "resume" | "resume-or-start";
/**
* The original (top-level) caller's auth for a newly started session,
* becoming `session.auth.initiator`. Defaults to {@link auth} when omitted
diff --git a/packages/eve/src/channel/send.test.ts b/packages/eve/src/channel/send.test.ts
index 0db9f50b8..7ebf80cbe 100644
--- a/packages/eve/src/channel/send.test.ts
+++ b/packages/eve/src/channel/send.test.ts
@@ -54,6 +54,22 @@ describe("createSendFn", () => {
warn.mockRestore();
});
+ it("rethrows a typed no-active-session error when resume intent forbids fallback", async () => {
+ const noSession = new RuntimeNoActiveSessionError("test:token");
+ const runtime = createRuntime(noSession);
+
+ const send = createSendFn(runtime, ADAPTER, "test");
+ await expect(
+ send("hello", {
+ auth: null,
+ continuationToken: "token",
+ intent: "resume",
+ }),
+ ).rejects.toBe(noSession);
+
+ expect(runtime.run).not.toHaveBeenCalled();
+ });
+
it("propagates unexpected delivery failures without starting a new session", async () => {
const failure = new Error("boom");
const runtime = createRuntime(failure);
@@ -117,6 +133,38 @@ describe("createSendFn", () => {
});
});
+ it("forwards the turn caller from options onto the deliver input", async () => {
+ const runtime: Runtime = {
+ cancelTurn: vi.fn(),
+ clearSession: vi.fn(),
+ compactSession: vi.fn(),
+ deliver: vi.fn().mockResolvedValue({ sessionId: "existing-session-id" }),
+ resolveSession: vi.fn(),
+ run: vi.fn().mockResolvedValue(createMockRunHandle()),
+ getEventStream: vi.fn().mockResolvedValue(new ReadableStream<MessageStreamEvent>()),
+ getStreamTailIndex: vi.fn().mockResolvedValue(-1),
+ terminateSession: vi.fn(),
+ };
+ const caller = {
+ callId: "call-1",
+ replyTo: { kind: "hook" as const, token: "parent-turn" },
+ subagentName: "research",
+ };
+
+ await createSendFn(
+ runtime,
+ ADAPTER,
+ "test",
+ )({ message: "follow up" }, { auth: null, caller, continuationToken: "token" });
+
+ expect(runtime.deliver).toHaveBeenCalledWith({
+ auth: null,
+ caller,
+ continuationToken: "test:token",
+ payload: expect.not.objectContaining({ caller: expect.anything() }),
+ });
+ });
+
it("adds channel request ids to deliver and run inputs when provided", async () => {
const deliverRuntime: Runtime = {
cancelTurn: vi.fn(),
diff --git a/packages/eve/src/channel/send.ts b/packages/eve/src/channel/send.ts
index 2ed42b423..22dcf6ce0 100644
--- a/packages/eve/src/channel/send.ts
+++ b/packages/eve/src/channel/send.ts
@@ -1,7 +1,7 @@
import type { FilePart, UserContent } from "ai";
import type { ChannelAdapter } from "#channel/adapter.js";
-import type { DeliverInput, RunInput, Runtime, SessionAuthContext } from "#channel/types.js";
+import type { DeliverInput, RunInput, Runtime } from "#channel/types.js";
import { createSession, type Session } from "#channel/session.js";
import type { SendFn, SendOptions, SendPayload } from "#channel/routes.js";
import { isRuntimeNoActiveSessionError } from "#execution/runtime-errors.js";
@@ -17,13 +17,13 @@ export function createSendFn<TState = undefined>(
input: string | UserContent | SendPayload,
options: SendOptions<TState>,
): Promise<Session> => {
- const auth = (options as { auth: SessionAuthContext | null }).auth;
- const initiatorAuth = (options as { initiatorAuth?: SessionAuthContext | null }).initiatorAuth;
- const callback = (options as { callback?: SendOptions<TState>["callback"] }).callback;
- const mode = (options as { mode?: SendOptions<TState>["mode"] }).mode ?? "conversation";
- const state = (options as { state?: TState }).state;
- const title = (options as { title?: string }).title;
- const rawToken = (options as { continuationToken: string }).continuationToken;
+ // `SendOptions<TState>` is conditional on `TState`, so its properties are
+ // not accessible until the generic resolves; widen once to the base shape.
+ const opts = options as SendOptions<undefined> & { readonly state?: TState };
+ const { auth, callback, caller, capabilities, initiatorAuth, state, title } = opts;
+ const intent = opts.intent ?? "resume-or-start";
+ const mode = opts.mode ?? "conversation";
+ const rawToken = opts.continuationToken;
const continuationToken = `${channelName}:${rawToken}`;
const {
@@ -37,6 +37,7 @@ export function createSendFn<TState = undefined>(
try {
const deliverInput: DeliverInput = {
auth,
+ caller,
continuationToken,
requestId: metadata.requestId,
payload: { inputResponses, message, context, outputSchema },
@@ -45,7 +46,9 @@ export function createSendFn<TState = undefined>(
return createSession(sessionId, rawToken, runtime);
} catch (error) {
- if (!isRuntimeNoActiveSessionError(error)) {
+ // A resume-intent miss is an expected protocol outcome; the caller
+ // (e.g. the eve channel's continue route) decides how to surface it.
+ if (!isRuntimeNoActiveSessionError(error) || intent === "resume") {
throw error;
}
}
@@ -65,7 +68,7 @@ export function createSendFn<TState = undefined>(
} = {
adapter: sessionAdapter,
auth,
- capabilities: mode === "conversation" ? { requestInput: true } : undefined,
+ capabilities: capabilities ?? (mode === "conversation" ? { requestInput: true } : undefined),
channelName,
callback,
continuationToken,
diff --git a/packages/eve/src/channel/types.ts b/packages/eve/src/channel/types.ts
index b9e5d2d1c..f6e55bd92 100644
--- a/packages/eve/src/channel/types.ts
+++ b/packages/eve/src/channel/types.ts
@@ -3,7 +3,7 @@ import type { UserContent } from "ai";
import type { UnstampedMessageStreamEvent, MessageStreamEvent } from "#protocol/message.js";
import type { CancelTurnStatus } from "#protocol/cancel-turn.js";
import type { RunMode } from "#shared/run-mode.js";
-import type { RuntimeActionResult } from "#runtime/actions/types.js";
+import type { RuntimeSubagentChildResult } from "#runtime/actions/types.js";
import type { InputRequest, InputResponse } from "#runtime/input/types.js";
import type { ChannelAdapter } from "#channel/adapter.js";
import type { AgentLimitsDefinition } from "#shared/agent-definition.js";
@@ -212,11 +212,14 @@ export interface ClearSessionHookPayload {
}
/**
- * Runtime-action results resumed back into a parked parent workflow.
+ * Child-produced subagent results resumed back into a parked parent workflow.
+ *
+ * The `runtime-action-result` discriminator predates this subagent-only inbox
+ * lane. Parent-produced dispatch results never travel through this hook.
*/
export interface RuntimeActionResultHookPayload {
readonly kind: "runtime-action-result";
- readonly results: readonly RuntimeActionResult[];
+ readonly results: readonly RuntimeSubagentChildResult[];
}
/**
diff --git a/packages/eve/src/client/message-reducer.test.ts b/packages/eve/src/client/message-reducer.test.ts
index fe0886a1c..e8ae7130f 100644
--- a/packages/eve/src/client/message-reducer.test.ts
+++ b/packages/eve/src/client/message-reducer.test.ts
@@ -128,6 +128,7 @@ describe("defaultMessageReducer", () => {
result: {
callId: "call_1",
kind: "subagent-result",
+ origin: "child",
output: { summary: "done" },
subagentName: "research",
},
diff --git a/packages/eve/src/compiler/extension-compatibility.ts b/packages/eve/src/compiler/extension-compatibility.ts
index 093eb5c43..791749c55 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: 3, supported: [1, 2, 3], dropped: {} },
- dynamicTool: { current: 7, supported: [1, 2, 3, 4, 5, 6, 7], dropped: {} },
+ tool: { current: 4, supported: [1, 2, 3, 4], dropped: {} },
+ dynamicTool: { current: 8, supported: [1, 2, 3, 4, 5, 6, 7, 8], dropped: {} },
connection: { current: 2, supported: [1, 2], dropped: {} },
- hook: { current: 5, supported: [1, 2, 3, 4, 5], dropped: {} },
+ hook: { current: 6, supported: [1, 2, 3, 4, 5, 6], dropped: {} },
skill: { current: 1, supported: [1], dropped: {} },
- dynamicSkill: { current: 4, supported: [1, 2, 3, 4], dropped: {} },
+ dynamicSkill: { current: 5, supported: [1, 2, 3, 4, 5], dropped: {} },
instructions: { current: 1, supported: [1], dropped: {} },
- dynamicInstructions: { current: 4, supported: [1, 2, 3, 4], dropped: {} },
+ dynamicInstructions: { current: 5, supported: [1, 2, 3, 4, 5], 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/assertions/run.test.ts b/packages/eve/src/evals/assertions/run.test.ts
index 403b30bb9..e26f07f1e 100644
--- a/packages/eve/src/evals/assertions/run.test.ts
+++ b/packages/eve/src/evals/assertions/run.test.ts
@@ -95,6 +95,7 @@ function failedSubagentResult(input: {
callId: input.callId,
isError: true,
kind: "subagent-result",
+ origin: "dispatch",
output: input.output as never,
subagentName: input.subagentName,
},
diff --git a/packages/eve/src/evals/runner/derive-run-facts.test.ts b/packages/eve/src/evals/runner/derive-run-facts.test.ts
index bc45e5371..805869782 100644
--- a/packages/eve/src/evals/runner/derive-run-facts.test.ts
+++ b/packages/eve/src/evals/runner/derive-run-facts.test.ts
@@ -78,6 +78,7 @@ function subagentResult(input: {
result: {
callId: input.callId,
kind: "subagent-result",
+ origin: "child",
output: input.output as never,
subagentName: input.subagentName,
},
diff --git a/packages/eve/src/execution/agent-handle-dispatch.ts b/packages/eve/src/execution/agent-handle-dispatch.ts
new file mode 100644
index 000000000..d57f5ed9c
--- /dev/null
+++ b/packages/eve/src/execution/agent-handle-dispatch.ts
@@ -0,0 +1,37 @@
+/**
+ * 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.
+ */
+
+import type { AgentAddress } from "#harness/handles/store.js";
+import type { RuntimeSubagentDispatchFailure } from "#runtime/actions/types.js";
+import type { hydrateDurableSession } from "#execution/session.js";
+
+/** Hydrated parent session snapshot threaded through dispatch. */
+export type RuntimeSession = ReturnType<typeof hydrateDurableSession>;
+
+/**
+ * Outcome of dispatching one planned runtime action: an adopted child ready
+ * for the `subagent.called` emission tail, or a per-action error result.
+ * Either way the (possibly updated) session snapshot rides along.
+ *
+ * `address` is the same confirmed {@link AgentAddress} recorded on the
+ * child's running handle; consumers project it into wire shapes (e.g. the
+ * flat `childSessionId` / `remote` fields of `subagent.called`) at the
+ * emission site instead of this type re-encoding them.
+ */
+export type DispatchOutcome =
+ | {
+ readonly address: AgentAddress;
+ readonly callId: string;
+ readonly kind: "called";
+ readonly name: string;
+ readonly session: RuntimeSession;
+ readonly toolName: string;
+ }
+ | {
+ readonly kind: "error";
+ readonly result: RuntimeSubagentDispatchFailure;
+ readonly session: RuntimeSession;
+ };
diff --git a/packages/eve/src/execution/cancel-descendant-turns-step.test.ts b/packages/eve/src/execution/cancel-descendant-turns-step.test.ts
index 2c409f68b..f2e06eb6e 100644
--- a/packages/eve/src/execution/cancel-descendant-turns-step.test.ts
+++ b/packages/eve/src/execution/cancel-descendant-turns-step.test.ts
@@ -9,12 +9,8 @@ import {
resolveRemoteAgentForAction,
} from "#execution/remote-agent-dispatch.js";
import { requestWorkflowTurnCancellation } from "#execution/workflow-runtime.js";
-import {
- recordPendingSubagentChild,
- setPendingRuntimeActionBatch,
-} from "#harness/runtime-actions.js";
+import { AGENT_HANDLES_STATE_KEY, type AgentHandle } from "#harness/handles/store.js";
import type { HarnessSession } from "#harness/types.js";
-import type { RuntimeActionRequest } from "#runtime/actions/types.js";
vi.mock("#context/serialize.js", () => ({
deserializeContext: vi.fn(),
@@ -30,33 +26,55 @@ vi.mock("./remote-agent-dispatch.js", () => ({
resolveRemoteAgentForAction: vi.fn(),
}));
-const localAction = {
- callId: "call-local",
- description: "Delegate locally.",
- input: { message: "work locally" },
- kind: "subagent-call",
- name: "local",
- nodeId: "subagents/local",
- subagentName: "local",
-} satisfies RuntimeActionRequest;
-
-const remoteAction = {
- callId: "call-remote",
- description: "Delegate remotely.",
- input: { message: "work remotely" },
- kind: "remote-agent-call",
- name: "remote",
- nodeId: "subagents/remote.ts",
- remoteAgentName: "remote",
-} satisfies RuntimeActionRequest;
+const LOCAL_RUNNING_HANDLE: AgentHandle = {
+ address: {
+ continuationToken: "subagent:parent:call-local",
+ kind: "agent/local",
+ sessionId: "local-child",
+ },
+ identity: {
+ id: "ag_local:aaaaaaaaaaaa",
+ name: "local",
+ nodeId: "subagents/local",
+ },
+ operation: {
+ callId: "call-local",
+ id: "op-local",
+ kind: "start",
+ parentTurnId: "turn_0",
+ },
+ phase: "running",
+};
+
+const REMOTE_RUNNING_HANDLE: AgentHandle = {
+ address: {
+ callbackBaseUrl: "https://parent.example.com",
+ continuationToken: "remote-token",
+ kind: "agent/remote",
+ sessionId: "remote-child",
+ url: "https://remote.example.com",
+ },
+ identity: {
+ id: "ag_remote:bbbbbbbbbbbb",
+ name: "remote",
+ nodeId: "subagents/remote.ts",
+ },
+ operation: {
+ callId: "call-remote",
+ id: "op-remote",
+ kind: "start",
+ parentTurnId: "turn_0",
+ },
+ phase: "running",
+};
const remote = {
kind: "remote",
name: "remote",
nodeId: "subagents/remote.ts",
path: "/custom-create-path",
- url: "https://remote.example.com",
-} as never;
+ url: "https://registry.example.com",
+} as const;
afterEach(() => {
vi.clearAllMocks();
@@ -64,15 +82,15 @@ afterEach(() => {
});
describe("cancelDescendantTurnsStep", () => {
- it("cancels every adopted local and remote child in parallel", async () => {
+ it("cancels every running local and remote child in parallel", async () => {
installRemoteRegistry();
- vi.mocked(resolveRemoteAgentForAction).mockReturnValue(remote);
+ vi.mocked(resolveRemoteAgentForAction).mockReturnValue(remote as never);
vi.mocked(requestWorkflowTurnCancellation).mockResolvedValue({ status: "accepted" });
vi.mocked(cancelRemoteAgentTurn).mockResolvedValue({ status: "accepted" });
await cancelDescendantTurnsStep({
serializedContext: { context: "parent" },
- sessionState: createPendingState(),
+ sessionState: createRunningState(),
});
expect(requestWorkflowTurnCancellation).toHaveBeenCalledWith({
@@ -80,12 +98,13 @@ describe("cancelDescendantTurnsStep", () => {
});
expect(resolveRemoteAgentForAction).toHaveBeenCalledWith({
dynamicRemoteAgent: undefined,
- nodeId: remoteAction.nodeId,
+ nodeId: REMOTE_RUNNING_HANDLE.identity.nodeId,
registry: expect.any(Map),
- remoteAgentName: remoteAction.remoteAgentName,
+ remoteAgentName: REMOTE_RUNNING_HANDLE.identity.name,
});
+ // Cancels at the dispatch-recorded URL, not the registry URL.
expect(cancelRemoteAgentTurn).toHaveBeenCalledWith({
- remote,
+ remote: { ...remote, url: "https://remote.example.com" },
sessionId: "remote-child",
});
});
@@ -95,7 +114,7 @@ describe("cancelDescendantTurnsStep", () => {
await cancelDescendantTurnsStep({
serializedContext: {},
- sessionState: createPendingState({ includeRemote: false }),
+ sessionState: createRunningState({ includeRemote: false }),
});
expect(requestWorkflowTurnCancellation).toHaveBeenCalledWith({
@@ -116,27 +135,55 @@ describe("cancelDescendantTurnsStep", () => {
prepared: {} as never,
remoteAgent: dynamicRemoteAgent,
});
- vi.mocked(resolveRemoteAgentForAction).mockReturnValue(remote);
+ vi.mocked(resolveRemoteAgentForAction).mockReturnValue(remote as never);
vi.mocked(requestWorkflowTurnCancellation).mockResolvedValue({ status: "accepted" });
vi.mocked(cancelRemoteAgentTurn).mockResolvedValue({ status: "accepted" });
await cancelDescendantTurnsStep({
serializedContext: {},
- sessionState: createPendingState(),
+ sessionState: createRunningState(),
});
expect(resolveRemoteAgentForAction).toHaveBeenCalledWith({
dynamicRemoteAgent,
- nodeId: remoteAction.nodeId,
+ nodeId: REMOTE_RUNNING_HANDLE.identity.nodeId,
registry: expect.any(Map),
- remoteAgentName: remoteAction.remoteAgentName,
+ remoteAgentName: REMOTE_RUNNING_HANDLE.identity.name,
});
});
+ it("skips parked handles: an idle child has no turn to cancel", async () => {
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ const session = createSession({
+ [AGENT_HANDLES_STATE_KEY]: {
+ handles: [
+ {
+ address: LOCAL_RUNNING_HANDLE.address,
+ identity: LOCAL_RUNNING_HANDLE.identity,
+ lastStatus: "waiting",
+ phase: "parked",
+ },
+ ],
+ },
+ });
+
+ await cancelDescendantTurnsStep({
+ serializedContext: {},
+ sessionState: createDurableSessionState({ session }),
+ });
+
+ expect(requestWorkflowTurnCancellation).not.toHaveBeenCalled();
+ expect(cancelRemoteAgentTurn).not.toHaveBeenCalled();
+ expect(warn).toHaveBeenCalledWith(
+ "[eve:execution.cancel-descendant-turns] no running agent handles found while cancelling descendants; nothing to cancel",
+ expect.objectContaining({ sessionId: expect.any(String) }),
+ );
+ });
+
it("retries no-active-turn responses during the child adoption window", async () => {
vi.useFakeTimers();
installRemoteRegistry();
- vi.mocked(resolveRemoteAgentForAction).mockReturnValue(remote);
+ vi.mocked(resolveRemoteAgentForAction).mockReturnValue(remote as never);
vi.mocked(requestWorkflowTurnCancellation)
.mockResolvedValueOnce({ status: "no_active_turn" })
.mockResolvedValueOnce({ status: "accepted" });
@@ -146,7 +193,7 @@ describe("cancelDescendantTurnsStep", () => {
const cancellation = cancelDescendantTurnsStep({
serializedContext: {},
- sessionState: createPendingState(),
+ sessionState: createRunningState(),
});
await vi.advanceTimersByTimeAsync(3_000);
await cancellation;
@@ -158,7 +205,7 @@ describe("cancelDescendantTurnsStep", () => {
it("contains unexpected local failures and exhausted remote failures", async () => {
vi.useFakeTimers();
installRemoteRegistry();
- vi.mocked(resolveRemoteAgentForAction).mockReturnValue(remote);
+ vi.mocked(resolveRemoteAgentForAction).mockReturnValue(remote as never);
vi.mocked(requestWorkflowTurnCancellation).mockRejectedValue(
new Error("local hook storage unavailable"),
);
@@ -168,7 +215,7 @@ describe("cancelDescendantTurnsStep", () => {
const cancellation = cancelDescendantTurnsStep({
serializedContext: {},
- sessionState: createPendingState(),
+ sessionState: createRunningState(),
});
await vi.advanceTimersByTimeAsync(10_000);
await expect(cancellation).resolves.toBeUndefined();
@@ -195,7 +242,7 @@ describe("cancelDescendantTurnsStep", () => {
const cancellation = cancelDescendantTurnsStep({
serializedContext: {},
- sessionState: createPendingState({ includeRemote: false }),
+ sessionState: createRunningState({ includeRemote: false }),
});
await vi.advanceTimersByTimeAsync(10_000);
await expect(cancellation).resolves.toBeUndefined();
@@ -211,18 +258,12 @@ describe("cancelDescendantTurnsStep", () => {
);
});
- it("treats pending batches from older deployments as having no descendants", async () => {
+ it("treats sessions without a handle store as having no descendants", async () => {
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
- const session = setPendingRuntimeActionBatch({
- actions: [localAction],
- event: { sequence: 0, stepIndex: 0, turnId: "turn_0" },
- responseMessages: [],
- session: createSession(),
- });
await cancelDescendantTurnsStep({
serializedContext: {},
- sessionState: createDurableSessionState({ session }),
+ sessionState: createDurableSessionState({ session: createSession() }),
});
expect(requestWorkflowTurnCancellation).not.toHaveBeenCalled();
@@ -230,7 +271,7 @@ describe("cancelDescendantTurnsStep", () => {
expect(deserializeContext).not.toHaveBeenCalled();
// The skipped cancellation is observable, not silent.
expect(warn).toHaveBeenCalledWith(
- "[eve:execution.cancel-descendant-turns] pending batch carries no child session ids; descendants cannot be cancelled",
+ "[eve:execution.cancel-descendant-turns] no running agent handles found while cancelling descendants; nothing to cancel",
expect.objectContaining({ sessionId: expect.any(String) }),
);
});
@@ -238,46 +279,34 @@ describe("cancelDescendantTurnsStep", () => {
function installRemoteRegistry(selection?: unknown): void {
vi.mocked(deserializeContext).mockResolvedValue({
- get: vi.fn(() => (selection === undefined ? undefined : { [remoteAction.nodeId]: selection })),
+ get: vi.fn(() =>
+ selection === undefined ? undefined : { [REMOTE_RUNNING_HANDLE.identity.nodeId]: selection },
+ ),
require: vi.fn(() => ({
- subagentRegistry: { subagentsByNodeId: new Map([[remoteAction.nodeId, remote]]) },
+ subagentRegistry: {
+ subagentsByNodeId: new Map([[REMOTE_RUNNING_HANDLE.identity.nodeId, remote]]),
+ },
})),
} as never);
}
-function createPendingState(input: { readonly includeRemote?: boolean } = {}) {
+function createRunningState(input: { readonly includeRemote?: boolean } = {}) {
const includeRemote = input.includeRemote ?? true;
- let session = setPendingRuntimeActionBatch({
- actions: includeRemote ? [localAction, remoteAction] : [localAction],
- event: { sequence: 0, stepIndex: 0, turnId: "turn_0" },
- responseMessages: [],
- session: createSession(),
+ const handles = includeRemote
+ ? [LOCAL_RUNNING_HANDLE, REMOTE_RUNNING_HANDLE]
+ : [LOCAL_RUNNING_HANDLE];
+ return createDurableSessionState({
+ session: createSession({ [AGENT_HANDLES_STATE_KEY]: { handles } }),
});
- session = recordPendingSubagentChild({
- callId: localAction.callId,
- child: {
- continuationToken: "subagent:parent:call-local",
- kind: "local",
- sessionId: "local-child",
- },
- session,
- });
- if (includeRemote) {
- session = recordPendingSubagentChild({
- callId: remoteAction.callId,
- child: { kind: "remote", sessionId: "remote-child" },
- session,
- });
- }
- return createDurableSessionState({ session });
}
-function createSession(): HarnessSession {
+function createSession(state?: HarnessSession["state"]): HarnessSession {
return {
agent: { modelReference: { id: "test-model" }, system: "", tools: [] },
compaction: { recentWindowSize: 10, threshold: 100_000 },
continuationToken: "http:parent",
history: [],
sessionId: "parent",
+ state,
};
}
diff --git a/packages/eve/src/execution/cancel-descendant-turns-step.ts b/packages/eve/src/execution/cancel-descendant-turns-step.ts
index 365648d08..8c1874aa6 100644
--- a/packages/eve/src/execution/cancel-descendant-turns-step.ts
+++ b/packages/eve/src/execution/cancel-descendant-turns-step.ts
@@ -8,12 +8,8 @@ import {
resolveRemoteAgentForAction,
} from "#execution/remote-agent-dispatch.js";
import { requestWorkflowTurnCancellation } from "#execution/workflow-runtime.js";
-import { getPendingRuntimeActionBatch } from "#harness/runtime-actions.js";
+import { getAgentHandleStore, type AgentHandle } from "#harness/handles/store.js";
import { createLogger, logError } from "#internal/logging.js";
-import type {
- RuntimeRemoteAgentCallActionRequest,
- RuntimeSubagentCallActionRequest,
-} from "#runtime/actions/types.js";
import type { RuntimeSubagentRegistry } from "#runtime/subagents/registry.js";
import { getDynamicSubagentSelection } from "#context/dynamic-subagent-lifecycle.js";
import type { ContextContainer } from "#context/container.js";
@@ -26,17 +22,21 @@ const CANCEL_RETRY_INITIAL_DELAY_MS = 250;
const CANCEL_RETRY_MAX_DELAY_MS = 1_500;
const log = createLogger("execution.cancel-descendant-turns");
-/** Cancels every successfully adopted child in the current pending batch. */
+type RunningAgentHandle = Extract<AgentHandle, { phase: "running" }>;
+
+/** Cancels every running delegated child recorded in the agent handle store. */
export async function cancelDescendantTurnsStep(input: {
readonly serializedContext: Record<string, unknown>;
readonly sessionState: DurableSessionState;
}): Promise<void> {
"use step";
- let batch;
+ let running: readonly RunningAgentHandle[];
try {
const session = await readDurableSession(input.sessionState);
- batch = getPendingRuntimeActionBatch(session.state);
+ running = (getAgentHandleStore(session.state)?.handles ?? []).filter(
+ (handle): handle is RunningAgentHandle => handle.phase === "running",
+ );
} catch (error) {
logError(log, "failed to read pending descendants during cancellation", error, {
sessionId: input.sessionState.sessionId,
@@ -44,16 +44,8 @@ export async function cancelDescendantTurnsStep(input: {
return;
}
- if (batch === undefined) {
- log.warn("no pending batch found while cancelling descendants; nothing to cancel", {
- sessionId: input.sessionState.sessionId,
- });
- return;
- }
- const childSessionIds = batch.childSessionIds;
- if (childSessionIds === undefined) {
- log.warn("pending batch carries no child session ids; descendants cannot be cancelled", {
- actionCount: batch.actions.length,
+ if (running.length === 0) {
+ log.warn("no running agent handles found while cancelling descendants; nothing to cancel", {
sessionId: input.sessionState.sessionId,
});
return;
@@ -71,91 +63,86 @@ export async function cancelDescendantTurnsStep(input: {
registry: ctx.require(BundleKey).subagentRegistry.subagentsByNodeId,
})));
- const cancellations = batch.actions.flatMap((action): Promise<void>[] => {
- const childSessionId = childSessionIds[action.callId];
- if (childSessionId === undefined) return [];
-
- if (action.kind === "subagent-call") {
- return [cancelLocalDescendant({ action, childSessionId })];
- }
- if (action.kind === "remote-agent-call") {
- return [
- cancelRemoteDescendant({
- action,
- childSessionId,
- remoteContext: getRemoteContext(),
- }),
- ];
- }
- return [];
- });
-
- await Promise.all(cancellations);
+ await Promise.all(
+ running.map((handle) =>
+ handle.address.kind === "agent/remote"
+ ? cancelRemoteDescendant({ handle, remoteContext: getRemoteContext() })
+ : cancelLocalDescendant({ handle }),
+ ),
+ );
}
async function cancelLocalDescendant(input: {
- readonly action: RuntimeSubagentCallActionRequest;
- readonly childSessionId: string;
+ readonly handle: RunningAgentHandle;
}): Promise<void> {
+ const { handle } = input;
try {
const final = await requestCancellationWithRetry({
- request: () => requestWorkflowTurnCancellation({ sessionId: input.childSessionId }),
+ request: () => requestWorkflowTurnCancellation({ sessionId: handle.address.sessionId }),
shouldRetryError: () => false,
});
if (final.status !== "accepted") {
log.warn("descendant cancel was never accepted; the child may run to completion", {
- callId: input.action.callId,
- childSessionId: input.childSessionId,
+ callId: handle.operation.callId,
+ childSessionId: handle.address.sessionId,
finalStatus: final.status,
reason: final.reason,
- subagentName: input.action.subagentName,
+ subagentName: handle.identity.name,
});
}
} catch (error) {
logError(log, "failed to cancel local descendant turn", error, {
- callId: input.action.callId,
- childSessionId: input.childSessionId,
- subagentName: input.action.subagentName,
+ callId: handle.operation.callId,
+ childSessionId: handle.address.sessionId,
+ subagentName: handle.identity.name,
});
}
}
async function cancelRemoteDescendant(input: {
- readonly action: RuntimeRemoteAgentCallActionRequest;
- readonly childSessionId: string;
readonly remoteContext: Promise<{
readonly ctx: ContextContainer;
readonly registry: RuntimeSubagentRegistry["subagentsByNodeId"];
}>;
+ readonly handle: RunningAgentHandle;
}): Promise<void> {
+ const { handle } = input;
+ if (handle.address.kind !== "agent/remote") {
+ return;
+ }
+ const childUrl = handle.address.url;
try {
const { ctx, registry } = await input.remoteContext;
- const selection = getDynamicSubagentSelection(ctx, input.action.nodeId);
- const remote = await resolveRemoteAgentForAction({
+ const selection = getDynamicSubagentSelection(ctx, handle.identity.nodeId);
+ const resolved = await resolveRemoteAgentForAction({
dynamicRemoteAgent: selection?.kind === "remote" ? selection.remoteAgent : undefined,
- nodeId: input.action.nodeId,
- remoteAgentName: input.action.remoteAgentName,
+ nodeId: handle.identity.nodeId,
+ remoteAgentName: handle.identity.name,
registry,
});
+ // Cancel where the child actually runs: the registry URL may point at a
+ // newer deployment than the one that adopted this child, so the
+ // dispatch-recorded URL wins — mirroring continuation delivery.
+ const remote = { ...resolved, url: childUrl };
const final = await requestCancellationWithRetry({
- request: () => cancelRemoteAgentTurn({ remote, sessionId: input.childSessionId }),
+ request: () => cancelRemoteAgentTurn({ remote, sessionId: handle.address.sessionId }),
shouldRetryError: isRetryableRemoteAgentCancelError,
});
if (final.status !== "accepted") {
log.warn("remote descendant cancel was never accepted; the child may run to completion", {
- callId: input.action.callId,
- childSessionId: input.childSessionId,
+ callId: handle.operation.callId,
+ childSessionId: handle.address.sessionId,
finalStatus: final.status,
reason: final.reason,
- remoteAgentName: input.action.remoteAgentName,
+ remoteAgentName: handle.identity.name,
});
}
} catch (error) {
logError(log, "failed to cancel remote descendant turn", error, {
- callId: input.action.callId,
- childSessionId: input.childSessionId,
- remoteAgentName: input.action.remoteAgentName,
+ callId: handle.operation.callId,
+ childSessionId: handle.address.sessionId,
+ remoteAgentName: handle.identity.name,
});
}
}
diff --git a/packages/eve/src/execution/delegated-parent-notification.test.ts b/packages/eve/src/execution/delegated-parent-notification.test.ts
index 10583564f..0642b6080 100644
--- a/packages/eve/src/execution/delegated-parent-notification.test.ts
+++ b/packages/eve/src/execution/delegated-parent-notification.test.ts
@@ -8,7 +8,7 @@ import { notifyDelegatedParentStep } from "#execution/delegated-parent-notificat
import { SUBAGENT_ADAPTER } from "#execution/subagent-adapter.js";
import { SUBAGENT_ADAPTER_KIND } from "#execution/subagent-adapter-state.js";
import { resumeHook } from "#internal/workflow/runtime.js";
-import type { RuntimeSubagentResultActionResult } from "#runtime/actions/types.js";
+import type { RuntimeSubagentChildResult } from "#runtime/actions/types.js";
vi.mock("../runtime/sessions/compiled-agent-cache.js", () => ({
getCompiledRuntimeAgentBundle: vi.fn(),
@@ -22,10 +22,11 @@ const resumeHookMock = vi.mocked(resumeHook);
const USAGE = { cacheReadTokens: 10, cacheWriteTokens: 5, inputTokens: 100, outputTokens: 50 };
-function createSuccessResult(): RuntimeSubagentResultActionResult {
+function createSuccessResult(): RuntimeSubagentChildResult {
return {
callId: "call-1",
kind: "subagent-result",
+ origin: "child",
output: "done",
subagentName: "research",
};
@@ -74,6 +75,7 @@ describe("notifyDelegatedParentStep", () => {
{
callId: "call-1",
kind: "subagent-result",
+ origin: "child",
output: "done",
subagentName: "research",
usage: USAGE,
@@ -95,10 +97,11 @@ describe("notifyDelegatedParentStep", () => {
});
it("never attaches usage to error results", async () => {
- const errorResult: RuntimeSubagentResultActionResult = {
+ const errorResult: RuntimeSubagentChildResult = {
callId: "call-1",
isError: true,
kind: "subagent-result",
+ origin: "child",
output: { code: "SUBAGENT_EXECUTION_FAILED", message: "boom" },
subagentName: "research",
};
diff --git a/packages/eve/src/execution/delegated-parent-notification.ts b/packages/eve/src/execution/delegated-parent-notification.ts
index 2e74c1655..fc78ed649 100644
--- a/packages/eve/src/execution/delegated-parent-notification.ts
+++ b/packages/eve/src/execution/delegated-parent-notification.ts
@@ -7,7 +7,7 @@
import { ChannelKey } from "#runtime/sessions/runtime-context-keys.js";
import { deserializeContext } from "#context/serialize.js";
-import type { RuntimeSubagentResultActionResult } from "#runtime/actions/types.js";
+import type { RuntimeSubagentChildResult } from "#runtime/actions/types.js";
import { SUBAGENT_ADAPTER_KIND } from "#execution/subagent-adapter-state.js";
import type { TokenUsage } from "#shared/token-usage.js";
import { resumeHook } from "#internal/workflow/runtime.js";
@@ -21,7 +21,7 @@ import { resumeHook } from "#internal/workflow/runtime.js";
* subagent's tokens. Error results never carry usage.
*/
export async function notifyDelegatedParentStep(input: {
- readonly result: RuntimeSubagentResultActionResult | undefined;
+ readonly result: RuntimeSubagentChildResult | undefined;
readonly serializedContext: Record<string, unknown>;
readonly usage?: TokenUsage;
}): Promise<void> {
diff --git a/packages/eve/src/execution/delegated-parent-result.ts b/packages/eve/src/execution/delegated-parent-result.ts
index 05643ed22..b10928b90 100644
--- a/packages/eve/src/execution/delegated-parent-result.ts
+++ b/packages/eve/src/execution/delegated-parent-result.ts
@@ -5,19 +5,20 @@
* step-proxy transform.
*/
-import type { RuntimeSubagentResultActionResult } from "#runtime/actions/types.js";
+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 { SUBAGENT_ADAPTER_KIND } from "#execution/subagent-adapter-state.js";
/**
- * Builds the success-shaped {@link RuntimeSubagentResultActionResult}.
+ * Builds the success-shaped {@link RuntimeSubagentChildResult}.
* Returns `undefined` for root sessions (no parent to notify).
*/
export function createDelegatedSubagentSuccessResult(
serializedContext: Record<string, unknown>,
output: unknown,
-): RuntimeSubagentResultActionResult | undefined {
+): RuntimeSubagentChildResult | undefined {
const channel = serializedContext["eve.channel"] as
| { kind?: string; state?: Record<string, unknown> }
| undefined;
@@ -29,6 +30,7 @@ export function createDelegatedSubagentSuccessResult(
return {
callId: String(channel.state?.callId ?? ""),
kind: "subagent-result",
+ origin: "child",
output: output as JsonValue,
subagentName: String(channel.state?.subagentName ?? ""),
};
@@ -38,7 +40,7 @@ export function createDelegatedSubagentSuccessResult(
export function createDelegatedSubagentErrorResult(
serializedContext: Record<string, unknown>,
error: unknown,
-): RuntimeSubagentResultActionResult | undefined {
+): RuntimeSubagentChildResult | undefined {
const success = createDelegatedSubagentSuccessResult(serializedContext, "");
if (success === undefined) {
@@ -49,7 +51,7 @@ export function createDelegatedSubagentErrorResult(
...success,
isError: true,
output: {
- code: "SUBAGENT_EXECUTION_FAILED",
+ code: SUBAGENT_EXECUTION_FAILED,
message: toErrorMessage(error),
},
};
diff --git a/packages/eve/src/execution/dispatch-runtime-actions-step.integration.test.ts b/packages/eve/src/execution/dispatch-runtime-actions-step.integration.test.ts
new file mode 100644
index 000000000..f6828ffc4
--- /dev/null
+++ b/packages/eve/src/execution/dispatch-runtime-actions-step.integration.test.ts
@@ -0,0 +1,388 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import type { ChannelAdapter } from "#channel/adapter.js";
+import type { DurableSessionState } from "#execution/durable-session-store.js";
+import { dispatchRuntimeActionsStep } from "#execution/dispatch-runtime-actions-step.js";
+import {
+ resolvePendingRuntimeActions,
+ setPendingRuntimeActionBatch,
+} from "#harness/runtime-actions.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";
+import {
+ AuthKey,
+ CapabilitiesKey,
+ ChannelInstrumentationKey,
+ InitiatorAuthKey,
+} from "#context/keys.js";
+import { BundleKey, ChannelKey } from "#runtime/sessions/runtime-context-keys.js";
+
+const mocks = vi.hoisted(() => ({
+ createDurableSessionState: vi.fn(),
+ deliver: vi.fn(),
+ deserializeContext: vi.fn(),
+ hydrateDurableSession: vi.fn(),
+ readDurableSession: vi.fn(),
+ run: vi.fn(),
+ startRemoteAgentSession: vi.fn(),
+}));
+
+vi.mock("#context/serialize.js", () => ({
+ deserializeContext: mocks.deserializeContext,
+}));
+
+vi.mock("#execution/durable-session-store.js", () => ({
+ createDurableSessionState: mocks.createDurableSessionState,
+ readDurableSession: mocks.readDurableSession,
+}));
+
+vi.mock("#execution/session.js", () => ({
+ hydrateDurableSession: mocks.hydrateDurableSession,
+ mintSubagentContinuationToken: (seed: string) => `subagent:${seed}`,
+}));
+
+vi.mock("#execution/workflow-runtime.js", () => ({
+ createWorkflowRuntime: () => ({
+ deliver: mocks.deliver,
+ run: mocks.run,
+ }),
+ workflowEntryReference: { workflowId: "workflow//eve//workflowEntry" },
+}));
+
+// Only the network calls are mocked; error classification and registry
+// resolution stay real so these tests cannot drift from the production
+// retry/forfeit policy.
+vi.mock("#execution/remote-agent-dispatch.js", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("#execution/remote-agent-dispatch.js")>()),
+ startRemoteAgentSession: mocks.startRemoteAgentSession,
+}));
+
+const ADAPTER: ChannelAdapter = { kind: "channel:test" };
+const BASE_STATE: DurableSessionState = {
+ continuationToken: "parent-token",
+ emissionState: { sequence: 0, sessionStarted: false, stepIndex: 0, turnId: "" },
+ hasProxyInputRequests: false,
+ sessionId: "parent-session",
+ version: 1,
+};
+const CHILD_SESSION_ID = "child-session-123456789012";
+
+const REMOTE_REGISTRY_DEFINITION = {
+ description: "Remote research",
+ kind: "remote",
+ name: "research",
+ nodeId: "remote/research",
+ path: "/eve/v1/session",
+ url: "https://registry.example.com",
+} as const;
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.deliver.mockResolvedValue({ sessionId: CHILD_SESSION_ID });
+ mocks.run.mockResolvedValue({ sessionId: CHILD_SESSION_ID });
+ mocks.startRemoteAgentSession.mockResolvedValue({
+ continuationToken: "remote-child-token",
+ sessionId: "remote-session-123456789012",
+ });
+ mocks.hydrateDurableSession.mockImplementation(({ durable }) => durable);
+ mocks.createDurableSessionState.mockImplementation(({ session }) => ({
+ ...BASE_STATE,
+ snapshot: { session, version: 1 },
+ }));
+});
+
+describe("dispatchRuntimeActionsStep child starts", () => {
+ const startOperationId = deriveAgentOperationId({
+ callId: "call-1",
+ parentSessionId: "parent-session",
+ parentTurnId: "turn-1",
+ });
+
+ it("owns a local child before the start effect and confirms its running address", async () => {
+ const session = createStartSession({ kind: "local" });
+ installContext(session, {
+ definition: { description: "Research", kind: "subagent" },
+ nodeId: "subagents/research",
+ });
+ const writes: Uint8Array[] = [];
+
+ const result = await dispatchRuntimeActionsStep({
+ parentContinuationToken: "turn-inbox",
+ parentWritable: createWritable(writes),
+ serializedContext: {},
+ sessionState: BASE_STATE,
+ });
+
+ expect(result.results).toEqual([]);
+ expect(mocks.run).toHaveBeenCalledTimes(1);
+ expect(getAgentHandleStore(readResultSessionState(result, session))).toEqual({
+ handles: [
+ {
+ address: {
+ continuationToken: "subagent:parent-session:call-1",
+ kind: "agent/local",
+ sessionId: CHILD_SESSION_ID,
+ },
+ identity: {
+ id: deriveAgentId("research", startOperationId),
+ name: "research",
+ nodeId: "subagents/research",
+ },
+ operation: {
+ callId: "call-1",
+ id: startOperationId,
+ kind: "start",
+ parentTurnId: "turn-1",
+ },
+ phase: "running",
+ },
+ ],
+ });
+ expect(writes).toHaveLength(1);
+ });
+
+ it("rejects the prepared handle when the local start fails", async () => {
+ const session = createStartSession({ kind: "local" });
+ installContext(session, {
+ definition: { description: "Research", kind: "subagent" },
+ nodeId: "subagents/research",
+ });
+ mocks.run.mockRejectedValue(new Error("runtime unavailable"));
+
+ const result = await dispatchRuntimeActionsStep({
+ parentContinuationToken: "turn-inbox",
+ parentWritable: createWritable(),
+ serializedContext: {},
+ sessionState: BASE_STATE,
+ });
+
+ expect(result.results[0]).toMatchObject({
+ isError: true,
+ output: { code: "SUBAGENT_START_FAILED" },
+ });
+ // The store was written (prepare committed ownership before the effect)
+ // and the dead start was rejected, so no handle survives.
+ expect(getAgentHandleStore(readResultSessionState(result, session))).toEqual({
+ handles: [],
+ });
+ });
+
+ it("owns a remote child with its confirmed remote address", async () => {
+ const session = createStartSession({ kind: "remote" });
+ installContext(session, {
+ definition: REMOTE_REGISTRY_DEFINITION,
+ nodeId: "remote/research",
+ });
+
+ const result = await dispatchRuntimeActionsStep({
+ callbackBaseUrl: "https://caller.example.com",
+ parentContinuationToken: "turn-inbox",
+ parentWritable: createWritable(),
+ serializedContext: {},
+ sessionState: BASE_STATE,
+ });
+
+ expect(result.results).toEqual([]);
+ expect(getAgentHandleStore(readResultSessionState(result, session))).toEqual({
+ handles: [
+ expect.objectContaining({
+ address: {
+ callbackBaseUrl: "https://caller.example.com",
+ continuationToken: "remote-child-token",
+ kind: "agent/remote",
+ sessionId: "remote-session-123456789012",
+ url: "https://registry.example.com",
+ },
+ phase: "running",
+ }),
+ ],
+ });
+ });
+
+ it("rejects the prepared handle when the remote start fails", async () => {
+ const session = createStartSession({ kind: "remote" });
+ installContext(session, {
+ definition: REMOTE_REGISTRY_DEFINITION,
+ nodeId: "remote/research",
+ });
+ mocks.startRemoteAgentSession.mockRejectedValue(new Error("HTTP 500"));
+
+ const result = await dispatchRuntimeActionsStep({
+ callbackBaseUrl: "https://caller.example.com",
+ parentContinuationToken: "turn-inbox",
+ parentWritable: createWritable(),
+ serializedContext: {},
+ sessionState: BASE_STATE,
+ });
+
+ expect(result.results[0]).toMatchObject({
+ isError: true,
+ output: { code: "REMOTE_AGENT_START_FAILED" },
+ });
+ expect(getAgentHandleStore(readResultSessionState(result, session))).toEqual({
+ handles: [],
+ });
+ });
+
+ it("binds the child result through the running handle and deletes it on terminal settlement", async () => {
+ const session = createStartSession({ kind: "local" });
+ installContext(session, {
+ definition: { description: "Research", kind: "subagent" },
+ nodeId: "subagents/research",
+ });
+
+ const dispatched = await dispatchRuntimeActionsStep({
+ parentContinuationToken: "turn-inbox",
+ parentWritable: createWritable(),
+ serializedContext: {},
+ sessionState: BASE_STATE,
+ });
+ // Only `state` changes across the dispatch step; graft the committed
+ // state map onto the in-memory session instead of re-hydrating.
+ const committedSession: HarnessSession = {
+ ...session,
+ state: dispatched.sessionState.snapshot?.session.state,
+ };
+
+ // A result for a callId no running handle records never settles the call.
+ const unbound = await resolvePendingRuntimeActions({
+ session: committedSession,
+ stepInput: {
+ runtimeActionResults: [
+ {
+ callId: "call-unknown",
+ kind: "subagent-result",
+ origin: "child",
+ output: "stray",
+ subagentName: "research",
+ },
+ ],
+ },
+ });
+ expect(unbound.outcome).toBe("unresolved");
+
+ const resolved = await resolvePendingRuntimeActions({
+ session: committedSession,
+ stepInput: {
+ runtimeActionResults: [
+ {
+ callId: "call-1",
+ kind: "subagent-result",
+ origin: "child",
+ output: "done",
+ subagentName: "research",
+ },
+ ],
+ },
+ });
+ expect(resolved.outcome).toBe("resolved");
+ expect(getAgentHandleStore(resolved.session.state)).toEqual({ handles: [] });
+ });
+});
+
+/**
+ * The step returns the input state unchanged when the session object is
+ * untouched; otherwise the mocked `createDurableSessionState` carries the
+ * updated session on `snapshot`.
+ */
+function readResultSessionState(
+ result: Awaited<ReturnType<typeof dispatchRuntimeActionsStep>>,
+ originalSession: HarnessSession,
+): HarnessSession["state"] {
+ return result.sessionState.snapshot?.session.state ?? originalSession.state;
+}
+
+function createBaseSession(handle?: AgentHandle): HarnessSession {
+ const base: HarnessSession = {
+ agent: { modelReference: { id: "test-model" }, system: "", tools: [] },
+ compaction: { recentWindowSize: 10, threshold: 100_000 },
+ continuationToken: "parent-token",
+ history: [],
+ sessionId: "parent-session",
+ };
+ return handle === undefined
+ ? base
+ : { ...base, state: { [AGENT_HANDLES_STATE_KEY]: { handles: [handle] } } };
+}
+
+function createStartSession(input: { readonly kind: "local" | "remote" }): HarnessSession {
+ return setPendingRuntimeActionBatch({
+ actions: [
+ input.kind === "local"
+ ? {
+ callId: "call-1",
+ description: "Research",
+ input: { message: "research this" },
+ kind: "subagent-call",
+ name: "research",
+ nodeId: "subagents/research",
+ subagentName: "research",
+ }
+ : {
+ callId: "call-1",
+ description: "Research",
+ input: { message: "research this" },
+ kind: "remote-agent-call",
+ name: "research",
+ nodeId: "remote/research",
+ remoteAgentName: "research",
+ },
+ ],
+ event: { sequence: 1, stepIndex: 2, turnId: "turn-1" },
+ responseMessages: [],
+ session: createBaseSession(),
+ });
+}
+
+function installContext(
+ session: HarnessSession,
+ remote?: { readonly definition: unknown; readonly nodeId: string },
+): void {
+ const subagentsByNodeId = new Map<string, { definition: unknown }>();
+ if (remote !== undefined) {
+ subagentsByNodeId.set(remote.nodeId, { definition: remote.definition });
+ }
+ const bundle = {
+ compiledArtifactsSource: {},
+ resolvedAgent: { config: {} },
+ subagentRegistry: { subagentsByNodeId },
+ turnAgent: {
+ id: "test-agent",
+ instructions: [],
+ model: { id: "test-model" },
+ skills: [],
+ tools: [],
+ workspaceSpec: {},
+ },
+ };
+ const values = new Map<unknown, unknown>([
+ [AuthKey, null],
+ [BundleKey, bundle],
+ [CapabilitiesKey, undefined],
+ [ChannelInstrumentationKey, undefined],
+ [InitiatorAuthKey, null],
+ [ChannelKey, ADAPTER],
+ ]);
+ mocks.deserializeContext.mockResolvedValue({
+ get: (key: unknown) => values.get(key),
+ require: (key: unknown) => {
+ if (!values.has(key)) throw new Error("missing context key");
+ return values.get(key);
+ },
+ });
+ mocks.readDurableSession.mockResolvedValue(session);
+}
+
+function createWritable(writes: Uint8Array[] = []): WritableStream<Uint8Array> {
+ return new WritableStream({
+ write(chunk) {
+ writes.push(chunk);
+ },
+ });
+}
diff --git a/packages/eve/src/execution/dispatch-runtime-actions-step.ts b/packages/eve/src/execution/dispatch-runtime-actions-step.ts
index 42ccbaedf..0c7206ca2 100644
--- a/packages/eve/src/execution/dispatch-runtime-actions-step.ts
+++ b/packages/eve/src/execution/dispatch-runtime-actions-step.ts
@@ -1,10 +1,12 @@
/**
* Starts every pending runtime action for the parked parent session.
*
- * Each child run starts in task mode, emits a parent `subagent.called`
- * control-plane event, and then runs independently on its own child
- * stream. Records each child's continuation token on the parent
- * session and returns the updated snapshot-bearing state.
+ * 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.
*/
import { buildAdapterContext } from "#channel/adapter-context.js";
@@ -15,12 +17,27 @@ import {
ChannelInstrumentationKey,
InitiatorAuthKey,
} from "#context/keys.js";
-import { BundleKey, ChannelKey } from "#runtime/sessions/runtime-context-keys.js";
+import {
+ BundleKey,
+ ChannelKey,
+ 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";
import {
- getPendingRuntimeActionBatch,
- recordPendingSubagentChild,
-} from "#harness/runtime-actions.js";
+ confirmAgentStarted,
+ prepareAgentStart,
+ rejectAgentEffect,
+} from "#harness/handles/transitions.js";
+import { getPendingRuntimeActionBatch } from "#harness/runtime-actions.js";
import {
createSubagentCalledEvent,
encodeMessageStreamEvent,
@@ -30,7 +47,8 @@ import type {
RuntimeActionRequest,
RuntimeRemoteAgentCallActionRequest,
RuntimeSubagentCallActionRequest,
- RuntimeSubagentResultActionResult,
+ RuntimeSubagentDispatchFailure,
+ RuntimeSubagentResult,
} from "#runtime/actions/types.js";
import {
createDurableSessionState,
@@ -53,6 +71,37 @@ import { resolveEffectiveAgentRuntime } from "#execution/effective-agent-config.
const log = createLogger("execution.dispatch-runtime-actions");
+type DynamicSubagentAgentConfig = NonNullable<
+ Extract<
+ ReturnType<typeof getDynamicSubagentSelection>,
+ { readonly kind: "subagent" }
+ >["agentConfig"]
+>;
+
+type DynamicRemoteAgentConfig = NonNullable<
+ Extract<
+ ReturnType<typeof getDynamicSubagentSelection>,
+ { readonly kind: "remote" }
+ >["remoteAgent"]
+>;
+
+type DispatchPlanEntry =
+ | { readonly kind: "reject"; readonly result: RuntimeSubagentDispatchFailure }
+ | { readonly kind: "start"; readonly target: DispatchStartTarget };
+
+type DispatchStartTarget =
+ | {
+ readonly kind: "local";
+ readonly action: RuntimeSubagentCallActionRequest;
+ readonly dynamicSubagentAgentConfig?: DynamicSubagentAgentConfig;
+ readonly source: SubagentInputSource;
+ }
+ | {
+ readonly kind: "remote";
+ readonly action: RuntimeRemoteAgentCallActionRequest;
+ readonly dynamicRemoteAgent?: DynamicRemoteAgentConfig;
+ };
+
export async function dispatchRuntimeActionsStep(input: {
readonly callbackBaseUrl?: string;
/** Internal hook that receives child completion and HITL payloads. */
@@ -61,7 +110,7 @@ export async function dispatchRuntimeActionsStep(input: {
readonly serializedContext: Record<string, unknown>;
readonly sessionState: DurableSessionState;
}): Promise<{
- readonly results: readonly RuntimeSubagentResultActionResult[];
+ readonly results: readonly RuntimeSubagentResult[];
readonly sessionState: DurableSessionState;
}> {
"use step";
@@ -88,192 +137,87 @@ export async function dispatchRuntimeActionsStep(input: {
const capabilities = ctx.get(CapabilitiesKey);
const channelMetadata = ctx.get(ChannelInstrumentationKey);
const initiatorAuth = ctx.get(InitiatorAuthKey) ?? null;
- const writer = input.parentWritable.getWriter();
const adapterCtx = buildAdapterContext(adapter, ctx);
- const subagentDepth = resolveSubagentDepth(session);
// 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);
- // Split the parent's remaining token quota across the batch's local
- // subagent calls, the children that actually receive an enforced cap.
- // Remote agents run on their own deployment under their own limits and
- // do not dilute the local shares.
- const fanoutSize = batch.actions.filter((action) => action.kind === "subagent-call").length;
+ // 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.
+ getAgentHandleStore(durableSession.state);
+ const plan = planDispatch({ actions: batch.actions, bundle, ctx, session });
+ // Acquired only once preflight can no longer throw, so a planning failure
+ // never leaks the writer lock.
+ 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.
+ const fanoutSize = plan.filter(
+ (entry) => entry.kind === "start" && entry.target.kind === "local",
+ ).length;
let nextSession = session;
- const results: RuntimeSubagentResultActionResult[] = [];
+ const results: RuntimeSubagentResult[] = [];
try {
- for (const action of batch.actions) {
- const isDynamicSubagent =
- (action.kind === "subagent-call" || action.kind === "remote-agent-call") &&
- bundle.subagentRegistry.dynamicNodeIds?.has(action.nodeId) === true;
- const dynamicSubagentSelection = isDynamicSubagent
- ? getDynamicSubagentSelection(ctx, action.nodeId)
- : undefined;
- if (
- isRecursiveAgentAction(action, bundle.subagentRegistry.subagentsByNodeId) &&
- (session.rootSessionId !== undefined || subagentDepth.currentDepth > 0)
- ) {
- log.warn("recursive agent call blocked outside the root session", {
- callId: action.callId,
- currentDepth: subagentDepth.currentDepth,
- nodeId: action.nodeId,
- subagentName: action.subagentName,
- });
- results.push(createRecursiveAgentRootOnlyResult(action));
+ for (const entry of plan) {
+ if (entry.kind === "reject") {
+ results.push(entry.result);
continue;
}
- if (
- isDynamicSubagent &&
- (dynamicSubagentSelection === undefined ||
- (action.kind === "subagent-call" && dynamicSubagentSelection.kind !== "subagent") ||
- (action.kind === "remote-agent-call" && dynamicSubagentSelection.kind !== "remote"))
- ) {
- const subagentName = getSubagentName(action);
- log.warn("dynamic subagent call blocked after availability changed", {
- callId: action.callId,
- nodeId: action.nodeId,
- subagentName,
- });
- results.push(createUnavailableDynamicSubagentResult(action));
+ 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,
+ });
+
+ nextSession = outcome.session;
+ if (outcome.kind === "error") {
+ results.push(outcome.result);
continue;
}
- let childSessionId: string;
- let name: string;
- let remote: { readonly url: string } | undefined;
- let toolName: string;
-
- switch (action.kind) {
- case "subagent-call": {
- const dynamicAgentConfig =
- dynamicSubagentSelection?.kind === "subagent"
- ? dynamicSubagentSelection.agentConfig
- : undefined;
- const registered = bundle.subagentRegistry.subagentsByNodeId.get(action.nodeId);
- const description =
- dynamicAgentConfig?.description ??
- (registered?.definition.kind === "subagent"
- ? registered.definition.description
- : undefined);
- const source: SubagentInputSource =
- description !== undefined ? { description, type: "local" } : { type: "runtime" };
- const childRuntime = createWorkflowRuntime({
- compiledArtifactsSource: bundle.compiledArtifactsSource,
- dynamicSubagentAgentConfig: dynamicAgentConfig,
- nodeId: action.nodeId,
- });
- const { childContinuationToken, runInput } = buildSubagentRunInput({
- action,
- auth,
- batchEvent: batch.event,
- capabilities,
- channelMetadata,
- fanoutSize,
- initiatorAuth,
- parentContinuationToken: input.parentContinuationToken,
- parentTraceContext,
- session,
- source,
- });
- try {
- const handle = await childRuntime.run(runInput);
- childSessionId = handle.sessionId;
- } catch (error) {
- logError(log, "local subagent start failed", error, {
- callId: action.callId,
- nodeId: action.nodeId,
- subagentName: action.subagentName,
- });
- results.push({
- callId: action.callId,
- isError: true,
- kind: "subagent-result",
- output: {
- code: "SUBAGENT_START_FAILED",
- message: toErrorMessage(error),
- },
- subagentName: action.subagentName,
- });
- continue;
- }
-
- nextSession = recordPendingSubagentChild({
- callId: action.callId,
- child: {
- continuationToken: childContinuationToken,
- kind: "local",
- sessionId: childSessionId,
- },
- session: nextSession,
- });
- name = action.name;
- toolName = action.subagentName;
- break;
- }
- case "remote-agent-call": {
- let resolvedRemote;
- try {
- resolvedRemote = await resolveRemoteAgentForAction({
- dynamicRemoteAgent:
- dynamicSubagentSelection?.kind === "remote"
- ? dynamicSubagentSelection.remoteAgent
- : undefined,
- nodeId: action.nodeId,
- remoteAgentName: action.remoteAgentName,
- registry: bundle.subagentRegistry.subagentsByNodeId,
- });
- childSessionId = await startRemoteAgentSession({
- action,
- auth,
- callbackBaseUrl: input.callbackBaseUrl,
- callbackToken: input.parentContinuationToken,
- initiatorAuth,
- remote: resolvedRemote,
- session,
- });
- } catch (error) {
- logError(log, "remote agent start failed", error, {
- remoteAgentName: action.remoteAgentName,
- nodeId: action.nodeId,
- callId: action.callId,
- });
- results.push(createRemoteAgentStartFailureResult({ action, error }));
- continue;
- }
- name = action.name;
- remote = { url: resolvedRemote.url };
- toolName = action.remoteAgentName;
- nextSession = recordPendingSubagentChild({
- callId: action.callId,
- child: { kind: "remote", sessionId: childSessionId },
- session: nextSession,
- });
- break;
- }
- default:
- throw new Error(`Unsupported runtime action kind "${action.kind}" in workflow runtime.`);
+ // Emission is observability, not control flow: a failure here must not
+ // escape the loop, because a durable-step retry would re-dispatch the
+ // children that already started.
+ try {
+ const parentEvent = await callAdapterEventHandler(
+ adapter,
+ createSubagentCalledEvent({
+ callId: outcome.callId,
+ childSessionId: outcome.address.sessionId,
+ name: outcome.name,
+ remote:
+ outcome.address.kind === "agent/remote" ? { url: outcome.address.url } : undefined,
+ sequence: batch.event.sequence,
+ sessionId: session.sessionId,
+ toolName: outcome.toolName,
+ turnId: batch.event.turnId,
+ workflowId: workflowEntryReference.workflowId,
+ }),
+ adapterCtx,
+ );
+ await writer.write(encodeMessageStreamEvent(stampMessageStreamEvent(parentEvent)));
+ } catch (error) {
+ logError(log, "subagent.called emission failed", error, {
+ callId: outcome.callId,
+ childSessionId: outcome.address.sessionId,
+ toolName: outcome.toolName,
+ });
}
-
- const parentEvent = await callAdapterEventHandler(
- adapter,
- createSubagentCalledEvent({
- callId: action.callId,
- childSessionId,
- name,
- remote,
- sequence: batch.event.sequence,
- sessionId: session.sessionId,
- toolName,
- turnId: batch.event.turnId,
- workflowId: workflowEntryReference.workflowId,
- }),
- adapterCtx,
- );
- await writer.write(encodeMessageStreamEvent(stampMessageStreamEvent(parentEvent)));
}
} finally {
writer.releaseLock();
@@ -284,17 +228,400 @@ export async function dispatchRuntimeActionsStep(input: {
? input.sessionState
: createDurableSessionState({ session: nextSession });
- return { results, sessionState: nextState };
+ return {
+ results,
+ sessionState: nextState,
+ };
+}
+
+/**
+ * Classifies every batch action before anything dispatches, so invalid
+ * batches fail without starting children and rejections never interleave
+ * with dispatch work.
+ */
+function planDispatch(input: {
+ readonly actions: readonly RuntimeActionRequest[];
+ readonly bundle: CompiledBundle;
+ readonly ctx: Parameters<typeof getDynamicSubagentSelection>[0];
+ readonly session: RuntimeSession;
+}): DispatchPlanEntry[] {
+ const registry = input.bundle.subagentRegistry.subagentsByNodeId;
+ const subagentDepth = resolveSubagentDepth(input.session);
+ const rootOnly = input.session.rootSessionId !== undefined || subagentDepth.currentDepth > 0;
+
+ return input.actions.map((action): DispatchPlanEntry => {
+ const isDynamicSubagent =
+ (action.kind === "subagent-call" || action.kind === "remote-agent-call") &&
+ input.bundle.subagentRegistry.dynamicNodeIds?.has(action.nodeId) === true;
+ const dynamicSubagentSelection = isDynamicSubagent
+ ? getDynamicSubagentSelection(input.ctx, action.nodeId)
+ : undefined;
+ if (
+ isDynamicSubagent &&
+ (dynamicSubagentSelection === undefined ||
+ (action.kind === "subagent-call" && dynamicSubagentSelection.kind !== "subagent") ||
+ (action.kind === "remote-agent-call" && dynamicSubagentSelection.kind !== "remote"))
+ ) {
+ const subagentName = getSubagentName(action);
+ log.warn("dynamic subagent call blocked after availability changed", {
+ callId: action.callId,
+ nodeId: action.nodeId,
+ subagentName,
+ });
+ return { kind: "reject", result: createUnavailableDynamicSubagentResult(action) };
+ }
+
+ if (isRecursiveAgentAction(action, registry) && rootOnly) {
+ log.warn("recursive agent call blocked outside the root session", {
+ callId: action.callId,
+ currentDepth: subagentDepth.currentDepth,
+ nodeId: action.nodeId,
+ subagentName: action.subagentName,
+ });
+ return { kind: "reject", result: createRecursiveAgentRootOnlyResult(action) };
+ }
+
+ switch (action.kind) {
+ case "subagent-call": {
+ const dynamicAgentConfig =
+ dynamicSubagentSelection?.kind === "subagent"
+ ? dynamicSubagentSelection.agentConfig
+ : undefined;
+ const registered = registry.get(action.nodeId);
+ const description =
+ dynamicAgentConfig?.description ??
+ (registered?.definition.kind === "subagent"
+ ? registered.definition.description
+ : undefined);
+ const source: SubagentInputSource =
+ description !== undefined ? { description, type: "local" } : { type: "runtime" };
+ return {
+ kind: "start",
+ target: {
+ action,
+ dynamicSubagentAgentConfig: dynamicAgentConfig,
+ kind: "local",
+ source,
+ },
+ };
+ }
+ case "remote-agent-call":
+ return {
+ kind: "start",
+ target: {
+ action,
+ dynamicRemoteAgent:
+ dynamicSubagentSelection?.kind === "remote"
+ ? dynamicSubagentSelection.remoteAgent
+ : undefined,
+ kind: "remote",
+ },
+ };
+ default:
+ throw new Error(`Unsupported runtime action kind "${action.kind}" in workflow runtime.`);
+ }
+ });
+}
+
+async function startSubagent(input: {
+ readonly auth: Parameters<typeof buildSubagentRunInput>[0]["auth"];
+ readonly batchEvent: { readonly sequence: number; readonly turnId: string };
+ readonly bundle: CompiledBundle;
+ readonly callbackBaseUrl: string | undefined;
+ readonly capabilities: Parameters<typeof buildSubagentRunInput>[0]["capabilities"];
+ readonly channelMetadata: Parameters<typeof buildSubagentRunInput>[0]["channelMetadata"];
+ readonly currentSession: RuntimeSession;
+ readonly fanoutSize: number;
+ readonly initiatorAuth: Parameters<typeof buildSubagentRunInput>[0]["initiatorAuth"];
+ readonly parentContinuationToken: string | undefined;
+ readonly parentTraceContext: Parameters<typeof buildSubagentRunInput>[0]["parentTraceContext"];
+ readonly session: RuntimeSession;
+ readonly target: DispatchStartTarget;
+}): Promise<DispatchOutcome> {
+ switch (input.target.kind) {
+ case "local":
+ return startLocalSubagent({
+ action: input.target.action,
+ auth: input.auth,
+ batchEvent: input.batchEvent,
+ bundle: input.bundle,
+ capabilities: input.capabilities,
+ channelMetadata: input.channelMetadata,
+ currentSession: input.currentSession,
+ dynamicSubagentAgentConfig: input.target.dynamicSubagentAgentConfig,
+ fanoutSize: input.fanoutSize,
+ initiatorAuth: input.initiatorAuth,
+ parentContinuationToken: input.parentContinuationToken,
+ parentTraceContext: input.parentTraceContext,
+ session: input.session,
+ source: input.target.source,
+ });
+ case "remote":
+ return startRemoteSubagent({
+ action: input.target.action,
+ auth: input.auth,
+ batchEvent: input.batchEvent,
+ bundle: input.bundle,
+ callbackBaseUrl: input.callbackBaseUrl,
+ currentSession: input.currentSession,
+ dynamicRemoteAgent: input.target.dynamicRemoteAgent,
+ initiatorAuth: input.initiatorAuth,
+ parentContinuationToken: input.parentContinuationToken,
+ session: input.session,
+ });
+ default: {
+ const _exhaustive: never = input.target;
+ return _exhaustive;
+ }
+ }
+}
+
+/**
+ * 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"];
+ readonly batchEvent: { readonly sequence: number; readonly turnId: string };
+ readonly bundle: CompiledBundle;
+ readonly capabilities: Parameters<typeof buildSubagentRunInput>[0]["capabilities"];
+ readonly channelMetadata: Parameters<typeof buildSubagentRunInput>[0]["channelMetadata"];
+ readonly currentSession: RuntimeSession;
+ readonly dynamicSubagentAgentConfig?: DynamicSubagentAgentConfig;
+ readonly fanoutSize: number;
+ readonly initiatorAuth: Parameters<typeof buildSubagentRunInput>[0]["initiatorAuth"];
+ readonly parentContinuationToken: string | undefined;
+ readonly parentTraceContext: Parameters<typeof buildSubagentRunInput>[0]["parentTraceContext"];
+ readonly session: RuntimeSession;
+ readonly source: SubagentInputSource;
+}): Promise<DispatchOutcome> {
+ const { action, source } = input;
+ const childRuntime = createWorkflowRuntime({
+ compiledArtifactsSource: input.bundle.compiledArtifactsSource,
+ dynamicSubagentAgentConfig: input.dynamicSubagentAgentConfig,
+ nodeId: action.nodeId,
+ });
+ const { childContinuationToken, runInput } = buildSubagentRunInput({
+ action,
+ auth: input.auth,
+ batchEvent: input.batchEvent,
+ capabilities: input.capabilities,
+ channelMetadata: input.channelMetadata,
+ fanoutSize: input.fanoutSize,
+ initiatorAuth: input.initiatorAuth,
+ parentContinuationToken: input.parentContinuationToken,
+ parentTraceContext: input.parentTraceContext,
+ session: input.session,
+ source,
+ });
+
+ const targetKind = source.type === "runtime" ? ("agent/self" as const) : ("agent/local" as const);
+ const { identity, operation } = mintStartOperation({
+ callId: action.callId,
+ name: action.subagentName,
+ nodeId: action.nodeId,
+ parentSessionId: input.session.sessionId,
+ parentTurnId: input.batchEvent.turnId,
+ });
+ // Ownership is recorded before the start side effect, and the prepared
+ // (or rejected) store rides every outcome into the step result. The
+ // guarantee is intra-step: a crash between the accepted start and the
+ // step-result commit still replays the whole dispatch step, so the
+ // orphan window shrinks to that boundary rather than disappearing.
+ const preparedSession = prepareAgentStart(input.currentSession, {
+ identity,
+ operation,
+ target: { continuationToken: childContinuationToken, kind: targetKind },
+ });
+
+ let childSessionId: string;
+ try {
+ const handle = await childRuntime.run(runInput);
+ childSessionId = handle.sessionId;
+ } catch (error) {
+ logError(log, "local subagent start failed", error, {
+ callId: action.callId,
+ nodeId: action.nodeId,
+ subagentName: action.subagentName,
+ });
+ return {
+ kind: "error",
+ result: {
+ callId: action.callId,
+ isError: true,
+ kind: "subagent-result",
+ origin: "dispatch",
+ output: {
+ code: SUBAGENT_START_FAILED,
+ message: toErrorMessage(error),
+ },
+ subagentName: action.subagentName,
+ },
+ session: rejectAgentEffect(preparedSession, {
+ disposition: "dead",
+ operationId: operation.id,
+ }),
+ };
+ }
+
+ const address = {
+ continuationToken: childContinuationToken,
+ kind: targetKind,
+ sessionId: childSessionId,
+ } as const;
+ return {
+ address,
+ callId: action.callId,
+ kind: "called",
+ name: action.name,
+ session: confirmAgentStarted(preparedSession, {
+ address,
+ operationId: operation.id,
+ }),
+ toolName: action.subagentName,
+ };
+}
+
+async function startRemoteSubagent(input: {
+ readonly action: RuntimeRemoteAgentCallActionRequest;
+ readonly auth: Parameters<typeof startRemoteAgentSession>[0]["auth"];
+ readonly batchEvent: { readonly sequence: number; readonly turnId: string };
+ readonly bundle: CompiledBundle;
+ readonly callbackBaseUrl: string | undefined;
+ readonly currentSession: RuntimeSession;
+ readonly dynamicRemoteAgent?: DynamicRemoteAgentConfig;
+ readonly initiatorAuth: Parameters<typeof startRemoteAgentSession>[0]["initiatorAuth"];
+ readonly parentContinuationToken: string | undefined;
+ readonly session: RuntimeSession;
+}): Promise<DispatchOutcome> {
+ const { action } = input;
+
+ // Preflight resolution failures happen before ownership exists, so they
+ // reject without touching the handle store.
+ let callbackBaseUrl: string;
+ let resolvedRemote: ReturnType<typeof resolveRemoteAgentForAction>;
+ try {
+ if (input.callbackBaseUrl === undefined) {
+ throw new Error("Cannot dispatch remote agent without a callback base URL.");
+ }
+ callbackBaseUrl = input.callbackBaseUrl;
+ resolvedRemote = resolveRemoteAgentForAction({
+ dynamicRemoteAgent: input.dynamicRemoteAgent,
+ nodeId: action.nodeId,
+ remoteAgentName: action.remoteAgentName,
+ registry: input.bundle.subagentRegistry.subagentsByNodeId,
+ });
+ } catch (error) {
+ logError(log, "remote agent start failed", error, {
+ remoteAgentName: action.remoteAgentName,
+ nodeId: action.nodeId,
+ callId: action.callId,
+ });
+ return {
+ kind: "error",
+ result: createRemoteAgentStartFailureResult({ action, error }),
+ session: input.currentSession,
+ };
+ }
+
+ const { identity, operation } = mintStartOperation({
+ callId: action.callId,
+ name: action.remoteAgentName,
+ nodeId: action.nodeId,
+ parentSessionId: input.session.sessionId,
+ parentTurnId: input.batchEvent.turnId,
+ });
+ const preparedSession = prepareAgentStart(input.currentSession, {
+ identity,
+ operation,
+ target: { callbackBaseUrl, kind: "agent/remote", url: resolvedRemote.url },
+ });
+
+ try {
+ const child = await startRemoteAgentSession({
+ action,
+ auth: input.auth,
+ callbackBaseUrl,
+ callbackToken: input.parentContinuationToken,
+ initiatorAuth: input.initiatorAuth,
+ remote: resolvedRemote,
+ session: input.session,
+ });
+ const address = {
+ callbackBaseUrl,
+ kind: "agent/remote",
+ sessionId: child.sessionId,
+ url: resolvedRemote.url,
+ ...(child.continuationToken === undefined
+ ? {}
+ : { continuationToken: child.continuationToken }),
+ } as const;
+ return {
+ address,
+ callId: action.callId,
+ kind: "called",
+ name: action.name,
+ session: confirmAgentStarted(preparedSession, {
+ address,
+ operationId: operation.id,
+ }),
+ toolName: action.remoteAgentName,
+ };
+ } catch (error) {
+ logError(log, "remote agent start failed", error, {
+ remoteAgentName: action.remoteAgentName,
+ nodeId: action.nodeId,
+ callId: action.callId,
+ });
+ return {
+ kind: "error",
+ result: createRemoteAgentStartFailureResult({ action, error }),
+ session: rejectAgentEffect(preparedSession, {
+ disposition: "dead",
+ operationId: operation.id,
+ }),
+ };
+ }
}
function createUnavailableDynamicSubagentResult(
action: RuntimeSubagentCallActionRequest | RuntimeRemoteAgentCallActionRequest,
-): RuntimeSubagentResultActionResult {
+): 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.`,
@@ -312,13 +639,14 @@ function getSubagentName(
function createRemoteAgentStartFailureResult(input: {
readonly action: RuntimeRemoteAgentCallActionRequest;
readonly error: unknown;
-}): RuntimeSubagentResultActionResult {
+}): RuntimeSubagentDispatchFailure {
return {
callId: input.action.callId,
isError: true,
kind: "subagent-result",
+ origin: "dispatch",
output: {
- code: "REMOTE_AGENT_START_FAILED",
+ code: REMOTE_AGENT_START_FAILED,
message: toErrorMessage(input.error),
},
subagentName: input.action.remoteAgentName,
@@ -327,11 +655,12 @@ function createRemoteAgentStartFailureResult(input: {
function createRecursiveAgentRootOnlyResult(
action: RuntimeSubagentCallActionRequest,
-): RuntimeSubagentResultActionResult {
+): 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.',
diff --git a/packages/eve/src/execution/dispatch-workflow-runtime-actions-step.ts b/packages/eve/src/execution/dispatch-workflow-runtime-actions-step.ts
index 48d62b9c1..47379b3f6 100644
--- a/packages/eve/src/execution/dispatch-workflow-runtime-actions-step.ts
+++ b/packages/eve/src/execution/dispatch-workflow-runtime-actions-step.ts
@@ -18,7 +18,8 @@ import { createLogger } from "#internal/logging.js";
import { BundleKey } from "#runtime/sessions/runtime-context-keys.js";
import type {
RuntimeActionRequest,
- RuntimeSubagentResultActionResult,
+ RuntimeSubagentDispatchFailure,
+ RuntimeSubagentResult,
} from "#runtime/actions/types.js";
import { resolveEffectiveAgentRuntime } from "#execution/effective-agent-config.js";
@@ -32,7 +33,7 @@ export async function dispatchWorkflowRuntimeActionsStep(input: {
readonly serializedContext: Record<string, unknown>;
readonly sessionState: DurableSessionState;
}): Promise<{
- readonly results: readonly RuntimeSubagentResultActionResult[];
+ readonly results: readonly RuntimeSubagentResult[];
readonly sessionState: DurableSessionState;
}> {
"use step";
@@ -106,7 +107,7 @@ export async function dispatchWorkflowRuntimeActionsStep(input: {
function createWorkflowSubagentLimitResult(input: {
readonly action: RuntimeActionRequest;
readonly plan: WorkflowSubagentDispatchPlan;
-}): RuntimeSubagentResultActionResult {
+}): RuntimeSubagentDispatchFailure {
const subagentName = isSubagentDelegationAction(input.action)
? getSubagentDelegationName(input.action)
: input.action.kind;
@@ -115,6 +116,7 @@ function createWorkflowSubagentLimitResult(input: {
callId: input.action.callId,
isError: true,
kind: "subagent-result",
+ origin: "dispatch",
output: {
code: "WORKFLOW_SUBAGENT_LIMIT_REACHED",
maxSubagents: input.plan.maxSubagents,
diff --git a/packages/eve/src/execution/durable-session-migrations/turn-workflow.ts b/packages/eve/src/execution/durable-session-migrations/turn-workflow.ts
index c5d546cf7..08c06615c 100644
--- a/packages/eve/src/execution/durable-session-migrations/turn-workflow.ts
+++ b/packages/eve/src/execution/durable-session-migrations/turn-workflow.ts
@@ -10,8 +10,13 @@
* deployment still runs after a rollout. Future shape changes bump
* {@link TURN_WORKFLOW_INPUT_VERSION} and append a v{N} → v{N+1} migration.
*/
-import type { HookPayload, SessionCapabilities } from "#channel/types.js";
+import type {
+ HookPayload,
+ RuntimeActionResultHookPayload,
+ SessionCapabilities,
+} from "#channel/types.js";
import type { DurableSessionState } from "#execution/durable-session-store.js";
+import type { RuntimeActionResult } from "#runtime/actions/types.js";
import type { RunMode } from "#shared/run-mode.js";
import { runMigrationChain, type VersionMigration } from "./chain.js";
@@ -19,10 +24,20 @@ import { turnWorkflowInputV0ToV1 } from "./turn-workflow-v0-to-v1.js";
export const TURN_WORKFLOW_INPUT_VERSION = 1;
+/** Trusted runtime-action results collected by the parent turn driver. */
+interface RuntimeActionResultStepInput {
+ readonly kind: "runtime-action-result";
+ readonly results: readonly RuntimeActionResult[];
+}
+
+export type TurnStepPayload =
+ | Exclude<HookPayload, RuntimeActionResultHookPayload>
+ | RuntimeActionResultStepInput;
+
export interface TurnStepInput {
/** Cancellation signal forwarded into the turn step. */
readonly abortSignal?: AbortSignal;
- readonly input: HookPayload | undefined;
+ readonly input: TurnStepPayload | undefined;
readonly parentWritable: WritableStream<Uint8Array>;
readonly serializedContext: Record<string, unknown>;
readonly sessionState: DurableSessionState;
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.ts
index 6a6c74e6b..e80a82bdd 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
@@ -220,7 +220,7 @@ describe("multi-agent callback routing", () => {
deploymentOrigin = await listen(deploymentServer);
// Remote subagent: records the create-session body and returns a session
- // id, like the eve channel's create-session route.
+ // id and continuation token, like the eve channel's create-session route.
remoteAgentServer = createServer((request, response) => {
const chunks: Buffer[] = [];
request.on("data", (chunk: Buffer) => chunks.push(chunk));
@@ -230,7 +230,12 @@ describe("multi-agent callback routing", () => {
"content-type": "application/json",
[EVE_SESSION_ID_HEADER]: "remote-session-1",
});
- response.end(JSON.stringify({ ok: true }));
+ response.end(
+ JSON.stringify({
+ continuationToken: "remote-session-1:continuation",
+ ok: true,
+ }),
+ );
});
});
remoteAgentOrigin = await listen(remoteAgentServer);
@@ -266,7 +271,7 @@ describe("multi-agent callback routing", () => {
const callbackToken = `${sessionId}:callback-token`;
const bodyCountBefore = createSessionBodies.length;
- const remoteSessionId = await startRemoteAgentSession({
+ const { sessionId: remoteSessionId } = await startRemoteAgentSession({
action: {
callId: `call-${agentName}`,
description: "delegate research",
diff --git a/packages/eve/src/execution/node-step.ts b/packages/eve/src/execution/node-step.ts
index a5389e599..b2f3ff2eb 100644
--- a/packages/eve/src/execution/node-step.ts
+++ b/packages/eve/src/execution/node-step.ts
@@ -99,6 +99,8 @@ export function createExecutionNodeStep(input: CreateExecutionNodeStepInput): St
instrumentation,
mode: input.mode,
onCompaction: preserveFrameworkStateOnCompaction,
+ persistentSubagentSessions:
+ input.node.agent.config?.experimental?.subagentPersistentSessions === true,
dispatchDynamicModelEvent: dispatchModelEvent,
resolveModel,
runtimeIdentity: buildRuntimeIdentity(input.node),
diff --git a/packages/eve/src/execution/remote-agent-dispatch.test.ts b/packages/eve/src/execution/remote-agent-dispatch.test.ts
index 2f2786df9..2a8004cbf 100644
--- a/packages/eve/src/execution/remote-agent-dispatch.test.ts
+++ b/packages/eve/src/execution/remote-agent-dispatch.test.ts
@@ -76,10 +76,17 @@ describe("startRemoteAgentSession", () => {
it("posts the formatted subagent message and callback metadata", async () => {
const fetchMock = vi.fn().mockResolvedValue(
- new Response(JSON.stringify({ ok: true, sessionId: "remote-session" }), {
- headers: { "x-eve-session-id": "remote-session-header" },
- status: 202,
- }),
+ new Response(
+ JSON.stringify({
+ continuationToken: "remote-token",
+ ok: true,
+ sessionId: "remote-session",
+ }),
+ {
+ headers: { "x-eve-session-id": "remote-session-header" },
+ status: 202,
+ },
+ ),
);
vi.stubGlobal("fetch", fetchMock);
@@ -104,7 +111,10 @@ describe("startRemoteAgentSession", () => {
},
});
- expect(childSessionId).toBe("remote-session-header");
+ expect(childSessionId).toEqual({
+ continuationToken: "remote-token",
+ sessionId: "remote-session-header",
+ });
expect(fetchMock).toHaveBeenCalledWith("https://remote.example.com/eve/v1/session", {
body: expect.any(String),
headers: {
@@ -130,15 +140,81 @@ describe("startRemoteAgentSession", () => {
"Caller message:",
"find the marker",
].join("\n"),
+ capabilities: {},
mode: "task",
});
});
+ it("accepts a create-session response without a continuationToken from an older deployment", async () => {
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValue(
+ new Response(JSON.stringify({ ok: true, sessionId: "remote-session" }), { status: 202 }),
+ );
+ vi.stubGlobal("fetch", fetchMock);
+
+ const coordinates = await startRemoteAgentSession({
+ action: createAction(),
+ callbackBaseUrl: "https://caller.example.com",
+ remote: createRemoteAgent(),
+ session: {
+ agent: {
+ modelReference: { id: "mock/test" },
+ system: "",
+ tools: [],
+ },
+ compaction: {
+ recentWindowSize: 10,
+ threshold: 100000,
+ },
+ continuationToken: "eve:parent-token",
+ history: [],
+ sessionId: "parent-session",
+ state: {},
+ },
+ });
+
+ expect(coordinates).toEqual({ sessionId: "remote-session" });
+ });
+
+ it("rejects a create-session response without any sessionId", async () => {
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValue(new Response(JSON.stringify({ ok: true }), { status: 202 }));
+ vi.stubGlobal("fetch", fetchMock);
+
+ await expect(
+ startRemoteAgentSession({
+ action: createAction(),
+ callbackBaseUrl: "https://caller.example.com",
+ remote: createRemoteAgent(),
+ session: {
+ agent: {
+ modelReference: { id: "mock/test" },
+ system: "",
+ tools: [],
+ },
+ compaction: {
+ recentWindowSize: 10,
+ threshold: 100000,
+ },
+ continuationToken: "eve:parent-token",
+ history: [],
+ sessionId: "parent-session",
+ state: {},
+ },
+ }),
+ ).rejects.toThrow("create-session response did not include a sessionId");
+ });
+
it("preserves a prefixed remote base path on create-session requests", async () => {
const fetchMock = vi
.fn()
.mockResolvedValue(
- new Response(JSON.stringify({ sessionId: "remote-session" }), { status: 202 }),
+ new Response(
+ JSON.stringify({ continuationToken: "remote-token", sessionId: "remote-session" }),
+ { status: 202 },
+ ),
);
vi.stubGlobal("fetch", fetchMock);
@@ -166,10 +242,17 @@ describe("startRemoteAgentSession", () => {
it("sends a declared outputSchema on the remote create-session request", async () => {
const fetchMock = vi.fn().mockResolvedValue(
- new Response(JSON.stringify({ ok: true, sessionId: "remote-session" }), {
- headers: { "x-eve-session-id": "remote-session-header" },
- status: 202,
- }),
+ new Response(
+ JSON.stringify({
+ continuationToken: "remote-token",
+ ok: true,
+ sessionId: "remote-session",
+ }),
+ {
+ headers: { "x-eve-session-id": "remote-session-header" },
+ status: 202,
+ },
+ ),
);
vi.stubGlobal("fetch", fetchMock);
@@ -196,6 +279,7 @@ describe("startRemoteAgentSession", () => {
const body = JSON.parse(fetchMock.mock.calls[0]?.[1]?.body as string);
expect(body.outputSchema).toEqual(outputSchema);
expect(body.mode).toBe("task");
+ expect(body.capabilities).toEqual({});
});
it("ignores an empty model-passed outputSchema instead of forwarding it", async () => {
@@ -204,9 +288,16 @@ describe("startRemoteAgentSession", () => {
// the remote child into structured-output mode and discards its text
// reply — local subagent dispatch already drops it; remote must match.
const fetchMock = vi.fn().mockResolvedValue(
- new Response(JSON.stringify({ ok: true, sessionId: "remote-session" }), {
- status: 202,
- }),
+ new Response(
+ JSON.stringify({
+ continuationToken: "remote-token",
+ ok: true,
+ sessionId: "remote-session",
+ }),
+ {
+ status: 202,
+ },
+ ),
);
vi.stubGlobal("fetch", fetchMock);
@@ -233,7 +324,10 @@ describe("startRemoteAgentSession", () => {
const fetchMock = vi
.fn()
.mockResolvedValue(
- new Response(JSON.stringify({ sessionId: "remote-session" }), { status: 202 }),
+ new Response(
+ JSON.stringify({ continuationToken: "remote-token", sessionId: "remote-session" }),
+ { status: 202 },
+ ),
);
vi.stubGlobal("fetch", fetchMock);
@@ -261,11 +355,16 @@ describe("startRemoteAgentSession", () => {
it("adds the Vercel automation bypass secret to callback URLs", async () => {
vi.stubEnv("VERCEL_AUTOMATION_BYPASS_SECRET", "remote callback secret");
- const fetchMock = vi
- .fn()
- .mockResolvedValue(
- new Response(JSON.stringify({ ok: true, sessionId: "remote-session" }), { status: 202 }),
- );
+ const fetchMock = vi.fn().mockResolvedValue(
+ new Response(
+ JSON.stringify({
+ continuationToken: "remote-token",
+ ok: true,
+ sessionId: "remote-session",
+ }),
+ { status: 202 },
+ ),
+ );
vi.stubGlobal("fetch", fetchMock);
await startRemoteAgentSession({
@@ -323,9 +422,12 @@ describe("startRemoteAgentSession — forwarded principal", () => {
};
function createSessionResponse(): Response {
- return new Response(JSON.stringify({ ok: true, sessionId: "remote-session" }), {
- status: 202,
- });
+ return new Response(
+ JSON.stringify({ continuationToken: "remote-token", ok: true, sessionId: "remote-session" }),
+ {
+ status: 202,
+ },
+ );
}
function createSession() {
@@ -351,7 +453,7 @@ describe("startRemoteAgentSession — forwarded principal", () => {
remote: { ...createRemoteAgent(), forwardPrincipal: true },
session: createSession(),
}),
- ).resolves.toBe("remote-session");
+ ).resolves.toEqual({ continuationToken: "remote-token", sessionId: "remote-session" });
expect(JSON.parse(fetchMock.mock.calls[0]?.[1]?.body as string).forwardedPrincipal).toEqual({
current: CURRENT_AUTH,
@@ -378,11 +480,16 @@ describe("startRemoteAgentSession — forwarded principal", () => {
});
it("omits the field when the turn has no auth", async () => {
- const fetchMock = vi
- .fn()
- .mockResolvedValue(
- new Response(JSON.stringify({ ok: true, sessionId: "remote-session" }), { status: 202 }),
- );
+ const fetchMock = vi.fn().mockResolvedValue(
+ new Response(
+ JSON.stringify({
+ continuationToken: "remote-token",
+ ok: true,
+ sessionId: "remote-session",
+ }),
+ { status: 202 },
+ ),
+ );
vi.stubGlobal("fetch", fetchMock);
await expect(
@@ -394,7 +501,7 @@ describe("startRemoteAgentSession — forwarded principal", () => {
remote: { ...createRemoteAgent(), forwardPrincipal: true },
session: createSession(),
}),
- ).resolves.toBe("remote-session");
+ ).resolves.toEqual({ continuationToken: "remote-token", sessionId: "remote-session" });
expect(JSON.parse(fetchMock.mock.calls[0]?.[1]?.body as string)).not.toHaveProperty(
"forwardedPrincipal",
@@ -402,11 +509,16 @@ describe("startRemoteAgentSession — forwarded principal", () => {
});
it("does not forward when forwardPrincipal is unset even with auth in scope", async () => {
- const fetchMock = vi
- .fn()
- .mockResolvedValue(
- new Response(JSON.stringify({ ok: true, sessionId: "remote-session" }), { status: 202 }),
- );
+ const fetchMock = vi.fn().mockResolvedValue(
+ new Response(
+ JSON.stringify({
+ continuationToken: "remote-token",
+ ok: true,
+ sessionId: "remote-session",
+ }),
+ { status: 202 },
+ ),
+ );
vi.stubGlobal("fetch", fetchMock);
await expect(
@@ -418,7 +530,7 @@ describe("startRemoteAgentSession — forwarded principal", () => {
remote: createRemoteAgent(),
session: createSession(),
}),
- ).resolves.toBe("remote-session");
+ ).resolves.toEqual({ continuationToken: "remote-token", sessionId: "remote-session" });
expect(JSON.parse(fetchMock.mock.calls[0]?.[1]?.body as string)).not.toHaveProperty(
"forwardedPrincipal",
diff --git a/packages/eve/src/execution/remote-agent-dispatch.ts b/packages/eve/src/execution/remote-agent-dispatch.ts
index 95f4be150..8348e4d60 100644
--- a/packages/eve/src/execution/remote-agent-dispatch.ts
+++ b/packages/eve/src/execution/remote-agent-dispatch.ts
@@ -1,3 +1,4 @@
+import { z } from "#compiled/zod/index.js";
import { EVE_SESSION_ID_HEADER } from "#protocol/message.js";
import { CancelTurnResponseSchema } from "#protocol/cancel-turn.js";
import { createEveCallbackRoutePath, createEveCancelTurnRoutePath } from "#protocol/routes.js";
@@ -16,6 +17,19 @@ import type { DynamicRemoteAgentConfig } from "#runtime/subagents/dynamic-remote
import type { ResolvedRuntimeRemoteAgentNode } from "#runtime/types.js";
import { expectFunction, expectObjectRecord } from "#internal/authored-module.js";
+const CreateSessionResponseSchema = z.object({
+ // Older eve deployments do not return a continuationToken. Their children
+ // still run to completion as task-mode one-shots; they just can never be
+ // continued, so the handle records no token.
+ continuationToken: z.string().min(1).optional(),
+ sessionId: z.string().min(1).optional(),
+});
+
+type RemoteAgentSessionCoordinates = {
+ readonly continuationToken?: string;
+ readonly sessionId: string;
+};
+
class RemoteAgentCancelRequestError extends Error {
readonly retryable: boolean;
@@ -36,7 +50,7 @@ export async function startRemoteAgentSession(input: {
readonly initiatorAuth?: SessionAuthContext | null;
readonly remote: ResolvedRuntimeRemoteAgentNode;
readonly session: HarnessSession;
-}): Promise<string> {
+}): Promise<RemoteAgentSessionCoordinates> {
const callbackToken = input.callbackToken ?? input.session.continuationToken;
if (!callbackToken) {
throw new Error("Cannot dispatch remote agent without a parent continuation token.");
@@ -47,6 +61,7 @@ export async function startRemoteAgentSession(input: {
const forwardedPrincipal = buildForwardedPrincipalField(input);
const requestBody: {
+ capabilities: {};
callback: {
callId: string;
subagentName: string;
@@ -55,9 +70,10 @@ export async function startRemoteAgentSession(input: {
};
forwardedPrincipal?: ForwardedPrincipal;
message: string;
- mode: "task";
+ mode: "conversation" | "task";
outputSchema?: object;
} = {
+ capabilities: {},
callback: {
callId: input.action.callId,
subagentName: input.action.remoteAgentName,
@@ -68,6 +84,8 @@ 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",
outputSchema:
normalizeRequestedOutputSchema(input.action.input.outputSchema) ?? input.remote.outputSchema,
@@ -92,23 +110,33 @@ export async function startRemoteAgentSession(input: {
);
}
- const sessionIdFromHeader = response.headers.get(EVE_SESSION_ID_HEADER);
- if (sessionIdFromHeader !== null && sessionIdFromHeader.length > 0) {
- return sessionIdFromHeader;
- }
-
+ let body: unknown;
try {
- const body = (await response.json()) as { readonly sessionId?: unknown };
- if (typeof body.sessionId === "string" && body.sessionId.length > 0) {
- return body.sessionId;
- }
+ body = await response.json();
} catch {
- // Fall through to the generic error below.
+ throw new Error(
+ `Remote agent "${input.action.remoteAgentName}" create-session response was not valid JSON.`,
+ );
+ }
+
+ const parsed = CreateSessionResponseSchema.safeParse(body);
+ const sessionIdFromHeader = response.headers.get(EVE_SESSION_ID_HEADER);
+ const sessionId =
+ sessionIdFromHeader !== null && sessionIdFromHeader.length > 0
+ ? sessionIdFromHeader
+ : parsed.success
+ ? parsed.data.sessionId
+ : undefined;
+
+ if (!parsed.success || sessionId === undefined) {
+ throw new Error(
+ `Remote agent "${input.action.remoteAgentName}" create-session response did not include a sessionId.`,
+ );
}
- throw new Error(
- `Remote agent "${input.action.remoteAgentName}" create-session response did not include a session id.`,
- );
+ return parsed.data.continuationToken === undefined
+ ? { sessionId }
+ : { continuationToken: parsed.data.continuationToken, sessionId };
}
function buildForwardedPrincipalField(input: {
@@ -175,12 +203,12 @@ export function isRetryableRemoteAgentCancelError(error: unknown): boolean {
return !(error instanceof RemoteAgentCancelRequestError) || error.retryable;
}
-export async function resolveRemoteAgentForAction(input: {
+export function resolveRemoteAgentForAction(input: {
readonly dynamicRemoteAgent?: DynamicRemoteAgentConfig;
readonly nodeId: string;
readonly registry: RuntimeSubagentRegistry["subagentsByNodeId"];
readonly remoteAgentName: string;
-}): Promise<ResolvedRuntimeRemoteAgentNode> {
+}): ResolvedRuntimeRemoteAgentNode {
const registered = input.registry.get(input.nodeId);
const definition = registered?.definition;
if (input.dynamicRemoteAgent !== undefined) {
diff --git a/packages/eve/src/execution/session-callback-request.ts b/packages/eve/src/execution/session-callback-request.ts
index f24901809..3a13059f2 100644
--- a/packages/eve/src/execution/session-callback-request.ts
+++ b/packages/eve/src/execution/session-callback-request.ts
@@ -11,6 +11,9 @@ export async function postSessionCallbackRequest(input: {
"content-type": "application/json",
},
method: "POST",
+ // Do not follow redirects: a validated callback host could otherwise
+ // 3xx-bounce the framework to an internal/metadata address after the
+ // path/token check has already passed.
redirect: "error",
signal: AbortSignal.timeout(SESSION_CALLBACK_TIMEOUT_MS),
});
diff --git a/packages/eve/src/execution/session-callback-step.ts b/packages/eve/src/execution/session-callback-step.ts
index f74b72245..ceed02bac 100644
--- a/packages/eve/src/execution/session-callback-step.ts
+++ b/packages/eve/src/execution/session-callback-step.ts
@@ -1,11 +1,12 @@
import type { SessionCallback } from "#channel/types.js";
import { parseSessionCallback } from "#channel/session-callback.js";
import { SessionCallbackKey } from "#context/keys.js";
+import { postSessionCallbackRequest } from "#execution/session-callback-request.js";
+import { SESSION_FAILED } from "#harness/agent-handle-errors.js";
import { createLogger } from "#internal/logging.js";
import { toErrorMessage } from "#shared/errors.js";
import type { TokenUsage } from "#shared/token-usage.js";
-const SESSION_CALLBACK_TIMEOUT_MS = 30_000;
const log = createLogger("execution.session-callback");
/**
@@ -50,7 +51,7 @@ export async function fireSessionCallbackStep(input: {
: {
callId: callback.callId,
error: {
- code: "SESSION_FAILED",
+ code: SESSION_FAILED,
message: toErrorMessage(input.error),
},
kind: "session.failed" as const,
@@ -58,18 +59,7 @@ export async function fireSessionCallbackStep(input: {
subagentName: callback.subagentName,
};
- const response = await fetch(callback.url, {
- body: JSON.stringify(body),
- headers: {
- "content-type": "application/json",
- },
- method: "POST",
- // Do not follow redirects: a validated callback host could otherwise
- // 3xx-bounce the framework to an internal/metadata address after the
- // path/token check has already passed.
- redirect: "error",
- signal: AbortSignal.timeout(SESSION_CALLBACK_TIMEOUT_MS),
- });
+ const response = await postSessionCallbackRequest({ body, url: callback.url });
if (!response.ok) {
throw new Error(`Session callback failed with HTTP ${response.status}.`);
diff --git a/packages/eve/src/execution/subagent-tool.ts b/packages/eve/src/execution/subagent-tool.ts
index 64e49af32..dc62d7cbb 100644
--- a/packages/eve/src/execution/subagent-tool.ts
+++ b/packages/eve/src/execution/subagent-tool.ts
@@ -128,6 +128,9 @@ 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",
parent: {
callId: action.callId,
diff --git a/packages/eve/src/execution/subagent-usage-span.test.ts b/packages/eve/src/execution/subagent-usage-span.test.ts
index 64a42ec85..936a63051 100644
--- a/packages/eve/src/execution/subagent-usage-span.test.ts
+++ b/packages/eve/src/execution/subagent-usage-span.test.ts
@@ -1,7 +1,7 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { recordSubagentUsageSpans } from "#execution/subagent-usage-span.js";
-import type { RuntimeActionResult } from "#runtime/actions/types.js";
+import type { RuntimeActionResult, RuntimeSubagentChildResult } from "#runtime/actions/types.js";
const startSpanMock = vi.fn();
const endSpanMock = vi.fn();
@@ -23,12 +23,11 @@ vi.mock("#compiled/@opentelemetry/api/index.js", async (importOriginal) => {
const USAGE = { cacheReadTokens: 10, cacheWriteTokens: 5, inputTokens: 100, outputTokens: 50 };
-function subagentResult(
- overrides: Partial<Extract<RuntimeActionResult, { kind: "subagent-result" }>> = {},
-): RuntimeActionResult {
+function subagentResult(overrides: Partial<RuntimeSubagentChildResult> = {}): RuntimeActionResult {
return {
callId: "call-1",
kind: "subagent-result",
+ origin: "child",
output: "done",
subagentName: "research",
...overrides,
diff --git a/packages/eve/src/execution/turn-execution-cursor.ts b/packages/eve/src/execution/turn-execution-cursor.ts
index bcb40ac87..2b4e63e0b 100644
--- a/packages/eve/src/execution/turn-execution-cursor.ts
+++ b/packages/eve/src/execution/turn-execution-cursor.ts
@@ -1,8 +1,11 @@
-import type { DeliverHookPayload, HookPayload } from "#channel/types.js";
+import type { DeliverHookPayload } from "#channel/types.js";
import type { TurnControlPayload } from "#execution/turn-control-protocol.js";
import { sendTurnControlStep } from "#execution/turn-control-protocol.js";
import type { DurableSessionState } from "#execution/durable-session-store.js";
-import type { TurnStepInput } from "#execution/durable-session-migrations/turn-workflow.js";
+import type {
+ TurnStepInput,
+ TurnStepPayload,
+} from "#execution/durable-session-migrations/turn-workflow.js";
import type { TokenUsage } from "#shared/token-usage.js";
interface TurnTransition {
@@ -67,7 +70,7 @@ export class TurnExecutionCursor {
}
/** Builds the next atomic turn-step input from the cursor's current state. */
- createStepInput(input: HookPayload | undefined, abortSignal?: AbortSignal): TurnStepInput {
+ createStepInput(input: TurnStepPayload | undefined, abortSignal?: AbortSignal): TurnStepInput {
return {
abortSignal,
input,
diff --git a/packages/eve/src/execution/turn-workflow.test.ts b/packages/eve/src/execution/turn-workflow.test.ts
index 5329a2fb2..22cd1140d 100644
--- a/packages/eve/src/execution/turn-workflow.test.ts
+++ b/packages/eve/src/execution/turn-workflow.test.ts
@@ -13,6 +13,7 @@ import {
} from "#execution/durable-session-migrations/turn-workflow.js";
import { routeDeliverToChildren } from "#execution/route-child-delivery.js";
import { turnStep } from "#execution/workflow-steps.js";
+import { AGENT_HANDLES_STATE_KEY } from "#harness/handles/store.js";
const resumeHookMock = vi.fn();
const createHookMock = vi.fn();
@@ -561,6 +562,7 @@ describe("turnWorkflow", () => {
{
callId: "call-1",
kind: "subagent-result",
+ origin: "child",
output: "child output",
subagentName: "delegate",
},
@@ -569,7 +571,9 @@ describe("turnWorkflow", () => {
]);
vi.mocked(dispatchRuntimeActionsStep).mockResolvedValue({
results: [],
- sessionState: pendingState,
+ sessionState: withRunningChildren(pendingState, [
+ { callId: "call-1", sessionId: "child-session" },
+ ]),
});
vi.mocked(turnStep)
.mockResolvedValueOnce({
@@ -692,6 +696,7 @@ describe("turnWorkflow", () => {
callId: "call-1",
isError: true,
kind: "subagent-result",
+ origin: "dispatch",
output: { code: "REMOTE_AGENT_START_FAILED", message: "remote unavailable" },
subagentName: "research",
},
@@ -736,8 +741,12 @@ describe("turnWorkflow", () => {
});
it("proxies child HITL and pulls the response through the active turn", async () => {
+ const runningChildren = [{ callId: "call-1", sessionId: "child-session" }];
const pendingState = createSessionState();
- const proxyState = createSessionState({ hasProxyInputRequests: true });
+ const proxyState = withRunningChildren(
+ createSessionState({ hasProxyInputRequests: true }),
+ runningChildren,
+ );
const completedState = createSessionState();
const requestId = "turn-token:inbox:delivery:0";
installInbox([
@@ -763,6 +772,7 @@ describe("turnWorkflow", () => {
{
callId: "call-1",
kind: "subagent-result",
+ origin: "child",
output: "approved child output",
subagentName: "delegate",
},
@@ -771,7 +781,7 @@ describe("turnWorkflow", () => {
]);
vi.mocked(dispatchRuntimeActionsStep).mockResolvedValue({
results: [],
- sessionState: pendingState,
+ sessionState: withRunningChildren(pendingState, runningChildren),
});
vi.mocked(runProxySubagentEventStep).mockResolvedValue({
serializedContext: { state: "proxied" },
@@ -889,9 +899,10 @@ describe("turnWorkflow", () => {
});
it("proxies child authorization lifecycle events while continuing to await its result", async () => {
+ const runningChildren = [{ callId: "call-1", sessionId: "child-session" }];
const pendingState = createSessionState();
- const requiredState = createSessionState();
- const completedAuthState = createSessionState();
+ const requiredState = withRunningChildren(createSessionState(), runningChildren);
+ const completedAuthState = withRunningChildren(createSessionState(), runningChildren);
const completedState = createSessionState();
const requiredEvent = {
data: {
@@ -937,15 +948,17 @@ describe("turnWorkflow", () => {
{
callId: "call-1",
kind: "subagent-result",
+ origin: "child",
output: "authorized child output",
subagentName: "delegate",
},
],
},
]);
+ const dispatchedState = withRunningChildren(pendingState, runningChildren);
vi.mocked(dispatchRuntimeActionsStep).mockResolvedValue({
results: [],
- sessionState: pendingState,
+ sessionState: dispatchedState,
});
vi.mocked(runProxySubagentEventStep)
.mockResolvedValueOnce({
@@ -985,7 +998,7 @@ describe("turnWorkflow", () => {
hookPayload: expect.objectContaining({ event: requiredEvent }),
parentWritable,
serializedContext: { state: "pending" },
- sessionState: pendingState,
+ sessionState: dispatchedState,
},
],
[
@@ -1025,7 +1038,13 @@ describe("turnWorkflow", () => {
{
kind: "runtime-action-result",
results: [
- { callId: "call-1", kind: "subagent-result", output: "first", subagentName: "delegate" },
+ {
+ callId: "call-1",
+ kind: "subagent-result",
+ origin: "child",
+ output: "first",
+ subagentName: "delegate",
+ },
],
},
{
@@ -1042,6 +1061,7 @@ describe("turnWorkflow", () => {
{
callId: "call-2",
kind: "subagent-result",
+ origin: "child",
output: "second",
subagentName: "delegate",
},
@@ -1050,7 +1070,10 @@ describe("turnWorkflow", () => {
]);
vi.mocked(dispatchRuntimeActionsStep).mockResolvedValue({
results: [],
- sessionState: pendingState,
+ sessionState: withRunningChildren(pendingState, [
+ { callId: "call-1", sessionId: "child-session-1" },
+ { callId: "call-2", sessionId: "child-session-2" },
+ ]),
});
vi.mocked(routeDeliverToChildren).mockResolvedValue({
kind: "continue",
@@ -1250,3 +1273,49 @@ function createSessionState(overrides: Partial<DurableSessionState> = {}): Durab
...overrides,
};
}
+
+/**
+ * Embeds a snapshot whose handle store owns each child as `running`, the
+ * shape the dispatch step commits: inbox results only resolve the wait when
+ * a running handle binds their callId to their claimed sessionId.
+ */
+function withRunningChildren(
+ state: DurableSessionState,
+ children: readonly { readonly callId: string; readonly sessionId: string }[],
+): DurableSessionState {
+ return {
+ ...state,
+ snapshot: {
+ session: {
+ agent: { system: "" },
+ continuationToken: state.continuationToken,
+ history: [],
+ sessionId: state.sessionId,
+ state: {
+ [AGENT_HANDLES_STATE_KEY]: {
+ handles: children.map((child) => ({
+ address: {
+ continuationToken: `subagent:parent:${child.callId}`,
+ kind: "agent/local",
+ sessionId: child.sessionId,
+ },
+ identity: {
+ id: `ag_delegate:${child.callId}`,
+ name: "delegate",
+ nodeId: "subagents/delegate",
+ },
+ operation: {
+ callId: child.callId,
+ id: `op-${child.callId}`,
+ kind: "start",
+ parentTurnId: "turn_0",
+ },
+ phase: "running",
+ })),
+ },
+ },
+ },
+ version: 1,
+ },
+ };
+}
diff --git a/packages/eve/src/execution/turn-workflow.ts b/packages/eve/src/execution/turn-workflow.ts
index 53d28536e..a72af6afb 100644
--- a/packages/eve/src/execution/turn-workflow.ts
+++ b/packages/eve/src/execution/turn-workflow.ts
@@ -1,3 +1,4 @@
+import { isInboxSubagentResultFromRunningHandle } from "#harness/handles/query.js";
import {
createHook,
getWorkflowMetadata,
@@ -27,7 +28,7 @@ import { resolveWorkflowCallbackBaseUrl } from "#execution/workflow-callback-url
import { normalizeSerializableError } from "#execution/workflow-errors.js";
import { turnStep } from "#execution/workflow-steps.js";
import { activeTurnId } from "#harness/active-turn-id.js";
-import { resolveRuntimeActionResultsForKeys } from "#harness/runtime-actions.js";
+import { resolveRuntimeActionResultsForKeys } from "#runtime/actions/results.js";
import type { RuntimeActionResult } from "#runtime/actions/types.js";
const TASK_MODE_WAIT_ERROR_MESSAGE = "Task mode cannot wait for follow-up input (`next: null`).";
@@ -327,7 +328,20 @@ async function waitForRuntimeActionResults(input: {
const value = next.value;
if (value.kind === "runtime-action-result") {
- results.push(...value.results);
+ // The inbox token is shared by every callee in the batch, so an inbox
+ // subagent result must bind to a running agent handle in the adopted
+ // session snapshot: its callId on the handle's operation and, when it
+ // claims a sessionId, that session on the handle's address (older eve
+ // deployments claim none and bind by callId alone). Anything else — a
+ // callee settling a sibling's call, or a result for a callId whose
+ // dispatch failed — is dropped; the genuine child's result (or the
+ // dispatch error already in `results`) still resolves the wait.
+ const sessionSnapshotState = input.cursor.sessionState.snapshot?.session.state;
+ results.push(
+ ...value.results.filter((result) =>
+ isInboxSubagentResultFromRunningHandle(sessionSnapshotState, result),
+ ),
+ );
continue;
}
diff --git a/packages/eve/src/execution/workflow-entry.test.ts b/packages/eve/src/execution/workflow-entry.test.ts
index 28e5f9fe4..d4c626884 100644
--- a/packages/eve/src/execution/workflow-entry.test.ts
+++ b/packages/eve/src/execution/workflow-entry.test.ts
@@ -519,6 +519,7 @@ describe("workflowEntry", () => {
callId: "call-1",
isError: true,
kind: "subagent-result",
+ origin: "child",
output: {
code: "SUBAGENT_EXECUTION_FAILED",
message: "persistent recoverable failure",
diff --git a/packages/eve/src/execution/workflow-steps.test.ts b/packages/eve/src/execution/workflow-steps.test.ts
index 138d3dbfa..24a7e021e 100644
--- a/packages/eve/src/execution/workflow-steps.test.ts
+++ b/packages/eve/src/execution/workflow-steps.test.ts
@@ -16,10 +16,8 @@ import {
} from "#context/keys.js";
import { BundleKey, ChannelKey } from "#runtime/sessions/runtime-context-keys.js";
import { serializeContext } from "#context/serialize.js";
-import {
- getPendingRuntimeActionBatch,
- setPendingRuntimeActionBatch,
-} from "#harness/runtime-actions.js";
+import { setPendingRuntimeActionBatch } from "#harness/runtime-actions.js";
+import { getAgentHandleStore } from "#harness/handles/store.js";
import { requestTurnSleep } from "#harness/turn-sleep.js";
import { getPendingAuthorization, setPendingAuthorization } from "#harness/authorization.js";
import type { HarnessSession, StepResult } from "#harness/types.js";
@@ -411,6 +409,7 @@ describe("dispatchRuntimeActionsStep", () => {
callId: "call-2",
isError: true,
kind: "subagent-result",
+ origin: "dispatch",
output: {
code: "SUBAGENT_START_FAILED",
message: "child start failed",
@@ -420,16 +419,21 @@ describe("dispatchRuntimeActionsStep", () => {
],
sessionState: expect.any(Object),
});
- expect(getPendingRuntimeActionBatch(result.sessionState.snapshot?.session.state)).toMatchObject(
- {
- childContinuationTokens: {
- "call-1": "subagent:parent-session:call-1",
- },
- childSessionIds: {
- "call-1": "child-run",
- },
- },
- );
+ // The started child stays owned as a running handle; the dead start's
+ // prepared handle was rejected.
+ expect(getAgentHandleStore(result.sessionState.snapshot?.session.state)).toEqual({
+ handles: [
+ expect.objectContaining({
+ address: {
+ continuationToken: "subagent:parent-session:call-1",
+ kind: "agent/local",
+ sessionId: "child-run",
+ },
+ operation: expect.objectContaining({ callId: "call-1", kind: "start" }),
+ phase: "running",
+ }),
+ ],
+ });
expect(startMock).toHaveBeenCalledWith(
workflowEntryReference,
[
@@ -545,31 +549,32 @@ describe("dispatchRuntimeActionsStep", () => {
sessionId: "parent-session",
});
- await expect(
- dispatchRuntimeActionsStep({
- callbackBaseUrl: "https://caller.example.com",
- parentContinuationToken: "turn-inbox",
- parentWritable: createTestWritable(),
- serializedContext: createSerializedContext(),
- sessionState,
- }),
- ).resolves.toEqual({
- results: [
- {
- callId: "call-1",
- isError: true,
- kind: "subagent-result",
- output: {
- code: "REMOTE_AGENT_START_FAILED",
- message: 'Remote agent "research" create-session request failed with HTTP 503.',
- },
- subagentName: "research",
- },
- ],
- // A remote-agent dispatch failure does not mutate the session,
- // so the step returns the input sessionState unchanged.
+ const result = await dispatchRuntimeActionsStep({
+ callbackBaseUrl: "https://caller.example.com",
+ parentContinuationToken: "turn-inbox",
+ parentWritable: createTestWritable(),
+ serializedContext: createSerializedContext(),
sessionState,
});
+
+ expect(result.results).toEqual([
+ {
+ callId: "call-1",
+ isError: true,
+ kind: "subagent-result",
+ origin: "dispatch",
+ output: {
+ code: "REMOTE_AGENT_START_FAILED",
+ message: 'Remote agent "research" create-session request failed with HTTP 503.',
+ },
+ subagentName: "research",
+ },
+ ]);
+ // The prepared handle was committed before the effect and rejected as
+ // dead when the start failed, so no handle survives.
+ expect(getAgentHandleStore(result.sessionState.snapshot?.session.state)).toEqual({
+ handles: [],
+ });
expect(JSON.parse(fetchMock.mock.calls[0]?.[1]?.body as string).callback.token).toBe(
"turn-inbox",
);
@@ -614,7 +619,7 @@ describe("dispatchRuntimeActionsStep", () => {
.fn()
.mockResolvedValue(
Response.json(
- { ok: true, sessionId: "remote-child" },
+ { continuationToken: "remote-continuation", ok: true, sessionId: "remote-child" },
{ headers: { "x-eve-session-id": "remote-child" }, status: 202 },
),
),
@@ -653,11 +658,18 @@ describe("dispatchRuntimeActionsStep", () => {
});
expect(result.results).toEqual([]);
- expect(getPendingRuntimeActionBatch(result.sessionState.snapshot?.session.state)).toMatchObject(
- {
- childSessionIds: { "call-remote": "remote-child" },
- },
- );
+ expect(getAgentHandleStore(result.sessionState.snapshot?.session.state)).toEqual({
+ handles: [
+ expect.objectContaining({
+ address: expect.objectContaining({
+ kind: "agent/remote",
+ sessionId: "remote-child",
+ url: "https://remote.example.com",
+ }),
+ phase: "running",
+ }),
+ ],
+ });
});
it("starts a remote agent from the current dynamic selection", async () => {
@@ -838,6 +850,7 @@ describe("dispatchRuntimeActionsStep", () => {
callId: "call-1",
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.',
@@ -934,6 +947,7 @@ describe("dispatchRuntimeActionsStep", () => {
callId: "call-dynamic",
isError: true,
kind: "subagent-result",
+ origin: "dispatch",
output: {
code: "SUBAGENT_UNAVAILABLE",
message: 'Subagent "researcher" is not available in the current session context.',
diff --git a/packages/eve/src/harness/agent-handle-errors.ts b/packages/eve/src/harness/agent-handle-errors.ts
new file mode 100644
index 000000000..e45075ddf
--- /dev/null
+++ b/packages/eve/src/harness/agent-handle-errors.ts
@@ -0,0 +1,34 @@
+/**
+ * Error codes carried by delegated agent (`subagent-result`) failures.
+ *
+ * Every producer that mints a code imports from this module, so the set
+ * stays closed. Codes are diagnostic only: child lifecycle is owned by the
+ * agent handle store and is never inferred from an error code.
+ */
+
+/** Error code for a requested agent id that is not registered. */
+export const AGENT_UNKNOWN = "AGENT_UNKNOWN";
+
+/** Error code for an agent id invoked through the wrong subagent tool. */
+export const AGENT_MISMATCH = "AGENT_MISMATCH";
+
+/** Error code for a registered agent that cannot be reached. */
+export const AGENT_UNREACHABLE = "AGENT_UNREACHABLE";
+
+/** Error code for an agent that is starting or already running a turn. */
+export const AGENT_BUSY = "AGENT_BUSY";
+
+/** Error code for a local subagent that failed to start. */
+export const SUBAGENT_START_FAILED = "SUBAGENT_START_FAILED";
+
+/** Error code for a delegated subagent whose execution threw. */
+export const SUBAGENT_EXECUTION_FAILED = "SUBAGENT_EXECUTION_FAILED";
+
+/** Error code for a remote agent session that failed to start. */
+export const REMOTE_AGENT_START_FAILED = "REMOTE_AGENT_START_FAILED";
+
+/** Fallback error code for a remote `session.failed` callback without error detail. */
+export const REMOTE_AGENT_FAILED = "REMOTE_AGENT_FAILED";
+
+/** Error code a child session reports back when the whole session failed. */
+export const SESSION_FAILED = "SESSION_FAILED";
diff --git a/packages/eve/src/harness/agent-handles.ts b/packages/eve/src/harness/agent-handles.ts
deleted file mode 100644
index 949658d47..000000000
--- a/packages/eve/src/harness/agent-handles.ts
+++ /dev/null
@@ -1,573 +0,0 @@
-import { createHash } from "node:crypto";
-
-import { z } from "#compiled/zod/index.js";
-
-import type { HarnessSession, SessionStateMap } from "#harness/types.js";
-import type { AgentTurnOutcome } from "#shared/agent-turn-outcome.js";
-
-/** Session-state key for delegated agent handles. */
-export const AGENT_HANDLES_STATE_KEY = "eve.agent.handles";
-const AGENTS_SNIPPET_LABEL = "[Agents]";
-const MAX_STATUS_LENGTH = 120;
-
-/** Error code for a requested agent id that is not registered. */
-export const AGENT_UNKNOWN = "AGENT_UNKNOWN";
-
-/** Error code for an agent id invoked through the wrong subagent tool. */
-export const AGENT_MISMATCH = "AGENT_MISMATCH";
-
-/** Error code for a registered agent that cannot be reached. */
-export const AGENT_UNREACHABLE = "AGENT_UNREACHABLE";
-
-/** Error code for an agent that is starting or already running a turn. */
-export const AGENT_BUSY = "AGENT_BUSY";
-
-/**
- * Stable identity of one delegated child, minted before its start side
- * effect runs. The model-visible `id` derives from the first start
- * operation, never from the child session id, so it exists before the
- * child does and cannot collide on externally supplied session suffixes.
- */
-export interface AgentIdentity {
- /** Model-visible identifier: `ag_<name>:<operation-hash>`. */
- readonly id: string;
- /** Subagent tool name. */
- readonly name: string;
- /** Agent-graph node used to re-resolve delivery configuration. */
- readonly nodeId: string;
-}
-
-/**
- * One dispatch the parent intends to perform or has performed. Repeating
- * the same operation is a replay; a different operation against a
- * starting/running handle is a busy conflict.
- */
-export interface StartOperation {
- readonly kind: "start";
- /** Derived via {@link deriveAgentOperationId}; stable across replays. */
- readonly id: string;
- readonly callId: string;
- readonly parentTurnId: string;
-}
-
-/** A continuation delivery against a parked handle. */
-export interface ContinueOperation {
- readonly kind: "continue";
- /** Derived via {@link deriveAgentOperationId}; stable across replays. */
- readonly id: string;
- readonly callId: string;
- readonly parentTurnId: string;
- /**
- * Status the handle showed before this delivery, restored when the
- * delivery is rejected as retryable so the handle returns to `parked`
- * without optional state.
- */
- readonly previousStatus: string;
-}
-
-/** Where a fresh child will be started. No session exists yet. */
-export type AgentStartTarget =
- | {
- readonly kind: "agent/local";
- /** Deterministic child continuation token chosen at dispatch. */
- readonly continuationToken: string;
- }
- | {
- readonly kind: "agent/self";
- readonly continuationToken: string;
- }
- | {
- readonly kind: "agent/remote";
- /** Deliver target base URL; never model-visible. */
- readonly url: string;
- /** Callback base URL stub captured at dispatch; never model-visible. */
- readonly callbackBaseUrl: string;
- };
-
-/** Confirmed delivery coordinates of a started child. */
-export type AgentAddress =
- | {
- readonly kind: "agent/local";
- readonly sessionId: string;
- readonly continuationToken: string;
- }
- | {
- readonly kind: "agent/self";
- readonly sessionId: string;
- readonly continuationToken: string;
- }
- | {
- readonly kind: "agent/remote";
- readonly sessionId: string;
- readonly continuationToken: string;
- readonly url: string;
- readonly callbackBaseUrl: string;
- };
-
-/**
- * Durable ownership record for one delegated child.
- *
- * The store owns the full nonterminal lifecycle:
- *
- * - `starting` — the parent committed intent to start; the child may or
- * may not exist yet.
- * - `running` — one identified child turn is outstanding.
- * - `parked` — the child is idle and resumable; only this phase is
- * model-visible.
- *
- * A terminal child has no handle: settlement deletes it.
- */
-export type AgentHandle =
- | {
- readonly phase: "starting";
- readonly identity: AgentIdentity;
- readonly operation: StartOperation;
- readonly target: AgentStartTarget;
- }
- | {
- readonly phase: "running";
- readonly identity: AgentIdentity;
- readonly operation: StartOperation | ContinueOperation;
- readonly address: AgentAddress;
- }
- | {
- readonly phase: "parked";
- readonly identity: AgentIdentity;
- readonly address: AgentAddress;
- readonly lastStatus: string;
- };
-
-/** Lifecycle phase of a delegated agent handle. */
-export type AgentHandlePhase = AgentHandle["phase"];
-
-/** Session-state collection of delegated agent handles. */
-export interface AgentHandleStore {
- readonly handles: readonly AgentHandle[];
-}
-
-const nonEmptyString = z.string().min(1);
-
-const identitySchema = z.strictObject({
- id: nonEmptyString,
- name: nonEmptyString,
- nodeId: nonEmptyString,
-});
-
-const startOperationSchema = z.strictObject({
- callId: nonEmptyString,
- id: nonEmptyString,
- kind: z.literal("start"),
- parentTurnId: nonEmptyString,
-});
-
-const continueOperationSchema = z.strictObject({
- callId: nonEmptyString,
- id: nonEmptyString,
- kind: z.literal("continue"),
- parentTurnId: nonEmptyString,
- previousStatus: z.string().max(MAX_STATUS_LENGTH),
-});
-
-const startTargetSchema: z.ZodType<AgentStartTarget> = z.discriminatedUnion("kind", [
- z.strictObject({ continuationToken: nonEmptyString, kind: z.literal("agent/local") }),
- z.strictObject({ continuationToken: nonEmptyString, kind: z.literal("agent/self") }),
- z.strictObject({
- callbackBaseUrl: z.url(),
- kind: z.literal("agent/remote"),
- url: z.url(),
- }),
-]);
-
-const addressSchema: z.ZodType<AgentAddress> = z.discriminatedUnion("kind", [
- z.strictObject({
- continuationToken: nonEmptyString,
- kind: z.literal("agent/local"),
- sessionId: nonEmptyString,
- }),
- z.strictObject({
- continuationToken: nonEmptyString,
- kind: z.literal("agent/self"),
- sessionId: nonEmptyString,
- }),
- z.strictObject({
- callbackBaseUrl: z.url(),
- continuationToken: nonEmptyString,
- kind: z.literal("agent/remote"),
- sessionId: nonEmptyString,
- url: z.url(),
- }),
-]);
-
-const agentHandleSchema: z.ZodType<AgentHandle> = z.discriminatedUnion("phase", [
- z.strictObject({
- identity: identitySchema,
- operation: startOperationSchema,
- phase: z.literal("starting"),
- target: startTargetSchema,
- }),
- z.strictObject({
- address: addressSchema,
- identity: identitySchema,
- operation: z.discriminatedUnion("kind", [startOperationSchema, continueOperationSchema]),
- phase: z.literal("running"),
- }),
- z.strictObject({
- address: addressSchema,
- identity: identitySchema,
- lastStatus: z.string().max(MAX_STATUS_LENGTH),
- phase: z.literal("parked"),
- }),
-]);
-
-const agentHandleStoreSchema: z.ZodType<AgentHandleStore> = z
- .strictObject({
- handles: z.array(agentHandleSchema),
- })
- .refine(
- (store) =>
- new Set(store.handles.map((handle) => handle.identity.id)).size === store.handles.length,
- { message: "Agent handle ids must be unique." },
- );
-
-/**
- * Derives the stable operation id for one dispatch. All three inputs are
- * parent-controlled, so the id exists before any child does and replaying
- * the same call produces the same operation.
- */
-export function deriveAgentOperationId(input: {
- readonly callId: string;
- readonly parentSessionId: string;
- readonly parentTurnId: string;
-}): string {
- return createHash("sha256")
- .update(`${input.parentSessionId}\0${input.parentTurnId}\0${input.callId}`)
- .digest("hex");
-}
-
-/** Derives the model-visible agent id from the first start operation. */
-export function deriveAgentId(name: string, startOperationId: string): string {
- return `ag_${name}:${startOperationId.slice(0, 12)}`;
-}
-
-/** Collapses whitespace and truncates output into a handle status line. */
-export function formatAgentStatus(output: unknown): string {
- const text = typeof output === "string" ? output : (JSON.stringify(output) ?? "");
- return text.replaceAll(/\s+/g, " ").trim().slice(0, MAX_STATUS_LENGTH);
-}
-
-/**
- * Reads and validates the agent handle store from session state.
- *
- * Returns `undefined` only when no store has been written. A present but
- * invalid store throws: treating corruption as absence would let the next
- * transition silently replace every delegated child's delivery coordinates.
- */
-export function getAgentHandleStore(
- state: SessionStateMap | undefined,
-): AgentHandleStore | undefined {
- const raw = state?.[AGENT_HANDLES_STATE_KEY];
- if (raw === undefined) {
- return undefined;
- }
- const parsed = agentHandleStoreSchema.safeParse(raw);
- if (!parsed.success) {
- throw new Error(
- `Corrupt agent handle store under session state key "${AGENT_HANDLES_STATE_KEY}": ${parsed.error.message}`,
- );
- }
- return parsed.data;
-}
-
-/**
- * Records intent to start a fresh child. Must commit before the start
- * side effect runs so a crashed dispatch never orphans an unowned child.
- *
- * Throws when the identity or operation already exists: fresh starts mint
- * a new identity, so a collision means corrupted derivation, not a replay.
- */
-export function prepareAgentStart(
- session: HarnessSession,
- input: {
- readonly identity: AgentIdentity;
- readonly operation: StartOperation;
- readonly target: AgentStartTarget;
- },
-): HarnessSession {
- const handles = getAgentHandleStore(session.state)?.handles ?? [];
- if (handles.some((handle) => handle.identity.id === input.identity.id)) {
- throw new Error(`Agent handle "${input.identity.id}" already exists.`);
- }
- return writeHandles(session, [
- ...handles,
- {
- identity: input.identity,
- operation: input.operation,
- phase: "starting",
- target: input.target,
- },
- ]);
-}
-
-/** Result of preparing a continuation against an existing handle. */
-export type PrepareAgentContinuationResult =
- | {
- readonly kind: "ready";
- readonly session: HarnessSession;
- readonly handle: Extract<AgentHandle, { phase: "running" }>;
- }
- | { readonly kind: "unknown" }
- | { readonly kind: "mismatch" }
- | { readonly kind: "busy" };
-
-/**
- * Records intent to deliver a follow-up turn to a parked child. Must
- * commit before the delivery side effect runs.
- *
- * `unknown`, `mismatch`, and `busy` do not change the session; the caller
- * maps them onto {@link AGENT_UNKNOWN}, {@link AGENT_MISMATCH}, and
- * {@link AGENT_BUSY} results. Replaying the operation already recorded on
- * a running handle returns `ready` with the unchanged session.
- */
-export function prepareAgentContinuation(
- session: HarnessSession,
- input: {
- readonly agentId: string;
- readonly invokedName: string;
- readonly operation: ContinueOperation;
- },
-): PrepareAgentContinuationResult {
- const handles = getAgentHandleStore(session.state)?.handles ?? [];
- const existing = handles.find((handle) => handle.identity.id === input.agentId);
- if (existing === undefined) {
- return { kind: "unknown" };
- }
- if (existing.identity.name !== input.invokedName) {
- return { kind: "mismatch" };
- }
- if (existing.phase === "running" && existing.operation.id === input.operation.id) {
- return { handle: existing, kind: "ready", session };
- }
- if (existing.phase !== "parked") {
- return { kind: "busy" };
- }
-
- const running: Extract<AgentHandle, { phase: "running" }> = {
- address: existing.address,
- identity: existing.identity,
- operation: { ...input.operation, previousStatus: existing.lastStatus },
- phase: "running",
- };
- return {
- handle: running,
- kind: "ready",
- session: writeHandles(
- session,
- handles.map((handle) => (handle.identity.id === input.agentId ? running : handle)),
- ),
- };
-}
-
-type ActiveAgentHandle = Extract<AgentHandle, { phase: "starting" | "running" }>;
-
-function findActiveHandle(
- handles: readonly AgentHandle[],
- operationId: string,
-): ActiveAgentHandle | undefined {
- return handles.find(
- (handle): handle is ActiveAgentHandle =>
- handle.phase !== "parked" && handle.operation.id === operationId,
- );
-}
-
-/**
- * Confirms a started child: `starting` becomes `running` with the child's
- * confirmed address. Throws when no starting handle carries the operation,
- * because confirming an unprepared start means ownership was never
- * committed. Re-confirming an already-running handle with the same
- * operation and address is a replay no-op.
- */
-export function confirmAgentStarted(
- session: HarnessSession,
- input: {
- readonly operationId: string;
- readonly address: AgentAddress;
- },
-): HarnessSession {
- const handles = getAgentHandleStore(session.state)?.handles ?? [];
- const existing = findActiveHandle(handles, input.operationId);
- if (existing === undefined) {
- throw new Error(`No prepared agent handle for operation "${input.operationId}".`);
- }
- if (existing.phase === "running") {
- return session;
- }
-
- return writeHandles(
- session,
- handles.map((handle) =>
- handle === existing
- ? {
- address: input.address,
- identity: existing.identity,
- operation: existing.operation,
- phase: "running",
- }
- : handle,
- ),
- );
-}
-
-/**
- * Resolves a dispatch that definitively failed.
- *
- * - A dead start or dead continuation deletes the handle: there is no
- * child left to own.
- * - A retryable continuation failure restores `parked` with the status the
- * handle showed before the delivery, so the model may retry the same
- * `agentId` later.
- *
- * Unknown operations are a no-op: the failure raced a settlement that
- * already resolved the handle.
- */
-export function rejectAgentEffect(
- session: HarnessSession,
- input: {
- readonly operationId: string;
- readonly disposition: "dead" | "retryable";
- },
-): HarnessSession {
- const handles = getAgentHandleStore(session.state)?.handles ?? [];
- const existing = findActiveHandle(handles, input.operationId);
- if (existing === undefined) {
- return session;
- }
-
- if (input.disposition === "retryable" && existing.phase === "running") {
- const { operation } = existing;
- if (operation.kind === "continue") {
- return writeHandles(
- session,
- handles.map((handle) =>
- handle === existing
- ? {
- address: existing.address,
- identity: existing.identity,
- lastStatus: operation.previousStatus,
- phase: "parked",
- }
- : handle,
- ),
- );
- }
- }
-
- return writeHandles(
- session,
- handles.filter((handle) => handle !== existing),
- );
-}
-
-/** Result of applying a settled child turn to the store. */
-export type SettleAgentTurnResult =
- | { readonly kind: "settled"; readonly session: HarnessSession }
- | { readonly kind: "ignored"; readonly reason: "unknown-operation" | "session-mismatch" };
-
-/**
- * Applies one settled child turn: `running` becomes `parked` for a parked
- * outcome or is deleted for a terminal outcome.
- *
- * The settlement must carry the operation currently recorded on the
- * running handle and the child session the address confirms; anything else
- * is ignored so a stale or forged delivery can never move a newer turn.
- */
-export function settleAgentTurn(
- session: HarnessSession,
- input: {
- readonly operationId: string;
- readonly sessionId: string;
- readonly outcome: AgentTurnOutcome;
- },
-): SettleAgentTurnResult {
- const handles = getAgentHandleStore(session.state)?.handles ?? [];
- const existing = handles.find(
- (handle) => handle.phase === "running" && handle.operation.id === input.operationId,
- );
- if (existing === undefined || existing.phase !== "running") {
- return { kind: "ignored", reason: "unknown-operation" };
- }
- if (existing.address.sessionId !== input.sessionId) {
- return { kind: "ignored", reason: "session-mismatch" };
- }
-
- if (input.outcome.kind === "terminal") {
- return {
- kind: "settled",
- session: writeHandles(
- session,
- handles.filter((handle) => handle !== existing),
- ),
- };
- }
-
- const { result } = input.outcome;
- const lastStatus =
- result.kind === "succeeded"
- ? formatAgentStatus(result.output)
- : result.kind === "failed"
- ? formatAgentStatus(result.error)
- : "(cancelled)";
- return {
- kind: "settled",
- session: writeHandles(
- session,
- handles.map((handle) =>
- handle === existing
- ? {
- address: existing.address,
- identity: existing.identity,
- lastStatus,
- phase: "parked",
- }
- : handle,
- ),
- ),
- };
-}
-
-/** Returns the resumable handles: the only phase the model may continue. */
-export function projectParkedAgentHandles(
- store: AgentHandleStore,
-): readonly Extract<AgentHandle, { phase: "parked" }>[] {
- return store.handles.filter((handle) => handle.phase === "parked");
-}
-
-/**
- * Renders the model-visible agent listing. Only parked handles appear:
- * starting and running children cannot accept a continuation, and private
- * delivery coordinates never render.
- */
-export function renderAgentsSnippet(store: AgentHandleStore): string {
- const agents = projectParkedAgentHandles(store).map(
- (handle) =>
- `<agent id="${escapeXml(handle.identity.id)}" name="${escapeXml(handle.identity.name)}">${escapeXml(handle.lastStatus === "" ? "(no status)" : handle.lastStatus)}</agent>`,
- );
- return [AGENTS_SNIPPET_LABEL, "<agents>", ...agents, "</agents>"].join("\n");
-}
-
-function writeHandles(session: HarnessSession, handles: readonly AgentHandle[]): HarnessSession {
- return {
- ...session,
- state: {
- ...session.state,
- [AGENT_HANDLES_STATE_KEY]: { handles } satisfies AgentHandleStore,
- },
- };
-}
-
-function escapeXml(value: string): string {
- return value
- .replaceAll("&", "&amp;")
- .replaceAll('"', "&quot;")
- .replaceAll("<", "&lt;")
- .replaceAll(">", "&gt;");
-}
diff --git a/packages/eve/src/harness/handles/operation-id.ts b/packages/eve/src/harness/handles/operation-id.ts
new file mode 100644
index 000000000..580225bc8
--- /dev/null
+++ b/packages/eve/src/harness/handles/operation-id.ts
@@ -0,0 +1,21 @@
+import { createHash } from "node:crypto";
+
+/**
+ * Derives the stable operation id for one dispatch. All three inputs are
+ * parent-controlled, so the id exists before any child does and replaying
+ * the same call produces the same operation.
+ *
+ * Lives apart from the handle store because it needs `node:crypto`: the
+ * store module is bundled into the workflow driver body (which rejects
+ * Node.js builtins), while operation ids are only ever minted inside
+ * dispatch steps.
+ */
+export function deriveAgentOperationId(input: {
+ readonly callId: string;
+ readonly parentSessionId: string;
+ readonly parentTurnId: string;
+}): string {
+ return createHash("sha256")
+ .update(`${input.parentSessionId}\0${input.parentTurnId}\0${input.callId}`)
+ .digest("hex");
+}
diff --git a/packages/eve/src/harness/handles/prompt.test.ts b/packages/eve/src/harness/handles/prompt.test.ts
new file mode 100644
index 000000000..c1a3406b6
--- /dev/null
+++ b/packages/eve/src/harness/handles/prompt.test.ts
@@ -0,0 +1,110 @@
+import { describe, expect, it } from "vitest";
+
+import {
+ projectParkedAgentHandles,
+ renderAgentsSnippet,
+ resolveAgentsAnnouncement,
+} from "#harness/handles/prompt.js";
+import type { AgentHandle } from "#harness/handles/store.js";
+
+const identity = {
+ id: "ag_research:abcdef123456",
+ name: "research",
+ nodeId: "node_research",
+} as const;
+
+const runningHandle: AgentHandle = {
+ address: {
+ continuationToken: "CONTINUATION_TOKEN_SENTINEL",
+ kind: "agent/local",
+ sessionId: "SESSION_ID_SENTINEL_123456789",
+ },
+ identity,
+ operation: {
+ callId: "call_1",
+ id: "op_1",
+ kind: "start",
+ parentTurnId: "turn_1",
+ },
+ phase: "running",
+};
+
+const parkedRemoteHandle: AgentHandle = {
+ address: {
+ callbackBaseUrl: "https://CALLBACK_SENTINEL.invalid",
+ continuationToken: "CONTINUATION_TOKEN_SENTINEL",
+ kind: "agent/remote",
+ sessionId: "SESSION_ID_SENTINEL_123456789",
+ url: "https://URL_SENTINEL.invalid",
+ },
+ identity,
+ lastStatus: "initial findings",
+ phase: "parked",
+};
+
+describe("projectParkedAgentHandles / renderAgentsSnippet", () => {
+ it("projects and renders only parked handles", () => {
+ const runningStore = { handles: [runningHandle] };
+ expect(projectParkedAgentHandles(runningStore)).toEqual([]);
+ expect(renderAgentsSnippet(runningStore)).toBe("[Agents]\n<agents>\n</agents>");
+
+ const parkedStore = { handles: [parkedRemoteHandle] };
+ expect(projectParkedAgentHandles(parkedStore)).toEqual([parkedRemoteHandle]);
+ const snippet = renderAgentsSnippet(parkedStore);
+ expect(snippet.startsWith("[Agents]\n<agents>")).toBe(true);
+ expect(snippet).toContain(
+ `<agent id="${identity.id}" name="research">initial findings</agent>`,
+ );
+ });
+
+ it("omits private delivery coordinates and renders a placeholder for empty statuses", () => {
+ const snippet = renderAgentsSnippet({
+ handles: [{ ...parkedRemoteHandle, lastStatus: "" }],
+ });
+
+ expect(snippet).toContain("(no status)");
+ expect(snippet).not.toContain(parkedRemoteHandle.address.sessionId);
+ expect(snippet).not.toContain(parkedRemoteHandle.address.continuationToken);
+ expect(snippet).not.toContain("URL_SENTINEL");
+ expect(snippet).not.toContain("CALLBACK_SENTINEL");
+ });
+});
+
+describe("resolveAgentsAnnouncement", () => {
+ it("announces a changed listing without replacing earlier conversation content", () => {
+ const messages = [{ content: "Earlier response", role: "assistant" as const }];
+ const content = resolveAgentsAnnouncement({
+ messages,
+ store: { handles: [parkedRemoteHandle] },
+ });
+
+ expect(content).toContain(`<agent id="${identity.id}"`);
+ expect(messages).toEqual([{ content: "Earlier response", role: "assistant" }]);
+ });
+
+ it("does not repeat an unchanged listing", () => {
+ const content = renderAgentsSnippet({ handles: [parkedRemoteHandle] });
+
+ expect(
+ resolveAgentsAnnouncement({
+ messages: [{ content, role: "assistant" }],
+ store: { handles: [parkedRemoteHandle] },
+ }),
+ ).toBeUndefined();
+ });
+
+ it("announces an empty listing after the last parked handle disappears", () => {
+ const previous = renderAgentsSnippet({ handles: [parkedRemoteHandle] });
+
+ expect(
+ resolveAgentsAnnouncement({
+ messages: [{ content: previous, role: "assistant" }],
+ store: { handles: [runningHandle] },
+ }),
+ ).toBe("[Agents]\n<agents>\n</agents>");
+ });
+
+ it("skips empty scaffolding when no listing was previously announced", () => {
+ expect(resolveAgentsAnnouncement({ messages: [], store: undefined })).toBeUndefined();
+ });
+});
diff --git a/packages/eve/src/harness/handles/prompt.ts b/packages/eve/src/harness/handles/prompt.ts
new file mode 100644
index 000000000..c2fe0a6d1
--- /dev/null
+++ b/packages/eve/src/harness/handles/prompt.ts
@@ -0,0 +1,58 @@
+import type { ModelMessage } from "ai";
+
+import type { AgentHandle, AgentHandleStore } from "#harness/handles/store.js";
+
+const AGENTS_SNIPPET_LABEL = "[Agents]";
+
+/** Returns the resumable handles: the only phase the model may continue. */
+export function projectParkedAgentHandles(
+ store: AgentHandleStore,
+): readonly Extract<AgentHandle, { phase: "parked" }>[] {
+ return store.handles.filter((handle) => handle.phase === "parked");
+}
+
+/**
+ * Renders the model-visible agent listing. Only parked handles appear:
+ * starting and running children cannot accept a continuation, and private
+ * delivery coordinates never render.
+ */
+export function renderAgentsSnippet(store: AgentHandleStore): string {
+ const agents = projectParkedAgentHandles(store).map(
+ (handle) =>
+ `<agent id="${escapeXml(handle.identity.id)}" name="${escapeXml(handle.identity.name)}">${escapeXml(handle.lastStatus === "" ? "(no status)" : handle.lastStatus)}</agent>`,
+ );
+ return [AGENTS_SNIPPET_LABEL, "<agents>", ...agents, "</agents>"].join("\n");
+}
+
+/**
+ * Returns an append-only model announcement when the visible handle listing
+ * changed. Keeping volatile handles in conversation history preserves the
+ * stable system prompt cache prefix.
+ */
+export function resolveAgentsAnnouncement(input: {
+ readonly messages: readonly ModelMessage[];
+ readonly store: AgentHandleStore | undefined;
+}): string | undefined {
+ const latest = input.messages.findLast(
+ (message) =>
+ message.role === "assistant" &&
+ typeof message.content === "string" &&
+ message.content.startsWith(AGENTS_SNIPPET_LABEL),
+ );
+ const store = input.store ?? { handles: [] };
+
+ if (latest === undefined && projectParkedAgentHandles(store).length === 0) {
+ return undefined;
+ }
+
+ const rendered = renderAgentsSnippet(store);
+ return latest?.content === rendered ? undefined : rendered;
+}
+
+function escapeXml(value: string): string {
+ return value
+ .replaceAll("&", "&amp;")
+ .replaceAll('"', "&quot;")
+ .replaceAll("<", "&lt;")
+ .replaceAll(">", "&gt;");
+}
diff --git a/packages/eve/src/harness/handles/query.ts b/packages/eve/src/harness/handles/query.ts
new file mode 100644
index 000000000..68bc6799c
--- /dev/null
+++ b/packages/eve/src/harness/handles/query.ts
@@ -0,0 +1,85 @@
+import type { RuntimeActionResult, RuntimeSubagentChildResult } from "#runtime/actions/types.js";
+import { AGENT_HANDLES_STATE_KEY } from "#harness/handles/state-key.js";
+import type { AgentHandle } from "#harness/handles/store.js";
+import type { SessionStateMap } from "#harness/types.js";
+
+/** A handle with one outstanding operation and a confirmed child address. */
+export type RunningAgentHandle = Extract<AgentHandle, { phase: "running" }>;
+
+/**
+ * Schema-free read of the agent handles from session state.
+ *
+ * Trust boundary: every write to this key goes through `writeHandles` in
+ * transitions.ts, which runs the strict zod store schema at persist time and
+ * refuses to write an invalid store. This driver-side query trusts that
+ * invariant instead of re-validating, so the workflow driver bundle stays
+ * free of the compiled zod runtime.
+ */
+function readAgentHandles(state: SessionStateMap | undefined): readonly AgentHandle[] {
+ const raw = state?.[AGENT_HANDLES_STATE_KEY];
+ if (raw === undefined) {
+ return [];
+ }
+ const handles = (raw as { handles?: unknown }).handles;
+ return Array.isArray(handles) ? (handles as readonly AgentHandle[]) : [];
+}
+
+/**
+ * Finds the running agent handle a child-produced result must settle: the
+ * handle whose recorded operation carries the result's callId.
+ *
+ * Binding is by callId alone. Possession of the parent's callback token is
+ * the authorization to settle; the handle's recorded address is used for
+ * outbound delivery (continuation, cancellation), never as an inbound
+ * identity check. Under the accepted at-least-once dispatch window a
+ * replay-orphaned duplicate child holds the same token and callId and may
+ * settle the call in place of the owned child — an accepted trade-off,
+ * since both children computed the same input.
+ */
+export function findRunningAgentHandle(
+ state: SessionStateMap | undefined,
+ input: { readonly callId: string },
+): RunningAgentHandle | undefined {
+ const handles = readAgentHandles(state);
+ return handles.find(
+ (handle): handle is RunningAgentHandle =>
+ handle.phase === "running" && handle.operation.callId === input.callId,
+ );
+}
+
+/**
+ * A subagent result may settle a call only when a running handle records
+ * its callId: a late or duplicate result for an already-settled call finds
+ * no running handle and is dropped.
+ *
+ * `dispatch`-origin failures pass unconditionally: the parent synthesizes
+ * them for calls whose child never started, and they reach the harness only
+ * through the trusted step-result path. Untrusted channels must use
+ * {@link isInboxSubagentResultFromRunningHandle} instead.
+ */
+export function isResultBoundToRunningHandle(
+ state: SessionStateMap | undefined,
+ result: RuntimeActionResult,
+): boolean {
+ if (result.kind !== "subagent-result") {
+ return true;
+ }
+ if (result.origin === "dispatch") {
+ return true;
+ }
+ return findRunningAgentHandle(state, { callId: result.callId }) !== undefined;
+}
+
+/**
+ * Strict variant of {@link isResultBoundToRunningHandle} for results arriving
+ * over the shared turn inbox (child notifications and remote callbacks).
+ * An inbox result must bind to a running handle by callId; one with no
+ * matching running handle — including one for a callId whose dispatch
+ * already failed — must not overwrite the dispatch-produced error result.
+ */
+export function isInboxSubagentResultFromRunningHandle(
+ state: SessionStateMap | undefined,
+ result: RuntimeSubagentChildResult,
+): boolean {
+ return findRunningAgentHandle(state, { callId: result.callId }) !== undefined;
+}
diff --git a/packages/eve/src/harness/handles/state-key.ts b/packages/eve/src/harness/handles/state-key.ts
new file mode 100644
index 000000000..62a41e006
--- /dev/null
+++ b/packages/eve/src/harness/handles/state-key.ts
@@ -0,0 +1,8 @@
+/**
+ * Session-state key for delegated agent handles.
+ *
+ * Lives apart from the store so schema-free readers (the workflow driver's
+ * handle query) can import the key without pulling the zod-backed store
+ * module into their bundle.
+ */
+export const AGENT_HANDLES_STATE_KEY = "eve.agent.handles";
diff --git a/packages/eve/src/harness/handles/store.test.ts b/packages/eve/src/harness/handles/store.test.ts
new file mode 100644
index 000000000..7d4c8508d
--- /dev/null
+++ b/packages/eve/src/harness/handles/store.test.ts
@@ -0,0 +1,129 @@
+import { describe, expect, it } from "vitest";
+
+import { deriveAgentOperationId } from "#harness/handles/operation-id.js";
+import {
+ AGENT_HANDLES_STATE_KEY,
+ assertPersistableAgentHandleStore,
+ deriveAgentId,
+ formatAgentStatus,
+ getAgentHandleStore,
+ type AgentAddress,
+ type AgentHandle,
+ type AgentIdentity,
+ type StartOperation,
+} from "#harness/handles/store.js";
+
+const startOperation: StartOperation = {
+ callId: "call_1",
+ id: deriveAgentOperationId({
+ callId: "call_1",
+ parentSessionId: "session_parent",
+ parentTurnId: "turn_1",
+ }),
+ kind: "start",
+ parentTurnId: "turn_1",
+};
+
+const identity: AgentIdentity = {
+ id: deriveAgentId("research", startOperation.id),
+ name: "research",
+ nodeId: "node_research",
+};
+
+const address: AgentAddress = {
+ continuationToken: "continuation_child",
+ kind: "agent/local",
+ sessionId: "session_child",
+};
+
+const parkedHandle: AgentHandle = {
+ address,
+ identity,
+ lastStatus: "initial findings",
+ phase: "parked",
+};
+
+describe("deriveAgentOperationId / deriveAgentId", () => {
+ it("is deterministic on parent-controlled inputs and independent of the child session", () => {
+ const again = deriveAgentOperationId({
+ callId: "call_1",
+ parentSessionId: "session_parent",
+ parentTurnId: "turn_1",
+ });
+ expect(again).toBe(startOperation.id);
+ expect(deriveAgentId("research", again)).toBe(identity.id);
+ expect(identity.id.startsWith("ag_research:")).toBe(true);
+ });
+
+ it("changes when any input changes", () => {
+ const other = deriveAgentOperationId({
+ callId: "call_2",
+ parentSessionId: "session_parent",
+ parentTurnId: "turn_1",
+ });
+ expect(other).not.toBe(startOperation.id);
+ });
+});
+
+describe("getAgentHandleStore", () => {
+ it("returns undefined only when no store has been written", () => {
+ expect(getAgentHandleStore(undefined)).toBeUndefined();
+ expect(getAgentHandleStore({})).toBeUndefined();
+ });
+
+ it("throws on a present but malformed store instead of treating it as absent", () => {
+ for (const malformed of [
+ null,
+ { handles: "not-an-array" },
+ { handles: [{ phase: "starting" }] },
+ { extra: true, handles: [] },
+ {
+ handles: [
+ {
+ address,
+ identity,
+ lastStatus: "x".repeat(121),
+ phase: "parked",
+ },
+ ],
+ },
+ ]) {
+ expect(() => getAgentHandleStore({ [AGENT_HANDLES_STATE_KEY]: malformed })).toThrow(
+ AGENT_HANDLES_STATE_KEY,
+ );
+ }
+ });
+
+ it("rejects duplicate handle ids", () => {
+ expect(() =>
+ getAgentHandleStore({
+ [AGENT_HANDLES_STATE_KEY]: { handles: [parkedHandle, parkedHandle] },
+ }),
+ ).toThrow("unique");
+ });
+});
+
+describe("assertPersistableAgentHandleStore", () => {
+ it("returns a valid store unchanged in shape", () => {
+ expect(assertPersistableAgentHandleStore({ handles: [parkedHandle] })).toEqual({
+ handles: [parkedHandle],
+ });
+ });
+
+ it("refuses to persist a malformed store", () => {
+ const corrupt = {
+ handles: [{ ...parkedHandle, lastStatus: "x".repeat(121) }],
+ };
+ expect(() => assertPersistableAgentHandleStore(corrupt)).toThrow(
+ "Refusing to persist a corrupt agent handle store",
+ );
+ });
+});
+
+describe("formatAgentStatus", () => {
+ it("collapses whitespace, truncates to 120, and stringifies objects", () => {
+ expect(formatAgentStatus(" a\n\tb ")).toBe("a b");
+ expect(formatAgentStatus({ ok: true })).toBe('{"ok":true}');
+ expect(formatAgentStatus("y".repeat(300)).length).toBe(120);
+ });
+});
diff --git a/packages/eve/src/harness/handles/store.ts b/packages/eve/src/harness/handles/store.ts
new file mode 100644
index 000000000..7c0240709
--- /dev/null
+++ b/packages/eve/src/harness/handles/store.ts
@@ -0,0 +1,268 @@
+import { z } from "#compiled/zod/index.js";
+
+import type { SessionStateMap } from "#harness/types.js";
+
+import { AGENT_HANDLES_STATE_KEY } from "./state-key.js";
+
+export { AGENT_HANDLES_STATE_KEY };
+
+const MAX_STATUS_LENGTH = 120;
+
+/**
+ * Stable identity of one delegated child, minted before its start side
+ * effect runs. The model-visible `id` derives from the first start
+ * operation, never from the child session id, so it exists before the
+ * child does and cannot collide on externally supplied session suffixes.
+ */
+export interface AgentIdentity {
+ /** Model-visible identifier: `ag_<name>:<operation-hash>`. */
+ readonly id: string;
+ /** Subagent tool name. */
+ readonly name: string;
+ /** Agent-graph node used to re-resolve delivery configuration. */
+ readonly nodeId: string;
+}
+
+/**
+ * One dispatch the parent intends to perform or has performed. Repeating
+ * the same operation is a replay; a different operation against a
+ * starting/running handle is a busy conflict.
+ */
+export interface StartOperation {
+ readonly kind: "start";
+ /** Derived via {@link deriveAgentOperationId}; stable across replays. */
+ readonly id: string;
+ readonly callId: string;
+ readonly parentTurnId: string;
+}
+
+/** A continuation delivery against a parked handle. */
+export interface ContinueOperation {
+ readonly kind: "continue";
+ /** Derived via {@link deriveAgentOperationId}; stable across replays. */
+ readonly id: string;
+ readonly callId: string;
+ readonly parentTurnId: string;
+ /**
+ * Status the handle showed before this delivery, restored when the
+ * delivery is rejected as retryable so the handle returns to `parked`
+ * without optional state.
+ */
+ readonly previousStatus: string;
+}
+
+/** Where a fresh child will be started. No session exists yet. */
+export type AgentStartTarget =
+ | {
+ readonly kind: "agent/local";
+ /** Deterministic child continuation token chosen at dispatch. */
+ readonly continuationToken: string;
+ }
+ | {
+ readonly kind: "agent/self";
+ readonly continuationToken: string;
+ }
+ | {
+ readonly kind: "agent/remote";
+ /** Deliver target base URL; never model-visible. */
+ readonly url: string;
+ /** Callback base URL stub captured at dispatch; never model-visible. */
+ readonly callbackBaseUrl: string;
+ };
+
+/** Confirmed delivery coordinates of a started child. */
+export type AgentAddress =
+ | {
+ readonly kind: "agent/local";
+ readonly sessionId: string;
+ readonly continuationToken: string;
+ }
+ | {
+ readonly kind: "agent/self";
+ readonly sessionId: string;
+ readonly continuationToken: string;
+ }
+ | {
+ readonly kind: "agent/remote";
+ readonly sessionId: string;
+ /**
+ * Absent when the remote deployment predates continuation tokens; the
+ * child completes as a task-mode one-shot and can never be continued.
+ */
+ readonly continuationToken?: string;
+ readonly url: string;
+ readonly callbackBaseUrl: string;
+ };
+
+/**
+ * Durable ownership record for one delegated child.
+ *
+ * The store owns the full nonterminal lifecycle:
+ *
+ * - `starting` — the parent committed intent to start; the child may or
+ * may not exist yet.
+ * - `running` — one identified child turn is outstanding.
+ * - `parked` — the child is idle and resumable; only this phase is
+ * model-visible.
+ *
+ * A terminal child has no handle: settlement deletes it.
+ */
+export type AgentHandle =
+ | {
+ readonly phase: "starting";
+ readonly identity: AgentIdentity;
+ readonly operation: StartOperation;
+ readonly target: AgentStartTarget;
+ }
+ | {
+ readonly phase: "running";
+ readonly identity: AgentIdentity;
+ readonly operation: StartOperation | ContinueOperation;
+ readonly address: AgentAddress;
+ }
+ | {
+ readonly phase: "parked";
+ readonly identity: AgentIdentity;
+ readonly address: AgentAddress;
+ readonly lastStatus: string;
+ };
+
+/** Lifecycle phase of a delegated agent handle. */
+export type AgentHandlePhase = AgentHandle["phase"];
+
+/** Session-state collection of delegated agent handles. */
+export interface AgentHandleStore {
+ readonly handles: readonly AgentHandle[];
+}
+
+const nonEmptyString = z.string().min(1);
+
+const identitySchema = z.strictObject({
+ id: nonEmptyString,
+ name: nonEmptyString,
+ nodeId: nonEmptyString,
+});
+
+const startOperationSchema = z.strictObject({
+ callId: nonEmptyString,
+ id: nonEmptyString,
+ kind: z.literal("start"),
+ parentTurnId: nonEmptyString,
+});
+
+const continueOperationSchema = z.strictObject({
+ callId: nonEmptyString,
+ id: nonEmptyString,
+ kind: z.literal("continue"),
+ parentTurnId: nonEmptyString,
+ previousStatus: z.string().max(MAX_STATUS_LENGTH),
+});
+
+const startTargetSchema: z.ZodType<AgentStartTarget> = z.discriminatedUnion("kind", [
+ z.strictObject({ continuationToken: nonEmptyString, kind: z.literal("agent/local") }),
+ z.strictObject({ continuationToken: nonEmptyString, kind: z.literal("agent/self") }),
+ z.strictObject({
+ callbackBaseUrl: z.url(),
+ kind: z.literal("agent/remote"),
+ url: z.url(),
+ }),
+]);
+
+const addressSchema: z.ZodType<AgentAddress> = z.discriminatedUnion("kind", [
+ z.strictObject({
+ continuationToken: nonEmptyString,
+ kind: z.literal("agent/local"),
+ sessionId: nonEmptyString,
+ }),
+ z.strictObject({
+ continuationToken: nonEmptyString,
+ kind: z.literal("agent/self"),
+ sessionId: nonEmptyString,
+ }),
+ z.strictObject({
+ callbackBaseUrl: z.url(),
+ continuationToken: nonEmptyString.optional(),
+ kind: z.literal("agent/remote"),
+ sessionId: nonEmptyString,
+ url: z.url(),
+ }),
+]);
+
+const agentHandleSchema: z.ZodType<AgentHandle> = z.discriminatedUnion("phase", [
+ z.strictObject({
+ identity: identitySchema,
+ operation: startOperationSchema,
+ phase: z.literal("starting"),
+ target: startTargetSchema,
+ }),
+ z.strictObject({
+ address: addressSchema,
+ identity: identitySchema,
+ operation: z.discriminatedUnion("kind", [startOperationSchema, continueOperationSchema]),
+ phase: z.literal("running"),
+ }),
+ z.strictObject({
+ address: addressSchema,
+ identity: identitySchema,
+ lastStatus: z.string().max(MAX_STATUS_LENGTH),
+ phase: z.literal("parked"),
+ }),
+]);
+
+const agentHandleStoreSchema: z.ZodType<AgentHandleStore> = z
+ .strictObject({
+ handles: z.array(agentHandleSchema),
+ })
+ .refine(
+ (store) =>
+ new Set(store.handles.map((handle) => handle.identity.id)).size === store.handles.length,
+ { message: "Agent handle ids must be unique." },
+ );
+
+/** Derives the model-visible agent id from the first start operation. */
+export function deriveAgentId(name: string, startOperationId: string): string {
+ return `ag_${name}:${startOperationId.slice(0, 12)}`;
+}
+
+/** Collapses whitespace and truncates output into a handle status line. */
+export function formatAgentStatus(output: unknown): string {
+ const text = typeof output === "string" ? output : (JSON.stringify(output) ?? "");
+ return text.replaceAll(/\s+/g, " ").trim().slice(0, MAX_STATUS_LENGTH);
+}
+
+/**
+ * Validates one agent handle store about to be persisted, returning the
+ * parsed value. Throws instead of writing an invalid store: transitions run
+ * this on every write, which is the invariant that lets the schema-free
+ * driver-side reader (`query.ts`) trust stored values without revalidating.
+ */
+export function assertPersistableAgentHandleStore(store: AgentHandleStore): AgentHandleStore {
+ const parsed = agentHandleStoreSchema.safeParse(store);
+ if (!parsed.success) {
+ throw new Error(`Refusing to persist a corrupt agent handle store: ${parsed.error.message}`);
+ }
+ return parsed.data;
+}
+
+/**
+ * Reads and validates the agent handle store from session state.
+ *
+ * Returns `undefined` only when no store has been written. A present but
+ * invalid store throws: treating corruption as absence would let the next
+ * transition silently replace every delegated child's delivery coordinates.
+ */
+export function getAgentHandleStore(
+ state: SessionStateMap | undefined,
+): AgentHandleStore | undefined {
+ const raw = state?.[AGENT_HANDLES_STATE_KEY];
+ if (raw === undefined) {
+ return undefined;
+ }
+ const parsed = agentHandleStoreSchema.safeParse(raw);
+ if (!parsed.success) {
+ throw new Error(
+ `Corrupt agent handle store under session state key "${AGENT_HANDLES_STATE_KEY}": ${parsed.error.message}`,
+ );
+ }
+ return parsed.data;
+}
diff --git a/packages/eve/src/harness/agent-handles.test.ts b/packages/eve/src/harness/handles/transitions.test.ts
similarity index 71%
rename from packages/eve/src/harness/agent-handles.test.ts
rename to packages/eve/src/harness/handles/transitions.test.ts
index 952a6c3b9..24dfbf408 100644
--- a/packages/eve/src/harness/agent-handles.test.ts
+++ b/packages/eve/src/harness/handles/transitions.test.ts
@@ -1,24 +1,22 @@
import { describe, expect, it } from "vitest";
+import { deriveAgentOperationId } from "#harness/handles/operation-id.js";
import {
- AGENT_HANDLES_STATE_KEY,
- confirmAgentStarted,
deriveAgentId,
- deriveAgentOperationId,
- formatAgentStatus,
getAgentHandleStore,
- prepareAgentContinuation,
- prepareAgentStart,
- projectParkedAgentHandles,
- rejectAgentEffect,
- renderAgentsSnippet,
- settleAgentTurn,
type AgentAddress,
type AgentHandle,
type AgentIdentity,
type ContinueOperation,
type StartOperation,
-} from "#harness/agent-handles.js";
+} from "#harness/handles/store.js";
+import {
+ confirmAgentStarted,
+ prepareAgentContinuation,
+ prepareAgentStart,
+ rejectAgentEffect,
+ settleAgentTurn,
+} from "#harness/handles/transitions.js";
import type { HarnessSession } from "#harness/types.js";
import type { TokenUsage } from "#shared/token-usage.js";
@@ -90,7 +88,6 @@ function parkedSession(): HarnessSession {
result: { kind: "succeeded", output: "initial findings" },
usageDelta: ZERO_USAGE,
},
- sessionId: address.sessionId,
});
if (settled.kind !== "settled") {
throw new Error("expected settled");
@@ -102,65 +99,6 @@ function handlesOf(session: HarnessSession): readonly AgentHandle[] {
return getAgentHandleStore(session.state)?.handles ?? [];
}
-describe("deriveAgentOperationId / deriveAgentId", () => {
- it("is deterministic on parent-controlled inputs and independent of the child session", () => {
- const again = deriveAgentOperationId({
- callId: "call_1",
- parentSessionId: "session_parent",
- parentTurnId: "turn_1",
- });
- expect(again).toBe(startOperation.id);
- expect(deriveAgentId("research", again)).toBe(identity.id);
- expect(identity.id.startsWith("ag_research:")).toBe(true);
- });
-
- it("changes when any input changes", () => {
- const other = deriveAgentOperationId({
- callId: "call_2",
- parentSessionId: "session_parent",
- parentTurnId: "turn_1",
- });
- expect(other).not.toBe(startOperation.id);
- });
-});
-
-describe("getAgentHandleStore", () => {
- it("returns undefined only when no store has been written", () => {
- expect(getAgentHandleStore(undefined)).toBeUndefined();
- expect(getAgentHandleStore({})).toBeUndefined();
- });
-
- it("throws on a present but malformed store instead of treating it as absent", () => {
- for (const malformed of [
- null,
- { handles: "not-an-array" },
- { handles: [{ phase: "starting" }] },
- { extra: true, handles: [] },
- {
- handles: [
- {
- address,
- identity,
- lastStatus: "x".repeat(121),
- phase: "parked",
- },
- ],
- },
- ]) {
- expect(() => getAgentHandleStore({ [AGENT_HANDLES_STATE_KEY]: malformed })).toThrow(
- AGENT_HANDLES_STATE_KEY,
- );
- }
- });
-
- it("rejects duplicate handle ids", () => {
- const parked = handlesOf(parkedSession());
- expect(() =>
- getAgentHandleStore({ [AGENT_HANDLES_STATE_KEY]: { handles: [...parked, ...parked] } }),
- ).toThrow("unique");
- });
-});
-
describe("prepareAgentStart", () => {
it("records starting ownership before any side effect", () => {
const session = preparedSession();
@@ -341,7 +279,6 @@ describe("settleAgentTurn", () => {
result: { kind: "succeeded", output: ` padded\n${"x".repeat(200)} ` },
usageDelta: ZERO_USAGE,
},
- sessionId: address.sessionId,
});
expect(settled.kind).toBe("settled");
if (settled.kind !== "settled") {
@@ -363,7 +300,6 @@ describe("settleAgentTurn", () => {
result: { error: { code: "BOOM" }, kind: "failed" },
usageDelta: ZERO_USAGE,
},
- sessionId: address.sessionId,
});
expect(settled.kind).toBe("settled");
if (settled.kind === "settled") {
@@ -379,7 +315,6 @@ describe("settleAgentTurn", () => {
result: { error: "model overloaded", kind: "failed" },
usageDelta: ZERO_USAGE,
},
- sessionId: address.sessionId,
});
expect(settled.kind).toBe("settled");
if (settled.kind === "settled") {
@@ -387,7 +322,7 @@ describe("settleAgentTurn", () => {
}
});
- it("ignores stale operations and mismatched child sessions", () => {
+ it("ignores stale operations", () => {
expect(
settleAgentTurn(runningSession(), {
operationId: "op_stale",
@@ -396,54 +331,7 @@ describe("settleAgentTurn", () => {
result: { kind: "succeeded", output: "" },
usageDelta: ZERO_USAGE,
},
- sessionId: address.sessionId,
}),
).toEqual({ kind: "ignored", reason: "unknown-operation" });
-
- expect(
- settleAgentTurn(runningSession(), {
- operationId: startOperation.id,
- outcome: {
- kind: "parked",
- result: { kind: "succeeded", output: "" },
- usageDelta: ZERO_USAGE,
- },
- sessionId: "session_forged",
- }),
- ).toEqual({ kind: "ignored", reason: "session-mismatch" });
- });
-});
-
-describe("projection", () => {
- it("projects and renders only parked handles", () => {
- const running = runningSession();
- const store = getAgentHandleStore(running.state);
- expect(store).toBeDefined();
- if (store === undefined) {
- return;
- }
- expect(projectParkedAgentHandles(store)).toEqual([]);
- expect(renderAgentsSnippet(store)).toBe("[Agents]\n<agents>\n</agents>");
-
- const parkedStore = getAgentHandleStore(parkedSession().state);
- expect(parkedStore).toBeDefined();
- if (parkedStore === undefined) {
- return;
- }
- const snippet = renderAgentsSnippet(parkedStore);
- expect(snippet.startsWith("[Agents]\n<agents>")).toBe(true);
- expect(snippet).toContain(
- `<agent id="${identity.id}" name="research">initial findings</agent>`,
- );
- expect(snippet).not.toContain(address.sessionId);
- expect(snippet).not.toContain(address.continuationToken);
- });
-});
-
-describe("formatAgentStatus", () => {
- it("collapses whitespace, truncates to 120, and stringifies objects", () => {
- expect(formatAgentStatus(" a\n\tb ")).toBe("a b");
- expect(formatAgentStatus({ ok: true })).toBe('{"ok":true}');
- expect(formatAgentStatus("y".repeat(300)).length).toBe(120);
});
});
diff --git a/packages/eve/src/harness/handles/transitions.ts b/packages/eve/src/harness/handles/transitions.ts
new file mode 100644
index 000000000..225845fdc
--- /dev/null
+++ b/packages/eve/src/harness/handles/transitions.ts
@@ -0,0 +1,297 @@
+import {
+ AGENT_HANDLES_STATE_KEY,
+ assertPersistableAgentHandleStore,
+ formatAgentStatus,
+ getAgentHandleStore,
+ type AgentAddress,
+ type AgentHandle,
+ type AgentIdentity,
+ type ContinueOperation,
+ type StartOperation,
+} from "#harness/handles/store.js";
+import type { HarnessSession } from "#harness/types.js";
+import type { AgentTurnOutcome } from "#shared/agent-turn-outcome.js";
+
+/**
+ * Records intent to start a fresh child. Must be applied to the step's
+ * working snapshot before the start side effect runs, so the returned state
+ * owns any child the step may have created.
+ *
+ * The guarantee is intra-step, not exactly-once: the prepared handle
+ * durably commits only when the enclosing dispatch step's result commits.
+ * A crash between an accepted start and that commit replays the step from
+ * the pre-step snapshot and re-runs the side effect.
+ *
+ * Throws when the identity or operation already exists: fresh starts mint
+ * a new identity, so a collision means corrupted derivation, not a replay.
+ */
+export function prepareAgentStart(
+ session: HarnessSession,
+ input: {
+ readonly identity: AgentIdentity;
+ readonly operation: StartOperation;
+ readonly target: AgentStartTargetInput;
+ },
+): HarnessSession {
+ const handles = getAgentHandleStore(session.state)?.handles ?? [];
+ if (handles.some((handle) => handle.identity.id === input.identity.id)) {
+ throw new Error(`Agent handle "${input.identity.id}" already exists.`);
+ }
+ return writeHandles(session, [
+ ...handles,
+ {
+ identity: input.identity,
+ operation: input.operation,
+ phase: "starting",
+ target: input.target,
+ },
+ ]);
+}
+
+type AgentStartTargetInput = Extract<AgentHandle, { phase: "starting" }>["target"];
+
+/** Result of preparing a continuation against an existing handle. */
+export type PrepareAgentContinuationResult =
+ | {
+ readonly kind: "ready";
+ readonly session: HarnessSession;
+ readonly handle: Extract<AgentHandle, { phase: "running" }>;
+ }
+ | { readonly kind: "unknown" }
+ | { readonly kind: "mismatch" }
+ | { readonly kind: "busy" };
+
+/**
+ * Records intent to deliver a follow-up turn to a parked child. Must be
+ * applied to the step's working snapshot before the delivery side effect
+ * runs.
+ *
+ * Delivery is at-least-once, not exactly-once: the `running` handle durably
+ * commits only when the enclosing dispatch step's result commits. If the
+ * step dies after a successful delivery, replay starts from `parked` and
+ * delivers the same operation again — which is why replaying the operation
+ * already recorded on a running handle returns `ready` with the unchanged
+ * session instead of a busy conflict.
+ *
+ * `unknown`, `mismatch`, and `busy` do not change the session; the caller
+ * maps them onto `AGENT_UNKNOWN`, `AGENT_MISMATCH`, and `AGENT_BUSY`
+ * results.
+ */
+export function prepareAgentContinuation(
+ session: HarnessSession,
+ input: {
+ readonly agentId: string;
+ readonly invokedName: string;
+ readonly operation: ContinueOperation;
+ },
+): PrepareAgentContinuationResult {
+ const handles = getAgentHandleStore(session.state)?.handles ?? [];
+ const existing = handles.find((handle) => handle.identity.id === input.agentId);
+ if (existing === undefined) {
+ return { kind: "unknown" };
+ }
+ if (existing.identity.name !== input.invokedName) {
+ return { kind: "mismatch" };
+ }
+ if (existing.phase === "running" && existing.operation.id === input.operation.id) {
+ return { handle: existing, kind: "ready", session };
+ }
+ if (existing.phase !== "parked") {
+ return { kind: "busy" };
+ }
+
+ const running: Extract<AgentHandle, { phase: "running" }> = {
+ address: existing.address,
+ identity: existing.identity,
+ operation: { ...input.operation, previousStatus: existing.lastStatus },
+ phase: "running",
+ };
+ return {
+ handle: running,
+ kind: "ready",
+ session: writeHandles(
+ session,
+ handles.map((handle) => (handle.identity.id === input.agentId ? running : handle)),
+ ),
+ };
+}
+
+type ActiveAgentHandle = Extract<AgentHandle, { phase: "starting" | "running" }>;
+
+function findActiveHandle(
+ handles: readonly AgentHandle[],
+ operationId: string,
+): ActiveAgentHandle | undefined {
+ return handles.find(
+ (handle): handle is ActiveAgentHandle =>
+ handle.phase !== "parked" && handle.operation.id === operationId,
+ );
+}
+
+/**
+ * Confirms a started child: `starting` becomes `running` with the child's
+ * confirmed address. Throws when no starting handle carries the operation,
+ * because confirming an unprepared start means ownership was never
+ * committed. Re-confirming an already-running handle with the same
+ * operation and address is a replay no-op.
+ */
+export function confirmAgentStarted(
+ session: HarnessSession,
+ input: {
+ readonly operationId: string;
+ readonly address: AgentAddress;
+ },
+): HarnessSession {
+ const handles = getAgentHandleStore(session.state)?.handles ?? [];
+ const existing = findActiveHandle(handles, input.operationId);
+ if (existing === undefined) {
+ throw new Error(`No prepared agent handle for operation "${input.operationId}".`);
+ }
+ if (existing.phase === "running") {
+ return session;
+ }
+
+ return writeHandles(
+ session,
+ handles.map((handle) =>
+ handle === existing
+ ? {
+ address: input.address,
+ identity: existing.identity,
+ operation: existing.operation,
+ phase: "running",
+ }
+ : handle,
+ ),
+ );
+}
+
+/**
+ * Resolves a dispatch that definitively failed.
+ *
+ * - A dead start or dead continuation deletes the handle: there is no
+ * child left to own.
+ * - A retryable continuation failure restores `parked` with the status the
+ * handle showed before the delivery, so the model may retry the same
+ * `agentId` later.
+ *
+ * Unknown operations are a no-op: the failure raced a settlement that
+ * already resolved the handle.
+ */
+export function rejectAgentEffect(
+ session: HarnessSession,
+ input: {
+ readonly operationId: string;
+ readonly disposition: "dead" | "retryable";
+ },
+): HarnessSession {
+ const handles = getAgentHandleStore(session.state)?.handles ?? [];
+ const existing = findActiveHandle(handles, input.operationId);
+ if (existing === undefined) {
+ return session;
+ }
+
+ if (input.disposition === "retryable" && existing.phase === "running") {
+ const { operation } = existing;
+ if (operation.kind === "continue") {
+ return writeHandles(
+ session,
+ handles.map((handle) =>
+ handle === existing
+ ? {
+ address: existing.address,
+ identity: existing.identity,
+ lastStatus: operation.previousStatus,
+ phase: "parked",
+ }
+ : handle,
+ ),
+ );
+ }
+ }
+
+ return writeHandles(
+ session,
+ handles.filter((handle) => handle !== existing),
+ );
+}
+
+/** Result of applying a settled child turn to the store. */
+export type SettleAgentTurnResult =
+ | { readonly kind: "settled"; readonly session: HarnessSession }
+ | { readonly kind: "ignored"; readonly reason: "unknown-operation" };
+
+/**
+ * Applies one settled child turn: `running` becomes `parked` for a parked
+ * outcome or is deleted for a terminal outcome.
+ *
+ * The settlement must carry the operation currently recorded on the
+ * running handle; anything else is ignored so a stale delivery can never
+ * move a newer turn.
+ */
+export function settleAgentTurn(
+ session: HarnessSession,
+ input: {
+ readonly operationId: string;
+ readonly outcome: AgentTurnOutcome;
+ },
+): SettleAgentTurnResult {
+ const handles = getAgentHandleStore(session.state)?.handles ?? [];
+ const existing = handles.find(
+ (handle) => handle.phase === "running" && handle.operation.id === input.operationId,
+ );
+ if (existing === undefined || existing.phase !== "running") {
+ return { kind: "ignored", reason: "unknown-operation" };
+ }
+
+ if (input.outcome.kind === "terminal") {
+ return {
+ kind: "settled",
+ session: writeHandles(
+ session,
+ handles.filter((handle) => handle !== existing),
+ ),
+ };
+ }
+
+ const { result } = input.outcome;
+ const lastStatus =
+ result.kind === "succeeded"
+ ? formatAgentStatus(result.output)
+ : result.kind === "failed"
+ ? formatAgentStatus(result.error)
+ : "(cancelled)";
+ return {
+ kind: "settled",
+ session: writeHandles(
+ session,
+ handles.map((handle) =>
+ handle === existing
+ ? {
+ address: existing.address,
+ identity: existing.identity,
+ lastStatus,
+ phase: "parked",
+ }
+ : handle,
+ ),
+ ),
+ };
+}
+
+/**
+ * Persists the handle store, validating it against the strict store schema
+ * first. This write-time check is what lets the schema-free driver-side
+ * reader (`query.ts`) trust any stored value without revalidating: a
+ * transition bug fails loudly here instead of poisoning the session for
+ * every later read.
+ */
+function writeHandles(session: HarnessSession, handles: readonly AgentHandle[]): HarnessSession {
+ return {
+ ...session,
+ state: {
+ ...session.state,
+ [AGENT_HANDLES_STATE_KEY]: assertPersistableAgentHandleStore({ handles }),
+ },
+ };
+}
diff --git a/packages/eve/src/harness/runtime-actions.test.ts b/packages/eve/src/harness/runtime-actions.test.ts
index f811bf3a6..7a719b7a7 100644
--- a/packages/eve/src/harness/runtime-actions.test.ts
+++ b/packages/eve/src/harness/runtime-actions.test.ts
@@ -1,15 +1,30 @@
+import {
+ isInboxSubagentResultFromRunningHandle,
+ isResultBoundToRunningHandle,
+} from "#harness/handles/query.js";
import { describe, expect, it } from "vitest";
import {
getPendingRuntimeActionBatch,
- recordPendingSubagentChild,
resolvePendingRuntimeActions,
resolveToolCallInputObject,
setPendingRuntimeActionBatch,
} 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 { 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 OPERATION_ID = deriveAgentOperationId({
+ callId: "call-1",
+ parentSessionId: "test-session",
+ parentTurnId: "turn_0",
+});
+
function createParkedSession(): HarnessSession {
const base: HarnessSession = {
agent: { modelReference: { id: "test-model" }, system: "", tools: [] },
@@ -38,7 +53,7 @@ function createParkedSession(): HarnessSession {
{
callId: "call-1",
description: "research subagent",
- input: { message: "go" },
+ input: { description: "Research the topic", message: "go" },
kind: "subagent-call",
name: "researcher",
nodeId: "subagents/researcher",
@@ -51,9 +66,130 @@ function createParkedSession(): HarnessSession {
});
}
+/** Parked session whose call-1 child is owned by a running agent handle. */
+function createSessionWithRunningChild(): HarnessSession {
+ const prepared = prepareAgentStart(createParkedSession(), {
+ identity: {
+ id: deriveAgentId("researcher", OPERATION_ID),
+ name: "researcher",
+ nodeId: "subagents/researcher",
+ },
+ operation: {
+ callId: "call-1",
+ id: OPERATION_ID,
+ kind: "start",
+ parentTurnId: "turn_0",
+ },
+ target: { continuationToken: CHILD_CONTINUATION_TOKEN, kind: "agent/local" },
+ });
+ return confirmAgentStarted(prepared, {
+ address: {
+ continuationToken: CHILD_CONTINUATION_TOKEN,
+ kind: "agent/local",
+ sessionId: CHILD_SESSION_ID,
+ },
+ operationId: OPERATION_ID,
+ });
+}
+
describe("resolvePendingRuntimeActions", () => {
+ it("settles the running handle terminally and deletes it with the batch", async () => {
+ const session = createSessionWithRunningChild();
+
+ const resolved = await resolvePendingRuntimeActions({
+ session,
+ stepInput: {
+ runtimeActionResults: [
+ {
+ callId: "call-1",
+ kind: "subagent-result",
+ origin: "child",
+ output: "done",
+ subagentName: "researcher",
+ },
+ ],
+ },
+ });
+
+ expect(resolved.outcome).toBe("resolved");
+ expect(getPendingRuntimeActionBatch(resolved.session.state)).toBeUndefined();
+ expect(getAgentHandleStore(resolved.session.state)).toEqual({ handles: [] });
+ });
+
+ it("settles a failed child result terminally as well", async () => {
+ const session = createSessionWithRunningChild();
+
+ const resolved = await resolvePendingRuntimeActions({
+ session,
+ stepInput: {
+ runtimeActionResults: [
+ {
+ callId: "call-1",
+ isError: true,
+ kind: "subagent-result",
+ origin: "child",
+ output: { code: "SESSION_FAILED", message: "child failed" },
+ subagentName: "researcher",
+ },
+ ],
+ },
+ });
+
+ expect(resolved.outcome).toBe("resolved");
+ expect(getAgentHandleStore(resolved.session.state)).toEqual({ handles: [] });
+ });
+
+ it("clears the child's proxy-input entries before settling its handle", async () => {
+ const session = upsertProxyInputRequests({
+ entries: [
+ ["request-1", { childContinuationToken: CHILD_CONTINUATION_TOKEN, kind: "question" }],
+ ],
+ forChildContinuationToken: CHILD_CONTINUATION_TOKEN,
+ session: createSessionWithRunningChild(),
+ });
+
+ const resolved = await resolvePendingRuntimeActions({
+ session,
+ stepInput: {
+ runtimeActionResults: [
+ {
+ callId: "call-1",
+ kind: "subagent-result",
+ origin: "child",
+ output: "done",
+ subagentName: "researcher",
+ },
+ ],
+ },
+ });
+
+ expect(resolved.outcome).toBe("resolved");
+ expect(getProxyInputRequests(resolved.session.state).size).toBe(0);
+ });
+
+ it("accepts a dispatch-origin failure result by callId", async () => {
+ const resolved = await resolvePendingRuntimeActions({
+ session: createParkedSession(),
+ stepInput: {
+ runtimeActionResults: [
+ {
+ callId: "call-1",
+ isError: true,
+ kind: "subagent-result",
+ origin: "dispatch",
+ output: { code: "SUBAGENT_START_FAILED", message: "boom" },
+ subagentName: "researcher",
+ },
+ ],
+ },
+ });
+
+ expect(resolved.outcome).toBe("resolved");
+ expect(getPendingRuntimeActionBatch(resolved.session.state)).toBeUndefined();
+ });
+
it("draws completed child usage down against the parent's session totals", async () => {
- const session = createParkedSession();
+ const session = createSessionWithRunningChild();
const resolved = await resolvePendingRuntimeActions({
session,
@@ -62,6 +198,7 @@ describe("resolvePendingRuntimeActions", () => {
{
callId: "call-1",
kind: "subagent-result",
+ origin: "child",
output: "done",
subagentName: "researcher",
usage: {
@@ -83,7 +220,7 @@ describe("resolvePendingRuntimeActions", () => {
});
it("leaves the parent's totals untouched when the child reports no usage", async () => {
- const session = createParkedSession();
+ const session = createSessionWithRunningChild();
const resolved = await resolvePendingRuntimeActions({
session,
@@ -92,6 +229,7 @@ describe("resolvePendingRuntimeActions", () => {
{
callId: "call-1",
kind: "subagent-result",
+ origin: "child",
output: "done",
subagentName: "researcher",
},
@@ -107,33 +245,56 @@ describe("resolvePendingRuntimeActions", () => {
});
});
-describe("pending subagent child adoption", () => {
- it("records child session ids without disturbing local continuation-token cleanup", () => {
- let session = createParkedSession();
- session = recordPendingSubagentChild({
+describe("result-to-handle binding", () => {
+ const boundResult = {
+ callId: "call-1",
+ kind: "subagent-result",
+ origin: "child",
+ output: "done",
+ subagentName: "researcher",
+ } as const;
+
+ it("accepts only results a running handle binds by callId", () => {
+ // Possession of the callback token authorizes settlement; binding is by
+ // callId alone. A callId with no running handle — one whose dispatch
+ // already failed — finds nothing and cannot overwrite the
+ // dispatch-produced error result.
+ const state = createSessionWithRunningChild().state;
+
+ for (const bound of [isResultBoundToRunningHandle, isInboxSubagentResultFromRunningHandle]) {
+ expect(bound(state, boundResult)).toBe(true);
+ expect(bound(state, { ...boundResult, callId: "call-other" })).toBe(false);
+ }
+ expect(
+ isResultBoundToRunningHandle(state, {
+ callId: "call-1",
+ kind: "tool-result",
+ output: "",
+ toolName: "x",
+ }),
+ ).toBe(true);
+ expect(
+ isInboxSubagentResultFromRunningHandle(state, {
+ ...boundResult,
+ callId: "call-unknown",
+ }),
+ ).toBe(false);
+ });
+
+ it("trusts dispatch-origin results on the parent step path", () => {
+ // The subagent-only inbox type cannot represent dispatch failures. These
+ // parent-synthesized results enter through the trusted step-result path.
+ const dispatchFailure = {
callId: "call-1",
- child: {
- continuationToken: "subagent:test-session:call-1",
- kind: "local",
- sessionId: "local-child",
- },
- session,
- });
- session = recordPendingSubagentChild({
- callId: "call-remote",
- child: { kind: "remote", sessionId: "remote-child" },
- session,
- });
+ isError: true,
+ kind: "subagent-result",
+ origin: "dispatch",
+ output: { code: "SUBAGENT_START_FAILED", message: "boom" },
+ subagentName: "researcher",
+ } as const;
+ const state = createSessionWithRunningChild().state;
- expect(getPendingRuntimeActionBatch(session.state)).toMatchObject({
- childContinuationTokens: {
- "call-1": "subagent:test-session:call-1",
- },
- childSessionIds: {
- "call-1": "local-child",
- "call-remote": "remote-child",
- },
- });
+ expect(isResultBoundToRunningHandle(state, dispatchFailure)).toBe(true);
});
});
diff --git a/packages/eve/src/harness/runtime-actions.ts b/packages/eve/src/harness/runtime-actions.ts
index 41d3a8cef..14893d05b 100644
--- a/packages/eve/src/harness/runtime-actions.ts
+++ b/packages/eve/src/harness/runtime-actions.ts
@@ -1,9 +1,13 @@
import type { ModelMessage, ToolSet, TypedToolCall } from "ai";
import { createActionResultEvent, type UnstampedMessageStreamEvent } from "#protocol/message.js";
-import { getRuntimeActionRequestKey, getRuntimeActionResultKey } from "#runtime/actions/keys.js";
+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 { findRunningAgentHandle, isResultBoundToRunningHandle } from "#harness/handles/query.js";
+import { settleAgentTurn } from "#harness/handles/transitions.js";
import { clearProxyInputRequestsForChild } from "#harness/proxy-input-requests.js";
import {
accumulateSessionUsage,
@@ -22,6 +26,24 @@ 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.
+ */
+function readSubagentResultUsage(
+ result: Extract<RuntimeActionResult, { kind: "subagent-result" }>,
+): TokenUsage | undefined {
+ return result.origin === "child" ? result.usage : undefined;
+}
+
/**
* Serializable event coordinates for one pending runtime-action batch.
*
@@ -37,14 +59,12 @@ interface PendingRuntimeActionEventMetadata {
/**
* Serializable pending runtime-action batch stored on `session.state`.
*
- * `childContinuationTokens` lets the harness clear local proxy-input entries
- * on result resolution. `childSessionIds` lets the turn workflow cancel every
- * successfully adopted local or remote child before dropping the batch.
+ * Child ownership does not live here: the agent handle store records every
+ * dispatched child (from before its start side effect) and is the sole
+ * authority for continuing, settling, and cancelling children.
*/
export interface PendingRuntimeActionBatch {
readonly actions: readonly RuntimeActionRequest[];
- readonly childContinuationTokens?: Readonly<Record<string, string>>;
- readonly childSessionIds?: Readonly<Record<string, string>>;
readonly event: PendingRuntimeActionEventMetadata;
readonly responseMessages: readonly ModelMessage[];
}
@@ -117,49 +137,6 @@ export function setPendingRuntimeActionBatch(input: {
return { ...input.session, state };
}
-type PendingSubagentChildIdentity =
- | {
- readonly continuationToken: string;
- readonly kind: "local";
- readonly sessionId: string;
- }
- | {
- readonly kind: "remote";
- readonly sessionId: string;
- };
-
-/** Records one successfully dispatched child's durable identities. */
-export function recordPendingSubagentChild(input: {
- readonly callId: string;
- readonly child: PendingSubagentChildIdentity;
- readonly session: HarnessSession;
-}): HarnessSession {
- const batch = getPendingRuntimeActionBatch(input.session.state);
-
- if (batch === undefined) {
- return input.session;
- }
-
- const state = { ...input.session.state };
- state[PENDING_RUNTIME_ACTION_BATCH_KEY] = {
- ...batch,
- ...(input.child.kind === "local"
- ? {
- childContinuationTokens: {
- ...batch.childContinuationTokens,
- [input.callId]: input.child.continuationToken,
- },
- }
- : {}),
- childSessionIds: {
- ...batch.childSessionIds,
- [input.callId]: input.child.sessionId,
- },
- } satisfies PendingRuntimeActionBatch;
-
- return { ...input.session, state };
-}
-
/**
* Returns the stable ordered runtime-action results for the current pending
* batch when every action has a matching result. Unknown and duplicate results
@@ -175,52 +152,24 @@ function resolveReadyRuntimeActionResults(input: {
return undefined;
}
- return resolveRuntimeActionResultsForBatch({ batch, results: input.results });
+ return resolveRuntimeActionResultsForBatch({
+ batch,
+ results: input.results,
+ state: input.session.state,
+ });
}
function resolveRuntimeActionResultsForBatch(input: {
readonly batch: PendingRuntimeActionBatch;
readonly results: readonly RuntimeActionResult[];
+ readonly state: SessionStateMap | undefined;
}): RuntimeActionResult[] | undefined {
return resolveRuntimeActionResultsForKeys({
pendingKeys: input.batch.actions.map((action) => getRuntimeActionRequestKey(action)),
- results: input.results,
+ results: input.results.filter((result) => isResultBoundToRunningHandle(input.state, result)),
});
}
-/** Returns results in pending-key order once every requested action has completed. */
-export function resolveRuntimeActionResultsForKeys(input: {
- readonly pendingKeys: readonly string[];
- readonly results: readonly RuntimeActionResult[];
-}): RuntimeActionResult[] | undefined {
- const pendingKeySet = new Set(input.pendingKeys);
- const resultsByKey = new Map<string, RuntimeActionResult>();
-
- for (const result of input.results) {
- const key = getRuntimeActionResultKey(result);
-
- if (!pendingKeySet.has(key)) {
- continue;
- }
-
- resultsByKey.set(key, result);
- }
-
- const orderedResults: RuntimeActionResult[] = [];
-
- for (const key of input.pendingKeys) {
- const result = resultsByKey.get(key);
-
- if (result === undefined) {
- return undefined;
- }
-
- orderedResults.push(result);
- }
-
- return orderedResults;
-}
-
/**
* Resolves one pending runtime-action batch back into model history.
*
@@ -282,42 +231,66 @@ export async function resolvePendingRuntimeActions(input: {
}
}
- const state = { ...input.session.state };
- delete state[PENDING_RUNTIME_ACTION_BATCH_KEY];
-
- let nextSession: HarnessSession = {
- ...input.session,
- state: Object.keys(state).length > 0 ? state : undefined,
- };
-
- // Clear proxy-input entries for completed children so future
+ // 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
// deliveries don't route responses to a dead child.
- const childTokens = batch.childContinuationTokens;
- if (childTokens !== undefined) {
- for (const result of readyResults) {
- if (result.kind !== "subagent-result") {
- continue;
- }
-
- const childToken = childTokens[result.callId];
- if (childToken !== undefined) {
- nextSession = clearProxyInputRequestsForChild(nextSession, childToken);
- }
+ let nextSession: HarnessSession = input.session;
+ for (const result of readyResults) {
+ // Dispatch failures never settle handles: the dispatch step already
+ // rejected (deleted) the handle when it synthesized the failure.
+ if (result.kind !== "subagent-result" || result.origin !== "child") {
+ continue;
+ }
+ const handle = findRunningAgentHandle(nextSession.state, { callId: result.callId });
+ if (handle === undefined) {
+ continue;
+ }
+ if (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,
+ },
+ });
+ if (settled.kind === "settled") {
+ nextSession = settled.session;
}
}
+ const state = { ...nextSession.state };
+ delete state[PENDING_RUNTIME_ACTION_BATCH_KEY];
+ nextSession = {
+ ...nextSession,
+ state: Object.keys(state).length > 0 ? state : undefined,
+ };
+
// Draw completed 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.
+ // delegations account for what the tree has already spent. Only
+ // child-produced results carry usage; parent-side dispatch failures
+ // never do.
for (const result of readyResults) {
- if (result.kind !== "subagent-result" || result.usage === undefined) {
+ if (result.kind !== "subagent-result") {
+ continue;
+ }
+ const usage = readSubagentResultUsage(result);
+ if (usage === undefined) {
continue;
}
nextSession = setTurnUsageState(
nextSession,
accumulateSessionUsage({
previous: getTurnUsageState(nextSession.state),
- usage: result.usage,
+ usage,
}),
);
}
@@ -358,7 +331,6 @@ export async function resolvePendingRuntimeActions(input: {
role: "tool",
});
}
-
return {
messages,
outcome: "resolved",
diff --git a/packages/eve/src/harness/tool-loop.test.ts b/packages/eve/src/harness/tool-loop.test.ts
index 63e315d7d..903b3c9e0 100644
--- a/packages/eve/src/harness/tool-loop.test.ts
+++ b/packages/eve/src/harness/tool-loop.test.ts
@@ -43,8 +43,9 @@ import {
setPendingInputBatch,
} from "#harness/input-requests.js";
import { getPendingRuntimeActionBatch } from "#harness/runtime-actions.js";
+import { AGENT_HANDLES_STATE_KEY } from "#harness/handles/store.js";
import { stashToolInterrupt } from "#harness/tool-interrupts.js";
-import { createToolLoopHarness } from "#harness/tool-loop.js";
+import { appendMissingToolResultMessages, createToolLoopHarness } from "#harness/tool-loop.js";
import { isSessionLimitDecline, TurnCancelledError } from "#harness/turn-cancellation.js";
import {
getSessionTokenLimitViolation,
@@ -690,6 +691,118 @@ describe("createToolLoopHarness", () => {
expect(agentCall!.tools).not.toHaveProperty("Workflow");
});
+ it("announces current agents outside the cacheable system prompt", async () => {
+ setupMockAgent({
+ finishReason: "stop",
+ response: { messages: [{ content: "Hello!", role: "assistant" }] },
+ text: "Hello!",
+ toolCalls: [],
+ toolResults: [],
+ });
+
+ const runStep = createToolLoopHarness(
+ createTestConfig("conversation", undefined, {
+ persistentSubagentSessions: true,
+ resolveModel: vi.fn().mockResolvedValue(
+ new MockLanguageModelV3({
+ modelId: "claude-sonnet-4-5",
+ provider: "anthropic.messages",
+ }),
+ ),
+ }),
+ );
+ const session = createTestSession({
+ state: {
+ [AGENT_HANDLES_STATE_KEY]: {
+ handles: [
+ {
+ address: {
+ continuationToken: "private-token",
+ kind: "agent/local",
+ sessionId: "child-session-123456789012",
+ },
+ identity: {
+ id: "ag_research:123456789012",
+ name: "research",
+ nodeId: "subagents/research",
+ },
+ lastStatus: "waiting",
+ phase: "parked",
+ },
+ ],
+ },
+ },
+ });
+
+ const result = await runStep(session, { message: "Hi" });
+
+ const { instructions } = vi.mocked(ToolLoopAgent).mock.calls[0]![0];
+ const agent = vi.mocked(ToolLoopAgent).mock.results[0]?.value as {
+ generate: ReturnType<typeof vi.fn>;
+ };
+ const messages = agent.generate.mock.calls[0]?.[0].messages as ModelMessage[];
+ expect(instructions).toBe("You are a test assistant.");
+ expect(messages).toContainEqual({
+ content: expect.stringContaining(
+ '<agent id="ag_research:123456789012" name="research">waiting</agent>',
+ ),
+ role: "assistant",
+ });
+ expect(messages.at(-1)).toEqual({ content: "Hi", role: "user" });
+ expect(JSON.stringify({ instructions, messages })).not.toContain("private-token");
+ expect(result.session.history).toContainEqual({
+ content: expect.stringContaining('<agent id="ag_research:123456789012"'),
+ role: "assistant",
+ });
+ });
+
+ it("skips the agents snippet when no handle is parked", async () => {
+ setupMockAgent({
+ finishReason: "stop",
+ response: { messages: [{ content: "Hello!", role: "assistant" }] },
+ text: "Hello!",
+ toolCalls: [],
+ toolResults: [],
+ });
+
+ const runStep = createToolLoopHarness(
+ createTestConfig("conversation", undefined, { persistentSubagentSessions: true }),
+ );
+ const session = createTestSession({
+ state: {
+ [AGENT_HANDLES_STATE_KEY]: {
+ handles: [
+ {
+ identity: {
+ id: "ag_research:123456789012",
+ name: "research",
+ nodeId: "subagents/research",
+ },
+ operation: {
+ callId: "call-1",
+ id: "op-1",
+ kind: "start",
+ parentTurnId: "turn-1",
+ },
+ phase: "starting",
+ target: { continuationToken: "private-token", kind: "agent/local" },
+ },
+ ],
+ },
+ },
+ });
+
+ await runStep(session, { message: "Hi" });
+
+ const call = vi.mocked(ToolLoopAgent).mock.calls[0]?.[0];
+ const agent = vi.mocked(ToolLoopAgent).mock.results[0]?.value as {
+ generate: ReturnType<typeof vi.fn>;
+ };
+ const messages = agent.generate.mock.calls[0]?.[0].messages as ModelMessage[];
+ expect(JSON.stringify(call?.instructions ?? "")).not.toContain("<agents>");
+ expect(JSON.stringify(messages)).not.toContain("<agents>");
+ });
+
it("uses dynamic model selection for the model call", async () => {
setupMockAgent({
finishReason: "stop",
@@ -10103,3 +10216,79 @@ describe("createToolLoopHarness", () => {
});
});
});
+
+describe("appendMissingToolResultMessages", () => {
+ const searchResult = {
+ type: "tool-result" as const,
+ toolCallId: "toolu_1",
+ toolName: "web_search",
+ output: { type: "json" as const, value: { winner: "OKC" } },
+ };
+
+ it("skips synthesized results for provider-executed calls already answered inline", () => {
+ // Provider-executed results live inside the *assistant* message until
+ // provider history normalization; a second result for the same id makes
+ // Anthropic reject the whole history on the next call.
+ const assistantWithInlineResult = {
+ role: "assistant" as const,
+ content: [
+ {
+ type: "tool-call" as const,
+ toolCallId: "toolu_1",
+ toolName: "web_search",
+ input: { query: "2025 NBA Finals" },
+ providerExecuted: true,
+ },
+ { ...searchResult, providerExecuted: true },
+ ],
+ };
+
+ const messages = appendMissingToolResultMessages({
+ append: [
+ {
+ type: "tool-result",
+ toolCallId: "toolu_1",
+ toolName: "web_search",
+ output: { type: "error-text", value: "Failed to parse tool-call arguments" },
+ },
+ ],
+ responseMessages: [assistantWithInlineResult],
+ });
+
+ expect(messages).toEqual([assistantWithInlineResult]);
+ });
+
+ it("still backfills calls with no result anywhere", () => {
+ const assistant = {
+ role: "assistant" as const,
+ content: [
+ {
+ type: "tool-call" as const,
+ toolCallId: "toolu_2",
+ toolName: "web_search",
+ input: {},
+ },
+ ],
+ };
+ const backfill = {
+ type: "tool-result" as const,
+ toolCallId: "toolu_2",
+ toolName: "web_search",
+ output: { type: "error-text" as const, value: "invalid input" },
+ };
+
+ expect(
+ appendMissingToolResultMessages({ append: [backfill], responseMessages: [assistant] }),
+ ).toEqual([assistant, { role: "tool", content: [backfill] }]);
+ });
+
+ it("dedupes against results already in tool messages", () => {
+ const toolMessage = { role: "tool" as const, content: [searchResult] };
+ expect(
+ appendMissingToolResultMessages({
+ append: [searchResult],
+ responseMessages: [toolMessage],
+ }),
+ ).toEqual([toolMessage]);
+ });
+});
diff --git a/packages/eve/src/harness/tool-loop.ts b/packages/eve/src/harness/tool-loop.ts
index e71e435e1..90a1767ab 100644
--- a/packages/eve/src/harness/tool-loop.ts
+++ b/packages/eve/src/harness/tool-loop.ts
@@ -49,6 +49,8 @@ import {
} from "#protocol/message.js";
import type { InstrumentationDefinition } from "#public/instrumentation/index.js";
import { ASK_QUESTION_TOOL_NAME } from "#runtime/framework-tools/ask-question.js";
+import { resolveAgentsAnnouncement } from "#harness/handles/prompt.js";
+import { getAgentHandleStore } from "#harness/handles/store.js";
import {
getWorkflowRuntimeActionInterrupts,
isWorkflowRuntimeActionInterrupt,
@@ -751,6 +753,16 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {
}
session = continuation.session;
+ if (config.persistentSubagentSessions === true) {
+ const announcement = resolveAgentsAnnouncement({
+ messages,
+ store: getAgentHandleStore(session.state),
+ });
+ if (announcement !== undefined) {
+ messages.push({ content: announcement, role: "assistant" });
+ }
+ }
+
if (effectiveStepInput?.context !== undefined && pending.deferredContext !== true) {
for (const entry of effectiveStepInput.context) {
messages.push({ content: entry, role: "user" });
@@ -1720,7 +1732,15 @@ function withAccumulatedResponseMessages(input: {
};
}
-function appendMissingToolResultMessages(input: {
+/**
+ * Appends synthesized tool results for calls that have no result anywhere in
+ * the step's response messages. Exported for its dedupe contract: a call
+ * already answered — including provider-executed results the SDK keeps
+ * inline in the assistant message — must never receive a second
+ * `tool-result`, or the next Anthropic call rejects the history with
+ * "each tool_use must have a single result".
+ */
+export function appendMissingToolResultMessages(input: {
readonly append: readonly ToolResultPart[];
readonly responseMessages: readonly StepResponseMessage[];
}): StepResponseMessage[] {
@@ -1752,16 +1772,23 @@ function getInvalidToolCallInputErrors(input: {
return errors;
}
+/**
+ * CallIds answered anywhere in the response messages. Scans every message
+ * role: provider-executed tool results arrive inline in the *assistant*
+ * message (the SDK only moves them to a `tool` message during provider
+ * history normalization, which runs after the backfill paths), so a
+ * tool-message-only scan would let a synthesized result duplicate them.
+ */
function extractToolResultCallIds(messages: readonly StepResponseMessage[]): ReadonlySet<string> {
const callIds = new Set<string>();
for (const message of messages) {
- if (message.role !== "tool" || !Array.isArray(message.content)) {
+ if (!Array.isArray(message.content)) {
continue;
}
for (const part of message.content) {
- if (part.type === "tool-result") {
+ if (typeof part === "object" && part !== null && part.type === "tool-result") {
callIds.add(part.toolCallId);
}
}
diff --git a/packages/eve/src/harness/types.ts b/packages/eve/src/harness/types.ts
index 78c6b5bb3..8c7df8444 100644
--- a/packages/eve/src/harness/types.ts
+++ b/packages/eve/src/harness/types.ts
@@ -278,6 +278,12 @@ export interface ToolLoopHarnessConfig {
* compacted history.
*/
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.
+ */
+ readonly persistentSubagentSessions?: boolean;
readonly dispatchDynamicModelEvent?: (input: {
readonly ctx: AlsContext;
readonly event: UnstampedMessageStreamEvent;
diff --git a/packages/eve/src/protocol/agent-handle-error.ts b/packages/eve/src/protocol/agent-handle-error.ts
new file mode 100644
index 000000000..c79f2f4a1
--- /dev/null
+++ b/packages/eve/src/protocol/agent-handle-error.ts
@@ -0,0 +1,27 @@
+/** JSON error returned when an agent-handle operation cannot be completed. */
+export interface AgentHandleErrorJson<TCode extends string = string> {
+ readonly code: TCode;
+ readonly error: string;
+ readonly ok: false;
+}
+
+function defineAgentHandleError<const TCode extends string>(
+ code: TCode,
+ message: string,
+): {
+ readonly code: TCode;
+ readonly toJson: () => AgentHandleErrorJson<TCode>;
+} {
+ return {
+ code,
+ toJson: () => ({ code, error: message, ok: false }),
+ };
+}
+
+/** Stable agent-handle errors shared by HTTP producers and consumers. */
+export const AgentHandleError = {
+ SessionNotResumable: defineAgentHandleError(
+ "SESSION_NOT_RESUMABLE",
+ "Session is not active and cannot be resumed.",
+ ),
+} as const;
diff --git a/packages/eve/src/public/channels/eve.test.ts b/packages/eve/src/public/channels/eve.test.ts
index 7603158aa..c04910504 100644
--- a/packages/eve/src/public/channels/eve.test.ts
+++ b/packages/eve/src/public/channels/eve.test.ts
@@ -20,6 +20,7 @@ import {
type Session as RuntimeSession,
} from "#context/keys.js";
import { createMessageCompletedEvent } from "#protocol/message.js";
+import { RuntimeNoActiveSessionError } from "#execution/runtime-errors.js";
/**
* Unit coverage for the inbound HTTP route's message-body parser and
@@ -740,6 +741,78 @@ describe("eveChannel — onMessage", () => {
const options = handler.send.mock.calls[0]?.[1] as SendOptions;
expect(options.auth).toEqual(ACCEPTED_AUTH);
});
+
+ it("maps validated continuation callback metadata onto the turn caller", async () => {
+ const handler = createEveContinueHandler({ auth: none() });
+
+ const response = await handler.fetch(
+ createJsonMessageRequest({
+ callback: {
+ callId: "call-2",
+ subagentName: "research",
+ token: "tok123",
+ url: "https://caller.example.com/eve/v1/callback/tok123",
+ },
+ continuationToken: "http:existing",
+ message: "follow up",
+ }),
+ );
+
+ expect(response.status).toBe(200);
+ expect(handler.send).toHaveBeenCalledWith(
+ expect.not.objectContaining({ caller: expect.anything() }),
+ expect.objectContaining({
+ caller: {
+ callId: "call-2",
+ replyTo: {
+ kind: "callback",
+ url: "https://caller.example.com/eve/v1/callback/tok123",
+ },
+ subagentName: "research",
+ },
+ intent: "resume",
+ }),
+ );
+ });
+
+ it("rejects invalid callback metadata on continuation requests", async () => {
+ const handler = createEveContinueHandler({ auth: none() });
+
+ const response = await handler.fetch(
+ createJsonMessageRequest({
+ callback: {
+ callId: "call-2",
+ subagentName: "research",
+ token: "tok123",
+ url: "https://caller.example.com/eve/v1/callback/other",
+ },
+ continuationToken: "http:existing",
+ message: "follow up",
+ }),
+ );
+
+ expect(response.status).toBe(400);
+ expect(handler.send).not.toHaveBeenCalled();
+ });
+
+ it("returns SESSION_NOT_RESUMABLE instead of starting a replacement session", async () => {
+ const handler = createEveContinueHandler({ auth: none() });
+ handler.send.mockRejectedValueOnce(new RuntimeNoActiveSessionError("eve:http:existing"));
+
+ const response = await handler.fetch(
+ createJsonMessageRequest({
+ continuationToken: "http:existing",
+ message: "follow up",
+ }),
+ );
+
+ expect(response.status).toBe(404);
+ await expect(response.json()).resolves.toEqual({
+ code: "SESSION_NOT_RESUMABLE",
+ error: "Session is not active and cannot be resumed.",
+ ok: false,
+ });
+ });
});
describe("eveChannel — create session (text)", () => {
@@ -763,7 +836,21 @@ describe("eveChannel — create session (text)", () => {
expect(handler.send.mock.calls[0]?.[1]).toMatchObject({ mode: "task" });
});
- it("accepts remote-agent callback metadata for task sessions", async () => {
+ it("accepts an explicit empty capability set for conversation sessions", async () => {
+ const handler = createEveCreateHandler({ auth: none() });
+
+ const response = await handler.fetch(
+ createJsonMessageRequest({ capabilities: {}, message: "hi", mode: "conversation" }),
+ );
+
+ expect(response.status).toBe(202);
+ expect(handler.send.mock.calls[0]?.[1]).toMatchObject({
+ capabilities: {},
+ mode: "conversation",
+ });
+ });
+
+ it("accepts remote-agent callback metadata for conversation sessions", async () => {
const handler = createEveCreateHandler({ auth: none() });
const response = await handler.fetch(
@@ -775,7 +862,7 @@ describe("eveChannel — create session (text)", () => {
url: "https://caller.example.com/eve/v1/callback/tok123",
},
message: "hi",
- mode: "task",
+ mode: "conversation",
}),
);
@@ -788,7 +875,7 @@ describe("eveChannel — create session (text)", () => {
token: "tok123",
url: "https://caller.example.com/eve/v1/callback/tok123",
},
- mode: "task",
+ mode: "conversation",
});
});
diff --git a/packages/eve/src/public/channels/eve.ts b/packages/eve/src/public/channels/eve.ts
index 7f58c8cfc..db0dc9dd1 100644
--- a/packages/eve/src/public/channels/eve.ts
+++ b/packages/eve/src/public/channels/eve.ts
@@ -1,6 +1,11 @@
import { type FilePart, type TextPart, type UserContent } from "ai";
-import type { CancelTurnResult, SessionAuthContext, SessionCallback } from "#channel/types.js";
+import type {
+ CancelTurnResult,
+ SessionAuthContext,
+ SessionCallback,
+ SessionCapabilities,
+} from "#channel/types.js";
import type { CancelTurnResponse } from "#protocol/cancel-turn.js";
import type { ClearResponse } from "#protocol/clear-session.js";
import type { CompactResponse } from "#protocol/compact-session.js";
@@ -8,12 +13,14 @@ import type { ResetResponse } from "#protocol/reset-session.js";
import type { SendOptions } from "#channel/routes.js";
import { resolveForwardedPrincipal, type TrustedForwarders } from "#channel/forwarded-principal.js";
import { parseSessionCallback } from "#channel/session-callback.js";
+import { isRuntimeNoActiveSessionError } from "#execution/runtime-errors.js";
import { hasInternalRefScheme } from "#internal/attachments/url-refs.js";
import { createLogger, logError } from "#internal/logging.js";
import {
readAgentInfoRouteResponse,
readRouteAgent,
} from "#internal/nitro/routes/channel-route-context.js";
+import { AgentHandleError } from "#protocol/agent-handle-error.js";
import {
EVE_MESSAGE_STREAM_CONTENT_TYPE,
EVE_MESSAGE_STREAM_FORMAT,
@@ -260,6 +267,7 @@ export function eveChannel(input: EveChannelInput): EveChannel {
const sendOptions: SendOptions = {
auth: messageResult.auth,
callback: body.callback,
+ capabilities: body.capabilities,
continuationToken: token,
mode: body.mode,
};
@@ -419,18 +427,39 @@ export function eveChannel(input: EveChannelInput): EveChannel {
dispatchAuth = messageResult.auth;
}
- const session = await send(
- {
- inputResponses: body.inputResponses,
- message: body.message,
- context,
- outputSchema: body.outputSchema,
- },
- {
- auth: dispatchAuth,
- continuationToken: body.continuationToken,
- },
- );
+ const sendOptions: SendOptions = {
+ auth: dispatchAuth,
+ continuationToken: body.continuationToken,
+ // This route addresses the session in the URL. If its continuation
+ // token no longer resolves, starting a new session would silently
+ // change that identity, so surface SESSION_NOT_RESUMABLE instead.
+ intent: "resume",
+ };
+ if (body.callback !== undefined) {
+ sendOptions.caller = {
+ callId: body.callback.callId,
+ replyTo: { kind: "callback", url: body.callback.url },
+ subagentName: body.callback.subagentName,
+ };
+ }
+
+ let session;
+ try {
+ session = await send(
+ {
+ inputResponses: body.inputResponses,
+ message: body.message,
+ context,
+ outputSchema: body.outputSchema,
+ },
+ sendOptions,
+ );
+ } catch (error) {
+ if (!isRuntimeNoActiveSessionError(error)) {
+ throw error;
+ }
+ return Response.json(AgentHandleError.SessionNotResumable.toJson(), { status: 404 });
+ }
return Response.json(
{
@@ -650,6 +679,7 @@ function droppedMessageResponse(): Response {
interface ParsedCreateBody {
callback?: SessionCallback;
+ capabilities?: SessionCapabilities;
message: string | UserContent;
mode?: RunMode;
context?: readonly string[];
@@ -666,6 +696,9 @@ function parseCreateBody(payload: Record<string, unknown>): ParsedCreateBody | R
const callback = parseCallbackField(payload.callback);
if (callback instanceof Response) return callback;
+ const capabilities = parseCapabilitiesField(payload.capabilities);
+ if (capabilities instanceof Response) return capabilities;
+
const mode = parseModeField(payload.mode);
if (mode instanceof Response) return mode;
@@ -679,10 +712,11 @@ function parseCreateBody(payload: Record<string, unknown>): ParsedCreateBody | R
);
}
- return { callback, message, mode, context, outputSchema };
+ return { callback, capabilities, message, mode, context, outputSchema };
}
interface ParsedContinueBody {
+ callback?: SessionCallback;
message?: string | UserContent;
continuationToken: string;
inputResponses?: readonly InputResponse[];
@@ -715,6 +749,9 @@ function parseContinueBody(payload: Record<string, unknown>): ParsedContinueBody
const message = parseMessageField(payload.message);
if (message instanceof Response) return message;
+ const callback = parseCallbackField(payload.callback);
+ if (callback instanceof Response) return callback;
+
const inputResponses = parseInputResponses(payload.inputResponses);
if (inputResponses instanceof Response) return inputResponses;
@@ -734,7 +771,7 @@ function parseContinueBody(payload: Record<string, unknown>): ParsedContinueBody
);
}
- return { message, continuationToken, inputResponses, context, outputSchema };
+ return { callback, message, continuationToken, inputResponses, context, outputSchema };
}
interface ParsedCancelTurnBody {
@@ -853,6 +890,30 @@ function parseCallbackField(value: unknown): SessionCallback | Response | undefi
return Response.json({ error: parsed.message, ok: false }, { status: 400 });
}
+function parseCapabilitiesField(value: unknown): SessionCapabilities | Response | undefined {
+ if (value === undefined) return undefined;
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
+ return Response.json(
+ { error: "Expected 'capabilities' to be an object.", ok: false },
+ { status: 400 },
+ );
+ }
+
+ const keys = Object.keys(value);
+ const requestInput = Reflect.get(value, "requestInput");
+ if (
+ keys.some((key) => key !== "requestInput") ||
+ (requestInput !== undefined && typeof requestInput !== "boolean")
+ ) {
+ return Response.json(
+ { error: "Expected 'capabilities.requestInput' to be a boolean when provided.", ok: false },
+ { status: 400 },
+ );
+ }
+
+ return requestInput === undefined ? {} : { requestInput };
+}
+
function parseModeField(value: unknown): RunMode | Response | undefined {
if (value === undefined) return undefined;
if (value === "conversation" || value === "task") return value;
diff --git a/packages/eve/src/public/tool-result-narrowing.test.ts b/packages/eve/src/public/tool-result-narrowing.test.ts
index 75bd55b55..1640b42c2 100644
--- a/packages/eve/src/public/tool-result-narrowing.test.ts
+++ b/packages/eve/src/public/tool-result-narrowing.test.ts
@@ -30,7 +30,13 @@ function toolResult(toolName: string, output: unknown, isError?: boolean): Runti
}
function subagentResult(): RuntimeActionResult {
- return { callId: "call_2", kind: "subagent-result", output: "done", subagentName: "sub" };
+ return {
+ callId: "call_2",
+ kind: "subagent-result",
+ origin: "child",
+ output: "done",
+ subagentName: "sub",
+ };
}
describe("toolResultFrom", () => {
diff --git a/packages/eve/src/runtime/actions/keys.test.ts b/packages/eve/src/runtime/actions/keys.test.ts
index 9b688dbdf..1046dd036 100644
--- a/packages/eve/src/runtime/actions/keys.test.ts
+++ b/packages/eve/src/runtime/actions/keys.test.ts
@@ -28,6 +28,7 @@ describe("runtime action keys", () => {
getRuntimeActionResultKey({
callId: "call_2",
kind: "subagent-result",
+ origin: "child",
output: "done",
subagentName: "reviewer",
}),
diff --git a/packages/eve/src/runtime/actions/results.ts b/packages/eve/src/runtime/actions/results.ts
new file mode 100644
index 000000000..79001fdeb
--- /dev/null
+++ b/packages/eve/src/runtime/actions/results.ts
@@ -0,0 +1,35 @@
+import { getRuntimeActionResultKey } from "#runtime/actions/keys.js";
+import type { RuntimeActionResult } from "#runtime/actions/types.js";
+
+/** Returns results in pending-key order once every requested action has completed. */
+export function resolveRuntimeActionResultsForKeys(input: {
+ readonly pendingKeys: readonly string[];
+ readonly results: readonly RuntimeActionResult[];
+}): RuntimeActionResult[] | undefined {
+ const pendingKeySet = new Set(input.pendingKeys);
+ const resultsByKey = new Map<string, RuntimeActionResult>();
+
+ for (const result of input.results) {
+ const key = getRuntimeActionResultKey(result);
+
+ if (!pendingKeySet.has(key)) {
+ continue;
+ }
+
+ resultsByKey.set(key, result);
+ }
+
+ const orderedResults: RuntimeActionResult[] = [];
+
+ for (const key of input.pendingKeys) {
+ const result = resultsByKey.get(key);
+
+ if (result === undefined) {
+ return undefined;
+ }
+
+ orderedResults.push(result);
+ }
+
+ return orderedResults;
+}
diff --git a/packages/eve/src/runtime/actions/types.ts b/packages/eve/src/runtime/actions/types.ts
index 0e17dd66c..bab7c1a21 100644
--- a/packages/eve/src/runtime/actions/types.ts
+++ b/packages/eve/src/runtime/actions/types.ts
@@ -126,29 +126,65 @@ const runtimeToolResultActionResultSchema = z
.strict();
/**
- * Runtime-owned subagent result projected back into a harness resume call.
+ * Subagent result produced by a dispatched child session and delivered back
+ * through the parent's resume hook.
*
- * `usage` carries the completed child session's token totals so the
- * caller can attribute the subagent's spend.
+ * Results bind to the pending call by callId alone: possession of the
+ * parent's callback token is the authorization to settle, so no further
+ * identity verification happens here. Under the accepted at-least-once
+ * 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.
*/
-export type RuntimeSubagentResultActionResult = z.infer<
- typeof runtimeSubagentResultActionResultSchema
->;
+export type RuntimeSubagentChildResult = z.infer<typeof runtimeSubagentChildResultSchema>;
/**
- * Zod schema for one runtime-owned subagent result action result.
+ * Zod schema for one child-produced subagent result.
*/
-const runtimeSubagentResultActionResultSchema = z
+const runtimeSubagentChildResultSchema = z
.object({
callId: z.string(),
isError: z.boolean().optional(),
kind: z.literal("subagent-result"),
+ origin: z.literal("child"),
output: jsonValueSchema,
subagentName: z.string(),
usage: tokenUsageSchema.optional(),
})
.strict();
+/**
+ * Subagent failure synthesized on the parent side when no child produced a
+ * result: dispatch rejections, start failures, and agentId-continuation
+ * delivery errors. Always an error. Enters the harness only through the
+ * trusted step-result path, never through the shared callback inbox.
+ */
+export type RuntimeSubagentDispatchFailure = z.infer<typeof runtimeSubagentDispatchFailureSchema>;
+
+/**
+ * Zod schema for one parent-synthesized subagent dispatch failure.
+ */
+const runtimeSubagentDispatchFailureSchema = z
+ .object({
+ callId: z.string(),
+ isError: z.literal(true),
+ kind: z.literal("subagent-result"),
+ origin: z.literal("dispatch"),
+ output: jsonValueSchema,
+ subagentName: z.string(),
+ })
+ .strict();
+
+/**
+ * Runtime-owned subagent result projected back into a harness resume call,
+ * discriminated on `origin`: `child` results come from a dispatched child
+ * session and must bind to a running agent handle; `dispatch` failures are
+ * parent-synthesized and trusted by construction.
+ */
+export type RuntimeSubagentResult = RuntimeSubagentChildResult | RuntimeSubagentDispatchFailure;
+
/**
* Runtime-owned action result produced by framework-owned loading code.
*/
@@ -175,5 +211,5 @@ const runtimeLoadSkillActionResultSchema = z
*/
export type RuntimeActionResult =
| RuntimeLoadSkillActionResult
- | RuntimeSubagentResultActionResult
+ | RuntimeSubagentResult
| RuntimeToolResultActionResult;
diff --git a/packages/eve/src/runtime/agent/mock-model-adapter.test.ts b/packages/eve/src/runtime/agent/mock-model-adapter.test.ts
index 62383a839..3e5127761 100644
--- a/packages/eve/src/runtime/agent/mock-model-adapter.test.ts
+++ b/packages/eve/src/runtime/agent/mock-model-adapter.test.ts
@@ -37,6 +37,42 @@ describe("createMockAuthoredRuntimeModel", () => {
expect(shouldMockAuthoredRuntimeModels()).toBe(true);
});
+ it("emits a message-only input for delegated agent calls", async () => {
+ const result = await generateWithPrompt(
+ [
+ {
+ content: "Delegate to a subagent: use the wait_for_cancel tool.",
+ role: "user",
+ },
+ ],
+ [
+ {
+ inputSchema: {
+ additionalProperties: false,
+ properties: {
+ message: { type: "string" },
+ },
+ required: ["message"],
+ type: "object",
+ },
+ name: "agent",
+ type: "function",
+ },
+ ],
+ );
+
+ expect(result.content).toEqual([
+ {
+ input: JSON.stringify({
+ message: "use the wait_for_cancel tool.",
+ }),
+ toolCallId: "call_agent",
+ toolName: "agent",
+ type: "tool-call",
+ },
+ ]);
+ });
+
it("activates a matching skill when the available skill line includes a skill path", async () => {
const result = await generateWithPrompt([
{
diff --git a/packages/eve/src/runtime/agent/mock-model-adapter.ts b/packages/eve/src/runtime/agent/mock-model-adapter.ts
index 4971dac74..58d1a8066 100644
--- a/packages/eve/src/runtime/agent/mock-model-adapter.ts
+++ b/packages/eve/src/runtime/agent/mock-model-adapter.ts
@@ -282,7 +282,8 @@ function createSubagentDelegationResult(
return null;
}
- const toolInput = { message: directive[1].trim() };
+ const message = directive[1].trim();
+ const toolInput = { message };
return createToolCallGenerateResult({
input: toolInput,
diff --git a/packages/eve/src/runtime/session-callback-route.test.ts b/packages/eve/src/runtime/session-callback-route.test.ts
index 8c4ac568e..211b795b8 100644
--- a/packages/eve/src/runtime/session-callback-route.test.ts
+++ b/packages/eve/src/runtime/session-callback-route.test.ts
@@ -60,6 +60,38 @@ describe("session callback route", () => {
{
callId: "call-1",
kind: "subagent-result",
+ origin: "child",
+ output: "done",
+ subagentName: "research",
+ },
+ ],
+ });
+ });
+
+ it("accepts a sessionId-less callback from an older eve deployment", async () => {
+ resumeHookMock.mockResolvedValue(undefined);
+
+ const response = await handleSessionCallbackRequest(
+ new Request("https://app.example.com/eve/v1/callback/tok123", {
+ body: JSON.stringify({
+ callId: "call-1",
+ kind: "session.completed",
+ output: "done",
+ subagentName: "research",
+ }),
+ method: "POST",
+ }),
+ createRouteContext({ token: "tok123" }),
+ );
+
+ expect(response.status).toBe(202);
+ expect(resumeHookMock).toHaveBeenCalledWith("tok123", {
+ kind: "runtime-action-result",
+ results: [
+ {
+ callId: "call-1",
+ kind: "subagent-result",
+ origin: "child",
output: "done",
subagentName: "research",
},
@@ -92,6 +124,7 @@ describe("session callback route", () => {
{
callId: "call-1",
kind: "subagent-result",
+ origin: "child",
output: "done",
subagentName: "research",
usage: { cacheReadTokens: 10, cacheWriteTokens: 5, inputTokens: 100, outputTokens: 50 },
@@ -166,12 +199,84 @@ describe("session callback route", () => {
{
callId: "call-1",
kind: "subagent-result",
+ origin: "child",
output: "done",
subagentName: "research",
},
],
});
});
+
+ it("projects a completed conversation turn like a completed task session", async () => {
+ resumeHookMock.mockResolvedValue(undefined);
+
+ 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(202);
+ expect(resumeHookMock).toHaveBeenCalledWith("tok123", {
+ kind: "runtime-action-result",
+ results: [
+ {
+ callId: "call-2",
+ kind: "subagent-result",
+ origin: "child",
+ output: "next result",
+ subagentName: "research",
+ },
+ ],
+ });
+ });
+
+ it("resumes a failed conversation turn as an error result", async () => {
+ resumeHookMock.mockResolvedValue(undefined);
+
+ 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",
+ },
+ kind: "turn.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-2",
+ isError: true,
+ kind: "subagent-result",
+ origin: "child",
+ output: {
+ code: "SUBAGENT_EXECUTION_FAILED",
+ message: "remote failed",
+ },
+ subagentName: "research",
+ },
+ ],
+ });
+ });
});
function createRouteContext(params: Record<string, string>): RouteContext {
diff --git a/packages/eve/src/runtime/session-callback-route.ts b/packages/eve/src/runtime/session-callback-route.ts
index 499c88445..13342fe0d 100644
--- a/packages/eve/src/runtime/session-callback-route.ts
+++ b/packages/eve/src/runtime/session-callback-route.ts
@@ -1,8 +1,9 @@
import { resumeHook } from "#internal/workflow/runtime.js";
+import { REMOTE_AGENT_FAILED } from "#harness/agent-handle-errors.js";
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 { RuntimeSubagentResultActionResult } from "#runtime/actions/types.js";
+import type { RuntimeSubagentChildResult } from "#runtime/actions/types.js";
import type { JsonValue } from "#shared/json.js";
import { tokenUsageSchema, type TokenUsage } from "#shared/token-usage.js";
@@ -10,20 +11,43 @@ export const HTTP_SESSION_CALLBACK_CHANNEL_NAME_PREFIX = "eve/v1/callback";
const HANDLED_METHODS: readonly ChannelMethod[] = ["POST"];
-type SessionTerminalCallbackPayload =
+/**
+ * Wire payload of the child→parent callback route. Possession of the
+ * callback token is the authorization to settle; results bind to the
+ * pending call by callId. `sessionId` is informational (tracing and
+ * diagnostics) and never verified — new senders emit it, older eve
+ * deployments may omit it.
+ */
+type SessionCallbackPayload =
| {
readonly callId: string;
readonly kind: "session.completed";
- readonly output: string;
- readonly sessionId: string;
+ readonly output: JsonValue;
+ readonly sessionId?: string;
readonly subagentName: string;
readonly usage?: TokenUsage;
}
| {
readonly callId: string;
- readonly error: JsonValue;
+ /** Absent on callbacks from older eve deployments. */
+ readonly error?: JsonValue;
readonly kind: "session.failed";
- readonly sessionId: string;
+ readonly sessionId?: string;
+ readonly subagentName: string;
+ }
+ | {
+ readonly callId: string;
+ readonly kind: "turn.completed";
+ readonly output: JsonValue;
+ readonly sessionId?: string;
+ readonly subagentName: string;
+ readonly usage?: TokenUsage;
+ }
+ | {
+ readonly callId: string;
+ readonly error: JsonValue;
+ readonly kind: "turn.failed";
+ readonly sessionId?: string;
readonly subagentName: string;
};
@@ -85,25 +109,23 @@ export async function handleSessionCallbackRequest(
return Response.json({ ok: true }, { status: 202 });
}
-function projectSessionCallbackResult(
- value: unknown,
-): RuntimeSubagentResultActionResult | Response {
+function projectSessionCallbackResult(value: unknown): RuntimeSubagentChildResult | Response {
if (value === null || typeof value !== "object") {
return Response.json({ error: "Expected a JSON object.", ok: false }, { status: 400 });
}
- const payload = value as Partial<SessionTerminalCallbackPayload>;
+ const payload = value as Partial<SessionCallbackPayload>;
if (typeof payload.callId !== "string" || payload.callId.length === 0) {
return Response.json({ error: "Missing callback callId.", ok: false }, { status: 400 });
}
if (typeof payload.subagentName !== "string" || payload.subagentName.length === 0) {
return Response.json({ error: "Missing callback subagentName.", ok: false }, { status: 400 });
}
-
- if (payload.kind === "session.completed") {
- const base: RuntimeSubagentResultActionResult = {
+ if (payload.kind === "session.completed" || payload.kind === "turn.completed") {
+ const base: RuntimeSubagentChildResult = {
callId: payload.callId,
kind: "subagent-result",
+ origin: "child",
output: payload.output ?? "",
subagentName: payload.subagentName,
};
@@ -116,10 +138,11 @@ function projectSessionCallbackResult(
callId: payload.callId,
isError: true,
kind: "subagent-result",
+ origin: "child",
output:
payload.error === undefined
? {
- code: "REMOTE_AGENT_FAILED",
+ code: REMOTE_AGENT_FAILED,
message: "Remote agent failed.",
}
: payload.error,
@@ -127,6 +150,20 @@ function projectSessionCallbackResult(
};
}
+ if (payload.kind === "turn.failed") {
+ if (payload.error === undefined) {
+ return Response.json({ error: "Missing callback error.", ok: false }, { status: 400 });
+ }
+ return {
+ callId: payload.callId,
+ isError: true,
+ kind: "subagent-result",
+ origin: "child",
+ output: payload.error,
+ subagentName: payload.subagentName,
+ };
+ }
+
return Response.json({ error: "Unsupported callback kind.", ok: false }, { status: 400 });
}
diff --git a/packages/eve/test/runtime-subagent-registry.test.ts b/packages/eve/test/runtime-subagent-registry.test.ts
index 9adb729ec..4bd6976ce 100644
--- a/packages/eve/test/runtime-subagent-registry.test.ts
+++ b/packages/eve/test/runtime-subagent-registry.test.ts
@@ -18,7 +18,7 @@ const SUBAGENT_TOOL_INPUT_SCHEMA = {
} as const;
describe("createRuntimeSubagentRegistry", () => {
- it("lowers local subagent inputs into serializable model-visible tools with a uniform message schema", () => {
+ it("lowers local subagent inputs into serializable model-visible tools with a uniform messaging schema", () => {
const registry = createRuntimeSubagentRegistry({
subagents: [
createResolvedRuntimeSubagentNode({
diff --git a/packages/eve/test/scenarios/remote-agent-principal-forwarding.scenario.test.ts b/packages/eve/test/scenarios/remote-agent-principal-forwarding.scenario.test.ts
index dc2d3f9bf..8d00b0b15 100644
--- a/packages/eve/test/scenarios/remote-agent-principal-forwarding.scenario.test.ts
+++ b/packages/eve/test/scenarios/remote-agent-principal-forwarding.scenario.test.ts
@@ -90,7 +90,7 @@ describe("remote agent auth forwarding", () => {
// Accepted: the trusted transport principal asserts a forwarded user.
// The receiver's onMessage (which throws on any other caller) proves
// the principal replacement happened.
- const childSessionId = await startRemoteAgentSession({
+ const child = await startRemoteAgentSession({
action: createAction(),
auth: FORWARDED_USER,
callbackBaseUrl: "https://caller.example.com",
@@ -98,7 +98,9 @@ describe("remote agent auth forwarding", () => {
remote: createRemote({ token: ROUTER_TOKEN, url: receiver.url }),
session: createParentSession(),
});
- expect(childSessionId.length).toBeGreaterThan(0);
+ expect(child.sessionId.length).toBeGreaterThan(0);
+ expect(child.continuationToken).toBeDefined();
+ expect(child.continuationToken?.length).toBeGreaterThan(0);
// Mismatch: an authenticated caller outside the forwarder allow-list
// fails loud at the hop instead of downgrading to service identity.