Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat(eve): agent-messaging model surface, docs, and evals (#1331)

Ruie5c91918ed89
diff --git a/.changeset/agent-messaging-part-one.md b/.changeset/agent-messaging-part-one.md
new file mode 100644
index 000000000..085e67624
--- /dev/null
+++ b/.changeset/agent-messaging-part-one.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Add experimental agent messaging behind `experimental.subagentPersistentSessions` in `agent.ts`. Opted-in agents keep delegated children alive after they answer: each child is owned by a lifecycle handle, settles every turn with an explicit outcome carrying its per-turn token usage, and parks instead of terminating. The parent's subagent tools gain an `agentId` parameter to continue a parked child, discoverable from a per-model-call `<agents>` system injection that lists only parked (resumable) children. An omitted, empty, or unknown `agentId` starts a fresh child; continuing a child that is still starting or working fails with `AGENT_BUSY`. Without the opt-in, children keep running as one-shot tasks. The subagent tool input schema no longer includes the unused `description` field.
diff --git a/docs/subagents.mdx b/docs/subagents.mdx
index e5bcf12b0..4dfbccb78 100644
--- a/docs/subagents.mdx
+++ b/docs/subagents.mdx
@@ -12,10 +12,13 @@ The root session receives `agent` by default. The model calls it to delegate a t
```ts
{
message: string; // everything the child needs; it does not see the parent's history
+ agentId?: string; // only with experimental.subagentPersistentSessions: continue an existing child
outputSchema?: object; // when set, the child runs in task mode and returns structured output
}
```
+The `agentId` field exists only when the agent opts into [agent messaging](#agent-messaging); without the opt-in the schema is `{ message, outputSchema? }`.
+
The copy uses the root's instructions, connections, auth, and sandbox. It receives the same tools except for the root-only `agent` and `Workflow`, and starts with fresh conversation history and fresh state. Its file writes are immediately visible to the root. To run independent tasks in parallel, emit multiple `agent` calls in one response; eve runs the batch concurrently and returns every result before the root continues. Give parallel children non-overlapping write scopes.
`agent` is intentionally root-only. Copies created by it cannot call `agent`, and declared subagents never receive the built-in tool. If a stale or forced recursive call reaches execution, eve rejects it instead of starting another child session.
@@ -144,7 +147,7 @@ The root built-in `agent` tool is the exception. Its children share the root's s
## What the parent sees
-eve lowers every subagent visible to the current agent (the root built-in copy, declared, or [remote](./guides/remote-agents)) into a model-visible tool with the same `{ message, outputSchema? }` shape. The parent packs `message` with everything the child needs, since the child never sees the parent's history. Set `outputSchema` to run the child in task mode, returning structured output as the tool result.
+eve lowers every subagent visible to the current agent (the root built-in copy, declared, or [remote](./guides/remote-agents)) into a model-visible tool with the same `{ message, outputSchema? }` shape — plus `agentId` when the agent opts into [agent messaging](#agent-messaging). The parent packs `message` with everything the child needs, since the child never sees the parent's history. Set `outputSchema` to run the child in task mode, returning structured output as the tool result; this works the same with or without agent messaging.
Declared subagents can call nested subagents defined under their own directories. eve does not apply a separate depth limit; nesting ends where the authored directory tree ends. The built-in `agent` follows the stricter root-only rule above, so `limits.maxSubagentDepth` no longer exists.
@@ -155,6 +158,7 @@ A declared subagent's tool name is the bare path-derived name, with no prefix. `
```ts
{
message: string; // all context the child needs; it never sees the parent's history
+ agentId?: string; // only with experimental.subagentPersistentSessions: continue an existing child
outputSchema?: object; // when set, the child runs in task mode and returns structured output
}
```
@@ -169,6 +173,29 @@ Cancelling a parent turn also requests cancellation of every active child it sta
Subagent model calls automatically retry classified transient provider failures, including overload errors delivered after a stream starts. eve makes at most three fresh model-call attempts, repeating only the current uncommitted call so completed earlier steps, tool results, and sandbox work remain available to the child. Other recoverable task errors fall back to Workflow's durable step retry from the last committed session snapshot. Exhausting the transient model-call attempts or the dedicated empty-response reissue returns one failed task result instead of stacking both retry budgets; terminal errors fail immediately.
+## Agent messaging
+
+Agent messaging is experimental and off by default. Opt in per agent in `agent.ts`:
+
+```ts title="agent/agent.ts"
+import { defineAgent } from "eve";
+
+export default defineAgent({
+ experimental: {
+ subagentPersistentSessions: true,
+ },
+ model: "anthropic/claude-sonnet-4.5",
+});
+```
+
+Without the opt-in, delegated children run as one-shot tasks: they answer once and terminate, and the subagent tool schema carries no `agentId` field.
+
+With it enabled, a child parks after answering instead of terminating, keeping its session and conversation history alive. A failed child turn can also leave the child parked — its latest status shows the error and the parent may message it again. Pass a parked child's `agentId` to the same subagent tool with a new `message` to continue that session. Omitting `agentId` (or passing an empty string or `null`) always starts a new child, and an `agentId` that matches no known agent falls back to starting a new child rather than failing. Passing a known `agentId` through a different subagent tool fails with `AGENT_MISMATCH`, and messaging a child that is still starting or working on its previous request fails with `AGENT_BUSY` — wait for its result before continuing it.
+
+On every model call, eve injects a system message containing an `<agents>` block listing the currently parked (resumable) children — each entry carries the `agentId`, name, and latest status. It is a per-call injection, not part of the conversation history: it always reflects the current state, never accumulates stale copies, and children that are starting or running do not appear until they park again.
+
+The parent holds agent handles only for its session lifetime. When the parent session ends, eve terminates its local children. Remote children are not terminated on parent shutdown — that is a known gap: a parked remote child stays alive on its own deployment until that deployment's own lifecycle ends it. For [remote agents](./guides/remote-agents), both deployments must run the same eve version to use agent messaging.
+
## When to split
Split out a subagent when the task needs a different prompt or specialist role, a narrower tool surface, or its own runtime context. Don't reach for one when a [skill](./skills) would do. If the agent can keep its identity and needs only an optional procedure, a skill is the lighter choice.
diff --git a/e2e/fixtures/agent-cancellation/evals/cancellation/cancel-turn.eval.ts b/e2e/fixtures/agent-cancellation/evals/cancellation/cancel-turn.eval.ts
index cc9ba6701..e35c42def 100644
--- a/e2e/fixtures/agent-cancellation/evals/cancellation/cancel-turn.eval.ts
+++ b/e2e/fixtures/agent-cancellation/evals/cancellation/cancel-turn.eval.ts
@@ -9,8 +9,7 @@ const TOOL_NAME = "wait-for-cancellation";
* Flow: start a turn that hangs mid-tool, request cooperative cancellation,
* and assert the turn settles as `turn.cancelled` followed by
* `session.waiting` with zero failure events. Then prove the session accepts a
- * follow-up normally and a late duplicate cancel reports the benign
- * `no_active_turn` outcome.
+ * follow-up normally and a late duplicate cancel is a benign no-op.
*/
export default defineEval({
tags: ["real-model"],
@@ -51,17 +50,12 @@ export default defineEval({
followUp.notEvent("session.failed");
followUp.messageIncludes(/CANCELLATION-FOLLOW-UP-OK/i);
- let lateStatus: "accepted" | "no_active_turn" | undefined;
- for (let attempt = 0; attempt < 30; attempt += 1) {
- lateStatus = (await t.cancel()).status;
- if (lateStatus === "no_active_turn") break;
- await t.sleep(500);
- }
+ const lateStatus = (await t.cancel()).status;
await t.require(
lateStatus,
satisfies(
- (value: typeof lateStatus) => value === "no_active_turn",
- "a late cancel reports no_active_turn",
+ (value: typeof lateStatus) => value === "accepted" || value === "no_active_turn",
+ "a late cancel is accepted as a no-op or reports no_active_turn",
),
);
diff --git a/e2e/fixtures/agent-subagents/agent/agent.ts b/e2e/fixtures/agent-subagents/agent/agent.ts
index c56a3896d..9d0d1ecfe 100644
--- a/e2e/fixtures/agent-subagents/agent/agent.ts
+++ b/e2e/fixtures/agent-subagents/agent/agent.ts
@@ -5,7 +5,17 @@ if (process.env.EVE_E2E_MODEL === "mock") {
process.env.EVE_MOCK_AUTHORED_MODELS = "1";
}
+const base = e2eAgentConfig();
+
export default defineAgent({
- ...e2eAgentConfig(),
+ ...base,
+ // Merge, don't replace: `e2eAgentConfig()` selects the workflow world
+ // under `experimental.workflow`, and dropping it silently falls back to
+ // the local world on the Postgres/Vercel suites (their durability check
+ // then fails with zero workflow runs).
+ experimental: {
+ ...base.experimental,
+ subagentPersistentSessions: true,
+ },
reasoning: "high",
});
diff --git a/e2e/fixtures/agent-subagents/agent/subagents/remote-loopback.ts b/e2e/fixtures/agent-subagents/agent/subagents/remote-loopback.ts
index e5c4f0af3..2753eb820 100644
--- a/e2e/fixtures/agent-subagents/agent/subagents/remote-loopback.ts
+++ b/e2e/fixtures/agent-subagents/agent/subagents/remote-loopback.ts
@@ -15,7 +15,7 @@ export default defineDynamic({
"session.started": () =>
defineRemoteAgent({
description:
- "Remote loopback agent. Call this only when the user explicitly asks to use the remote-loopback agent, passing the user's requested message through unchanged. Call it with only the `message` argument — never pass `outputSchema`.",
+ "Remote loopback agent. Call this only when the user explicitly asks to use the remote-loopback agent, passing the user's requested message through unchanged. Never pass `outputSchema`.",
url: () =>
process.env.VERCEL_URL !== undefined && process.env.VERCEL_URL !== ""
? `https://${process.env.VERCEL_URL}`
diff --git a/e2e/fixtures/agent-subagents/evals/agent-messaging-local.eval.ts b/e2e/fixtures/agent-subagents/evals/agent-messaging-local.eval.ts
new file mode 100644
index 000000000..9dd0e5c0d
--- /dev/null
+++ b/e2e/fixtures/agent-subagents/evals/agent-messaging-local.eval.ts
@@ -0,0 +1,51 @@
+import { defineEval } from "eve/evals";
+
+const MEMORABLE_FACT = "The observatory locker code is ORBIT-CEDAR-7319.";
+
+/**
+ * Cross-turn continuation of a local child: turn one delegates a fact to the
+ * built-in agent subagent and lets it park; turn two re-messages the same
+ * child via its agentId. The fact can only come back if the child's session
+ * survived the parent turn boundary.
+ */
+export default defineEval({
+ description:
+ "A parked local child re-messaged in a later parent turn still recalls a fact from its first turn.",
+ tags: ["real-model"],
+ async test(t) {
+ await t.send(
+ [
+ "Call the built-in agent subagent exactly once with this message:",
+ `"Remember this exact fact: ${MEMORABLE_FACT} Reply only with READY."`,
+ "When it returns, reply with the single word: delegated.",
+ ].join(" "),
+ );
+
+ await t.send(
+ [
+ "Message that same agent again: call the agent subagent with the agentId shown in the latest <agents> block",
+ 'and the message: "What exact fact did I ask you to remember? Reply with only the fact."',
+ "Do not state the fact yourself.",
+ "When it returns, reply with the agent's exact output and no other text.",
+ ].join(" "),
+ );
+
+ t.succeeded();
+ t.calledSubagent("agent", { count: 2 });
+ t.calledSubagent("agent", { output: new RegExp(MEMORABLE_FACT), count: 1 });
+ t.eventsSatisfy("both turns continue one child session", (events) => {
+ const childSessionIds = events.flatMap((event) =>
+ event.type === "subagent.called" && event.data.name === "agent"
+ ? [event.data.childSessionId]
+ : [],
+ );
+ return (
+ childSessionIds.length === 2 &&
+ childSessionIds[0] !== undefined &&
+ childSessionIds[0] === childSessionIds[1]
+ );
+ });
+ t.messageIncludes(MEMORABLE_FACT);
+ t.noFailedActions();
+ },
+});
diff --git a/e2e/fixtures/agent-subagents/evals/agent-messaging-remote.eval.ts b/e2e/fixtures/agent-subagents/evals/agent-messaging-remote.eval.ts
new file mode 100644
index 000000000..3c50a3372
--- /dev/null
+++ b/e2e/fixtures/agent-subagents/evals/agent-messaging-remote.eval.ts
@@ -0,0 +1,51 @@
+import { defineEval } from "eve/evals";
+
+const MEMORABLE_FACT = "The tide station passphrase is HARBOR-LUMEN-4482.";
+
+/**
+ * Cross-turn continuation of a remote child over a real HTTP hop: turn one
+ * delegates a fact to `remote-loopback` and lets it park; turn two
+ * re-messages the same remote child via its agentId. The fact can only come
+ * back if the continuation reached the same remote session.
+ */
+export default defineEval({
+ description:
+ "A parked remote child re-messaged in a later parent turn still recalls a fact from its first turn.",
+ tags: ["real-model"],
+ async test(t) {
+ await t.send(
+ [
+ "Use the remote-loopback agent exactly once with this message (no outputSchema):",
+ `"Remember this exact fact: ${MEMORABLE_FACT} Reply only with READY."`,
+ "When it returns, reply with the single word: delegated.",
+ ].join(" "),
+ );
+
+ await t.send(
+ [
+ "Message that same remote-loopback agent again: call it with the agentId shown in the latest <agents> block",
+ 'and the message: "What exact fact did I ask you to remember? Reply with only the fact."',
+ "Do not state the fact yourself.",
+ "When it returns, reply with the agent's exact output and no other text.",
+ ].join(" "),
+ );
+
+ t.succeeded();
+ t.calledSubagent("remote-loopback", { count: 2 });
+ t.calledSubagent("remote-loopback", { output: new RegExp(MEMORABLE_FACT), count: 1 });
+ t.eventsSatisfy("both turns continue one remote child session", (events) => {
+ const childSessionIds = events.flatMap((event) =>
+ event.type === "subagent.called" && event.data.name === "remote-loopback"
+ ? [event.data.childSessionId]
+ : [],
+ );
+ return (
+ childSessionIds.length === 2 &&
+ childSessionIds[0] !== undefined &&
+ childSessionIds[0] === childSessionIds[1]
+ );
+ });
+ t.messageIncludes(MEMORABLE_FACT);
+ t.noFailedActions();
+ },
+});
diff --git a/packages/eve/src/context/dynamic-subagent-lifecycle.test.ts b/packages/eve/src/context/dynamic-subagent-lifecycle.test.ts
index 5cf083991..d7cbea2ff 100644
--- a/packages/eve/src/context/dynamic-subagent-lifecycle.test.ts
+++ b/packages/eve/src/context/dynamic-subagent-lifecycle.test.ts
@@ -22,6 +22,7 @@ describe("dynamic subagent lifecycle", () => {
ctx,
event: createSessionStartedEvent(),
messages: [],
+ persistentSessions: false,
resolvers: [resolver],
});
@@ -41,6 +42,7 @@ describe("dynamic subagent lifecycle", () => {
ctx,
event: createSessionStartedEvent(),
messages: [],
+ persistentSessions: false,
resolvers: [resolver],
});
@@ -75,6 +77,7 @@ describe("dynamic subagent lifecycle", () => {
ctx,
event: createSessionStartedEvent(),
messages: [],
+ persistentSessions: false,
resolvers: [resolver],
});
expect(buildDynamicSubagentTools(ctx)).toHaveLength(1);
@@ -83,6 +86,7 @@ describe("dynamic subagent lifecycle", () => {
ctx,
event: createTurnStartedEvent({ sequence: 0, turnId: "turn-1" }),
messages: [],
+ persistentSessions: false,
resolvers: [resolver],
});
expect(buildDynamicSubagentTools(ctx)).toEqual([]);
@@ -114,6 +118,7 @@ describe("dynamic subagent lifecycle", () => {
ctx,
event: createSessionStartedEvent(),
messages: [],
+ persistentSessions: false,
resolvers: [resolver],
});
const sessionSelection = getDynamicSubagentSelection(ctx, resolver.nodeId);
@@ -126,6 +131,7 @@ describe("dynamic subagent lifecycle", () => {
ctx,
event: createTurnStartedEvent({ sequence: 0, turnId: "turn-1" }),
messages: [],
+ persistentSessions: false,
resolvers: [resolver],
});
const turnSelection = getDynamicSubagentSelection(ctx, resolver.nodeId);
@@ -167,6 +173,7 @@ describe("dynamic subagent lifecycle", () => {
ctx,
event: createSessionStartedEvent(),
messages: [],
+ persistentSessions: true,
resolvers: [resolver],
});
@@ -183,6 +190,11 @@ describe("dynamic subagent lifecycle", () => {
]);
expect(getDynamicSubagentSelection(ctx, resolver.nodeId)).toMatchObject({
kind: "remote",
+ prepared: {
+ inputSchema: {
+ properties: { agentId: expect.any(Object) },
+ },
+ },
remoteAgent: {
credentialsStepId: "eve:dynamic-remote-agent//researcher",
forwardPrincipal: true,
@@ -207,6 +219,7 @@ describe("dynamic subagent lifecycle", () => {
ctx,
event: createSessionStartedEvent(),
messages: [],
+ persistentSessions: false,
resolvers: [resolver],
});
@@ -226,6 +239,7 @@ describe("dynamic subagent lifecycle", () => {
ctx,
event: createSessionStartedEvent(),
messages: [],
+ persistentSessions: false,
resolvers: [resolver],
runtimeRevision: "deployment:one",
});
@@ -233,6 +247,7 @@ describe("dynamic subagent lifecycle", () => {
ctx,
event: createSessionStartedEvent(),
messages: [],
+ persistentSessions: false,
resolvers: [resolver],
runtimeRevision: "deployment:one",
});
diff --git a/packages/eve/src/context/dynamic-subagent-lifecycle.ts b/packages/eve/src/context/dynamic-subagent-lifecycle.ts
index 9dd8767c1..d9e834f77 100644
--- a/packages/eve/src/context/dynamic-subagent-lifecycle.ts
+++ b/packages/eve/src/context/dynamic-subagent-lifecycle.ts
@@ -14,7 +14,10 @@ import type { HarnessToolDefinition } from "#harness/execute-tool.js";
import { createLogger } from "#internal/logging.js";
import type { SessionStartedStreamEvent, UnstampedMessageStreamEvent } from "#protocol/message.js";
import type { ResolvedDynamicSubagentResolver } from "#runtime/subagents/registry.js";
-import { createPreparedRuntimeSubagentTool } from "#runtime/subagents/registry.js";
+import {
+ createPreparedRuntimeSubagentTool,
+ getSubagentToolInputJsonSchema,
+} from "#runtime/subagents/registry.js";
import { normalizeDynamicSubagentAgentConfig } from "#runtime/subagents/dynamic-agent-config.js";
import { normalizeDynamicRemoteAgentConfig } from "#runtime/subagents/dynamic-remote-agent-config.js";
import { toErrorMessage } from "#shared/errors.js";
@@ -28,8 +31,10 @@ async function resolveSelections(input: {
readonly ctx: ContextContainer;
readonly event: UnstampedMessageStreamEvent;
readonly messages: readonly ModelMessage[];
+ readonly persistentSessions: boolean;
readonly resolvers: readonly ResolvedDynamicSubagentResolver[];
}): Promise<DynamicSubagentSelections> {
+ const inputSchema = getSubagentToolInputJsonSchema(input.persistentSessions);
const outcomes = await Promise.allSettled(
input.resolvers.map(async (resolver) => {
const handler = resolver.events[input.event.type];
@@ -46,18 +51,21 @@ async function resolveSelections(input: {
name: resolver.name,
value: result,
});
- const prepared = createPreparedRuntimeSubagentTool({
- description: remoteAgent.description,
- kind: "remote",
- logicalPath: resolver.logicalPath,
- name: resolver.name,
- nodeId: resolver.nodeId,
- outputSchema: remoteAgent.outputSchema,
- path: remoteAgent.path,
- sourceId: resolver.sourceId,
- sourceKind: resolver.sourceKind,
- url: remoteAgent.url,
- });
+ const prepared = createPreparedRuntimeSubagentTool(
+ {
+ description: remoteAgent.description,
+ kind: "remote",
+ logicalPath: resolver.logicalPath,
+ name: resolver.name,
+ nodeId: resolver.nodeId,
+ outputSchema: remoteAgent.outputSchema,
+ path: remoteAgent.path,
+ sourceId: resolver.sourceId,
+ sourceKind: resolver.sourceKind,
+ url: remoteAgent.url,
+ },
+ inputSchema,
+ );
return [resolver.nodeId, { kind: "remote", prepared, remoteAgent }] as const;
}
@@ -66,15 +74,18 @@ async function resolveSelections(input: {
name: resolver.name,
value: result,
});
- const prepared = createPreparedRuntimeSubagentTool({
- description: agentConfig.description,
- kind: "subagent",
- logicalPath: resolver.logicalPath,
- name: resolver.name,
- nodeId: resolver.nodeId,
- sourceId: resolver.sourceId,
- sourceKind: resolver.sourceKind,
- });
+ const prepared = createPreparedRuntimeSubagentTool(
+ {
+ description: agentConfig.description,
+ kind: "subagent",
+ logicalPath: resolver.logicalPath,
+ name: resolver.name,
+ nodeId: resolver.nodeId,
+ sourceId: resolver.sourceId,
+ sourceKind: resolver.sourceKind,
+ },
+ inputSchema,
+ );
return [resolver.nodeId, { agentConfig, kind: "subagent", prepared }] as const;
}),
@@ -110,6 +121,7 @@ export async function dispatchDynamicSubagentEvent(input: {
readonly ctx: ContextContainer;
readonly event: UnstampedMessageStreamEvent;
readonly messages: readonly ModelMessage[];
+ readonly persistentSessions: boolean;
readonly resolvers: readonly ResolvedDynamicSubagentResolver[];
}): Promise<void> {
if (!ALLOWED_DYNAMIC_SUBAGENT_EVENTS.has(input.event.type)) {
@@ -132,6 +144,7 @@ export async function refreshDynamicSessionSubagentsForRuntimeRevision(input: {
readonly ctx: ContextContainer;
readonly event: SessionStartedStreamEvent;
readonly messages: readonly ModelMessage[];
+ readonly persistentSessions: boolean;
readonly resolvers: readonly ResolvedDynamicSubagentResolver[];
readonly runtimeRevision: string;
}): Promise<void> {
diff --git a/packages/eve/src/execution/agent-handle-dispatch.ts b/packages/eve/src/execution/agent-handle-dispatch.ts
index 046a8e528..3792dffc8 100644
--- a/packages/eve/src/execution/agent-handle-dispatch.ts
+++ b/packages/eve/src/execution/agent-handle-dispatch.ts
@@ -8,12 +8,7 @@
* dead (handle deleted) or retryable (handle restored to `parked`).
*/
-import {
- AGENT_BUSY,
- AGENT_MISMATCH,
- AGENT_UNKNOWN,
- AGENT_UNREACHABLE,
-} from "#harness/agent-handle-errors.js";
+import { AGENT_BUSY, AGENT_MISMATCH, AGENT_UNREACHABLE } from "#harness/agent-handle-errors.js";
import { deriveAgentOperationId } from "#harness/handles/operation-id.js";
import type { AgentAddress, AgentHandle, ContinueOperation } from "#harness/handles/store.js";
import { prepareAgentContinuation, rejectAgentEffect } from "#harness/handles/transitions.js";
@@ -83,7 +78,9 @@ export type DispatchOutcome =
/**
* Delivers one `agentId` continuation to the child the handle names.
*
- * Unknown ids, name mismatches, and busy handles report `AGENT_UNKNOWN` /
+ * Planning converts initially unknown ids into fresh starts, so an id that
+ * matches no handle here disappeared mid-batch and reports
+ * `AGENT_UNREACHABLE`. Name mismatches and busy handles report
* `AGENT_MISMATCH` / `AGENT_BUSY` without touching the store. Delivery
* failures report `AGENT_UNREACHABLE`: permanent ones resolve the handle as
* dead, transient ones restore it to `parked` so the model can retry the
@@ -123,12 +120,14 @@ export async function dispatchToAgentHandle(input: {
switch (prepared.kind) {
case "unknown":
+ // Planning resolved this id against the store, so the handle was
+ // deleted by an earlier action in this batch; no retry can reach it.
return {
kind: "error",
result: createAgentErrorResult({
action,
- code: AGENT_UNKNOWN,
- message: `No agent from the <agents> list found for id "${agentId}".`,
+ code: AGENT_UNREACHABLE,
+ message: `Agent with id "${agentId}" is no longer reachable.`,
}),
session: input.currentSession,
};
diff --git a/packages/eve/src/execution/agent-messaging.scenario.test.ts b/packages/eve/src/execution/agent-messaging.scenario.test.ts
new file mode 100644
index 000000000..1ef9dd787
--- /dev/null
+++ b/packages/eve/src/execution/agent-messaging.scenario.test.ts
@@ -0,0 +1,486 @@
+import { spawn, type ChildProcessByStdio } from "node:child_process";
+import { readFile } from "node:fs/promises";
+import { join } from "node:path";
+import type { Readable } from "node:stream";
+
+import { describe, expect, it } from "vitest";
+
+import { Client } from "#client/client.js";
+import { filterEventsByType } from "#internal/testing/events.js";
+import { type ScenarioAppDescriptor, useScenarioApp } from "#internal/testing/scenario-app.js";
+import { EVE_SESSION_ID_HEADER, type HandleMessageStreamEvent } from "#protocol/message.js";
+
+const scenarioApp = useScenarioApp();
+const SCENARIO_TIMEOUT_MS = 360_000;
+const EVENT_TIMEOUT_MS = 30_000;
+const CODEWORD = "LANTERN-COMET-7319";
+const PARENT_RESULT = `PARENT_RECALLED=${CODEWORD}`;
+
+function createScriptedParentAgentSource(subagentName: string): string {
+ const agentIdPattern = `<agent id="([^"]+)" name="${subagentName}">`;
+
+ return `import { defineAgent } from "eve";
+import { mockModel } from "eve/evals";
+
+const CODEWORD = ${JSON.stringify(CODEWORD)};
+const SUBAGENT_NAME = ${JSON.stringify(subagentName)};
+const AGENT_ID_PATTERN = new RegExp(${JSON.stringify(agentIdPattern)}, "u");
+
+const model = mockModel((request) => {
+ const childResults = request.toolResults.filter((result) => result.name === SUBAGENT_NAME);
+
+ if (childResults.length === 0) {
+ return {
+ toolCalls: [
+ {
+ id: "memory-exchange-1",
+ input: {
+ message: \`Remember the codeword \${CODEWORD}. Confirm that you stored it.\`,
+ },
+ name: SUBAGENT_NAME,
+ },
+ ],
+ };
+ }
+
+ if (childResults.length === 1) {
+ // The agents listing rides the conversation as an assistant announcement
+ // (not the system prompt), so scan every message for the latest listing.
+ const agentsSnippet = request.messages.map((message) => message.text).join("\\n");
+ const agentId = AGENT_ID_PATTERN.exec(agentsSnippet)?.[1];
+ if (agentId === undefined) {
+ throw new Error(\`Parent model did not receive a \${SUBAGENT_NAME} agent id.\`);
+ }
+
+ return {
+ toolCalls: [
+ {
+ id: "memory-exchange-2",
+ input: {
+ agentId,
+ message: "What codeword did I ask you to remember? Reply with the codeword.",
+ },
+ name: SUBAGENT_NAME,
+ },
+ ],
+ };
+ }
+
+ if (childResults.length === 2) {
+ const recalled = childResults[1]?.output;
+ if (typeof recalled !== "string") {
+ throw new Error("Second child result was not text.");
+ }
+ return \`PARENT_RECALLED=\${recalled}\`;
+ }
+
+ throw new Error("Parent model received an unexpected number of child results.");
+});
+
+export default defineAgent({
+ experimental: {
+ subagentPersistentSessions: true,
+ },
+ model,
+ modelContextWindowTokens: 32_000,
+});
+`;
+}
+
+const EVE_CHANNEL_SOURCE = `import { none } from "eve/channels/auth";
+import { eveChannel } from "eve/channels/eve";
+
+export default eveChannel({ auth: none() });
+`;
+
+const MEMORY_AGENT_SOURCE = `import { defineAgent } from "eve";
+import { mockModel } from "eve/evals";
+
+const CODEWORD = ${JSON.stringify(CODEWORD)};
+
+const model = mockModel((request) => {
+ if (request.userMessageCount === 1) {
+ return request.lastUserMessage?.includes(CODEWORD) === true
+ ? \`STORED=\${CODEWORD}\`
+ : "FIRST_EXCHANGE_MISSING_CODEWORD";
+ }
+
+ if (request.userMessageCount === 2) {
+ const retainedFirstExchange = request.userMessages[0]?.includes(CODEWORD) === true;
+ const asksForCodeword = request.lastUserMessage?.includes("What codeword") === true;
+ return retainedFirstExchange && asksForCodeword ? CODEWORD : "CONTEXT_LOST";
+ }
+
+ throw new Error("Child model received an unexpected conversation length.");
+});
+
+export default defineAgent({
+ description: "Remember a fact and recall it in a later agent exchange.",
+ model,
+ modelContextWindowTokens: 32_000,
+});
+`;
+
+const AGENT_MESSAGING_DESCRIPTOR: ScenarioAppDescriptor = {
+ files: {
+ "agent/agent.ts": createScriptedParentAgentSource("memory-child"),
+ "agent/channels/eve.ts": EVE_CHANNEL_SOURCE,
+ "agent/instructions.md": "Run the scripted memory-child exchanges.\n",
+ "agent/subagents/memory-child/agent.ts": MEMORY_AGENT_SOURCE,
+ "agent/subagents/memory-child/instructions.md":
+ "Remember facts from earlier turns and answer follow-up questions from that history.\n",
+ },
+ installDependencies: true,
+ name: "agent-messaging",
+};
+
+const REMOTE_MEMORY_AGENT_DESCRIPTOR: ScenarioAppDescriptor = {
+ files: {
+ "agent/agent.ts": MEMORY_AGENT_SOURCE,
+ "agent/channels/eve.ts": EVE_CHANNEL_SOURCE,
+ "agent/instructions.md":
+ "Remember facts from earlier turns and answer follow-up questions from that history.\n",
+ },
+ installDependencies: true,
+ name: "remote-memory-agent",
+};
+
+function createRemoteAgentMessagingDescriptor(remoteUrl: string): ScenarioAppDescriptor {
+ return {
+ files: {
+ "agent/agent.ts": createScriptedParentAgentSource("remote-memory-child"),
+ "agent/channels/eve.ts": EVE_CHANNEL_SOURCE,
+ "agent/instructions.md": "Run the scripted remote-memory-child exchanges.\n",
+ "agent/subagents/remote-memory-child.ts": `import { defineRemoteAgent } from "eve";
+
+export default defineRemoteAgent({
+ description: "Remember a fact and recall it in a later agent exchange.",
+ url: ${JSON.stringify(remoteUrl)},
+});
+`,
+ },
+ installDependencies: true,
+ name: "remote-agent-messaging",
+ };
+}
+
+describe("agent messaging", () => {
+ it(
+ "continues one parked child with its retained conversation and terminates it with the parent",
+ async () => {
+ const app = await scenarioApp(AGENT_MESSAGING_DESCRIPTOR);
+ const server = await startScriptedEveDev(app.appRoot);
+
+ try {
+ const childSessionId = await runScriptedParentSession({
+ serverUrl: server.url,
+ subagentName: "memory-child",
+ });
+ await expectRetainedChildConversation({
+ childSessionId,
+ client: new Client({ host: server.url }),
+ });
+ expect(await readWorkflowRunStatus(app.appRoot, childSessionId)).toBe("cancelled");
+ } catch (error) {
+ throw new Error(
+ [`stdout:\n${server.stdout()}`, `stderr:\n${server.stderr()}`].join("\n\n"),
+ { cause: error },
+ );
+ } finally {
+ await server.stop();
+ }
+ },
+ SCENARIO_TIMEOUT_MS,
+ );
+
+ it(
+ "continues one parked remote agent with its retained conversation",
+ async () => {
+ const remoteApp = await scenarioApp(REMOTE_MEMORY_AGENT_DESCRIPTOR);
+ const remoteServer = await startScriptedEveDev(remoteApp.appRoot);
+
+ try {
+ const parentApp = await scenarioApp(createRemoteAgentMessagingDescriptor(remoteServer.url));
+ const parentServer = await startScriptedEveDev(parentApp.appRoot);
+
+ try {
+ const childSessionId = await runScriptedParentSession({
+ expectedRemoteUrl: remoteServer.url,
+ serverUrl: parentServer.url,
+ subagentName: "remote-memory-child",
+ });
+ await expectRetainedChildConversation({
+ childSessionId,
+ client: new Client({ host: remoteServer.url }),
+ });
+ } catch (error) {
+ throw new Error(
+ [
+ `parent stdout:\n${parentServer.stdout()}`,
+ `parent stderr:\n${parentServer.stderr()}`,
+ `remote stdout:\n${remoteServer.stdout()}`,
+ `remote stderr:\n${remoteServer.stderr()}`,
+ ].join("\n\n"),
+ { cause: error },
+ );
+ } finally {
+ await parentServer.stop();
+ }
+ } finally {
+ await remoteServer.stop();
+ }
+ },
+ SCENARIO_TIMEOUT_MS,
+ );
+});
+
+async function runScriptedParentSession(input: {
+ readonly expectedRemoteUrl?: string;
+ readonly serverUrl: string;
+ readonly subagentName: string;
+}): Promise<string> {
+ const createResponse = await fetch(new URL("eve/v1/session", input.serverUrl), {
+ body: JSON.stringify({
+ message: `Run both scripted ${input.subagentName} exchanges.`,
+ mode: "task",
+ }),
+ headers: { "content-type": "application/json" },
+ method: "POST",
+ });
+ expect(createResponse.status).toBe(202);
+
+ const parentSessionId = createResponse.headers.get(EVE_SESSION_ID_HEADER);
+ if (parentSessionId === null) {
+ throw new Error("Parent session response did not include a session id.");
+ }
+
+ const client = new Client({ host: input.serverUrl });
+ const parentEvents = await collectStreamToEnd({
+ label: "parent task completion",
+ stream: client.session({ sessionId: parentSessionId, streamIndex: 0 }).stream(),
+ });
+ const calls = filterEventsByType(parentEvents, "subagent.called");
+
+ if (calls.length !== 2) {
+ throw new Error(`Expected two subagent calls. Parent events: ${JSON.stringify(parentEvents)}`);
+ }
+ expect(calls.map((call) => call.data.name)).toEqual([input.subagentName, input.subagentName]);
+ expect(calls[0]?.data.childSessionId).toBeDefined();
+ expect(calls[1]?.data.childSessionId).toBe(calls[0]?.data.childSessionId);
+ if (input.expectedRemoteUrl === undefined) {
+ expect(calls.every((call) => call.data.remote === undefined)).toBe(true);
+ } else {
+ expect(calls.map((call) => call.data.remote?.url)).toEqual([
+ input.expectedRemoteUrl,
+ input.expectedRemoteUrl,
+ ]);
+ }
+ expect(parentEvents.at(-1)?.type).toBe("session.completed");
+ expect(
+ filterEventsByType(parentEvents, "message.completed").some(
+ (event) => event.data.message === PARENT_RESULT,
+ ),
+ ).toBe(true);
+
+ const childSessionId = calls[0]?.data.childSessionId;
+ if (childSessionId === undefined) {
+ throw new Error("First subagent.called event did not include a child session id.");
+ }
+ return childSessionId;
+}
+
+async function expectRetainedChildConversation(input: {
+ readonly childSessionId: string;
+ readonly client: Client;
+}): Promise<void> {
+ const childEvents = await collectStreamToEnd({
+ label: "persisted child events",
+ stream: input.client
+ .session({ sessionId: input.childSessionId, streamIndex: 0 })
+ .stream({ follow: false }),
+ });
+ const childTurnStarts = indexesOf(childEvents, "turn.started");
+ const childWaits = indexesOf(childEvents, "session.waiting");
+
+ expect(childTurnStarts).toHaveLength(2);
+ expect(childWaits).toHaveLength(2);
+ expect(childWaits[0]).toBeLessThan(childTurnStarts[1] ?? -1);
+ expect(filterEventsByType(childEvents, "session.completed")).toHaveLength(0);
+ expect(filterEventsByType(childEvents, "session.failed")).toHaveLength(0);
+ expect(
+ filterEventsByType(childEvents, "message.completed").some(
+ (event) => event.data.message === CODEWORD,
+ ),
+ ).toBe(true);
+}
+
+async function collectStreamToEnd(input: {
+ readonly label: string;
+ readonly stream: AsyncIterable<HandleMessageStreamEvent>;
+}): Promise<readonly HandleMessageStreamEvent[]> {
+ const events: HandleMessageStreamEvent[] = [];
+ let timeout: ReturnType<typeof setTimeout> | undefined;
+
+ try {
+ return await Promise.race([
+ (async () => {
+ for await (const event of input.stream) {
+ events.push(event);
+ }
+ return events;
+ })(),
+ new Promise<never>((_resolve, reject) => {
+ timeout = setTimeout(
+ () => reject(new Error(`Timed out waiting for ${input.label}.`)),
+ EVENT_TIMEOUT_MS,
+ );
+ }),
+ ]);
+ } finally {
+ if (timeout !== undefined) {
+ clearTimeout(timeout);
+ }
+ }
+}
+
+function indexesOf(
+ events: readonly HandleMessageStreamEvent[],
+ type: HandleMessageStreamEvent["type"],
+): readonly number[] {
+ return events.flatMap((event, index) => (event.type === type ? [index] : []));
+}
+
+async function readWorkflowRunStatus(appRoot: string, sessionId: string): Promise<string> {
+ const runPath = join(appRoot, ".eve", ".workflow-data", "runs", `${sessionId}.json`);
+ const run: unknown = JSON.parse(await readFile(runPath, "utf8"));
+
+ if (typeof run !== "object" || run === null) {
+ throw new Error(`Workflow run ${sessionId} was not an object.`);
+ }
+
+ const status = Reflect.get(run, "status");
+ if (typeof status !== "string") {
+ throw new Error(`Workflow run ${sessionId} did not contain a string status.`);
+ }
+
+ return status;
+}
+
+interface RunningScriptedEveDev {
+ readonly stderr: () => string;
+ readonly stdout: () => string;
+ readonly url: string;
+ stop(): Promise<void>;
+}
+
+async function startScriptedEveDev(appRoot: string): Promise<RunningScriptedEveDev> {
+ const eveBinPath = join(appRoot, "node_modules", "eve", "bin", "eve.js");
+ const child = spawn(
+ process.execPath,
+ [eveBinPath, "dev", "--no-ui", "--host", "127.0.0.1", "--port", "0"],
+ {
+ cwd: appRoot,
+ env: {
+ ...process.env,
+ EVE_MOCK_AUTHORED_MODELS: "",
+ NODE_ENV: "production",
+ },
+ stdio: ["ignore", "pipe", "pipe"],
+ },
+ );
+ let stderr = "";
+ let stdout = "";
+
+ child.stdout.setEncoding("utf8");
+ child.stderr.setEncoding("utf8");
+ child.stdout.on("data", (chunk: string) => {
+ stdout += chunk;
+ });
+ child.stderr.on("data", (chunk: string) => {
+ stderr += chunk;
+ });
+
+ let url: string;
+ try {
+ url = await waitForServerUrl(child, () => ({ stderr, stdout }));
+ } catch (error) {
+ await stopChild(child);
+ throw error;
+ }
+
+ return {
+ stderr: () => stderr,
+ stdout: () => stdout,
+ async stop() {
+ await stopChild(child);
+ },
+ url,
+ };
+}
+
+async function waitForServerUrl(
+ child: ChildProcessByStdio<null, Readable, Readable>,
+ output: () => { readonly stderr: string; readonly stdout: string },
+): Promise<string> {
+ return await new Promise((resolve, reject) => {
+ const timeout = setTimeout(() => {
+ cleanup();
+ const current = output();
+ reject(
+ new Error(
+ `Timed out waiting for eve dev.\n\nstdout:\n${current.stdout}\n\nstderr:\n${current.stderr}`,
+ ),
+ );
+ }, EVENT_TIMEOUT_MS);
+
+ function inspect() {
+ const match = /\[DEV\] server listening at (http:\/\/[^\s]+)/u.exec(output().stdout);
+ if (match?.[1] === undefined) {
+ return;
+ }
+ cleanup();
+ resolve(match[1]);
+ }
+
+ function exited(code: number | null, signal: NodeJS.Signals | null) {
+ cleanup();
+ const current = output();
+ reject(
+ new Error(
+ [
+ `eve dev exited before startup (code ${String(code)}, signal ${String(signal)}).`,
+ `stdout:\n${current.stdout}`,
+ `stderr:\n${current.stderr}`,
+ ].join("\n\n"),
+ ),
+ );
+ }
+
+ function cleanup() {
+ clearTimeout(timeout);
+ child.stdout.off("data", inspect);
+ child.stderr.off("data", inspect);
+ child.off("exit", exited);
+ }
+
+ child.stdout.on("data", inspect);
+ child.stderr.on("data", inspect);
+ child.once("exit", exited);
+ inspect();
+ });
+}
+
+async function stopChild(child: ChildProcessByStdio<null, Readable, Readable>): Promise<void> {
+ if (child.exitCode !== null || child.signalCode !== null) {
+ return;
+ }
+
+ await new Promise<void>((resolve) => {
+ const force = setTimeout(() => child.kill("SIGKILL"), 10_000);
+ child.once("exit", () => {
+ clearTimeout(force);
+ resolve();
+ });
+ child.kill("SIGTERM");
+ });
+}
diff --git a/packages/eve/src/execution/dispatch-runtime-actions-step.integration.test.ts b/packages/eve/src/execution/dispatch-runtime-actions-step.integration.test.ts
index 7c846d480..44eb77389 100644
--- a/packages/eve/src/execution/dispatch-runtime-actions-step.integration.test.ts
+++ b/packages/eve/src/execution/dispatch-runtime-actions-step.integration.test.ts
@@ -408,12 +408,36 @@ describe("dispatchRuntimeActionsStep agent delivery", () => {
});
it.each([
- {
- handle: undefined,
- agentId: "ag_research:missing",
- code: "AGENT_UNKNOWN",
- title: "unknown",
- },
+ { agentId: "ag_research:missing", title: "matches no stored handle" },
+ { agentId: "", title: "is an empty string from a strict provider" },
+ { agentId: null, title: "is null from a strict provider" },
+ ])("starts a fresh agent when the agentId $title", async ({ agentId }) => {
+ const session = createPendingSession({ agentId, handle: undefined });
+ installContext(session);
+
+ const result = await dispatchRuntimeActionsStep({
+ parentContinuationToken: "turn-inbox",
+ parentWritable: createWritable(),
+ serializedContext: {},
+ sessionState: BASE_STATE,
+ });
+
+ expect(result.results).toEqual([]);
+ expect(mocks.createSession).toHaveBeenCalledTimes(1);
+ expect(mocks.dispatchSession).not.toHaveBeenCalled();
+ // The fallback dispatches through the normal start path: the fresh
+ // child is owned by a confirmed running handle, not the stale id.
+ expect(getAgentHandleStore(readResultSessionState(result, session))).toEqual({
+ handles: [
+ expect.objectContaining({
+ address: expect.objectContaining({ sessionId: CHILD_SESSION_ID }),
+ phase: "running",
+ }),
+ ],
+ });
+ });
+
+ it.each([
{
handle: {
...LOCAL_PARKED_HANDLE,
@@ -488,6 +512,52 @@ describe("dispatchRuntimeActionsStep agent delivery", () => {
});
});
+ it("reports AGENT_UNREACHABLE when the handle disappears mid-batch instead of starting a fresh agent", async () => {
+ // Two continuations to one agentId in a single batch: the first delivery
+ // fails permanently and deletes the handle, so the second — planned as a
+ // resume while the handle still existed — must fail rather than fall
+ // back to an unplanned fresh start.
+ const session = setPendingRuntimeActionBatch({
+ actions: [1, 2].map((n) => ({
+ callId: `call-${n}`,
+ description: "Research",
+ input: { agentId: LOCAL_PARKED_HANDLE.identity.id, message: `continue ${n}` },
+ kind: "subagent-call" as const,
+ name: "research",
+ nodeId: "subagents/research",
+ subagentName: "research",
+ })),
+ event: { sequence: 1, stepIndex: 2, turnId: "turn-1" },
+ responseMessages: [],
+ session: createBaseSession(LOCAL_PARKED_HANDLE),
+ });
+ installContext(session);
+ mocks.dispatchSession.mockResolvedValue({ status: "session_not_active" });
+
+ const result = await dispatchRuntimeActionsStep({
+ parentContinuationToken: "turn-inbox",
+ parentWritable: createWritable(),
+ serializedContext: {},
+ sessionState: BASE_STATE,
+ });
+
+ expect(mocks.dispatchSession).toHaveBeenCalledTimes(1);
+ expect(mocks.createSession).not.toHaveBeenCalled();
+ expect(result.results).toEqual([
+ expect.objectContaining({
+ isError: true,
+ output: expect.objectContaining({ code: "AGENT_UNREACHABLE" }),
+ }),
+ expect.objectContaining({
+ isError: true,
+ output: expect.objectContaining({ code: "AGENT_UNREACHABLE" }),
+ }),
+ ]);
+ expect(getAgentHandleStore(readResultSessionState(result, session))).toEqual({
+ handles: [],
+ });
+ });
+
it("continues a stored remote handle and maps a permanent failure to AGENT_UNREACHABLE", async () => {
const session = createPendingSession({
handle: REMOTE_PARKED_HANDLE,
@@ -652,7 +722,7 @@ function createStartSession(input: { readonly kind: "local" | "remote" }): Harne
function createPendingSession(input: {
readonly handle?: AgentHandle;
- readonly agentId: string;
+ readonly agentId: string | null;
}): HarnessSession {
return setPendingRuntimeActionBatch({
actions: [
diff --git a/packages/eve/src/execution/dispatch-runtime-actions-step.ts b/packages/eve/src/execution/dispatch-runtime-actions-step.ts
index cf89a57b9..4fe974ada 100644
--- a/packages/eve/src/execution/dispatch-runtime-actions-step.ts
+++ b/packages/eve/src/execution/dispatch-runtime-actions-step.ts
@@ -276,6 +276,15 @@ export async function dispatchRuntimeActionsStep(input: {
* Classifies every batch action before anything dispatches, so invalid
* batches fail without starting children and rejections never interleave
* with dispatch work.
+ *
+ * This is the single place that decides fresh start vs. continuation:
+ * an omitted, null, empty, or whitespace-only agentId is a fresh start
+ * (strict tool-calling providers force every schema property to be present,
+ * so models emit `""`/`null` when they mean "no continuation"), and an
+ * agentId that matches no stored handle also falls back to a fresh start —
+ * models sometimes pass a hallucinated or stale id, and hard-failing made
+ * them conclude the subagent itself was unavailable. Only an id that
+ * resolves to a stored handle becomes a resume.
*/
function planDispatch(input: {
readonly actions: readonly RuntimeActionRequest[];
@@ -283,99 +292,133 @@ function planDispatch(input: {
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;
+ const handles = getAgentHandleStore(input.session.state)?.handles ?? [];
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;
- const agentId = typeof action.input.agentId === "string" ? action.input.agentId : undefined;
- // Resume classification runs before the recursion guard: an agentId
- // continuation resumes an already-adopted child rather than starting a
- // new one, and a non-root session can never own an `agent`-tool handle,
- // so an agentId-carrying recursive call falls through to AGENT_UNKNOWN.
+ const rawAgentId = action.input.agentId;
+ const agentId =
+ typeof rawAgentId === "string" && rawAgentId.trim() !== "" ? rawAgentId : undefined;
if (agentId !== undefined && isAgentHandleAction(action)) {
- return {
- action,
+ // Resume classification runs before the recursion guard: an agentId
+ // continuation resumes an already-adopted child rather than starting
+ // a new one. Unknown ids go through classifyFreshStart below, which
+ // re-applies the guard the resume path bypasses.
+ if (handles.some((handle) => handle.identity.id === agentId)) {
+ const dynamicSubagentSelection =
+ input.bundle.subagentRegistry.dynamicNodeIds?.has(action.nodeId) === true
+ ? getDynamicSubagentSelection(input.ctx, action.nodeId)
+ : undefined;
+ return {
+ action,
+ agentId,
+ dynamicRemoteAgent:
+ action.kind === "remote-agent-call" && dynamicSubagentSelection?.kind === "remote"
+ ? dynamicSubagentSelection.remoteAgent
+ : undefined,
+ kind: "resume",
+ };
+ }
+ log.warn("unknown agentId on subagent call; starting a new agent", {
agentId,
- dynamicRemoteAgent:
- action.kind === "remote-agent-call" && dynamicSubagentSelection?.kind === "remote"
- ? dynamicSubagentSelection.remoteAgent
- : undefined,
- kind: "resume",
- };
- }
-
- 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) };
- }
+ return classifyFreshStart({
+ action,
+ bundle: input.bundle,
+ ctx: input.ctx,
+ session: input.session,
+ });
+ });
+}
- 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.`);
+/**
+ * Classifies one action for fresh dispatch: rejected by the recursion guard,
+ * or started against a local/remote target. Shared by plain starts and the
+ * unknown-agentId fallback, so both paths enforce the same guard.
+ */
+function classifyFreshStart(input: {
+ readonly action: RuntimeActionRequest;
+ readonly bundle: CompiledBundle;
+ readonly ctx: Parameters<typeof getDynamicSubagentSelection>[0];
+ readonly session: RuntimeSession;
+}): Extract<DispatchPlanEntry, { kind: "reject" | "start" }> {
+ const { action } = input;
+ const registry = input.bundle.subagentRegistry.subagentsByNodeId;
+ const subagentDepth = resolveSubagentDepth(input.session);
+ const rootOnly = input.session.rootSessionId !== undefined || subagentDepth.currentDepth > 0;
+
+ 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: {
diff --git a/packages/eve/src/execution/node-step.ts b/packages/eve/src/execution/node-step.ts
index b4681434a..5d23e429b 100644
--- a/packages/eve/src/execution/node-step.ts
+++ b/packages/eve/src/execution/node-step.ts
@@ -17,11 +17,18 @@ import {
type RuntimeModelResolutionScope,
} from "#runtime/agent/resolve-model.js";
import type { RuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";
-import { AGENT_TOOL_DESCRIPTION, AGENT_TOOL_NAME } from "#runtime/framework-tools/agent.js";
-import { ROOT_RUNTIME_AGENT_NODE_ID, type ResolvedRuntimeAgentNode } from "#runtime/graph.js";
+import {
+ AGENT_TOOL_DESCRIPTION,
+ AGENT_TOOL_NAME,
+ isImplicitAgentToolAvailable,
+} from "#runtime/framework-tools/agent.js";
+import type { ResolvedRuntimeAgentNode } from "#runtime/graph.js";
import type { PreparedRuntimeTool } from "#runtime/sessions/turn.js";
-import { SUBAGENT_TOOL_INPUT_SCHEMA } from "#runtime/subagents/registry.js";
+import {
+ PERSISTENT_SUBAGENT_TOOL_INPUT_SCHEMA,
+ SUBAGENT_TOOL_INPUT_SCHEMA,
+} from "#runtime/subagents/registry.js";
import { findRegisteredRuntimeTool } from "#runtime/tools/registry.js";
import type { ResolvedToolDefinition } from "#runtime/types.js";
import { preserveFrameworkStateOnCompaction } from "#execution/compaction.js";
@@ -198,13 +205,18 @@ export function createNodeHarnessTools(input: {
}
if (
- input.node.nodeId === ROOT_RUNTIME_AGENT_NODE_ID &&
- !input.node.agent.disabledFrameworkTools.includes(AGENT_TOOL_NAME) &&
- !tools.has(AGENT_TOOL_NAME)
+ isImplicitAgentToolAvailable({
+ disabledFrameworkTools: input.node.agent.disabledFrameworkTools,
+ hasAuthoredAgentTool: tools.has(AGENT_TOOL_NAME),
+ nodeId: input.node.nodeId,
+ })
) {
tools.set(AGENT_TOOL_NAME, {
description: AGENT_TOOL_DESCRIPTION,
- inputSchema: SUBAGENT_TOOL_INPUT_SCHEMA,
+ inputSchema:
+ input.node.agent.config?.experimental?.subagentPersistentSessions === true
+ ? PERSISTENT_SUBAGENT_TOOL_INPUT_SCHEMA
+ : SUBAGENT_TOOL_INPUT_SCHEMA,
name: AGENT_TOOL_NAME,
runtimeAction: {
kind: "subagent-call",
diff --git a/packages/eve/src/execution/remote-agent-dispatch.ts b/packages/eve/src/execution/remote-agent-dispatch.ts
index 2152bf101..3114bd51d 100644
--- a/packages/eve/src/execution/remote-agent-dispatch.ts
+++ b/packages/eve/src/execution/remote-agent-dispatch.ts
@@ -91,7 +91,11 @@ export async function startRemoteAgentSession(input: {
createEveCallbackRoutePath(callbackToken),
),
},
- message: formatRemoteAgentCallInputMessage({ action: input.action, remote: input.remote }),
+ message: formatRemoteAgentCallInputMessage({
+ action: input.action,
+ persistentSession: input.persistentSessions,
+ remote: input.remote,
+ }),
mode: input.persistentSessions === true ? "conversation" : "task",
outputSchema:
normalizeRequestedOutputSchema(input.action.input.outputSchema) ?? input.remote.outputSchema,
@@ -444,6 +448,7 @@ async function resolveRemoteAgentRequestHeaders(
function formatRemoteAgentCallInputMessage(input: {
readonly action: RuntimeRemoteAgentCallActionRequest;
+ readonly persistentSession?: boolean;
readonly remote: ResolvedRuntimeRemoteAgentNode;
}): string {
const message = typeof input.action.input.message === "string" ? input.action.input.message : "";
@@ -451,6 +456,7 @@ function formatRemoteAgentCallInputMessage(input: {
description: input.remote.description,
message,
name: input.action.remoteAgentName,
+ persistentSession: input.persistentSession,
type: "remote",
}).message;
}
diff --git a/packages/eve/src/execution/subagent-invocation.ts b/packages/eve/src/execution/subagent-invocation.ts
index c5494a44c..2a255a914 100644
--- a/packages/eve/src/execution/subagent-invocation.ts
+++ b/packages/eve/src/execution/subagent-invocation.ts
@@ -28,6 +28,7 @@ export function normalizeRequestedOutputSchema(
type RuntimeSubagentInputFormatRequest = {
readonly message: string;
readonly name: string;
+ readonly persistentSession?: boolean;
readonly type: "runtime";
};
@@ -35,6 +36,7 @@ type LocalSubagentInputFormatRequest = {
readonly description: string;
readonly message: string;
readonly name: string;
+ readonly persistentSession?: boolean;
readonly type: "local";
};
@@ -42,6 +44,7 @@ type RemoteSubagentInputFormatRequest = {
readonly description: string;
readonly message: string;
readonly name: string;
+ readonly persistentSession?: boolean;
readonly type: "remote";
};
@@ -62,6 +65,7 @@ const formatSubagentInputByType = {
descriptionLines: [],
message: input.message,
name: input.name,
+ persistentSession: input.persistentSession,
});
},
local(input) {
@@ -69,6 +73,7 @@ const formatSubagentInputByType = {
descriptionLines: formatDescriptionLines(input.description),
message: input.message,
name: input.name,
+ persistentSession: input.persistentSession,
});
},
remote(input) {
@@ -76,6 +81,7 @@ const formatSubagentInputByType = {
descriptionLines: formatDescriptionLines(input.description),
message: input.message,
name: input.name,
+ persistentSession: input.persistentSession,
});
},
} satisfies SubagentInputFormatters;
@@ -104,13 +110,16 @@ function formatSubagentPrompt(input: {
readonly descriptionLines: readonly string[];
readonly message: string;
readonly name: string;
+ readonly persistentSession?: boolean;
}): FormattedSubagentInvocation {
return {
message: [
`You are the subagent "${input.name}".`,
...input.descriptionLines,
"",
- "The caller delegated the following task to you. Complete it and return the final result directly.",
+ input.persistentSession === true
+ ? "The caller delegated the following task to you. Complete it and return the result directly. The caller may send follow-up messages after you answer."
+ : "The caller delegated the following task to you. Complete it and return the final result directly.",
"",
"Caller message:",
input.message,
diff --git a/packages/eve/src/execution/subagent-tool.ts b/packages/eve/src/execution/subagent-tool.ts
index bd6596c1d..5c2645f7a 100644
--- a/packages/eve/src/execution/subagent-tool.ts
+++ b/packages/eve/src/execution/subagent-tool.ts
@@ -131,7 +131,11 @@ export function buildSubagentRunInput(input: {
continuationToken: childContinuationToken,
initiatorAuth,
input: {
- message: formatSubagentCallInputMessage({ action, source }),
+ message: formatSubagentCallInputMessage({
+ action,
+ persistentSession: input.persistentSessions,
+ source,
+ }),
outputSchema: requestedOutputSchema,
},
limits: inheritedLimits,
@@ -157,6 +161,7 @@ export function buildSubagentRunInput(input: {
*/
function formatSubagentCallInputMessage(input: {
readonly action: Pick<RuntimeSubagentCallActionRequest, "input" | "subagentName">;
+ readonly persistentSession?: boolean;
readonly source: SubagentInputSource;
}): string {
const { message } = input.action.input as { message: string };
@@ -167,12 +172,14 @@ function formatSubagentCallInputMessage(input: {
description: input.source.description,
message,
name: input.action.subagentName,
+ persistentSession: input.persistentSession,
type: "local",
}).message;
case "runtime":
return formatSubagentInput({
message,
name: input.action.subagentName,
+ persistentSession: input.persistentSession,
type: "runtime",
}).message;
default: {
diff --git a/packages/eve/src/execution/terminate-child-sessions-step.test.ts b/packages/eve/src/execution/terminate-child-sessions-step.test.ts
index 98a5010fe..729a61387 100644
--- a/packages/eve/src/execution/terminate-child-sessions-step.test.ts
+++ b/packages/eve/src/execution/terminate-child-sessions-step.test.ts
@@ -4,20 +4,22 @@ import { AGENT_HANDLES_STATE_KEY, type AgentHandle } from "#harness/handles/stor
import type { DurableSessionState } from "#execution/durable-session-store.js";
import { terminateChildSessionsStep } from "#execution/terminate-child-sessions-step.js";
-const { dispatchSessionMock } = vi.hoisted(() => ({
- dispatchSessionMock: vi.fn(),
+const { cancelRunMock, getWorldMock } = vi.hoisted(() => ({
+ cancelRunMock: vi.fn(),
+ getWorldMock: vi.fn(),
}));
-vi.mock("./workflow-runtime.js", () => ({
- createWorkflowRuntime: vi.fn(() => ({
- dispatchSession: dispatchSessionMock,
- })),
+vi.mock("#internal/workflow/runtime.js", () => ({
+ cancelRun: cancelRunMock,
+ getWorld: getWorldMock,
}));
describe("terminateChildSessionsStep", () => {
beforeEach(() => {
- dispatchSessionMock.mockReset();
- dispatchSessionMock.mockResolvedValue({ status: "accepted" });
+ cancelRunMock.mockReset();
+ cancelRunMock.mockResolvedValue(undefined);
+ getWorldMock.mockReset();
+ getWorldMock.mockResolvedValue("world");
});
it("terminates running and parked local/self children", async () => {
@@ -30,14 +32,12 @@ describe("terminateChildSessionsStep", () => {
sessionState: makeSessionState(handles),
});
- expect(dispatchSessionMock).toHaveBeenCalledTimes(2);
- expect(dispatchSessionMock).toHaveBeenNthCalledWith(1, {
- command: { kind: "reset", reason: "Parent session ended" },
- sessionId: "session-local",
+ expect(cancelRunMock).toHaveBeenCalledTimes(2);
+ expect(cancelRunMock).toHaveBeenNthCalledWith(1, "world", "session-local", {
+ cancelReason: "Parent session ended",
});
- expect(dispatchSessionMock).toHaveBeenNthCalledWith(2, {
- command: { kind: "reset", reason: "Parent session ended" },
- sessionId: "session-self",
+ expect(cancelRunMock).toHaveBeenNthCalledWith(2, "world", "session-self", {
+ cancelReason: "Parent session ended",
});
});
@@ -49,9 +49,8 @@ describe("terminateChildSessionsStep", () => {
]),
});
- expect(dispatchSessionMock).toHaveBeenCalledExactlyOnceWith({
- command: { kind: "reset", reason: "Parent session ended" },
- sessionId: "session-local",
+ expect(cancelRunMock).toHaveBeenCalledExactlyOnceWith("world", "session-local", {
+ cancelReason: "Parent session ended",
});
});
@@ -63,17 +62,16 @@ describe("terminateChildSessionsStep", () => {
]),
});
- expect(dispatchSessionMock).toHaveBeenCalledExactlyOnceWith({
- command: { kind: "reset", reason: "Parent session ended" },
- sessionId: "session-self",
+ expect(cancelRunMock).toHaveBeenCalledExactlyOnceWith("world", "session-self", {
+ cancelReason: "Parent session ended",
});
});
it("continues terminating children after one termination fails", async () => {
const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
- dispatchSessionMock
+ cancelRunMock
.mockRejectedValueOnce(new Error("termination unavailable"))
- .mockResolvedValueOnce({ status: "accepted" });
+ .mockResolvedValueOnce(undefined);
try {
await expect(
@@ -85,7 +83,7 @@ describe("terminateChildSessionsStep", () => {
}),
).resolves.toBeUndefined();
- expect(dispatchSessionMock).toHaveBeenCalledTimes(2);
+ expect(cancelRunMock).toHaveBeenCalledTimes(2);
expect(errorSpy).toHaveBeenCalledWith(
"[eve:execution.terminate-child-sessions] failed to terminate child session",
expect.objectContaining({
diff --git a/packages/eve/src/execution/terminate-child-sessions-step.ts b/packages/eve/src/execution/terminate-child-sessions-step.ts
index 1c095597f..f979c018d 100644
--- a/packages/eve/src/execution/terminate-child-sessions-step.ts
+++ b/packages/eve/src/execution/terminate-child-sessions-step.ts
@@ -1,7 +1,7 @@
import { readDurableSession, type DurableSessionState } from "#execution/durable-session-store.js";
-import { createWorkflowRuntime } from "#execution/workflow-runtime.js";
import { getAgentHandleStore, type AgentHandle } from "#harness/handles/store.js";
import { createLogger, logError } from "#internal/logging.js";
+import { cancelRun, getWorld } from "#internal/workflow/runtime.js";
const log = createLogger("execution.terminate-child-sessions");
@@ -36,10 +36,6 @@ export async function terminateChildSessionsStep(input: {
return;
}
- const runtime = createWorkflowRuntime({
- compiledArtifactsSource: { kind: "bundled" },
- });
-
for (const handle of handles) {
if (handle.phase === "starting") {
log.debug("skipping starting child without a session id", {
@@ -50,9 +46,8 @@ export async function terminateChildSessionsStep(input: {
continue;
}
try {
- await runtime.dispatchSession({
- command: { kind: "reset", reason: "Parent session ended" },
- sessionId: handle.address.sessionId,
+ await cancelRun(await getWorld(), handle.address.sessionId, {
+ cancelReason: "Parent session ended",
});
} catch (error) {
logError(log, "failed to terminate child session", error, {
diff --git a/packages/eve/src/execution/workflow-steps.ts b/packages/eve/src/execution/workflow-steps.ts
index 9ea211b8e..f6f59e52c 100644
--- a/packages/eve/src/execution/workflow-steps.ts
+++ b/packages/eve/src/execution/workflow-steps.ts
@@ -288,6 +288,8 @@ export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResu
const dynamicInstructionsResolvers = bundle.resolvedAgent.dynamicInstructionsResolvers ?? [];
const dynamicSkillResolvers = bundle.resolvedAgent.dynamicSkillResolvers ?? [];
const dynamicSubagentResolvers = bundle.subagentRegistry.dynamicResolvers ?? [];
+ const persistentSubagentSessions =
+ bundle.resolvedAgent.config.experimental?.subagentPersistentSessions === true;
const dynamicToolResolvers = bundle.resolvedAgent.dynamicToolResolvers ?? [];
const effectiveNode = {
...bundle.graph.root,
@@ -311,6 +313,7 @@ export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResu
resolvers: dynamicSubagentResolvers,
event: refreshEvent,
messages: initialSession.history,
+ persistentSessions: persistentSubagentSessions,
runtimeRevision: dynamicRuntimeRevision,
}),
refreshDynamicSessionToolsForRuntimeRevision({
@@ -358,6 +361,7 @@ export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResu
resolvers: dynamicSubagentResolvers,
event: emitted,
messages: messages ?? [],
+ persistentSessions: persistentSubagentSessions,
});
await dispatchDynamicToolEvent({
ctx,
diff --git a/packages/eve/src/harness/agent-handle-errors.ts b/packages/eve/src/harness/agent-handle-errors.ts
index e45075ddf..6a3a16e5b 100644
--- a/packages/eve/src/harness/agent-handle-errors.ts
+++ b/packages/eve/src/harness/agent-handle-errors.ts
@@ -6,9 +6,6 @@
* 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";
diff --git a/packages/eve/src/harness/handles/transitions.ts b/packages/eve/src/harness/handles/transitions.ts
index af30bd74e..bd8574257 100644
--- a/packages/eve/src/harness/handles/transitions.ts
+++ b/packages/eve/src/harness/handles/transitions.ts
@@ -74,7 +74,7 @@ export type PrepareAgentContinuationResult =
* 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`
+ * maps them onto `AGENT_UNREACHABLE`, `AGENT_MISMATCH`, and `AGENT_BUSY`
* results.
*/
export function prepareAgentContinuation(
diff --git a/packages/eve/src/runtime/agent/bootstrap.test.ts b/packages/eve/src/runtime/agent/bootstrap.test.ts
new file mode 100644
index 000000000..edaa9d97d
--- /dev/null
+++ b/packages/eve/src/runtime/agent/bootstrap.test.ts
@@ -0,0 +1,101 @@
+import { describe, expect, it } from "vitest";
+
+import { createResolvedRuntimeTurnAgent } from "#runtime/agent/bootstrap.js";
+import { AGENT_TOOL_NAME } from "#runtime/framework-tools/agent.js";
+import { ROOT_RUNTIME_AGENT_NODE_ID } from "#runtime/graph.js";
+import type { ResolvedAgent } from "#runtime/types.js";
+
+function createResolvedAgentForTest(overrides: Partial<ResolvedAgent> = {}): ResolvedAgent {
+ const agent: Partial<ResolvedAgent> = {
+ config: { name: "test-agent" } as ResolvedAgent["config"],
+ connections: [],
+ disabledFrameworkTools: [],
+ instructions: { markdown: "" } as ResolvedAgent["instructions"],
+ skills: [],
+ ...overrides,
+ };
+ return agent as ResolvedAgent;
+}
+
+describe("createResolvedRuntimeTurnAgent agent-messaging gating", () => {
+ it("includes the messaging instruction for an opted-in root agent (framework agent tool)", () => {
+ const turnAgent = createResolvedRuntimeTurnAgent({
+ agent: createResolvedAgentForTest({
+ config: {
+ experimental: { subagentPersistentSessions: true },
+ name: "test-agent",
+ } as ResolvedAgent["config"],
+ }),
+ nodeId: ROOT_RUNTIME_AGENT_NODE_ID,
+ tools: [],
+ });
+
+ expect(turnAgent.instructions).toContainEqual(expect.stringContaining("Pass `agentId`"));
+ expect(turnAgent.instructions).toContainEqual(expect.stringContaining("Tool execution"));
+ });
+
+ it("omits the messaging instruction for a root agent without the experimental opt-in", () => {
+ const turnAgent = createResolvedRuntimeTurnAgent({
+ agent: createResolvedAgentForTest(),
+ nodeId: ROOT_RUNTIME_AGENT_NODE_ID,
+ tools: [],
+ });
+
+ expect(turnAgent.instructions).not.toContainEqual(expect.stringContaining("Pass `agentId`"));
+ });
+
+ it("omits the messaging instruction when an authored tool named agent shadows the framework tool", () => {
+ const turnAgent = createResolvedRuntimeTurnAgent({
+ agent: createResolvedAgentForTest({
+ config: {
+ experimental: { subagentPersistentSessions: true },
+ name: "test-agent",
+ } as ResolvedAgent["config"],
+ }),
+ nodeId: ROOT_RUNTIME_AGENT_NODE_ID,
+ tools: [
+ {
+ description: "Authored replacement for the framework agent tool.",
+ inputSchema: null,
+ kind: "authored-tool",
+ logicalPath: `tools/${AGENT_TOOL_NAME}.ts`,
+ name: AGENT_TOOL_NAME,
+ sourceId: `tools/${AGENT_TOOL_NAME}.ts`,
+ },
+ ],
+ });
+
+ expect(turnAgent.instructions).not.toContainEqual(expect.stringContaining("Pass `agentId`"));
+ });
+
+ it("omits the messaging instruction when the root disables the framework agent tool", () => {
+ const turnAgent = createResolvedRuntimeTurnAgent({
+ agent: createResolvedAgentForTest({
+ config: {
+ experimental: { subagentPersistentSessions: true },
+ name: "test-agent",
+ } as ResolvedAgent["config"],
+ disabledFrameworkTools: [AGENT_TOOL_NAME],
+ } as Partial<ResolvedAgent>),
+ nodeId: ROOT_RUNTIME_AGENT_NODE_ID,
+ tools: [],
+ });
+
+ expect(turnAgent.instructions).not.toContainEqual(expect.stringContaining("Pass `agentId`"));
+ });
+
+ it("omits the messaging instruction for a non-root node without declared subagents", () => {
+ const turnAgent = createResolvedRuntimeTurnAgent({
+ agent: createResolvedAgentForTest({
+ config: {
+ experimental: { subagentPersistentSessions: true },
+ name: "test-agent",
+ } as ResolvedAgent["config"],
+ }),
+ nodeId: "subagents/researcher",
+ tools: [],
+ });
+
+ expect(turnAgent.instructions).not.toContainEqual(expect.stringContaining("Pass `agentId`"));
+ });
+});
diff --git a/packages/eve/src/runtime/agent/bootstrap.ts b/packages/eve/src/runtime/agent/bootstrap.ts
index e0396746e..e44166a9d 100644
--- a/packages/eve/src/runtime/agent/bootstrap.ts
+++ b/packages/eve/src/runtime/agent/bootstrap.ts
@@ -1,3 +1,4 @@
+import { AGENT_TOOL_NAME, isImplicitAgentToolAvailable } from "#runtime/framework-tools/agent.js";
import { composeRuntimeBasePrompt } from "#runtime/prompt/compose.js";
import type { PreparedRuntimeTool } from "#runtime/sessions/turn.js";
import type { ResolvedAgent } from "#runtime/types.js";
@@ -64,6 +65,19 @@ export function createResolvedRuntimeTurnAgent(input: {
readonly tools: readonly PreparedRuntimeTool[];
}): RuntimeTurnAgent {
const agent = input.agent;
+ const subagentDeclaredTool = input.tools.some(
+ (tool) => tool.kind === "subagent" || tool.kind === "remote",
+ );
+ // The framework `agent` tool is injected after graph resolution, so
+ // declared tools alone under-count. isImplicitAgentToolAvailable is the
+ // same predicate node-step uses for the injection itself — including the
+ // authored-tool shadowing leg, so instructions never advertise a tool an
+ // authored "agent" tool has replaced.
+ const subagentImplicitRootTool = isImplicitAgentToolAvailable({
+ disabledFrameworkTools: agent.disabledFrameworkTools,
+ hasAuthoredAgentTool: input.tools.some((tool) => tool.name === AGENT_TOOL_NAME),
+ nodeId: input.nodeId,
+ });
return {
availableSkills: agent.skills.map((skill) => ({
description: skill.description,
@@ -73,7 +87,9 @@ export function createResolvedRuntimeTurnAgent(input: {
instructions: composeRuntimeBasePrompt({
connections: agent.connections,
instructions: agent.instructions,
- toolsAvailable: input.tools.length > 0,
+ persistentSubagentSessions: agent.config.experimental?.subagentPersistentSessions === true,
+ subagentsAvailable: subagentDeclaredTool || subagentImplicitRootTool,
+ toolsAvailable: input.tools.length > 0 || subagentImplicitRootTool,
workspaceSpec: agent.workspaceSpec,
}),
compactionModel: agent.config.compaction?.model,
diff --git a/packages/eve/src/runtime/framework-tools/agent.ts b/packages/eve/src/runtime/framework-tools/agent.ts
index f17993d54..8681309e9 100644
--- a/packages/eve/src/runtime/framework-tools/agent.ts
+++ b/packages/eve/src/runtime/framework-tools/agent.ts
@@ -1,3 +1,4 @@
+import { ROOT_RUNTIME_AGENT_NODE_ID } from "#runtime/graph.js";
import { SUBAGENT_TOOL_INPUT_SCHEMA } from "#runtime/subagents/registry.js";
import type { ResolvedToolDefinition } from "#runtime/types.js";
@@ -16,6 +17,29 @@ export const AGENT_TOOL_DESCRIPTION = [
"Each child has fresh history and state but shares your tools and sandbox, so include essential context in `message` and give parallel writers non-overlapping scopes.",
].join(" ");
+/**
+ * Whether one node receives the implicit built-in `agent` tool.
+ *
+ * Single source of truth for the injection predicate: node-step uses it to
+ * decide whether to add the tool, and prompt bootstrap uses it to decide
+ * whether agent-messaging instructions may reference the tool. The
+ * `hasAuthoredAgentTool` leg matters because an authored tool named "agent"
+ * shadows the framework tool — instructions must not advertise a tool the
+ * model cannot call.
+ */
+export function isImplicitAgentToolAvailable(input: {
+ readonly disabledFrameworkTools: readonly string[];
+ readonly hasAuthoredAgentTool: boolean;
+ /** Undefined when the caller prepares a turn without a graph node (never root). */
+ readonly nodeId: string | undefined;
+}): boolean {
+ return (
+ input.nodeId === ROOT_RUNTIME_AGENT_NODE_ID &&
+ !input.disabledFrameworkTools.includes(AGENT_TOOL_NAME) &&
+ !input.hasAuthoredAgentTool
+ );
+}
+
/**
* Shared metadata for the root-only agent delegation tool.
*/
diff --git a/packages/eve/src/runtime/prompt/compose.test.ts b/packages/eve/src/runtime/prompt/compose.test.ts
new file mode 100644
index 000000000..7a0c21ca6
--- /dev/null
+++ b/packages/eve/src/runtime/prompt/compose.test.ts
@@ -0,0 +1,34 @@
+import { describe, expect, it } from "vitest";
+
+import { composeRuntimeBasePrompt } from "#runtime/prompt/compose.js";
+
+describe("composeRuntimeBasePrompt", () => {
+ it("includes agent messaging instructions when subagents are available and persistent sessions are enabled", () => {
+ const prompt = composeRuntimeBasePrompt({
+ persistentSubagentSessions: true,
+ subagentsAvailable: true,
+ });
+
+ expect(prompt).toContainEqual(expect.stringContaining("Pass `agentId`"));
+ expect(prompt).toContainEqual(expect.stringContaining("<agents>"));
+ });
+
+ it("omits agent messaging instructions when persistent sessions are not enabled", () => {
+ const prompt = composeRuntimeBasePrompt({
+ subagentsAvailable: true,
+ });
+
+ expect(prompt).not.toContainEqual(expect.stringContaining("Pass `agentId`"));
+ expect(prompt).not.toContainEqual(expect.stringContaining("<agents>"));
+ });
+
+ it("omits agent messaging instructions when subagents are unavailable", () => {
+ const prompt = composeRuntimeBasePrompt({
+ persistentSubagentSessions: true,
+ subagentsAvailable: false,
+ });
+
+ expect(prompt).not.toContainEqual(expect.stringContaining("Pass `agentId`"));
+ expect(prompt).not.toContainEqual(expect.stringContaining("<agents>"));
+ });
+});
diff --git a/packages/eve/src/runtime/prompt/compose.ts b/packages/eve/src/runtime/prompt/compose.ts
index 16bad0192..b9233018c 100644
--- a/packages/eve/src/runtime/prompt/compose.ts
+++ b/packages/eve/src/runtime/prompt/compose.ts
@@ -11,6 +11,9 @@ import { formatConnectionsSection } from "#runtime/prompt/connections.js";
const PARALLEL_ACTION_INSTRUCTION =
"Tool execution\nA single tool or subagent call runs as one serial action. If you call multiple independent tools or subagents in one response, eve treats that batch as parallel work. Only batch work that is independent and does not rely on another call in the same response.";
+const AGENT_MESSAGING_INSTRUCTION =
+ "Agent messaging\nAgents you have already delegated to stay available after they answer. The system-message `<agents>` list is only a record of those existing agents — their `agentId`, name, and latest status. It does not limit which subagent tools you can call: your tool list is the source of truth, and any subagent tool can always be called without `agentId` to start a new agent, including when the `<agents>` list is empty or absent. Pass `agentId` to the same subagent tool only to continue one of those existing agents' sessions.";
+
/**
* Input for composing the base authored instructions prompt for one
* resolved agent.
@@ -18,7 +21,14 @@ const PARALLEL_ACTION_INSTRUCTION =
interface ComposeRuntimeBasePromptInput {
connections?: readonly ResolvedConnectionDefinition[];
instructions?: ResolvedInstructionsDefinition;
+ /**
+ * Whether the agent opted into `experimental.subagentPersistentSessions`.
+ * Gates the agent-messaging prompt block that documents `agentId`
+ * continuation and the `<agents>` listing.
+ */
+ persistentSubagentSessions?: boolean;
skills?: readonly ResolvedSkillDefinition[];
+ subagentsAvailable?: boolean;
toolsAvailable?: boolean;
workspaceSpec?: WorkspaceRuntimeSpec;
}
@@ -32,6 +42,9 @@ export function composeRuntimeBasePrompt(input: ComposeRuntimeBasePromptInput):
...createInstructionsPromptBlocks(input.instructions),
...createWorkspacePromptBlocks(input.workspaceSpec),
...(input.toolsAvailable ? [PARALLEL_ACTION_INSTRUCTION] : []),
+ ...(input.subagentsAvailable && input.persistentSubagentSessions
+ ? [AGENT_MESSAGING_INSTRUCTION]
+ : []),
...createConnectionsPromptBlocks(input.connections),
...createSkillsPromptBlocks(input.skills),
];
diff --git a/packages/eve/src/runtime/resolve-agent-graph.ts b/packages/eve/src/runtime/resolve-agent-graph.ts
index 58b625c12..ab0858cd7 100644
--- a/packages/eve/src/runtime/resolve-agent-graph.ts
+++ b/packages/eve/src/runtime/resolve-agent-graph.ts
@@ -215,6 +215,7 @@ async function resolveRuntimeAgentNode(
workspaceResourceRoot: agent.workspaceResourceRoot,
});
const subagentRegistry = createRuntimeSubagentRegistry({
+ persistentSessions: agent.config.experimental?.subagentPersistentSessions === true,
reservedToolNames: [
LOAD_SKILL_TOOL_NAME,
...toolRegistry.preparedTools.map((tool) => tool.name),
diff --git a/packages/eve/src/runtime/subagents/registry.ts b/packages/eve/src/runtime/subagents/registry.ts
index de47a2f01..8a3f58df9 100644
--- a/packages/eve/src/runtime/subagents/registry.ts
+++ b/packages/eve/src/runtime/subagents/registry.ts
@@ -6,6 +6,7 @@ import type {
ResolvedDynamicSubagentDefinition,
ResolvedRuntimeDelegationNode,
} from "#runtime/types.js";
+import type { JsonObject } from "#shared/json.js";
import { serializeInputSchema } from "#shared/tool-schema.js";
/**
@@ -51,16 +52,49 @@ export const SUBAGENT_TOOL_INPUT_SCHEMA = z.strictObject({
.optional(),
});
+/**
+ * Extended subagent tool input schema for agents that opt into
+ * `experimental.subagentPersistentSessions`: adds the `agentId` field the
+ * model uses to continue a previous delegation.
+ */
+export const PERSISTENT_SUBAGENT_TOOL_INPUT_SCHEMA = SUBAGENT_TOOL_INPUT_SCHEMA.extend({
+ agentId: z
+ .string()
+ .nullable()
+ .describe(
+ "Only pass this to continue a previous delegation: the id of an agent from the <agents> list. To start a new agent — the common case — omit this field entirely (or pass null or an empty string).",
+ )
+ .optional(),
+});
+
const SUBAGENT_TOOL_INPUT_JSON_SCHEMA = serializeInputSchema(SUBAGENT_TOOL_INPUT_SCHEMA);
+const PERSISTENT_SUBAGENT_TOOL_INPUT_JSON_SCHEMA = serializeInputSchema(
+ PERSISTENT_SUBAGENT_TOOL_INPUT_SCHEMA,
+);
+
+/** Selects the serialized subagent tool input schema for one agent's opt-in state. */
+export function getSubagentToolInputJsonSchema(persistentSessions: boolean): JsonObject {
+ return persistentSessions
+ ? PERSISTENT_SUBAGENT_TOOL_INPUT_JSON_SCHEMA
+ : SUBAGENT_TOOL_INPUT_JSON_SCHEMA;
+}
+
/**
* Builds the runtime-owned registry for the resolved subagents visible from one
* runtime agent node.
*/
export function createRuntimeSubagentRegistry(input: {
+ /**
+ * Whether the owning agent opted into
+ * `experimental.subagentPersistentSessions`. Adds the model-visible
+ * `agentId` continuation field to every lowered subagent tool schema.
+ */
+ readonly persistentSessions?: boolean;
readonly reservedToolNames?: readonly string[];
readonly subagents: readonly ResolvedRuntimeDelegationNode[];
}): RuntimeSubagentRegistry {
+ const inputSchema = getSubagentToolInputJsonSchema(input.persistentSessions === true);
const preparedTools: PreparedRuntimeDelegationTool[] = [];
const dynamicNodeIds = new Set<string>();
const dynamicResolvers: ResolvedDynamicSubagentResolver[] = [];
@@ -87,7 +121,7 @@ export function createRuntimeSubagentRegistry(input: {
let registeredSubagent: RuntimeRegisteredSubagent;
const dynamic = subagentDefinition.kind === "subagent" ? subagentDefinition.dynamic : undefined;
if (dynamic === undefined) {
- const prepared = createPreparedRuntimeSubagentTool(subagentDefinition);
+ const prepared = createPreparedRuntimeSubagentTool(subagentDefinition, inputSchema);
registeredSubagent = {
definition: subagentDefinition,
prepared,
@@ -127,13 +161,14 @@ export function createRuntimeSubagentRegistry(input: {
export function createPreparedRuntimeSubagentTool(
definition: ResolvedRuntimeDelegationNode,
+ inputSchema: JsonObject = SUBAGENT_TOOL_INPUT_JSON_SCHEMA,
): PreparedRuntimeDelegationTool {
if (definition.description === undefined) {
throw new Error(`Static subagent "${definition.name}" is missing a description.`);
}
return {
description: definition.description,
- inputSchema: SUBAGENT_TOOL_INPUT_JSON_SCHEMA,
+ inputSchema,
kind: definition.kind,
logicalPath: definition.logicalPath,
name: definition.name,
diff --git a/packages/eve/test/runtime-subagent-registry.test.ts b/packages/eve/test/runtime-subagent-registry.test.ts
index 4bd6976ce..3ebd21c1f 100644
--- a/packages/eve/test/runtime-subagent-registry.test.ts
+++ b/packages/eve/test/runtime-subagent-registry.test.ts
@@ -1,7 +1,10 @@
import { describe, expect, it } from "vitest";
import { RuntimeRegistryError } from "../src/internal/runtime-registry.js";
-import { createRuntimeSubagentRegistry } from "../src/runtime/subagents/registry.js";
+import {
+ createRuntimeSubagentRegistry,
+ PERSISTENT_SUBAGENT_TOOL_INPUT_SCHEMA,
+} from "../src/runtime/subagents/registry.js";
import type { ResolvedRuntimeSubagentNode } from "../src/runtime/types.js";
const SUBAGENT_TOOL_INPUT_SCHEMA = {
@@ -18,6 +21,15 @@ const SUBAGENT_TOOL_INPUT_SCHEMA = {
} as const;
describe("createRuntimeSubagentRegistry", () => {
+ it("accepts null as an omitted persistent agentId", () => {
+ expect(
+ PERSISTENT_SUBAGENT_TOOL_INPUT_SCHEMA.parse({
+ agentId: null,
+ message: "Investigate this",
+ }),
+ ).toEqual({ agentId: null, message: "Investigate this" });
+ });
+
it("lowers local subagent inputs into serializable model-visible tools with a uniform messaging schema", () => {
const registry = createRuntimeSubagentRegistry({
subagents: [