Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

test(eve): add background subagent steering evals (#3016)

Rui4b5fad41beee
diff --git a/.changeset/steer-background-subagents.md b/.changeset/steer-background-subagents.md
new file mode 100644
index 000000000..b70911d80
--- /dev/null
+++ b/.changeset/steer-background-subagents.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Steer a running background subagent by sending an updated message with its existing `agentId`. eve cancels its previous task and starts a new task in the same child session, preserving its conversation history.
diff --git a/docs/guides/remote-agents.md b/docs/guides/remote-agents.md
index 603aaf757..383c69338 100644
--- a/docs/guides/remote-agents.md
+++ b/docs/guides/remote-agents.md
@@ -180,6 +180,8 @@ The parent stream carries the same `subagent.called`, `action.result`, and `suba
An admitted task survives cancellation of the turn that started it; background work that has not yet been admitted is rejected with the cancelled step. Use `task_cancel` to stop an admitted task. 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.
+You can also steer a running remote background child by calling its subagent tool with the same `agentId` and an updated `message`. eve cancels the old task and requests cancellation of the remote turn before continuing the same remote session under a new task ID. The remote must support the standard eve cancellation and session-message routes. See [Agent messaging](../subagents#agent-messaging) for the shared steering contract.
+
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.
A failed _start_ rejects admission before a task receipt is returned. After a remote starts, a terminal failure callback fails the task and notifies the parent with 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.
diff --git a/docs/subagents/index.mdx b/docs/subagents/index.mdx
index b2c1ec191..5709bc1b2 100644
--- a/docs/subagents/index.mdx
+++ b/docs/subagents/index.mdx
@@ -12,7 +12,7 @@ The root session receives `agent` by default. The model calls it to delegate a t
```ts
{
message: string; // everything the child needs; it does not see the parent's history
- agentId?: string; // continue an existing child
+ agentId?: string; // continue or steer an existing child
outputSchema?: object; // require structured output for this turn
}
```
@@ -160,7 +160,7 @@ 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; // continue an existing child
+ agentId?: string; // continue or steer an existing child
outputSchema?: object; // require structured output for this turn
}
```
@@ -177,7 +177,11 @@ Subagent model calls automatically retry classified transient provider failures,
## Agent messaging
-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`.
+
+To steer a running background child, call the same subagent tool with its `agentId` and the updated `message`. eve cancels the previous task before starting a new task in the same child session. The child retains its conversation history, and the receipt contains the same `agentId` with a new `taskId`. The cancelled task cannot publish a later successful result. Steering does not undo tool side effects that have already occurred.
+
+A child that is still starting, or is owned by a blocking workflow invocation rather than an admitted background task, continues to return `AGENT_BUSY`. Cancellation or delivery failures are reported to the caller; eve does not start a replacement child session to hide them.
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.
diff --git a/e2e/fixtures/agent-cancellation/agent/instructions.md b/e2e/fixtures/agent-cancellation/agent/instructions.md
index db2c23427..0d5281cb7 100644
--- a/e2e/fixtures/agent-cancellation/agent/instructions.md
+++ b/e2e/fixtures/agent-cancellation/agent/instructions.md
@@ -4,10 +4,14 @@ You are a test fixture agent for turn-cancellation coverage.
# Rules
+- When the user asks for `steering-worker`, delegate the supplied message
+ verbatim to that subagent in the background. Acknowledge the receipt without
+ reporting a result.
+- When a background worker completes, relay its result verbatim once. Do not
+ report a superseded result or include result markers in acknowledgments.
- When the user asks you to delegate a cancellation wait, call the `sleeper`
subagent exactly once and tell it to wait for cancellation.
- When the user asks you to wait for cancellation yourself, call the
`wait-for-cancellation` tool exactly once, immediately, with no preamble
text before the call.
-- For any other request, answer directly and concisely without calling
- tools.
+- Answer ordinary questions directly and concisely.
diff --git a/e2e/fixtures/agent-cancellation/agent/subagents/steering-worker/agent.ts b/e2e/fixtures/agent-cancellation/agent/subagents/steering-worker/agent.ts
new file mode 100644
index 000000000..655021bc0
--- /dev/null
+++ b/e2e/fixtures/agent-cancellation/agent/subagents/steering-worker/agent.ts
@@ -0,0 +1,7 @@
+import { e2eSubagentConfig } from "@eve-e2e/config";
+import { defineAgent } from "eve";
+
+export default defineAgent({
+ description: "Carries out an assignment while preserving its memo across steering messages.",
+ ...e2eSubagentConfig(),
+});
diff --git a/e2e/fixtures/agent-cancellation/agent/subagents/steering-worker/instructions.md b/e2e/fixtures/agent-cancellation/agent/subagents/steering-worker/instructions.md
new file mode 100644
index 000000000..ca12ccff0
--- /dev/null
+++ b/e2e/fixtures/agent-cancellation/agent/subagents/steering-worker/instructions.md
@@ -0,0 +1,11 @@
+You carry out an assignment and follow steering while you work.
+
+The first message gives you `ASSIGNMENT <memo>`. Remember that memo throughout
+the assignment. Its initial result label is `ORIGINAL`.
+
+Start by calling `wait-for-cancellation` once, without a preamble, to represent
+the slow operation. Do not delegate, send progress updates, or report a result
+while that call is pending. When it returns, finish the assignment.
+
+Return only `WORKER-RESULT:<label>:<memo>`, using the latest requested label and
+the original memo. Report one result, with no explanation or superseded result.
diff --git a/e2e/fixtures/agent-cancellation/agent/subagents/steering-worker/tools/wait-for-cancellation.ts b/e2e/fixtures/agent-cancellation/agent/subagents/steering-worker/tools/wait-for-cancellation.ts
new file mode 100644
index 000000000..97c12ec6c
--- /dev/null
+++ b/e2e/fixtures/agent-cancellation/agent/subagents/steering-worker/tools/wait-for-cancellation.ts
@@ -0,0 +1 @@
+export { default } from "../../sleeper/tools/wait-for-cancellation.js";
diff --git a/e2e/fixtures/agent-cancellation/evals/cancellation/background-steering.eval.ts b/e2e/fixtures/agent-cancellation/evals/cancellation/background-steering.eval.ts
new file mode 100644
index 000000000..2988faaaf
--- /dev/null
+++ b/e2e/fixtures/agent-cancellation/evals/cancellation/background-steering.eval.ts
@@ -0,0 +1,245 @@
+import { defineEval, type EveEvalTurn } from "eve/evals";
+import { equals, satisfies } from "eve/evals/expect";
+
+const cases = [
+ {
+ parentActive: false,
+ steering: true,
+ description: "after the parent acknowledges delegation",
+ },
+ { parentActive: true, steering: true, description: "while the parent also has an active turn" },
+ {
+ parentActive: true,
+ steering: false,
+ description: "an unrelated follow-up preserves the work",
+ },
+] as const;
+
+export default cases.map(({ parentActive, steering, description }) =>
+ defineEval({
+ description: `Background subagent steering: ${description}.`,
+ // The parent chooses whether and how to redirect work. A scripted parent
+ // would bake an implementation option into the acceptance test.
+ tags: ["real-model", "background-steering"],
+ timeoutMs: 240_000,
+ async test(t) {
+ const memo = crypto.randomUUID();
+ const original = `WORKER-RESULT:ORIGINAL:${memo}`;
+ const steered = `WORKER-RESULT:STEERED:${memo}`;
+ const expected = steering ? steered : original;
+ let parent = await t.start(
+ [
+ "Call steering-worker exactly once in the background with this exact message:",
+ `ASSIGNMENT ${memo}`,
+ "Acknowledge the receipt without reporting a result. Relay its final result verbatim when it completes.",
+ "End this turn after acknowledging the receipt; the worker will keep running.",
+ ].join("\n"),
+ );
+
+ const sessionId = parent.sessionId;
+ try {
+ const acknowledged = await parent.result();
+ acknowledged.expectOk();
+ const parentTurns: EveEvalTurn[] = [acknowledged];
+ // Admission can acknowledge before the child starts. Keep observing
+ // from the cursor instead of assuming subagent.called precedes it.
+ if (!parent.events.some((event) => event.type === "subagent.called")) {
+ parent = t.target.watchTurn(sessionId, {
+ startIndex: parent.session.state!.streamIndex,
+ });
+ }
+ const called = await parent.waitForEvent("subagent.called", {
+ data: { name: "steering-worker" },
+ });
+ await t.require(
+ called.data.agentId,
+ satisfies((value) => typeof value === "string", "the worker has an agent id"),
+ );
+ const child = t.target.watchTurn(called.data.childSessionId);
+ await child.waitForEvent("actions.requested", {
+ data: {
+ actions: (actions) =>
+ actions.some(
+ (action) =>
+ action.kind === "tool-call" && action.toolName === "wait-for-cancellation",
+ ),
+ },
+ });
+
+ if (parentActive) {
+ // Establish a running child before holding another parent turn;
+ // holding the launch turn can delay dispatch until its wait ends.
+ parent = await parent.session.start("Please wait for cancellation.");
+ await parent.waitForEvent("actions.requested", {
+ data: {
+ actions: (actions) =>
+ actions.some(
+ (action) =>
+ action.kind === "tool-call" && action.toolName === "wait-for-cancellation",
+ ),
+ },
+ });
+ }
+
+ await t.require(
+ child.events,
+ satisfies(
+ (events: typeof child.events) =>
+ !events.some((event) =>
+ ["turn.completed", "turn.cancelled", "turn.failed", "session.waiting"].includes(
+ event.type,
+ ),
+ ),
+ "the follow-up arrives before the original child turn settles",
+ ),
+ );
+
+ parent = await parent.session.start(
+ steering
+ ? "Actually, use STEERED instead of ORIGINAL."
+ : "What is 2 + 2? Reply with just the number.",
+ { turnPolicy: "steer" },
+ );
+ await t.require(parent.sessionId, equals(sessionId));
+
+ if (parentActive) {
+ // start() observes from the current cursor, including the turn
+ // cancelled by this steering message before its replacement begins.
+ const cancelled = await parent.result();
+ cancelled.notEvent("turn.failed");
+ cancelled.event("turn.cancelled", { count: 1 });
+ parentTurns.push(cancelled);
+ parent = t.target.watchTurn(sessionId, {
+ startIndex: parent.session.state!.streamIndex,
+ });
+ }
+ // Observe through the result-bearing task wake, not just the parent's
+ // acknowledgment of the steering message or an AGENT_BUSY failure wake.
+ for (let attempt = 0; attempt < 6; attempt++) {
+ const turn = await parent.result();
+ parentTurns.push(turn);
+ if (
+ turn.events.some(
+ (event) =>
+ event.type === "message.received" &&
+ (JSON.stringify(event.data.message).includes(original) ||
+ JSON.stringify(event.data.message).includes(steered)),
+ )
+ ) {
+ break;
+ }
+ parent = t.target.watchTurn(sessionId, {
+ startIndex: parent.session.state!.streamIndex,
+ });
+ }
+
+ const calls = parentTurns.flatMap((turn) =>
+ turn.events.filter((event) => event.type === "subagent.called"),
+ );
+ await t.require(
+ calls,
+ satisfies(
+ (events: typeof calls) =>
+ events.length > 0 &&
+ events.every(
+ (event) =>
+ event.data.name === "steering-worker" &&
+ event.data.agentId === called.data.agentId &&
+ event.data.childSessionId === called.data.childSessionId,
+ ),
+ "all delegations address the original worker session",
+ ),
+ );
+
+ const firstChildTurn = await child.result();
+ const childWasCancelled = firstChildTurn.events.some(
+ (event) => event.type === "turn.cancelled",
+ );
+ if (steering && childWasCancelled) {
+ // Also permits cancel-and-resume of the same child; no specific
+ // control API or task-id lifetime is required by these assertions.
+ const resumed = await t.target
+ .watchTurn(called.data.childSessionId, { startIndex: child.session.state!.streamIndex })
+ .result();
+ resumed.expectOk();
+ resumed.messageIncludes(expected);
+ } else {
+ firstChildTurn.expectOk();
+ firstChildTurn.notEvent("turn.cancelled");
+ firstChildTurn.messageIncludes(expected);
+ }
+ if (steering) {
+ firstChildTurn.eventsSatisfy(
+ "the original child never emits the superseded result",
+ (events) =>
+ !events.some(
+ (event) =>
+ event.type === "message.completed" && event.data.message?.includes(original),
+ ),
+ );
+ }
+
+ // A queued follow-up extends observation beyond the first result wake
+ // without cancelling a duplicate wake that is already pending.
+ parent = await parent.session.start(
+ "Reply with exactly STEERING-CHECKPOINT. Do not repeat any earlier result or call tools.",
+ { turnPolicy: "queue" },
+ );
+ let checkpointReached = false;
+ for (let attempt = 0; attempt < 4; attempt++) {
+ const turn = await parent.result();
+ parentTurns.push(turn);
+ turn.notEvent("subagent.called");
+ if (turn.message?.includes("STEERING-CHECKPOINT")) {
+ checkpointReached = true;
+ break;
+ }
+ parent = t.target.watchTurn(sessionId, {
+ startIndex: parent.session.state!.streamIndex,
+ });
+ }
+ t.check(checkpointReached, equals(true)).label("parent processes the queued checkpoint");
+
+ const replies = parentTurns.flatMap((turn) =>
+ turn.events.flatMap((event) =>
+ event.type === "message.completed" && event.data.message !== null
+ ? [event.data.message]
+ : [],
+ ),
+ );
+ t.check(replies.filter((message) => message.includes("WORKER-RESULT:")).length, equals(1));
+ t.check(
+ replies.some((message) => message.includes(expected)),
+ equals(true),
+ );
+ if (steering)
+ t.check(
+ replies.some((message) => message.includes(original)),
+ equals(false),
+ );
+ else
+ t.check(
+ replies.some((message) => message.trim() === "4"),
+ equals(true),
+ );
+ for (const turn of parentTurns) {
+ turn.notEvent("turn.failed");
+ turn.notEvent("session.failed");
+ }
+ } finally {
+ // Reset owns admitted background tasks; cancelling only the parent
+ // turn would leave workers alive when a gate fails.
+ try {
+ const cleanup = await t.target.fetch(`/eve/v1/session/${sessionId}/reset`, {
+ method: "POST",
+ signal: AbortSignal.timeout(10_000),
+ });
+ t.check(cleanup.ok, equals(true)).label("reset cleans up background work");
+ } catch (error) {
+ t.log(`Background steering cleanup failed: ${String(error)}`);
+ t.check(false, equals(true)).label("reset cleans up background work");
+ }
+ }
+ },
+ }),
+);
diff --git a/e2e/fixtures/agent-cancellation/evals/cancellation/background-steering.md b/e2e/fixtures/agent-cancellation/evals/cancellation/background-steering.md
new file mode 100644
index 000000000..cb358fdad
--- /dev/null
+++ b/e2e/fixtures/agent-cancellation/evals/cancellation/background-steering.md
@@ -0,0 +1,78 @@
+# Background subagent steering
+
+Steering must reach the existing background child before its original work completes, preserve its context, and produce one result reflecting the updated instructions; an unrelated follow-up must leave that work running.
+
+This is a provisional acceptance contract for steering an
+already-delegated assignment. These evals use synthetic assignments to detect
+duplicate delegation and superseded results.
+
+## Cases
+
+[background-steering.eval.ts][eval] exports three cases:
+
+| Case | Parent when the follow-up arrives | Expected child behavior |
+| ------ | ------------------------------------- | -------------------------------------------------------------------------------- |
+| `0000` | Finished acknowledging the delegation | Apply the steering message to the same child session. |
+| `0001` | Waiting in its own tool call | Cancel the parent turn and apply the steering message to the same child session. |
+| `0002` | Waiting in its own tool call | Answer an unrelated question; the original child finishes normally. |
+
+The eval observes the child's pending tool call before sending the follow-up
+with the eval session driver's `start(message, { turnPolicy: "steer" })`.
+The steering message is “Actually, use STEERED instead of ORIGINAL.” It does
+not name the worker, repeat the memo, or tell the parent how to route it. The
+unrelated follow-up asks “What is 2 + 2?” without instructions about background
+work. The
+[worker][worker] uses the same real matrix model as the parent and the existing
+bounded [cancellation wait][wait] (90 seconds). Its [instructions][instructions]
+ask it to return `WORKER-RESULT:ORIGINAL:<memo>` unless steering replaces
+the label. The model must interpret the steering message, retain the original memo,
+and return `WORKER-RESULT:STEERED:<memo>`; no scripted responder selects the
+answer.
+
+Assertions inspect the child stream and the parent's result-bearing task wake.
+A parent acknowledgment alone cannot pass. All observed delegations must retain
+the original `agentId` and `childSessionId`; the original child must not emit the
+superseded result, and the parent must emit the expected result exactly once
+through a subsequent queued checkpoint. This also catches duplicate result
+wakes queued before that checkpoint; it does not prove absence of arbitrarily
+late delivery.
+The unrelated case must finish normally. Reset cleans up admitted tasks even
+when an assertion fails.
+
+Same-child continuation is provisional. The eval permits either in-turn
+steering or cancellation followed by a new turn in that same child session;
+it does not fix the task-id lifetime or require a particular steering tool.
+It permits an acknowledgment of the steering message; acknowledgment wording and
+count are outside this contract.
+
+Both parent and child use the matrix model: the parent must identify and route
+the steering message, and the child must apply it while retaining context. These cases carry `real-model`, so
+mock world suites exclude them. They are acceptance tests, not assertions that
+the existing limitation should remain. No expected-failure inversion or skip
+hides a failure. Run them in CI from this fixture with
+`pnpm exec eve eval --strict --tag background-steering`.
+
+## Options to evaluate against these cases
+
+| Option | Decision criterion | Boundary to verify |
+| ------------------------------------------------------------- | ----------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Parent calls `task_cancel`, then continues the same `agentId` | Smallest public API change: uses existing tools | Cancellation requests the child's stop, but continuation must wait until the old owner releases its claim. The eval must establish that this sequence is reliable. |
+| Explicit steering addressed to a busy `agentId` | One model action with runtime-owned ordering | Preserve the child and serialize cancellation/delivery with the existing task owner; prevent the superseded result from settling the new operation. The exact API shape is open. |
+| Automatically propagate parent steering to children | Least work for the parent model | A parent message contains no target child. Blanket propagation fails case `0002`; targeted propagation still needs a rule for selecting the affected assignment. |
+
+Current source rejects a continuation claimed by another operation as
+[`busy`][claim], mapped to [`AGENT_BUSY`][busy].
+[`cancelBackgroundAgentTask`][cancel] requests cancellation of the owned child
+turn; [`agent-settled`][settle] is a separate owner-release path. These are
+source observations, not a measured verdict for the new evals. CI results are
+needed before choosing whether existing composition is sufficient or a new
+runtime operation is warranted.
+
+[eval]: ./background-steering.eval.ts
+[worker]: ../../agent/subagents/steering-worker/agent.ts
+[instructions]: ../../agent/subagents/steering-worker/instructions.md
+[wait]: ../../agent/subagents/sleeper/tools/wait-for-cancellation.ts
+[claim]: ../../../../../packages/eve/src/subagents/handles/transitions.ts
+[busy]: ../../../../../packages/eve/src/execution/tools/subagent/invoke-step.ts
+[cancel]: ../../../../../packages/eve/src/execution/tools/subagent/task-cancel.ts
+[settle]: ../../../../../packages/eve/src/execution/tools/subagent/task-agent-requests.ts
diff --git a/e2e/fixtures/fixture-tasks/evals/task-transition.ts b/e2e/fixtures/fixture-tasks/evals/task-transition.ts
index b30ae1cbb..0caa15df6 100644
--- a/e2e/fixtures/fixture-tasks/evals/task-transition.ts
+++ b/e2e/fixtures/fixture-tasks/evals/task-transition.ts
@@ -27,6 +27,7 @@ type SemanticInput =
| "authorization-callback"
| "start-turn"
| "agent-continuation"
+ | "agent-steering"
| "task-peek"
| "task-notification"
| "task-update"
@@ -330,7 +331,7 @@ export const TASK_TRANSITIONS = {
"task.agent.continue.rejected-agent-busy": transition({
preState: { agent: "busy" },
input: "agent-continuation",
- guards: ["agent-has-a-nonterminal-task"],
+ guards: ["agent-is-claimed-by-another-call-in-the-same-batch"],
expected: {
outcome: "rejected",
postState: { agent: "busy" },
@@ -338,6 +339,17 @@ export const TASK_TRANSITIONS = {
sideEffects: { suppressed: ["task-index-write", "child-delivery"] },
},
}),
+ "task.agent.steer.accepted-busy": transition({
+ preState: { lifecycle: "working", agent: "busy", ownership: "owned" },
+ input: "agent-steering",
+ guards: ["parent-owns-admitted-task", "agent-has-a-confirmed-address"],
+ expected: {
+ outcome: "accepted",
+ postState: { lifecycle: "cancelled", agent: "busy", ownership: "owned" },
+ events: { emitted: ["background-receipt", "task-ready-notification"] },
+ sideEffects: { executed: ["child-abort", "task-index-write", "child-delivery"] },
+ },
+ }),
"task.update.emitted-working": transition({
preState: { lifecycle: "working" },
input: "task-update",
diff --git a/e2e/fixtures/fixture-tasks/evals/task.agent.continue.rejected-agent-busy.eval.ts b/e2e/fixtures/fixture-tasks/evals/task.agent.steer.accepted-busy.eval.ts
similarity index 64%
rename from e2e/fixtures/fixture-tasks/evals/task.agent.continue.rejected-agent-busy.eval.ts
rename to e2e/fixtures/fixture-tasks/evals/task.agent.steer.accepted-busy.eval.ts
index d9ea0583a..455ef55e5 100644
--- a/e2e/fixtures/fixture-tasks/evals/task.agent.continue.rejected-agent-busy.eval.ts
+++ b/e2e/fixtures/fixture-tasks/evals/task.agent.steer.accepted-busy.eval.ts
@@ -1,21 +1,26 @@
+import { satisfies } from "eve/evals/expect";
+
import { defineTaskEval } from "./task-transition.js";
import {
requireBackgroundTaskId,
+ requireTaskView,
parseToolErrorOutput,
sendAndFollowQueuedTurn,
waitForCompletedTask,
+ waitForTaskNotification,
} from "./shared.js";
-/** A persistent child with a nonterminal task rejects every competing continuation. */
+/** Same-batch calls compete for one claim; a later message steers the admitted task. */
export default defineTaskEval({
description:
- "One agentId continuation is admitted; competing continuations are rejected as AGENT_BUSY.",
+ "One same-batch continuation is admitted; later steering cancels its task and reuses the child.",
transition: {
- primary: "task.agent.continue.rejected-agent-busy",
+ primary: "task.agent.steer.accepted-busy",
setup: [
"task.dispatch.start.accepted-acknowledged",
"task.lifecycle.complete.accepted-nonterminal",
"task.agent.continue.accepted-terminal-available",
+ "task.agent.continue.rejected-agent-busy",
],
dimensions: { transport: "local", parentPhase: "active" },
},
@@ -61,15 +66,44 @@ export default defineTaskEval({
t,
`CHILD-TASK-EXCLUSIVITY-LATER ${agentId}`,
race.session,
- { allowFailedActions: true },
);
- later.turn.calledTool("busy-worker", {
- count: 1,
- output: (output) => isBusyRejection(output, admittedTaskId),
- status: "failed",
- });
+ later.turn.expectOk();
+ later.turn.calledSubagent("busy-worker", { count: 1, status: "completed" });
+ const steeredTaskId = requireBackgroundTaskId(later.turn);
+ await t.require(
+ steeredTaskId,
+ satisfies((taskId) => taskId !== admittedTaskId, "steering creates a new task identity"),
+ );
- await waitForCompletedTask(t, later.session, "CHILD-TASK-EXCLUSIVITY-VERIFY", admittedTaskId);
+ const cancelled = await waitForTaskNotification(
+ t,
+ later.session,
+ admittedTaskId,
+ "cancelled",
+ later.observedTurns,
+ );
+ const completed = await waitForCompletedTask(
+ t,
+ cancelled.session,
+ "CHILD-TASK-EXCLUSIVITY-VERIFY",
+ steeredTaskId,
+ );
+ const output = completed.requireToolCall("task_cancel").output;
+ await t.require(
+ agentIdFromTaskView(output, steeredTaskId),
+ satisfies((id) => id === agentId, "steering retains the same agent identity"),
+ );
+ const view = requireTaskView(output, steeredTaskId);
+ await t.require(
+ view.lastOutput,
+ satisfies(
+ (value) =>
+ value !== null &&
+ typeof value === "object" &&
+ Reflect.get(value, "data") === "BUSY-WORKER:Return BUSY-WORKER-LATER.",
+ "the replacement task completes with the steering message's result",
+ ),
+ );
},
});
diff --git a/packages/eve/src/execution/tasks/parent/dispatch.test.ts b/packages/eve/src/execution/tasks/parent/dispatch.test.ts
index e3c50c84e..f554e788c 100644
--- a/packages/eve/src/execution/tasks/parent/dispatch.test.ts
+++ b/packages/eve/src/execution/tasks/parent/dispatch.test.ts
@@ -76,6 +76,40 @@ describe("task cancellation", () => {
expect(cancelWorkflowToolRun).not.toHaveBeenCalled();
});
+ it("retries child cancellation after the cancelled task's inbox has closed", async () => {
+ vi.mocked(readLatestTaskView).mockResolvedValue({
+ metadata: entry.metadata,
+ status: "cancelled",
+ taskId: entry.taskId,
+ });
+ const cancelOwnedWork = vi
+ .fn()
+ .mockRejectedValueOnce(new Error("Child cancellation failed"))
+ .mockResolvedValueOnce(undefined);
+ await expect(cancelOwnedTask({ cancelOwnedWork, entry })).rejects.toThrow(
+ "Child cancellation failed",
+ );
+
+ vi.mocked(sendTaskCommand).mockResolvedValue("unreachable");
+ await expect(cancelOwnedTask({ cancelOwnedWork, entry })).resolves.toMatchObject({
+ status: "cancelled",
+ });
+ expect(cancelOwnedWork).toHaveBeenCalledTimes(2);
+ });
+
+ it("leaves child work untouched when completion won the cancellation race", async () => {
+ vi.mocked(readLatestTaskView).mockResolvedValue({
+ metadata: entry.metadata,
+ lastOutput: { type: "result", data: "Finished" },
+ status: "completed",
+ taskId: entry.taskId,
+ });
+ const cancelOwnedWork = vi.fn();
+ await cancelOwnedTask({ cancelOwnedWork, entry });
+ expect(cancelOwnedWork).not.toHaveBeenCalled();
+ expect(cancelWorkflowToolRun).not.toHaveBeenCalled();
+ });
+
it("hard-cancels a task run that does not unwind cooperatively", async () => {
vi.mocked(readLatestTaskView).mockResolvedValue({
metadata: entry.metadata,
diff --git a/packages/eve/src/execution/tasks/parent/dispatch.ts b/packages/eve/src/execution/tasks/parent/dispatch.ts
index 34809c8cc..b54883626 100644
--- a/packages/eve/src/execution/tasks/parent/dispatch.ts
+++ b/packages/eve/src/execution/tasks/parent/dispatch.ts
@@ -123,7 +123,7 @@ export async function cancelOwnedTask(input: {
readonly serializedContext?: Record<string, unknown>;
readonly session?: RuntimeSession;
}): Promise<TaskView> {
- const delivery = await sendTaskCommand({
+ await sendTaskCommand({
command: { kind: "cancel" },
taskInboxToken: input.entry.taskInboxToken,
});
@@ -139,8 +139,10 @@ export async function cancelOwnedTask(input: {
if (!isTerminalTaskStatus(view.status)) {
throw new Error(`Task "${input.entry.taskId}" did not commit cancellation before timeout.`);
}
- if (view.status !== "cancelled" || delivery !== "delivered") return view;
+ if (view.status !== "cancelled") return view;
+ // The task inbox may be closed after an earlier cancellation committed but
+ // failed to stop its child. Retrying must still finish that cancellation.
await cancelTaskOwnedWork({
cancelOwnedWork: input.cancelOwnedWork,
entry: input.entry,
diff --git a/packages/eve/src/execution/tasks/parent/tool-execution.integration.test.ts b/packages/eve/src/execution/tasks/parent/tool-execution.integration.test.ts
new file mode 100644
index 000000000..e6030f7e6
--- /dev/null
+++ b/packages/eve/src/execution/tasks/parent/tool-execution.integration.test.ts
@@ -0,0 +1,306 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { ContextContainer, contextStorage } from "#context/container.js";
+import { SessionKey } from "#context/keys.js";
+import { cancelOwnedTask } from "#execution/tasks/parent/dispatch.js";
+import { startTaskRun, waitForTaskCommandOwner } from "#execution/tasks/parent/run-parent.js";
+import {
+ backgroundToolExecutionProvider,
+ readRetainedBackgroundToolResult,
+} from "#execution/tasks/parent/tool-execution.js";
+import { cancelBackgroundAgentTask } from "#execution/tools/subagent/task-cancel.js";
+import {
+ BackgroundToolExecutorKey,
+ createBackgroundToolCallBatch,
+} from "#harness/background-tools.js";
+import { setHarnessEmissionState } from "#harness/emission-state.js";
+import { TurnCancelledError } from "#harness/turn-cancellation.js";
+import type { HarnessSession } from "#harness/types.js";
+import { getAgentHandleStore, setAgentHandleStore } from "#subagents/handles/store.js";
+import { applyTaskAgentHandleCommand } from "#subagents/handles/transitions.js";
+import { getSessionTaskIndex, recordSessionTask } from "#tasks/session-index.js";
+
+vi.mock("#execution/tasks/parent/dispatch.js", () => ({ cancelOwnedTask: vi.fn() }));
+vi.mock("#execution/tools/subagent/task-cancel.js", () => ({ cancelBackgroundAgentTask: vi.fn() }));
+vi.mock("#execution/tasks/parent/run-parent.js", () => ({
+ sendTaskCommand: vi.fn(async () => "delivered"),
+ startTaskRun: vi.fn(),
+ waitForTaskCommandOwner: vi.fn(),
+}));
+
+const identity = { id: "agent-1", name: "research", nodeId: "subagents/research" };
+const address = {
+ continuationToken: "child-token",
+ kind: "agent/local" as const,
+ sessionId: "child-session",
+};
+const handle = {
+ address,
+ callId: "original-call",
+ identity,
+ operationId: "original-operation",
+ ownerId: "original-task",
+ phase: "claimed" as const,
+};
+const entry = {
+ createdByTurnId: "turn-1",
+ metadata: { agentId: identity.id, kind: "subagent", name: identity.name },
+ taskId: handle.ownerId,
+ taskInboxToken: "original-task-inbox",
+ taskRunId: "original-task-run",
+};
+const cancelledView = {
+ metadata: entry.metadata,
+ status: "cancelled" as const,
+ taskId: entry.taskId,
+};
+
+function createSession(owned = true): HarnessSession {
+ const session = setHarnessEmissionState(
+ {
+ agent: { dynamicModel: true, system: "", tools: [] },
+ compaction: { recentWindowSize: 5, threshold: 10_000 },
+ continuationToken: "parent-token",
+ history: [],
+ sessionId: "parent",
+ state: setAgentHandleStore(undefined, { handles: [handle] }),
+ },
+ { sessionStarted: true, sequence: 2, stepIndex: 0, turnId: "turn-2" },
+ );
+ return owned ? recordSessionTask(session, entry) : session;
+}
+
+async function createScope(session = createSession()) {
+ const ctx = new ContextContainer();
+ ctx.setVirtualContext(SessionKey, {
+ auth: { current: null, initiator: null },
+ sessionId: session.sessionId,
+ turn: { id: "turn-2", sequence: 2 },
+ });
+ const created = await backgroundToolExecutionProvider.create(ctx, session);
+ if (created === undefined) throw new Error("Expected background executor");
+ const executor = created.value;
+ ctx.setVirtualContext(BackgroundToolExecutorKey, executor);
+ const batch = createBackgroundToolCallBatch();
+ return {
+ execute(
+ callId = "steering-call",
+ agentId: string | undefined = identity.id,
+ name = identity.name,
+ ) {
+ const definition = {
+ execute: vi.fn(),
+ name,
+ nodeId: identity.nodeId,
+ resultKind: "subagent" as const,
+ workflowId: "research-workflow",
+ };
+ const toolInput = { agentId, message: "Use the updated instruction" };
+ batch.setTool(name, definition);
+ batch.register({ callId, input: toolInput, toolName: name });
+ return contextStorage.run(ctx, () =>
+ executor.execute({
+ batch,
+ definition,
+ options: { messages: [], toolCallId: callId },
+ toolInput,
+ }),
+ );
+ },
+ commit: () => backgroundToolExecutionProvider.commit!(executor, session),
+ rollback: (cause: unknown) => backgroundToolExecutionProvider.rollback!(executor, cause),
+ retained: () => readRetainedBackgroundToolResult(ctx),
+ };
+}
+
+describe("background subagent steering", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.mocked(cancelOwnedTask).mockResolvedValue(cancelledView);
+ vi.mocked(startTaskRun).mockResolvedValue(undefined as never);
+ vi.mocked(waitForTaskCommandOwner).mockResolvedValue({ runId: "steering-task-run" } as never);
+ });
+
+ it("cancels the old task before starting a new task in the same child", async () => {
+ const scope = await createScope();
+ const cancellation = Promise.withResolvers<typeof cancelledView>();
+ vi.mocked(cancelOwnedTask).mockReturnValue(cancellation.promise);
+ const steering = scope.execute();
+ expect(startTaskRun).not.toHaveBeenCalled();
+ expect(cancelOwnedTask).toHaveBeenCalledWith(
+ expect.objectContaining({
+ cancelOwnedWork: cancelBackgroundAgentTask,
+ entry,
+ serializedContext: {},
+ }),
+ );
+
+ cancellation.resolve(cancelledView);
+ const receipt = await steering;
+ expect(receipt).toMatchObject({ agentId: identity.id, status: "working" });
+ const session = await scope.commit();
+ const claimed = getAgentHandleStore(session.state)?.handles[0];
+ expect(claimed).toMatchObject({ address, identity, phase: "claimed", callId: "steering-call" });
+ expect(claimed).not.toHaveProperty("ownerId", entry.taskId);
+ expect(getSessionTaskIndex(session.state)).toHaveLength(2);
+
+ const released = applyTaskAgentHandleCommand(session, {
+ kind: "release-owner",
+ ownerId: entry.taskId,
+ });
+ expect(released.session).toBe(session);
+ });
+
+ it("keeps the original claim and starts no replacement when cancellation fails", async () => {
+ const scope = await createScope();
+ vi.mocked(cancelOwnedTask).mockRejectedValue(new Error("Cancellation did not commit"));
+ await expect(scope.execute()).rejects.toThrow("Cancellation did not commit");
+ expect(startTaskRun).not.toHaveBeenCalled();
+ expect(getAgentHandleStore((await scope.commit()).state)?.handles).toEqual([handle]);
+ });
+
+ it("does not cancel a task outside the parent task index", async () => {
+ const scope = await createScope(createSession(false));
+ await expect(scope.execute()).rejects.toThrow("AGENT_BUSY");
+ expect(cancelOwnedTask).not.toHaveBeenCalled();
+ });
+
+ it("does not cancel a task associated with another child", async () => {
+ const scope = await createScope(
+ recordSessionTask(createSession(), {
+ ...entry,
+ metadata: { ...entry.metadata, agentId: "another-child" },
+ }),
+ );
+ await expect(scope.execute()).rejects.toThrow("AGENT_BUSY");
+ expect(cancelOwnedTask).not.toHaveBeenCalled();
+ });
+
+ it("rejects a different subagent tool before cancellation", async () => {
+ const scope = await createScope();
+ await expect(scope.execute("call-1", identity.id, "another-tool")).rejects.toThrow(
+ "AGENT_MISMATCH",
+ );
+ expect(cancelOwnedTask).not.toHaveBeenCalled();
+ });
+
+ it("rejects a different local/remote target before cancellation", async () => {
+ const session = createSession();
+ const scope = await createScope({
+ ...session,
+ state: setAgentHandleStore(session.state, {
+ handles: [
+ {
+ ...handle,
+ address: {
+ kind: "agent/remote",
+ sessionId: address.sessionId,
+ url: "https://child.example",
+ callbackBaseUrl: "https://parent.example",
+ },
+ },
+ ],
+ }),
+ });
+ await expect(scope.execute()).rejects.toThrow("AGENT_MISMATCH");
+ expect(cancelOwnedTask).not.toHaveBeenCalled();
+ });
+
+ it("does not steer a reservation before the child has an address", async () => {
+ const { address: _address, ...reservation } = handle;
+ const session = createSession();
+ const scope = await createScope({
+ ...session,
+ state: setAgentHandleStore(session.state, {
+ handles: [{ ...reservation, phase: "reserved" }],
+ }),
+ });
+ await expect(scope.execute()).rejects.toThrow("AGENT_BUSY");
+ expect(cancelOwnedTask).not.toHaveBeenCalled();
+ });
+
+ it("preserves a different child's claim made while cancellation was pending", async () => {
+ const second = {
+ address: { ...address, sessionId: "second-session" },
+ identity: { ...identity, id: "agent-2" },
+ phase: "available" as const,
+ };
+ const session = createSession();
+ const scope = await createScope({
+ ...session,
+ state: setAgentHandleStore(session.state, { handles: [handle, second] }),
+ });
+ const cancellation = Promise.withResolvers<typeof cancelledView>();
+ vi.mocked(cancelOwnedTask).mockReturnValue(cancellation.promise);
+ const first = scope.execute();
+ await scope.execute("second-call", second.identity.id);
+ cancellation.resolve(cancelledView);
+ await first;
+ expect(getAgentHandleStore((await scope.commit()).state)?.handles).toEqual([
+ expect.objectContaining({ identity, phase: "claimed", callId: "steering-call" }),
+ expect.objectContaining({
+ identity: second.identity,
+ phase: "claimed",
+ callId: "second-call",
+ }),
+ ]);
+ });
+
+ it("rejects competing steering before it can send a delayed child cancellation", async () => {
+ const scope = await createScope();
+ const cancellation = Promise.withResolvers<typeof cancelledView>();
+ const delayedCancellation = Promise.withResolvers<typeof cancelledView>();
+ vi.mocked(cancelOwnedTask).mockImplementation(() =>
+ vi.mocked(cancelOwnedTask).mock.calls.length === 1
+ ? cancellation.promise
+ : delayedCancellation.promise,
+ );
+ const first = scope.execute("first-call");
+ const second = scope.execute("second-call");
+ const settled = Promise.allSettled([first, second]);
+ try {
+ expect(cancelOwnedTask).toHaveBeenCalledTimes(1);
+ await expect(second).rejects.toThrow("AGENT_BUSY");
+ expect(startTaskRun).not.toHaveBeenCalled();
+ } finally {
+ cancellation.resolve(cancelledView);
+ delayedCancellation.resolve(cancelledView);
+ await settled;
+ }
+ const results = await settled;
+ expect(results.map((result) => result.status)).toEqual(["fulfilled", "rejected"]);
+ expect(startTaskRun).toHaveBeenCalledTimes(1);
+ expect(getAgentHandleStore((await scope.commit()).state)?.handles[0]).toMatchObject({
+ callId: "first-call",
+ });
+ });
+
+ it("allows another steering attempt after cancellation fails", async () => {
+ const scope = await createScope();
+ vi.mocked(cancelOwnedTask).mockRejectedValueOnce(new Error("Child cancellation failed"));
+ await expect(scope.execute("first-call")).rejects.toThrow("Child cancellation failed");
+
+ await expect(scope.execute("retry-call")).resolves.toMatchObject({
+ agentId: identity.id,
+ status: "working",
+ });
+ expect(cancelOwnedTask).toHaveBeenCalledTimes(2);
+ expect(startTaskRun).toHaveBeenCalledTimes(1);
+ expect(getAgentHandleStore((await scope.commit()).state)?.handles[0]).toMatchObject({
+ callId: "retry-call",
+ });
+ });
+
+ it("retains the released child if the parent turn is cancelled before the replacement starts", async () => {
+ const scope = await createScope();
+ const cancellation = new TurnCancelledError();
+ vi.mocked(startTaskRun).mockRejectedValueOnce(cancellation);
+ await expect(scope.execute()).rejects.toThrow(cancellation);
+ await scope.rollback(cancellation);
+ const retained = scope.retained();
+ expect(retained?.backgroundTasks).toEqual([]);
+ expect(getAgentHandleStore(retained?.backgroundTaskSession.state)?.handles).toEqual([
+ { address, identity, phase: "available" },
+ ]);
+ });
+});
diff --git a/packages/eve/src/execution/tasks/parent/tool-execution.ts b/packages/eve/src/execution/tasks/parent/tool-execution.ts
index 6b069506a..808707e65 100644
--- a/packages/eve/src/execution/tasks/parent/tool-execution.ts
+++ b/packages/eve/src/execution/tasks/parent/tool-execution.ts
@@ -4,6 +4,7 @@ import { ActivityObserverKey } from "#context/keys.js";
import type { FrameworkContextProvider } from "#context/provider.js";
import { runStep } from "#context/run-step.js";
import { buildCallbackContext } from "#context/build-callback-context.js";
+import { serializeContext } from "#context/serialize.js";
import { isAuthorizationSignal } from "#harness/authorization.js";
import { activeTurnId } from "#harness/active-turn-id.js";
import { getHarnessEmissionState } from "#harness/emission.js";
@@ -20,7 +21,7 @@ import { isAsyncIterable } from "#shared/async-iterable.js";
import { parseJsonValue } from "#shared/json.js";
import type { ToolExecuteOptions } from "#tools/definition.js";
import { createTaskMessage, isTaskMessage, type TaskExec } from "#tools/task.js";
-import { recordSessionTask } from "#tasks/session-index.js";
+import { findSessionTaskEntry, recordSessionTask } from "#tasks/session-index.js";
import type { AgentView } from "#subagents/handles/prompt.js";
import {
beginBackgroundTask,
@@ -47,6 +48,8 @@ import {
type AgentHandleStoreCommandResult,
} from "#subagents/handles/store.js";
import { applyTaskAgentHandleCommand } from "#subagents/handles/transitions.js";
+import { cancelOwnedTask } from "#execution/tasks/parent/dispatch.js";
+import { cancelBackgroundAgentTask } from "#execution/tools/subagent/task-cancel.js";
const IN_PROCESS_WORKFLOW_EXECUTOR = { data: {}, kind: "workflow-task" } as const;
@@ -135,6 +138,7 @@ export function readRetainedBackgroundToolResult(
class BackgroundToolExecutionScope implements BackgroundToolExecutor {
private readonly executions = new Map<string, Promise<unknown>>();
private readonly records: BackgroundToolExecutionRecord[] = [];
+ private readonly steeringAgents = new Set<string>();
private agentHandleSession: HarnessSession;
private agentHandlesChanged = false;
private retained = false;
@@ -212,7 +216,10 @@ class BackgroundToolExecutionScope implements BackgroundToolExecutor {
if (incomplete.length > 0) {
await this.compensate(incomplete, cause);
}
- if (settled.length === 0) return;
+ if (settled.length === 0) {
+ this.retained = this.agentHandlesChanged && isTurnCancellation(cause);
+ return;
+ }
// Cancellation must not compensate settled records: their tasks are
// already running. Retain them for readRetainedBackgroundToolResult.
if (isTurnCancellation(cause)) {
@@ -242,7 +249,7 @@ class BackgroundToolExecutionScope implements BackgroundToolExecutor {
const tasks = this.records.flatMap((record) =>
record.settled && record.task !== undefined ? [record.task] : [],
);
- if (tasks.length === 0) return undefined;
+ if (tasks.length === 0 && !this.agentHandlesChanged) return undefined;
return {
backgroundTaskSession: this.apply(this.initialSession),
backgroundTasks: tasks.map(({ taskInboxToken, taskId, taskRunId }) => ({
@@ -425,15 +432,18 @@ class BackgroundToolExecutionScope implements BackgroundToolExecutor {
parentSessionId: taskInput.parentSessionId,
parentTurnId,
});
- const claim = this.applyAgentHandleCommand({
- agentId: subagentProjection.metadata.agentId,
- callId: taskInput.callId,
- expectedTarget: subagentProjection.metadata.mode,
- invokedName: subagentProjection.metadata.name,
- kind: "claim",
- operationId,
- ownerId: task.taskId,
- });
+ const claim = await this.claimAgentForSteering(
+ {
+ agentId: subagentProjection.metadata.agentId,
+ callId: taskInput.callId,
+ expectedTarget: subagentProjection.metadata.mode,
+ invokedName: subagentProjection.metadata.name,
+ kind: "claim",
+ operationId,
+ ownerId: task.taskId,
+ },
+ input.ctx,
+ );
if (!readClaimedHandle(claim)) {
throwAgentClaimError(subagentProjection.metadata.agentId, claim);
} else {
@@ -480,6 +490,42 @@ class BackgroundToolExecutionScope implements BackgroundToolExecutor {
return { receipt: subagentProjection.receipt, task: backgroundTask };
}
+ private async claimAgentForSteering(
+ command: Extract<AgentHandleStoreCommand, { kind: "claim" }>,
+ ctx: ReturnType<typeof loadContext>,
+ ): Promise<AgentHandleStoreCommandResult> {
+ const claim = this.applyAgentHandleCommand(command);
+ if (claim.kind !== "busy" || claim.handle.phase !== "claimed") return claim;
+
+ const handle = claim.handle;
+ if (this.steeringAgents.has(handle.identity.id)) return claim;
+
+ const entry = findSessionTaskEntry(this.agentHandleSession.state, handle.ownerId);
+ if (
+ entry?.metadata.kind !== "subagent" ||
+ entry.metadata.agentId !== handle.identity.id ||
+ entry.metadata.name !== handle.identity.name
+ ) {
+ return claim;
+ }
+
+ this.steeringAgents.add(handle.identity.id);
+ try {
+ await cancelOwnedTask({
+ cancelOwnedWork: cancelBackgroundAgentTask,
+ entry,
+ serializedContext: serializeContext(ctx),
+ session: this.agentHandleSession,
+ });
+ // Other calls in this batch may have changed the store while cancellation
+ // was pending. Release only the old owner, then claim the current handle.
+ this.applyAgentHandleCommand({ kind: "release-owner", ownerId: handle.ownerId });
+ return this.applyAgentHandleCommand(command);
+ } finally {
+ this.steeringAgents.delete(handle.identity.id);
+ }
+ }
+
private applyAgentHandleCommand(command: AgentHandleStoreCommand): AgentHandleStoreCommandResult {
const applied = applyTaskAgentHandleCommand(this.agentHandleSession, command);
if (applied.session !== this.agentHandleSession) {
diff --git a/packages/eve/src/runtime/prompt/compose.ts b/packages/eve/src/runtime/prompt/compose.ts
index 7231f927e..defbd62e7 100644
--- a/packages/eve/src/runtime/prompt/compose.ts
+++ b/packages/eve/src/runtime/prompt/compose.ts
@@ -12,7 +12,7 @@ const PARALLEL_ACTION_INSTRUCTION =
"Tool execution\nA single tool or subagent call runs as one serial action. If you call multiple independent tools or subagents in one response, eve treats that batch as parallel work. Only batch work that is independent and does not rely on another call in the same response.";
const AGENT_MESSAGING_INSTRUCTION =
- "Agent messaging\nSubagent calls start durable background tasks and return immediately with a task receipt. After delegating, continue helping the user or end your turn. The task will notify you when it completes, fails, needs input, or sends an update; completion and failure notifications include the task's result. Agents you have already delegated to remain visible in the framework-authored `<agents>` conversation note. `availability=busy` means the listed task still owns that agent session: wait for its notification or use task_cancel with its taskId instead of starting a continuation. `availability=available` means no nonterminal task owns the session, so you may pass agentId to the original subagent tool to continue it. Calling a subagent without agentId always starts a new agent session.";
+ "Agent messaging\nSubagent calls start durable background tasks and return immediately with a task receipt. After delegating, continue helping the user or end your turn. The task will notify you when it completes, fails, needs input, or sends an update; completion and failure notifications include the task's result. Agents you have already delegated to remain visible in the framework-authored `<agents>` conversation note. To steer delegated work, send the updated instruction to the original subagent tool with that agentId. If availability=busy, this cancels its previous task and starts a new task in the same child session, preserving its history. Forward user steering to the affected child promptly; an acknowledgement alone does not update its work. Leave unrelated background work running. If availability=available, the same call continues the idle child. Calling a subagent without agentId starts a new agent session. Use task_cancel with its taskId to stop work without sending a replacement instruction.";
/**
* Input for composing the base authored instructions prompt for one
diff --git a/packages/eve/src/tools/framework/agent-contract.ts b/packages/eve/src/tools/framework/agent-contract.ts
index 67d8a6f8f..d46680e24 100644
--- a/packages/eve/src/tools/framework/agent-contract.ts
+++ b/packages/eve/src/tools/framework/agent-contract.ts
@@ -3,7 +3,7 @@ import { z } from "#compiled/zod/index.js";
export const AGENT_TOOL_NAME = "agent";
export const AGENT_TOOL_DESCRIPTION = [
- "Delegate a focused subtask to a copy of yourself, or continue a previous delegation with `agentId`.",
+ "Delegate a focused subtask to a copy of yourself, or continue or steer 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.",
"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.",
@@ -14,7 +14,7 @@ export const SUBAGENT_TOOL_INPUT_SCHEMA = z.strictObject({
.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).",
+ "The id of an existing agent from the <agents> list or a task receipt. A message to a busy agent steers it: its previous task is cancelled and the updated work runs in the same child session. Omit this field (or pass null or an empty string) to start a new agent.",
)
.optional(),
message: z
diff --git a/packages/eve/test/runtime-subagent-registry.test.ts b/packages/eve/test/runtime-subagent-registry.test.ts
index 9978ebee4..09e84ea6e 100644
--- a/packages/eve/test/runtime-subagent-registry.test.ts
+++ b/packages/eve/test/runtime-subagent-registry.test.ts
@@ -14,7 +14,7 @@ const SUBAGENT_TOOL_INPUT_SCHEMA = {
agentId: {
type: ["string", "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).",
+ "The id of an existing agent from the <agents> list or a task receipt. A message to a busy agent steers it: its previous task is cancelled and the updated work runs in the same child session. Omit this field (or pass null or an empty string) to start a new agent.",
},
message: {
type: "string",