The Open Framework for Building Agents
feat(eve): graduate persistent subagent sessions (#2506)
Ruif439e3ddd6b5
diff --git a/.changeset/normalize-task-persistent-sessions.md b/.changeset/normalize-task-persistent-sessions.mdnew file mode 100644index 000000000..cdb54ffc0--- /dev/null+++ b/.changeset/normalize-task-persistent-sessions.md@@ -0,0 +1,5 @@+---+"eve": minor+---++Persistent subagent sessions are now the default: subagent tools expose `agentId`, completed children remain available for follow-up messages, and eve publishes the `<agents>` listing automatically. Remove `experimental.subagentPersistentSessions` from agent configuration; `false` is no longer an opt-out.diff --git a/docs/agent-config.md b/docs/agent-config.mdindex 614e4a5f0..b783e7991 100644--- a/docs/agent-config.md+++ b/docs/agent-config.md@@ -172,7 +172,7 @@ is queued while the existing prompt stays pending; eve does not raise anothercopy. The reply is processed once the budget is granted.Sessions that cannot reach a human — task-mode runs such as schedules and-subagents without input proxying — skip the prompt and fail the next model+delegated runs without input proxying — skip the prompt and fail the next modelcall with `SESSION_TOKEN_LIMIT_REACHED`. A delegated task with no inheritedquota also fails instead of raising a continuation prompt that could onlygrant another zero-token window.@@ -239,7 +239,7 @@ installed package must stay external in hosted output, list it in| `modelOptions` | `AgentModelOptionsDefinition` | none | Provider option overrides forwarded to the model call. || `limits` | `AgentLimitsDefinition` | field-specific | Framework-owned runtime limits. Sessions complete after 30 days by default; token-limit defaults and inheritance are described above. Set a limit to `false` to disable it. || `experimental` | `{ workflow?: { world?: string } }` | unset | Opt-in settings that can change or disappear in any release. Treat them as unstable. `workflow.world` selects the Workflow world package backing session state, queues, hooks, and streams on the root agent. |-| `outputSchema` | Standard Schema or a JSON Schema object | none | Structured return type for task-mode runs (a subagent, schedule, or remote job). Interactive conversation turns ignore it unless the client supplies a per-message schema. |+| `outputSchema` | Standard Schema or a JSON Schema object | none | Structured return type for function-like invocations such as a subagent turn, schedule, or remote job. Ordinary interactive turns ignore it unless the client supplies a per-message schema. || `build` | `{ externalDependencies?: string[] }` | none | Hosted-build packaging controls. `externalDependencies` keeps listed packages external while eve compiles authored modules such as tools and channels, and traces those packages into the hosted output. |`externalDependencies` is a packaging control only. It keeps selected packages as runtime dependencies in the hosted output; it does not authorize, configure, or review any third-party service those packages may call.diff --git a/docs/guides/auth-and-route-protection.md b/docs/guides/auth-and-route-protection.mdindex 93ef3c90a..dc58df5de 100644--- a/docs/guides/auth-and-route-protection.md+++ b/docs/guides/auth-and-route-protection.md@@ -243,7 +243,7 @@ When the predicate accepts a create request, `ctx.session.auth.current` and `.in> ⚠️ Both deployments must support continuation forwarding before you resume persistent remote sessions. A create-only receiver rejects a forwarded continuation with HTTP 400; the sender does not fall back to service authority. See [Forwarding the caller identity](./remote-agents#forwarding-the-caller-identity) for the upgrade behavior.-Persistent sessions do not preserve caller authority between turns. Every accepted follow-up replaces `auth.current`, including replacing it with no authenticated caller on internal local delivery; per-user connection lookup is then keyed from that current principal. This prevents a later caller from resolving a prior caller's OAuth grant. It does not hide the persistent session's conversation history or artifacts from a caller who is otherwise allowed to continue that session; session ownership remains an application policy.+Subagent sessions are persistent by default, but they do not preserve caller authority between turns. Every accepted follow-up replaces `auth.current`, including replacing it with no authenticated caller on internal local delivery; per-user connection lookup is then keyed from that current principal. This prevents a later caller from resolving a prior caller's OAuth grant. It does not hide the persistent session's conversation history or artifacts from a caller who is otherwise allowed to continue that session; session ownership remains an application policy.## What reaches `ctx.session.auth`diff --git a/docs/guides/client/output-schema.mdx b/docs/guides/client/output-schema.mdxindex a80024132..ba7a542b5 100644--- a/docs/guides/client/output-schema.mdx+++ b/docs/guides/client/output-schema.mdx@@ -119,10 +119,10 @@ const followUp = await followUpResponse.result();console.log(followUp.data); // undefined unless this turn also requested a schema```-For task-mode output that belongs to the agent or subagent definition itself, see [`agent.ts`](../../agent-config#other-defineagent-fields) and [Subagents](../../subagents).+For configured output that belongs to the agent or subagent definition itself, see [`agent.ts`](../../agent-config#other-defineagent-fields) and [Subagents](../../subagents).## What to read next- [Messages](./messages): send turns with `send()`- [Streaming](./streaming): handle `result.completed` live-- [`agent.ts`](../../agent-config#other-defineagent-fields): configured task-mode output+- [`agent.ts`](../../agent-config#other-defineagent-fields): configured output for function-like invocationsdiff --git a/docs/guides/remote-agents.md b/docs/guides/remote-agents.mdindex 3291ff8fe..a4ab1436d 100644--- a/docs/guides/remote-agents.md+++ b/docs/guides/remote-agents.md@@ -20,15 +20,15 @@ export default defineRemoteAgent({`defineRemoteAgent` accepts:-| Parameter | Type | Required | Default | Description |-| ------------------ | --------------------------------------------- | -------- | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |-| `url` | `string \| (() => string \| Promise<string>)` | Yes | n/a | Base URL of the remote eve deployment to call. A string is baked at compile time; a function is resolved at runtime (see [Runtime URLs](#runtime-urls)). |-| `description` | `string` | Yes | n/a | Model-visible delegation description. |-| `auth` | `OutboundAuthFn` | No | none | Outbound auth hook from `eve/agents/auth`. |-| `forwardPrincipal` | `boolean` | No | `false` | Forward the dispatching turn's session principal to the remote deployment (see [Forwarding the caller identity](#forwarding-the-caller-identity)). |-| `headers` | `HeadersValue` | No | none | Static or lazily resolved request headers. |-| `path` | `string` | No | `/eve/v1/session` | Route appended to `url` for the create-session request. |-| `outputSchema` | `StandardSchema \| JSON Schema` | No | none | Structured return type the caller requires. Enforced by the remote agent like any task-mode output schema. Set it on the definition to apply to every call, or override it per call. |+| Parameter | Type | Required | Default | Description |+| ------------------ | --------------------------------------------- | -------- | ----------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `url` | `string \| (() => string \| Promise<string>)` | Yes | n/a | Base URL of the remote eve deployment to call. A string is baked at compile time; a function is resolved at runtime (see [Runtime URLs](#runtime-urls)). |+| `description` | `string` | Yes | n/a | Model-visible delegation description. |+| `auth` | `OutboundAuthFn` | No | none | Outbound auth hook from `eve/agents/auth`. |+| `forwardPrincipal` | `boolean` | No | `false` | Forward the dispatching turn's session principal to the remote deployment (see [Forwarding the caller identity](#forwarding-the-caller-identity)). |+| `headers` | `HeadersValue` | No | none | Static or lazily resolved request headers. |+| `path` | `string` | No | `/eve/v1/session` | Route appended to `url` for the create-session request. |+| `outputSchema` | `StandardSchema \| JSON Schema` | No | none | Structured return type for the first turn of each fresh remote session. A continuation may provide its own per-call schema. |## Dynamic remote agents@@ -82,7 +82,7 @@ The function may be async and must return a non-empty string. `auth` and `headerTo the model, a remote agent is another subagent tool. You call it the same way you call a local subagent, with a `message` and an optional `outputSchema`. The message must carry the full task, including any context the remote agent needs, because it never receives the parent's conversation history.-To get one structured result back instead of an open-ended reply, set an `outputSchema` on the agent definition or on an individual call. The remote agent then runs in task mode, a single-shot delegation that returns structured output as the tool result. See [Subagents](../subagents) for how task mode works.+To require structured output, set an `outputSchema` on the agent definition for fresh delegations or on an individual call for that turn. The structured value becomes the tool result, and the remote child remains available for follow-up messages. See [Subagents](../subagents) for continuation behavior.## Outbound auth@@ -130,7 +130,7 @@ A receiver on an eve version that predates all principal forwarding may insteadA local subagent runs inline. A remote one runs in its own deployment, so dispatch is asynchronous:-1. The parent starts a task-mode session on the remote's `POST /eve/v1/session`, passing a framework callback URL.+1. The parent starts a persistent conversation session on the remote's `POST /eve/v1/session`, passing a framework callback URL.2. The parent turn parks (suspends durably without holding compute; see [Execution model & durability](../concepts/execution-model-and-durability)) until the remote posts a terminal callback.3. When the callback arrives, the parent resumes and surfaces the result.@@ -138,6 +138,8 @@ The parent stream carries the same `subagent.called`, `action.result`, and `subaCancelling the parent while a remote call is active sends an authenticated `POST /eve/v1/session/:childSessionId/cancel` to the remote and waits for that request to be accepted before the parent settles. eve resolves the remote's `headers` and `auth` again for every cancellation attempt, so rotating credentials work the same way as they do for session creation. Cancellation always uses the standard eve cancel path on `url`, even when `path` customizes only the create-session endpoint. The remote child reports `turn.cancelled` → `session.waiting` on its own stream; an older or unreachable remote is logged but cannot turn the parent's cancellation into a failure.+When the parent session ends, eve sends an authenticated `POST /eve/v1/session/:childSessionId/reset` for each remote child. Reset retires the parked remote session and recursively cleans up its descendants. The request uses freshly resolved `headers` and `auth`; failures are logged so an unreachable remote cannot block parent finalization.+Both failure paths surface to the parent as a failed tool result, so the caller can explain or recover within the same session. A failed _start_ returns the error inline. A remote that starts and then fails posts a terminal failure callback, which the parent receives as an errored subagent result carrying the remote's error (or `REMOTE_AGENT_FAILED` when none is supplied). Terminal callback delivery runs as a durable step on the underlying workflow engine (see [Execution model & durability](../concepts/execution-model-and-durability)). A failed callback POST is rethrown rather than marking the task complete, so the engine retries it.## What to read nextdiff --git a/docs/subagents/index.mdx b/docs/subagents/index.mdxindex 9d7e2cfd3..1ce7a710a 100644--- a/docs/subagents/index.mdx+++ b/docs/subagents/index.mdx@@ -3,22 +3,20 @@ title: "Subagents"description: "Delegate work to root-agent copies or declared specialists with their own tools and sandbox."----eve supports two ways to delegate work: the root-only built-in `agent` tool, which runs a fresh copy of the root agent, and declared subagents, which are specialists with their own directories. Use a subagent to run independent work in parallel, narrow the available tools, or give a task to a specialist.+eve supports two ways to delegate work: the root-only built-in `agent` tool, which starts or continues a copy of the root agent, and declared subagents, which are specialists with their own directories. Use a subagent to run independent work in parallel, narrow the available tools, or give a task to a specialist.## The built-in `agent` tool-The root session receives `agent` by default. The model calls it to delegate a task to a fresh copy of the root agent:+The root session receives `agent` by default. The model calls it to delegate a task to a new copy of the root agent or continue an existing copy:```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+ agentId?: string; // continue an existing child+ outputSchema?: object; // require structured output for this turn}```-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.@@ -149,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 — 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.+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, agentId?, outputSchema? }` shape. The parent packs `message` with everything the child needs, since the child never sees the parent's history. Set `outputSchema` to require structured output for that turn; the child remains available for follow-up messages afterward.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.@@ -160,8 +158,8 @@ A directly declared subagent's tool name is the bare path-derived name, with no```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+ agentId?: string; // continue an existing child+ outputSchema?: object; // require structured output for this turn}```@@ -177,26 +175,11 @@ Subagent model calls automatically retry classified transient provider failures,## 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.+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.Whenever the set of parked (resumable) children changes, eve appends a framework-injected note to the conversation — labeled `[Agents]` and carrying an `<agents>` block — listing each child's `agentId`, name, and latest status. The static system prompt tells the model the note is injected by eve, not written by the user. The note is appended only when the listing changes (an append-only design that preserves the provider prompt cache), the most recent note is authoritative, 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.+The parent holds agent handles only for its session lifetime. When the parent session ends, eve terminates local children and sends authenticated reset requests for remote children. Remote reset is best-effort: an unreachable deployment may retain the parked child until its own session deadline. For [remote agents](./guides/remote-agents), upgrade both deployments before relying on continuation or reset behavior introduced by a newer eve version.## When to splitdiff --git a/e2e/fixtures/agent-cancellation/agent/agent.ts b/e2e/fixtures/agent-cancellation/agent/agent.tsindex b3c2be2c3..653b3dd63 100644--- a/e2e/fixtures/agent-cancellation/agent/agent.ts+++ b/e2e/fixtures/agent-cancellation/agent/agent.ts@@ -18,8 +18,4 @@ const base = e2eAgentConfig({export default defineAgent({...base,- // Persistent children keep the cancelled sleeper in the model-visible- // [Agents] listing, which the cancel-subagent eval inspects after a- // cascaded cancellation.- experimental: { ...base.experimental, subagentPersistentSessions: true },});diff --git a/e2e/fixtures/agent-subagents/agent/agent.ts b/e2e/fixtures/agent-subagents/agent/agent.tsindex 9d0d1ecfe..0bc59390a 100644--- a/e2e/fixtures/agent-subagents/agent/agent.ts+++ b/e2e/fixtures/agent-subagents/agent/agent.ts@@ -9,13 +9,5 @@ const base = e2eAgentConfig();export default defineAgent({...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-tools-sandbox/agent/lib/mock-responder.ts b/e2e/fixtures/agent-tools-sandbox/agent/lib/mock-responder.tsindex 31f64aef5..e3676fbe1 100644--- a/e2e/fixtures/agent-tools-sandbox/agent/lib/mock-responder.ts+++ b/e2e/fixtures/agent-tools-sandbox/agent/lib/mock-responder.ts@@ -12,8 +12,16 @@ const SKILL_DIRECTIVE = /load the `([^`]+)` skill/iu;*/export function respond(request: MockModelRequest): MockModelResponse | string {const message = request.lastUserMessage ?? "";- const roles = request.messages.map((entry) => entry.role);- const turnHasToolResult = roles.lastIndexOf("tool") > roles.lastIndexOf("user");+ let lastAuthoredUserIndex = -1;+ let lastToolResultIndex = -1;+ for (let index = 0; index < request.messages.length; index += 1) {+ const entry = request.messages[index]!;+ if (entry.role === "tool") lastToolResultIndex = index;+ if (entry.role === "user" && !entry.text.trim().startsWith("[Agents]")) {+ lastAuthoredUserIndex = index;+ }+ }+ const turnHasToolResult = lastToolResultIndex > lastAuthoredUserIndex;const subagent = SUBAGENT_DIRECTIVE.exec(message);if (subagent?.[1] !== undefined && subagent[2] !== undefined) {diff --git a/packages/eve/extension-contracts/reports/subagent/v3.json b/packages/eve/extension-contracts/reports/subagent/v3.jsonnew file mode 100644index 000000000..b09da1411--- /dev/null+++ b/packages/eve/extension-contracts/reports/subagent/v3.json@@ -0,0 +1,20 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "subagent",+ "epoch": 3,+ "sha256": "539a5ddb907e4324356534f7a2479887b6a00dfc702e5e6f9bdaf4313266628d",+ "exports": [+ "AgentCompactionDefinition",+ "AgentDefinition",+ "AgentModelDefinition",+ "AgentStaticModelDefinition",+ "DefinedAgent",+ "DynamicLocalSubagentDefinition",+ "DynamicSubagentDefinition",+ "RemoteAgentDefinition",+ "RemoteAgentDefinitionInput",+ "defineAgent",+ "defineDynamic",+ "defineRemoteAgent"+ ]+}diff --git a/packages/eve/src/compiler/extension-compatibility.ts b/packages/eve/src/compiler/extension-compatibility.tsindex d85750b4c..300629107 100644--- a/packages/eve/src/compiler/extension-compatibility.ts+++ b/packages/eve/src/compiler/extension-compatibility.ts@@ -33,7 +33,14 @@ const EXTENSION_CAPABILITY_CONTRACTS = {},channel: { current: 9, supported: [1, 2, 3, 4, 5, 6, 7, 8, 9], dropped: {} },schedule: { current: 3, supported: [1, 2, 3], dropped: {} },- subagent: { current: 2, supported: [1, 2], dropped: {} },+ subagent: {+ current: 3,+ supported: [3],+ dropped: {+ 1: "Persistent subagent sessions are now the default and the experimental opt-in was removed",+ 2: "Persistent subagent sessions are now the default and the experimental opt-in was removed",+ },+ },connection: {current: 6,supported: [1, 2, 3, 4, 5, 6],diff --git a/packages/eve/src/compiler/manifest.test.ts b/packages/eve/src/compiler/manifest.test.tsindex 9dc710c81..d1fb3b053 100644--- a/packages/eve/src/compiler/manifest.test.ts+++ b/packages/eve/src/compiler/manifest.test.ts@@ -121,4 +121,18 @@ describe("compiled agent manifest v43", () => {"subagent graph contains a cycle",);});++ it("rejects the removed persistent-session field in compiled manifests", async () => {+ const { manifest } = await compileFromMemory({ model: "openai/gpt-5.4" });++ expect(() =>+ compiledAgentManifestSchema.parse({+ ...manifest,+ config: {+ ...manifest.config,+ experimental: { subagentPersistentSessions: true },+ },+ }),+ ).toThrow();+ });});diff --git a/packages/eve/src/compiler/manifest.ts b/packages/eve/src/compiler/manifest.tsindex ae7c471f9..2f0667c0b 100644--- a/packages/eve/src/compiler/manifest.ts+++ b/packages/eve/src/compiler/manifest.ts@@ -586,7 +586,6 @@ const compiledAgentConfigBaseFields = {experimental: z.object({instrumentationProviders: z.boolean().optional(),- subagentPersistentSessions: z.boolean().optional(),tasks: z.boolean().optional(),workflow: compiledAgentWorkflowDefinitionSchema.optional(),})@@ -1112,7 +1111,6 @@ function cloneCompiledAgentDefinition(config: CompiledAgentDefinition): Compiled? undefined: {instrumentationProviders: config.experimental.instrumentationProviders,- subagentPersistentSessions: config.experimental.subagentPersistentSessions,tasks: config.experimental.tasks,workflow:config.experimental.workflow === undefineddiff --git a/packages/eve/src/compiler/normalize-agent-config.ts b/packages/eve/src/compiler/normalize-agent-config.tsindex dfe44f4f4..691113f14 100644--- a/packages/eve/src/compiler/normalize-agent-config.ts+++ b/packages/eve/src/compiler/normalize-agent-config.ts@@ -180,10 +180,6 @@ function normalizeExperimentalDefinition(compiledExperimental.instrumentationProviders = experimental.instrumentationProviders;}- if (experimental.subagentPersistentSessions !== undefined) {- compiledExperimental.subagentPersistentSessions = experimental.subagentPersistentSessions;- }-if (experimental.tasks !== undefined) {compiledExperimental.tasks = experimental.tasks;}diff --git a/packages/eve/src/context/dynamic-subagent-lifecycle.test.ts b/packages/eve/src/context/dynamic-subagent-lifecycle.test.tsindex 01e06d0ae..6ed80ef53 100644--- a/packages/eve/src/context/dynamic-subagent-lifecycle.test.ts+++ b/packages/eve/src/context/dynamic-subagent-lifecycle.test.ts@@ -22,7 +22,6 @@ describe("dynamic subagent lifecycle", () => {ctx,event: createSessionStartedEvent(),messages: [],- persistentSessions: false,resolvers: [resolver],});@@ -42,7 +41,6 @@ describe("dynamic subagent lifecycle", () => {ctx,event: createSessionStartedEvent(),messages: [],- persistentSessions: false,resolvers: [resolver],});@@ -77,7 +75,6 @@ describe("dynamic subagent lifecycle", () => {ctx,event: createSessionStartedEvent(),messages: [],- persistentSessions: false,resolvers: [resolver],});expect(buildDynamicSubagentTools(ctx)).toHaveLength(1);@@ -86,7 +83,6 @@ describe("dynamic subagent lifecycle", () => {ctx,event: createTurnStartedEvent({ sequence: 0, turnId: "turn-1" }),messages: [],- persistentSessions: false,resolvers: [resolver],});expect(buildDynamicSubagentTools(ctx)).toEqual([]);@@ -120,7 +116,6 @@ describe("dynamic subagent lifecycle", () => {ctx,event: createSessionStartedEvent(),messages: [],- persistentSessions: false,resolvers: [resolver],});const sessionSelection = getDynamicSubagentSelection(ctx, resolver.nodeId);@@ -133,7 +128,6 @@ describe("dynamic subagent lifecycle", () => {ctx,event: createTurnStartedEvent({ sequence: 0, turnId: "turn-1" }),messages: [],- persistentSessions: false,resolvers: [resolver],});const turnSelection = getDynamicSubagentSelection(ctx, resolver.nodeId);@@ -175,7 +169,6 @@ describe("dynamic subagent lifecycle", () => {ctx,event: createSessionStartedEvent(),messages: [],- persistentSessions: true,resolvers: [resolver],});@@ -221,7 +214,6 @@ describe("dynamic subagent lifecycle", () => {ctx,event: createSessionStartedEvent(),messages: [],- persistentSessions: false,resolvers: [resolver],});@@ -241,7 +233,6 @@ describe("dynamic subagent lifecycle", () => {ctx,event: createSessionStartedEvent(),messages: [],- persistentSessions: false,resolvers: [resolver],runtimeRevision: "deployment:one",});@@ -249,7 +240,6 @@ 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.tsindex 30d6682e0..ad45a9291 100644--- a/packages/eve/src/context/dynamic-subagent-lifecycle.ts+++ b/packages/eve/src/context/dynamic-subagent-lifecycle.ts@@ -18,10 +18,7 @@ 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,- getSubagentToolInputJsonSchema,-} from "#runtime/subagents/registry.js";+import { createPreparedRuntimeSubagentTool } 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";@@ -35,10 +32,8 @@ 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];@@ -55,21 +50,18 @@ 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,- },- inputSchema,- );+ 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,+ });return [resolver.nodeId, { kind: "remote", prepared, remoteAgent }] as const;}@@ -80,18 +72,15 @@ async function resolveSelections(input: {value: result,});const resolvedAgentConfig = await agentConfig;- const prepared = createPreparedRuntimeSubagentTool(- {- description: resolvedAgentConfig.description,- kind: "subagent",- logicalPath: resolver.logicalPath,- name: resolver.name,- nodeId: resolver.nodeId,- sourceId: resolver.sourceId,- sourceKind: resolver.sourceKind,- },- inputSchema,- );+ const prepared = createPreparedRuntimeSubagentTool({+ description: resolvedAgentConfig.description,+ kind: "subagent",+ logicalPath: resolver.logicalPath,+ name: resolver.name,+ nodeId: resolver.nodeId,+ sourceId: resolver.sourceId,+ sourceKind: resolver.sourceKind,+ });return [resolver.nodeId,@@ -130,7 +119,6 @@ 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)) {@@ -153,7 +141,6 @@ 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-messaging.scenario.test.ts b/packages/eve/src/execution/agent-messaging.scenario.test.tsindex 4b027bf14..744c19cef 100644--- a/packages/eve/src/execution/agent-messaging.scenario.test.ts+++ b/packages/eve/src/execution/agent-messaging.scenario.test.ts@@ -79,9 +79,6 @@ const model = mockModel((request) => {});export default defineAgent({- experimental: {- subagentPersistentSessions: true,- },model,modelContextWindowTokens: 32_000,});diff --git a/packages/eve/src/execution/delegated-parent-notification.test.ts b/packages/eve/src/execution/delegated-parent-notification.test.tsindex 31fe8cea3..2bb80db6b 100644--- a/packages/eve/src/execution/delegated-parent-notification.test.ts+++ b/packages/eve/src/execution/delegated-parent-notification.test.ts@@ -469,7 +469,58 @@ describe("turn caller notification", () => {});});-describe("task turn caller binding", () => {+describe("turn caller binding", () => {+ it("rebinds local adapter forwarding to a non-task continuation caller", async () => {+ await expect(+ bindTurnCallerContextStep({+ caller: {+ callId: "call-new",+ replyTo: { kind: "hook", token: "turn-new" },+ subagentName: "research",+ },+ serializedContext: {+ [ChannelKey.name]: {+ kind: SUBAGENT_ADAPTER_KIND,+ state: {+ callId: "call-old",+ parentContinuationToken: "turn-old",+ parentSessionId: "parent",+ subagentName: "research",+ },+ },+ },+ }),+ ).resolves.toMatchObject({+ [ChannelKey.name]: {+ state: { callId: "call-new", parentContinuationToken: "turn-new" },+ },+ });+ });++ it("rebinds remote callback forwarding to a non-task continuation caller", async () => {+ await expect(+ bindTurnCallerContextStep({+ caller: {+ callId: "call-new",+ replyTo: {+ kind: "callback",+ token: "turn-new",+ url: "https://parent.example/eve/v1/callback/turn-new",+ },+ subagentName: "research",+ },+ serializedContext: {},+ }),+ ).resolves.toEqual({+ [SessionCallbackKey.name]: {+ callId: "call-new",+ subagentName: "research",+ token: "turn-new",+ url: "https://parent.example/eve/v1/callback/turn-new",+ },+ });+ });+it("rebinds local adapter forwarding to the current task", async () => {const serializedContext = {[ChannelKey.name]: {diff --git a/packages/eve/src/execution/delegated-parent-notification.ts b/packages/eve/src/execution/delegated-parent-notification.tsindex 26c663af5..41157d815 100644--- a/packages/eve/src/execution/delegated-parent-notification.ts+++ b/packages/eve/src/execution/delegated-parent-notification.ts@@ -288,7 +288,7 @@ export async function resolveInitialTurnCallerStep(input: {};}-/** Rebinds child event forwarding to the task that owns the next accepted turn. */+/** Rebinds child event forwarding to the caller that owns the next accepted turn. */export async function bindTurnCallerContextStep(input: {readonly caller: TurnCaller | undefined;readonly serializedContext: Record<string, unknown>;@@ -296,17 +296,18 @@ export async function bindTurnCallerContextStep(input: {"use step";const caller = input.caller;- if (caller?.taskId === undefined) return input.serializedContext;+ if (caller === undefined) return input.serializedContext;if (caller.replyTo.kind === "callback") {+ const callback = {+ callId: caller.callId,+ subagentName: caller.subagentName,+ token: caller.replyTo.token,+ url: caller.replyTo.url,+ };return {...input.serializedContext,- [SessionCallbackKey.name]: {- callId: caller.callId,- subagentName: caller.subagentName,- taskId: caller.taskId,- token: caller.replyTo.token,- url: caller.replyTo.url,- },+ [SessionCallbackKey.name]:+ caller.taskId === undefined ? callback : { ...callback, taskId: caller.taskId },};}@@ -317,7 +318,7 @@ export async function bindTurnCallerContextStep(input: {Reflect.get(adapter, "kind") !== SUBAGENT_ADAPTER_KIND ||!isSubagentAdapterState(Reflect.get(adapter, "state"))) {- throw new Error("Task-owned local turn is missing its subagent adapter binding.");+ throw new Error("Delegated local turn is missing its subagent adapter binding.");}const state = Reflect.get(adapter, "state") as SubagentAdapterState;return {diff --git a/packages/eve/src/execution/dispatch-runtime-actions-shared.ts b/packages/eve/src/execution/dispatch-runtime-actions-shared.tsindex 8f483b8f9..a600eb934 100644--- a/packages/eve/src/execution/dispatch-runtime-actions-shared.ts+++ b/packages/eve/src/execution/dispatch-runtime-actions-shared.ts@@ -503,7 +503,15 @@ function classifyFreshStart(input: {? registered.definition.description: undefined);const source: SubagentInputSource =- description !== undefined ? { description, type: "local" } : { type: "runtime" };+ description !== undefined+ ? {+ description,+ outputSchema:+ dynamicAgentConfig?.outputSchema ??+ input.bundle.graph?.nodesByNodeId.get(action.nodeId)?.turnAgent?.outputSchema,+ type: "local",+ }+ : { outputSchema: input.bundle.turnAgent.outputSchema, type: "runtime" };return {kind: "start",target: {@@ -544,7 +552,6 @@ export async function startSubagent(input: {readonly initiatorAuth: Parameters<typeof buildSubagentRunInput>[0]["initiatorAuth"];readonly parentContinuationToken: string | undefined;readonly parentTraceContext: Parameters<typeof buildSubagentRunInput>[0]["parentTraceContext"];- readonly persistentSessions: boolean;readonly sandboxSessionId: string;readonly serializedContext: Record<string, unknown>;readonly session: RuntimeSession;@@ -574,7 +581,6 @@ export async function startSubagent(input: {initiatorAuth: input.initiatorAuth,parentContinuationToken: input.parentContinuationToken,parentTraceContext,- persistentSessions: input.persistentSessions,sandboxSessionId: input.sandboxSessionId,session: input.session,source: input.target.source,@@ -592,7 +598,6 @@ export async function startSubagent(input: {initiatorAuth: input.initiatorAuth,parentContinuationToken: input.parentContinuationToken,parentTraceContext,- persistentSessions: input.persistentSessions,session: input.session,taskOwned: input.taskOwned,});diff --git a/packages/eve/src/execution/dispatch-runtime-actions-step.integration.test.ts b/packages/eve/src/execution/dispatch-runtime-actions-step.integration.test.tsindex aba14dc28..8e24a3cba 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@@ -191,7 +191,9 @@ describe("dispatchRuntimeActionsStep child starts", () => {ctx.set(ChannelKey, ADAPTER);ctx.set(BundleKey, {compiledArtifactsSource: {},- resolvedAgent: { config: { experimental: { tasks: true } } },+ resolvedAgent: {+ config: { experimental: { tasks: true } },+ },subagentRegistry: {subagentsByNodeId: new Map([["remote/research", { definition: REMOTE_REGISTRY_DEFINITION }],@@ -645,6 +647,7 @@ describe("dispatchRuntimeActionsStep child starts", () => {expect.objectContaining({address: {callbackBaseUrl: "https://caller.example.com",+ credentialResolver: { resolverId: "remote/research" },kind: "agent/remote",sessionId: "remote-session-123456789012",url: "https://registry.example.com",@@ -1278,7 +1281,9 @@ function installContext(}const bundle = {compiledArtifactsSource: {},- resolvedAgent: { config: tasks ? { experimental: { tasks: true } } : {} },+ resolvedAgent: {+ config: tasks ? { experimental: { tasks: true } } : {},+ },subagentRegistry: { subagentsByNodeId },turnAgent: {id: "test-agent",diff --git a/packages/eve/src/execution/dispatch-runtime-actions-step.ts b/packages/eve/src/execution/dispatch-runtime-actions-step.tsindex 9afdc5a8f..287dbc27d 100644--- a/packages/eve/src/execution/dispatch-runtime-actions-step.ts+++ b/packages/eve/src/execution/dispatch-runtime-actions-step.ts@@ -42,8 +42,6 @@ export async function dispatchRuntimeActionsStep(}const { batch, bundle, session } = prepared;- const persistentSessions =- bundle.resolvedAgent.config?.experimental?.subagentPersistentSessions === true;// Acquired only once preflight can no longer throw, so a planning failure// never leaks the writer lock.const writer = input.parentWritable.getWriter();@@ -92,7 +90,6 @@ export async function dispatchRuntimeActionsStep(initiatorAuth: prepared.initiatorAuth,parentContinuationToken: input.parentContinuationToken,parentTraceContext: prepared.parentTraceContext,- persistentSessions,sandboxSessionId: prepared.sandboxSessionId,serializedContext: prepared.serializedContext,session,diff --git a/packages/eve/src/execution/effective-output-schema.ts b/packages/eve/src/execution/effective-output-schema.tsindex 7fd777513..c90ba4226 100644--- a/packages/eve/src/execution/effective-output-schema.ts+++ b/packages/eve/src/execution/effective-output-schema.ts@@ -10,7 +10,8 @@ import type { RunMode } from "#shared/run-mode.js";* A run-scoped (client-supplied) schema on the turn's {@link StepInput} always* wins. With no run-scoped schema, a task run adopts the agent's declared* return schema — its function-output contract, which only applies when the- * agent is invoked as a function (subagent / schedule / job), i.e. task mode.+ * agent is invoked directly as a task-mode schedule or job. Subagent+ * dispatch carries its declared schema as a run-scoped schema instead.* A conversation run with no run-scoped schema enforces nothing. Continuation* steps (no new `StepInput`) preserve whatever is already in effect.*/diff --git a/packages/eve/src/execution/node-step.ts b/packages/eve/src/execution/node-step.tsindex 31a717225..f1b708cb3 100644--- a/packages/eve/src/execution/node-step.ts+++ b/packages/eve/src/execution/node-step.ts@@ -21,15 +21,14 @@ 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 "#tools/framework/agent-contract.js";-import { createTaskToolHarnessDefinitions } from "#execution/tools/tasks.js";-import type { ResolvedRuntimeAgentNode } from "#runtime/graph.js";-import type { HistoryViewProjector, PreparedHistoryView } from "#shared/history-view.js";import {- PERSISTENT_SUBAGENT_TOOL_INPUT_SCHEMA,+ AGENT_TOOL_DESCRIPTION,+ AGENT_TOOL_NAME,SUBAGENT_TOOL_INPUT_SCHEMA,} from "#tools/framework/agent-contract.js";-+import { createTaskToolHarnessDefinitions } from "#execution/tools/tasks.js";+import type { ResolvedRuntimeAgentNode } from "#runtime/graph.js";+import type { HistoryViewProjector, PreparedHistoryView } from "#shared/history-view.js";import type { PreparedRuntimeTool } from "#runtime/sessions/turn.js";import { findRegisteredRuntimeTool } from "#runtime/tools/registry.js";import type { ResolvedToolDefinition } from "#runtime/types.js";@@ -114,9 +113,6 @@ export function createExecutionNodeStep(input: CreateExecutionNodeStepInput): Stinstrumentation,mode: input.mode,onCompaction: preserveFrameworkStateOnCompaction,- persistentSubagentSessions:- input.node.agent.config?.experimental?.tasks === true ||- input.node.agent.config?.experimental?.subagentPersistentSessions === true,dispatchDynamicModelEvent: dispatchModelEvent,resolveModel,runtimeIdentity: buildRuntimeIdentity(input.node),@@ -238,11 +234,7 @@ function resolveHarnessToolDefinition(input: {if (def.owner.kind === "framework" && def.name === AGENT_TOOL_NAME) {const delegation = {description: AGENT_TOOL_DESCRIPTION,- inputSchema:- input.tasksEnabled ||- input.node.agent.config?.experimental?.subagentPersistentSessions === true- ? PERSISTENT_SUBAGENT_TOOL_INPUT_SCHEMA- : SUBAGENT_TOOL_INPUT_SCHEMA,+ inputSchema: SUBAGENT_TOOL_INPUT_SCHEMA,kind: "subagent" as const,name: AGENT_TOOL_NAME,nodeId: input.node.nodeId,diff --git a/packages/eve/src/execution/remote-agent-dispatch.test.ts b/packages/eve/src/execution/remote-agent-dispatch.test.tsindex 843769038..d368ba413 100644--- a/packages/eve/src/execution/remote-agent-dispatch.test.ts+++ b/packages/eve/src/execution/remote-agent-dispatch.test.ts@@ -7,6 +7,7 @@ import {isAmbiguousRemoteAgentContinueError,isRetryableRemoteAgentCancelError,isRetryableRemoteAgentContinueError,+ resetRemoteAgentSession,resolveRemoteAgentForAction,resolveRemoteAgentStreamHeaders,startRemoteAgentSession,@@ -263,13 +264,13 @@ describe("startRemoteAgentSession", () => {'You are the subagent "research".',"Description: Performs research.","",- "The caller delegated the following task to you. Complete it and return the final result directly.",+ "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.","","Caller message:","find the marker",].join("\n"),capabilities: {},- mode: "task",+ mode: "conversation",});});@@ -398,7 +399,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.mode).toBe("conversation");expect(body.capabilities).toEqual({});});@@ -958,6 +959,67 @@ describe("cancelRemoteAgentTurn", () => {});});+describe("resetRemoteAgentSession", () => {+ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it("retires the exact remote session with fresh auth and a preserved base path", async () => {+ const fetchMock = vi+ .fn()+ .mockResolvedValue(+ Response.json(+ { ok: true, previousSessionId: "remote/session id", status: "reset" },+ { status: 200 },+ ),+ );+ vi.stubGlobal("fetch", fetchMock);++ await expect(+ resetRemoteAgentSession({+ remote: {+ ...createRemoteAgent(),+ url: "https://remote.example.com/eve/agents/researcher/",+ },+ sessionId: "remote/session id",+ }),+ ).resolves.toEqual({+ ok: true,+ previousSessionId: "remote/session id",+ status: "reset",+ });+ expect(fetchMock).toHaveBeenCalledWith(+ "https://remote.example.com/eve/agents/researcher/eve/v1/session/remote%2Fsession%20id/reset",+ {+ body: JSON.stringify({ reason: "Parent session ended" }),+ headers: {+ authorization: "Bearer remote-token",+ "content-type": "application/json",+ "x-static": "yes",+ },+ method: "POST",+ },+ );+ });++ it("accepts an already inactive remote session and rejects a mismatched reset", async () => {+ const fetchMock = vi+ .fn()+ .mockResolvedValueOnce(Response.json({ ok: true, status: "no_active_session" }))+ .mockResolvedValueOnce(+ Response.json({ ok: true, previousSessionId: "other", status: "reset" }),+ );+ vi.stubGlobal("fetch", fetchMock);++ await expect(+ resetRemoteAgentSession({ remote: createRemoteAgent(), sessionId: "remote-session" }),+ ).resolves.toEqual({ ok: true, status: "no_active_session" });+ await expect(+ resetRemoteAgentSession({ remote: createRemoteAgent(), sessionId: "remote-session" }),+ ).rejects.toThrow("response was invalid");+ });+});+function createAction(): RuntimeRemoteAgentCallActionRequest {return {callId: "call-remote",diff --git a/packages/eve/src/execution/remote-agent-dispatch.ts b/packages/eve/src/execution/remote-agent-dispatch.tsindex cd4e71e63..c2bc15907 100644--- a/packages/eve/src/execution/remote-agent-dispatch.ts+++ b/packages/eve/src/execution/remote-agent-dispatch.ts@@ -1,9 +1,11 @@import { z } from "#compiled/zod/index.js";import { CancelTurnResponseSchema } from "#protocol/cancel-turn.js";+import { ResetResponseSchema, type ResetResponse } from "#protocol/reset-session.js";import { AgentHandleError } from "#protocol/agent-handle-error.js";import {createEveCallbackRoutePath,createEveSessionCancelRoutePath,+ createEveSessionResetRoutePath,createEveSessionRoutePath,} from "#protocol/routes.js";import type { CancelTurnResult, SessionAuthContext, SessionTraceContext } from "#channel/types.js";@@ -60,12 +62,6 @@ export async function startRemoteAgentSession(input: {* created instead of starting a second one.*/readonly operationId?: string;- /**- * Whether the dispatching agent opted into- * `experimental.subagentPersistentSessions`. Persistent remote children run- * in conversation mode so their sessions accept follow-up messages.- */- readonly persistentSessions?: boolean;readonly parentTraceContext?: SessionTraceContext;readonly remote: ResolvedRuntimeRemoteAgentNode;readonly session: HarnessSession;@@ -107,10 +103,9 @@ export async function startRemoteAgentSession(input: {},message: formatRemoteAgentCallInputMessage({action: input.action,- persistentSession: input.persistentSessions,remote: input.remote,}),- mode: input.persistentSessions === true ? "conversation" : "task",+ mode: "conversation",outputSchema:normalizeRequestedOutputSchema(input.action.input.outputSchema) ?? input.remote.outputSchema,};@@ -302,12 +297,13 @@ function buildForwardedPrincipalField(input: {}export async function cancelRemoteAgentTurn(input: {- readonly remote: ResolvedRuntimeRemoteAgentNode;+ readonly headers?: Record<string, string>;+ readonly remote: Pick<ResolvedRuntimeRemoteAgentNode, "auth" | "headers" | "name" | "url">;readonly sessionId: string;readonly taskId?: string;readonly turnId?: string;}): Promise<CancelTurnResult> {- const headers = await resolveRemoteAgentRequestHeaders(input.remote);+ const headers = input.headers ?? (await resolveRemoteAgentRequestHeaders(input.remote));const response = await fetch(createRemoteAgentCancelTurnUrl(input.remote, input.sessionId), {body:input.turnId === undefined && input.taskId === undefined@@ -350,6 +346,36 @@ export async function cancelRemoteAgentTurn(input: {: { status: "no_active_turn" };}+/** Retires one exact remote child session through eve's authenticated reset route. */+export async function resetRemoteAgentSession(input: {+ readonly headers?: Record<string, string>;+ readonly remote: Pick<ResolvedRuntimeRemoteAgentNode, "auth" | "headers" | "name" | "url">;+ readonly sessionId: string;+}): Promise<ResetResponse> {+ const headers = input.headers ?? (await resolveRemoteAgentRequestHeaders(input.remote));+ const response = await fetch(+ createRemoteAgentRouteUrl(input.remote.url, createEveSessionResetRoutePath(input.sessionId)),+ {+ body: JSON.stringify({ reason: "Parent session ended" }),+ headers: { "content-type": "application/json", ...headers },+ method: "POST",+ },+ );+ if (!response.ok) {+ throw new Error(+ `Remote agent "${input.remote.name}" reset-session request failed with HTTP ${response.status}.`,+ );+ }+ const result = ResetResponseSchema.safeParse(await response.json());+ if (+ !result.success ||+ (result.data.status === "reset" && result.data.previousSessionId !== input.sessionId)+ ) {+ throw new Error(`Remote agent "${input.remote.name}" reset-session response was invalid.`);+ }+ return result.data;+}+export function isRetryableRemoteAgentCancelError(error: unknown): boolean {return !(error instanceof RemoteAgentCancelRequestError) || error.retryable;}@@ -512,7 +538,7 @@ function createRemoteAgentSessionUrl(remote: ResolvedRuntimeRemoteAgentNode): st}function createRemoteAgentCancelTurnUrl(- remote: ResolvedRuntimeRemoteAgentNode,+ remote: Pick<ResolvedRuntimeRemoteAgentNode, "url">,sessionId: string,): string {return createRemoteAgentRouteUrl(remote.url, createEveSessionCancelRoutePath(sessionId));@@ -547,7 +573,6 @@ 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 : "";@@ -555,7 +580,6 @@ 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/settle-cancelled-turn-step.integration.test.ts b/packages/eve/src/execution/settle-cancelled-turn-step.integration.test.tsindex 690f0a5a0..ada627f5e 100644--- a/packages/eve/src/execution/settle-cancelled-turn-step.integration.test.ts+++ b/packages/eve/src/execution/settle-cancelled-turn-step.integration.test.ts@@ -79,6 +79,7 @@ function createCancelledTurnSession(handles: readonly AgentHandle[]): HarnessSescompaction: { recentWindowSize: 10, threshold: 100_000 },continuationToken: CONTINUATION_TOKEN,history: [],+ outputSchema: { type: "object" },sessionId: PARENT_SESSION_ID,state: { [AGENT_HANDLES_STATE_KEY]: { handles } },},@@ -121,6 +122,7 @@ describe("settleCancelledTurnStep handle store", () => {PARKED_HANDLE,],});+ expect(result.sessionState.snapshot?.session.outputSchema).toBeUndefined();});});});diff --git a/packages/eve/src/execution/settle-cancelled-turn-step.ts b/packages/eve/src/execution/settle-cancelled-turn-step.tsindex 5a0193659..7a7344a6e 100644--- a/packages/eve/src/execution/settle-cancelled-turn-step.ts+++ b/packages/eve/src/execution/settle-cancelled-turn-step.ts@@ -143,7 +143,9 @@ export async function settleCancelledTurnStep(input: {clearPendingSessionLimitPrompt(clearAllProxyInputRequests(clearPendingWorkflowInterrupt(- clearPendingRuntimeActionBatch(abandonRunningAgentTurns(session)),+ clearPendingRuntimeActionBatch(+ abandonRunningAgentTurns({ ...session, outputSchema: undefined }),+ ),),),),diff --git a/packages/eve/src/execution/subagent-adapter.test.ts b/packages/eve/src/execution/subagent-adapter.test.tsindex 16615deaf..0e5db344f 100644--- a/packages/eve/src/execution/subagent-adapter.test.ts+++ b/packages/eve/src/execution/subagent-adapter.test.ts@@ -5,8 +5,10 @@ import { buildSessionHandle } from "#channel/session.js";import { type SubagentAdapterState } from "#execution/subagent-adapter-state.js";import { ContextContainer } from "#context/container.js";import { ContinuationTokenKey, SessionIdKey } from "#context/keys.js";+import { ChannelKey } from "#runtime/sessions/runtime-context-keys.js";import type { InputRequest } from "#shared/input.js";import { SUBAGENT_ADAPTER } from "#execution/subagent-adapter.js";+import { bindTurnCallerContextStep } from "#execution/delegated-parent-notification.js";const SUBAGENT_INPUT_REQUESTED = SUBAGENT_ADAPTER["input.requested"];const SUBAGENT_AUTHORIZATION_REQUIRED = SUBAGENT_ADAPTER["authorization.required"];@@ -139,6 +141,40 @@ describe("SUBAGENT_ADAPTER authorization handlers", () => {});describe("SUBAGENT_ADAPTER input.requested handler", () => {+ it("forwards continuation HITL to the newly bound parent turn", async () => {+ resumeHookMock.mockClear();+ const rebound = await bindTurnCallerContextStep({+ caller: {+ callId: "call-continued",+ replyTo: { kind: "hook", token: "parent-token-current" },+ subagentName: "linear",+ },+ serializedContext: {+ [ChannelKey.name]: {+ kind: "subagent",+ state: makeContext().state,+ },+ },+ });+ const base = makeContext();+ const channel = rebound[ChannelKey.name] as { readonly state: Record<string, unknown> };++ await SUBAGENT_INPUT_REQUESTED(+ {+ requests: [sampleRequest()],+ sequence: 0,+ stepIndex: 1,+ turnId: "turn-continued",+ },+ { ...base, state: channel.state },+ );++ expect(resumeHookMock).toHaveBeenCalledWith(+ "parent-token-current",+ expect.objectContaining({ callId: "call-continued", kind: "subagent-input-request" }),+ );+ });+it("forwards the child's HITL batch via resumeHook", async () => {resumeHookMock.mockClear();const ctx = makeContext();diff --git a/packages/eve/src/execution/subagent-invocation.ts b/packages/eve/src/execution/subagent-invocation.tsindex 2a255a914..3dd65830f 100644--- a/packages/eve/src/execution/subagent-invocation.ts+++ b/packages/eve/src/execution/subagent-invocation.ts@@ -28,7 +28,6 @@ export function normalizeRequestedOutputSchema(type RuntimeSubagentInputFormatRequest = {readonly message: string;readonly name: string;- readonly persistentSession?: boolean;readonly type: "runtime";};@@ -36,7 +35,6 @@ type LocalSubagentInputFormatRequest = {readonly description: string;readonly message: string;readonly name: string;- readonly persistentSession?: boolean;readonly type: "local";};@@ -44,7 +42,6 @@ type RemoteSubagentInputFormatRequest = {readonly description: string;readonly message: string;readonly name: string;- readonly persistentSession?: boolean;readonly type: "remote";};@@ -65,7 +62,6 @@ const formatSubagentInputByType = {descriptionLines: [],message: input.message,name: input.name,- persistentSession: input.persistentSession,});},local(input) {@@ -73,7 +69,6 @@ const formatSubagentInputByType = {descriptionLines: formatDescriptionLines(input.description),message: input.message,name: input.name,- persistentSession: input.persistentSession,});},remote(input) {@@ -81,7 +76,6 @@ const formatSubagentInputByType = {descriptionLines: formatDescriptionLines(input.description),message: input.message,name: input.name,- persistentSession: input.persistentSession,});},} satisfies SubagentInputFormatters;@@ -110,16 +104,13 @@ 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,"",- 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.",+ "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.","","Caller message:",input.message,diff --git a/packages/eve/src/execution/subagent-start-local.ts b/packages/eve/src/execution/subagent-start-local.tsindex 2032419d1..d3001e786 100644--- a/packages/eve/src/execution/subagent-start-local.ts+++ b/packages/eve/src/execution/subagent-start-local.ts@@ -35,7 +35,6 @@ export async function startLocalSubagent(input: {readonly initiatorAuth: Parameters<typeof buildSubagentRunInput>[0]["initiatorAuth"];readonly parentContinuationToken: string | undefined;readonly parentTraceContext: Parameters<typeof buildSubagentRunInput>[0]["parentTraceContext"];- readonly persistentSessions: boolean;readonly sandboxSessionId: string;readonly session: RuntimeSession;readonly source: SubagentInputSource;@@ -58,7 +57,6 @@ export async function startLocalSubagent(input: {graph: input.bundle.graph,parentContinuationToken: input.parentContinuationToken,parentTraceContext: input.parentTraceContext,- persistentSessions: input.persistentSessions,sandboxSessionId: input.sandboxSessionId,session: input.session,source,diff --git a/packages/eve/src/execution/subagent-start-remote.ts b/packages/eve/src/execution/subagent-start-remote.tsindex ae82e4648..79b9fd592 100644--- a/packages/eve/src/execution/subagent-start-remote.ts+++ b/packages/eve/src/execution/subagent-start-remote.ts@@ -31,7 +31,6 @@ export async function startRemoteSubagent(input: {readonly initiatorAuth: Parameters<typeof startRemoteAgentSession>[0]["initiatorAuth"];readonly parentContinuationToken: string | undefined;readonly parentTraceContext: Parameters<typeof startRemoteAgentSession>[0]["parentTraceContext"];- readonly persistentSessions: boolean;readonly session: RuntimeSession;readonly taskOwned: boolean;}): Promise<DispatchOutcome> {@@ -72,10 +71,16 @@ export async function startRemoteSubagent(input: {parentSessionId: input.session.sessionId,parentTurnId: input.batchEvent.turnId,});+ const credentialResolver = {+ resolverId:+ input.dynamicRemoteAgent === undefined+ ? action.nodeId+ : input.dynamicRemoteAgent.credentialsStepId,+ };const preparedSession = prepareAgentStart(input.currentSession, {identity,operation,- target: { callbackBaseUrl, kind: "agent/remote", url: resolvedRemote.url },+ target: { callbackBaseUrl, credentialResolver, kind: "agent/remote", url: resolvedRemote.url },});try {@@ -87,12 +92,12 @@ export async function startRemoteSubagent(input: {initiatorAuth: input.initiatorAuth,operationId: operation.id,parentTraceContext: input.parentTraceContext,- persistentSessions: input.persistentSessions,remote: resolvedRemote,session: input.session,});const address = {callbackBaseUrl,+ credentialResolver,kind: "agent/remote",sessionId: child.sessionId,url: resolvedRemote.url,diff --git a/packages/eve/src/execution/subagent-tool.test.ts b/packages/eve/src/execution/subagent-tool.test.tsindex a5663c73e..d90881ba3 100644--- a/packages/eve/src/execution/subagent-tool.test.ts+++ b/packages/eve/src/execution/subagent-tool.test.ts@@ -97,7 +97,7 @@ describe("buildSubagentRunInput", () => {});expect(runInput.continuationToken).toBe(childContinuationToken);expect(childContinuationToken).toMatch(/^subagent:parent-session:call-1$/);- expect(runInput.mode).toBe("task");+ expect(runInput.mode).toBe("conversation");});it("routes parent notifications to an active turn inbox when supplied", () => {@@ -215,6 +215,37 @@ describe("buildSubagentRunInput", () => {});expect(runInput.input.outputSchema).toEqual(schema);+ expect(runInput.mode).toBe("conversation");+ });++ it("uses a declared local outputSchema on the persistent child's first turn", () => {+ const schema = { properties: { result: { type: "string" } }, type: "object" };+ const { runInput } = buildSubagentRunInput({+ action: makeAction(),+ auth: null,+ batchEvent: { sequence: 0, turnId: "turn-0" },+ initiatorAuth: null,+ session: makeSession(),+ source: { description: "Research the request.", outputSchema: schema, type: "local" },+ });++ expect(runInput.input.outputSchema).toEqual(schema);+ expect(runInput.mode).toBe("conversation");+ });++ it("lets a per-call outputSchema override the local child's declared schema", () => {+ const declared = { properties: { declared: { type: "string" } }, type: "object" };+ const requested = { properties: { requested: { type: "number" } }, type: "object" };+ const { runInput } = buildSubagentRunInput({+ action: { ...makeAction(), input: { message: "do something", outputSchema: requested } },+ auth: null,+ batchEvent: { sequence: 0, turnId: "turn-0" },+ initiatorAuth: null,+ session: makeSession(),+ source: { description: "Research the request.", outputSchema: declared, type: "local" },+ });++ expect(runInput.input.outputSchema).toEqual(requested);});it("hands the parent's trace window down to the child, and omits it when absent", () => {@@ -257,7 +288,7 @@ describe("buildSubagentRunInput", () => {'You are the subagent "linear".',"Description: Local delegate subagent description.","",- "The caller delegated the following task to you. Complete it and return the final result directly.",+ "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.","","Caller message:","Make an issue titled 'Resolve flaky test'.",@@ -286,7 +317,7 @@ describe("buildSubagentRunInput", () => {[`You are the subagent "${action.subagentName}".`,"",- "The caller delegated the following task to you. Complete it and return the final result directly.",+ "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.","","Caller message:","Make an issue titled 'Resolve flaky test'.",@@ -295,6 +326,21 @@ describe("buildSubagentRunInput", () => {expect(runInput.input.message).not.toContain(action.description);});+ it("uses the root agent's declared outputSchema for a fresh built-in copy", () => {+ const schema = { properties: { result: { type: "string" } }, type: "object" };+ const { runInput } = buildSubagentRunInput({+ action: { ...makeAction(), name: "agent", nodeId: "root", subagentName: "agent" },+ auth: null,+ batchEvent: { sequence: 0, turnId: "turn-0" },+ initiatorAuth: null,+ session: makeSession(),+ source: { outputSchema: schema, type: "runtime" },+ });++ expect(runInput.input.outputSchema).toEqual(schema);+ expect(runInput.mode).toBe("conversation");+ });+it("leaves outputSchema undefined when not provided", () => {const { runInput } = buildRuntimeSubagentRunInput({action: makeAction(),diff --git a/packages/eve/src/execution/subagent-tool.ts b/packages/eve/src/execution/subagent-tool.tsindex 9dfe23a23..2515646a3 100644--- a/packages/eve/src/execution/subagent-tool.ts+++ b/packages/eve/src/execution/subagent-tool.ts@@ -16,6 +16,7 @@ import type { RuntimeSubagentCallActionRequest } from "#shared/action-types.js";import { mintSubagentContinuationToken } from "#execution/session.js";import { resolveSubagentDepth } from "#harness/subagent-depth.js";import { resolveRemainingSessionTokenLimits } from "#harness/subagent-token-budget.js";+import type { JsonObject } from "#shared/json.js";/*** Pending runtime-action batch event metadata needed for child run lineage.@@ -28,9 +29,11 @@ interface BatchEventMetadata {export type SubagentInputSource =| {readonly description: string;+ readonly outputSchema?: JsonObject;readonly type: "local";}| {+ readonly outputSchema?: JsonObject;readonly type: "runtime";};@@ -95,13 +98,6 @@ export function buildSubagentRunInput(input: {/** Hook token owned by the workflow currently waiting for this child. */readonly parentContinuationToken?: string;readonly parentTraceContext?: SessionTraceContext;- /**- * Whether the parent agent opted into- * `experimental.subagentPersistentSessions`. Persistent children run in- * conversation mode so their sessions survive the first answer; otherwise- * children run as one-shot task sessions.- */- readonly persistentSessions?: boolean;readonly session: HarnessSession;readonly source: SubagentInputSource;}): SubagentRunInputBuild {@@ -164,13 +160,12 @@ export function buildSubagentRunInput(input: {input: {message: formatSubagentCallInputMessage({action,- persistentSession: input.persistentSessions,source,}),- outputSchema: requestedOutputSchema,+ outputSchema: requestedOutputSchema ?? source.outputSchema,},limits: inheritedLimits,- mode: input.persistentSessions === true ? "conversation" : "task",+ mode: "conversation",parent: {callId: action.callId,rootSessionId,@@ -192,7 +187,6 @@ 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 };@@ -203,14 +197,12 @@ 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/tasks/parent/dispatch-task-step.ts b/packages/eve/src/execution/tasks/parent/dispatch-task-step.tsindex 8666d8138..7b3048afa 100644--- a/packages/eve/src/execution/tasks/parent/dispatch-task-step.ts+++ b/packages/eve/src/execution/tasks/parent/dispatch-task-step.ts@@ -157,11 +157,6 @@ export async function dispatchTaskStep(initiatorAuth: prepared.initiatorAuth,parentContinuationToken: delegated.taskInboxToken,parentTraceContext: prepared.parentTraceContext,- // Background tasks require resumable children, so task mode- // always dispatches conversation-mode (persistent) sessions;- // `experimental.subagentPersistentSessions` never produces a- // third mode here.- persistentSessions: true,sandboxSessionId: prepared.sandboxSessionId,serializedContext: prepared.serializedContext,session,diff --git a/packages/eve/src/execution/tasks/parent/dispatch.test.ts b/packages/eve/src/execution/tasks/parent/dispatch.test.tsindex 435bcee10..14c04cd70 100644--- a/packages/eve/src/execution/tasks/parent/dispatch.test.ts+++ b/packages/eve/src/execution/tasks/parent/dispatch.test.ts@@ -1,9 +1,12 @@import { beforeEach, describe, expect, it, vi } from "vitest";+import { getDynamicSubagentSelection } from "#context/dynamic-subagent-lifecycle.js";+import { deserializeContext } from "#context/serialize.js";import type { RuntimeSession } from "#execution/agent-handle-dispatch.js";import {cancelRemoteAgentTurn,resolveRemoteAgentForAction,+ resolveRemoteAgentStreamHeaders,} from "#execution/remote-agent-dispatch.js";import { executeTaskControlAction } from "#execution/tasks/parent/dispatch.js";import { readLatestTaskView, sendTaskCommand } from "#execution/tasks/parent/run-parent.js";@@ -17,6 +20,10 @@ vi.mock("#execution/tasks/parent/run-parent.js", () => ({readLatestTaskView: vi.fn(),sendTaskCommand: vi.fn(),}));+vi.mock("#context/serialize.js", () => ({ deserializeContext: vi.fn() }));+vi.mock("#context/dynamic-subagent-lifecycle.js", () => ({+ getDynamicSubagentSelection: vi.fn(),+}));vi.mock("#execution/workflow-runtime.js", async (importOriginal) => ({...(await importOriginal<typeof import("#execution/workflow-runtime.js")>()),requestWorkflowTurnCancellation: vi.fn(),@@ -25,6 +32,7 @@ vi.mock("#execution/remote-agent-dispatch.js", async (importOriginal) => ({...(await importOriginal<typeof import("#execution/remote-agent-dispatch.js")>()),cancelRemoteAgentTurn: vi.fn(),resolveRemoteAgentForAction: vi.fn(),+ resolveRemoteAgentStreamHeaders: vi.fn(),}));const action: RuntimeToolCallActionRequest = {@@ -105,6 +113,9 @@ describe("task cancellation identity", () => {sessionId: "child-1",status: "accepted",});+ vi.mocked(resolveRemoteAgentStreamHeaders).mockResolvedValue({ authorization: "Bearer fresh" });+ vi.mocked(deserializeContext).mockResolvedValue("context" as never);+ vi.mocked(getDynamicSubagentSelection).mockReturnValue(undefined);});it.each(["local", "remote"] as const)(@@ -141,6 +152,234 @@ describe("task cancellation identity", () => {},);+ it("cancels a dynamic remote task with its creation-time credential resolver", async () => {+ const session = createSession("remote");+ const handleStore = session.state?.[AGENT_HANDLES_STATE_KEY] as {+ handles: Array<{ address: { credentialResolver?: { resolverId?: string } } }>;+ };+ handleStore.handles[0]!.address.credentialResolver = {+ resolverId: "dynamic-credentials-step",+ };+ vi.mocked(readLatestTaskView).mockResolvedValue({+ metadata: {+ agentId: "agent-1",+ kind: "subagent",+ mode: "remote",+ name: "research",+ },+ executor: {+ binding: {+ data: {+ address: handleStore.handles[0]!.address,+ identity: { id: "agent-1", name: "research", nodeId: "node-1" },+ },+ kind: "subagent",+ },+ childSessionId: "child-1",+ childTurnId: "turn_child_7",+ },+ status: "cancelled",+ taskId: "task-1",+ });++ await executeTaskControlAction({+ action,+ bundle: { subagentRegistry: { subagentsByNodeId: new Map() } } as never,+ parentTurnId: "turn-parent",+ session,+ });++ expect(resolveRemoteAgentForAction).not.toHaveBeenCalled();+ expect(resolveRemoteAgentStreamHeaders).toHaveBeenCalledWith({+ bundle: expect.any(Object),+ name: "research",+ resolverId: "dynamic-credentials-step",+ url: "https://child.example",+ });+ expect(cancelRemoteAgentTurn).toHaveBeenCalledWith(+ expect.objectContaining({+ headers: { authorization: "Bearer fresh" },+ remote: { name: "research", url: "https://child.example" },+ sessionId: "child-1",+ turnId: "turn_child_7",+ }),+ );+ });++ it("does not resolve authored credentials when creation recorded none", async () => {+ const session = createSession("remote");+ const address = (+ session.state?.[AGENT_HANDLES_STATE_KEY] as {+ handles: Array<{ address: { credentialResolver?: { resolverId?: string } } }>;+ }+ ).handles[0]!.address;+ address.credentialResolver = {};+ vi.mocked(readLatestTaskView).mockResolvedValue({+ metadata: { agentId: "agent-1", kind: "subagent", mode: "remote", name: "research" },+ executor: {+ binding: {+ data: {+ address,+ identity: { id: "agent-1", name: "research", nodeId: "node-1" },+ },+ kind: "subagent",+ },+ childSessionId: "child-1",+ childTurnId: "turn_child_7",+ },+ status: "cancelled",+ taskId: "task-1",+ });++ await executeTaskControlAction({+ action,+ bundle: { subagentRegistry: { subagentsByNodeId: new Map() } } as never,+ parentTurnId: "turn-parent",+ session,+ });++ expect(resolveRemoteAgentForAction).not.toHaveBeenCalled();+ expect(resolveRemoteAgentStreamHeaders).not.toHaveBeenCalled();+ expect(cancelRemoteAgentTurn).toHaveBeenCalledWith(+ expect.objectContaining({+ headers: {},+ remote: { name: "research", url: "https://child.example" },+ }),+ );+ });++ it("recovers the current dynamic selection for a legacy remote binding", async () => {+ const dynamicRemoteAgent = {+ credentialsStepId: "legacy-dynamic-step",+ description: "Remote research",+ path: "/eve/v1/session",+ url: "https://child.example",+ };+ vi.mocked(getDynamicSubagentSelection).mockReturnValue({+ kind: "remote",+ prepared: {} as never,+ remoteAgent: dynamicRemoteAgent,+ });++ await executeTaskControlAction({+ action,+ bundle: { subagentRegistry: { subagentsByNodeId: new Map() } } as never,+ parentTurnId: "turn-parent",+ serializedContext: { context: "serialized" },+ session: createSession("remote"),+ });++ expect(deserializeContext).toHaveBeenCalledWith({ context: "serialized" });+ expect(resolveRemoteAgentForAction).toHaveBeenCalledWith(+ expect.objectContaining({ dynamicRemoteAgent }),+ );+ });++ it("does not send current credentials to a legacy child's previous URL", async () => {+ vi.mocked(getDynamicSubagentSelection).mockReturnValue({+ kind: "remote",+ prepared: {} as never,+ remoteAgent: {+ credentialsStepId: "new-dynamic-step",+ description: "Remote research",+ path: "/eve/v1/session",+ url: "https://new-child.example",+ },+ });+ vi.mocked(resolveRemoteAgentForAction).mockReturnValue({+ name: "research",+ url: "https://new-child.example",+ } as never);++ await executeTaskControlAction({+ action,+ bundle: { subagentRegistry: { subagentsByNodeId: new Map() } } as never,+ parentTurnId: "turn-parent",+ serializedContext: { context: "serialized" },+ session: createSession("remote"),+ });++ expect(cancelRemoteAgentTurn).toHaveBeenCalledWith(+ expect.objectContaining({+ headers: {},+ remote: { name: "research", url: "https://child.example" },+ }),+ );+ expect(resolveRemoteAgentStreamHeaders).not.toHaveBeenCalled();+ });++ it("uses fresh current credentials when a legacy child's URL still matches", async () => {+ const auth = vi.fn();+ const headers = vi.fn();+ vi.mocked(resolveRemoteAgentForAction).mockReturnValue({+ auth,+ headers,+ name: "research",+ url: "https://child.example",+ } as never);++ await executeTaskControlAction({+ action,+ bundle: { subagentRegistry: { subagentsByNodeId: new Map() } } as never,+ parentTurnId: "turn-parent",+ session: createSession("remote"),+ });++ expect(cancelRemoteAgentTurn).toHaveBeenCalledWith(+ expect.objectContaining({+ remote: expect.objectContaining({+ auth,+ headers,+ name: "research",+ url: "https://child.example",+ }),+ }),+ );+ expect(vi.mocked(cancelRemoteAgentTurn).mock.calls[0]?.[0]).not.toHaveProperty("headers");+ });++ it("preserves resolved headers when retrying an unguarded remote cancel", async () => {+ vi.mocked(cancelRemoteAgentTurn)+ .mockResolvedValueOnce({ status: "no_active_turn" })+ .mockResolvedValueOnce({ sessionId: "child-1", status: "accepted" });+ const session = createSession("remote");+ const address = (+ session.state?.[AGENT_HANDLES_STATE_KEY] as {+ handles: Array<{ address: { credentialResolver?: { resolverId?: string } } }>;+ }+ ).handles[0]!.address;+ address.credentialResolver = { resolverId: "dynamic-credentials-step" };+ vi.mocked(readLatestTaskView).mockResolvedValue({+ metadata: { agentId: "agent-1", kind: "subagent", mode: "remote", name: "research" },+ executor: {+ binding: {+ data: {+ address,+ identity: { id: "agent-1", name: "research", nodeId: "node-1" },+ },+ kind: "subagent",+ },+ childSessionId: "child-1",+ childTurnId: "turn_child_7",+ },+ status: "cancelled",+ taskId: "task-1",+ });++ await executeTaskControlAction({+ action,+ bundle: { subagentRegistry: { subagentsByNodeId: new Map() } } as never,+ parentTurnId: "turn-parent",+ session,+ });++ expect(cancelRemoteAgentTurn).toHaveBeenNthCalledWith(+ 2,+ expect.objectContaining({ headers: { authorization: "Bearer fresh" } }),+ );+ expect(vi.mocked(cancelRemoteAgentTurn).mock.calls[1]?.[0]).not.toHaveProperty("turnId");+ });+it("uses task-scoped cancellation before child-turn identity arrives", async () => {vi.mocked(readLatestTaskView).mockResolvedValue({metadata: { agentId: "agent-1", kind: "subagent", mode: "local", name: "research" },diff --git a/packages/eve/src/execution/tasks/parent/dispatch.ts b/packages/eve/src/execution/tasks/parent/dispatch.tsindex eac5d8d24..ea91b4d27 100644--- a/packages/eve/src/execution/tasks/parent/dispatch.ts+++ b/packages/eve/src/execution/tasks/parent/dispatch.ts@@ -1,7 +1,10 @@import type { RuntimeSession } from "#execution/agent-handle-dispatch.js";+import { deserializeContext } from "#context/serialize.js";+import { getDynamicSubagentSelection } from "#context/dynamic-subagent-lifecycle.js";import {cancelRemoteAgentTurn,resolveRemoteAgentForAction,+ resolveRemoteAgentStreamHeaders,} from "#execution/remote-agent-dispatch.js";import {createTaskControlError,@@ -107,7 +110,14 @@ export async function executeTaskControlAction(input: {const views: TaskView[] = [];for (const entry of entries) {- views.push(await cancelOwnedTask({ bundle: input.bundle, entry, session }));+ views.push(+ await cancelOwnedTask({+ bundle: input.bundle,+ entry,+ serializedContext: input.serializedContext,+ session,+ }),+ );}return { result: createTaskViewsResult(action, views), session };}@@ -116,6 +126,7 @@ export async function executeTaskControlAction(input: {export async function cancelOwnedTask(input: {readonly bundle: CompiledBundle;readonly entry: SessionTaskIndexEntry;+ readonly serializedContext?: Record<string, unknown>;readonly session: RuntimeSession;}): Promise<TaskView> {const { entry } = input;@@ -141,7 +152,12 @@ export async function cancelOwnedTask(input: {const settledView = view;if (settledView.status === "cancelled" && delivery === "delivered") {- await propagateTaskCancel({ bundle: input.bundle, session: input.session, view: settledView });+ await propagateTaskCancel({+ bundle: input.bundle,+ serializedContext: input.serializedContext,+ session: input.session,+ view: settledView,+ });}return settledView;}@@ -155,6 +171,7 @@ export async function cancelOwnedTask(input: {*/async function propagateTaskCancel(input: {readonly bundle: CompiledBundle;+ readonly serializedContext?: Record<string, unknown>;readonly session: RuntimeSession;readonly view: TaskView;}): Promise<void> {@@ -174,6 +191,7 @@ async function propagateTaskCancel(input: {bundle: input.bundle,childTurnId: input.view.executor?.childTurnId,executor,+ serializedContext: input.serializedContext,taskId: input.view.taskId,});}@@ -188,6 +206,7 @@ export async function propagateSubagentExecutorCancel(input: {readonly bundle: CompiledBundle | undefined;readonly childTurnId?: string;readonly executor: SubagentExecutorData;+ readonly serializedContext?: Record<string, unknown>;readonly taskId: string;}): Promise<void> {const { address, identity } = input.executor;@@ -199,29 +218,65 @@ export async function propagateSubagentExecutorCancel(input: {if (input.bundle === undefined) {throw new Error("No compiled bundle is available to resolve the remote agent.");}- const resolved = resolveRemoteAgentForAction({- nodeId: identity.nodeId,- remoteAgentName: identity.name,- registry: input.bundle.subagentRegistry.subagentsByNodeId,- });+ const credentialResolver = address.credentialResolver;+ let dynamicRemoteAgent;+ if (credentialResolver === undefined && input.serializedContext !== undefined) {+ const ctx = await deserializeContext(input.serializedContext);+ const selection = getDynamicSubagentSelection(ctx, identity.nodeId);+ dynamicRemoteAgent = selection?.kind === "remote" ? selection.remoteAgent : undefined;+ }+ const resolved =+ credentialResolver === undefined+ ? resolveRemoteAgentForAction({+ dynamicRemoteAgent,+ nodeId: identity.nodeId,+ remoteAgentName: identity.name,+ registry: input.bundle.subagentRegistry.subagentsByNodeId,+ })+ : { name: identity.name, url: address.url };+ const legacyUrlMismatch = credentialResolver === undefined && resolved.url !== address.url;+ const headers = legacyUrlMismatch+ ? {}+ : credentialResolver?.resolverId === undefined+ ? credentialResolver === undefined+ ? undefined+ : {}+ : await resolveRemoteAgentStreamHeaders({+ bundle: input.bundle,+ name: identity.name,+ resolverId: credentialResolver.resolverId,+ url: address.url,+ });+ const remote = legacyUrlMismatch+ ? { name: identity.name, url: address.url }+ : { ...resolved, url: address.url };const cancelInput: {+ headers?: Record<string, string>;readonly remote: typeof resolved & { readonly url: string };readonly sessionId: string;readonly taskId: string;turnId?: string;} = {- remote: { ...resolved, url: address.url },+ remote,sessionId: childSessionId,taskId: input.taskId,};+ if (headers !== undefined) cancelInput.headers = headers;if (childTurnId !== undefined) cancelInput.turnId = childTurnId;const result = await cancelRemoteAgentTurn(cancelInput);if (result.status === "no_active_turn") {- await cancelRemoteAgentTurn({- remote: { ...resolved, url: address.url },+ const retryInput: {+ headers?: Record<string, string>;+ remote: typeof resolved & { readonly url: string };+ sessionId: string;+ taskId: string;+ } = {+ remote,sessionId: childSessionId,taskId: input.taskId,- });+ };+ if (headers !== undefined) retryInput.headers = headers;+ await cancelRemoteAgentTurn(retryInput);}return;}diff --git a/packages/eve/src/execution/terminate-child-sessions-step.test.ts b/packages/eve/src/execution/terminate-child-sessions-step.test.tsindex abda9a959..c50f8c610 100644--- a/packages/eve/src/execution/terminate-child-sessions-step.test.ts+++ b/packages/eve/src/execution/terminate-child-sessions-step.test.ts@@ -5,31 +5,51 @@ import type { DurableSessionState } from "#execution/durable-session-store.js";import { terminateChildSessionsStep } from "#execution/terminate-child-sessions-step.js";import { SESSION_TASKS_STATE_KEY, type SessionTaskIndexEntry } from "#tasks/session-index.js";+const COMPILED_BUNDLE = {+ subagentRegistry: { subagentsByNodeId: new Map() },+};+const {cancelOwnedTaskMock,cancelRunMock,deserializeContextMock,getWorldMock,+ getDynamicSubagentSelectionMock,hydrateDurableSessionMock,+ resetRemoteAgentSessionMock,+ resolveRemoteAgentForActionMock,+ resolveRemoteAgentStreamHeadersMock,resolveEffectiveAgentRuntimeMock,} = vi.hoisted(() => ({cancelOwnedTaskMock: vi.fn(),cancelRunMock: vi.fn(),deserializeContextMock: vi.fn(),getWorldMock: vi.fn(),+ getDynamicSubagentSelectionMock: vi.fn(),hydrateDurableSessionMock: vi.fn(),+ resetRemoteAgentSessionMock: vi.fn(),+ resolveRemoteAgentForActionMock: vi.fn(),+ resolveRemoteAgentStreamHeadersMock: vi.fn(),resolveEffectiveAgentRuntimeMock: vi.fn(),}));vi.mock("#context/serialize.js", () => ({deserializeContext: deserializeContextMock,}));+vi.mock("#context/dynamic-subagent-lifecycle.js", () => ({+ getDynamicSubagentSelection: getDynamicSubagentSelectionMock,+}));vi.mock("#execution/effective-agent-config.js", () => ({resolveEffectiveAgentRuntime: resolveEffectiveAgentRuntimeMock,}));vi.mock("#execution/session.js", () => ({hydrateDurableSession: hydrateDurableSessionMock,}));+vi.mock("#execution/remote-agent-dispatch.js", () => ({+ resetRemoteAgentSession: resetRemoteAgentSessionMock,+ resolveRemoteAgentForAction: resolveRemoteAgentForActionMock,+ resolveRemoteAgentStreamHeaders: resolveRemoteAgentStreamHeadersMock,+}));vi.mock("#execution/tasks/parent/dispatch.js", () => ({cancelOwnedTask: cancelOwnedTaskMock,}));@@ -45,11 +65,26 @@ describe("terminateChildSessionsStep", () => {cancelRunMock.mockReset();cancelRunMock.mockResolvedValue(undefined);deserializeContextMock.mockReset();- deserializeContextMock.mockResolvedValue({ require: vi.fn().mockReturnValue("bundle") });+ deserializeContextMock.mockResolvedValue({ require: vi.fn().mockReturnValue(COMPILED_BUNDLE) });getWorldMock.mockReset();getWorldMock.mockResolvedValue("world");+ getDynamicSubagentSelectionMock.mockReset();+ getDynamicSubagentSelectionMock.mockReturnValue(undefined);hydrateDurableSessionMock.mockReset();hydrateDurableSessionMock.mockReturnValue("runtime-session");+ resetRemoteAgentSessionMock.mockReset();+ resetRemoteAgentSessionMock.mockResolvedValue({ ok: true, status: "no_active_session" });+ resolveRemoteAgentForActionMock.mockReset();+ resolveRemoteAgentForActionMock.mockReturnValue({+ description: "Research remotely",+ kind: "remote",+ name: "research",+ nodeId: "subagents/research",+ path: "/eve/v1/session",+ url: "https://remote.example.com",+ });+ resolveRemoteAgentStreamHeadersMock.mockReset();+ resolveRemoteAgentStreamHeadersMock.mockResolvedValue({ authorization: "Bearer fresh" });resolveEffectiveAgentRuntimeMock.mockReset();resolveEffectiveAgentRuntimeMock.mockReturnValue({ turnAgent: "turn-agent" });});@@ -73,8 +108,9 @@ describe("terminateChildSessionsStep", () => {});});- it("skips remote handles: remote children survive parent termination (documented gap)", async () => {+ it("resets remote children and terminates local children", async () => {await terminateChildSessionsStep({+ serializedContext: { context: "serialized" },sessionState: makeSessionState([parkedHandle({ id: "ag_remote:1", kind: "agent/remote", sessionId: "session-remote" }),runningHandle({ id: "ag_local:1", kind: "agent/local", sessionId: "session-local" }),@@ -84,6 +120,114 @@ describe("terminateChildSessionsStep", () => {expect(cancelRunMock).toHaveBeenCalledExactlyOnceWith("world", "session-local", {cancelReason: "Parent session ended",});+ expect(resolveRemoteAgentForActionMock).toHaveBeenCalledWith({+ dynamicRemoteAgent: undefined,+ nodeId: "subagents/research",+ registry: COMPILED_BUNDLE.subagentRegistry.subagentsByNodeId,+ remoteAgentName: "research",+ });+ expect(resetRemoteAgentSessionMock).toHaveBeenCalledWith({+ remote: expect.objectContaining({ url: "https://remote.example.com" }),+ sessionId: "session-remote",+ });+ });++ it("does not send current credentials to a legacy child's previous URL", async () => {+ resolveRemoteAgentForActionMock.mockReturnValue({+ name: "research",+ url: "https://new-remote.example.com",+ });++ await terminateChildSessionsStep({+ serializedContext: { context: "serialized" },+ sessionState: makeSessionState([+ parkedHandle({ id: "ag_remote:1", kind: "agent/remote", sessionId: "session-remote" }),+ ]),+ });++ expect(resetRemoteAgentSessionMock).toHaveBeenCalledWith({+ headers: {},+ remote: { name: "research", url: "https://remote.example.com" },+ sessionId: "session-remote",+ });+ });++ it("uses fresh current credentials when a legacy child's URL still matches", async () => {+ const auth = vi.fn();+ const headers = vi.fn();+ resolveRemoteAgentForActionMock.mockReturnValue({+ auth,+ headers,+ name: "research",+ url: "https://remote.example.com",+ });++ await terminateChildSessionsStep({+ serializedContext: { context: "serialized" },+ sessionState: makeSessionState([+ parkedHandle({ id: "ag_remote:1", kind: "agent/remote", sessionId: "session-remote" }),+ ]),+ });++ expect(resetRemoteAgentSessionMock).toHaveBeenCalledWith({+ remote: expect.objectContaining({+ auth,+ headers,+ name: "research",+ url: "https://remote.example.com",+ }),+ sessionId: "session-remote",+ });+ });++ it("resets a remote child with its creation-time credential resolver", async () => {+ await terminateChildSessionsStep({+ serializedContext: { context: "serialized" },+ sessionState: makeSessionState([+ parkedHandle({+ credentialResolver: { resolverId: "dynamic-credentials-step" },+ id: "ag_remote:1",+ kind: "agent/remote",+ sessionId: "session-remote",+ }),+ ]),+ });++ expect(getDynamicSubagentSelectionMock).not.toHaveBeenCalled();+ expect(resolveRemoteAgentForActionMock).not.toHaveBeenCalled();+ expect(resolveRemoteAgentStreamHeadersMock).toHaveBeenCalledWith({+ bundle: COMPILED_BUNDLE,+ name: "research",+ resolverId: "dynamic-credentials-step",+ url: "https://remote.example.com",+ });+ expect(resetRemoteAgentSessionMock).toHaveBeenCalledWith({+ headers: { authorization: "Bearer fresh" },+ remote: { name: "research", url: "https://remote.example.com" },+ sessionId: "session-remote",+ });+ });++ it("does not invent credentials for a child created without a resolver", async () => {+ await terminateChildSessionsStep({+ serializedContext: { context: "serialized" },+ sessionState: makeSessionState([+ parkedHandle({+ credentialResolver: {},+ id: "ag_remote:1",+ kind: "agent/remote",+ sessionId: "session-remote",+ }),+ ]),+ });++ expect(getDynamicSubagentSelectionMock).not.toHaveBeenCalled();+ expect(resolveRemoteAgentStreamHeadersMock).not.toHaveBeenCalled();+ expect(resetRemoteAgentSessionMock).toHaveBeenCalledWith({+ headers: {},+ remote: { name: "research", url: "https://remote.example.com" },+ sessionId: "session-remote",+ });});it("skips a starting handle that has no session id yet", async () => {@@ -217,10 +361,15 @@ function makeIdentity(id: string): { id: string; name: string; nodeId: string }return { id, name: "research", nodeId: "subagents/research" };}-function makeAddress(kind: AddressKind, sessionId: string) {+function makeAddress(+ kind: AddressKind,+ sessionId: string,+ credentialResolver?: { readonly resolverId?: string },+) {return kind === "agent/remote"? {callbackBaseUrl: "https://parent.example.com",+ credentialResolver,kind,sessionId,url: "https://remote.example.com",@@ -229,12 +378,13 @@ function makeAddress(kind: AddressKind, sessionId: string) {}function runningHandle(input: {+ readonly credentialResolver?: { readonly resolverId?: string };readonly id: string;readonly kind: AddressKind;readonly sessionId: string;}): AgentHandle {return {- address: makeAddress(input.kind, input.sessionId),+ address: makeAddress(input.kind, input.sessionId, input.credentialResolver),identity: makeIdentity(input.id),operation: {callId: "call-1",@@ -247,12 +397,13 @@ function runningHandle(input: {}function parkedHandle(input: {+ readonly credentialResolver?: { readonly resolverId?: string };readonly id: string;readonly kind: AddressKind;readonly sessionId: string;}): AgentHandle {return {- address: makeAddress(input.kind, input.sessionId),+ address: makeAddress(input.kind, input.sessionId, input.credentialResolver),identity: makeIdentity(input.id),lastStatus: "ready",phase: "parked",diff --git a/packages/eve/src/execution/terminate-child-sessions-step.ts b/packages/eve/src/execution/terminate-child-sessions-step.tsindex 34452427f..f825a5004 100644--- a/packages/eve/src/execution/terminate-child-sessions-step.ts+++ b/packages/eve/src/execution/terminate-child-sessions-step.ts@@ -1,26 +1,32 @@import { deserializeContext } from "#context/serialize.js";+import type { ContextContainer } from "#context/container.js";+import { getDynamicSubagentSelection } from "#context/dynamic-subagent-lifecycle.js";import { readDurableSession, type DurableSessionState } from "#execution/durable-session-store.js";import { resolveEffectiveAgentRuntime } from "#execution/effective-agent-config.js";import { hydrateDurableSession } from "#execution/session.js";+import {+ resetRemoteAgentSession,+ resolveRemoteAgentForAction,+ resolveRemoteAgentStreamHeaders,+} from "#execution/remote-agent-dispatch.js";import { cancelOwnedTask } from "#execution/tasks/parent/dispatch.js";-import { getAgentHandleStore, type AgentHandle } from "#harness/handles/store.js";+import { getAgentHandleStore } from "#harness/handles/store.js";import { createLogger, logError } from "#internal/logging.js";import { cancelRun, getWorld } from "#internal/workflow/runtime.js";import { getSessionTaskIndex } from "#tasks/session-index.js";-import { BundleKey } from "#runtime/sessions/runtime-context-keys.js";+import { BundleKey, type CompiledBundle } from "#runtime/sessions/runtime-context-keys.js";const log = createLogger("execution.terminate-child-sessions");/**- * Terminates same-deployment children the parent holds handles to when the- * parent session ends.+ * Terminates children the parent holds handles to when the parent session+ * ends.** Every nonterminal `agent/local`/`agent/self` handle is covered: `running`* and `parked` handles carry a confirmed address; a `starting` handle has* no session id yet (the child may not exist), so it is skipped with a- * debug log rather than guessed at. Remote handles are out of scope —- * documented gap: remote children survive parent termination until a- * remote-termination protocol exists.+ * debug log rather than guessed at. Remote handles are retired through the+ * authenticated session-reset route.*/export async function terminateChildSessionsStep(input: {readonly serializedContext?: Record<string, unknown>;@@ -44,12 +50,25 @@ export async function terminateChildSessionsStep(input: {// into an ended parent. Already-terminal tasks report `unreachable`,// which is the expected no-op.const taskEntries = readSessionTaskIndex(session.state, session.sessionId);- if (taskEntries.length > 0) {+ const handles = getAgentHandleStore(session.state)?.handles ?? [];+ const hasRemoteHandle = handles.some(+ (handle) => handle.phase !== "starting" && handle.address.kind === "agent/remote",+ );+ let runtimeContext:+ | {+ readonly bundle: CompiledBundle;+ readonly ctx: ContextContainer;+ }+ | undefined;+ if (taskEntries.length > 0 || hasRemoteHandle) {if (input.serializedContext === undefined) {- throw new Error("Task finalization requires serialized runtime context.");+ throw new Error("Child finalization requires serialized runtime context.");}const ctx = await deserializeContext(input.serializedContext);- const bundle = ctx.require(BundleKey);+ runtimeContext = { bundle: ctx.require(BundleKey), ctx };+ }+ if (taskEntries.length > 0) {+ const { bundle, ctx } = runtimeContext!;const effectiveAgent = resolveEffectiveAgentRuntime(bundle, ctx);const runtimeSession = hydrateDurableSession({durable: session,@@ -57,7 +76,12 @@ export async function terminateChildSessionsStep(input: {});for (const entry of taskEntries) {try {- await cancelOwnedTask({ bundle, entry, session: runtimeSession });+ await cancelOwnedTask({+ bundle,+ entry,+ serializedContext: input.serializedContext,+ session: runtimeSession,+ });} catch (error) {logError(log, "failed to cancel task during parent finalization", error, {parentSessionId: session.sessionId,@@ -67,7 +91,6 @@ export async function terminateChildSessionsStep(input: {}}- const handles = (getAgentHandleStore(session.state)?.handles ?? []).filter(isLocalChildHandle);if (handles.length === 0) {return;}@@ -82,9 +105,50 @@ export async function terminateChildSessionsStep(input: {continue;}try {- await cancelRun(await getWorld(), handle.address.sessionId, {- cancelReason: "Parent session ended",- });+ if (handle.address.kind === "agent/remote") {+ if (handle.address.credentialResolver !== undefined) {+ const resolverId = handle.address.credentialResolver.resolverId;+ const headers =+ resolverId === undefined+ ? {}+ : await resolveRemoteAgentStreamHeaders({+ bundle: runtimeContext!.bundle,+ name: handle.identity.name,+ resolverId,+ url: handle.address.url,+ });+ await resetRemoteAgentSession({+ headers,+ remote: { name: handle.identity.name, url: handle.address.url },+ sessionId: handle.address.sessionId,+ });+ } else {+ // Compatibility for handles written before resolver identity was persisted.+ const selection = getDynamicSubagentSelection(+ runtimeContext!.ctx,+ handle.identity.nodeId,+ );+ const remote = resolveRemoteAgentForAction({+ dynamicRemoteAgent: selection?.kind === "remote" ? selection.remoteAgent : undefined,+ nodeId: handle.identity.nodeId,+ registry: runtimeContext!.bundle.subagentRegistry.subagentsByNodeId,+ remoteAgentName: handle.identity.name,+ });+ if (remote.url === handle.address.url) {+ await resetRemoteAgentSession({ remote, sessionId: handle.address.sessionId });+ } else {+ await resetRemoteAgentSession({+ headers: {},+ remote: { name: handle.identity.name, url: handle.address.url },+ sessionId: handle.address.sessionId,+ });+ }+ }+ } else {+ await cancelRun(await getWorld(), handle.address.sessionId, {+ cancelReason: "Parent session ended",+ });+ }} catch (error) {logError(log, "failed to terminate child session", error, {agentId: handle.identity.id,@@ -96,11 +160,6 @@ export async function terminateChildSessionsStep(input: {}}-function isLocalChildHandle(handle: AgentHandle): boolean {- const kind = handle.phase === "starting" ? handle.target.kind : handle.address.kind;- return kind === "agent/local" || kind === "agent/self";-}-function readSessionTaskIndex(state: Parameters<typeof getSessionTaskIndex>[0],parentSessionId: string,diff --git a/packages/eve/src/execution/tools/subagent/local.ts b/packages/eve/src/execution/tools/subagent/local.tsindex 920370289..e70bbe5fb 100644--- a/packages/eve/src/execution/tools/subagent/local.ts+++ b/packages/eve/src/execution/tools/subagent/local.ts@@ -27,7 +27,7 @@ import type {RuntimeSubagentCallActionRequest,} from "#shared/action-types.js";import { SUBAGENT_TASK_RECEIPT_OUTPUT_SCHEMA } from "#tools/framework/task-contract.js";-import { PERSISTENT_SUBAGENT_TOOL_INPUT_SCHEMA } from "#tools/framework/agent-contract.js";+import { SUBAGENT_TOOL_INPUT_SCHEMA } from "#tools/framework/agent-contract.js";import { parseJsonObject } from "#shared/json.js";import { createSubagentExecutorBinding } from "#tasks/types.js";import { activeTurnId } from "#harness/active-turn-id.js";@@ -77,7 +77,7 @@ export function defineSubagent(input: SubagentDefinitionInput) {const definition = defineTool({description: input.description,execution: "background",- inputSchema: PERSISTENT_SUBAGENT_TOOL_INPUT_SCHEMA,+ inputSchema: SUBAGENT_TOOL_INPUT_SCHEMA,outputSchema: SUBAGENT_TASK_RECEIPT_OUTPUT_SCHEMA,execute: (toolInput, ctx, task) =>executeSubagentTool({ definition: input, kind: "local", task, toolContext: ctx, toolInput }),@@ -108,7 +108,7 @@ export async function executeSubagentTool(input: {const commonAction = {callId: input.toolContext.callId,description: input.definition.description,- input: parseJsonObject(PERSISTENT_SUBAGENT_TOOL_INPUT_SCHEMA.parse(input.toolInput)),+ input: parseJsonObject(SUBAGENT_TOOL_INPUT_SCHEMA.parse(input.toolInput)),name: input.definition.name,nodeId: input.definition.nodeId,};@@ -240,7 +240,6 @@ async function dispatchSubagent(input: SubagentDispatchInput): Promise<SubagentDinitiatorAuth: prepared.initiatorAuth,parentContinuationToken: input.task.taskInboxToken,parentTraceContext: prepared.parentTraceContext,- persistentSessions: true,sandboxSessionId: prepared.sandboxSessionId,serializedContext: prepared.serializedContext,session: prepared.session,diff --git a/packages/eve/src/execution/tools/subagent/remote.ts b/packages/eve/src/execution/tools/subagent/remote.tsindex 6759d6e75..f6e73a1a7 100644--- a/packages/eve/src/execution/tools/subagent/remote.ts+++ b/packages/eve/src/execution/tools/subagent/remote.ts@@ -1,6 +1,6 @@import { defineTool } from "#tools/definition.js";import { SUBAGENT_TASK_RECEIPT_OUTPUT_SCHEMA } from "#tools/framework/task-contract.js";-import { PERSISTENT_SUBAGENT_TOOL_INPUT_SCHEMA } from "#tools/framework/agent-contract.js";+import { SUBAGENT_TOOL_INPUT_SCHEMA } from "#tools/framework/agent-contract.js";import { executeSubagentTool } from "#execution/tools/subagent/local.js";export function defineRemoteSubagent(input: {@@ -11,7 +11,7 @@ export function defineRemoteSubagent(input: {return defineTool({description: input.description,execution: "background",- inputSchema: PERSISTENT_SUBAGENT_TOOL_INPUT_SCHEMA,+ inputSchema: SUBAGENT_TOOL_INPUT_SCHEMA,outputSchema: SUBAGENT_TASK_RECEIPT_OUTPUT_SCHEMA,execute: (toolInput, ctx, task) =>executeSubagentTool({ definition: input, kind: "remote", task, toolContext: ctx, toolInput }),diff --git a/packages/eve/src/execution/workflow-entry.test.ts b/packages/eve/src/execution/workflow-entry.test.tsindex 3a3845402..84a05d81c 100644--- a/packages/eve/src/execution/workflow-entry.test.ts+++ b/packages/eve/src/execution/workflow-entry.test.ts@@ -213,6 +213,43 @@ describe("workflowEntry", () => {});});+ it("finalizes children when the durable command inbox closes", async () => {+ const sessionState = createBaseSessionState();+ const serializedContext = {+ ...createSerializedContext(),+ "eve.sessionId": "wrun_test_123",+ };+ vi.mocked(createSessionStep).mockResolvedValue(createSessionStepResultForMock(sessionState));+ installHookMocks({+ deliveryHooks: [{ token: "http:test" }],+ stableHook: {+ next: vi.fn(async (): Promise<IteratorResult<SessionInboxPayload>> => ({+ done: true,+ value: undefined,+ })),+ },+ turnControls: [+ turnResult({+ action: "park",+ serializedContext,+ sessionState,+ }),+ ],+ });++ await expect(+ workflowEntry({+ input: { message: "hello there" },+ serializedContext: createSerializedContext(),+ }),+ ).resolves.toEqual({ output: "" });++ expect(terminateChildSessionsStep).toHaveBeenCalledWith({+ serializedContext,+ sessionState,+ });+ });+it("exits a conflicting initial continuation before dispatching the first turn", async () => {const sessionState = createBaseSessionState();const dispose = vi.fn();diff --git a/packages/eve/src/execution/workflow-entry.ts b/packages/eve/src/execution/workflow-entry.tsindex 3d78e11cb..8f9c76e4c 100644--- a/packages/eve/src/execution/workflow-entry.ts+++ b/packages/eve/src/execution/workflow-entry.ts@@ -568,6 +568,10 @@ async function runDriverLoop(input: {}if (next.kind === "closed") {+ await terminateChildSessionsStep({+ serializedContext: stateCursor.serializedContext,+ sessionState: stateCursor.sessionState,+ });return { kind: "result", result: { output: "" } };}diff --git a/packages/eve/src/execution/workflow-steps.test.ts b/packages/eve/src/execution/workflow-steps.test.tsindex 4aae1111a..d45a46bd5 100644--- a/packages/eve/src/execution/workflow-steps.test.ts+++ b/packages/eve/src/execution/workflow-steps.test.ts@@ -1677,7 +1677,9 @@ describe("turnStep", () => {},moduleMap: { nodes: {} },hookRegistry: createEmptyHookRegistry(),- resolvedAgent: { config: { experimental: { tasks: true } } },+ resolvedAgent: {+ config: { experimental: { tasks: true } },+ },subagentRegistry: {},toolRegistry: {},turnAgent: TestTurnAgent,@@ -1930,7 +1932,9 @@ describe("turnStep", () => {},moduleMap: { nodes: {} },hookRegistry: createEmptyHookRegistry(),- resolvedAgent: { config: { experimental: { tasks: true } } },+ resolvedAgent: {+ config: { experimental: { tasks: true } },+ },subagentRegistry: {},toolRegistry: {},turnAgent: TestTurnAgent,@@ -1992,7 +1996,9 @@ describe("turnStep", () => {},moduleMap: { nodes: {} },hookRegistry: createEmptyHookRegistry(),- resolvedAgent: { config: { experimental: { tasks: true } } },+ resolvedAgent: {+ config: { experimental: { tasks: true } },+ },subagentRegistry: {},toolRegistry: {},turnAgent: TestTurnAgent,@@ -2389,7 +2395,9 @@ describe("turnStep", () => {},moduleMap: { nodes: {} },hookRegistry: createEmptyHookRegistry(),- resolvedAgent: { config: { experimental: { tasks: true } } },+ resolvedAgent: {+ config: { experimental: { tasks: true } },+ },subagentRegistry: {},toolRegistry: {},turnAgent: TestTurnAgent,diff --git a/packages/eve/src/execution/workflow-steps.ts b/packages/eve/src/execution/workflow-steps.tsindex 609d7fb0b..2dca90c28 100644--- a/packages/eve/src/execution/workflow-steps.ts+++ b/packages/eve/src/execution/workflow-steps.ts@@ -320,8 +320,6 @@ export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResuconst dynamicInstructionsResolvers = bundle.resolvedAgent.dynamicInstructionsResolvers ?? [];const dynamicSkillResolvers = bundle.resolvedAgent.dynamicSkillResolvers ?? [];const dynamicSubagentResolvers = bundle.subagentRegistry.dynamicResolvers ?? [];- const persistentSubagentSessions =- tasksEnabled || bundle.resolvedAgent.config?.experimental?.subagentPersistentSessions === true;const dynamicToolResolvers = bundle.resolvedAgent.dynamicToolResolvers ?? [];const effectiveNode = {...bundle.graph.root,@@ -346,7 +344,6 @@ export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResuresolvers: dynamicSubagentResolvers,event: refreshEvent,messages: history.initial.messages,- persistentSessions: persistentSubagentSessions,runtimeRevision: dynamicRuntimeRevision,}),refreshDynamicSessionToolsForRuntimeRevision({@@ -401,7 +398,6 @@ export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResuresolvers: dynamicSubagentResolvers,event: emitted,messages: messages ?? [],- persistentSessions: persistentSubagentSessions,});await dispatchDynamicToolEvent({ctx,diff --git a/packages/eve/src/harness/handles/store.test.ts b/packages/eve/src/harness/handles/store.test.tsindex a11947161..d9459d4dd 100644--- a/packages/eve/src/harness/handles/store.test.ts+++ b/packages/eve/src/harness/handles/store.test.ts@@ -116,6 +116,25 @@ describe("assertPersistableAgentHandleStore", () => {});});+ it("preserves a remote child's creation-time credential resolver", () => {+ const remoteHandle: AgentHandle = {+ address: {+ callbackBaseUrl: "https://parent.example.com",+ credentialResolver: { resolverId: "dynamic-credentials-step" },+ kind: "agent/remote",+ sessionId: "remote-child",+ url: "https://remote.example.com",+ },+ identity,+ lastStatus: "waiting",+ phase: "parked",+ };++ expect(assertPersistableAgentHandleStore({ handles: [remoteHandle] })).toEqual({+ handles: [remoteHandle],+ });+ });+it("refuses to persist a malformed store", () => {const corrupt = {handles: [{ ...parkedHandle, lastStatus: "x".repeat(121) }],diff --git a/packages/eve/src/harness/handles/store.ts b/packages/eve/src/harness/handles/store.tsindex b9c52d774..6abe6c289 100644--- a/packages/eve/src/harness/handles/store.ts+++ b/packages/eve/src/harness/handles/store.ts@@ -68,6 +68,8 @@ export type AgentStartTarget =readonly url: string;/** Callback base URL stub captured at dispatch; never model-visible. */readonly callbackBaseUrl: string;+ /** Auth/header resolver selected when this child was created; `{}` means none. */+ readonly credentialResolver?: { readonly resolverId?: string };};/** Confirmed delivery coordinates of a started child. */@@ -87,6 +89,8 @@ export type AgentAddress =readonly sessionId: string;readonly url: string;readonly callbackBaseUrl: string;+ /** Auth/header resolver selected when this child was created; `{}` means none. */+ readonly credentialResolver?: { readonly resolverId?: string };};/**@@ -166,6 +170,7 @@ const startTargetSchema: z.ZodType<AgentStartTarget> = z.discriminatedUnion("kinz.strictObject({ continuationToken: nonEmptyString, kind: z.literal("agent/self") }),z.strictObject({callbackBaseUrl: z.url(),+ credentialResolver: z.strictObject({ resolverId: nonEmptyString.optional() }).optional(),kind: z.literal("agent/remote"),url: z.url(),}),@@ -184,6 +189,7 @@ const addressSchema: z.ZodType<AgentAddress> = z.discriminatedUnion("kind", [}),z.strictObject({callbackBaseUrl: z.url(),+ credentialResolver: z.strictObject({ resolverId: nonEmptyString.optional() }).optional(),kind: z.literal("agent/remote"),sessionId: nonEmptyString,url: z.url(),diff --git a/packages/eve/src/harness/tool-loop.test.ts b/packages/eve/src/harness/tool-loop.test.tsindex 10d184087..5bb79ae4f 100644--- a/packages/eve/src/harness/tool-loop.test.ts+++ b/packages/eve/src/harness/tool-loop.test.ts@@ -1009,7 +1009,6 @@ describe("createToolLoopHarness", () => {const runStep = createToolLoopHarness(createTestConfig("conversation", undefined, {- persistentSubagentSessions: true,resolveModel: vi.fn().mockResolvedValue(new MockLanguageModelV3({modelId: "claude-sonnet-4-5",@@ -1079,9 +1078,7 @@ describe("createToolLoopHarness", () => {toolResults: [],});- const runStep = createToolLoopHarness(- createTestConfig("conversation", undefined, { persistentSubagentSessions: true }),- );+ const runStep = createToolLoopHarness(createTestConfig("conversation"));const session = createTestSession({state: {[AGENT_HANDLES_STATE_KEY]: {@@ -1132,9 +1129,7 @@ describe("createToolLoopHarness", () => {toolResults: [],});- const runStep = createToolLoopHarness(- createTestConfig("conversation", undefined, { persistentSubagentSessions: true }),- );+ const runStep = createToolLoopHarness(createTestConfig("conversation"));const session = createTestSession({history: [{ content: "Delegate this.", role: "user" },@@ -1406,7 +1401,9 @@ describe("createToolLoopHarness", () => {};const runStep = createToolLoopHarness(createTestConfig("conversation", emit));- const result = await runStep(createTestSession(), { message: "Hi" });+ const result = await runStep(createTestSession({ outputSchema: { type: "object" } }), {+ message: "Hi",+ });expect(result.next).toEqual({ done: true, output: "" });expect(events.map((event) => event.type)).toEqual([@@ -2530,6 +2527,7 @@ describe("createToolLoopHarness", () => {type: "step.failed",}),);+ expect(result.session.outputSchema).toBeUndefined();});it("returns only the final assistant reply when a completed task step includes tool work", async () => {@@ -4285,6 +4283,7 @@ describe("createToolLoopHarness", () => {// same thread rather than the whole run being torn down.expect(result.next).toBeNull();expect(result.settledTurn).toEqual({ isError: true, output: "Model blew up" });+ expect(result.session.outputSchema).toBeUndefined();const types = events.map((e) => e.type);expect(types).toContain("session.started");@@ -4389,9 +4388,8 @@ describe("createToolLoopHarness", () => {it("surfaces a terminal model-call error to the parent as a failed task result", async () => {// Regression test for https://github.com/vercel/eve/issues/412 — a- // delegated subagent runs in task mode; when its model id does not- // resolve (terminal 404), the failure must reach the parent as an- // error result, not a successful empty output.+ // delegated task-mode child whose model id does not resolve (terminal 404)+ // must report an error to its parent, not a successful empty output.const error = Object.assign(new Error("No endpoints found for anthropic/claude-3.5-haiku"), {name: "AI_APICallError",statusCode: 404,@@ -6196,6 +6194,67 @@ describe("createToolLoopHarness", () => {expect(toolResult).toEqual(resumedToolResultMessage.content[0]);});+ it("defers an agents announcement until an approved sibling tool has produced its result", async () => {+ const toolResultMessage = {+ content: [+ {+ output: { type: "text", value: "ok" },+ toolCallId: "call-1",+ toolName: "bash",+ type: "tool-result",+ },+ ],+ role: "tool",+ };+ setupMockAgent({+ content: [],+ finishReason: "stop",+ response: { messages: [{ content: "Done.", role: "assistant" }] },+ responseMessages: [toolResultMessage, { content: "Done.", role: "assistant" }],+ text: "Done.",+ toolCalls: [],+ toolResults: [],+ });++ const pending = createPendingBashApprovalSession();+ const session = {+ ...pending,+ state: {+ ...pending.state,+ [AGENT_HANDLES_STATE_KEY]: {+ handles: [+ {+ address: {+ continuationToken: "private-token",+ kind: "agent/local" as const,+ sessionId: "child-session-123456789012",+ },+ identity: {+ id: "ag_research:123456789012",+ name: "research",+ nodeId: "subagents/research",+ },+ lastStatus: "waiting",+ phase: "parked" as const,+ },+ ],+ },+ },+ };+ const harness = createToolLoopHarness(+ createTestConfig("conversation", undefined, { tools: new Map() }),+ );++ await harness(session, {+ inputResponses: [{ optionId: "approve", requestId: "approval-1" }],+ });++ const agent = vi.mocked(ToolLoopAgent).mock.results.at(-1)?.value;+ if (agent === undefined) throw new Error("ToolLoopAgent mock did not return an instance.");+ const messages = vi.mocked(agent.generate).mock.calls[0]?.[0].messages as ModelMessage[];+ expect(JSON.stringify(messages)).not.toContain("[Agents]");+ });+it("does not persist provider-executed deferred tool-results as generic tool messages", async () => {const toolCallId = "srvtoolu_01HhTt9QAEancMSj7jE8CXN7";const webSearchOutput = [diff --git a/packages/eve/src/harness/tool-loop.ts b/packages/eve/src/harness/tool-loop.tsindex e231e00f2..d4c376c46 100644--- a/packages/eve/src/harness/tool-loop.ts+++ b/packages/eve/src/harness/tool-loop.ts@@ -1202,16 +1202,18 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {// results, keeping the request user-final for providers that reject// assistant-final histories. See resolveAgentsAnnouncement for the role// rationale (assistant-final rejection, prompt-cache preservation).- if (config.persistentSubagentSessions === true) {- const store = getAgentHandleStore(session.state);- if (store?.handles.some((handle) => handle.phase === "addressed") !== true) {- const announcement = resolveAgentsAnnouncement({- messages: projectHistory(messages, session.state),- store,- });- if (announcement !== undefined) {- messages.push({ content: announcement, role: "user" });- }+ const agentStore = getAgentHandleStore(session.state);+ if (+ agentStore !== undefined &&+ !hasUnansweredToolCall(messages) &&+ agentStore.handles.some((handle) => handle.phase === "addressed") !== true+ ) {+ const announcement = resolveAgentsAnnouncement({+ messages: projectHistory(messages, session.state),+ store: agentStore,+ });+ if (announcement !== undefined) {+ messages.push({ content: announcement, role: "user" });}}@@ -1944,6 +1946,7 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {message: errorMessage,});const settledTurn = { isError: true, output: taskFailureOutput } satisfies SettledTurn;+ session = { ...session, outputSchema: undefined };return {next: null,session: setHarnessEmissionState(session, emissionState),@@ -2335,6 +2338,26 @@ function extractToolResultCallIds(messages: readonly StepResponseMessage[]): Reareturn callIds;}+/** True when provider history still owes a result for any assistant tool call. */+function hasUnansweredToolCall(messages: readonly ModelMessage[]): boolean {+ const callIds = new Set<string>();+ const resultIds = new Set<string>();++ for (const message of messages) {+ if (!Array.isArray(message.content)) continue;+ for (const part of message.content) {+ if (typeof part !== "object" || part === null) continue;+ if (part.type === "tool-call") callIds.add(part.toolCallId);+ if (part.type === "tool-result") resultIds.add(part.toolCallId);+ }+ }++ for (const callId of callIds) {+ if (!resultIds.has(callId)) return true;+ }+ return false;+}+/*** Inspects a model-call failure for the "tool type 'X' is not supported"* provider-attempt rejection that AI Gateway returns when a fallback@@ -2958,6 +2981,8 @@ async function finishTaskTurn(input: {const structured = extractFinalOutput(result);if (structured === undefined) {+ // The schema belongs to the settled invocation.+ session = { ...session, outputSchema: undefined };if (emit) {await emitFailedStep(emit, emissionState, {...OUTPUT_SCHEMA_NOT_FULFILLED,@@ -3006,6 +3031,9 @@ async function finishConversationTurn(input: {const structured = extractFinalOutput(result);if (structured === undefined) {+ // The schema belongs to the settled turn. A later conversation turn that+ // omits outputSchema must not inherit a failed turn's contract.+ session = { ...session, outputSchema: undefined };if (emit) {emissionState = await emitRecoverableFailedTurn(emit, emissionState, {...OUTPUT_SCHEMA_NOT_FULFILLED,diff --git a/packages/eve/src/harness/types.ts b/packages/eve/src/harness/types.tsindex aee44aeb2..54e0c77ed 100644--- a/packages/eve/src/harness/types.ts+++ b/packages/eve/src/harness/types.ts@@ -326,12 +326,6 @@ export interface ToolLoopHarnessConfig {* compacted history.*/readonly onCompaction?: () => readonly ModelMessage[];- /**- * Whether the agent opted into `experimental.subagentPersistentSessions`.- * Gates delegated-agent handle tracking and the model-visible `<agents>`- * listing appended after runtime-action batches resolve.- */- readonly persistentSubagentSessions?: boolean;/** Resolves step-scoped dynamic tools once for approval policy and model work. */readonly resolveStepDynamicTools?: (input: {readonly ctx: AlsContext;diff --git a/packages/eve/src/internal/authored-definition/core.test.ts b/packages/eve/src/internal/authored-definition/core.test.tsindex c74a6a427..f37904312 100644--- a/packages/eve/src/internal/authored-definition/core.test.ts+++ b/packages/eve/src/internal/authored-definition/core.test.ts@@ -253,32 +253,18 @@ describe("normalizeAgentDefinition", () => {).toThrow('"experimental.workflow.world" must be a non-empty package name');});- it("accepts a boolean subagentPersistentSessions flag", () => {- const definition = normalizeAgentDefinition(- {- model: "openai/gpt-5.5",- experimental: {- subagentPersistentSessions: true,- },- },- FAILURE_MESSAGE,- );-- expect(definition.experimental?.subagentPersistentSessions).toBe(true);- });-- it("rejects non-boolean subagentPersistentSessions values", () => {+ it.each([true, false])("rejects the removed subagentPersistentSessions flag", (value) => {expect(() =>normalizeAgentDefinition({model: "openai/gpt-5.5",experimental: {- subagentPersistentSessions: "yes",+ subagentPersistentSessions: value,},},FAILURE_MESSAGE,),- ).toThrow('"experimental.subagentPersistentSessions" must be a boolean.');+ ).toThrow('Unknown key "subagentPersistentSessions"');});it("accepts a boolean tasks flag", () => {diff --git a/packages/eve/src/internal/authored-definition/core.ts b/packages/eve/src/internal/authored-definition/core.tsindex 013a5ed9f..281a0fd92 100644--- a/packages/eve/src/internal/authored-definition/core.ts+++ b/packages/eve/src/internal/authored-definition/core.ts@@ -258,11 +258,7 @@ function normalizeAgentExperimentalDefinition(message: string,): NonNullable<NormalizedAgentDefinition["experimental"]> {const record = expectObjectRecord(value, message);- expectOnlyKnownKeys(- record,- ["instrumentationProviders", "subagentPersistentSessions", "tasks", "workflow"],- message,- );+ expectOnlyKnownKeys(record, ["instrumentationProviders", "tasks", "workflow"], message);const normalizedDefinition: Mutable<NonNullable<NormalizedAgentDefinition["experimental"]>> = {};if (record.instrumentationProviders !== undefined) {@@ -272,13 +268,6 @@ function normalizeAgentExperimentalDefinition(normalizedDefinition.instrumentationProviders = record.instrumentationProviders;}- if (record.subagentPersistentSessions !== undefined) {- if (typeof record.subagentPersistentSessions !== "boolean") {- throw new Error(`${message} "experimental.subagentPersistentSessions" must be a boolean.`);- }- normalizedDefinition.subagentPersistentSessions = record.subagentPersistentSessions;- }-if (record.tasks !== undefined) {if (typeof record.tasks !== "boolean") {throw new Error(`${message} "experimental.tasks" must be a boolean.`);diff --git a/packages/eve/src/runtime/agent/bootstrap.test.ts b/packages/eve/src/runtime/agent/bootstrap.test.tsindex ca6a73a80..cd9324b2a 100644--- a/packages/eve/src/runtime/agent/bootstrap.test.ts+++ b/packages/eve/src/runtime/agent/bootstrap.test.ts@@ -76,14 +76,9 @@ describe("createResolvedRuntimeTurnAgent agent-messaging gating", () => {);});- it("includes the messaging instruction for an opted-in root agent (framework agent tool)", () => {+ it("includes the messaging instruction for the root framework agent tool", () => {const turnAgent = createResolvedRuntimeTurnAgent({- agent: createResolvedAgentForTest({- config: {- experimental: { subagentPersistentSessions: true },- name: "test-agent",- } as ResolvedAgent["config"],- }),+ agent: createResolvedAgentForTest(),nodeId: ROOT_RUNTIME_AGENT_NODE_ID,tools: [createFrameworkAgentTool()],});@@ -92,17 +87,7 @@ describe("createResolvedRuntimeTurnAgent agent-messaging gating", () => {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("explains task-derived busy agents when tasks imply persistent sessions", () => {+ it("explains task-derived busy agents in task mode", () => {const turnAgent = createResolvedRuntimeTurnAgent({agent: createResolvedAgentForTest({config: {@@ -121,10 +106,7 @@ describe("createResolvedRuntimeTurnAgent agent-messaging gating", () => {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"],+ config: { name: "test-agent" } as ResolvedAgent["config"],}),nodeId: ROOT_RUNTIME_AGENT_NODE_ID,tools: [@@ -146,10 +128,7 @@ describe("createResolvedRuntimeTurnAgent agent-messaging gating", () => {it("omits the messaging instruction when no agent tool was compiled", () => {const turnAgent = createResolvedRuntimeTurnAgent({agent: createResolvedAgentForTest({- config: {- experimental: { subagentPersistentSessions: true },- name: "test-agent",- } as ResolvedAgent["config"],+ config: { name: "test-agent" } as ResolvedAgent["config"],}),nodeId: ROOT_RUNTIME_AGENT_NODE_ID,tools: [],@@ -161,10 +140,7 @@ describe("createResolvedRuntimeTurnAgent agent-messaging gating", () => {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"],+ config: { name: "test-agent" } as ResolvedAgent["config"],}),nodeId: "subagents/researcher",tools: [],diff --git a/packages/eve/src/runtime/agent/bootstrap.ts b/packages/eve/src/runtime/agent/bootstrap.tsindex a6e426c53..c3323cc1b 100644--- a/packages/eve/src/runtime/agent/bootstrap.ts+++ b/packages/eve/src/runtime/agent/bootstrap.ts@@ -112,9 +112,6 @@ export function createResolvedRuntimeTurnAgent(input: {instructions: composeRuntimeBasePrompt({connections: agent.connections,instructions: agent.instructions,- persistentSubagentSessions:- config?.experimental?.tasks === true ||- config?.experimental?.subagentPersistentSessions === true,subagentsAvailable: subagentDeclaredTool || subagentFrameworkRootTool,tasksEnabled: config?.experimental?.tasks === true,toolsAvailable: input.tools.length > 0,diff --git a/packages/eve/src/runtime/prompt/compose.test.ts b/packages/eve/src/runtime/prompt/compose.test.tsindex 1be19d5ad..e31598063 100644--- a/packages/eve/src/runtime/prompt/compose.test.ts+++ b/packages/eve/src/runtime/prompt/compose.test.ts@@ -3,9 +3,8 @@ 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", () => {+ it("includes agent messaging instructions when subagents are available", () => {const prompt = composeRuntimeBasePrompt({- persistentSubagentSessions: true,subagentsAvailable: true,});@@ -13,18 +12,8 @@ describe("composeRuntimeBasePrompt", () => {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("instructs task-mode parents to rely on notifications instead of polling", () => {const prompt = composeRuntimeBasePrompt({- persistentSubagentSessions: true,subagentsAvailable: true,tasksEnabled: true,});@@ -42,7 +31,6 @@ describe("composeRuntimeBasePrompt", () => {it("omits agent messaging instructions when subagents are unavailable", () => {const prompt = composeRuntimeBasePrompt({- persistentSubagentSessions: true,subagentsAvailable: false,});diff --git a/packages/eve/src/runtime/prompt/compose.ts b/packages/eve/src/runtime/prompt/compose.tsindex 618c623a8..f20d56e10 100644--- a/packages/eve/src/runtime/prompt/compose.ts+++ b/packages/eve/src/runtime/prompt/compose.ts@@ -24,12 +24,6 @@ const TASK_AGENT_MESSAGING_INSTRUCTION =interface ComposeRuntimeBasePromptInput {connections?: readonly ResolvedConnectionDefinition[];instructions?: readonly ResolvedInstructionsDefinition[];- /**- * Whether the agent opted into `experimental.subagentPersistentSessions`.- * Gates the agent-messaging prompt block that documents `agentId`- * continuation and the `<agents>` listing.- */- persistentSubagentSessions?: boolean;tasksEnabled?: boolean;skills?: readonly ResolvedSkillDefinition[];subagentsAvailable?: boolean;@@ -46,7 +40,7 @@ export function composeRuntimeBasePrompt(input: ComposeRuntimeBasePromptInput):...createInstructionsPromptBlocks(input.instructions),...createWorkspacePromptBlocks(input.workspaceSpec),...(input.toolsAvailable ? [PARALLEL_ACTION_INSTRUCTION] : []),- ...(input.subagentsAvailable && input.persistentSubagentSessions+ ...(input.subagentsAvailable? [input.tasksEnabled ? TASK_AGENT_MESSAGING_INSTRUCTION : AGENT_MESSAGING_INSTRUCTION]: []),...createConnectionsPromptBlocks(input.connections),diff --git a/packages/eve/src/runtime/resolve-agent-graph.ts b/packages/eve/src/runtime/resolve-agent-graph.tsindex 46d03e3c7..05389427e 100644--- a/packages/eve/src/runtime/resolve-agent-graph.ts+++ b/packages/eve/src/runtime/resolve-agent-graph.ts@@ -147,9 +147,6 @@ async function resolveRuntimeAgentNode(workspaceResourceRoot: agent.workspaceResourceRoot,});const subagentRegistry = createRuntimeSubagentRegistry({- persistentSessions:- agent.config?.experimental?.tasks === true ||- agent.config?.experimental?.subagentPersistentSessions === true,reservedToolNames: [LOAD_SKILL_TOOL_NAME,...toolRegistry.preparedTools.map((tool) => tool.name),diff --git a/packages/eve/src/runtime/resolve-agent.ts b/packages/eve/src/runtime/resolve-agent.tsindex f1dde857a..defc47dc4 100644--- a/packages/eve/src/runtime/resolve-agent.ts+++ b/packages/eve/src/runtime/resolve-agent.ts@@ -224,7 +224,6 @@ function createResolvedAgentConfig(if (manifest.config.experimental !== undefined) {config.experimental = {instrumentationProviders: manifest.config.experimental.instrumentationProviders,- subagentPersistentSessions: manifest.config.experimental.subagentPersistentSessions,tasks: manifest.config.experimental.tasks,workflow:manifest.config.experimental.workflow === undefineddiff --git a/packages/eve/src/runtime/subagents/registry.ts b/packages/eve/src/runtime/subagents/registry.tsindex 8c9f22e83..3508d5b89 100644--- a/packages/eve/src/runtime/subagents/registry.ts+++ b/packages/eve/src/runtime/subagents/registry.ts@@ -6,10 +6,7 @@ import type {} from "#runtime/types.js";import type { JsonObject } from "#shared/json.js";import { serializeInputSchema } from "#tools/schema.js";-import {- PERSISTENT_SUBAGENT_TOOL_INPUT_SCHEMA,- SUBAGENT_TOOL_INPUT_SCHEMA,-} from "#tools/framework/agent-contract.js";+import { SUBAGENT_TOOL_INPUT_SCHEMA } from "#tools/framework/agent-contract.js";/*** One runtime-owned subagent tracked by the prepared registry.@@ -42,32 +39,14 @@ export interface RuntimeSubagentRegistry {*/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[] = [];@@ -94,7 +73,7 @@ export function createRuntimeSubagentRegistry(input: {let registeredSubagent: RuntimeRegisteredSubagent;const dynamic = subagentDefinition.kind === "subagent" ? subagentDefinition.dynamic : undefined;if (dynamic === undefined) {- const prepared = createPreparedRuntimeSubagentTool(subagentDefinition, inputSchema);+ const prepared = createPreparedRuntimeSubagentTool(subagentDefinition);registeredSubagent = {definition: subagentDefinition,prepared,diff --git a/packages/eve/src/shared/agent-definition.ts b/packages/eve/src/shared/agent-definition.tsindex dbeb68760..1ff61d245 100644--- a/packages/eve/src/shared/agent-definition.ts+++ b/packages/eve/src/shared/agent-definition.ts@@ -200,18 +200,11 @@ export interface AgentExperimentalDefinition {* `instrumentation/` directory is.*/readonly instrumentationProviders?: boolean;- /**- * Keeps this agent's delegated subagent sessions alive after they answer.- * The model can pass `agentId` to a subagent tool to continue a previous- * delegation, and the system prompt documents the `<agents>` listing.- * When unset, delegated children run as one-shot tasks.- */- readonly subagentPersistentSessions?: boolean;/*** Runs this agent's delegated subagent calls as durable background tasks.* The originating tool call returns a task receipt immediately and the- * model manages the work through the `task_*` framework tools. Implies- * persistent-session children for subagent dispatch. Root agents only.+ * model manages the work through the `task_*` framework tools. Root agents+ * only.*/readonly tasks?: boolean;/**diff --git a/packages/eve/src/tasks/types.test.ts b/packages/eve/src/tasks/types.test.tsindex 450b67c26..308f8136a 100644--- a/packages/eve/src/tasks/types.test.ts+++ b/packages/eve/src/tasks/types.test.ts@@ -21,6 +21,7 @@ const localAddress: AgentAddress = {const remoteAddress: AgentAddress = {callbackBaseUrl: "https://parent.example",+ credentialResolver: { resolverId: "dynamic-credentials-step" },kind: "agent/remote",sessionId: "session_child",url: "https://child.example",@@ -38,6 +39,16 @@ describe("subagent executor binding", () => {expect(readSubagentExecutor(binding)).toEqual({ address: remoteAddress, identity });});+ it("round-trips an explicit no-credential remote resolver", () => {+ const address: AgentAddress = {+ ...remoteAddress,+ credentialResolver: {},+ };+ const binding = createSubagentExecutorBinding({ address, identity });++ expect(readSubagentExecutor(binding)).toEqual({ address, identity });+ });+it("reads the binding recorded on task executor state", () => {const binding = createSubagentExecutorBinding({ address: localAddress, identity });expect(readSubagentExecutor({ binding })).toEqual({ address: localAddress, identity });diff --git a/packages/eve/src/tasks/types.ts b/packages/eve/src/tasks/types.tsindex f1573824c..05addd3f5 100644--- a/packages/eve/src/tasks/types.ts+++ b/packages/eve/src/tasks/types.ts@@ -116,7 +116,7 @@ function readAgentIdentity(value: JsonValue | undefined): AgentIdentity | undefifunction readAgentAddress(value: JsonValue | undefined): AgentAddress | undefined {if (value === undefined || !isJsonObjectValue(value)) return undefined;- const { callbackBaseUrl, continuationToken, kind, sessionId, url } = value;+ const { callbackBaseUrl, continuationToken, credentialResolver, kind, sessionId, url } = value;if (typeof sessionId !== "string") return undefined;if (kind === "agent/local" || kind === "agent/self") {return typeof continuationToken === "string"@@ -124,13 +124,32 @@ function readAgentAddress(value: JsonValue | undefined): AgentAddress | undefine: undefined;}if (kind === "agent/remote") {- return typeof url === "string" && typeof callbackBaseUrl === "string"- ? { callbackBaseUrl, kind, sessionId, url }- : undefined;+ const resolver = readCredentialResolver(credentialResolver);+ if (credentialResolver !== undefined && resolver === undefined) return undefined;+ if (typeof url !== "string" || typeof callbackBaseUrl !== "string") return undefined;+ const address: {+ callbackBaseUrl: string;+ credentialResolver?: { readonly resolverId?: string };+ kind: "agent/remote";+ sessionId: string;+ url: string;+ } = { callbackBaseUrl, kind, sessionId, url };+ if (resolver !== undefined) address.credentialResolver = resolver;+ return address;}return undefined;}+function readCredentialResolver(+ value: JsonValue | undefined,+): { readonly resolverId?: string } | undefined {+ if (value === undefined) return undefined;+ if (!isJsonObjectValue(value)) return undefined;+ const { resolverId } = value;+ if (resolverId !== undefined && typeof resolverId !== "string") return undefined;+ return resolverId === undefined ? {} : { resolverId };+}+export function sameTaskMetadata(left: DurableTaskMetadata, right: DurableTaskMetadata): boolean {if (left.kind !== right.kind || left.name !== right.name) return false;const leftSubagent = "agentId" in left;diff --git a/packages/eve/src/tools/framework/agent-contract.ts b/packages/eve/src/tools/framework/agent-contract.tsindex ff0bbcb12..67d8a6f8f 100644--- a/packages/eve/src/tools/framework/agent-contract.ts+++ b/packages/eve/src/tools/framework/agent-contract.ts@@ -3,13 +3,20 @@ import { z } from "#compiled/zod/index.js";export const AGENT_TOOL_NAME = "agent";export const AGENT_TOOL_DESCRIPTION = [- "Delegate a focused subtask to a fresh copy of yourself.",+ "Delegate a focused subtask to a copy of yourself, or continue a previous delegation with `agentId`.","Use it to isolate complex work or split a large task into independent pieces.","Issue multiple `agent` calls in one response to run a small fixed set in parallel.",- "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.",+ "A new 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(" ");export const SUBAGENT_TOOL_INPUT_SCHEMA = z.strictObject({+ 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(),message: z.string().describe(@@ -22,13 +29,3 @@ export const SUBAGENT_TOOL_INPUT_SCHEMA = z.strictObject({).optional(),});--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(),-});diff --git a/packages/eve/test/runtime-subagent-registry.test.ts b/packages/eve/test/runtime-subagent-registry.test.tsindex 3edaf5c1f..f7ae9ae60 100644--- a/packages/eve/test/runtime-subagent-registry.test.ts+++ b/packages/eve/test/runtime-subagent-registry.test.ts@@ -2,12 +2,17 @@ import { describe, expect, it } from "vitest";import { RuntimeRegistryError } from "../src/internal/runtime-registry.js";import { createRuntimeSubagentRegistry } from "../src/runtime/subagents/registry.js";-import { PERSISTENT_SUBAGENT_TOOL_INPUT_SCHEMA } from "../src/tools/framework/agent-contract.js";+import { SUBAGENT_TOOL_INPUT_SCHEMA as subagentToolInputSchema } from "../src/tools/framework/agent-contract.js";import type { ResolvedRuntimeSubagentNode } from "../src/runtime/types.js";const SUBAGENT_TOOL_INPUT_SCHEMA = {type: "object",properties: {+ agentId: {+ anyOf: [{ type: "string" }, { type: "null" }],+ description:+ "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).",+ },message: {type: "string",description:@@ -19,9 +24,9 @@ const SUBAGENT_TOOL_INPUT_SCHEMA = {} as const;describe("createRuntimeSubagentRegistry", () => {- it("accepts null as an omitted persistent agentId", () => {+ it("accepts null as an omitted agentId", () => {expect(- PERSISTENT_SUBAGENT_TOOL_INPUT_SCHEMA.parse({+ subagentToolInputSchema.parse({agentId: null,message: "Investigate this",}),diff --git a/packages/eve/test/scenarios/compile-agent.scenario.test.ts b/packages/eve/test/scenarios/compile-agent.scenario.test.tsindex afbcd0a52..b5b964f97 100644--- a/packages/eve/test/scenarios/compile-agent.scenario.test.ts+++ b/packages/eve/test/scenarios/compile-agent.scenario.test.ts@@ -1049,6 +1049,29 @@ describe("compileAgent", () => {await expect(compileAgent({ startPath: appRoot })).rejects.toThrow("codeMode");});+ it("rejects the removed experimental.subagentPersistentSessions field", async () => {+ const { agentRoot, appRoot } = await createAppRoot(+ "eve-compile-experimental-subagent-persistence-",+ APP_ROOT_OPTIONS,+ );++ await writeFile(join(agentRoot, "instructions.md"), "You are a precise assistant.");+ await writeFile(+ join(agentRoot, "agent.mjs"),+ [+ "export default {",+ ' model: "openai/gpt-5.4",',+ " experimental: { subagentPersistentSessions: true },",+ "};",+ "",+ ].join("\n"),+ );++ await expect(compileAgent({ startPath: appRoot })).rejects.toThrow(+ "subagentPersistentSessions",+ );+ });+it("uses the authored local subagent id as the canonical compiled runtime id", async () => {const { agentRoot, appRoot } = await createAppRoot("eve-compile-subagent-id-",diff --git a/packages/eve/test/scenarios/mounted-extension-directory-override.scenario.test.ts b/packages/eve/test/scenarios/mounted-extension-directory-override.scenario.test.tsindex c2a5ffb20..6350a14b7 100644--- a/packages/eve/test/scenarios/mounted-extension-directory-override.scenario.test.ts+++ b/packages/eve/test/scenarios/mounted-extension-directory-override.scenario.test.ts@@ -192,7 +192,7 @@ describe("mounted extension via directory form with override", () => {kind: "eve-extension",formatVersion: 1,builtWithEve: "0.0.0-test",- requires: { extension: 1, subagent: 2 },+ requires: { extension: 1, subagent: 3 },}),"node_modules/@acme/crm/extension/extension.mjs": ['import { defineExtension } from "eve/extension";',diff --git a/packages/eve/test/scenarios/mounted-extension-installed.scenario.test.ts b/packages/eve/test/scenarios/mounted-extension-installed.scenario.test.tsindex 7faae7da4..db13b1ec6 100644--- a/packages/eve/test/scenarios/mounted-extension-installed.scenario.test.ts+++ b/packages/eve/test/scenarios/mounted-extension-installed.scenario.test.ts@@ -249,7 +249,7 @@ describe("mounted extension installed under node_modules", () => {);expect(JSON.parse(extensionFiles[`node_modules/${PACKAGE_NAME}/dist/extension/_manifest.json`]!),- ).toMatchObject({ requires: { channel: 9, schedule: 3, subagent: 2 } });+ ).toMatchObject({ requires: { channel: 9, schedule: 3, subagent: 3 } });const app = await scenarioApp({name: "mounted-extension-installed",installDependencies: true,diff --git a/research/programmatic-agent-sources.md b/research/programmatic-agent-sources.mdindex b13ec98b4..0880f0b70 100644--- a/research/programmatic-agent-sources.md+++ b/research/programmatic-agent-sources.md@@ -1100,7 +1100,8 @@ and v3 inspection metadata. The compiler diagnostic artifact moves fromversion 1 to version 2 in the same PR. Disk and bundled loaders rejectearlier serialized shapes rather than repairing them. The complete version 42schema, its single semantic validator, and serialization fixtures land first-inside the PR, and the serialized shape does not change again within it. Kernel preparation+inside the PR, and the serialized shape does not change again within it; the+same rule applies to version 44 in PR 2. Kernel preparationswitches from catalog membership to slot survival: a capability prepares onlywhen its canonical source survived composition, and agent-info v3 derives itsprepared kernel entries from that survival plus the static kind mapping.diff --git a/research/subagents-as-tasks-implementation.md b/research/subagents-as-tasks-implementation.mdindex bddf37f40..4b64695f4 100644--- a/research/subagents-as-tasks-implementation.md+++ b/research/subagents-as-tasks-implementation.md@@ -1,7 +1,7 @@---issue: https://github.com/vercel/eve/issues/1084status: draft-last_updated: "2026-08-20"+last_updated: "2026-08-24"---# Subagents as tasks: additive delivery plan@@ -42,13 +42,12 @@ Tasks must not build a second addressing mechanism. The task record composes witTask identity reuses the operation-id derivation, `hash(parentSessionId, parentTurnId, callId)`,so replayed creation for the same originating call yields the same task without new machinery.-### Flag composition+### Persistent subagent baseline`agentId` follow-ups to a finished child require conversation-mode children and parked-handles, which `experimental.subagentPersistentSessions` gates today. `experimental.tasks`-therefore implies persistent-session children for subagent dispatch. Whether it sets the other-flag or simply selects the same behavior internally is a stage-4 decision; the two flags must-not produce a third hybrid mode.+handles. Persistent subagent sessions are the default: every subagent tool exposes `agentId`, and+children park after each turn so later calls can continue the same session. `experimental.tasks`+selects background-task execution only; it does not change child identity or lifecycle.## Additivity rules@@ -62,7 +61,8 @@ Each PR in this plan must satisfy:them until the stage that selects the mode. Receivers land before senders.3. New modules over edits to shared modules wherever possible. Where a shared codepath mustbranch, the branch condition is the flag or a mode value that nothing sets yet.-4. Existing tests pass unmodified. Stages add tests; they do not rewrite flag-off expectations.+4. Existing tests pass unmodified through stage 4. Stage 5 intentionally replaces the one-shot+ default and updates those expectations.## Stages@@ -72,10 +72,9 @@ section, folding its A2A step into the baseline.### Stage 0 — flag plumbing-Add `tasks?: boolean` to `AgentExperimentalDefinition`, mirroring the-`subagentPersistentSessions` plumbing exactly: authored normalization, compiler copy, the strict-compiled-manifest schema, manifest serialization, root-only enforcement, and a-`ResolvedAgent` / harness-session projection. The flag does nothing.+Add `tasks?: boolean` to `AgentExperimentalDefinition`: authored normalization, compiler copy,+the strict compiled-manifest schema, manifest serialization, root-only enforcement, and a+`ResolvedAgent` projection. The flag does nothing.Verification: compile/manifest unit tests; a fixture with the flag on behaves identically to onewithout it.@@ -169,9 +168,17 @@ Concretely:cooperatively cancel live tasks first.Verification: the design doc's acceptance criteria become a scenario suite plus a new e2e-fixture with the flag on; existing subagent fixtures prove the flag-off path is unchanged.+fixture with the flag on; existing subagent fixtures prove task-mode selection is flag-gated.-### Stage 5 — normalize and retire+### Stage 5 — graduate persistent subagent sessions++Persistent sessions are now the default for subagent dispatch, and+`experimental.subagentPersistentSessions` is removed. The continuation semantics remain:+successful delegation returns an `agentId`, follow-ups address that child, and busy/unreachable+errors remain explicit. This graduation precedes default task execution so persistent identity is+the stable baseline rather than an incidental task-mode behavior.++### Stage 6 — normalize and retire task modeConverge local and remote subagents onto the same delegated path while preserving authoreddefinitions, then make tasks the default subagent execution and retire the flag once the