The Open Framework for Building Agents
feat(eve): let background tasks update parents (#2113)
Rui77de32014fa3
diff --git a/.changeset/quiet-tasks-update.md b/.changeset/quiet-tasks-update.mdnew file mode 100644index 000000000..2139395be--- /dev/null+++ b/.changeset/quiet-tasks-update.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Let background task children send intermediate progress to their parent with `task_update`, using the existing local and remote child-to-parent transports. Remote task HITL is now presented only by the parent channel, finished agents continue through their original subagent tool with `agentId`, and the redundant `task_send` tool has been removed.diff --git a/e2e/fixtures/fixture-tasks/agent/agent.ts b/e2e/fixtures/fixture-tasks/agent/agent.tsindex 1c4d6c35c..85e378653 100644--- a/e2e/fixtures/fixture-tasks/agent/agent.ts+++ b/e2e/fixtures/fixture-tasks/agent/agent.ts@@ -12,6 +12,10 @@ const TASK_ID_PATTERN = /task_[a-z0-9]+/iu;function respond(request: MockModelRequest): MockModelResponse | string {// Framework agent-list notes are model context, not scenario turns.const message = [...request.userMessages].reverse().find(isScenarioMessage) ?? "";+ if (request.userMessages.some((entry) => entry.includes("TASK-UPDATE-PROGRESS"))) {+ return "TASK-UPDATE-RECEIVED";+ }+ if (message.includes("TASK-UPDATE-CHILD")) return sendTaskUpdate(request);if (message.includes("TASK-FANOUT-INTERACTIVE-CHECK")) return "TASK-FANOUT-INTERACTIVE-OK";if (message.includes("TASK-CANCEL-NOW")) return cancelWorkerTask(request);if (message.includes("CHILD-TASK-EXCLUSIVITY-RACE")) return raceBusyWorker(request);@@ -52,6 +56,7 @@ function respond(request: MockModelRequest): MockModelResponse | string {if (message === "TASK-FANOUT-PARENT-UPDATES") return fanoutTasks(request, 10);if (message === "TASK-PARENT-WAKE-UPDATES") return fanoutTasks(request, 3);if (message === "TASK-FAN-IN") return fanInTasks(request);+ if (message === "TASK-UPDATE-SETUP") return startTaskUpdateChild(request);if (message === "TASK-CANCEL-SETUP") return setupCancelWorker(request);if (message.startsWith("TASK-CANCEL-VERIFY ")) {return peekTask(request, "task-cancel-verify", "TASK-CANCEL-STATUS", message);@@ -99,6 +104,44 @@ function respond(request: MockModelRequest): MockModelResponse | string {return `Mock reply: ${message}`;}+function startTaskUpdateChild(request: MockModelRequest): MockModelResponse | string {+ if (resultById(request, "task-update-child") === undefined) {+ return {+ toolCalls: [+ {+ id: "task-update-child",+ input: { message: "TASK-UPDATE-CHILD" },+ name: "agent",+ },+ ],+ };+ }+ return "TASK-UPDATE-STARTED";+}++function sendTaskUpdate(request: MockModelRequest): MockModelResponse | string {+ const result = resultById(request, "task-update-progress");+ if (result === undefined) {+ return {+ toolCalls: [+ {+ id: "task-update-progress",+ input: { message: "TASK-UPDATE-PROGRESS" },+ name: "task_update",+ },+ ],+ };+ }+ if (+ result.output === null ||+ typeof result.output !== "object" ||+ Reflect.get(result.output, "status") !== "sent"+ ) {+ throw new Error("task_update did not confirm delivery.");+ }+ return "TASK-UPDATE-CHILD-DONE";+}+function fanoutTasks(request: MockModelRequest, size: number): MockModelResponse | string {const pending = Array.from({ length: size }, (_, index) => index + 1).filter((index) => resultById(request, `task-fanout-${index}`) === undefined,@@ -366,19 +409,19 @@ function raceBusyWorker(request: MockModelRequest): MockModelResponse | string {const second = resultById(request, "child-task-exclusivity-send-b");if (first === undefined && second === undefined) {const initial = resultById(request, "child-task-exclusivity-initial-worker");- const taskId = findTaskId(initial?.output);- if (taskId === undefined) throw new Error("Busy-worker race has no initial task id.");+ const agentId = findAgentId(initial?.output);+ if (agentId === undefined) throw new Error("Busy-worker race has no initial agent id.");return {toolCalls: [{id: "child-task-exclusivity-send-a",- input: { message: "Return BUSY-WORKER-A.", taskId },- name: "task_send",+ input: { agentId, message: "Return BUSY-WORKER-A." },+ name: "busy-worker",},{id: "child-task-exclusivity-send-b",- input: { message: "Return BUSY-WORKER-B.", taskId },- name: "task_send",+ input: { agentId, message: "Return BUSY-WORKER-B." },+ name: "busy-worker",},],};@@ -389,14 +432,14 @@ function raceBusyWorker(request: MockModelRequest): MockModelResponse | string {function laterBusyWorker(request: MockModelRequest, message: string): MockModelResponse | string {const result = resultById(request, "child-task-exclusivity-later");if (result === undefined) {- const taskId = findTaskId(message);- if (taskId === undefined) throw new Error("Later exclusivity send has no task id.");+ const agentId = findAgentId(message);+ if (agentId === undefined) throw new Error("Later exclusivity continuation has no agent id.");return {toolCalls: [{id: "child-task-exclusivity-later",- input: { message: "Return BUSY-WORKER-LATER.", taskId },- name: "task_send",+ input: { agentId, message: "Return BUSY-WORKER-LATER." },+ name: "busy-worker",},],};@@ -411,8 +454,8 @@ function continueApprovalWorker(const callId = "task-continuation-hitl-send";const result = resultById(request, callId);if (result === undefined) {- const taskId = findTaskId(message);- if (taskId === undefined) throw new Error("Continuation HITL send has no task id.");+ const agentId = findAgentId(message);+ if (agentId === undefined) throw new Error("Continuation HITL has no agent id.");return {toolCalls: [{@@ -420,9 +463,9 @@ function continueApprovalWorker(input: {message:"Run four continuation approval gates in order, then return CHILD-GATES-COMPLETE.",- taskId,+ agentId,},- name: "task_send",+ name: "approval-worker",},],};@@ -454,6 +497,26 @@ function findTaskId(value: unknown): string | undefined {return undefined;}+function findAgentId(value: unknown): string | undefined {+ if (typeof value === "string") return /ag_[^\s<>]+/u.exec(value)?.[0];+ if (Array.isArray(value)) {+ for (const entry of value) {+ const agentId = findAgentId(entry);+ if (agentId !== undefined) return agentId;+ }+ return undefined;+ }+ if (value !== null && typeof value === "object") {+ const agentId = Reflect.get(value, "agentId");+ if (typeof agentId === "string") return agentId;+ for (const entry of Object.values(value)) {+ const nested = findAgentId(entry);+ if (nested !== undefined) return nested;+ }+ }+ return undefined;+}+function findString(value: unknown, prefix: string): string | undefined {if (typeof value === "string") return value.startsWith(prefix) ? value : undefined;if (Array.isArray(value)) {diff --git a/e2e/fixtures/fixture-tasks/evals/task-transition.ts b/e2e/fixtures/fixture-tasks/evals/task-transition.tsindex f8a7e4708..ecbcf6a3d 100644--- a/e2e/fixtures/fixture-tasks/evals/task-transition.ts+++ b/e2e/fixtures/fixture-tasks/evals/task-transition.ts@@ -26,9 +26,10 @@ type SemanticInput =| "answer-input"| "authorization-callback"| "start-turn"- | "task-send"+ | "agent-continuation"| "task-peek"| "task-notification"+ | "task-update"| "parent-message";type SemanticEvent =@@ -36,7 +37,8 @@ type SemanticEvent =| "input-requested"| "authorization-required"| "authorization-completed"- | "task-ready-notification";+ | "task-ready-notification"+ | "task-update-notification";type SemanticSideEffect =| "task-view-append"@@ -291,9 +293,9 @@ export const TASK_TRANSITIONS = {sideEffects: { executed: ["child-dispatch", "task-index-write"] },},}),- "task.agent.send.accepted-terminal-available": transition({+ "task.agent.continue.accepted-terminal-available": transition({preState: { lifecycle: ["completed", "failed", "cancelled"], agent: "available" },- input: "task-send",+ input: "agent-continuation",guards: ["source-task-is-terminal", "agent-has-no-nonterminal-task"],expected: {outcome: "accepted",@@ -302,9 +304,9 @@ export const TASK_TRANSITIONS = {sideEffects: { executed: ["task-index-write", "child-delivery"] },},}),- "task.agent.send.rejected-agent-busy": transition({+ "task.agent.continue.rejected-agent-busy": transition({preState: { agent: "busy" },- input: "task-send",+ input: "agent-continuation",guards: ["agent-has-a-nonterminal-task"],expected: {outcome: "rejected",@@ -313,6 +315,17 @@ export const TASK_TRANSITIONS = {sideEffects: { suppressed: ["task-index-write", "child-delivery"] },},}),+ "task.update.emitted-working": transition({+ preState: { lifecycle: "working" },+ input: "task-update",+ guards: ["child-is-owned-by-task"],+ expected: {+ outcome: "emitted",+ postState: { lifecycle: "working" },+ events: { emitted: ["task-update-notification"] },+ sideEffects: { executed: ["parent-wake"], suppressed: ["task-view-append"] },+ },+ }),"task.authorization.callback.accepted-current-attempt": transition({preState: { lifecycle: "input_required", outstandingInput: "authorization" },input: "authorization-callback",diff --git a/e2e/fixtures/fixture-tasks/evals/task.agent.send.accepted-terminal-available.eval.ts b/e2e/fixtures/fixture-tasks/evals/task.agent.continue.accepted-terminal-available.eval.tssimilarity index 83%rename from e2e/fixtures/fixture-tasks/evals/task.agent.send.accepted-terminal-available.eval.tsrename to e2e/fixtures/fixture-tasks/evals/task.agent.continue.accepted-terminal-available.eval.tsindex ce79a5c9f..ddb31d8a9 100644--- a/e2e/fixtures/fixture-tasks/evals/task.agent.send.accepted-terminal-available.eval.ts+++ b/e2e/fixtures/fixture-tasks/evals/task.agent.continue.accepted-terminal-available.eval.ts@@ -11,9 +11,9 @@ import { defineTaskEval } from "./task-transition.js";/** A reused child must route every new-turn event through the new owning task. */export default defineTaskEval({- description: "task_send rebinds a reused child's HITL events to the new task lifecycle.",+ description: "An agentId continuation rebinds a reused child's HITL events to a new task.",transition: {- primary: "task.agent.send.accepted-terminal-available",+ primary: "task.agent.continue.accepted-terminal-available",setup: ["task.input.answer.accepted-complete"],dimensions: { transport: "local" },},@@ -45,23 +45,19 @@ export default defineTaskEval({firstTerminal.requireToolCall("task_peek").output,firstTaskId,);+ const firstAgentId = requireAgentId(firstView);t.log("first task completed; sending continuation");const continued = await sendAndFollowQueuedTurn(t,- `TASK-CONTINUATION-HITL-SEND ${firstTaskId}`,+ `TASK-CONTINUATION-HITL-SEND ${firstAgentId}`,second.session,);continued.turn.expectOk();- const send = continued.turn.toolCalls.find((call) => call.name === "task_send");- const secondTaskId =- send?.output !== null && typeof send?.output === "object"- ? Reflect.get(send.output, "taskId")- : undefined;- if (typeof secondTaskId !== "string") throw new Error("task_send returned no new task id.");+ const secondTaskId = requireBackgroundTaskId(continued.turn);await t.require(secondTaskId,- satisfies((taskId) => taskId !== firstTaskId, "task_send creates a new task identity"),+ satisfies((taskId) => taskId !== firstTaskId, "continuation creates a new task identity"),);t.log("continuation admitted; waiting for rebound HITL");const continuedThird = await waitForTaskInput(t, continued.session, "third_gate");@@ -89,7 +85,6 @@ export default defineTaskEval({secondTerminal.requireToolCall("task_peek").output,secondTaskId,);- const firstAgentId = requireAgentId(firstView);await t.require(secondView,satisfies(diff --git a/e2e/fixtures/fixture-tasks/evals/task.agent.continue.rejected-agent-busy.eval.ts b/e2e/fixtures/fixture-tasks/evals/task.agent.continue.rejected-agent-busy.eval.tsnew file mode 100644index 000000000..307dacf01--- /dev/null+++ b/e2e/fixtures/fixture-tasks/evals/task.agent.continue.rejected-agent-busy.eval.ts@@ -0,0 +1,96 @@+import { defineTaskEval } from "./task-transition.js";+import {+ requireBackgroundTaskId,+ sendAndFollowQueuedTurn,+ waitForCompletedTask,+} from "./shared.js";++/** A persistent child with a nonterminal task rejects every competing continuation. */+export default defineTaskEval({+ description:+ "One agentId continuation is admitted; competing continuations are rejected as AGENT_BUSY.",+ transition: {+ primary: "task.agent.continue.rejected-agent-busy",+ setup: [+ "task.dispatch.start.accepted-acknowledged",+ "task.lifecycle.complete.accepted-nonterminal",+ "task.agent.continue.accepted-terminal-available",+ ],+ dimensions: { transport: "local", parentPhase: "active" },+ },+ async test(t) {+ const setup = await t.send("CHILD-TASK-EXCLUSIVITY-SETUP");+ setup.expectOk();+ setup.messageIncludes("CHILD-TASK-EXCLUSIVITY-READY");+ const initialTaskId = requireBackgroundTaskId(setup);+ const initial = await waitForCompletedTask(+ t,+ t,+ "CHILD-TASK-EXCLUSIVITY-VERIFY",+ initialTaskId,+ );+ const agentId = agentIdFromTaskView(initial.requireToolCall("task_peek").output, initialTaskId);++ const race = await sendAndFollowQueuedTurn(t, "CHILD-TASK-EXCLUSIVITY-RACE", t, {+ allowFailedActions: true,+ });+ const raced = race.turn;+ raced.expectOk();+ raced.messageIncludes("CHILD-TASK-EXCLUSIVITY-RACE-DONE");++ const admittedTaskId = requireBackgroundTaskId(raced);+ raced.event("action.result", {+ count: 2,+ data: { result: { kind: "subagent-result", subagentName: "busy-worker" } },+ });+ raced.calledSubagent("busy-worker", {+ count: 1,+ status: "completed",+ });+ raced.calledSubagent("busy-worker", {+ count: 1,+ output: (output) => isBusyRejection(output, admittedTaskId),+ status: "failed",+ });++ const later = await sendAndFollowQueuedTurn(+ t,+ `CHILD-TASK-EXCLUSIVITY-LATER ${agentId}`,+ race.session,+ { allowFailedActions: true },+ );+ later.turn.calledSubagent("busy-worker", {+ count: 1,+ output: (output) => isBusyRejection(output, admittedTaskId),+ status: "failed",+ });++ await waitForCompletedTask(t, later.session, "CHILD-TASK-EXCLUSIVITY-VERIFY", admittedTaskId);+ },+});++function agentIdFromTaskView(output: unknown, taskId: string): string {+ if (output === null || typeof output !== "object") throw new Error("No task view output.");+ const tasks = Reflect.get(output, "tasks");+ if (!Array.isArray(tasks)) throw new Error("No task views.");+ const task = tasks.find(+ (value) =>+ value !== null && typeof value === "object" && Reflect.get(value, "taskId") === taskId,+ );+ const metadata = task !== null && typeof task === "object" ? Reflect.get(task, "metadata") : null;+ const agentId =+ metadata !== null && typeof metadata === "object" ? Reflect.get(metadata, "agentId") : null;+ if (typeof agentId !== "string") throw new Error("Task view has no agent id.");+ return agentId;+}++function isBusyRejection(output: unknown, activeTaskId?: string): boolean {+ if (output === null || typeof output !== "object") return false;+ const message = Reflect.get(output, "message");+ return (+ Reflect.get(output, "code") === "AGENT_BUSY" &&+ typeof message === "string" &&+ !Object.hasOwn(output, "taskId") &&+ (activeTaskId === undefined || message.includes(activeTaskId))+ );+}diff --git a/e2e/fixtures/fixture-tasks/evals/task.agent.send.rejected-agent-busy.eval.ts b/e2e/fixtures/fixture-tasks/evals/task.agent.send.rejected-agent-busy.eval.tsdeleted file mode 100644index f1d874f42..000000000--- a/e2e/fixtures/fixture-tasks/evals/task.agent.send.rejected-agent-busy.eval.ts+++ /dev/null@@ -1,110 +0,0 @@-import { type EveEvalToolCall } from "eve/evals";-import { satisfies } from "eve/evals/expect";--import { defineTaskEval } from "./task-transition.js";-import {- requireBackgroundTaskId,- sendAndFollowQueuedTurn,- waitForCompletedTask,-} from "./shared.js";--/** A persistent child with a nonterminal task rejects every competing send. */-export default defineTaskEval({- description:- "One competing task_send is admitted; same-batch and later sends are rejected as AGENT_BUSY without task receipts.",- transition: {- primary: "task.agent.send.rejected-agent-busy",- setup: [- "task.dispatch.start.accepted-acknowledged",- "task.lifecycle.complete.accepted-nonterminal",- "task.agent.send.accepted-terminal-available",- ],- dimensions: { transport: "local", parentPhase: "active" },- },- async test(t) {- const setup = await t.send("CHILD-TASK-EXCLUSIVITY-SETUP");- setup.expectOk();- setup.messageIncludes("CHILD-TASK-EXCLUSIVITY-READY");- const initialTaskId = requireBackgroundTaskId(setup);- await waitForCompletedTask(t, t, "CHILD-TASK-EXCLUSIVITY-VERIFY", initialTaskId);-- const race = await sendAndFollowQueuedTurn(t, "CHILD-TASK-EXCLUSIVITY-RACE", t, {- allowFailedActions: true,- });- const raced = race.turn;- raced.expectOk();- raced.messageIncludes("CHILD-TASK-EXCLUSIVITY-RACE-DONE");-- const sends = raced.toolCalls.filter((call) => call.name === "task_send");- const admitted = sends.filter(hasTaskReceipt);- await t.require(- sends,- satisfies(- (calls: readonly EveEvalToolCall[]) =>- calls.length === 2 &&- calls.filter(hasTaskReceipt).length === 1 &&- calls.filter((call) => isBusyRejection(call.output)).length === 1,- "one competing send is admitted and one is rejected without a task receipt",- ),- );-- const admittedTaskId = taskIdFromReceipt(admitted[0]);- const rejected = sends.find((call) => isBusyRejection(call.output));- await t.require(- rejected?.output,- satisfies(- (output) => isBusyRejection(output, admittedTaskId),- "the same-batch rejection identifies the admitted task and creates no task receipt",- ),- );-- const later = await sendAndFollowQueuedTurn(- t,- `CHILD-TASK-EXCLUSIVITY-LATER ${initialTaskId}`,- race.session,- { allowFailedActions: true },- );- const laterSends = later.turn.toolCalls.filter((call) => call.name === "task_send");- await t.require(- laterSends,- satisfies(- (calls: readonly EveEvalToolCall[]) =>- calls.length === 1 && isBusyRejection(calls[0]?.output, admittedTaskId),- "the later rejection creates no task receipt while the admitted task is nonterminal",- ),- );-- await waitForCompletedTask(t, later.session, "CHILD-TASK-EXCLUSIVITY-VERIFY", admittedTaskId);- },-});--function hasTaskReceipt(call: EveEvalToolCall): boolean {- return (- call.output !== null &&- typeof call.output === "object" &&- typeof Reflect.get(call.output, "agentId") === "string" &&- typeof Reflect.get(call.output, "taskId") === "string" &&- Reflect.get(call.output, "status") === "working"- );-}--function taskIdFromReceipt(call: EveEvalToolCall | undefined): string {- const output = call?.output;- const taskId =- output !== null && typeof output === "object" ? Reflect.get(output, "taskId") : null;- if (typeof taskId !== "string") throw new Error("No admitted continuation task id.");- return taskId;-}--function isBusyRejection(output: unknown, activeTaskId?: string): boolean {- if (output === null || typeof output !== "object") return false;- const keys = Object.keys(output);- const message = Reflect.get(output, "message");- return (- keys.length === 1 &&- keys[0] === "message" &&- typeof message === "string" &&- message.startsWith("AGENT_BUSY") &&- (activeTaskId === undefined || message.includes(activeTaskId))- );-}diff --git a/e2e/fixtures/fixture-tasks/evals/task.update.emitted-working.eval.ts b/e2e/fixtures/fixture-tasks/evals/task.update.emitted-working.eval.tsnew file mode 100644index 000000000..72c660d63--- /dev/null+++ b/e2e/fixtures/fixture-tasks/evals/task.update.emitted-working.eval.ts@@ -0,0 +1,61 @@+import { satisfies } from "eve/evals/expect";++import { defineTaskEval } from "./task-transition.js";+import { requireBackgroundTaskId, requireSessionStreamIndex } from "./shared.js";++const UPDATE = "TASK-UPDATE-PROGRESS";++export default defineTaskEval({+ description: "A running child sends one intermediate update to its parent through task_update.",+ transition: {+ primary: "task.update.emitted-working",+ setup: ["task.dispatch.start.accepted-acknowledged"],+ dimensions: { transport: "local", parentPhase: "parked" },+ },+ async test(t) {+ const started = await t.send("TASK-UPDATE-SETUP");+ started.expectOk();+ started.messageIncludes("TASK-UPDATE-STARTED");+ const taskId = requireBackgroundTaskId(started);++ const sessionId = t.sessionId;+ if (sessionId === undefined) throw new Error("Task update eval has no parent session id.");+ const live = t.target.watchTurn(sessionId, {+ startIndex: requireSessionStreamIndex(t, "Task update wait"),+ });+ const updateTurn = await live.result();+ updateTurn.expectOk();+ updateTurn.messageIncludes("TASK-UPDATE-RECEIVED");+ await t.require(+ updateTurn.events,+ satisfies(+ (events: typeof updateTurn.events) =>+ events.some(+ (event) =>+ event.type === "message.received" &&+ messageText(event.data.message).includes(+ `Background task ${taskId} (agent) update: ${UPDATE}`,+ ),+ ),+ "parent receives the child update with its owning task identity",+ ),+ );+ updateTurn.notEvent("subagent.completed");+ t.noFailedActions();+ },+});++function messageText(message: unknown): string {+ if (typeof message === "string") return message;+ if (!Array.isArray(message)) return "";+ return message+ .flatMap((part) =>+ part !== null &&+ typeof part === "object" &&+ Reflect.get(part, "type") === "text" &&+ typeof Reflect.get(part, "text") === "string"+ ? [Reflect.get(part, "text") as string]+ : [],+ )+ .join("\n");+}diff --git a/packages/eve/src/cli/dev/tui/tool-presentation.test.ts b/packages/eve/src/cli/dev/tui/tool-presentation.test.tsindex 1de393e84..7b63be5c0 100644--- a/packages/eve/src/cli/dev/tui/tool-presentation.test.ts+++ b/packages/eve/src/cli/dev/tui/tool-presentation.test.ts@@ -180,7 +180,7 @@ describe("presentTool", () => {read_file: { filePath: "/workspace/a.ts" },task_cancel: { taskIds: ["task_abc"] },task_peek: { taskIds: ["task_abc"] },- task_send: { message: "Continue with the next region.", taskId: "task_abc" },+ task_update: { message: "Finished the next region." },task_sleep: { seconds: 30 },todo: { todos: [] },web_fetch: { url: "https://example.com" },diff --git a/packages/eve/src/cli/dev/tui/tool-presentation.ts b/packages/eve/src/cli/dev/tui/tool-presentation.tsindex a27542e24..757b68084 100644--- a/packages/eve/src/cli/dev/tui/tool-presentation.ts+++ b/packages/eve/src/cli/dev/tui/tool-presentation.ts@@ -139,13 +139,6 @@ const BUILTIN_TOOL_COPY: Readonly<Record<string, BuiltinToolCopy>> = {singularNoun: "task",pluralNoun: "tasks",},- task_send: {- verb: "Send",- pastVerb: "Sent",- argKey: "taskId",- singularNoun: "task",- pluralNoun: "tasks",- },task_sleep: {verb: "Pause",pastVerb: "Paused",@@ -154,6 +147,13 @@ const BUILTIN_TOOL_COPY: Readonly<Record<string, BuiltinToolCopy>> = {singularNoun: "pause",pluralNoun: "pauses",},+ task_update: {+ verb: "Update",+ pastVerb: "Updated",+ argKey: "message",+ singularNoun: "parent",+ pluralNoun: "parents",+ },web_fetch: {verb: "Fetch",pastVerb: "Fetched",diff --git a/packages/eve/src/execution/create-session-step.test.ts b/packages/eve/src/execution/create-session-step.test.tsindex 3a5f4eac5..19643f55a 100644--- a/packages/eve/src/execution/create-session-step.test.ts+++ b/packages/eve/src/execution/create-session-step.test.ts@@ -18,6 +18,46 @@ const TestTurnAgent: RuntimeTurnAgent = {};describe("createSessionStep", () => {+ it("adds task_update guidance to a task-owned session system prompt", async () => {+ vi.mocked(getCompiledRuntimeAgentBundle).mockResolvedValue({+ resolvedAgent: {+ config: { experimental: { tasks: true } },+ disabledFrameworkTools: [],+ },+ turnAgent: TestTurnAgent,+ } as never);++ const { state } = await createSessionStep({+ compiledArtifactsSource: { kind: "bundled" },+ continuationToken: "subagent:test",+ sessionId: "sess-child",+ taskOwned: true,+ });++ expect(state.snapshot?.session.agent.system).toContain("Background task updates");+ expect(state.snapshot?.session.agent.system).toContain("what you are currently doing");+ expect(state.snapshot?.session.state).toBeUndefined();+ });++ it("does not add task_update guidance to a task-owned node without the tool", async () => {+ vi.mocked(getCompiledRuntimeAgentBundle).mockResolvedValue({+ resolvedAgent: {+ config: {},+ disabledFrameworkTools: [],+ },+ turnAgent: TestTurnAgent,+ } as never);++ const { state } = await createSessionStep({+ compiledArtifactsSource: { kind: "bundled" },+ continuationToken: "subagent:test",+ sessionId: "sess-child",+ taskOwned: true,+ });++ expect(state.snapshot?.session.agent.system).not.toContain("Background task updates");+ });+it("defaults root sessions to the root input token budget", async () => {vi.mocked(getCompiledRuntimeAgentBundle).mockResolvedValue({resolvedAgent: {diff --git a/packages/eve/src/execution/create-session-step.ts b/packages/eve/src/execution/create-session-step.tsindex 76933c7ad..375c429dd 100644--- a/packages/eve/src/execution/create-session-step.ts+++ b/packages/eve/src/execution/create-session-step.ts@@ -13,6 +13,8 @@ import type { RunSessionLimits } from "#channel/types.js";import type { JsonObject } from "#shared/json.js";import { resolveEffectiveAgentRuntimeFromConfig } from "#execution/effective-agent-config.js";import type { DynamicSubagentAgentConfig } from "#runtime/subagents/dynamic-agent-config.js";+import { TASK_UPDATE_SESSION_INSTRUCTION } from "#execution/tasks/child/instructions.js";+import { isTaskToolAvailable, TASK_UPDATE_TOOL_NAME } from "#runtime/framework-tools/tasks.js";/*** Result returned by {@link createSessionStep}.@@ -40,6 +42,7 @@ export async function createSessionStep(input: {readonly rootSessionId?: string;readonly sessionId: string;readonly subagentDepth?: number;+ readonly taskOwned?: boolean;}): Promise<CreateSessionStepResult> {"use step";@@ -51,6 +54,16 @@ export async function createSessionStep(input: {bundle,input.dynamicSubagentAgentConfig,);+ const taskUpdatesEnabled =+ input.taskOwned === true &&+ isTaskToolAvailable({+ disabledFrameworkTools: bundle.resolvedAgent.disabledFrameworkTools ?? [],+ hasAuthoredTool: effectiveAgent.turnAgent.tools.some(+ (tool) => tool.name === TASK_UPDATE_TOOL_NAME,+ ),+ tasksEnabled: bundle.resolvedAgent.config?.experimental?.tasks === true,+ toolName: TASK_UPDATE_TOOL_NAME,+ });// Both token axes resolve tighter-wins against the cap inherited from the// delegating parent: a child may narrow what its parent granted, never widen@@ -77,6 +90,7 @@ export async function createSessionStep(input: {rootSessionId: input.rootSessionId,sessionId: input.sessionId,subagentDepth: input.subagentDepth,+ systemPromptAdditions: taskUpdatesEnabled ? [TASK_UPDATE_SESSION_INSTRUCTION] : undefined,turnAgent: effectiveAgent.turnAgent,workflowMaxSubagents: bundle.resolvedAgent.workflowTool?.maxSubagents,});diff --git a/packages/eve/src/execution/dispatch-runtime-actions-shared.ts b/packages/eve/src/execution/dispatch-runtime-actions-shared.tsindex f7fb06351..0d197f315 100644--- a/packages/eve/src/execution/dispatch-runtime-actions-shared.ts+++ b/packages/eve/src/execution/dispatch-runtime-actions-shared.ts@@ -168,7 +168,7 @@ export async function prepareRuntimeActionDispatch(input: {readonly serializedContext: Record<string, unknown>;readonly sessionState: DurableSessionState;/**- * Classify `task_peek` / `task_cancel` / `task_send` calls as+ * Classify task-control calls as* task-control plan entries. Only task mode plans them; in plain mode* those calls fail as unsupported batch actions.*/diff --git a/packages/eve/src/execution/node-step.test.ts b/packages/eve/src/execution/node-step.test.tsindex d9541db25..1244a1b1e 100644--- a/packages/eve/src/execution/node-step.test.ts+++ b/packages/eve/src/execution/node-step.test.ts@@ -278,7 +278,7 @@ describe("createNodeHarnessTools", () => {it("does not inject task tools without experimental.tasks", () => {const tools = createNodeHarnessTools({ node: createTestNode() });- for (const name of ["task_peek", "task_cancel", "task_send", "task_sleep"]) {+ for (const name of ["task_peek", "task_cancel", "task_sleep", "task_update"]) {expect(tools.has(name)).toBe(false);}});@@ -295,7 +295,7 @@ describe("createNodeHarnessTools", () => {},});- for (const name of ["task_peek", "task_cancel", "task_send"]) {+ for (const name of ["task_peek", "task_cancel", "task_update"]) {expect(tools.get(name)?.runtimeAction).toEqual({ kind: "task-control" });expect(tools.get(name)?.execute).toBeUndefined();}diff --git a/packages/eve/src/execution/session-callback-step.test.ts b/packages/eve/src/execution/session-callback-step.test.tsindex b09cc9c73..72367b41f 100644--- a/packages/eve/src/execution/session-callback-step.test.ts+++ b/packages/eve/src/execution/session-callback-step.test.ts@@ -1,6 +1,9 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { fireSessionCallbackStep } from "#execution/session-callback-step.js";+import {+ fireSessionCallbackStep,+ fireTaskUpdateCallbackStep,+} from "#execution/session-callback-step.js";const USAGE = { cacheReadTokens: 10, cacheWriteTokens: 5, inputTokens: 100, outputTokens: 50 };@@ -298,12 +301,43 @@ describe("fireSessionCallbackStep", () => {});});-function parsePostedBody(fetchMock: ReturnType<typeof vi.fn>): { usage?: unknown } {+describe("fireTaskUpdateCallbackStep", () => {+ it("posts a progress update over a task-owned callback", async () => {+ const fetchMock = vi.fn().mockResolvedValue(new Response(null, { status: 202 }));+ vi.stubGlobal("fetch", fetchMock);++ const taskId = await fireTaskUpdateCallbackStep({+ callback: {+ callId: "parent-call",+ subagentName: "research",+ taskId: "task_abc",+ token: "task-token",+ url: "https://caller.example.com/eve/v1/callback/task-token",+ },+ callId: "update-call",+ childStepIndex: 2,+ childTurnId: "turn-child",+ message: "Found three matching records.",+ });++ expect(taskId).toBe("task_abc");+ expect(parsePostedBody(fetchMock)).toEqual({+ callId: "update-call",+ childStepIndex: 2,+ childTurnId: "turn-child",+ kind: "task.update",+ message: "Found three matching records.",+ taskId: "task_abc",+ });+ });+});++function parsePostedBody(fetchMock: ReturnType<typeof vi.fn>): Record<string, unknown> {const call = fetchMock.mock.calls[0];if (call === undefined) {throw new Error("expected fetch to have been called");}- return JSON.parse((call[1] as { body: string }).body) as { usage?: unknown };+ return JSON.parse((call[1] as { body: string }).body) as Record<string, unknown>;}function createSerializedContext(): Record<string, unknown> {diff --git a/packages/eve/src/execution/session-callback-step.ts b/packages/eve/src/execution/session-callback-step.tsindex d0a17d8d1..d36e132fb 100644--- a/packages/eve/src/execution/session-callback-step.ts+++ b/packages/eve/src/execution/session-callback-step.ts@@ -42,6 +42,35 @@ export async function fireTaskEventCallbackStep(input: {}}+/** Sends one remote task progress update over its existing parent callback. */+export async function fireTaskUpdateCallbackStep(input: {+ readonly callback: unknown;+ readonly callId: string;+ readonly childStepIndex: number;+ readonly childTurnId: string;+ readonly message: string;+}): Promise<string | undefined> {+ "use step";++ const callback = parseSerializedSessionCallback(input.callback);+ if (callback.taskId === undefined) return undefined;+ const response = await postSessionCallbackRequest({+ body: {+ callId: input.callId,+ childStepIndex: input.childStepIndex,+ childTurnId: input.childTurnId,+ kind: "task.update",+ message: input.message,+ taskId: callback.taskId,+ },+ url: callback.url,+ });+ if (!response.ok) {+ throw new Error(`Task update callback failed with HTTP ${response.status}.`);+ }+ return callback.taskId;+}+/*** Sends the configured session terminal callback.*diff --git a/packages/eve/src/execution/session.test.ts b/packages/eve/src/execution/session.test.tsindex 74da8eb4f..292bc689f 100644--- a/packages/eve/src/execution/session.test.ts+++ b/packages/eve/src/execution/session.test.ts@@ -415,6 +415,25 @@ describe("mintSubagentContinuationToken", () => {});describe("refreshSessionFromTurnAgent", () => {+ it("keeps session-specific system additions alongside refreshed authored instructions", () => {+ const session = createSession({+ continuationToken: "child-token",+ sessionId: "child-session",+ systemPromptAdditions: ["Background task updates"],+ turnAgent: createTestTurnAgent({ instructions: ["Original instructions."] }),+ });+ expect(session.agent.system).toBe("Original instructions.\n\nBackground task updates");++ const refreshed = refreshSessionFromTurnAgent({+ session,+ systemPromptAdditions: ["Background task updates"],+ turnAgent: createTestTurnAgent({ instructions: ["Updated instructions."] }),+ });++ expect(refreshed.agent.system).toBe("Updated instructions.\n\nBackground task updates");+ expect(refreshed.state).toBeUndefined();+ });+it("refreshes the current agent configuration while preserving history", () => {const session = createSession({continuationToken: "root-token",diff --git a/packages/eve/src/execution/session.ts b/packages/eve/src/execution/session.tsindex 012e5ed90..fa11653af 100644--- a/packages/eve/src/execution/session.ts+++ b/packages/eve/src/execution/session.ts@@ -73,6 +73,7 @@ export interface CreateSessionInput {readonly limits?: AuthoredSessionLimits;readonly outputSchema?: HarnessSession["outputSchema"];readonly subagentDepth?: number;+ readonly systemPromptAdditions?: readonly string[];readonly workflowMaxSubagents?: number;}@@ -84,7 +85,11 @@ export function createSession(input: CreateSessionInput): HarnessSession {const session: {-readonly [K in keyof HarnessSession]: HarnessSession[K];} = {- agent: createSessionAgent(turnAgent, createSessionSystemPrompt({ turnAgent }), tools),+ agent: createSessionAgent(+ turnAgent,+ createSessionSystemPrompt({ additions: input.systemPromptAdditions, turnAgent }),+ tools,+ ),compaction: createCompactionConfig({contextWindowTokens: turnAgent.model?.contextWindowTokens,thresholdPercent: input.compactionOverrides?.thresholdPercent,@@ -139,6 +144,7 @@ function createSessionAgent(*/export function refreshSessionFromTurnAgent(input: {readonly session: HarnessSession;+ readonly systemPromptAdditions?: readonly string[];readonly turnAgent: RuntimeTurnAgent;readonly compactionOverrides?: {readonly thresholdPercent?: number;@@ -148,7 +154,10 @@ export function refreshSessionFromTurnAgent(input: {...input.session,agent: createSessionAgent(input.turnAgent,- createSessionSystemPrompt({ turnAgent: input.turnAgent }),+ createSessionSystemPrompt({+ additions: input.systemPromptAdditions,+ turnAgent: input.turnAgent,+ }),createSessionToolDefinitions(input.turnAgent),),compaction: createCompactionConfig({@@ -160,13 +169,16 @@ export function refreshSessionFromTurnAgent(input: {};}-function createSessionSystemPrompt(input: { readonly turnAgent: RuntimeTurnAgent }): string {+function createSessionSystemPrompt(input: {+ readonly additions?: readonly string[];+ readonly turnAgent: RuntimeTurnAgent;+}): string {const skillSection = formatAvailableSkillsSection(input.turnAgent.availableSkills ?? []);const blocks =skillSection === null? input.turnAgent.instructions: [...input.turnAgent.instructions, skillSection];- return blocks.join("\n\n");+ return [...blocks, ...(input.additions ?? [])].join("\n\n");}/**diff --git a/packages/eve/src/execution/task-event-callback.ts b/packages/eve/src/execution/task-event-callback.tsindex d55aac986..efbbadce8 100644--- a/packages/eve/src/execution/task-event-callback.ts+++ b/packages/eve/src/execution/task-event-callback.ts@@ -7,24 +7,23 @@ import type { UnstampedMessageStreamEvent } from "#protocol/message.js";* Forwards one task child's blocking transition to its parent's session* callback.*- * Task children report HITL and authorization transitions to the parent's- * task run before local emission, so the run can block/unblock the task- * under one durable decision. A session without a callback capability- * (non-delegated runs) is a no-op, as is any event outside the three- * blocking transitions.+ * Task children report HITL and authorization transitions exclusively to the+ * parent's task run, so the run can block/unblock the task under one durable+ * decision and only the parent channel owns the interaction. Returns whether+ * the event was forwarded and must therefore be suppressed locally.*/export async function forwardTaskEventToSessionCallback(ctx: ContextContainer,event: UnstampedMessageStreamEvent,-): Promise<void> {+): Promise<boolean> {const callback = ctx.get(SessionCallbackKey);- if (callback === undefined) return;+ if (callback?.taskId === undefined) return false;if (event.type !== "input.requested" &&event.type !== "authorization.required" &&event.type !== "authorization.completed") {- return;+ return false;}await fireTaskEventCallbackStep({callback,@@ -32,4 +31,5 @@ export async function forwardTaskEventToSessionCallback(childSessionId: ctx.require(SessionIdKey),event,});+ return true;}diff --git a/packages/eve/src/execution/tasks/child/instructions.ts b/packages/eve/src/execution/tasks/child/instructions.tsnew file mode 100644index 000000000..f5be214a6--- /dev/null+++ b/packages/eve/src/execution/tasks/child/instructions.ts@@ -0,0 +1,25 @@+import { readTaskIdFromInboxToken } from "#tasks/task-inbox-token.js";++const SESSION_CALLBACK_CONTEXT_KEY = "eve.sessionCallback";+const CHANNEL_CONTEXT_KEY = "eve.channel";++export const TASK_UPDATE_SESSION_INSTRUCTION =+ "Background task updates\nYou are running as a background task. For multi-step work, use `task_update` at meaningful milestones to briefly state what you are currently doing. Keep updates terse and activity-focused; do not include preliminary findings or results. Do not wait for a response, and return your final result normally.";++/** True when the serialized caller binding points at a durable task inbox. */+export function isTaskOwnedSerializedContext(serializedContext: Record<string, unknown>): boolean {+ const callback = serializedContext[SESSION_CALLBACK_CONTEXT_KEY];+ if (+ callback !== null &&+ typeof callback === "object" &&+ typeof Reflect.get(callback, "taskId") === "string"+ ) {+ return true;+ }+ const channel = serializedContext[CHANNEL_CONTEXT_KEY];+ if (channel === null || typeof channel !== "object") return false;+ const state = Reflect.get(channel, "state");+ if (state === null || typeof state !== "object") return false;+ const token = Reflect.get(state, "parentContinuationToken");+ return typeof token === "string" && readTaskIdFromInboxToken(token) !== undefined;+}diff --git a/packages/eve/src/execution/tasks/child/steps.ts b/packages/eve/src/execution/tasks/child/steps.tsindex d64aaaed2..987b8dec1 100644--- a/packages/eve/src/execution/tasks/child/steps.ts+++ b/packages/eve/src/execution/tasks/child/steps.ts@@ -15,6 +15,7 @@ import {type TaskInboundAnswerInput,type TaskInboundAuthorizationEvent,type TaskInboundInputRequest,+ type TaskInboundUpdate,type TaskView,} from "#tasks/types.js";@@ -115,6 +116,29 @@ export async function wakeTaskParentStep(input: {}}+/** Forwards a running child's intermediate update to its parent session. */+export async function wakeTaskUpdateParentStep(input: {+ readonly token: string;+ readonly update: TaskInboundUpdate;+ readonly view: TaskView;+}): Promise<void> {+ "use step";++ const command: SessionCommand = {+ kind: "send",+ payload: {+ message: `Background task ${input.view.taskId} (${input.view.metadata.name}) update: ${input.update.message}`,+ },+ taskDeliveryId: `${input.view.taskId}:update:${input.update.childTurnId}:${input.update.childStepIndex}:${input.update.callId}`,+ };+ try {+ await resumeHook(input.token, command);+ } catch (error) {+ if (isTaskWorkflowTargetGone(error)) return;+ throw error;+ }+}+/** Sends an exact local-task HITL batch to the parent's pre-model router. */export async function wakeTaskInputRequestParentStep(input: {readonly request: TaskInboundInputRequest;diff --git a/packages/eve/src/execution/tasks/child/update.test.ts b/packages/eve/src/execution/tasks/child/update.test.tsnew file mode 100644index 000000000..c8699046f--- /dev/null+++ b/packages/eve/src/execution/tasks/child/update.test.ts@@ -0,0 +1,79 @@+import { afterEach, describe, expect, it, vi } from "vitest";++import { fireTaskUpdateCallbackStep } from "#execution/session-callback-step.js";+import { executeTaskUpdate } from "#execution/tasks/child/update.js";++const resumeHookMock = vi.fn();++vi.mock("#compiled/@workflow/core/runtime.js", () => ({+ resumeHook: (token: string, payload: unknown) => resumeHookMock(token, payload),+}));+vi.mock("#execution/session-callback-step.js", () => ({+ fireTaskUpdateCallbackStep: vi.fn(),+}));++const action = {+ callId: "update-call",+ input: { message: "Found three matching records." },+ kind: "tool-call" as const,+ toolName: "task_update",+};++afterEach(() => vi.resetAllMocks());++describe("executeTaskUpdate", () => {+ it("sends local updates through the owning task inbox", async () => {+ const token = "task:task_abc:0123456789abcdef0123456789abcdef";+ const result = await executeTaskUpdate({+ action,+ adapter: {+ kind: "subagent",+ state: {+ callId: "parent-call",+ parentContinuationToken: token,+ parentSessionId: "parent-session",+ subagentName: "agent",+ },+ } as never,+ childStepIndex: 2,+ childTurnId: "turn-child",+ serializedContext: {},+ });++ expect(resumeHookMock).toHaveBeenCalledWith(token, {+ callId: "update-call",+ childStepIndex: 2,+ childTurnId: "turn-child",+ kind: "task-update",+ message: "Found three matching records.",+ });+ expect(result).toMatchObject({ output: { status: "sent", taskId: "task_abc" } });+ });++ it("sends remote updates through the owning task callback", async () => {+ vi.mocked(fireTaskUpdateCallbackStep).mockResolvedValue("task_abc");+ const callback = {+ callId: "parent-call",+ subagentName: "agent",+ taskId: "task_abc",+ token: "task-token",+ url: "https://parent.example/eve/v1/callback/task-token",+ };+ const result = await executeTaskUpdate({+ action,+ adapter: undefined,+ childStepIndex: 2,+ childTurnId: "turn-child",+ serializedContext: { "eve.sessionCallback": callback },+ });++ expect(fireTaskUpdateCallbackStep).toHaveBeenCalledWith({+ callback,+ callId: "update-call",+ childStepIndex: 2,+ childTurnId: "turn-child",+ message: "Found three matching records.",+ });+ expect(result).toMatchObject({ output: { status: "sent", taskId: "task_abc" } });+ });+});diff --git a/packages/eve/src/execution/tasks/child/update.ts b/packages/eve/src/execution/tasks/child/update.tsnew file mode 100644index 000000000..dd844d815--- /dev/null+++ b/packages/eve/src/execution/tasks/child/update.ts@@ -0,0 +1,78 @@+import type { ChannelAdapter } from "#channel/adapter.js";+import { SessionCallbackKey } from "#context/keys.js";+import { fireTaskUpdateCallbackStep } from "#execution/session-callback-step.js";+import {+ isSubagentAdapterState,+ SUBAGENT_ADAPTER_KIND,+} from "#execution/subagent-adapter-state.js";+import { createTaskControlError } from "#execution/tasks/parent/control-shared.js";+import { resumeHook } from "#internal/workflow/runtime.js";+import type { RuntimeActionResult, RuntimeToolCallActionRequest } from "#runtime/actions/types.js";+import { readTaskIdFromInboxToken } from "#tasks/task-id.js";+import type { TaskInboundUpdate } from "#tasks/types.js";++/** Sends one child-authored progress update over its existing parent transport. */+export async function executeTaskUpdate(input: {+ readonly action: RuntimeToolCallActionRequest;+ readonly adapter: ChannelAdapter | undefined;+ readonly childStepIndex: number;+ readonly childTurnId: string;+ readonly serializedContext: Record<string, unknown> | undefined;+}): Promise<RuntimeActionResult> {+ const message = readUpdateMessage(input.action.input);+ if (message === undefined) {+ return createTaskControlError(input.action, "Provide a non-empty `message`.");+ }++ const callback = input.serializedContext?.[SessionCallbackKey.name];+ if (callback !== undefined) {+ const taskId = await fireTaskUpdateCallbackStep({+ callback,+ callId: input.action.callId,+ childStepIndex: input.childStepIndex,+ childTurnId: input.childTurnId,+ message,+ });+ if (taskId === undefined) {+ return createTaskControlError(input.action, "This session is not owned by a parent task.");+ }+ return createTaskUpdateResult(input.action, taskId);+ }++ const adapter = input.adapter;+ if (adapter?.kind !== SUBAGENT_ADAPTER_KIND || !isSubagentAdapterState(adapter.state)) {+ return createTaskControlError(input.action, "This session is not owned by a parent task.");+ }+ const token = adapter.state.parentContinuationToken;+ const taskId = readTaskIdFromInboxToken(token);+ if (taskId === undefined) {+ return createTaskControlError(input.action, "This session is not owned by a parent task.");+ }+ const update: TaskInboundUpdate = {+ callId: input.action.callId,+ childStepIndex: input.childStepIndex,+ childTurnId: input.childTurnId,+ kind: "task-update",+ message,+ };+ await resumeHook(token, update);+ return createTaskUpdateResult(input.action, taskId);+}++function readUpdateMessage(input: Record<string, unknown>): string | undefined {+ return typeof input.message === "string" && input.message.trim() !== ""+ ? input.message+ : undefined;+}++function createTaskUpdateResult(+ action: RuntimeToolCallActionRequest,+ taskId: string,+): RuntimeActionResult {+ return {+ callId: action.callId,+ kind: "tool-result",+ output: { status: "sent", taskId },+ toolName: action.toolName,+ };+}diff --git a/packages/eve/src/execution/tasks/child/workflow.test.ts b/packages/eve/src/execution/tasks/child/workflow.test.tsindex 1db95602d..a1d234986 100644--- a/packages/eve/src/execution/tasks/child/workflow.test.ts+++ b/packages/eve/src/execution/tasks/child/workflow.test.ts@@ -9,6 +9,7 @@ import {wakeTaskAuthorizationParentStep,wakeTaskInputRequestParentStep,wakeTaskParentStep,+ wakeTaskUpdateParentStep,} from "#execution/tasks/child/steps.js";import { taskRunWorkflow } from "#execution/tasks/child/workflow.js";import type {@@ -34,6 +35,7 @@ vi.mock("#execution/tasks/child/steps.js", () => ({wakeTaskAuthorizationParentStep: vi.fn(),wakeTaskInputRequestParentStep: vi.fn(),wakeTaskParentStep: vi.fn(),+ wakeTaskUpdateParentStep: vi.fn(),}));afterEach(() => {@@ -74,6 +76,75 @@ function appendedStatuses(): readonly string[] {}describe("taskRunWorkflow", () => {+ it("forwards child updates after dispatch acknowledgement without changing the view", async () => {+ const update = {+ callId: "update-call",+ childStepIndex: 2,+ childTurnId: "turn-child",+ kind: "task-update" as const,+ message: "Found three matching records.",+ };+ mockCommandHook([+ update,+ { command: { kind: "ready" }, kind: "task-command" },+ { ...update, callId: "update-call-2" },+ { command: { data: "done", kind: "complete" }, kind: "task-command" },+ ]);++ const view = createWorkingView();+ await taskRunWorkflow({+ taskInboxToken: "task-token",+ initialView: view,+ parentContinuationToken: "parent-session-token",+ });++ expect(wakeTaskUpdateParentStep).toHaveBeenNthCalledWith(1, {+ token: "parent-session-token",+ update,+ view,+ });+ expect(wakeTaskUpdateParentStep).toHaveBeenNthCalledWith(2, {+ token: "parent-session-token",+ update: { ...update, callId: "update-call-2" },+ view,+ });+ expect(appendedStatuses()).toEqual(["working", "working", "completed"]);+ });++ it("forwards a fast child update before its terminal wake", async () => {+ const update = {+ callId: "update-call",+ childStepIndex: 2,+ childTurnId: "turn-child",+ kind: "task-update" as const,+ message: "Final progress update.",+ };+ mockCommandHook([+ update,+ { command: { data: "done", kind: "complete" }, kind: "task-command" },+ { command: { kind: "ready" }, kind: "task-command" },+ ]);++ await taskRunWorkflow({+ taskInboxToken: "task-token",+ initialView: createWorkingView(),+ parentContinuationToken: "parent-session-token",+ });++ expect(wakeTaskUpdateParentStep).toHaveBeenCalledWith({+ token: "parent-session-token",+ update,+ view: expect.objectContaining({ status: "completed" }),+ });+ expect(wakeTaskParentStep).toHaveBeenCalledWith({+ token: "parent-session-token",+ view: expect.objectContaining({ status: "completed" }),+ });+ expect(vi.mocked(wakeTaskUpdateParentStep).mock.invocationCallOrder[0]).toBeLessThan(+ vi.mocked(wakeTaskParentStep).mock.invocationCallOrder[0] ?? 0,+ );+ });+it("publishes the initial view, applies commands, and stops at terminal", async () => {mockCommandHook([{ command: { kind: "ready" }, kind: "task-command" },diff --git a/packages/eve/src/execution/tasks/child/workflow.ts b/packages/eve/src/execution/tasks/child/workflow.tsindex 30afb0f9a..d039e6f5f 100644--- a/packages/eve/src/execution/tasks/child/workflow.ts+++ b/packages/eve/src/execution/tasks/child/workflow.ts@@ -8,6 +8,7 @@ import {wakeTaskAuthorizationParentStep,wakeTaskInputRequestParentStep,wakeTaskParentStep,+ wakeTaskUpdateParentStep,} from "#execution/tasks/child/steps.js";import { applyTaskTransition } from "#tasks/transitions.js";import { translateTaskInboundPayload } from "#tasks/wire.js";@@ -20,6 +21,7 @@ import {type TaskInboundAnswerInput,type TaskInboundAuthorizationEvent,type TaskInboundInputRequest,+ type TaskInboundUpdate,type TaskRunInboundPayload,type TaskView,} from "#tasks/types.js";@@ -55,9 +57,9 @@ function isTaskRunFinished(view: TaskView, dispatchAcknowledged: boolean): boole* change nothing.** Wake policy: a transition into a ready status — terminal or- * `input_required` — delivers a framework notification to the parent- * session. A parked parent starts a turn; an active turn observes the- * delivery at its next safe boundary. Nothing else wakes the parent.+ * `input_required` — and an explicit child `task_update` deliver a+ * framework notification to the parent session. A parked parent starts+ * a turn; an active turn observes the delivery at its next safe boundary.** The run ends when the task reaches a terminal status. Its view* stream stays readable, so terminal tasks remain peekable; the@@ -89,6 +91,7 @@ export async function taskRunWorkflow(input: TaskRunWorkflowInput): Promise<voidlet view = input.initialView;let pendingInputRequest: TaskInboundInputRequest | undefined;let pendingAuthorizationEvents: TaskInboundAuthorizationEvent[] = [];+ let pendingUpdates: TaskInboundUpdate[] = [];let dispatchAcknowledged = false;await appendTaskViewStep({ view });@@ -121,6 +124,18 @@ export async function taskRunWorkflow(input: TaskRunWorkflowInput): Promise<voidif (payload.kind === "authorization-event") {pendingAuthorizationEvents.push(payload);}+ if (payload.kind === "task-update") {+ if (dispatchAcknowledged && !isTerminalTaskStatus(view.status)) {+ await wakeTaskUpdateParentStep({+ token: input.parentContinuationToken,+ update: payload,+ view,+ });+ } else {+ pendingUpdates.push(payload);+ }+ continue;+ }const isExecutorResultAfterCancellation =view.status === "cancelled" && payload.kind === "runtime-action-result";const isTaskInputAnswer = payload.kind === "input-response";@@ -139,6 +154,14 @@ export async function taskRunWorkflow(input: TaskRunWorkflowInput): Promise<void}if (command === undefined) continue;if (isReadinessCommand && isTerminalTaskStatus(view.status)) {+ for (const update of pendingUpdates) {+ await wakeTaskUpdateParentStep({+ token: input.parentContinuationToken,+ update,+ view,+ });+ }+ pendingUpdates = [];await wakeTaskParentStep({ token: input.parentContinuationToken, view });continue;}@@ -158,6 +181,16 @@ export async function taskRunWorkflow(input: TaskRunWorkflowInput): Promise<voidtoken: input.parentContinuationToken,});}+ if (dispatchAcknowledged && pendingUpdates.length > 0 && !isTerminalTaskStatus(view.status)) {+ for (const update of pendingUpdates) {+ await wakeTaskUpdateParentStep({+ token: input.parentContinuationToken,+ update,+ view,+ });+ }+ pendingUpdates = [];+ }if (becameTerminal || routableAuthorizationEvents.length > 0) pendingAuthorizationEvents = [];const routableInputRequest =pendingInputRequest !== undefined &&diff --git a/packages/eve/src/execution/tasks/parent/control-shared.ts b/packages/eve/src/execution/tasks/parent/control-shared.tsindex 7eec18eaa..dc38b5761 100644--- a/packages/eve/src/execution/tasks/parent/control-shared.ts+++ b/packages/eve/src/execution/tasks/parent/control-shared.ts@@ -14,7 +14,7 @@ import type { TaskView } from "#tasks/types.js";/*** Result and lookup helpers shared by the task-control executors* (`task_peek`/`task_cancel` in the dispatch module,- * `task_send` in its own).+ * task controls in their own).*//** Resolves owned index entries, or the ids this session does not own. */diff --git a/packages/eve/src/execution/tasks/parent/dispatch-task-step.ts b/packages/eve/src/execution/tasks/parent/dispatch-task-step.tsindex 2b8641fcb..e39a40656 100644--- a/packages/eve/src/execution/tasks/parent/dispatch-task-step.ts+++ b/packages/eve/src/execution/tasks/parent/dispatch-task-step.ts@@ -11,7 +11,7 @@* parent turn inbox, and every start dispatches a conversation-mode* (persistent) child so the background task stays resumable.*- * Task-control calls (`task_peek` / `task_cancel` / `task_send`) execute+ * Task-control calls (`task_peek` / `task_cancel` / `task_update`) execute* inline in this step, which holds the session ownership index and world* access they need.*/@@ -77,9 +77,11 @@ export async function dispatchTaskStep(if (entry.kind === "task-control") {const control = await executeTaskControlAction({action: entry.action,+ adapter: prepared.adapter,bundle,parentStepIndex: batch.event.stepIndex,parentTurnId: batch.event.turnId,+ serializedContext: prepared.serializedContext,session: nextSession,});nextSession = control.session;diff --git a/packages/eve/src/execution/tasks/parent/dispatch.ts b/packages/eve/src/execution/tasks/parent/dispatch.tsindex e6de0e9d4..f7c85e4da 100644--- a/packages/eve/src/execution/tasks/parent/dispatch.ts+++ b/packages/eve/src/execution/tasks/parent/dispatch.ts@@ -12,7 +12,8 @@ import {readTaskViews,readTaskView,} from "#execution/tasks/parent/control-shared.js";-import { executeTaskSend } from "#execution/tasks/parent/send.js";+import { executeTaskUpdate } from "#execution/tasks/child/update.js";+import type { ChannelAdapter } from "#channel/adapter.js";import type { DelegatedTask } from "#execution/tasks/parent/delegate.js";import { sendTaskCommand } from "#execution/tasks/parent/run-parent.js";import { requestWorkflowTurnCancellation } from "#execution/workflow-runtime.js";@@ -27,7 +28,7 @@ import {TASK_CANCEL_TOOL_NAME,TASK_CONTROL_TOOL_NAMES,TASK_PEEK_TOOL_NAME,- TASK_SEND_TOOL_NAME,+ TASK_UPDATE_TOOL_NAME,} from "#runtime/framework-tools/tasks.js";import type { SessionTaskIndexEntry } from "#tasks/session-index.js";import { isTerminalTaskStatus, type TaskView } from "#tasks/types.js";@@ -37,7 +38,7 @@ const log = createLogger("execution.tasks.dispatch");const CANCEL_COMMIT_POLL_ATTEMPTS = 10;const CANCEL_COMMIT_POLL_DELAY_MS = 250;-/** True for `task_peek` / `task_cancel` / `task_send` calls. */+/** True for task-control calls dispatched outside the model loop. */export function isTaskControlAction(action: RuntimeActionRequest,): action is RuntimeToolCallActionRequest {@@ -49,14 +50,15 @@ export function isTaskControlAction(* the durable session state (ownership index) and world access the* tools need.*- * Returns the (possibly updated) session: `task_send` follow-ups record- * new tasks and settle the continued agent handle.+ * Returns the current session alongside the action result.*/export async function executeTaskControlAction(input: {readonly action: RuntimeToolCallActionRequest;+ readonly adapter?: ChannelAdapter;readonly bundle: CompiledBundle;readonly parentStepIndex?: number;readonly parentTurnId: string;+ readonly serializedContext?: Record<string, unknown>;readonly session: RuntimeSession;}): Promise<{readonly result: RuntimeActionResult;@@ -65,8 +67,17 @@ export async function executeTaskControlAction(input: {}> {const { action, session } = input;- if (action.toolName === TASK_SEND_TOOL_NAME) {- return executeTaskSend(input);+ if (action.toolName === TASK_UPDATE_TOOL_NAME) {+ return {+ result: await executeTaskUpdate({+ action,+ adapter: input.adapter,+ childStepIndex: input.parentStepIndex ?? 0,+ childTurnId: input.parentTurnId,+ serializedContext: input.serializedContext,+ }),+ session,+ };}const taskIds = readTaskIds(action.input);diff --git a/packages/eve/src/execution/tasks/parent/send.test.ts b/packages/eve/src/execution/tasks/parent/send.test.tsdeleted file mode 100644index 4fe3cec98..000000000--- a/packages/eve/src/execution/tasks/parent/send.test.ts+++ /dev/null@@ -1,284 +0,0 @@-import { beforeEach, describe, expect, it, vi } from "vitest";--import {- dispatchToTaskAgentAddress,- type RuntimeSession,-} from "#execution/agent-handle-dispatch.js";-import {- beginDelegatedTask,- failDelegatedDispatch,- settleDelegatedDispatch,-} from "#execution/tasks/parent/delegate.js";-import { readLatestTaskView } from "#execution/tasks/parent/run-parent.js";-import { executeTaskSend } from "#execution/tasks/parent/send.js";-import { AGENT_HANDLES_STATE_KEY } from "#harness/handles/store.js";-import type { RuntimeToolCallActionRequest } from "#runtime/actions/types.js";-import type { CompiledBundle } from "#runtime/sessions/runtime-context-keys.js";-import { SESSION_TASKS_STATE_KEY } from "#tasks/session-index.js";-import type { TaskStatus, TaskView } from "#tasks/types.js";--vi.mock("#execution/agent-handle-dispatch.js", async (importOriginal) => ({- ...(await importOriginal<typeof import("#execution/agent-handle-dispatch.js")>()),- dispatchToTaskAgentAddress: vi.fn(),-}));--vi.mock("#execution/tasks/parent/delegate.js", () => ({- beginDelegatedTask: vi.fn(),- failDelegatedDispatch: vi.fn(),- settleDelegatedDispatch: vi.fn(),-}));--vi.mock("#execution/tasks/parent/run-parent.js", () => ({- readLatestTaskView: vi.fn(),- sendTaskCommand: vi.fn(),-}));--const agentId = "ag_research:abcdef123456";-const metadata = { agentId, kind: "subagent" as const, mode: "local" as const, name: "research" };--function task(taskId: string, status: TaskStatus): TaskView {- // Cast on purpose: mock views omit the per-status payload fields the- // TaskView union requires (e.g. lastOutput on completed).- return { metadata, status, taskId } as TaskView;-}--function createSession(includeActive = false, activeCreatedByTurnId = "turn-1"): RuntimeSession {- const tasks = [- {- taskInboxToken: "task-token-terminal",- createdByTurnId: "turn-1",- metadata,- operationId: "operation-terminal",- taskId: "task_terminal",- taskRunId: "run-terminal",- },- ...(includeActive- ? [- {- taskInboxToken: "task-token-active",- createdByTurnId: activeCreatedByTurnId,- metadata,- operationId: "operation-active",- taskId: "task_active",- taskRunId: "run-active",- },- ]- : []),- ];- return {- agent: { modelReference: { id: "model" }, system: "", tools: [] },- compaction: { recentWindowSize: 4, threshold: 1_000_000 },- continuationToken: "parent-token",- history: [],- sessionId: "parent-session",- state: {- [AGENT_HANDLES_STATE_KEY]: {- handles: [- {- address: {- continuationToken: "child-token",- kind: "agent/local",- sessionId: "child-session",- },- identity: { id: agentId, name: "research", nodeId: "node-research" },- phase: "addressed",- },- ],- },- [SESSION_TASKS_STATE_KEY]: { tasks },- },- } as RuntimeSession;-}--const action: RuntimeToolCallActionRequest = {- callId: "call-send",- input: { message: "continue", taskId: "task_terminal" },- kind: "tool-call",- toolName: "task_send",-};--describe("task_send persistent-agent availability", () => {- beforeEach(() => vi.resetAllMocks());-- it("starts a new task on the same address after terminal work", async () => {- const session = createSession();- vi.mocked(readLatestTaskView).mockResolvedValue(task("task_terminal", "completed"));- vi.mocked(beginDelegatedTask).mockResolvedValue({- taskInboxToken: "task-token-new",- createdByTurnId: "turn-2",- metadata,- operationId: "operation-new",- taskId: "task_new",- taskRunId: "run-new",- });- vi.mocked(dispatchToTaskAgentAddress).mockResolvedValue({- address: {- continuationToken: "child-token",- kind: "agent/local",- sessionId: "child-session",- },- callId: action.callId,- kind: "called",- name: "research",- session,- toolName: "research",- });- vi.mocked(settleDelegatedDispatch).mockResolvedValue({- receipt: {} as never,- session,- });-- const result = await executeTaskSend({- action,- bundle: {} as CompiledBundle,- parentTurnId: "turn-2",- session,- });-- expect(beginDelegatedTask).toHaveBeenCalledWith(expect.objectContaining({ agentId }));- expect(dispatchToTaskAgentAddress).toHaveBeenCalledWith(- expect.objectContaining({ agentId, currentSession: session }),- );- expect(result.result).toMatchObject({- output: { agentId, status: "working", taskId: "task_new" },- });- });-- it("rejects a follow-up while another nonterminal task owns the agent", async () => {- const session = createSession(true);- vi.mocked(readLatestTaskView).mockImplementation(async ({ taskRunId }) =>- taskRunId === "run-active"- ? task("task_active", "input_required")- : task("task_terminal", "completed"),- );-- const result = await executeTaskSend({- action,- bundle: {} as CompiledBundle,- parentTurnId: "turn-2",- session,- });-- expect(result.result).toMatchObject({- isError: true,- output: { message: expect.stringContaining("task_active") },- });- expect(beginDelegatedTask).not.toHaveBeenCalled();- expect(dispatchToTaskAgentAddress).not.toHaveBeenCalled();- expect(failDelegatedDispatch).not.toHaveBeenCalled();- });-- it("rejects a second same-batch follow-up even if the first task already completed", async () => {- const session = createSession(true, "turn-2");- vi.mocked(readLatestTaskView).mockImplementation(async ({ taskRunId }) =>- taskRunId === "run-active"- ? task("task_active", "completed")- : task("task_terminal", "completed"),- );-- const result = await executeTaskSend({- action,- bundle: {} as CompiledBundle,- parentTurnId: "turn-2",- session,- });-- expect(result.result).toMatchObject({- isError: true,- output: { message: expect.stringContaining("AGENT_BUSY") },- });- expect(beginDelegatedTask).not.toHaveBeenCalled();- expect(dispatchToTaskAgentAddress).not.toHaveBeenCalled();- });-- it("persists the continuation task before an ambiguous delivery", async () => {- const current = createSession();- const persisted = createSession(true, "turn-2");- vi.mocked(readLatestTaskView).mockResolvedValue(task("task_terminal", "completed"));- vi.mocked(beginDelegatedTask).mockResolvedValue({- taskInboxToken: "task-token-new",- createdByTurnId: "turn-2",- metadata,- operationId: "operation-new",- taskId: "task_active",- taskRunId: "run-active",- });- vi.mocked(settleDelegatedDispatch).mockResolvedValue({- receipt: {} as never,- session: persisted,- });- vi.mocked(dispatchToTaskAgentAddress).mockResolvedValue({- deliveryAmbiguous: true,- kind: "error",- result: {- callId: action.callId,- isError: true,- kind: "subagent-result",- origin: "dispatch",- output: { code: "AGENT_UNREACHABLE", message: "response lost" },- subagentName: "research",- },- session: persisted,- });-- const result = await executeTaskSend({- action,- bundle: {} as CompiledBundle,- parentTurnId: "turn-2",- session: current,- });-- expect(vi.mocked(settleDelegatedDispatch).mock.invocationCallOrder[0]).toBeLessThan(- vi.mocked(dispatchToTaskAgentAddress).mock.invocationCallOrder[0] ?? 0,- );- expect(dispatchToTaskAgentAddress).toHaveBeenCalledWith(- expect.objectContaining({ currentSession: persisted }),- );- expect(result.result).toMatchObject({ isError: true, output: { taskId: "task_active" } });- expect(result.session).toBe(persisted);- expect(failDelegatedDispatch).not.toHaveBeenCalled();- });-- it("fails a persisted continuation after a definitive remote rejection", async () => {- const current = createSession();- const persisted = createSession(true, "turn-2");- vi.mocked(readLatestTaskView).mockResolvedValue(task("task_terminal", "completed"));- vi.mocked(beginDelegatedTask).mockResolvedValue({- taskInboxToken: "task-token-new",- createdByTurnId: "turn-2",- metadata,- operationId: "operation-new",- taskId: "task_active",- taskRunId: "run-active",- });- vi.mocked(settleDelegatedDispatch).mockResolvedValue({- receipt: {} as never,- session: persisted,- });- vi.mocked(dispatchToTaskAgentAddress).mockResolvedValue({- deliveryAmbiguous: false,- kind: "error",- result: {- callId: action.callId,- isError: true,- kind: "subagent-result",- origin: "dispatch",- output: { code: "AGENT_UNREACHABLE", message: "HTTP 401" },- subagentName: "research",- },- session: persisted,- });-- await executeTaskSend({- action,- bundle: {} as CompiledBundle,- parentTurnId: "turn-2",- session: current,- });-- expect(failDelegatedDispatch).toHaveBeenCalledWith({- error: { code: "AGENT_UNREACHABLE", message: "HTTP 401" },- task: expect.objectContaining({ taskId: "task_active" }),- });- });-});diff --git a/packages/eve/src/execution/tasks/parent/send.ts b/packages/eve/src/execution/tasks/parent/send.tsdeleted file mode 100644index 4b865c871..000000000--- a/packages/eve/src/execution/tasks/parent/send.ts+++ /dev/null@@ -1,219 +0,0 @@-import {- dispatchToTaskAgentAddress,- type RuntimeAgentHandleAction,- type RuntimeSession,-} from "#execution/agent-handle-dispatch.js";-import {- createTaskControlError,- createUnknownTasksError,- findActiveTaskForAgent,- findTaskAgentAddress,- readTaskView,-} from "#execution/tasks/parent/control-shared.js";-import {- beginDelegatedTask,- type DelegatedTask,- failDelegatedDispatch,- settleDelegatedDispatch,-} from "#execution/tasks/parent/delegate.js";-import { AGENT_BUSY, AGENT_UNREACHABLE } from "#harness/agent-handle-errors.js";-import type { RuntimeActionResult, RuntimeToolCallActionRequest } from "#runtime/actions/types.js";-import type { CompiledBundle } from "#runtime/sessions/runtime-context-keys.js";-import { findSessionTaskEntry } from "#tasks/session-index.js";-import type { TaskView } from "#tasks/types.js";--/**- * Routes one `task_send`:- *- * - `working` tasks are busy — the send surfaces `AGENT_BUSY` instead- * of queueing (settled decision; queueing is the reversible follow-up);- * - `input_required` tasks reject model-authored sends; clients answer- * them through the parent channel's direct HITL route;- * - terminal tasks accept a `message` follow-up, which starts a new- * task bound to the same child session and returns its receipt.- */-export async function executeTaskSend(input: {- readonly action: RuntimeToolCallActionRequest;- readonly bundle: CompiledBundle;- readonly parentStepIndex?: number;- readonly parentTurnId: string;- readonly session: RuntimeSession;-}): Promise<{- readonly result: RuntimeActionResult;- readonly session: RuntimeSession;- readonly pendingTask?: DelegatedTask;-}> {- const { action, session } = input;- const send = readTaskSendInput(action.input);- if (send.kind === "invalid") {- return { result: createTaskControlError(action, send.message), session };- }-- const entry = findSessionTaskEntry(session.state, send.taskId);- if (entry === undefined) {- return { result: createUnknownTasksError(action, [send.taskId]), session };- }-- const view = await readTaskView(entry);-- if (view.status === "working") {- return {- result: createTaskControlError(- action,- `${AGENT_BUSY}: task "${view.taskId}" is still working. Let it finish, or cancel it first.`,- ),- session,- };- }-- if (view.status === "input_required") {- return {- result: createTaskControlError(- action,- `Task "${view.taskId}" is waiting on input; the human must answer through the parent channel.`,- ),- session,- };- }-- return followUpTerminalTask({- action,- bundle: input.bundle,- message: send.message,- parentStepIndex: input.parentStepIndex,- parentTurnId: input.parentTurnId,- session,- view,- });-}--async function followUpTerminalTask(input: {- readonly action: RuntimeToolCallActionRequest;- readonly bundle: CompiledBundle;- readonly message: string;- readonly parentStepIndex?: number;- readonly parentTurnId: string;- readonly session: RuntimeSession;- readonly view: TaskView;-}): Promise<{- readonly result: RuntimeActionResult;- readonly session: RuntimeSession;- readonly pendingTask?: DelegatedTask;-}> {- const { action, view } = input;- const active = await findActiveTaskForAgent(- input.session,- view.metadata.agentId,- input.parentTurnId,- input.parentStepIndex,- );- if (active !== undefined) {- return {- result: createTaskControlError(- action,- `${AGENT_BUSY}: agent "${view.metadata.agentId}" is busy with task "${active.view.taskId}" (${active.view.status}).`,- ),- session: input.session,- };- }- const handle = findTaskAgentAddress(input.session, view.metadata.agentId);- if (handle === undefined) {- return {- result: createTaskControlError(- action,- `${AGENT_UNREACHABLE}: task "${view.taskId}"'s agent is no longer addressable.`,- ),- session: input.session,- };- }- const continuation: RuntimeAgentHandleAction =- handle.address.kind === "agent/remote"- ? {- callId: action.callId,- description: "",- input: { message: input.message },- kind: "remote-agent-call",- name: handle.identity.name,- nodeId: handle.identity.nodeId,- remoteAgentName: handle.identity.name,- }- : {- callId: action.callId,- description: "",- input: { message: input.message },- kind: "subagent-call",- name: handle.identity.name,- nodeId: handle.identity.nodeId,- subagentName: handle.identity.name,- };-- const task = await beginDelegatedTask({- agentId: handle.identity.id,- callId: action.callId,- mode: handle.address.kind === "agent/remote" ? "remote" : "local",- name: handle.identity.name,- parentSessionId: input.session.sessionId,- parentStepIndex: input.parentStepIndex,- parentTurnId: input.parentTurnId,- session: input.session,- });- // Persist the task in the parent session before the ambiguous delivery side effect.- const persisted = await settleDelegatedDispatch({- callId: action.callId,- session: input.session,- subagentName: handle.identity.name,- task,- });- const outcome = await dispatchToTaskAgentAddress({- action: continuation,- agentId: handle.identity.id,- bundle: input.bundle,- currentSession: persisted.session,- parentToken: task.taskInboxToken,- });- if (outcome.kind === "error") {- if (outcome.deliveryAmbiguous !== true) {- await failDelegatedDispatch({ error: outcome.result.output, task });- }- return {- result: {- callId: action.callId,- isError: true,- kind: "tool-result",- output: { error: outcome.result.output, taskId: task.taskId },- toolName: action.toolName,- },- session: outcome.session,- pendingTask: task,- };- }-- return {- result: {- callId: action.callId,- kind: "tool-result",- output: { agentId: task.metadata.agentId, status: "working", taskId: task.taskId },- toolName: action.toolName,- },- session: outcome.session,- pendingTask: task,- };-}--type TaskSendInput =- | { readonly kind: "invalid"; readonly message: string }- | { readonly kind: "send"; readonly message: string; readonly taskId: string };--function readTaskSendInput(input: Record<string, unknown>): TaskSendInput {- const taskId =- typeof input.taskId === "string" && input.taskId.trim() !== "" ? input.taskId : undefined;- if (taskId === undefined) {- return { kind: "invalid", message: "Provide the `taskId` from a task receipt." };- }- const message =- typeof input.message === "string" && input.message.trim() !== "" ? input.message : undefined;- if (message !== undefined) {- return { kind: "send", message, taskId };- }- return { kind: "invalid", message: "Provide a non-empty `message`." };-}diff --git a/packages/eve/src/execution/workflow-entry.test.ts b/packages/eve/src/execution/workflow-entry.test.tsindex bfeb165f9..8ad1878fe 100644--- a/packages/eve/src/execution/workflow-entry.test.ts+++ b/packages/eve/src/execution/workflow-entry.test.ts@@ -179,12 +179,15 @@ describe("workflowEntry", () => {deadline: new Date("2026-01-31T00:00:00.000Z"),token: sessionCommandHookToken("wrun_test_123"),});- expect(createSessionStep).toHaveBeenCalledWith({- compiledArtifactsSource: {},- continuationToken: "http:test",- nodeId: undefined,- sessionId: "wrun_test_123",- });+ expect(createSessionStep).toHaveBeenCalledWith(+ expect.objectContaining({+ compiledArtifactsSource: {},+ continuationToken: "http:test",+ nodeId: undefined,+ sessionId: "wrun_test_123",+ taskOwned: false,+ }),+ );expect(dispatchTurnStep).toHaveBeenCalledWith(expect.objectContaining({completionToken: expect.any(String),diff --git a/packages/eve/src/execution/workflow-entry.ts b/packages/eve/src/execution/workflow-entry.tsindex b069027d6..3d78e11cb 100644--- a/packages/eve/src/execution/workflow-entry.ts+++ b/packages/eve/src/execution/workflow-entry.ts@@ -46,6 +46,7 @@ import { terminateChildSessionsStep } from "#execution/terminate-child-sessions-import { readSerializedSubagentDepth } from "#harness/subagent-depth.js";import type { DynamicSubagentAgentConfig } from "#runtime/subagents/dynamic-agent-config.js";import type { TokenUsage } from "#shared/token-usage.js";+import { isTaskOwnedSerializedContext } from "#execution/tasks/child/instructions.js";const SAFE_OUTER_WORKFLOW_FAILURE_MESSAGE ="Agent workflow failed. Inspect the private session trace for details.";@@ -174,6 +175,7 @@ export async function workflowEntry(input: WorkflowEntryInput): Promise<WorkflowrootSessionId: rootSessionIdFromParent,sessionId,subagentDepth,+ taskOwned: isTaskOwnedSerializedContext(input.serializedContext),});crashCleanupState.lastSessionState = sessionState;// Resolved for every session so the cell's population never dependsdiff --git a/packages/eve/src/execution/workflow-steps.test.ts b/packages/eve/src/execution/workflow-steps.test.tsindex 70e4e9cdc..6b6e7a78c 100644--- a/packages/eve/src/execution/workflow-steps.test.ts+++ b/packages/eve/src/execution/workflow-steps.test.ts@@ -9,6 +9,7 @@ import {ContinuationTokenKey,DynamicSubagentAgentConfigKey,ModeKey,+ SessionCallbackKey,SessionDynamicSubagentSelectionsKey,SessionDynamicModelReferenceKey,SessionDynamicToolMetadataKey,@@ -26,6 +27,7 @@ import { getProxyInputRequests, upsertProxyInputRequests } from "#harness/proxy-import { appendPendingInputBatch } from "#harness/input-requests.js";import type { HarnessSession, StepResult } from "#harness/types.js";import { createEmptyHookRegistry } from "#runtime/hooks/registry.js";+import { createInputRequestedEvent } from "#protocol/message.js";import { getCompiledRuntimeAgentBundle } from "#runtime/sessions/compiled-agent-cache.js";import {createDurableSessionState,@@ -1365,6 +1367,98 @@ describe("dispatchRuntimeActionsStep", () => {});describe("turnStep", () => {+ it("routes remote task HITL only to the parent callback", async () => {+ const inputRequested = vi.fn();+ const remoteTaskAdapter: ChannelAdapter = {+ kind: "remote-task-test",+ "input.requested": inputRequested,+ };+ const compiledBundle = {+ adapterRegistry: {+ adaptersByKind: new Map([[remoteTaskAdapter.kind, remoteTaskAdapter]]),+ },+ compiledArtifactsSource: {} as never,+ graph: {+ nodesByNodeId: new Map(),+ root: {+ sandboxRegistry: { sandbox: null },+ turnAgent: TestTurnAgent,+ },+ },+ moduleMap: { nodes: {} },+ hookRegistry: createEmptyHookRegistry(),+ resolvedAgent: { config: { experimental: { tasks: true } } },+ subagentRegistry: {},+ toolRegistry: {},+ turnAgent: TestTurnAgent,+ } as never;+ vi.mocked(getCompiledRuntimeAgentBundle).mockResolvedValue(compiledBundle);+ const session = createStubSession();+ installSessionStoreMocks([session]);+ vi.mocked(createExecutionNodeStep).mockImplementation((input) => {+ return async (stepSession): Promise<StepResult> => {+ await input.handleEvent?.(+ createInputRequestedEvent({+ requests: [+ {+ action: {+ callId: "tool-call-1",+ input: {},+ kind: "tool-call",+ toolName: "dangerous_tool",+ },+ kind: "tool-approval",+ options: [+ { id: "approve", label: "Approve" },+ { id: "cancel", label: "Cancel" },+ ],+ prompt: "Approve?",+ requestId: "request-1",+ },+ ],+ sequence: 1,+ stepIndex: 2,+ turnId: "turn-child",+ }),+ );+ return { next: null, session: stepSession };+ };+ });+ const fetchMock = vi.fn().mockResolvedValue(new Response(null, { status: 202 }));+ vi.stubGlobal("fetch", fetchMock);++ const ctx = new ContextContainer();+ ctx.set(AuthKey, null);+ ctx.set(BundleKey, compiledBundle);+ ctx.set(ChannelKey, remoteTaskAdapter);+ ctx.set(ContinuationTokenKey, "child-token");+ ctx.set(ModeKey, "conversation");+ ctx.set(SessionCallbackKey, {+ callId: "parent-call",+ subagentName: "remote-worker",+ taskId: "task_abc",+ token: "task-token",+ url: "https://parent.example/eve/v1/callback/task-token",+ });+ ctx.set(SessionIdKey, "child-session");++ await turnStep({+ input: { kind: "deliver", payloads: [{ message: "run the task" }] },+ parentWritable: createTestWritable(),+ serializedContext: serializeContext(ctx),+ sessionState: createStubSessionState(),+ });++ expect(fetchMock).toHaveBeenCalledWith(+ "https://parent.example/eve/v1/callback/task-token",+ expect.objectContaining({+ body: expect.stringContaining('"kind":"task.input-requested"'),+ }),+ );+ expect(inputRequested).not.toHaveBeenCalled();+ expect(workflowWritesByNamespace.get(DEFAULT_WORKFLOW_STREAM_NAMESPACE) ?? []).toEqual([]);+ });+it("keeps a session-scoped dynamic model selection when the first turn is cancelled", async () => {const session = createStubSession();installSessionStoreMocks([session]);diff --git a/packages/eve/src/execution/workflow-steps.ts b/packages/eve/src/execution/workflow-steps.tsindex 89982668c..66844f76e 100644--- a/packages/eve/src/execution/workflow-steps.ts+++ b/packages/eve/src/execution/workflow-steps.ts@@ -85,6 +85,10 @@ import {import type { TurnStepInput } from "#execution/durable-session-migrations/turn-workflow.js";import { buildRuntimeIdentity, createExecutionNodeStep } from "#execution/node-step.js";import { appendTaskAgentAnnouncement } from "#execution/tasks/parent/agent-views.js";+import {+ isTaskOwnedSerializedContext,+ TASK_UPDATE_SESSION_INSTRUCTION,+} from "#execution/tasks/child/instructions.js";import { prepareWorkflowPreambleTrace } from "#execution/workflow-trace-context.js";import { resolveEffectiveAgentRuntime } from "#execution/effective-agent-config.js";import { recordSubagentUsageSpans } from "#execution/subagent-usage-span.js";@@ -92,6 +96,7 @@ import { reconcileSessionContinuationToken } from "#execution/reconcile-session-import { hydrateDurableSession, refreshSessionFromTurnAgent } from "#execution/session.js";import { resolveRuntimeCompiledArtifactsVersionedCacheKey } from "#runtime/cache-key.js";import { createWorkflowRuntime } from "#execution/workflow-runtime.js";+import { isTaskToolAvailable, TASK_UPDATE_TOOL_NAME } from "#runtime/framework-tools/tasks.js";const TASK_DONE_WITH_PENDING_INPUT_ERROR_MESSAGE ="Task mode cannot complete while input requests remain pending.";@@ -174,6 +179,16 @@ export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResuconst bundle = ctx.require(BundleKey);const tasksEnabled = bundle.resolvedAgent.config?.experimental?.tasks === true;const effectiveAgent = resolveEffectiveAgentRuntime(bundle, ctx);+ const taskUpdatesEnabled =+ isTaskOwnedSerializedContext(input.serializedContext) &&+ isTaskToolAvailable({+ disabledFrameworkTools: bundle.resolvedAgent.disabledFrameworkTools ?? [],+ hasAuthoredTool: effectiveAgent.turnAgent.tools.some(+ (tool) => tool.name === TASK_UPDATE_TOOL_NAME,+ ),+ tasksEnabled,+ toolName: TASK_UPDATE_TOOL_NAME,+ });// Populate the callback base URL so getHookUrl() works during tool// execution, preferring eve's active local origin over metadata fallback.@@ -391,11 +406,11 @@ export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResuevent: UnstampedMessageStreamEvent,messages?: readonly import("ai").ModelMessage[],): Promise<void> => {- // Task children report HITL and authorization transitions to their- // parent's session callback before local emission, so the parent's- // task run can block/unblock the task under one durable decision.- await forwardTaskEventToSessionCallback(ctx, event);- const emitted = await emit(event);+ // A remote task's parent owns its HITL. Forward blocking events over+ // the task callback and keep them out of the child's local channel;+ // otherwise two TUIs can present and answer the same request.+ const forwardedToTaskParent = await forwardTaskEventToSessionCallback(ctx, event);+ const emitted = forwardedToTaskParent ? stampMessageStreamEvent(event) : await emit(event);await dispatchStreamEventHooks({ ctx, registry: hookRegistry, event: emitted });if (emitted.type !== "step.started") {await dispatchDynamicModelEvent({@@ -509,6 +524,7 @@ export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResuthresholdPercent: effectiveAgent.thresholdPercent,},session: lifecycleSession,+ systemPromptAdditions: taskUpdatesEnabled ? [TASK_UPDATE_SESSION_INSTRUCTION] : undefined,turnAgent: effectiveAgent.turnAgent,});const modelSession = tasksEnableddiff --git a/packages/eve/src/harness/advertised-tools.test.ts b/packages/eve/src/harness/advertised-tools.test.tsindex 4b68c600f..1e3334b23 100644--- a/packages/eve/src/harness/advertised-tools.test.ts+++ b/packages/eve/src/harness/advertised-tools.test.ts@@ -140,6 +140,7 @@ describe("getAdvertisedTools for definition arrays", () => {["add", createTool("add")],["task_peek", createTaskControlTool("task_peek")],["task_sleep", createTool("task_sleep")],+ ["task_update", createTaskControlTool("task_update")],]) satisfies HarnessToolMap;const advertisedTools = getAdvertisedTools({ session: {}, tools });@@ -147,19 +148,32 @@ describe("getAdvertisedTools for definition arrays", () => {expect([...advertisedTools.keys()]).toEqual(["add", "task_peek", "task_sleep"]);});- it("removes the task tools from delegated sessions", () => {+ it("keeps only task_update in delegated sessions", () => {const tools = new Map([["add", createTool("add")],["task_cancel", createTaskControlTool("task_cancel")],["task_peek", createTaskControlTool("task_peek")],["task_sleep", createTool("task_sleep")],+ ["task_update", createTaskControlTool("task_update")],]) satisfies HarnessToolMap;const advertisedTools = getAdvertisedTools({+ delegatedCaller: true,session: { rootSessionId: "root-session", subagentDepth: 1 },tools,});+ expect([...advertisedTools.keys()]).toEqual(["add", "task_update"]);+ });++ it("removes task_update from sessions without a delegated caller", () => {+ const tools = new Map([+ ["add", createTool("add")],+ ["task_update", createTaskControlTool("task_update")],+ ]) satisfies HarnessToolMap;++ const advertisedTools = getAdvertisedTools({ session: {}, tools });+expect([...advertisedTools.keys()]).toEqual(["add"]);});});diff --git a/packages/eve/src/harness/advertised-tools.ts b/packages/eve/src/harness/advertised-tools.tsindex 301fccbaa..08c43ed85 100644--- a/packages/eve/src/harness/advertised-tools.ts+++ b/packages/eve/src/harness/advertised-tools.ts@@ -2,7 +2,7 @@ import type { ToolSet } from "ai";import type { HarnessToolDefinition } from "#harness/execute-tool.js";import { resolveSubagentDepth } from "#harness/subagent-depth.js";import { AGENT_TOOL_NAME } from "#runtime/framework-tools/agent.js";-import { TASK_TOOL_NAMES } from "#runtime/framework-tools/tasks.js";+import { TASK_TOOL_NAMES, TASK_UPDATE_TOOL_NAME } from "#runtime/framework-tools/tasks.js";import { ROOT_RUNTIME_AGENT_NODE_ID } from "#runtime/graph.js";import {ensureWorkflowContinuationSecurity,@@ -15,16 +15,19 @@ import type { WorkflowSandboxLifecycle } from "#shared/workflow-sandbox.js";type AdvertisedToolSession = Pick<HarnessSession, "rootSessionId" | "subagentDepth">;type AdvertisedToolMapInput = {+ readonly delegatedCaller?: boolean;readonly session: AdvertisedToolSession;readonly tools: HarnessToolMap;};type AdvertisedToolDefinitionsInput = {+ readonly delegatedCaller?: boolean;readonly session: AdvertisedToolSession;readonly tools: readonly HarnessToolDefinition[];};type AdvertisedModelToolsInput = {+ readonly delegatedCaller?: boolean;readonly modelTools: ToolSet;readonly session: HarnessSession;readonly tools: HarnessToolMap;@@ -62,16 +65,24 @@ export function getAdvertisedTools(}if (isToolDefinitionList(input.tools)) {- return filterUnavailableDelegationToolDefinitions(input.tools, input.session);+ return filterUnavailableDelegationToolDefinitions(+ input.tools,+ input.session,+ input.delegatedCaller,+ );}- return filterUnavailableDelegationToolMap(input.tools, input.session);+ return filterUnavailableDelegationToolMap(input.tools, input.session, input.delegatedCaller);}async function getAdvertisedModelTools(input: AdvertisedModelToolsInput,): Promise<AdvertisedModelTools> {- const tools = filterUnavailableDelegationToolMap(input.tools, input.session);+ const tools = filterUnavailableDelegationToolMap(+ input.tools,+ input.session,+ input.delegatedCaller,+ );if (input.workflow === undefined) {return {harnessTools: tools,@@ -108,11 +119,12 @@ async function getAdvertisedModelTools(function filterUnavailableDelegationToolDefinitions(tools: readonly HarnessToolDefinition[],session: AdvertisedToolSession,+ delegatedCaller: boolean | undefined,): readonly HarnessToolDefinition[] {const filteredTools: HarnessToolDefinition[] = [];for (const tool of tools) {- if (shouldHideDelegationTool(tool, session)) {+ if (shouldHideDelegationTool(tool, session, delegatedCaller)) {continue;}filteredTools.push(tool);@@ -123,11 +135,12 @@ function filterUnavailableDelegationToolDefinitions(function filterUnavailableDelegationToolMap(tools: HarnessToolMap,session: AdvertisedToolSession,+ delegatedCaller: boolean | undefined,): HarnessToolMap {const filteredTools = new Map<string, HarnessToolDefinition>();for (const [name, tool] of tools) {- if (shouldHideDelegationTool(tool, session)) {+ if (shouldHideDelegationTool(tool, session, delegatedCaller)) {continue;}filteredTools.set(name, tool);@@ -162,7 +175,9 @@ function isDelegatedRuntimeActionTool(definition: HarnessToolDefinition): booleafunction shouldHideDelegationTool(definition: HarnessToolDefinition,session: AdvertisedToolSession,+ delegatedCaller: boolean | undefined,): boolean {+ if (definition.name === TASK_UPDATE_TOOL_NAME) return delegatedCaller !== true;if (isRootOnlyFrameworkTool(definition)) {return session.rootSessionId !== undefined || resolveSubagentDepth(session).currentDepth > 0;}@@ -172,7 +187,7 @@ function shouldHideDelegationTool(/*** Tools that only a root session may see. The `agent` self-delegation- * tool and the `experimental.tasks` controls are injected from the root+ * tool and parent-side `experimental.tasks` controls are injected from the root* node's config, which self-delegated children share — session shape is* the only signal that separates the root from its children.*/@@ -185,7 +200,7 @@ function isRootOnlyFrameworkTool(definition: HarnessToolDefinition): boolean {return true;}- return TASK_TOOL_NAMES.has(definition.name);+ return definition.name !== TASK_UPDATE_TOOL_NAME && TASK_TOOL_NAMES.has(definition.name);}function isToolDefinitionList(diff --git a/packages/eve/src/harness/tool-loop.ts b/packages/eve/src/harness/tool-loop.tsindex a0b4ebb21..1a7e5b1f7 100644--- a/packages/eve/src/harness/tool-loop.ts+++ b/packages/eve/src/harness/tool-loop.ts@@ -147,6 +147,8 @@ import { attemptIdempotencyKey } from "#harness/instrumentation/lifecycle.js";import { resolveParentLineage } from "#harness/parent-lineage.js";import { prepareTurnTraceContext } from "#harness/prepare-trace-context.js";import { ChannelKey } from "#runtime/sessions/runtime-context-keys.js";+import { TASK_UPDATE_TOOL_NAME } from "#runtime/framework-tools/tasks.js";+import { readTaskIdFromInboxToken } from "#tasks/task-inbox-token.js";import {consumeDeferredStepInput,getApprovedTools,@@ -624,8 +626,14 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {let emissionState = getHarnessEmissionState(session.state);const store = contextStorage.getStore();const parent = store?.get(ParentSessionKey);- const hasDelegatedCaller = parent !== undefined || store?.get(SessionCallbackKey) !== undefined;- const parentLineage = resolveParentLineage(parent, store?.get(ChannelKey));+ const channel = store?.get(ChannelKey);+ const callback = store?.get(SessionCallbackKey);+ const hasDelegatedCaller = parent !== undefined || callback !== undefined;+ const taskOwned =+ callback?.taskId !== undefined ||+ readTaskIdFromInboxToken(String(channel?.state?.parentContinuationToken ?? "")) !== undefined;+ const taskUpdatesEnabled = taskOwned && config.tools.has(TASK_UPDATE_TOOL_NAME);+ const parentLineage = resolveParentLineage(parent, channel);const parentTraceContext = store?.get(ParentTraceContextKey);let activeAttemptScope: InstrumentationAttemptScope | undefined;const emit = createInstrumentationHandleEvent({@@ -1336,6 +1344,7 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {: modelMessages;const harnessTools = buildHarnessToolsWithDynamicSubagents(config.tools, ctx);const advertisedHarnessTools = getAdvertisedTools({+ delegatedCaller: taskUpdatesEnabled,session,tools: harnessTools,});@@ -1352,6 +1361,7 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {if (ctx !== undefined) {const dynamicTools = getAdvertisedTools({+ delegatedCaller: taskUpdatesEnabled,session,tools: buildDynamicTools(ctx),});@@ -1389,6 +1399,7 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {: undefined;const advertisedModelTools = await getAdvertisedTools({+ delegatedCaller: taskUpdatesEnabled,modelTools: flatTools,session,tools: advertisedHarnessTools,@@ -1867,6 +1878,7 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {config,emit,emissionState,+ delegatedCaller: taskUpdatesEnabled,promptMessages: messages,result,runStep,@@ -2385,6 +2397,7 @@ async function handleStepResult(input: {readonly config: ToolLoopHarnessConfig;readonly emit?: ToolLoopHarnessConfig["handleEvent"];readonly emissionState: ReturnType<typeof getHarnessEmissionState>;+ readonly delegatedCaller: boolean;readonly promptMessages: readonly ModelMessage[];readonly result: HarnessStepResult;readonly runStep: StepFn;@@ -2473,6 +2486,7 @@ async function handleStepResult(input: {});const inputRequests: InputRequest[] = [...approvalRequests, ...questionRequests];const advertisedRuntimeActionTools = getAdvertisedTools({+ delegatedCaller: input.delegatedCaller,session: baseSession,tools: input.runtimeActionTools,});diff --git a/packages/eve/src/runtime/framework-tools/index.test.ts b/packages/eve/src/runtime/framework-tools/index.test.tsindex dba4bb117..896b9742c 100644--- a/packages/eve/src/runtime/framework-tools/index.test.ts+++ b/packages/eve/src/runtime/framework-tools/index.test.ts@@ -22,6 +22,8 @@ describe("framework-tools/index", () => {expect(names.has("load_skill")).toBe(true);expect(names.has("ask_question")).toBe(true);expect(names.has("agent")).toBe(true);+ expect(names.has("task_update")).toBe(true);+ expect(names.has("task_send")).toBe(false);// connection_search is now a dynamic tool resolver, not a framework toolexpect(names.has("connection_search")).toBe(false);});diff --git a/packages/eve/src/runtime/framework-tools/tasks.test.ts b/packages/eve/src/runtime/framework-tools/tasks.test.tsdeleted file mode 100644index ba9b18cab..000000000--- a/packages/eve/src/runtime/framework-tools/tasks.test.ts+++ /dev/null@@ -1,17 +0,0 @@-import { describe, expect, it } from "vitest";--import { TASK_SEND_INPUT_SCHEMA } from "#runtime/framework-tools/tasks.js";--describe("task_send input", () => {- it("accepts only terminal-task message follow-ups", () => {- expect(- TASK_SEND_INPUT_SCHEMA.safeParse({ message: "continue", taskId: "task_1" }).success,- ).toBe(true);- expect(- TASK_SEND_INPUT_SCHEMA.safeParse({- inputResponses: [{ optionId: "approve", requestId: "request_1" }],- taskId: "task_1",- }).success,- ).toBe(false);- });-});diff --git a/packages/eve/src/runtime/framework-tools/tasks.ts b/packages/eve/src/runtime/framework-tools/tasks.tsindex c19547675..0e75873c0 100644--- a/packages/eve/src/runtime/framework-tools/tasks.ts+++ b/packages/eve/src/runtime/framework-tools/tasks.ts@@ -8,8 +8,8 @@ import type { ResolvedToolDefinition } from "#runtime/types.js";* Framework task tools for `experimental.tasks`.** With the flag on, subagent calls return a task receipt instead of- * blocking the parent turn; these tools are the model's controls over- * that delegated work. `task_peek` and `task_cancel` are+ * blocking the parent turn; these tools coordinate that delegated work.+ * `task_peek`, `task_cancel`, and `task_update` are* execute-less runtime actions — they need durable session state and* world access, so the runtime-action dispatch step executes them.* `task_sleep` only records a durable pause and executes in-loop.@@ -17,22 +17,22 @@ import type { ResolvedToolDefinition } from "#runtime/types.js";export const TASK_PEEK_TOOL_NAME = "task_peek";export const TASK_CANCEL_TOOL_NAME = "task_cancel";-export const TASK_SEND_TOOL_NAME = "task_send";export const TASK_SLEEP_TOOL_NAME = "task_sleep";+export const TASK_UPDATE_TOOL_NAME = "task_update";/** Every model-visible task tool name, for gating and dispatch matching. */export const TASK_TOOL_NAMES: ReadonlySet<string> = new Set([TASK_PEEK_TOOL_NAME,TASK_CANCEL_TOOL_NAME,- TASK_SEND_TOOL_NAME,TASK_SLEEP_TOOL_NAME,+ TASK_UPDATE_TOOL_NAME,]);/** Task-control tools executed by the runtime-action dispatch step. */export const TASK_CONTROL_TOOL_NAMES: ReadonlySet<string> = new Set([TASK_PEEK_TOOL_NAME,TASK_CANCEL_TOOL_NAME,- TASK_SEND_TOOL_NAME,+ TASK_UPDATE_TOOL_NAME,]);const TASK_IDS_SCHEMA = z@@ -43,13 +43,8 @@ const TASK_IDS_SCHEMA = zexport const TASK_PEEK_INPUT_SCHEMA = z.strictObject({ taskIds: TASK_IDS_SCHEMA });export const TASK_CANCEL_INPUT_SCHEMA = z.strictObject({ taskIds: TASK_IDS_SCHEMA });-export const TASK_SEND_INPUT_SCHEMA = z.strictObject({- message: z- .string()- .describe(- "Follow-up message for a finished task's agent; starts a new task in the same conversation.",- ),- taskId: z.string().min(1).describe("Task id from an earlier task receipt."),+export const TASK_UPDATE_INPUT_SCHEMA = z.strictObject({+ message: z.string().min(1).describe("Brief description of what this task is currently doing."),});const MAX_SLEEP_SECONDS = Math.floor(Number.MAX_SAFE_INTEGER / 1_000);@@ -92,16 +87,14 @@ const TASK_CANCEL_DESCRIPTION ="Request cooperative cancellation of one or more background tasks. " +"Cancellation is final: a task that finishes after you cancel it stays cancelled. Cancelling an already-finished task changes nothing.";-const TASK_SEND_DESCRIPTION =- "Send a follow-up message to a finished background task's agent. " +- "This starts a new task in the same conversation and returns its receipt. " +- "Human input for an input_required task is routed directly through the parent channel. " +- "A task that is still working cannot receive sends.";-const TASK_SLEEP_DESCRIPTION ="Pause durably before continuing, for paced background-task checks. " +"Does not read or change any task; follow it with task_peek.";+const TASK_UPDATE_DESCRIPTION =+ "Briefly tell the parent agent what this background task is currently doing. " ++ "Report activity, not preliminary findings or results.";+/*** Builds the harness definitions injected when the root agent enables* `experimental.tasks`. Follows the implicit `agent` tool pattern:@@ -124,12 +117,6 @@ export function createTaskToolHarnessDefinitions(): readonly HarnessToolDefinitioutputSchema: TASK_VIEWS_OUTPUT_SCHEMA,runtimeAction: { kind: "task-control" },},- {- description: TASK_SEND_DESCRIPTION,- inputSchema: TASK_SEND_INPUT_SCHEMA,- name: TASK_SEND_TOOL_NAME,- runtimeAction: { kind: "task-control" },- },{description: TASK_SLEEP_DESCRIPTION,execute: async (input: { readonly seconds: number }) => {@@ -140,6 +127,12 @@ export function createTaskToolHarnessDefinitions(): readonly HarnessToolDefinitiname: TASK_SLEEP_TOOL_NAME,outputSchema: TASK_SLEEP_OUTPUT_SCHEMA,},+ {+ description: TASK_UPDATE_DESCRIPTION,+ inputSchema: TASK_UPDATE_INPUT_SCHEMA,+ name: TASK_UPDATE_TOOL_NAME,+ runtimeAction: { kind: "task-control" },+ },];}@@ -150,8 +143,8 @@ export function createTaskToolHarnessDefinitions(): readonly HarnessToolDefiniti* rejects `experimental.tasks` on subagents, authored tools with the* same name shadow the framework tool, and `disableTool(name)` removes* individual tools. Root-node self-delegated children share this node's- * config, so advertised-tools additionally hides the tools from any- * child-shaped session.+ * config, so advertised-tools uses caller/session shape to expose only+ * `task_update` to delegated task children.*/export function isTaskToolAvailable(input: {readonly disabledFrameworkTools: readonly string[];@@ -188,6 +181,6 @@ function createResolvedTaskToolStub(input: {export const TASK_TOOL_DEFINITIONS: readonly ResolvedToolDefinition[] = [createResolvedTaskToolStub({ description: TASK_PEEK_DESCRIPTION, name: TASK_PEEK_TOOL_NAME }),createResolvedTaskToolStub({ description: TASK_CANCEL_DESCRIPTION, name: TASK_CANCEL_TOOL_NAME }),- createResolvedTaskToolStub({ description: TASK_SEND_DESCRIPTION, name: TASK_SEND_TOOL_NAME }),createResolvedTaskToolStub({ description: TASK_SLEEP_DESCRIPTION, name: TASK_SLEEP_TOOL_NAME }),+ createResolvedTaskToolStub({ description: TASK_UPDATE_DESCRIPTION, name: TASK_UPDATE_TOOL_NAME }),];diff --git a/packages/eve/src/runtime/prompt/compose.test.ts b/packages/eve/src/runtime/prompt/compose.test.tsindex 7a0c21ca6..d139b1483 100644--- a/packages/eve/src/runtime/prompt/compose.test.ts+++ b/packages/eve/src/runtime/prompt/compose.test.ts@@ -9,7 +9,7 @@ describe("composeRuntimeBasePrompt", () => {subagentsAvailable: true,});- expect(prompt).toContainEqual(expect.stringContaining("Pass `agentId`"));+ expect(prompt).toContainEqual(expect.stringContaining("agentId"));expect(prompt).toContainEqual(expect.stringContaining("<agents>"));});@@ -22,6 +22,20 @@ describe("composeRuntimeBasePrompt", () => {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,+ });++ expect(prompt).toContainEqual(+ expect.stringContaining("return immediately with a task receipt"),+ );+ expect(prompt).toContainEqual(expect.stringContaining("do not poll with task_peek"));+ expect(prompt).toContainEqual(expect.stringContaining("notify you"));+ });+it("omits agent messaging instructions when subagents are unavailable", () => {const prompt = composeRuntimeBasePrompt({persistentSubagentSessions: true,diff --git a/packages/eve/src/runtime/prompt/compose.ts b/packages/eve/src/runtime/prompt/compose.tsindex 3ddac2a10..96618c89f 100644--- a/packages/eve/src/runtime/prompt/compose.ts+++ b/packages/eve/src/runtime/prompt/compose.ts@@ -15,7 +15,7 @@ const AGENT_MESSAGING_INSTRUCTION ="Agent messaging\nAgents you have already delegated to stay available after they answer. eve injects the current `<agents>` list into the conversation as a note labeled `[Agents]`; it is added automatically by the framework, not written by the user, and never requires a reply. The list is only a record of those existing agents — their `agentId`, name, and latest status. It does not limit which subagent tools you can call: your tool list is the source of truth, and any subagent tool can always be called without `agentId` to start a new agent, including when the `<agents>` list is empty or absent. Pass `agentId` to the same subagent tool only to continue one of those existing agents' sessions.";const TASK_AGENT_MESSAGING_INSTRUCTION =- "Agent messaging\nAgents 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: use task_peek, task_send, or 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 same 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; do not poll with task_peek or wait with task_sleep unless the user explicitly asks you to wait or the task result is required before you can answer. The task will notify you when it completes, fails, needs input, or sends an update. 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: use task_peek or 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.";/*** Input for composing the base authored instructions prompt for onediff --git a/packages/eve/src/runtime/session-callback-route.test.ts b/packages/eve/src/runtime/session-callback-route.test.tsindex 42a7417e7..da9a15167 100644--- a/packages/eve/src/runtime/session-callback-route.test.ts+++ b/packages/eve/src/runtime/session-callback-route.test.ts@@ -117,6 +117,33 @@ describe("session callback route", () => {});});+ it("forwards remote task updates to the owning task hook", async () => {+ resumeHookMock.mockResolvedValue(undefined);+ const response = await handleSessionCallbackRequest(+ new Request(`https://app.example.com/eve/v1/callback/${TASK_TOKEN}`, {+ body: JSON.stringify({+ callId: "update-call",+ childStepIndex: 2,+ childTurnId: "turn-child",+ kind: "task.update",+ message: "Found three matching records.",+ taskId: TASK_ID,+ }),+ method: "POST",+ }),+ createRouteContext({ token: TASK_TOKEN }),+ );++ expect(response.status).toBe(202);+ expect(resumeHookMock).toHaveBeenCalledWith(TASK_TOKEN, {+ callId: "update-call",+ childStepIndex: 2,+ childTurnId: "turn-child",+ kind: "task-update",+ message: "Found three matching records.",+ });+ });+it.each([["parent turn token", "turn-inbox", TASK_ID],["different task token", TASK_TOKEN, "task_other"],diff --git a/packages/eve/src/runtime/session-callback-route.ts b/packages/eve/src/runtime/session-callback-route.tsindex 18da40e3c..e140dd142 100644--- a/packages/eve/src/runtime/session-callback-route.ts+++ b/packages/eve/src/runtime/session-callback-route.ts@@ -15,6 +15,7 @@ import type {TaskInboundAuthorizationEvent,TaskInboundInputRequest,TaskInboundTurnStarted,+ TaskInboundUpdate,} from "#tasks/types.js";import { readTaskIdFromInboxToken } from "#tasks/task-id.js";@@ -117,6 +118,15 @@ const taskTurnStartedCallbackSchema = z.object({turnId: z.string().min(1),});+const taskUpdateCallbackSchema = z.object({+ callId: z.string().min(1),+ childStepIndex: eventCoordinateSchema,+ childTurnId: z.string().min(1),+ kind: z.literal("task.update"),+ message: z.string().min(1),+ taskId: z.string().min(1),+});+/*** Turn callbacks must carry the explicit `AgentTurnOutcome` envelope:* the receiving parent settles the child's handle from `outcome.kind`, so@@ -209,6 +219,17 @@ export async function handleSessionCallbackRequest(return Response.json({ ok: true }, { status: 202 });}+ const update = projectTaskUpdate(body, token);+ if (update instanceof Response) return update;+ if (update !== undefined) {+ try {+ await resumeHook(token, update);+ } catch {+ return Response.json({ error: "Session callback not pending.", ok: false }, { status: 404 });+ }+ return Response.json({ ok: true }, { status: 202 });+ }+const started = projectTaskTurnStarted(body, token);if (started instanceof Response) return started;if (started !== undefined) {@@ -296,6 +317,26 @@ function projectTaskTurnStarted(};}+function projectTaskUpdate(+ value: unknown,+ token: string,+): TaskInboundUpdate | Response | undefined {+ if (callbackKind(value) !== "task.update") return undefined;+ const parsed = taskUpdateCallbackSchema.safeParse(value);+ if (!parsed.success) {+ return Response.json({ error: "Invalid task update callback.", ok: false }, { status: 400 });+ }+ const tokenRejection = rejectMismatchedTaskToken(token, parsed.data.taskId);+ if (tokenRejection !== undefined) return tokenRejection;+ return {+ callId: parsed.data.callId,+ childStepIndex: parsed.data.childStepIndex,+ childTurnId: parsed.data.childTurnId,+ kind: "task-update",+ message: parsed.data.message,+ };+}+function rejectMismatchedTaskToken(token: string, taskId: string): Response | undefined {return readTaskIdFromInboxToken(token) === taskId? undefineddiff --git a/packages/eve/src/tasks/task-id.ts b/packages/eve/src/tasks/task-id.tsindex 8496fe4d9..4a3d69815 100644--- a/packages/eve/src/tasks/task-id.ts+++ b/packages/eve/src/tasks/task-id.ts@@ -1,6 +1,7 @@import { createHash } from "node:crypto";import { deriveAgentOperationId } from "#harness/handles/operation-id.js";+export { readTaskIdFromInboxToken } from "#tasks/task-inbox-token.js";/*** Derives the stable task id for one originating subagent call.@@ -42,9 +43,3 @@ export function deriveTaskInboxToken(input: {.digest("hex").slice(0, 32)}`;}--/** Reads the non-secret task id embedded in a private task inbox token. */-export function readTaskIdFromInboxToken(token: string): string | undefined {- const match = /^task:(task_[^:]+):[a-f0-9]{32}$/.exec(token);- return match?.[1];-}diff --git a/packages/eve/src/tasks/task-inbox-token.ts b/packages/eve/src/tasks/task-inbox-token.tsnew file mode 100644index 000000000..c4a4eabca--- /dev/null+++ b/packages/eve/src/tasks/task-inbox-token.ts@@ -0,0 +1,5 @@+/** Reads the non-secret task id embedded in a private task inbox token. */+export function readTaskIdFromInboxToken(token: string): string | undefined {+ const match = /^task:(task_[^:]+):[a-f0-9]{32}$/.exec(token);+ return match?.[1];+}diff --git a/packages/eve/src/tasks/types.ts b/packages/eve/src/tasks/types.tsindex 5ad2adb2c..78aaea7ed 100644--- a/packages/eve/src/tasks/types.ts+++ b/packages/eve/src/tasks/types.ts@@ -300,6 +300,15 @@ export interface TaskInboundTurnStarted {readonly taskId: string;}+/** Intermediate progress sent by a running child to its parent agent. */+export interface TaskInboundUpdate {+ readonly callId: string;+ readonly childStepIndex: number;+ readonly childTurnId: string;+ readonly kind: "task-update";+ readonly message: string;+}+/*** Arrives when the delegated child emits `authorization.required` or* `authorization.completed`. The former exposes an authorization blocker in@@ -335,6 +344,7 @@ export type TaskRunInboundPayload =| TaskInboundChildResult| TaskInboundInputRequest| TaskInboundTurnStarted+ | TaskInboundUpdate| TaskInboundAuthorizationEvent| TaskInboundAnswerInput;diff --git a/packages/eve/src/tasks/wire.ts b/packages/eve/src/tasks/wire.tsindex 933e0871a..1a41ac4d2 100644--- a/packages/eve/src/tasks/wire.ts+++ b/packages/eve/src/tasks/wire.ts@@ -4,9 +4,8 @@ import { readTaskUsage, taskAuthorizationRequestId } from "#tasks/types.js";/*** Translates one inbound hook payload into a lifecycle command.*- * The child wire is unchanged by `experimental.tasks`; delegated- * dispatch hands children the task run's hook token, so the payloads- * that used to resume the parent turn arrive here instead:+ * Delegated dispatch hands children the task run's hook token, so the+ * payloads that used to resume the parent turn arrive here instead:** - a settled child turn (local notification or remote callback)* carries an explicit outcome — its result status decidesdiff --git a/research/subagents-as-tasks-implementation.md b/research/subagents-as-tasks-implementation.mdindex 5836d7814..187c2540d 100644--- a/research/subagents-as-tasks-implementation.md+++ b/research/subagents-as-tasks-implementation.md@@ -44,7 +44,7 @@ so replayed creation for the same originating call yields the same task without### Flag composition-`task_send` follow-ups to a finished child require conversation-mode children and parked+`agentId` follow-ups to a finished child require conversation-mode children and parkedhandles, which `experimental.subagentPersistentSessions` gates today. `experimental.tasks`therefore implies persistent-session children for subagent dispatch. Whether it sets the otherflag or simply selects the same behavior internally is a stage-4 decision; the two flags must@@ -86,7 +86,7 @@ New `packages/eve/src/tasks/` module cluster:- `TaskStatus`, `TaskView`, `TaskMetadata`, `TaskOutput`, and a pure transition functionenforcing the lifecycle rules (terminal is final; `working <-> input_required`). This stage- also settles how `input_required` exposes its outstanding `InputRequest[]`; `task_send`+ also settles how `input_required` exposes its outstanding `InputRequest[]`; agent continuationsaccepts only a message follow-up for a terminal task.- The **durable task run**: a dedicated small workflow per task (precedent: the session-timeoutrun). It is the single writer for transitions, consumes commands over its own hook, and@@ -102,12 +102,12 @@ lifecycle path.### Stage 2 — task tools, undiscoverable-Register the parent tools (`task_peek`, `task_send`, `task_cancel`, `task_sleep`)+Register the task tools (`task_peek`, `task_cancel`, `task_sleep`, `task_update`)as framework tools, filtered out of the tool set unless the flag is on. The first implementationhas no child-facing task tool.- `task_sleep` reuses the existing durable turn-sleep request.-- `task_peek`, `task_cancel`, and `task_send` read the session task index; `task_send` resolves a+- `task_peek` and `task_cancel` read the session task index; an `agentId` continuation resolves aterminal task's child address through the agent handle store and starts a new task.Verification: unit tests per tool; a scenario test that the tools are absent from advertised@@ -176,7 +176,7 @@ deliberately; they get their own plans if anything nontrivial surfaces.`<agents>` with their active task id and status.2. **Wake policy.** Terminal and `input_required` transitions wake a parked parent through thesession delivery path; they are the only wake triggers.-3. **`task_send` to a busy child.** A send to a `working` task surfaces `AGENT_BUSY` as a tool+3. **Continuation to a busy child.** An `agentId` continuation to a `working` task surfaces `AGENT_BUSY` as a toolerror, matching handle-continuation semantics. Queuing on the task run is deferred; it isthe reversible follow-up if busy errors prove noisy in practice.The same agent is reserved for the whole dispatch batch even if its first task settles quickly.diff --git a/research/tools-as-tasks.md b/research/tools-as-tasks.mdindex d6c4cec1f..a9e10108c 100644--- a/research/tools-as-tasks.md+++ b/research/tools-as-tasks.md@@ -126,7 +126,7 @@ The parent receives these framework-owned tools:interface TaskParentTools {task_cancel(input: { taskIds: string[] }): Promise<TaskToolResult<boolean>>;task_peek(input: { taskIds: string[] }): Promise<TaskToolResult<TaskView[]>>;- task_send(input: { taskId: string; message: string }): Promise<TaskToolResult<TaskView>>;+ task_update(input: { message: string }): Promise<{ status: "sent"; taskId: string }>;task_sleep(input: { seconds: number }): Promise<TaskToolResult<boolean>>;}```@@ -138,7 +138,7 @@ The controls have distinct behavior:- `task_peek` reads current state without blocking and does not return credentials or routinghandles.-- `task_send` sends a follow-up message after the prior task became terminal, creating a new task+- Passing `agentId` to the original subagent tool sends a follow-up after the prior task became terminal, creating a new taskbound to the same child session. It never reopens a terminal task or answers HITL.- `task_cancel` requests cooperative cancellation. A committed terminal state is final, so a latechild result cannot revive a cancelled task.@@ -344,7 +344,7 @@ The current [MCP Tasks extension] provides the closest standard vocabulary:- full task snapshots in `notifications/tasks`;- terminal states that do not change.-eve's `task_peek`, `task_send`, and `task_cancel` map to those operations. `task_sleep` is an eve+eve's `task_peek` and `task_cancel` map to those operations. `task_sleep` is an evecontrol, not an MCP method. eve is not implementing the MCP wire protocol in this work.One semantic difference is decided. MCP treats a tool-level `isError: true` result as@@ -384,7 +384,7 @@ than MCP compatibility.task views with `task_peek` and decide whether the available state is sufficient.- `task_peek` observes current state without waking or mutating the executor.- Parent-session responses route directly to the intended local task child without a parent model- turn and cannot cross task or session ownership. `task_send` accepts terminal follow-up messages only.+ turn and cannot cross task or session ownership. Follow-up messages use the original subagent tool with `agentId`.- One child session owns at most one nonterminal task; repeated sends return `AGENT_BUSY` and donot queue.- Cancellation is cooperative and idempotent. A late completion cannot overwrite `cancelled`.