The Open Framework for Building Agents
feat(eve)!: run long work as tasks (#3850)
Andrew Barbac8d38a8f1d1e
diff --git a/.changeset/agent-correction-at-turn-end.md b/.changeset/agent-correction-at-turn-end.mdnew file mode 100644index 000000000..1d24fd034--- /dev/null+++ b/.changeset/agent-correction-at-turn-end.md@@ -0,0 +1,5 @@+---+"eve": patch+---++A message sent to an agent task by `taskId` just as the agent's turn ends now reaches the agent and gets the reply of the turn that read it. Before, the message could be settled with the earlier turn's reply without the agent ever seeing it, and a message sent just after a `task_cancel` could be left unanswered.diff --git a/.changeset/agent-correction-reply.md b/.changeset/agent-correction-reply.mdnew file mode 100644index 000000000..7aed89ac0--- /dev/null+++ b/.changeset/agent-correction-reply.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Correcting an agent by `taskId` while it works now gets the agent's corrected reply, and a correction sent during the agent's first turn joins that turn instead of waiting for it to end. Before, a message the agent read only after its turn ended was answered with the earlier turn's reply, and the corrected reply was lost, which could leave the caller's turn waiting forever. The same applies to `ctx.agent(name).send()`: a response resolves with the result of the turn that read its message.diff --git a/.changeset/agent-started-during-model-step.md b/.changeset/agent-started-during-model-step.mdnew file mode 100644index 000000000..4cf1939d6--- /dev/null+++ b/.changeset/agent-started-during-model-step.md@@ -0,0 +1,5 @@+---+"eve": patch+---++The parent stream now publishes `agent.started` for a session a task opens as soon as the session opens, even while the parent's model is still generating, so clients can follow the child while it works instead of after the parent's next step.diff --git a/.changeset/agent-turn-failure-reason.md b/.changeset/agent-turn-failure-reason.mdnew file mode 100644index 000000000..b65de5ad1--- /dev/null+++ b/.changeset/agent-turn-failure-reason.md@@ -0,0 +1,5 @@+---+"eve": patch+---++A `ctx.agent` turn that fails now reports why: `result()` returns `error.message` alongside `status: "failed"`. Agent tasks and `workflow` program calls include that reason in their failure, so the parent sees the agent's error instead of "The agent's session ended."diff --git a/.changeset/agents-as-tasks.md b/.changeset/agents-as-tasks.mdnew file mode 100644index 000000000..526259993--- /dev/null+++ b/.changeset/agents-as-tasks.md@@ -0,0 +1,5 @@+---+"eve": minor+---++Every agent tool is now a `serve(receive, ctx)` tool built on `ctx.agent`, so every subagent call is a resumable task: the call returns a receipt, the agent's reply arrives as a task result, and the model continues the same agent by passing `taskId` (replacing `agentId`) or stops its current turn with `task_cancel`. The `subagent.called`, `subagent.started`, `subagent.event`, and `subagent.completed` events, their hooks, the `[Agents]` note, and the `AGENT_*` errors are removed; clients, hooks, and evals read `task.started`, `task.settled`, and `agent.started` instead, and `session.streamSubagent()` takes only an `agent.started` event. `task.started` carries `kind: "agent"` for an agent tool's call and `"tool"` otherwise, so `t.calledSubagent` also sees an agent call that failed before its session opened. The default message reducer behind `useEveAgent()` settles a task call's tool part from `task.settled` (output, error, or cancellation).diff --git a/.changeset/cancelled-turn-keeps-calls.md b/.changeset/cancelled-turn-keeps-calls.mdnew file mode 100644index 000000000..b8bd87cce--- /dev/null+++ b/.changeset/cancelled-turn-keeps-calls.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Cancelling a turn no longer erases the tool calls it was waiting on from the model's history. Each one stays, answered as cancelled, so in the next turn the model sees that the work was started and stopped instead of redoing a request that looks unanswered.diff --git a/.changeset/client-agent-session.md b/.changeset/client-agent-session.mdnew file mode 100644index 000000000..921ad9f00--- /dev/null+++ b/.changeset/client-agent-session.md@@ -0,0 +1,5 @@+---+"eve": minor+---++`session.streamSubagent(started)` is now `session.agent(started).stream()`. `session.agent()` takes an `agent.started` event and returns a `ClientAgentSession` handle with the child's `name`, `sessionId`, and `taskId`; eval sessions get the same `session.agent(started).stream()`.diff --git a/.changeset/held-turn-presentation.md b/.changeset/held-turn-presentation.mdnew file mode 100644index 000000000..9776aa421--- /dev/null+++ b/.changeset/held-turn-presentation.md@@ -0,0 +1,5 @@+---+"eve": minor+---++When eve holds a turn because its tasks are still working, the stream now emits `turn.waiting` for that turn in every session, and `session.waiting` comes only after the turn really ends. In a root session, the model's text before the wait now completes as an ordinary `"stop"` message, so a person sees it right away. Child and schedule turns still report it as `"tool-calls"`, so they post once. `send().result()` and MCP `agent_get` return the final reply, not the text written before the wait.diff --git a/.changeset/one-reply-settles-together.md b/.changeset/one-reply-settles-together.mdnew file mode 100644index 000000000..16dd935f9--- /dev/null+++ b/.changeset/one-reply-settles-together.md@@ -0,0 +1,5 @@+---+"eve": patch+---++A `serve` task's `ctx.reply()` that answers several calls, such as an agent's reply to a message and its correction, now settles them together: `task_wait` no longer reports the task as both done and still working, and the model receives the reply once instead of once per call. Each call still gets its own `task.settled` event.diff --git a/.changeset/provider-results-before-local-calls.md b/.changeset/provider-results-before-local-calls.mdnew file mode 100644index 000000000..b01348070--- /dev/null+++ b/.changeset/provider-results-before-local-calls.md@@ -0,0 +1,5 @@+---+"eve": patch+---++A model response that mixes AI Gateway `web_search` results with local tool calls such as `web_fetch` no longer breaks the next model call. eve kept a local call ahead of a later search result, so Anthropic rejected the history with "`tool_use` ids were found without `tool_result` blocks" and the turn failed.diff --git a/.changeset/resumable-tasks.md b/.changeset/resumable-tasks.mdnew file mode 100644index 000000000..040ad17ac--- /dev/null+++ b/.changeset/resumable-tasks.md@@ -0,0 +1,5 @@+---+"eve": minor+---++Workflow tools can define `serve(receive, ctx)` to run a resumable task: `receive()` resolves the call that started the task, then each later call the model makes with the task's `taskId`, and `ctx.reply(output)` delivers a result while the task stays available. eve adds an optional `taskId` to a `serve` tool's model input (the build fails if `inputSchema` declares its own), idle tasks don't hold the turn and are listed in the `[Tasks]` note, and `task_cancel` aborts the current work's `abortSignal` while the task stays available for its next call, as long as the body returns to `receive()` within 30 seconds. While the task serves a later call, `ctx.session` describes that call, with its turn and the auth it was admitted with, and `ctx.agents` lists the agents that call may open. A session opened with `ctx.agent` is the child in lineage and trace of the call served when it opens, and each message sent to it carries the auth of the call served when it's sent. The events a call causes, including `task.settled`, `agent.started`, and questions, carry its `callId` and `turnId`.diff --git a/.changeset/slack-post-before-task-wait.md b/.changeset/slack-post-before-task-wait.mdnew file mode 100644index 000000000..c6edd73ea--- /dev/null+++ b/.changeset/slack-post-before-task-wait.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Slack now posts the model's text for a step whose only tool call is `task_wait`, so people see what the agent is waiting on while the turn waits; a step with any other tool call, or a schedule's turn, keeps that text as the typing status. `defineChannel` event handlers can now subscribe to `step.completed`, which Slack uses to decide once the step's actions are known.diff --git a/.changeset/steering-signals.md b/.changeset/steering-signals.mdindex 426ae1cfc..da37598e2 100644--- a/.changeset/steering-signals.md+++ b/.changeset/steering-signals.md@@ -2,4 +2,4 @@"eve": minor----Workflow tool bodies get `ctx.interruptSignal`, which aborts once when a steering message arrives while the turn waits on the call, and `ctx.ask(request, { signal })` withdraws the question when the signal aborts, resolving as `cancelled` with an `input.resolved` outcome of `"cancelled"`. `sleep` and `ask_question` now stop early for a new message, and `dismissible` and the `dismissed` status are removed; pass `{ signal: ctx.interruptSignal }` to `ctx.ask` instead.+A steering message now aborts the `ctx.abortSignal` of each `execute` workflow tool call the turn waits on, so a waited call stops early and settles with what its body returns, or `{ interrupted: true }` if the body rejects. `ctx.ask(request, { signal })` withdraws the question when the call's `abortSignal` or `signal` aborts, resolving as `cancelled` with an `input.resolved` outcome of `"cancelled"`. `sleep` and `ask_question` now stop early for a new message, and `dismissible` and the `dismissed` status are removed: a question in an `execute` call lapses when the conversation moves on, and a question asked from a `task` stays open.diff --git a/.changeset/task-kernel.md b/.changeset/task-kernel.mdnew file mode 100644index 000000000..24bd032bc--- /dev/null+++ b/.changeset/task-kernel.md@@ -0,0 +1,5 @@+---+"eve": minor+---++A workflow tool now defines exactly one of `execute(input, ctx)` or `task(input, ctx)`. A `task` tool runs each call as a task: the model gets a receipt at once, the result arrives later in a `task.result` message, the model waits with `task_wait` or stops a task with `task_cancel`, and a turn can't end while its tasks work. `agentRouter()` and the `workflow` tool now run as tasks. The stream reports `task.started` and `task.settled` with each call's `turnId`, `turn.waiting` while `task_wait` waits, and the `taskId` on `agent.started` for a session a task opens; task results are not published as `message.received`. `session.cancel()` also stops working tasks, and `execution` now fails with a pointer to `task()`. Authored tools can no longer be named `task_wait` or `task_cancel`. Consecutive queued messages from one principal now share a turn even when their auth claims changed, and the turn runs with the latest claims.diff --git a/.changeset/task-receipt-activity.md b/.changeset/task-receipt-activity.mdnew file mode 100644index 000000000..5766e8134--- /dev/null+++ b/.changeset/task-receipt-activity.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Channel activity, such as Slack's activity message, now shows a call to a task as running from its receipt until the task settles, then marks it completed, failed, or cancelled. Before, the receipt marked the call done as soon as the task started.diff --git a/.changeset/task-reply-before-result.md b/.changeset/task-reply-before-result.mdnew file mode 100644index 000000000..37b325354--- /dev/null+++ b/.changeset/task-reply-before-result.md@@ -0,0 +1,5 @@+---+"eve": patch+---++The task system prompt now tells the model it can reply before a task's result when it doesn't need the result yet. Its turn stays open and it gets the result when the task finishes, so a person who says there's no rush gets a reply right away. A question asked while tasks work is now answered before the model waits again.diff --git a/apps/frameworks/next/app/_chat/trace.ts b/apps/frameworks/next/app/_chat/trace.tsindex ac5b4e8f9..670ec4eba 100644--- a/apps/frameworks/next/app/_chat/trace.ts+++ b/apps/frameworks/next/app/_chat/trace.ts@@ -396,7 +396,7 @@ export function buildTraceTurnsFromTranscript(if (step !== undefined && eventStepIndex !== undefined) {step.events.push(event);- } else if (step !== undefined && event.type === "subagent.called") {+ } else if (step !== undefined && event.type === "agent.started") {step.events.push(event);}@@ -557,7 +557,7 @@ export function buildTraceTurnsFromTranscript(continue;}- if (event.type === "subagent.called") {+ if (event.type === "agent.started") {turn.subagentCount += 1;if (step !== undefined) {step.subagentCount += 1;diff --git a/apps/templates/eve-chat-template/.agents/skills/eve-chat-template-eve/SKILL.md b/apps/templates/eve-chat-template/.agents/skills/eve-chat-template-eve/SKILL.mdindex ffd71522a..d61d3d9ce 100644--- a/apps/templates/eve-chat-template/.agents/skills/eve-chat-template-eve/SKILL.md+++ b/apps/templates/eve-chat-template/.agents/skills/eve-chat-template-eve/SKILL.md@@ -38,6 +38,7 @@ Use this skill to preserve the Eve protocol and durable-session invariants while- Treat `message.appended.data.messageDelta` as the new text. Treat `messageSoFar`, reduced message text, and rendered parts as cumulative.- Read the stream as NDJSON. Buffering until newline is normal parsing, not app-level response buffering.- Consider a turn settled on `session.completed`, `session.failed`, or `session.waiting`. Treat `authorization.required` as a blocked state for normal text input.+- Treat `turn.waiting` as progress, not a settled turn: the turn is parked, for example while its tasks work or a running call asks a question, and resumes with the next `step.started` for the same `turnId`. Keep following the stream until one of the settling events above.- On disconnect, reconnect from the next unread remote stream index. On refresh mid-turn, resume from saved `activeChat.session` and layer resumed events until the final snapshot catches up.## Connections And Toolsdiff --git a/apps/templates/eve-llm-council-template/apps/web/app/council-app.tsx b/apps/templates/eve-llm-council-template/apps/web/app/council-app.tsxindex 209baedbb..127fc49ab 100644--- a/apps/templates/eve-llm-council-template/apps/web/app/council-app.tsx+++ b/apps/templates/eve-llm-council-template/apps/web/app/council-app.tsx@@ -44,6 +44,7 @@ const initialMembers = (): Record<MemberId, MemberState> => ({export function CouncilApp() {const [client] = useState(() => new Client({ host: "" }));const completedMembersRef = useRef(new Set<MemberId>());+ const memberCallsRef = useRef(new Map<string, MemberId>());const runIdRef = useRef(0);const synthesisStartedRef = useRef(false);const textareaRef = useRef<HTMLTextAreaElement>(null);@@ -119,24 +120,34 @@ export function CouncilApp() {const handleEvent = useCallback((event: MessageStreamEvent) => {- if (event.type === "subagent.called" && isMemberId(event.data.name)) {+ if (event.type === "task.started" && isMemberId(event.data.name)) {+ memberCallsRef.current.set(event.data.callId, event.data.name);+ }++ if (event.type === "agent.started" && isMemberId(event.data.name)) {const memberId = event.data.name;setMemberState((current) => ({...current,[memberId]: { ...current[memberId], status: "running" },}));- void streamMember(memberId, event.data.childSessionId, runIdRef.current);+ void streamMember(memberId, event.data.sessionId, runIdRef.current);}- if (event.type === "subagent.completed" && isMemberId(event.data.subagentName)) {- const memberId = event.data.subagentName;+ // A member's task.settled carries the call id its task.started named.+ const settledMember =+ event.type === "task.settled" && event.data.status === "completed"+ ? { id: memberCallsRef.current.get(event.data.callId), output: event.data.output }+ : undefined;+ if (settledMember?.id !== undefined) {+ const memberId = settledMember.id;+ const output = typeof settledMember.output === "string" ? settledMember.output : "";completedMembersRef.current.add(memberId);synthesisStartedRef.current = completedMembersRef.current.size === members.length;setMemberState((current) => ({...current,[memberId]: {...current[memberId],- response: event.data.output || current[memberId].response,+ response: output || current[memberId].response,status: "complete",},}));@@ -178,6 +189,7 @@ export function CouncilApp() {runIdRef.current += 1;completedMembersRef.current.clear();+ memberCallsRef.current.clear();synthesisStartedRef.current = false;setMemberState(initialMembers());setResult(undefined);diff --git a/docs/channels/mcp.mdx b/docs/channels/mcp.mdxindex 580b5223e..f08b82587 100644--- a/docs/channels/mcp.mdx+++ b/docs/channels/mcp.mdx@@ -187,7 +187,7 @@ The invocation response is discriminated by `status`:- `working`: work is active; continue polling according to `pollAfterMs`.- `input_required`: present `inputRequests`, then send the complete answer batch through `agent_update`. A successful update returns the current invocation state.- `authorization_required`: present the returned sign-in URL, user code, or instructions. The connection callback resumes the invocation automatically; continue polling.-- `completed`: the agent's turn settled. Consume the optional `result`: the final assistant message.+- `completed`: the agent's turn settled, after any [tasks](/docs/tools/workflows#run-calls-as-tasks-task) it started finished. Consume the optional `result`: the final assistant message.- `failed`: inspect the structured `error`.- `cancelled`: cancellation reached a terminal state.diff --git a/docs/channels/slack.mdx b/docs/channels/slack.mdxindex efe7b8858..82963ea0c 100644--- a/docs/channels/slack.mdx+++ b/docs/channels/slack.mdx@@ -450,7 +450,7 @@ The bases say where a call may go. `apiBaseUrl` is the base Slack Web API method### Delivery-The default handlers reply in-thread and show activity. Typing indicators post automatically: `Thinking…` on inbound, `Working…` on `turn.started`, a truncated reasoning snippet on `reasoning.appended`, and an action label on `actions.requested` — the tool name plus its most telling argument (`grep useEveAgent`, `read_file agent/agent.ts`), the subagent or remote-agent name for dispatched calls, and `+N more` when the model requests several actions at once. The model's own pre-tool narration, when present, takes precedence over the derived label. Reasoning snippets build progressively: extensions of at least four characters appear immediately, while smaller streamed deltas use the five-second refresh interval to avoid one Slack request per token. Override `events["reasoning.appended"]` if you prefer generic wording. Override an inbound handler or the `events` handlers to customize.+The default handlers reply in-thread and show activity. Typing indicators post automatically: `Thinking…` on inbound, `Working…` on `turn.started`, a truncated reasoning snippet on `reasoning.appended`, and an action label on `actions.requested` — the tool name plus its most telling argument (`grep useEveAgent`, `read_file agent/agent.ts`), the subagent or remote-agent name for dispatched calls, and `+N more` when the model requests several actions at once. The model's own pre-tool narration, when present, takes precedence over the derived label. When a step's only tool call is `task_wait`, Slack also posts that narration to the thread once the step completes, so people see what the agent is waiting on; a schedule's session shows it only as a typing indicator, and the reply after the wait posts as usual. Reasoning snippets build progressively: extensions of at least four characters appear immediately, while smaller streamed deltas use the five-second refresh interval to avoid one Slack request per token. Override `events["reasoning.appended"]` if you prefer generic wording. Override an inbound handler or the `events` handlers to customize.The built-in `message.completed` handler renders responses up to 12,000 characters inline. Longer responses are uploaded unchanged as a Markdown snippet named `eve-response.md` with a short in-thread note, which requires the `files:write` bot scope. Upload failures are logged by the channel dispatcher; they do not trigger a model retry. An authored `events["message.completed"]` handler replaces this behavior and owns its own delivery limits.diff --git a/docs/concepts/built-in-tools.md b/docs/concepts/built-in-tools.mdindex 0439c4044..d3e4b0fc9 100644--- a/docs/concepts/built-in-tools.md+++ b/docs/concepts/built-in-tools.md@@ -215,7 +215,7 @@ export default disableTool();### `agent`-`agent` delegates a subtask to a fresh copy of the root agent. It is root-only and waits for the child's reply, which it returns as the tool result. The child receives the root's instructions, tools, connections, and sandbox, but starts with fresh conversation history and [state](./state). See [Subagents](../subagents).+`agent` delegates a subtask to a fresh copy of the root agent. It is root-only, and each call is a [task](/docs/tools/tasks): the call returns a receipt, and the child's reply arrives later as the task's result. The child receives the root's instructions, tools, connections, and sandbox, but starts with fresh conversation history and [state](./state). See [Subagents](../subagents).```sheve add tool/agent@@ -225,7 +225,7 @@ eve add tool/agentexport { default } from "eve/tools/agent";```-An authored tool at `agent/tools/agent.ts` replaces the framework behavior. Re-export the definition above to restore direct root-copy delegation, export another tool such as `agentRouter()` to change the model-facing behavior, or disable the slot:+An authored tool at `agent/tools/agent.ts` replaces the framework behavior. Re-export the definition above to restore direct root-copy delegation, export another tool such as `agentRouter()` to change the model-facing behavior, or disable the slot. `agentRouter()` runs each call as a [task](/docs/tools/workflows#run-calls-as-tasks-task), which adds `task_wait` and `task_cancel`:```ts title="agent/tools/agent.ts"import { disableTool } from "eve/tools";@@ -271,6 +271,13 @@ export default disableTool();An authored `agent/tools/connection_search.ts` replaces the framework behavior. Import the framework definition from `eve/tools/connection_search` when you need to reference it directly. Exporting `disableTool()` from this slot is an error because agents with connections require connection discovery.+### `task_wait` and `task_cancel`++eve adds `task_wait` and `task_cancel` when the agent has a tool that runs its calls as [tasks](/docs/tools/tasks): any agent tool, including the built-in `agent` tool, declared subagents, and remote agents, or a tool such as `agentRouter()`, the `workflow` tool, or an authored workflow tool that defines `task(input, ctx)` or `serve(receive, ctx)`. There is no add command, and the tools are not workflow tools. Both names are reserved: the compiler rejects an authored `agent/tools/task_wait.ts` or `agent/tools/task_cancel.ts`.++- `task_wait({ timeout? })` parks the turn until any task has a result, a new message arrives, or `timeout` milliseconds pass, and returns at once when a result is already waiting. While it waits, the stream reports `turn.waiting` for the open turn. Results arrive in a `<task_result>` message right after it returns. Waiting never stops a task.+- `task_cancel({ taskId })` stops a task's current work and returns `{ status: "cancelled" }`, or `{ status: "already_finished" }` when the task already finished or is an idle [resumable task](/docs/tools/workflows#resumable-tasks-serve). An id that names no task fails with `UNKNOWN_TASK`. A resumable task stays available after a cancel.+Review these tools before production use. Disable, wrap, restrict, or require approval for any tool that can access the filesystem, network, shell, or sensitive data.You can also add the opt-in framework tools described below.diff --git a/docs/concepts/execution-model-and-durability.mdx b/docs/concepts/execution-model-and-durability.mdxindex 2bd120505..20c051060 100644--- a/docs/concepts/execution-model-and-durability.mdx+++ b/docs/concepts/execution-model-and-durability.mdx@@ -115,7 +115,10 @@ For ordinary tools, eve manages the workflow around your executor. Use [`defineWSome work has to wait, including a human approving a [tool](../tools) or an interactive OAuth sign-in for a [connection](../connections). At those points the turn parks durably. The workflow suspends and holds no compute until the input it's waiting on arrives, even if that's much later. When it does, the conversation picks up exactly where it left off.A workflow tool can suspend too, with its original tool call still pending and the turn parked-until the workflow settles. `defineTool` always executes inside its initiating step.+until the workflow settles. `defineTool` always executes inside its initiating step. A workflow+tool that defines `task(input, ctx)` or `serve(receive, ctx)` doesn't park the turn: its call returns a receipt, the run keeps working,+and the turn parks only when the model calls `task_wait` or tries to end the turn while the task+works. See [tasks](../tools/workflows#run-calls-as-tasks-task).An awaited workflow operation provides the durable wait. A generator's `yield` reports progress.See [durable waits](../tools#durable-waits) anddiff --git a/docs/concepts/sessions-runs-and-streaming.md b/docs/concepts/sessions-runs-and-streaming.mdindex 4361af23e..f62b8f30e 100644--- a/docs/concepts/sessions-runs-and-streaming.md+++ b/docs/concepts/sessions-runs-and-streaming.md@@ -67,39 +67,39 @@ curl http://127.0.0.1:2000/eve/v1/session/<sessionId>/streamThe stream is newline-delimited JSON (NDJSON), one event per line:-| Event | Meaning |-| ------------------------- | ---------------------------------------------------------------------------------------------------------------------------- |-| `session.started` | A durable session was created; carries `trace` when the runtime is traced. |-| `turn.started` | A new turn began; carries the active `trace` when the runtime is traced. |-| `message.received` | Input reached a turn; carries flattened text plus structured text/file parts. |-| `step.started` | A model step began. |-| `action.input.appended` | A raw tool-input text delta and its tool-call identity. |-| `actions.requested` | The model requested one or more actions, including tool calls; calls stream before execution. |-| `action.partial` | A locally executed tool generator yielded a preliminary output snapshot. |-| `action.result` | A tool call returned. |-| `input.requested` | The run paused for human input ([HITL](/docs/human-in-the-loop) approval or a `ctx.ask()` question); carries `requests`. |-| `input.resolved` | The server accepted terminal human-input outcomes; carries `resolutions` with responses when provided. |-| `subagent.called` | A subagent was delegated; carries `childSessionId` and the `childStreamPath` that `session.streamSubagent()` follows. |-| `subagent.completed` | The parent recorded a successful subagent invocation result; carries the actual output. |-| `agent.started` | A workflow tool opened a session with `ctx.agent`; carries `sessionId` and the `streamPath` that `streamSubagent()` follows. |-| `reasoning.appended` | A reasoning text delta. |-| `reasoning.completed` | The finalized reasoning block. |-| `message.appended` | An assistant text delta. |-| `message.completed` | A finalized assistant text block. |-| `result.completed` | The finalized structured result for a turn that requested an output schema; carries `result`. |-| `compaction.requested` | Context-window compaction began; carries `modelId`, `sessionId`, `turnId`, `stepIndex`, and `usageInputTokens`. |-| `compaction.completed` | A compaction checkpoint was written to durable history; carries the same model, session, turn, and step identity. |-| `authorization.required` | A connection needs OAuth; carries `name`, `description`, and an `authorization` challenge. |-| `authorization.completed` | A connection's authorization resolved; carries `outcome`. |-| `step.completed` | A model step finished; carries `finishReason` and usage. |-| `step.failed` | A model step failed; carries `{ code, message, details? }`. |-| `turn.waiting` | The open turn parked, such as when a call it runs asks a question; carries `turnId`. The turn has not ended. |-| `turn.completed` | The turn finished. |-| `turn.failed` | The turn failed; carries `{ code, message, details? }`. |-| `turn.cancelled` | The turn was cancelled before finishing; always followed by `session.waiting`. |-| `session.waiting` | The session parked and is ready for the next message. |-| `session.failed` | The session failed. |-| `session.completed` | The session reached a terminal end. |+| Event | Meaning |+| ------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `session.started` | A durable session was created; carries `trace` when the runtime is traced. |+| `turn.started` | A new turn began; carries the active `trace` when the runtime is traced. |+| `message.received` | Input reached a turn; carries flattened text plus structured text/file parts. |+| `step.started` | A model step began. |+| `action.input.appended` | A raw tool-input text delta and its tool-call identity. |+| `actions.requested` | The model requested one or more actions, including tool calls; calls stream before execution. |+| `action.partial` | A locally executed tool generator yielded a preliminary output snapshot. |+| `action.result` | A tool call returned. |+| `input.requested` | The run paused for human input ([HITL](/docs/human-in-the-loop) approval or a `ctx.ask()` question); carries `requests`. |+| `input.resolved` | The server accepted terminal human-input outcomes; carries `resolutions` with responses when provided. |+| `agent.started` | A workflow run opened a session with `ctx.agent`, such as an agent tool's; carries `taskId` when the run is a task, `sessionId`, and the `streamPath` that `session.agent(started).stream()` follows. |+| `task.started` | A tool call started a [task](#task-events); carries `taskId`, `callId`, `turnId`, the tool `name`, and `kind`: `"agent"` for an agent tool, `"tool"` otherwise. |+| `task.settled` | A task's call settled; carries `taskId`, `callId`, `turnId`, `status`, and `output` or `error.message`. |+| `reasoning.appended` | A reasoning text delta. |+| `reasoning.completed` | The finalized reasoning block. |+| `message.appended` | An assistant text delta. |+| `message.completed` | A finalized assistant text block. |+| `result.completed` | The finalized structured result for a turn that requested an output schema; carries `result`. |+| `compaction.requested` | Context-window compaction began; carries `modelId`, `sessionId`, `turnId`, `stepIndex`, and `usageInputTokens`. |+| `compaction.completed` | A compaction checkpoint was written to durable history; carries the same model, session, turn, and step identity. |+| `authorization.required` | A connection needs OAuth; carries `name`, `description`, and an `authorization` challenge. |+| `authorization.completed` | A connection's authorization resolved; carries `outcome`. |+| `step.completed` | A model step finished; carries `finishReason` and usage. |+| `step.failed` | A model step failed; carries `{ code, message, details? }`. |+| `turn.waiting` | The open turn parked while its tasks work or a call it runs waits on input; carries `turnId`. The turn has not ended. |+| `turn.completed` | The turn finished. |+| `turn.failed` | The turn failed; carries `{ code, message, details? }`. |+| `turn.cancelled` | The turn was cancelled before finishing; always followed by `session.waiting`. |+| `session.waiting` | The session parked and is ready for the next message. |+| `session.failed` | The session failed. |+| `session.completed` | The session reached a terminal end. |The optional `data.trace` on session and turn starts contains eve-owned W3C trace coordinates: `traceId`, `spanId`, and `traceFlags`. Use it to correlate stream consumers such as eval reporters with an observability backend. An uninstrumented target omits it.@@ -119,11 +119,17 @@ Note: consider the privacy, confidentiality, and user-experience implications fo`message.completed` can fire more than once in a turn: the agent often emits interim assistant text before a tool call. To tell tool-call narration from a terminal reply, check `message.completed.data.finishReason`. `step.completed.data.finishReason` mirrors the step outcome, and usage lives on `step.completed`.-A delegated subagent publishes progress on its own child-session stream. The parent emits `subagent.called` with a `childSessionId` and a `childStreamPath`, which a client follows with `session.streamSubagent()`. Every call emits `subagent.completed` with the actual output after the parent records a successful outcome. Completion does not mean that the reusable child session has ended. A session a workflow tool opens with `ctx.agent` is announced with `agent.started`, which carries the child's `sessionId` and a `streamPath` that `session.streamSubagent()` also follows; the workflow tool's result carries what it returns.+A delegated subagent publishes progress on its own child-session stream. When a subagent tool call or a workflow tool's `ctx.agent` opens a session, the parent emits `agent.started` with the call's `callId` and `turnId`, its `taskId` when the call runs as a task, the child's `sessionId`, and a `streamPath` that a client follows with `session.agent(started).stream()`. A subagent tool call is a [task](#task-events) whose `task.started` has `kind: "agent"`: its `task.started` and `task.settled` carry the call, and `task.settled.data.output` is the child's reply. A call that fails before the child session opens has no `agent.started`. A settled call does not end the child session; later calls with the same `taskId` reach it.A question or sign-in from inside a running call does not end the turn. This covers a workflow tool's `ctx.ask()`, including the built-in `ask_question` tool, and a delegated subagent's question or sign-in. The stream emits `input.requested` or `authorization.required`, then `turn.waiting` with the open turn's `turnId`. After the answer or sign-in, the turn resumes with the next `step.started` for the same `turnId`, and only `turn.completed`, `turn.failed`, or `turn.cancelled` ends it. When you answer a question that belongs to a workflow tool or a subagent, the session you answer on emits `input.resolved` for it as it routes the answer down. A tool approval the turn requests still ends the turn: `input.requested`, `turn.completed`, then `session.waiting`.-`step.failed` and `turn.failed` carry `{ code, message, details? }` for the failed fragment or turn, and `session.failed` is the terminal session-level variant. `turn.cancelled` is not a failure: the cancelled turn ends without any failure event, `session.waiting` follows, and the session accepts the next message normally. Whatever the turn streamed before cancellation stays on the stream. Durable history keeps the accepted user input and previously settled work, but discards incomplete assistant output and unfinished tool state. When a turn requested an output schema, the finalized payload lands on `result.completed` as `data.result` before the turn boundary. `authorization.required` carries the sign-in challenge (`data.authorization` may include `url`, `userCode`, `expiresAt`, `instructions`), and `authorization.completed` carries `data.outcome` (`"authorized" | "declined" | "failed" | "timed-out"`).+### Task events++A call to a tool that runs as a task, such as an agent tool, `agentRouter()`, the `workflow` tool, or a workflow tool that defines [`task(input, ctx)`](/docs/tools/workflows#run-calls-as-tasks-task) or [`serve(receive, ctx)`](/docs/tools/workflows#resumable-tasks-serve), returns a receipt as its `action.result` and keeps working. `task.started` reports the task's `taskId` for the call's `callId` and `turnId`, both when a call starts a task and when a call reaches a resumable task by its `taskId`, before any event the task's run publishes for that call. `task.settled` comes once per call, with the same `turnId`, `status` `"completed"`, `"failed"`, or `"cancelled"`, and the call's `output` when it completed or `error.message` when it failed. Results reach the model as a message in its history, not as a stream event, so read outcomes from `task.settled`. A session the task's run opens with `ctx.agent` is announced with `agent.started` carrying the `taskId`. An `input.requested`, `authorization.required`, or `authorization.completed` event from a task's run carries its `taskId`. Each of these events names the call the task is serving when it happens: a resumable task's later call brings its own `callId` and `turnId`, which may belong to a later turn than the call that started the task.++A turn doesn't end while tasks are working. When the model ends its text early, eve holds the turn and the stream emits `turn.waiting` for it; the turn continues once a result arrives or its caller writes. In a root session, that text completes as an ordinary `message.completed`. In a child session or a schedule's session, it reports `finishReason: "tool-calls"`, so channels post only the final reply. When the model calls `task_wait` and no result is ready yet, the stream also emits `turn.waiting`. Either way, the next `step.started` for the same `turnId` means the turn resumed, and `session.waiting` comes only after the turn ends. See [Tasks](/docs/tools/tasks#turns-wait-for-their-tasks).++`step.failed` and `turn.failed` carry `{ code, message, details? }` for the failed fragment or turn, and `session.failed` is the terminal session-level variant. `turn.cancelled` is not a failure: the cancelled turn ends without any failure event, `session.waiting` follows, and the session accepts the next message normally. Whatever the turn streamed before cancellation stays on the stream. Durable history keeps the accepted user input and previously settled work, and discards incomplete assistant output. Tool calls the cancellation stopped stay in history, each answered as cancelled, so the model sees that the work started and stopped instead of a request left unanswered. When a turn requested an output schema, the finalized payload lands on `result.completed` as `data.result` before the turn boundary. `authorization.required` carries the sign-in challenge (`data.authorization` may include `url`, `userCode`, `expiresAt`, `instructions`), and `authorization.completed` carries `data.outcome` (`"authorized" | "declined" | "failed" | "timed-out"`).A provider response ending with `content-filter` fails with `MODEL_CALL_FAILED`,`details.semanticErrorId: "model-response-content-filtered"`, and@@ -185,7 +191,7 @@ Three more things to know:- **Ids are time-ordered, not a total order.** The turn steps of one session can run in different processes, each generating ids from its own clock and its own random bits. Two events emitted in the same millisecond by different steps may sort either way, and clock skew between machines can invert neighbours. Record your own ingestion sequence, or read the stream in order and store the index, when you need an exact ordering to page against — do not use `where id > $cursor` as a lossless cursor. The stream itself is authoritative: `startIndex` is an absolute event count.- **Ids identify events, not intent.** Two events with identical payloads — the `step.failed` → `turn.failed` → `session.failed` cascade, or two identical text deltas in one step — are distinct events with distinct ids. Deduplicate on `meta.id` only; matching on content would drop real data.-- **A subagent's event is re-emitted, not shared.** When a parent forwards a child's event onto its own stream, the parent's copy is a separate event with its own id. Correlate the two streams through `subagent.called.data.childSessionId`.+- **A subagent's event is re-emitted, not shared.** When a parent forwards a child's event onto its own stream, the parent's copy is a separate event with its own id. Correlate the two streams through `agent.started.data.sessionId`.Authored [hooks](../guides/hooks) receive the same envelope, but observe each event as it is emitted rather than as it is read — so a hook sees a retry as new events, and `meta.id` is a key for a stored row rather than a retry guard. Two things a hook does not have to defend against: a turn that parks for human input resumes without re-emitting anything it already sent, and a retried turn dispatch cannot double-stream a turn, because one session owner executes it.@@ -207,11 +213,11 @@ curl -X POST http://127.0.0.1:2000/eve/v1/session/<sessionId> \-d '{"inputResponses":[{"requestId":"req_A","optionId":"approve"}]}'```-Message sends default to `"steer"`. Before assistant output begins, eve interrupts pending model generation and continues the same turn with the correction. Reasoning and provider search progress do not count as assistant output. An executing eve tool finishes safely, and its result is preserved before the correction reaches the next model call. A workflow tool call the turn is waiting on learns of the message through its [`ctx.interruptSignal`](/docs/tools/workflows#stop-early-for-a-new-message-ctxinterruptsignal): `sleep` and `ask_question` stop early, and other workflow tools keep going unless their body handles the signal. After assistant output starts, steering applies at the next committed workflow boundary; text already streamed remains visible. Channels and TypeScript `Session.send(...)` calls can select `turnPolicy: "queue"` when the active turn should finish first. Structured `inputResponses` answer their addressed requests.+Message sends default to `"steer"`. Before assistant output begins, eve interrupts pending model generation and continues the same turn with the correction. Reasoning and provider search progress do not count as assistant output. An executing eve tool finishes safely, and its result is preserved before the correction reaches the next model call. A steering message aborts the [`ctx.abortSignal`](/docs/tools/workflows#stop-early-for-a-new-message) of each `execute` workflow tool call the turn is waiting on: its questions are withdrawn, `sleep` and `ask_question` stop early, and the call settles with what its body returns. A steering message ends a `task_wait` but never interrupts a task. Only the turn's own caller steers it; another caller's message waits for the turn to end. After assistant output starts, steering applies at the next committed workflow boundary; text already streamed remains visible. Channels and TypeScript `Session.send(...)` calls can select `turnPolicy: "queue"` when the active turn should finish first. Structured `inputResponses` answer their addressed requests.If the session is waiting on a human-in-the-loop approval, respond with the channel’s Approve or Cancel controls. Text messages do not decide an approval; unrelated text starts an ordinary turn while the approval stays pending and answerable. A later structured `inputResponses` answer keyed by its `requestId` still resumes the original tool call, even after intervening turns.-A pending `ctx.ask()` question from a tool, such as `ask_question`, can be answered with plain text. When it is the only pending question, a message that matches an option answers it, and so does any message when the question allows free text. Otherwise eve does not guess which question the text addresses: the message follows the normal `turnPolicy`. A steering message withdraws questions asked with `ctx.interruptSignal` as their signal, which resolve as `cancelled`; other questions stay open. Questions from subagents always need a structured response. Use structured responses to target requests unambiguously.+A pending `ctx.ask()` question from a tool, such as `ask_question`, can be answered with plain text. When it is the only pending question, a message that matches an option answers it, and so does any message when the question allows free text. Otherwise eve does not guess which question the text addresses: the message follows the normal `turnPolicy`. A steering message withdraws the questions of the `execute` workflow tool calls the turn waits on, which resolve as `cancelled`; a task's questions stay open. Questions from subagents always need a structured response. Use structured responses to target requests unambiguously.A structured response matches any currently pending request by ID, not only the newest batch. It becomes stale only after that request was answered, cleared, or cancelled. eve delivers a stale response to the model as a new user message, and the model decides whether the old selection still matters. A stale approval never authorizes the earlier tool call; the model must request the action and approval again if they are still needed.@@ -228,7 +234,7 @@ curl -X POST http://127.0.0.1:2000/eve/v1/session/<sessionId>/cancel# {"ok":true,"sessionId":"<sessionId>","status":"accepted"}```-`"accepted"` means the live session durably queued the request; cancellation completes asynchronously. Confirm turn cancellation on the stream as `turn.cancelled` followed by `session.waiting`. The session then accepts the next message normally. Each cancelled child reports its own boundary on its child-session stream. A live but already-parked session returns `"accepted"`; cancellation is a no-op there. `"no_active_turn"` means the session or channel address is unknown or terminal. Both statuses are success, so clients can fire and forget. See the [eve channel](../channels/eve) for the full route contract.+`"accepted"` means the live session durably queued the request; cancellation completes asynchronously. Confirm turn cancellation on the stream as `turn.cancelled` followed by `session.waiting`. The session then accepts the next message normally. Each cancelled child reports its own boundary on its child-session stream. Cancelling also stops every working task, each reported as `task.settled` with `status: "cancelled"`, including while the session waits between turns. A live but already-parked session returns `"accepted"`; with no working tasks, cancellation is a no-op there. `"no_active_turn"` means the session or channel address is unknown or terminal. Both statuses are success, so clients can fire and forget. See the [eve channel](../channels/eve) for the full route contract.The HTTP route returns `202` for `"accepted"` and `200` for`"no_active_turn"`. Only the accepted result includes `sessionId`.diff --git a/docs/evals/assertions.mdx b/docs/evals/assertions.mdxindex cac425e95..7c66502df 100644--- a/docs/evals/assertions.mdx+++ b/docs/evals/assertions.mdx@@ -85,9 +85,9 @@ Pick the cheapest builder that captures what "correct" means. When exact match i`t.calledTool` and `t.calledSubagent` take matcher objects. Tools accept `{ input, output, status, count }`; subagents accept `{ callId, childSessionId, remoteUrl, output, status, count }`. Calls match `status: "completed"` by default. Tool lifecycle checks also accept `"pending"`, `"failed"`, and `"rejected"`. Subagent checks accept `"working"`, `"completed"`, `"failed"`, and `"cancelled"`. A numeric `count` requires an exact number of calls matching every supplied constraint. Use a predicate for ranges or other custom count requirements; it receives the observed number of matching calls.-A subagent call stays `working` until its result is observed. It becomes `completed` when its successful result is observed through its tool result or `subagent.completed`, even when the child session stays available for another call. A rejected dispatch or failed call is `failed`; an explicit cancelled child outcome is `cancelled`.+A subagent call is a task call: it stays `working` until its `task.settled` event arrives, then takes that event's `status` (`completed`, `failed`, or `cancelled`) and, when completed, its `output`. A completed call leaves the child session available for later calls with the same `taskId`.-The runner derives these values from captured events. A proxied input request alone does not change the subagent call's status; assert that request with `requireInputRequest`.+The runner counts each `task.started` with `kind: "agent"` as a subagent call and takes its status from `task.settled`. `childSessionId` and `remoteUrl` come from the task's `agent.started`, so they are absent for a call that failed before its session opened. A proxied input request alone does not change the subagent call's status; assert that request with `requireInputRequest`.Matcher values accept a literal (objects partial-deep-match), a RegExp, or a predicate function that returns a boolean:@@ -125,8 +125,8 @@ Typed event matching covers presence, absence, numeric or predicate counts, part```tsturn.notEvent("result.completed");turn.eventOrder([- { type: "subagent.called", data: { name: "researcher" }, count: 2 },- { type: "subagent.completed", data: { subagentName: "researcher" }, count: 2 },+ { type: "task.started", data: { name: "researcher" }, count: 2 },+ { type: "task.settled", data: { status: "completed" }, count: 2 },]);```diff --git a/docs/evals/cases.mdx b/docs/evals/cases.mdxindex 468f29fda..1ce04e4ca 100644--- a/docs/evals/cases.mdx+++ b/docs/evals/cases.mdx@@ -111,7 +111,7 @@ Every `t.session()` or `t.send()` creates a new independent conversation. Contin- `session.start(message, options?)` starts a text turn and returns as soon as the server accepts it. The live turn exposes `.session`, `.sessionId`, `.waitForEvent(...)`, `.cancel()`, and `.result()`.- `session.cancel()` requests cooperative cancellation of that session's active turn. Both `accepted` and `no_active_turn` are successful outcomes.- `session.sendFile(text, path, mediaType?)` attaches a local file as a data URL.-- `session.streamSubagent(started, options?)` follows a delegated child's stream through the parent with the eval client's credentials. Pass an `agent.started` or `subagent.called` event from that session. It also reaches children on another deployment, which `t.target.watchTurn(...)` cannot address.+- `session.agent(started).stream(options?)` follows a delegated child's stream through the parent with the eval client's credentials. Pass an `agent.started` event from that session. It also reaches children on another deployment, which `t.target.watchTurn(...)` cannot address.- `session.requireInputRequest(filter?)` records a gate, requires exactly one pending request, and returns it. Filters match tool name, action input, prompt, display, and option ids.- `session.respond(responses, options?)` answers specific pending input requests and sends them as the next turn. `session.startRespond(...)` returns a live turn for the same operation.- `session.respondAll(optionId)` answers every pending input request with the same option and sends the responses as the next turn.diff --git a/docs/guides/client/streaming.mdx b/docs/guides/client/streaming.mdxindex 1de519735..54f13385c 100644--- a/docs/guides/client/streaming.mdx+++ b/docs/guides/client/streaming.mdx@@ -67,6 +67,11 @@ runs asks a question, such as a workflow tool's `ctx.ask()`, `result()` returnsits `input.resolved`, which the session you answer on also emits for asubagent's or workflow tool's question.+A turn that waits on its [tasks](/docs/tools/workflows#run-calls-as-tasks-task)+also emits `turn.waiting` without a pending request. The text the model wrote+before the wait is not the reply: `result()` resolves with the final reply+after the tasks finish.+`result()` closes that HTTP stream, including when fetch instrumentation clonesthe response for tracing. The durable session remains available for follow-upturns after `session.waiting`.@@ -84,7 +89,7 @@ for await (const event of response) {}if (event.type === "message.completed" && event.data.finishReason !== "tool-calls") {- console.log("\nfinal:", event.data.message);+ console.log("\nmessage:", event.data.message);}}```@@ -137,6 +142,8 @@ The most common UI events are:| `actions.requested` | Show tool calls as the model requests them, before execution. || `action.partial` | Update a generator tool's provisional output snapshot. || `action.result` | Show tool call results. |+| `task.started` | Show a task call; `action.result` is a receipt. `kind: "agent"` marks agents. |+| `task.settled` | Show the task's result, error, or cancellation for the call's `callId`. || `input.requested` | Pause the UI for approval or a question answer. || `input.resolved` | Record the server-accepted outcome and response for each human-input request. || `result.completed` | Read structured output from an [output schema](./output-schema). |@@ -148,6 +155,8 @@ For the complete event table, see [Sessions, runs & streaming](../../concepts/seFor `action.input.appended`, the default message reducer accumulates accepted deltas into a `dynamic-tool` part with `state: "input-streaming"`; its `inputText` field contains cumulative raw text that may be incomplete JSON. The matching `actions.requested` event upgrades the same `toolCallId` to `state: "input-available"` and puts the validated value in `input`.+A call to a tool that runs as a [task](/docs/tools/workflows#run-calls-as-tasks-task) returns a receipt as its `action.result` and settles later with `task.settled`, matched by `callId`. The model receives the result as a message in its history, but the stream reports it only as `task.settled`, so render the result from that event.+When a submitted message includes attachments, `message.received.data.message` stays theflattened compatibility summary, while `message.received.data.parts` carries renderable text andfile metadata. File parts never include raw bytes or internal sandbox paths; `url` appears only for@@ -253,24 +262,25 @@ stream index after the captured prefix.## Follow a subagent-A delegated subagent reports its progress on its own child session. The parent stream announces each child: `subagent.called` when the model calls a subagent tool, and `agent.started` when a [workflow tool](/docs/tools/workflows#delegate-work-ctxagent) opens a session with `ctx.agent`. Pass either event to `streamSubagent()` on the parent's session handle to follow the child:+A delegated subagent reports its progress on its own child session. The parent stream announces each child session with `agent.started`, whether the model called a subagent tool or a [workflow tool](/docs/tools/workflows#delegate-work-ctxagent) opened the session with `ctx.agent`. Pass the event to `agent()` on the parent's session handle to get the child's handle, then follow it with `stream()`:```tsimport { isCurrentTurnBoundaryEvent } from "eve/client";const session = client.sessions.attach(parentSessionId);const { events } = await session.snapshot();-const called = events.find((event) => event.type === "subagent.called");+const started = events.find((event) => event.type === "agent.started");-if (called?.type === "subagent.called") {- for await (const event of session.streamSubagent(called)) {- console.log(called.data.name, event.type);+if (started?.type === "agent.started") {+ const child = session.agent(started);+ for await (const event of child.stream()) {+ console.log(child.name, event.type);if (isCurrentTurnBoundaryEvent(event)) break;}}```-`streamSubagent()` reads the event's stream path, `childStreamPath` on `subagent.called` or `streamPath` on `agent.started`, with the parent session's host and credentials, so the same client works for local and [remote](../remote-agents) children:+`stream()` reads the event's `streamPath` with the parent session's host and credentials, so the same client works for local and [remote](../remote-agents) children:- A local child's path is its own session stream route on the same deployment. The channel's usual session authorization applies.- A remote child's path is a proxy route on the parent deployment. The parent checks that its session recorded the child for that tool call, then relays the remote child's stream with the remote agent's authored `auth` and `headers`. The client never needs the remote URL or its credentials.diff --git a/docs/guides/frontend/overview.mdx b/docs/guides/frontend/overview.mdxindex 9c0020aa6..8822912f9 100644--- a/docs/guides/frontend/overview.mdx+++ b/docs/guides/frontend/overview.mdx@@ -170,7 +170,7 @@ supplied `session` remains externally owned and is never replaced by prewarming`data.messages` are eve-owned `EveMessage[]`. Common text, reasoning, file, and dynamic-tool parts follow the [AI SDK `UIMessage`](https://ai-sdk.dev/docs/reference/ai-sdk-core/ui-message) rendering convention, but the types are not interchangeable. eve also exposes authorization and HITL metadata, and a file part's URL can be absent. Adapt those parts before passing messages to an API typed as `UIMessage[]`.-When the root agent delegates, its stream emits `subagent.called` with the child's `childSessionId`, then `subagent.completed` when the parent records a successful result. The child session can remain available for reuse. Detailed child progress lives on the child session's stream instead of being flattened into the root `data.messages`. When your UI needs live subagent activity, attach a [client session](../client/overview#sessions) to the parent and pass the `subagent.called` event from `events` to [`streamSubagent()`](../client/streaming#follow-a-subagent). It follows local and remote children through the parent, so the browser never calls a remote deployment directly. See [What the parent sees](../../subagents#what-the-parent-sees) for the complete contract.+When the root agent delegates, its stream emits `agent.started` with the child's `sessionId`, and the subagent tool call's `task.settled` carries the child's reply. The child session can remain available for reuse. Detailed child progress lives on the child session's stream instead of being flattened into the root `data.messages`. When your UI needs live subagent activity, attach a [client session](../client/overview#sessions) to the parent and pass the `agent.started` event from `events` to [`session.agent()`](../client/streaming#follow-a-subagent) and follow the child with `stream()`. It follows local and remote children through the parent, so the browser never calls a remote deployment directly. See [What the parent sees](../../subagents#what-the-parent-sees) for the complete contract.## Sending and streamingdiff --git a/docs/guides/hooks.md b/docs/guides/hooks.mdindex 9d4908596..5a457139e 100644--- a/docs/guides/hooks.md+++ b/docs/guides/hooks.md@@ -87,10 +87,11 @@ handle can also automatically resume on later I/O. A hook failure, including afailed stop, follows the normal[hook failure behavior](#what-happens-when-a-hook-throws).-For `subagent.called` and `subagent.completed`, `ctx.session.id` identifies the-parent session. Typed handlers and `*` handlers receive this context even when-the subagent event arrives between parent turns. These hooks can use-`ctx.getSandbox()` against the parent session.+For `task.started`, `task.settled`, and `agent.started`, `ctx.session.id`+identifies the session that started the task or opened the subagent session.+Typed handlers and `*` handlers receive this context even when the event+arrives between turns. These hooks can use `ctx.getSandbox()` against that+session, and sandbox changes they make are kept for its next turn.### Narrowing tool results@@ -184,7 +185,7 @@ Hooks always run after the event is durably recorded, so if a hook throws, the seve logs a thrown or rejected handler with the hook slug, subscription, event type, event ID, and session ID, then runs the remaining subscribers in order. The current turn, subagent notification, and session continue. This applies to every stream-event hook, including `turn.started`, `step.started`, and failure events. Throwing from a hook does not reject work or veto a turn. To stop the running turn, call [`ctx.cancel()`](#cancel-the-running-turn-from-a-hook).-A hook failure does not trigger a retry. State changes and external side effects made before the exception are not rolled back. If a side effect needs retries or compensation, handle that inside the hook. Runtime failures outside the authored handler, such as failures setting up context or persisting state, still propagate. If persisting state after a subagent notification fails, the workflow runtime retries the notification step, which can publish the event again.+A hook failure does not trigger a retry. State changes and external side effects made before the exception are not rolled back. If a side effect needs retries or compensation, handle that inside the hook. Runtime failures outside the authored handler, such as failures setting up context or persisting state, still propagate. If persisting state after a `task.started`, `task.settled`, or `agent.started` event fails, the workflow runtime retries the publishing step, which can publish the event again.## Cancel the running turn from a hook@@ -215,7 +216,7 @@ The remaining subscribers for the event still run. Then eve cancels the turn the`ctx.cancel()` returns `void` rather than a promise. The turn stops after the hook returns, so there is nothing to await. Call it before the handler's promise settles: eve ignores a call from work the handler does not await and logs a warning.-`ctx.cancel()` only stops a running turn. eve logs a warning and ignores the call on `step.failed`, `turn.completed`, `turn.failed`, `turn.cancelled`, `turn.waiting`, `session.waiting`, `session.completed`, `session.failed`, `context.cleared`, `agent.started`, and `subagent.*` events, and during clear or compact requests.+`ctx.cancel()` only stops a running turn. eve logs a warning and ignores the call on `step.failed`, `turn.completed`, `turn.failed`, `turn.cancelled`, `turn.waiting`, `session.waiting`, `session.completed`, `session.failed`, `context.cleared`, `task.started`, `task.settled`, and `agent.started`, and during clear or compact requests.## Subagent isolationdiff --git a/docs/guides/remote-agents.md b/docs/guides/remote-agents.mdindex 699cdc9b4..8d76ce624 100644--- a/docs/guides/remote-agents.md+++ b/docs/guides/remote-agents.md@@ -80,7 +80,7 @@ The function may be async and must return a non-empty string. `auth` and `header## Calling a remote agent-By default, a remote agent is another subagent tool to the model. The model calls it the same way it calls a local subagent, with a `message` and an optional `agentId`. Set `tool: false` when an authored workflow tool should be the only model-facing routing surface; the workflow can still call the remote agent by its path-derived name through `ctx.agent()`. The message must carry the full task, including any context the remote agent needs, because it never receives the parent's conversation history.+By default, a remote agent is another subagent tool to the model. The model calls it the same way it calls a local subagent, with a `message` and an optional `taskId`. Set `tool: false` when an authored workflow tool should be the only model-facing routing surface; the workflow can still call the remote agent by its path-derived name through `ctx.agent()`. The message must carry the full task, including any context the remote agent needs, because it never receives the parent's conversation history.To require structured output, open a session with the remote agent from an authored workflow tool with `ctx.agent(name)` and pass `outputSchema` to `send()`. The schema applies to that turn, the structured value is the response's `data`, and the session accepts follow-up messages until the workflow run finishes. See [Delegate work: `ctx.agent`](../tools/workflows#delegate-work-ctxagent).@@ -131,9 +131,9 @@ export default defineRemoteAgent({});```-The create-session request carries the parent turn's `session.auth.current` and `session.auth.initiator` as a `forwardedPrincipal` body field (`initiator` is optional on the wire; when absent, the receiver seeds both from `current`). Every continuation carries only that turn's `session.auth.current`; the remote session keeps its original `auth.initiator`. Only principal metadata crosses the wire — never tokens or credentials. The receiving deployment resolves its own per-user credentials through its own connections.+The create-session request carries the parent turn's `session.auth.current` and `session.auth.initiator` as a `forwardedPrincipal` body field (`initiator` is optional on the wire; when absent, the receiver seeds both from `current`). A continuation by `taskId` carries the `session.auth.current` of the call that continues the task; the remote session keeps its original `auth.initiator`. Only principal metadata crosses the wire — never tokens or credentials. The receiving deployment resolves its own per-user credentials through its own connections.-This makes caller authority turn-scoped even when the remote child session is persistent. If Alice starts the child and Bob later continues it, the follow-up runs with Bob as `auth.current`, not Alice. If the parent turn's auth is `null`, a local child clears `auth.current`, while a remote child uses the freshly verified transport principal; neither inherits Alice. eve's in-step bearer cache is also keyed by the resolved principal and is not serialized across steps. The external authorization provider may preserve each user's server-side OAuth grant, but a later turn can resolve only the grant belonging to its own `auth.current` principal.+This makes caller authority turn-scoped even when the remote child session is persistent. If Alice starts the child and Bob later continues it with its `taskId`, the follow-up runs with Bob as `auth.current`, not Alice. If the parent turn's auth is `null`, a local child clears `auth.current`, while a remote child uses the freshly verified transport principal; neither inherits Alice. eve's in-step bearer cache is also keyed by the resolved principal and is not serialized across steps. The external authorization provider may preserve each user's server-side OAuth grant, but a later turn can resolve only the grant belonging to its own `auth.current` principal.Identity forwarding does not make a persistent session private to one caller. Conversation history, tool outputs, and other child-session state still persist. If those values must not be visible across users, give each user a distinct child session or enforce that ownership at the application boundary.@@ -183,19 +183,19 @@ widen capture and use metadata-only tracing.## How remote dispatch and callbacks work-A remote subagent call runs a child session in the remote deployment and waits for its reply:+A remote subagent call runs a child session in the remote deployment as a task:1. The parent starts a persistent conversation session on the remote's `POST /eve/v1/session`, passing a framework callback URL.-2. The remote accepts the child and runs its turn while the parent turn waits.-3. The callback delivers the child's reply, which becomes the tool result.+2. The remote accepts the child and runs its turn while the task works.+3. The callback delivers the child's reply, which becomes the task's result.-The parent stream carries the same `subagent.called`, `action.result`, and `subagent.completed` events as local delegation. For a remote call, `subagent.called.data.remote.url` records the target. A session a workflow tool opens with `ctx.agent` is announced with `agent.started` instead, whose `data.remote.url` records the target.+The parent stream carries the same `task.started`, `agent.started`, and `task.settled` events as local delegation. For a remote child, `agent.started.data.remote.url` records the target.-Clients follow a remote child through the parent. [`session.streamSubagent()`](./client/streaming#follow-a-subagent) reads the event's stream path, a route on the parent deployment. The parent verifies that its session recorded the child for that tool call, resolves the remote agent's `auth` and `headers`, and relays the child's stream. A browser never calls the remote deployment or holds its credentials; it only needs access to the parent session.+Clients follow a remote child through the parent. [`session.agent(started).stream()`](./client/streaming#follow-a-subagent) reads the `agent.started` event's `streamPath`, a route on the parent deployment. The parent verifies that its session recorded the child for that tool call, resolves the remote agent's `auth` and `headers`, and relays the child's stream. A browser never calls the remote deployment or holds its credentials; it only needs access to the parent session.-Cancelling the parent turn also cancels the remote child's current turn. eve resolves the remote's `headers` and `auth` again for every cancellation attempt, so rotating credentials work the same way as they do for session creation. Cancellation always uses the standard eve cancel path on `url`, even when `path` customizes only the create-session endpoint. The remote child reports `turn.cancelled` → `session.waiting` on its own stream; an older or unreachable remote is logged but cannot turn the parent's cancellation into a failure.+Cancelling the parent turn or the agent task with `task_cancel` also cancels the remote child's current turn. eve resolves the remote's `headers` and `auth` again for every cancellation attempt, so rotating credentials work the same way as they do for session creation. Cancellation always uses the standard eve cancel path on `url`, even when `path` customizes only the create-session endpoint. The remote child reports `turn.cancelled` → `session.waiting` on its own stream; an older or unreachable remote is logged but cannot turn the parent's cancellation into a failure.-When the parent session ends, eve sends an authenticated `POST /eve/v1/session/:childSessionId/reset` for each remote child. A session opened with `ctx.agent` is reset the same way when its workflow run finishes. Reset retires the parked remote session and recursively cleans up its descendants. The request uses freshly resolved `headers` and `auth`; failures are logged so an unreachable remote cannot block parent finalization.+When the workflow run that opened a remote child finishes, eve sends an authenticated `POST /eve/v1/session/:childSessionId/reset` for it. An agent task's run finishes when the parent session ends. Reset retires the parked remote session and recursively cleans up its descendants. The request uses freshly resolved `headers` and `auth`; failures are logged so an unreachable remote cannot block parent finalization.Both deployments must speak the same eve remote agent protocol version. The parent names its version when it creates the child, and the remote rejects a mismatch; either way the call fails at start with an error naming both versions, so upgrade both deployments to the same eve release. A failed _start_ fails the call immediately. After a remote starts, a terminal failure callback fails the call with the remote's error. Terminal callback delivery runs as a durable step on the underlying workflow engine (see [Execution model & durability](../concepts/execution-model-and-durability)). A failed callback POST is rethrown rather than completing the call, so the engine retries it.diff --git a/docs/subagents/index.mdx b/docs/subagents/index.mdxindex ca5e9b49b..c51281946 100644--- a/docs/subagents/index.mdx+++ b/docs/subagents/index.mdx@@ -9,11 +9,13 @@ Use a subagent to run independent work in parallel, narrow the available tools,- Use a [declared local subagent](#declared-subagents) for a specialist with its own directory and authored capabilities, rather than inheriting the root's.- Use a [remote agent](./guides/remote-agents) to delegate to a separately deployed eve agent, with its own configuration and authentication.-Each subagent call blocks the calling turn until the child replies, and the child's final result is-the tool result. If the child session expires, resets, or closes before replying, the call fails-and reports the usage accumulated since its previous settlement. This applies to root-agent copies,-declared local subagents, and remote subagents. The subagent session remains available for later-calls.+Every subagent call runs as a [task](./tools/tasks). The call returns a+receipt naming the task's `taskId` right away, the child works while the parent continues, and the+child's final reply for that turn arrives as the task's result. The parent's turn does not end while+the task is working. If the child's turn fails, the call fails and the task ends. This applies to+root-agent copies, declared local subagents, and remote subagents. The subagent session remains+available for later calls with the same `taskId`. When an action must wait for a subagent's result,+such as publishing only after a review, [run both from one workflow tool](./tools/tasks#order-work-that-depends-on-a-result).## The built-in `agent` tool@@ -21,12 +23,12 @@ The root session receives `agent` by default. The model calls it to delegate a t```ts{- message: string; // everything the child needs; it does not see the parent's history- agentId?: string; // continue an existing child+ message: string; // everything the child needs; it does not see the parent's history+ taskId?: string; // continue an existing child}```-The copy uses the root's instructions, connections, auth, and sandbox. It receives the same tools except for the root-only `agent`, and starts with fresh conversation history and fresh state. Its file writes are immediately visible to the root. The built-in `agent` needs no configuration. Each call waits for the child's reply and returns it as the tool result, and several `agent` calls in one response run in parallel. Give parallel children non-overlapping write scopes.+The copy uses the root's instructions, connections, auth, and sandbox. It receives the same tools except for the root-only `agent`, and starts with fresh conversation history and fresh state. Its file writes are immediately visible to the root. The built-in `agent` needs no configuration. Each call starts or continues a task whose result is the child's reply, and several `agent` calls in one response run in parallel. Give parallel children non-overlapping write scopes.`agent` is intentionally root-only. Copies created by it cannot call `agent`, and declared subagents never receive the built-in tool. If a stale or forced recursive call reaches execution, eve rejects it instead of starting another child session.@@ -72,7 +74,7 @@ export default defineAgent({The parent can alternatively export `disableTool()` from a same-named tool path, such as `agent/tools/researcher.ts`. This suppresses the derived model tool without removing `researcher` from the workflow invocation registry. A same-named authored tool replaces the model-facing surface while the workflow can still call the underlying subagent with `ctx.agent("researcher", ...)`.-A declared local or remote subagent call waits for the child's reply and returns it as the tool result. Human input requests from the child surface on the parent session while the call waits. Cancelling the calling turn also cancels the child's current turn.+A declared local or remote subagent call returns a receipt, and the child's reply arrives as the task's result. Human input requests from the child surface on the parent session while the task works. `task_cancel` with the task's `taskId` cancels the child's current turn, and so does cancelling the calling turn.A mounted extension can also contribute declared subagents from `extension/subagents/`. The mount namespace prefixes the subagent visible to the consuming agent node: mounting an extension as `crm` exposes its `reviewer` subagent as `crm__reviewer`. The contributed subagent keeps its own isolated tools, connections, skills, hooks, instructions, sandbox, and nested subagents, and its modules can read configuration from the extension handle. See [Extensions](./extensions#add-a-subagent) for the authoring and override behavior.@@ -206,7 +208,7 @@ The root built-in `agent` tool is the exception. Its children reuse the root's s## What the parent sees-eve lowers every tool-enabled subagent visible to the current agent (the root built-in copy, declared, or [remote](./guides/remote-agents)) into a model-visible tool with the same `{ message, agentId? }` shape. The parent packs `message` with everything the child needs, since the child never sees the parent's history. To require structured output from a child, open a session with it from an authored workflow tool with [`ctx.agent(name)`](./tools/workflows#delegate-work-ctxagent) and pass `outputSchema` to `send()`; the schema applies to that turn, and the session accepts follow-up messages until the workflow run finishes.+eve lowers every tool-enabled subagent visible to the current agent (the root built-in copy, declared, or [remote](./guides/remote-agents)) into a model-visible tool with the same `{ message, taskId? }` shape. The parent packs `message` with everything the child needs, since the child never sees the parent's history. To require structured output from a child, open a session with it from an authored workflow tool with [`ctx.agent(name)`](./tools/workflows#delegate-work-ctxagent) and pass `outputSchema` to `send()`; the schema applies to that turn, and the session accepts follow-up messages until the workflow run finishes.Declared subagents can call nested subagents defined under their own directories. eve does not apply a separate depth limit; nesting ends where the authored directory tree ends. The built-in `agent` follows the stricter root-only rule above, so `limits.maxSubagentDepth` no longer exists.@@ -216,20 +218,20 @@ A directly declared subagent's tool name is the bare path-derived name, with no```ts{- message: string; // all context the child needs; it never sees the parent's history- agentId?: string; // continue an existing child+ message: string; // all context the child needs; it never sees the parent's history+ taskId?: string; // continue an existing child}```+The tool's description is the subagent's `description` followed by a sentence telling the model that the agent does not see the conversation and that `taskId` continues an agent task.+By default, a subagent named `researcher` collides with an authored tool named `researcher`. Set the subagent's `tool` to `false` when the authored tool intentionally wraps that subagent; the authored tool becomes the model-facing capability while `ctx.agent("researcher", ...)` continues to address the child. A same-named `disableTool()` removes the model-facing capability entirely. Other static and active dynamic collisions remain errors.Do not rely on subagent delegation by itself as an approval boundary. Put sensitive tools behind `approval`, connection approval, route/session authorization, or other controls wherever those tools can be called.-Each delegated subagent spins up its own child session and stream. The parent stream carries the control-plane events `subagent.called` and `subagent.completed`, plus interactive `input.requested`, `authorization.required`, and `authorization.completed` events proxied from descendants so the root channel can prompt the user. The parent emits `input.resolved` when it routes an answer back down to the descendant that asked. To follow the child's other progress, pass the `subagent.called` event to [`session.streamSubagent()`](./guides/client/streaming#follow-a-subagent) on a client session attached to the parent. It reads `subagent.called.data.childStreamPath`: the child's own session stream for a local child, or a parent-origin proxy for a remote child, which the parent authenticates to the remote deployment.--Every invocation emits `subagent.called` after dispatch and `subagent.completed` after the parent records successful completion. Completion carries the actual output and identifies the same invocation by `callId`; the child session can remain available for reuse. Failure and cancellation do not emit `subagent.completed`; the failed tool result carries the error.+Each delegated subagent spins up its own child session and stream. The parent stream carries the call's `task.started` and `task.settled` events, `agent.started` when the child session opens, plus interactive `input.requested`, `authorization.required`, and `authorization.completed` events proxied from descendants so the root channel can prompt the user. The parent emits `input.resolved` when it routes an answer back down to the descendant that asked. `task.settled` carries the child's reply as `output` when the call completes, or `error.message` when it fails. To follow the child's other progress, pass the `agent.started` event to [`session.agent()`](./guides/client/streaming#follow-a-subagent) on a client session attached to the parent and follow the child with `stream()`. It reads `agent.started.data.streamPath`: the child's own session stream for a local child, or a parent-origin proxy for a remote child, which the parent authenticates to the remote deployment.-A session an authored workflow tool opens with `ctx.agent` is announced with `agent.started` instead, which carries the workflow tool call's `callId` and `turnId`, the agent `name`, the child's `sessionId`, and a `streamPath` that `session.streamSubagent()` also accepts. Its questions and sign-ins reach the root session the same way.+`agent.started` carries the `callId` and `turnId` of the call that opened the session, the call's `taskId`, the agent `name`, and the child's `sessionId`. Later calls with the same `taskId` reach the same session and do not announce it again, so match a child to its calls by `taskId`. A session an authored workflow tool opens with `ctx.agent` is announced the same way, with its `taskId` only when the workflow tool call runs as a task.Channels with activity reporting show a subagent's tool activity beneath that subagent's progress item. Activity reporting is best-effort and does not change execution or result delivery.@@ -237,13 +239,13 @@ Subagent model calls automatically retry classified transient provider failures,## Agent messaging-A child parks after answering instead of terminating, keeping its session and conversation history alive. A failed child turn can also leave the child parked — its latest status shows the error and the parent may message it again. Pass a parked child's `agentId` to the same subagent tool with a new `message` to continue that session. Omitting `agentId` (or passing an empty string or `null`) always starts a new child, and an `agentId` that matches no known agent falls back to starting a new child rather than failing. Passing a known `agentId` through a different subagent tool fails with `AGENT_MISMATCH`.+A child parks after answering instead of terminating, keeping its session and conversation history alive. Pass the task's `taskId` to the same subagent tool with a new `message` to continue that session. Omitting `taskId` always starts a new child. When a child's turn fails, the call fails and the task ends. A `taskId` that names no task of that subagent tool, including one that ended, fails with `UNKNOWN_TASK`. Any later turn can continue the child, and each continuation runs with the auth of the caller that sends it.-A call that names a child that is still starting or running returns `AGENT_BUSY`. Delivery failures are reported to the caller; eve does not start a replacement child session to hide them.+A call with the `taskId` of a child that is still working joins the child's current turn, and that turn's final reply settles both calls. If the turn ends before the child reads the message, the message starts the child's next turn, and that turn's reply settles both calls. Use it to correct or add to work in progress. `task_cancel` with the task's `taskId` cancels the child's current turn and keeps its conversation, so a later call with the same `taskId` continues where it left off.-Whenever the set of parked (resumable) children changes, eve appends a framework-injected note to the conversation — labeled `[Agents]` and carrying an `<agents>` block — listing each child's `agentId`, name, and latest status. The static system prompt tells the model the note is injected by eve, not written by the user. The note is appended only when the listing changes (an append-only design that preserves the provider prompt cache), the most recent note is authoritative, and children that are starting or running do not appear until they park again.+eve adds a framework-injected `[Tasks]` note to the conversation that lists the working and idle tasks by `taskId` and tool, so the model can find a child to continue. See [Tasks](./tools/tasks) for how the model waits for, corrects, and cancels agent tasks.-The parent holds agent handles only for its session lifetime. When the parent session ends, eve terminates local children and sends authenticated reset requests for remote children. Remote reset is best-effort: an unreachable deployment may retain the parked child until its own session deadline. For [remote agents](./guides/remote-agents), upgrade both deployments before relying on continuation or reset behavior introduced by a newer eve version.+The parent holds each child for the life of the task's run, which lasts until the parent session ends. Then eve resets local children and sends authenticated reset requests for remote children. Remote reset is best-effort: an unreachable deployment may retain the parked child until its own session deadline. For [remote agents](./guides/remote-agents), upgrade both deployments before relying on continuation or reset behavior introduced by a newer eve version.## When to splitdiff --git a/docs/tools/human-in-the-loop.md b/docs/tools/human-in-the-loop.mdindex b32daab17..c5c6cd0c0 100644--- a/docs/tools/human-in-the-loop.md+++ b/docs/tools/human-in-the-loop.md@@ -180,7 +180,7 @@ Approvals and questions share one protocol:3. The turn parks at `session.waiting`, durably, for as long as it takes.4. The client answers with `inputResponses` (structured, keyed by `requestId`) or a normal follow-up `message`. A follow-up whose text matches an option ID, option label, or numeric option index resolves automatically, including approval options such as `approve` and `cancel`.-For `ctx.ask()` questions from tools, a follow-up message answers the question only when exactly one question is pending. The message must match an option, or the question must allow free text. Otherwise the message follows the session's `turnPolicy`. A steering message, the default, fires `ctx.interruptSignal` for each workflow tool call the turn waits on, so a question asked with that signal, such as `ask_question`'s, is withdrawn and resolves as `cancelled`. The model reads the message once those calls settle. Questions from subagents need a structured response.+For `ctx.ask()` questions from tools, a follow-up message answers the question only when exactly one question is pending. The message must match an option, or the question must allow free text. Otherwise the message follows the session's `turnPolicy`. A steering message, the default, aborts the `ctx.abortSignal` of each `execute` workflow tool call the turn waits on, so a question such a call asked, such as `ask_question`'s, is withdrawn and resolves as `cancelled`. The model reads the message once those calls settle. Questions from subagents need a structured response.Each request includes a `kind` discriminator: `tool-approval`, `question`, or`session-limit`. Clients should use `kind` to choose behavior and presentation.diff --git a/docs/tools/meta.json b/docs/tools/meta.jsonindex b6f3245ee..d7efbe735 100644--- a/docs/tools/meta.json+++ b/docs/tools/meta.json@@ -1,5 +1,5 @@{"title": "Tools","defaultOpen": false,- "pages": ["overview", "human-in-the-loop", "workflows"]+ "pages": ["overview", "human-in-the-loop", "workflows", "tasks", "tasks-upgrade"]}diff --git a/docs/tools/overview.mdx b/docs/tools/overview.mdxindex 76e8c5547..775da88f5 100644--- a/docs/tools/overview.mdx+++ b/docs/tools/overview.mdx@@ -138,6 +138,13 @@ can wait durably while the call is pending:| `defineTool` | No; the executor runs inside the initiating step. | Executor output after it finishes. || `defineWorkflowTool` | Yes; the tool call waits while the workflow can suspend. | Workflow output after it finishes. |+A workflow tool that defines `task(input, ctx)` in place of `execute` runs each call as a+[task](/docs/tools/workflows#run-calls-as-tasks-task):+the call returns a receipt at once, and the workflow's output reaches the model later in a+`task.result` message. One that defines `serve(receive, ctx)` runs a+[resumable task](/docs/tools/workflows#resumable-tasks-serve), which the model can send more calls+by its `taskId`.+The `TaskExec` argument and `task.postMessage` have been removed. Return the result. In a workflowbody, keep values needed after a wait in local variables; workflow replay reconstructs them acrossdurable waits. Use [`ctx.ask`](/docs/tools/workflows#ask-a-human-ctxask) when the body needs andiff --git a/docs/tools/tasks-upgrade.md b/docs/tools/tasks-upgrade.mdnew file mode 100644index 000000000..514b05996--- /dev/null+++ b/docs/tools/tasks-upgrade.md@@ -0,0 +1,185 @@+---+title: "Upgrade to Tasks"+description: "Move workflow tools, agent calls, clients, hooks, and evals from background tasks to tasks."+url: /tools/tasks-upgrade+---++This release replaces background tasks with [tasks](/docs/tools/tasks). Every change below breaks+the previous API. Work through the sections that apply to your agent. A workflow tool that uses+none of `execution: "background"`, `dismissible`, or `ctx.agent` keeps its code: `execute(input,+ctx)` keeps its signature, and `ctx.abortSignal` and `ctx.callId` are where they were. One behavior+changes for every `execute` tool: a steering message now aborts its `ctx.abortSignal`. See+[Drop `dismissible`](#drop-dismissible-a-new-message-stops-an-execute-call).+Type-checking flags most of the code changes, such as the removed `execution` and `dismissible`+options and the old `ctx.agent` call.++## Replace `execution: "background"` with `task(input, ctx)`++Rename `execute` to `task` and remove `execution`. The body doesn't change:++```diff+ export default defineWorkflowTool({+ description: "Deploy a service.",+ inputSchema: z.object({ service: z.string() }),+- execution: "background",+- async execute({ service }, ctx) {++ async task({ service }, ctx) {+ "use workflow";+ return await deploy(service, ctx.abortSignal);+ },+ });+```++`defineWorkflowTool` rejects `execution` with+`"execution" was replaced by task(). Define task(input, ctx) to run each call as a task.` A+`task` body gets the same `WorkflowToolContext` as an `execute` body, and steering never aborts a+task's `abortSignal`. An `execute` tool is an ordinary tool call: the turn waits for its result. See+[Choose how a call runs](/docs/tools/tasks#choose-how-a-call-runs).++A tool that the model should be able to send more input while it works, such as a plan it revises+on request, defines [`serve(receive, ctx)`](/docs/tools/workflows#resumable-tasks-serve) instead.++## Drop `dismissible`: a new message stops an `execute` call++`ctx.ask` no longer accepts `dismissible`. A steering message now aborts the `ctx.abortSignal` of+each `execute` call the turn waits on, which withdraws every question the call asked, as+`dismissible: true` did:++```diff+-const answer = await ctx.ask({ prompt, dismissible: true });++const answer = await ctx.ask({ prompt });+```++To keep a question open through new messages, ask it from a+[`task`](#replace-execution-background-with-taskinput-ctx) instead. Other work that+receives `ctx.abortSignal`, such as a step or a `ctx.agent` send, stops too. The call settles with+what the body returns, or with `{ interrupted: true }` if the body rejects, and the model reads the+message next.++A withdrawn question resolves as `{ status: "cancelled" }` instead of `dismissed`, and the+`input.resolved` outcome `"dismissed"` is now `"cancelled"`. Update clients and channels that+match on the old value. See [Pass signals to the work](/docs/tools/tasks#pass-signals-to-the-work).++## Open agent sessions with `ctx.agent(name)`++`ctx.agent(name, { message, agentId })`, which returned the agent's output, is now+`ctx.agent(name)`, which returns a session. Send a message and read the turn's result:++```diff+-const review = await ctx.agent("reviewer", { message: plan });++const response = await ctx.agent("reviewer").send(plan, { signal: ctx.abortSignal });++const { message: review, status } = await response.result();++if (status === "failed") throw new Error("The review failed.");+```++`agentId` is removed. Each `ctx.agent(name)` call returns a new session, and later `send` calls on+the same handle continue its conversation until the workflow run finishes. See+[Delegate work](/docs/tools/workflows#delegate-work-ctxagent). The `workflow` tool's generated+programs keep their `ctx.agent(name, { message, outputSchema? })` capability.++## Continue agents by `taskId`++Every agent tool is now a `serve` tool, so every agent call is a resumable task. The model's agent+tools take `taskId` instead of `agentId`:++```diff+-{ "message": "Check the Q2 numbers too.", "agentId": "…" }++{ "message": "Check the Q2 numbers too.", "taskId": "researcher-7k2m9q" }+```++An agent call returns a receipt at once, and the agent's reply arrives later in a `task.result`+message. Update instructions, prompts, and evals that mention `agentId` or expect the reply as+the tool result. `agentRouter()` and the `workflow` tool now run each call as a task too.++The removed codes `AGENT_BUSY`, `AGENT_MISMATCH`, `AGENT_UNREACHABLE`, and+`AGENT_INVOCATION_NOT_ADMITTED` have no replacement. A `taskId` that names no unfinished task of+that tool fails with `UNKNOWN_TASK`, and a call past the limit of 32 working tasks fails with+`TOO_MANY_TASKS`.++## Remove background delivery options++Results reach the model one way: a `task.result` message at a step boundary. Remove these:++- `taskDeliveryPolicy` and delivery cohorts.+- The `tasks` option of `session.cancel()`. `session.cancel()` now cancels the turn, the `execute`+ calls it waits on, and every working task; it still accepts `turnId` and `signal`.++The model no longer sees `[Task state]` or `[Agents]` notes, prose task notifications,+`<eve-empty-delivery/>`, or result turns. A `[Tasks]` note lists its working and idle tasks+instead. The `BACKGROUND_TASK_FAILED` and `BACKGROUND_TASK_CANCELLED` codes are removed; a+failed task reports its error in `task.settled` and in its `task.result` block.++## Read task events instead of `subagent.*` events++The `subagent.called`, `subagent.started`, `subagent.completed`, and `subagent.event` events are+removed. Use these instead:++| Event | Replaces | Data |+| --------------- | -------------------- | --------------------------------------------------------------- |+| `task.started` | `subagent.called` | `taskId`, `callId`, `turnId`, `name` |+| `task.settled` | `subagent.completed` | `taskId`, `callId`, `turnId`, `status`, and `output` or `error` |+| `agent.started` | `subagent.started` | `callId`, `turnId`, `taskId`, `name`, `sessionId`, `streamPath` |++Follow a child's own events, which `subagent.event` used to relay, on its stream:+`session.streamSubagent()` is now `session.agent(started).stream()`, and it takes the `agent.started` event.++```diff+ for await (const event of session.stream()) {+- if (event.type !== "subagent.called") continue;++ if (event.type !== "agent.started") continue;+- for await (const childEvent of session.streamSubagent(event)) {++ for await (const childEvent of session.agent(event).stream()) {+```++Hooks subscribe the same way:++```diff+ export default defineHook({+ events: {+- async "subagent.completed"(event, ctx) {++ async "task.settled"(event, ctx) {++ if (event.data.status !== "completed") return;+```++The eval assertion `t.calledSubagent(name, { status })` keeps its API and reads task events.++## Handle open turns in clients++A turn doesn't end while tasks are working, so one turn can span a wait. The stream+reports each wait with the new `turn.waiting` event, which carries the open turn's `turnId`:++- **Held turns.** When the model ends its text while its tasks work, and when `task_wait` has no+ result yet, the stream emits `turn.waiting`. The next `step.started` for the same `turnId` means+ the turn resumed. In a root session, the text before the wait completes as a normal+ `message.completed`; in child sessions and a schedule's sessions, that step reports+ `finishReason: "tool-calls"`.+- **Questions and sign-ins inside a call no longer end the turn.** Previously, a question or+ sign-in from inside a running call, such as a workflow tool's `ctx.ask()`, `ask_question`, or a+ subagent's question, emitted `turn.completed` and `session.waiting` in the middle of the turn.+ It now emits `input.requested` or `authorization.required`, then `turn.waiting`, and the turn+ resumes under the same `turnId` after the answer. The session you answer on emits+ `input.resolved` for every question it routes an answer to. A tool approval the turn itself+ requests still ends the turn with `turn.completed` and `session.waiting`.+- **`turn.completed` comes only when the turn really ends,** and `session.waiting` always means+ the turn has ended.++The TypeScript client's `send(...).result()` reads past `turn.waiting` and returns the final reply+of a held turn, not the text written before the wait. It stops at `turn.waiting` only while a+question is pending, and returns `status: "waiting"` with that question; `respond()` then reads the+same turn to its end. A custom client that ends a response at `turn.completed` or+`session.waiting` mid-turn, or that shows the first completed message as the reply, should follow+the same rule. See [Aggregate a turn](/docs/guides/client/streaming#aggregate-a-turn).++Task results aren't stream events. Background task results used to appear as `message.received`+with `data.kind: "execution.background_task"`; `message.received` no longer has `kind`, and a task+result reaches only the model. Read each call's outcome from `task.settled` instead.++The message stream version is now 26. The TypeScript client accepts versions 21 through 26. A+client that accepts only versions up to 25 fails the stream with an unsupported-version error. See+[Turns wait for their tasks](/docs/tools/tasks#turns-wait-for-their-tasks).++## Upgrade remote agents together++The remote agent protocol is now version 2. Upgrade the calling deployment and every+[remote agent](/docs/guides/remote-agents) it calls to this release together; a mismatch fails the+call at start with an error that names both versions.diff --git a/docs/tools/tasks.md b/docs/tools/tasks.mdnew file mode 100644index 000000000..a588e3975--- /dev/null+++ b/docs/tools/tasks.md@@ -0,0 +1,283 @@+---+title: "Tasks"+description: "Run agent and workflow tool calls as tasks that keep working while the conversation continues, and control how the model waits for, corrects, and cancels them."+url: /tools/tasks+---++A task is a tool call that returns a receipt right away and keeps working while the conversation+continues. Every call to an agent is a task, and so is every call to a+[workflow tool](/docs/tools/workflows) that defines `task(input, ctx)` or `serve(receive, ctx)`.+A task's result reaches the model later, in a `task.result` message, and a turn can't end while+tasks are still working.++This page covers when to use a task, how to order work that depends on a result, the signals a+workflow tool body receives, and what the model and the stream see.++## Choose how a call runs++A workflow tool defines exactly one entry point, and the entry point answers one question: should+the conversation continue while the call works?++```ts+defineWorkflowTool({ /* … */ async execute(input, ctx) {} }); // the turn waits until the call settles+defineWorkflowTool({ /* … */ async task(input, ctx) {} }); // a task: a receipt now, the result later+defineWorkflowTool({ /* … */ async serve(receive, ctx) {} }); // a task that accepts more calls+```++Defining none of the three, or more than one, throws when the tool is defined.++| Call | Runs as | Result | A new message during the call |+| ----------------------------------------------------------------------- | ------------------------- | ------------------------------------------------- | --------------------------------- |+| `execute` workflow tool, including `sleep` and `ask_question` | Tool call; the turn waits | The tool result | Aborts the call's `abortSignal` |+| `task` workflow tool, including `agentRouter()` and the `workflow` tool | Task | A receipt, then a `task.result` message | Nothing |+| `serve` workflow tool, including every agent tool | Resumable task | A receipt, then a `task.result` message per reply | Nothing |+| `task_wait` | Wait inside the turn | Which tasks settled | Ends the wait |+| Plain and MCP tools | Inside the model step | The tool result | Applied at the next step boundary |++Waiting alone doesn't need a task. A question, a `sleep`, or an approval inside an `execute` call+parks the turn durably and holds no compute, and a new message stops the wait. Use a task when the+model should keep talking while the work runs, such as a twenty-minute deploy or research the model+may not need right away, or when a question should stay open through new messages. A long+`execute` tool holds the conversation until it settles or a new message stops it.++Agents have no choice to make: every agent tool is a `serve` tool, so every agent call is a+resumable task, because only the model can tell from the conversation whether it needs an agent's+answer now. The [turn rule](#turns-wait-for-their-tasks) guarantees the answer reaches the model+before the turn ends.++See [Run calls as tasks](/docs/tools/workflows#run-calls-as-tasks-task) for writing a `task` body+and [Resumable tasks](/docs/tools/workflows#resumable-tasks-serve) for `serve` bodies,+`receive()`, and `ctx.reply()`.++## Order work that depends on a result++Because agent calls are tasks, the model decides when to wait for them. An instruction such as+"publish only after the review approves" holds only as long as the model follows it. When an order+must always hold, write a workflow tool that runs the first step through+[`ctx.agent`](/docs/tools/workflows#delegate-work-ctxagent) and then acts, and don't expose the+side effect as a separate tool:++```ts title="agent/tools/publish_reviewed_notes.ts"+import { defineWorkflowTool } from "eve/tools";+import { z } from "zod";+import { publishNotes } from "../lib/release";++const Review = z.object({ approved: z.boolean(), reason: z.string() });++export default defineWorkflowTool({+ description: "Have the reviewer check the release notes, then publish them if approved.",+ inputSchema: z.object({ notes: z.string() }),+ async execute({ notes }, ctx) {+ "use workflow";+ const response = await ctx.agent("reviewer").send(`Review these release notes:\n\n${notes}`, {+ outputSchema: Review,+ signal: ctx.abortSignal,+ });+ const { data, status } = await response.result();+ if (status === "failed" || data === undefined) {+ throw new Error("The review did not finish.");+ }+ if (!data.approved) return { published: false, reason: data.reason };+ return { published: true, url: await publish(notes) };+ },+});++async function publish(notes: string) {+ "use step";+ return await publishNotes(notes);+}+```++The publish step can only run after the review returns. Set `tool: false` on the `reviewer`+subagent if the model shouldn't call it directly, and define `task` in place of `execute` if the+conversation should continue while the review runs.++## Pass signals to the work++A workflow tool body receives its signals from its context or, in a `serve` body, from each call+`receive()` resolves:++- **`abortSignal`** aborts when the call's work should stop: by `task_cancel`, `session.cancel()`,+ a cancelled or failed turn, or the end of the session, and, for an `execute` call, by a steering+ message that arrives while the turn waits on it. `execute` and `task` bodies read it as+ `ctx.abortSignal`. In a `serve` body, each call from `receive()` carries its own `abortSignal`;+ every call in one stretch of work shares one signal, and the next stretch gets a new one. Pass it+ to the steps and `ctx.agent` sends that should stop.+- **`ctx.ask(request)`** withdraws the question when the call's `abortSignal` aborts, and+ `ctx.ask(request, { signal })` also when `signal` does. The answer resolves as+ `{ status: "cancelled" }`, and the stream reports `input.resolved` with `outcome: "cancelled"` so+ channels stop offering the question. A person's answer that reached the session first still wins:+ the ask resolves as `answered`, so branch on `status`, not on the signal.++A body doesn't need to tell a steering message from a cancel: in both cases, stop and return what+you have. After a steering message the call settles with what the body returns, or with+`{ interrupted: true }` if the body rejects, and the model reads the message next. After a cancel,+eve discards the result. So a question in an `execute` call lapses once the conversation moves on,+as the provided `ask_question` tool's does, while a question in a task stays open:++```ts+async execute({ service }, ctx) {+ "use workflow";+ const answer = await ctx.ask({+ prompt: `Deploy ${service} now?`,+ display: "confirmation",+ options: DEPLOY_OR_WAIT,+ });+ if (answer.status === "cancelled") return { deployed: false, reason: "the conversation moved on" };+ // …+}+```++See [Stop early for a new message](/docs/tools/workflows#stop-early-for-a-new-message) for how the+provided `sleep` tool races its timer against the signal.++## What the model sees++eve adds `task_wait`, `task_cancel`, and a short system prompt block that explains tasks whenever+the agent has an agent tool or a `task` or `serve` workflow tool.++**Receipts.** A call that starts a task returns a receipt as its tool result. Task ids are the tool+name and six characters. A resumable task's receipt tells the model how to reach it again, and a+call that reaches it by `taskId` returns a short receipt of its own:++```text+Started task deploy-4hd8sa.+Started task researcher-7k2m9q. Call researcher again with taskId researcher-7k2m9q to send it another message.+Sent to task researcher-7k2m9q.+```++**Results.** Each result arrives once, as a `<task_result>` block in a `task.result` message that+eve appends at the next step boundary, right after `task_wait` returns, or when a held turn+resumes. The body is the tool's `toModelOutput` projection of the output, or the error message for+a failed call. All results in one message share a budget of 50 KB and 2,000 lines, after which the+text is cut and marked `[truncated]`.++```text+<task_result id="deploy-4hd8sa" tool="deploy" status="completed">{"url":"https://…"}</task_result>+```++**`task_wait({ timeout? })`** parks the turn until any task has a result, a new message+arrives, or `timeout` milliseconds pass. It returns at once when a result is already+waiting, and a `timeout` of `0` returns at once with any results that are ready. Waiting never+stops a task. The model reads which tasks settled and which are still working, for example:++```text+deploy-4hd8sa completed; its result follows. 1 task is still working: researcher-7k2m9q.+```++**`task_cancel({ taskId })`** stops a task's current work and returns `{ status: "cancelled" }`.+When the task has no work to stop, because it already finished or is an idle resumable task, it+returns `{ status: "already_finished" }`.++**`[Tasks]` note.** When the session's tasks change, eve adds a note at the next step boundary that+lists the working tasks and the 10 most recently used idle resumable tasks. The note returns after+[compaction](/docs/concepts/default-harness#compaction), so the model can always find a task id:++```text+[Tasks]+<tasks>+<task id="deploy-4hd8sa" tool="deploy" status="working"/>+</tasks>+<idle>+<task id="researcher-7k2m9q" tool="researcher"/>+</idle>+```++**Errors.** Two error codes are specific to tasks:++| Code | When |+| ---------------- | ----------------------------------------------------------------------------------------- |+| `UNKNOWN_TASK` | A call's `taskId` names no unfinished resumable task that the same tool started |+| `UNKNOWN_TASK` | `task_cancel`'s `taskId` names no task; a finished or idle one returns `already_finished` |+| `TOO_MANY_TASKS` | A call would start a task, or make an idle one work, while 32 tasks are working |++A `final_output` call made while tasks are working returns an error that names them.++## Turns wait for their tasks++No turn ends while any task is working. When the model ends a turn early, eve waits as+`task_wait` does: it parks until one of the tasks settles or the turn's own caller steers it,+appends the results, and calls the model again in the same turn. No result ever starts a turn on+its own. An idle resumable task isn't working, so it doesn't hold the turn.++A held turn stays open. Each time it parks, when eve holds it or when `task_wait` has no result+yet, the stream emits `turn.waiting` with the turn's `turnId`. The next `step.started` for the+same `turnId` means the turn resumed, and `session.waiting` comes only after the turn ends. The+model's text before the wait depends on the session:++- **Root sessions:** the text completes as an ordinary message. The person can keep writing, and+ the turn resumes under the same id.+- **Child sessions and a schedule's sessions:** the held text step reports+ `finishReason: "tool-calls"` on `message.completed`, so channels post only the final reply.++A question or sign-in from a task, such as an agent's question, parks the turn the same way: the+stream emits `input.requested` or `authorization.required`, then `turn.waiting`, and the turn+continues once the person answers or signs in.++In every session, `turn.completed` comes only when the turn really ends. The TypeScript client's+`send(...).result()` and the MCP channel's `agent_get` read past `turn.waiting` and report the+final reply rather than the text written before the wait. `result()` stops at `turn.waiting` only+while a question is pending, and returns `status: "waiting"` with it; `respond()` then reads the+same turn to its end. See [Aggregate a turn](/docs/guides/client/streaming#aggregate-a-turn). The+[Slack channel](/docs/channels/slack) also posts the text of a step whose only tool call is+`task_wait`, so people see what the agent is waiting on.++A steering message from the turn's own caller, one sent with `turnPolicy: "steer"`, the default,+ends a `task_wait` and aborts the `abortSignal` of any `execute` call the turn waits on, but it+never interrupts a task. The model reads the message and decides whether to keep each task,+correct an agent by calling it again with its `taskId`, or stop a task with `task_cancel`. A+`"queue"` message, or a message from another caller, waits for the turn to end.++## Cancel a task++- **`task_cancel`** stops one task's current work.+- **`session.cancel()`** cancels the turn, the `execute` calls it waits on, and every working task+ in the session.+- **A failed turn** cancels every working task.+- **The end of the session** ends every task.++Cancelled work never reports back. A `task` tool's task is then finished; its run waits up to 30+seconds for the body to finish unwinding, then ends as cancelled. A `serve` tool's task stays+available instead: its waiting calls settle as `cancelled`, the stretch's `abortSignal` aborts, and+the task becomes idle, as long as the body catches that abort and returns to `receive()`. For an+agent, that cancels the agent's current turn and keeps its conversation, so a later call with the+same `taskId` continues where it left off. A `serve` body that doesn't return to `receive()` within+30 seconds of a cancel ends, and the task finishes.++## Stream events++| Event | When | Data |+| --------------- | ------------------------------------------------------------------------ | --------------------------------------------------------------- |+| `task.started` | A call starts a task, or reaches a resumable task by its `taskId` | `taskId`, `callId`, `turnId`, and the tool `name` |+| `task.settled` | A reply, return, failure, or cancel settles one call | `taskId`, `callId`, `turnId`, `status`, and `output` or `error` |+| `agent.started` | A workflow run, including an agent tool's, opens a session with an agent | `callId`, `turnId`, `taskId`, `name`, `sessionId`, `streamPath` |+| `turn.waiting` | An open turn parks on its tasks, a `task_wait`, a question, or a sign-in | `turnId` and `sequence` |++`task.started` and `task.settled` come once each per call, and `(taskId, callId)` identifies the+call. Both carry that call's `turnId`, which for a resumable task's later call can be a later turn+than the one that started the task. `status` is `"completed"`, `"failed"`, or `"cancelled"`.+`agent.started` names the call and turn whose run opened the session, and its `taskId` is absent+when an `execute` call opened it. Results reach the model as a message in its history, not as a+stream event, so read outcomes from `task.settled`. An `input.requested`,+`authorization.required`, or `authorization.completed` event from a task's run carries its+`taskId`. Hooks subscribe to the same events. See+[Sessions, runs, and streaming](/docs/concepts/sessions-runs-and-streaming#task-events) and+[Follow a subagent](/docs/guides/client/streaming#follow-a-subagent).++## Ownership and limits++- **Ownership.** Tasks belong to the session's open turn, not to the caller that started them. A+ session has at most one open turn, so `task_wait`, `task_cancel`, task results, and the `[Tasks]`+ note cover every task in the session. Any later turn can continue an idle resumable task by its+ `taskId`, and that call runs with its own caller's auth. Only the turn's own caller steers it;+ anonymous callers share one identity.+- **Working tasks.** A session runs at most 32 working tasks at once. An idle resumable task doesn't+ count, and a call that makes it work again does.+- **No time limits.** Tasks have no timeout of their own. The session lifetime,+ `limits.sessionTimeoutMs` (30 days by default), bounds all work in a session. A body that needs a+ deadline races `sleep` against its work.++## Upgrade from background tasks++Tasks replace background tasks, `execution: "background"`, and `agentId` continuation. See+[Upgrade to Tasks](/docs/tools/tasks-upgrade) for every breaking change.diff --git a/docs/tools/workflows.mdx b/docs/tools/workflows.mdxindex 975427642..1cad77fad 100644--- a/docs/tools/workflows.mdx+++ b/docs/tools/workflows.mdx@@ -8,9 +8,14 @@ A workflow tool is a static tool defined with `defineWorkflowTool` from `eve/too`"use workflow"` as the first statement of its executor. Each call starts a durable Workflow run. Use one when a tool must wait for a person, webhook, or timer,delegate work to subagents, or coordinate retryable steps over a long period.-Every workflow tool call blocks its turn until the workflow settles, and the parent agent receives-the workflow's output as the tool result. While the body waits durably, the turn parks without-holding compute.+A workflow tool defines exactly one entry point, and the entry point decides how its calls run. A+call to an `execute(input, ctx)` tool blocks its turn until the workflow settles, and the parent+agent receives the workflow's output as the tool result. While the body waits durably, the turn+parks without holding compute. A `task(input, ctx)` tool runs each call as a+[task](#run-calls-as-tasks-task) instead: the model gets a receipt at once and the result arrives+later. A `serve(receive, ctx)` tool runs a [resumable task](#resumable-tasks-serve), which the+model can send more calls by its `taskId`. See [Tasks](/docs/tools/tasks) for choosing+between them and for what the model sees while tasks work.Workflow tools use the [Workflow SDK](https://workflow-sdk.dev): `"use workflow"`, `"use step"`, `createHook`,`createWebhook`, `sleep`, retries, and replay. eve provides `ctx.ask` for questions answered through@@ -66,19 +71,24 @@ or days later, the run resumes, deploys, and returns. The model sees one tool re### Rules-- Export `defineWorkflowTool({ ... })` as the default export. Its `execute` must be an async- function or async generator, written inline or referenced as a top-level `async function` in- the same module or an imported application module. Start the executor with `"use workflow"`- as its first statement. A missing- directive is a build error, even if another function in the module has one.+- Export `defineWorkflowTool({ ... })` as the default export. Define exactly one entry point,+ `execute`, `task`, or `serve`, written inline or referenced as a top-level `async function` in+ the same module or an imported application module. `execute` and `task` can be async functions+ or async generators; `serve` is an async function. Defining none, or more than one, throws at+ definition time. Start the entry point with `"use workflow"` as its+ first statement. A missing directive is a build error, even if another function in the module+ has one.- `"use step"` marks a top-level `async function` in the tool module, or any module it imports, as astep. Side effects, clocks, randomness, `process.env`, and Node.js APIs belong in steps; the bodyis replayed and must stay deterministic.- Import `createHook`, `createWebhook`, `sleep`, and `FatalError` from `workflow` in the body.`start`, `getRun`, and `resumeHook` from `workflow/api` belong in steps. Your app does not installthe SDK; for types, new projects list `eve/workflow-modules` in the tsconfig `types`.-- In the body, `ctx` has `session`, `callId`, `toolName`, `abortSignal`, `interruptSignal`, `agent`,- `agents`, and `ask`.+- In an `execute` or `task` body, `ctx` is a `WorkflowToolContext` with `session`, `callId`,+ `toolName`, `abortSignal`, `agent`, `agents`, and `ask`. A `serve` body gets a+ `WorkflowServeContext` with `session`, `toolName`,+ `agent`, `agents`, `ask`, and `reply`; each call it receives carries its own `callId` and+ `abortSignal`.A `"use step"` helper that receives `ctx` directly gets a restricted `WorkflowStepToolContext` with`session`, `callId`, `toolName`, `abortSignal`, `getToken`, and `requireAuth`. Read `ctx.agents`, call`ctx.agent()`, and call `ctx.ask()` in the workflow body; pass only the serializable values the step needs.@@ -86,7 +96,8 @@ or days later, the run resumes, deploys, and returns. The model sees one tool re- The tool's input must be a JSON object. Workflow bodies are for static tools under `agent/tools/`,not tools returned from `defineDynamic` resolvers.-`ctx.agent`, `ctx.agents`, and `ctx.ask` are available only on `WorkflowToolContext` in the workflow body.+`ctx.agent`, `ctx.agents`, and `ctx.ask` are available only on `WorkflowToolContext` and+`WorkflowServeContext` in the workflow body.Ordinary tools, channel handlers, schedule handlers, and workflow steps do not receive these methods. Typestep helpers with `WorkflowStepToolContext` from `eve/tools` when they need step-safe context capabilities.@@ -112,7 +123,9 @@ import { workflow } from "eve/tools/workflow";export default workflow({ maxSubagents: 20 });```-The model supplies an async function body through the tool's `js` input. Its only host capability is+The `workflow` tool runs each call as a [task](#run-calls-as-tasks-task), so the program's return+value reaches the model in a `task.result` message. The model supplies an async function body+through the tool's `js` input. Its only host capability is`ctx.agent(name, { message, outputSchema? })`, which sends the message to a new session with thatagent and resolves to its reply, or to the structured value when `outputSchema` is set. This can invoke subagents configured with `tool: false` or hidden by a same-named `disableTool()` file. Include those path-derived names in the workflow tool description or agent instructions when the model writes the program. For example:@@ -163,29 +176,37 @@ an agent catalog. Calls use the same target resolution, availability, and authorReplace `defineTool` with `defineWorkflowTool`, keep the executor's `"use workflow"` directive,and replace `agent(ctx, input)` and `ask(ctx, request)` with an agent session from[`ctx.agent(name)`](#delegate-work-ctxagent) and `ctx.ask(request)`. The `eve/workflow` entry point-has been removed. Import `WorkflowToolContext`, `AgentSession`, `ToolInputRequest`,-`ToolInputRequestOptions`, and `ToolInputResponse` from `eve/tools` when you need explicit types.+has been removed. Import `WorkflowToolContext`, `AgentSession`,+`ToolInputRequest`, `ToolInputRequestOptions`, and `ToolInputResponse` from `eve/tools` when you+need explicit types.-`ctx.ask` no longer accepts `dismissible`, and its `dismissed` status is now `cancelled`. To stop-asking once a new message arrives, pass `ctx.interruptSignal`:+`ctx.ask` no longer accepts `dismissible`, and its `dismissed` status is now `cancelled`. A+steering message withdraws a question an `execute` call asks, so drop the option. To keep a+question open while the conversation continues, ask it from a [`task`](#run-calls-as-tasks-task).```diff-const answer = await ctx.ask({ prompt, dismissible: true });-+const answer = await ctx.ask({ prompt }, { signal: ctx.interruptSignal });++const answer = await ctx.ask({ prompt });```+See [Upgrade to Tasks](/docs/tools/tasks-upgrade) for `task` replacing `execution: "background"`+and the other changes in this release.+## Wait for the result-A workflow tool call works like any other tool call from the model's point of view:+A call to an `execute` tool works like any other tool call from the model's point of view:- **Tool result:** the workflow's output after the body finishes.- **Parent turn:** waits for the call to settle, then continues with the result.- **Durable wait inside the body:** suspends the workflow while the tool call stays pending.- **Cancel:** cancelling the turn cancels the run.-- **Steering:** a new message fires the call's `ctx.interruptSignal`, and the body decides whether- to stop. See [Stop early for a new message](#stop-early-for-a-new-message-ctxinterruptsignal).+- **Steering:** a new message aborts the call's `ctx.abortSignal`, and the call settles with what+ the body returns. See [Stop early for a new message](#stop-early-for-a-new-message).++To keep the conversation going while a call works, [define `task` instead](#run-calls-as-tasks-task).-`defineWorkflowTool` does not accept an `execution` option. Passing one throws at definition time.+`defineWorkflowTool` does not accept an `execution` option. Passing one throws+`"execution" was replaced by task(). Define task(input, ctx) to run each call as a task.`### How suspension works@@ -214,6 +235,139 @@ the body returns.Promise or Node.js timer inside a step also does not create a durable workflow suspension; usethe workflow operations for waits that must survive a restart.+## Run calls as tasks: `task`++Define `task(input, ctx)` in place of `execute` when the conversation should continue while a call+works, such as a twenty-minute deploy or research the model may not need right away. An `execute`+tool holds the conversation until each call settles, however long it runs. A question, a sleep, or+an approval inside an `execute` call already parks durably and holds no compute, so waiting alone+doesn't need a task.++```ts title="agent/tools/deploy.ts"+import { defineWorkflowTool } from "eve/tools";+import { z } from "zod";+import { runDeploy } from "../lib/deploy";++export default defineWorkflowTool({+ description: "Deploy a service.",+ inputSchema: z.object({ service: z.string() }),+ async task({ service }, ctx) {+ "use workflow";+ return await runDeploy(service, ctx.abortSignal);+ },+});+```++A `task` body is written like an `execute` body, with the same `WorkflowToolContext`: returning+settles the call, a throw fails it, and an `async *task` generator can `yield` progress. A+steering message never aborts a task's `abortSignal`.++Each call is a task with its own id, `<tool>-<6 characters>`:++- **Receipt:** the call's tool result is a receipt, such as `Started task deploy-4hd8sa.`, and the+ model continues at once.+- **Result:** the body's return value or its error arrives later as a `<task_result>` block in a+ `task.result` message, which eve appends at the next step boundary. `toModelOutput` projects the+ result, not the receipt.++The model waits for results with `task_wait` and stops a task with `task_cancel`, and a turn can't+end while tasks are working. `task_cancel`, `session.cancel()`, a failed turn, and the+end of the session abort the call's `abortSignal`; the run waits up to 30 seconds for the body to+finish unwinding, then ends as cancelled. See [Tasks](/docs/tools/tasks) for what the model sees,+how held turns look on the stream, steering, events, and limits.++## Resumable tasks: `serve`++Define `serve(receive, ctx)` when the model should be able to send a running task more input, such+as a revision request. A `serve` body runs once per task and gets its calls from `receive()`+instead of taking an input:++```ts title="agent/tools/release-plan.ts"+import { defineWorkflowTool } from "eve/tools";+import { z } from "zod";+import { revise, type Plan } from "../lib/release-plan";++export default defineWorkflowTool({+ description: "Draft a release plan and revise it on request.",+ inputSchema: z.object({ request: z.string() }),+ async serve(receive, ctx) {+ "use workflow";+ let plan: Plan | undefined;+ for (;;) {+ const { input, abortSignal } = await receive(); // the first call, then each by taskId+ try {+ plan = await revise(plan, input.request, { signal: abortSignal });+ ctx.reply(plan); // a result; the task stays available+ } catch (error) {+ if (!abortSignal.aborted) throw error; // cancelled: wait for the next call+ }+ }+ },+});+```++A `serve` tool's calls are tasks, with the receipts and results+[described above](#run-calls-as-tasks-task) and the waiting, turn rule, ownership, and limit+described in [Tasks](/docs/tools/tasks). What differs:++- **`receive()`:** resolves with the next call, `{ input, callId, abortSignal }`, with `input`+ validated by `inputSchema`. The first `receive()` resolves at once with the call that started+ the task, without a step or a durable wait, and replays deterministically. After that, it+ resolves with each call made with the task's `taskId`, in arrival order. Calls that arrive while+ the body isn't waiting are kept. A pending `receive()` is shared, so calling it again returns the+ same promise. A call counts as received as soon as its promise resolves, even if that promise+ lost a `Promise.race`, and the next `ctx.reply()` settles it. If you race `receive()`, keep its+ promise until you read the call instead of calling `receive()` again.+- **`taskId` on the model input:** eve adds an optional `taskId` to the tool's model input and+ appends a sentence explaining it to the description. A call without `taskId` starts a new task,+ whose receipt names it: `Started task release-plan-7k2m9q. Call release-plan again with taskId+release-plan-7k2m9q to send it another message.` A call with `taskId` goes to that task and+ returns `Sent to task release-plan-7k2m9q.` The build fails if `inputSchema` declares its own+ `taskId`.+- **Unknown tasks:** the id must name an unfinished task this tool started; otherwise the call+ fails with `UNKNOWN_TASK`. The call can come from any caller in the session.+- **`ctx.session` and `ctx.agents` describe the call being served:** a later call can come in a+ later turn than the one that started the task. Its `task.started` and `task.settled` carry that+ call's `callId` and `turnId`, and so do the questions, sign-ins, and `agent.started` events the+ body causes while serving it. From the moment `receive()` resolves with a call, `ctx.session` is that call's view of+ the session, including in a step that receives `ctx`: `ctx.session.turn` is the call's turn, and+ `ctx.session.auth` is the auth the session admitted the call with, which may belong to a+ different caller than the one that started the task. `getToken`, `requireAuth`, and connections+ in a step use the current call's auth. `ctx.agents` lists the+ agents the current call may open, including dynamic agents selected in its turn.+- **Agents belong to the call that opened them:** a session the body opens with `ctx.agent` while+ serving a call is that call's child. Its `session.parent` names the call's `callId` and turn, and+ its trace continues from the call's tool span. The session keeps that lineage for its later+ messages, even after the task receives another call. Auth belongs to each message instead: a+ message carries the auth of the call being served when it's sent.+- **Results:** `ctx.reply(output)` settles every call received so far with `output`, all at once.+ Each settled call reports its own `task.settled`, and the model receives the reply once. The task+ then goes idle until its next call. A reply with+ no call left to settle is dropped, and `ctx.ask` throws while no call is waiting for a result.+ Returning settles the calls still waiting and ends the task; a throw fails them. `serve` is not+ a generator, so it can't `yield` progress.+- **Working and idle:** a resumable task is working while one of its calls has no result, and idle+ otherwise. An idle task doesn't hold the turn and doesn't count toward the limit of 32; a call+ that makes it work again does. The `[Tasks]` note lists the 10 most recently used idle tasks+ after the working ones, so the model can find them again.+- **One `abortSignal` per stretch of work:** a stretch starts when a call reaches an idle task and+ ends when a reply or a cancel settles its calls. Calls that arrive during a stretch share its+ signal, and the next stretch gets a new one, so a task can be cancelled any number of times.+- **Cancellation:** `task_cancel`, `session.cancel()`, and a failed turn settle the task's waiting+ calls as `cancelled` and abort the stretch's `abortSignal`. The run keeps waiting for more calls,+ so the task becomes idle and stays available. `task_cancel` on an idle task returns+ `{ status: "already_finished" }`. To stay available, a body must catch its stretch's abort and+ return to `receive()`, as the example does; an abort that escapes the body finishes the task. A+ body that ignores the signal keeps working and its reply is dropped, but a body that doesn't+ return to `receive()` within 30 seconds of a cancel ends, and the task finishes.+- **Finishing:** the task finishes when its body returns or throws, or when the session ends,+ which aborts the current stretch's signal and rejects a pending `receive()`.++Every [agent tool](/docs/subagents), including the built-in `agent` tool and remote agents, is a+`serve` tool that eve builds this way on public API: each task opens one session with+[`ctx.agent`](#delegate-work-ctxagent), sends each call's `message` with that call's `abortSignal`,+and replies with the final response of each agent turn.+## Authorize inside a stepPass `ctx` directly to a step helper and call `ctx.getToken(provider)` there. User-scoped providers@@ -318,8 +472,9 @@ if (answer === undefined) return { deployed: false, reason: "timed out" };- Ending the run, by returning, throwing, or cancellation, withdraws its pending requests.- Several requests may be outstanding at once.- A response never steers. A new human message that does not answer a pending request follows the- session's normal `turnPolicy`. A steering message also fires `ctx.interruptSignal`; pass it as- `signal` to withdraw the question when the conversation moves on, as `ask_question` does.+ session's normal `turnPolicy`. A steering message aborts the `abortSignal` of each `execute` call+ the turn waits on, which withdraws that call's questions, such as `ask_question`'s. A task's+ questions stay open.- An aborted `signal` asks the session to withdraw the question, and the session decides. If aperson's answer reached the session first, the ask resolves as `answered` even though the signalaborted, and the channel shows it answered. Branch on `status`, not on the signal.@@ -358,23 +513,30 @@ An unavailable name rejects the first `send`.| `signal` | Aborting it cancels the turn the message started or joined. The turn still reports, as cancelled. |A message sent while the session's turn is running joins that turn, and its response resolves with-that turn's result. A message sent while the session is idle starts the next turn, and the session-keeps its conversation between turns. `result()` returns the client's `MessageResult` fields:+that turn's result. If the turn ends before the agent reads the message, the message starts the next+turn instead, and its response resolves with that turn's result. The responses of earlier messages+that are still waiting resolve with the same result. A message sent while the session is idle starts+the next turn, and the session keeps its conversation between turns. `result()` returns the+client's `MessageResult` fields, plus `error` when the turn failed:| Field | Description || --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- || `data` | The structured value, when the turn requested `outputSchema`. || `message` | The agent's final reply text, when the turn did not request `outputSchema`. || `status` | `"waiting"` when the session waits for its next message, `"completed"` when the session ended with the turn, or `"failed"` when the turn failed. A cancelled turn is `"waiting"` with neither `data` nor `message`. |+| `error` | `{ message }` with the reason the turn failed, present only when `status` is `"failed"`. |Every `ctx.agent(name)` call returns a new session that only the workflow run can address. The modeldoes not see it; it sees what the tool returns. The session runs as the caller's principal with thecaller's capabilities, and a person answers its questions and sign-ins at the root session, as forany subagent. The session ends when the run finishes, which cancels any turn still running.-The parent stream announces each session with `agent.started`, which carries the tool call's-`callId` and `turnId`, the agent `name`, the child's `sessionId`, and a `streamPath`. Pass the event to-[`session.streamSubagent()`](/docs/guides/client/streaming#follow-a-subagent) to follow the child.+The parent stream announces each session with `agent.started`, which carries the `callId` and+`turnId` of the tool call the run is serving when it opens the session (for a `serve` task, the+latest call it received), the+`taskId` when the call runs as a task, the agent `name`, the child's `sessionId`, and a+`streamPath`. Pass the event to+[`session.agent(started).stream()`](/docs/guides/client/streaming#follow-a-subagent) to follow the child.### Route to a hidden subagent with Jev@@ -456,8 +618,8 @@ export default defineWorkflowTool({);const response = await ctx.agent(target).send(task, { signal: ctx.abortSignal });- const { message, status } = await response.result();- if (status === "failed") throw new Error(`${target} could not complete the task.`);+ const { error, message, status } = await response.result();+ if (status === "failed") throw new Error(`${target} failed: ${error?.message}`);return message ?? null;},});@@ -465,7 +627,7 @@ export default defineWorkflowTool({The evaluation runs in a step so workflow replay records its result instead of making the routing request again. The parent model receives `agent-router`, but not `researcher` or `operator`. Jev returns the typed `"researcher" | "operator"` choice, and the selected subagent's reply becomes the `agent-router` tool result.-`ctx.agents` is a replay-stable metadata snapshot taken when the workflow starts. In a top-level root workflow, `ctx.agents.agent` always represents the root-copy target and carries the root's authored `description` when provided. The snapshot also includes declared agents hidden from the parent model with `tool: false` or `disableTool()`, but exposes no model definitions, credentials, or callbacks. A delegated root copy omits `agent`, so `agentRouter()` cannot select another root copy recursively. Invocation still checks each target's availability through `ctx.agent()`.+`ctx.agents` is a replay-stable metadata snapshot taken when the session admits the call. In a `serve` task, it follows the call being served. In a top-level root workflow, `ctx.agents.agent` always represents the root-copy target and carries the root's authored `description` when provided. The snapshot also includes declared agents hidden from the parent model with `tool: false` or `disableTool()`, but exposes no model definitions, credentials, or callbacks. A delegated root copy omits `agent`, so `agentRouter()` cannot select another root copy recursively. Invocation still checks each target's availability through `ctx.agent()`.#### Route across every agent target@@ -477,7 +639,8 @@ import { agentRouter } from "eve/tools/agent-router";export default agentRouter();```-Its input is `{ message: string }`. `agentRouter()` ignores entries without a non-empty description. With two or more described targets, it sends the message and effective descriptions to Jev, then sends the message to a new session with the selected agent through `ctx.agent()` and returns its reply. It invokes a sole target without evaluation. In a top-level root session, the candidates include the root-copy `agent`; delegated root copies and declared subagent contexts include only their declared targets.+Its input is `{ message: string }`. `agentRouter()` ignores entries without a non-empty description. With two or more described targets, it sends the message and effective descriptions to Jev, then sends the message to a new session with the selected agent through `ctx.agent()` and returns its reply. It invokes a sole target without evaluation. Each call+runs as a [task](#run-calls-as-tasks-task), so the reply reaches the model as the task's result. In a top-level root session, the candidates include the root-copy `agent`; delegated root copies and declared subagent contexts include only their declared targets.When an authored tool accepts a JSON Schema supplied by the model, represent that input with a permissive object such as `z.looseObject({})`. Avoid `z.record(z.string(), z.json())`: its generated JSON Schema uses `propertyNames`, which OpenAI does not support. Validate the supplied value at the point where your tool consumes it.@@ -523,10 +686,11 @@ Use [`ctx.ask`](#ask-a-human-ctxask) when the workflow needs a human answer. See## Cancel and clean up: `ctx.abortSignal`-`ctx.abortSignal` aborts when the run is cancelled by explicit turn cancellation. It is durable — it-survives replay, and a step that-receives it observes the abort. Pass it into the steps that should stop, and clean up in-`try/finally`:+`ctx.abortSignal` aborts when the call is cancelled: by `session.cancel()`, or, for a task, by+`task_cancel`, a failed turn, or the end of the session. A steering message also aborts it for an+`execute` call; see [Stop early for a new message](#stop-early-for-a-new-message). It is durable —+it survives replay, and a step that receives it observes the abort. Pass it into the steps that+should stop, and clean up in `try/finally`:```tsasync execute({ projectId }, ctx) {@@ -540,53 +704,58 @@ async execute({ projectId }, ctx) {}```-After the signal fires, the run waits up to 30 seconds for the body to finish unwinding, then ends-as cancelled whether or not it did. A body parked on a hook or a `sleep` does not observe the signal;-it is abandoned when the grace period ends. Steps that received the signal are how you clean up-first.+After a cancel aborts the signal, the run waits up to 30 seconds for the body to finish unwinding,+then ends as cancelled whether or not it did. A body parked on a hook or a `sleep` does not observe+the signal; it is abandoned when the grace period ends. Steps that received the signal are how you+clean up first.The caller waits up to 35 seconds for a cooperatively cancelled run to settle before forcing itto stop. This includes time for the run to publish its outcome after body cleanup.-## Stop early for a new message: `ctx.interruptSignal`+## Stop early for a new message-`ctx.interruptSignal` aborts when a steering message arrives while the turn waits on the call. A+A steering message aborts the `ctx.abortSignal` of each `execute` call the turn waits on. Asteering message is one sent with `turnPolicy: "steer"`, the default, that does not answer a pending-question; a message that answers a question never interrupts. The signal aborts once, on the first-such message. Later messages wait for the call like any other.+question; a message that answers a question never stops a call. Steering never touches a+[task](#run-calls-as-tasks-task).++Steering does not cancel the call or end the turn. The call settles with what the body returns, and+the model reads the new message after the step's workflow tool calls settle:-The signal only informs the body. Steering does not cancel the call or end the turn, and the model-reads the new message after the step's workflow tool calls settle. A body that ignores the signal-keeps going: a deploy waiting on an approval survives unrelated messages. A body that should stop-races the signal or passes it on. The provided `sleep` tool races it against the timer:+- **Questions:** a pending `ctx.ask` question is withdrawn and resolves as `cancelled`, unless a+ person's answer reached the session first.+- **Rejections:** a body that rejects after the abort, such as one whose step received the signal,+ settles as `{ interrupted: true }` instead of failing.+- **No grace period:** a body that doesn't observe the signal, such as one parked on a hook or a+ `sleep`, keeps the turn waiting until it finishes.++The body doesn't need to tell a steering message from a cancel: in both cases, stop and return what+you have. After a cancel, eve discards the result. The provided `sleep` tool races its timer+against the signal:```tsimport { sleep } from "workflow";async execute(input, ctx) {"use workflow";- const interrupted = new Promise<"interrupted">((resolve) =>- ctx.interruptSignal.addEventListener("abort", () => resolve("interrupted"), { once: true }),+ const stopped = new Promise<"stopped">((resolve) =>+ ctx.abortSignal.addEventListener("abort", () => resolve("stopped"), { once: true }),);const elapsed = sleep(input.seconds * 1_000).then(() => "elapsed" as const);- const woke = await Promise.race([elapsed, interrupted]);+ const woke = await Promise.race([elapsed, stopped]);return woke === "elapsed" ? { waitedSeconds: input.seconds } : { interrupted: true };}```-Pass the signal to `ctx.ask` as `signal` to withdraw a question once the conversation moves on. The-provided `ask_question` tool does this:--```ts-const answer = await ctx.ask(question, { signal: ctx.interruptSignal });-```+To keep a question or long work going while the conversation continues, define+[`task`](#run-calls-as-tasks-task) instead of `execute`.## Workflow tool examples### Approve with a deadline and an escalation```ts-async execute({ service }, ctx) {+async task({ service }, ctx) {"use workflow";const plan = await planDeploy(service);const pending = ctx.ask({ prompt: `Deploy ${service}?`, display: "confirmation", options: APPROVE_OR_CANCEL });@@ -605,8 +774,9 @@ async execute({ service }, ctx) {}```-One request stays on the channel the whole time. `sleep` is the deadline, `pageOnCall` is a step,-and returning withdraws the request.+One request stays on the channel the whole time. As a `task`, the call doesn't hold the+conversation, and a steering message doesn't withdraw the request. `sleep` is the deadline,+`pageOnCall` is a step, and returning withdraws the request.### Wait for an external system to call back@@ -674,9 +844,10 @@ and the agent receives the outcome as the tool result.One call, one result. A workflow tool call resolves once, with the return value, the error, or acancellation.-While a workflow tool runs, the turn is parked. A `queue` message waits for it. A `steer` message-that answers no pending question fires the call's `ctx.interruptSignal` and reaches the model once-the call settles; it never cancels the run. Input responses never steer.+While an `execute` call runs, the turn is parked. A `queue` message waits for it. A `steer` message+that answers no pending question aborts the call's `ctx.abortSignal` and reaches the model once the+call settles; it never cancels the run. Input responses never steer. A task doesn't park the+turn, and steering never touches it.Errors follow the SDK. A thrown error in a step retries per the step's policy; `FatalError` doesnot. An error that escapes the body fails the tool invocation.@@ -686,7 +857,8 @@ run, its retry starts another run, and both may execute. The parent tracks the rsuccessful dispatch attempt. Use an application idempotency key for side effects that must happenonly once.-The workflow id derives from the executor's module path and function name. Inline executors use-the tool module and the name `execute`; imported executors use their declaring module and name.+The workflow id derives from the entry point's module path and function name. Inline entry points+use the tool module and the name `execute`, `task`, or `serve`; imported ones use their declaring module and+name.Renaming or moving that function creates a new workflow. Runs in flight finish on the deployment that started them; a run thatresumes on a deployment without its tool fails with an error naming the missing workflow.diff --git a/e2e/README.md b/e2e/README.mdindex d62b1d879..a8b24d5be 100644--- a/e2e/README.md+++ b/e2e/README.md@@ -153,6 +153,12 @@ checks generated tools through real calls in fresh sessions and restores sourceafter retiring the parent and child sessions. Routing-only self-modificationcoverage stays in `agent-subagents`.+`agent-tasks` is the real-model gate for how models plan around tasks: waiting+for a needed result, fanning out, keeping or correcting tasks after a new+message, and ordering a side effect after the result it depends on. Every eval+in it is tagged `real-model`. Deterministic task coverage lives with the+surfaces it exercises, in `agent-workflow-tools` and `agent-subagents`.+E2E fixtures live under `e2e/fixtures/*`. Fixture discovery also accepts`apps/fixtures/*` apps with an `evals/` directory, but shared development appsshould stay out of the e2e matrix unless they intentionally own evals.diff --git a/e2e/fixtures/agent-cancellation/agent/agent.ts b/e2e/fixtures/agent-cancellation/agent/agent.tsindex 3d1c26041..1bdf06522 100644--- a/e2e/fixtures/agent-cancellation/agent/agent.ts+++ b/e2e/fixtures/agent-cancellation/agent/agent.ts@@ -3,9 +3,15 @@ import { defineAgent } from "eve";import type { MockModelRequest, MockModelResponse } from "eve/evals";const HITL_REQUEST = "GENERATED-PROGRAM-CHILD-HITL";+const AGENT_TASK_CANCEL = "AGENT-TASK-CANCEL";+const SLEEPER_FOLLOW_UP = "SLEEPER-FOLLOW-UP";+const CANCELLED_TURN_FOLLOW_UP = "CANCELLATION-SUBAGENT-FOLLOW-UP-OK";+/** How a call the cancelled turn stopped reads in history. */+const CANCELLED_CALL_TEXT = "cancelled before this call finished";async function respond(request: MockModelRequest): Promise<MockModelResponse | string> {const message = request.lastUserMessage ?? "";+ if (message.includes(AGENT_TASK_CANCEL)) return cancelAndContinueSleeper(request);if (message.includes("Alice is preparing the 2026 report.")) {await new Promise((resolve) => setTimeout(resolve, 30_000));return "Original 2026 report";@@ -46,11 +52,14 @@ async function respond(request: MockModelRequest): Promise<MockModelResponse | s}if (message.includes("call the sleeper subagent")) {const hitl = message.includes(HITL_REQUEST);- const hitlResult = request.toolResults.find((entry) => entry.id === "hitl-sleeper");- if (hitlResult !== undefined) {- return typeof hitlResult.output === "string"- ? hitlResult.output- : JSON.stringify(hitlResult.output);+ // The workflow tool runs as a task: its call returns a receipt, and the+ // program's result arrives in a <task_result> message after task_wait.+ const taskResult = request.messages.find(+ (entry) => entry.role === "user" && entry.text.startsWith("<task_result"),+ );+ if (taskResult !== undefined) return taskResult.text;+ if (request.toolResults.some((entry) => entry.name === "workflow")) {+ return { toolCalls: [{ id: "wait-for-sleeper", input: {}, name: "task_wait" }] };}return {toolCalls: [@@ -66,9 +75,54 @@ async function respond(request: MockModelRequest): Promise<MockModelResponse | s],};}+ if (message.includes(CANCELLED_TURN_FOLLOW_UP)) return replyAfterCancelledTurn(request);return `Mock reply: ${message}`;}+/**+ * Answers the follow-up to a cancelled sleeper turn only when history keeps+ * what that turn did: the sleeper call, and the calls the cancel stopped+ * answered as cancelled. Without them the sleeper request would look unanswered.+ */+function replyAfterCancelledTurn(request: MockModelRequest): string {+ const calledSleeper = request.toolResults.some((entry) => entry.id === "cancel-sleeper");+ const cancelledCall = request.toolResults.some((entry) =>+ String(entry.output).includes(CANCELLED_CALL_TEXT),+ );+ return calledSleeper && cancelledCall+ ? CANCELLED_TURN_FOLLOW_UP+ : "The cancelled turn's calls are missing from history.";+}++/**+ * Calls the sleeper agent, waits briefly for it to reach its tool, cancels+ * the task, then continues it by taskId and returns its follow-up result.+ */+function cancelAndContinueSleeper(request: MockModelRequest): MockModelResponse | string {+ const calls = (name: string) => request.toolResults.filter((entry) => entry.name === name);+ const [started, continued] = calls("sleeper");+ if (started === undefined) {+ return {+ toolCalls: [{ input: { message: "Please wait for cancellation." }, name: "sleeper" }],+ };+ }+ const taskId = /Started task (\S+)\./u.exec(String(started.output))?.[1];+ if (taskId === undefined) throw new Error("The sleeper call returned no task receipt.");+ if (calls("task_wait").length === 0) {+ return { toolCalls: [{ input: { timeout: 2_000 }, name: "task_wait" }] };+ }+ if (calls("task_cancel").length === 0) {+ return { toolCalls: [{ input: { taskId }, name: "task_cancel" }] };+ }+ if (continued === undefined) {+ return { toolCalls: [{ input: { message: SLEEPER_FOLLOW_UP, taskId }, name: "sleeper" }] };+ }+ const result = [...request.messages]+ .reverse()+ .find((entry) => entry.role === "user" && entry.text.startsWith("<task_result"));+ return result?.text ?? { toolCalls: [{ input: {}, name: "task_wait" }] };+}+const base = e2eAgentConfig({ mock: respond });export default defineAgent({diff --git a/e2e/fixtures/agent-cancellation/agent/subagents/sleeper/agent.ts b/e2e/fixtures/agent-cancellation/agent/subagents/sleeper/agent.tsindex 1371eda45..c33766c06 100644--- a/e2e/fixtures/agent-cancellation/agent/subagents/sleeper/agent.ts+++ b/e2e/fixtures/agent-cancellation/agent/subagents/sleeper/agent.ts@@ -6,7 +6,13 @@ const HITL_REQUEST = "GENERATED-PROGRAM-CHILD-HITL";export default defineAgent({description: "Waits until its delegated turn is cancelled.",...e2eSubagentConfig({- mock: ({ lastUserMessage, toolResults }) => {+ mock: ({ lastUserMessage, toolResults, userMessages }) => {+ // A continued task reaches the same session, so the first message is still in it.+ if (lastUserMessage?.includes("SLEEPER-FOLLOW-UP") === true) {+ return `SLEEPER-REMEMBERS=${String(+ userMessages.some((entry) => entry.includes("Please wait for cancellation.")),+ )}`;+ }if (lastUserMessage?.includes(HITL_REQUEST) === true) {const answer = toolResults.find((result) => result.id === "child-question");return answer === undefineddiff --git a/e2e/fixtures/agent-cancellation/agent/subagents/sleeper/instructions.md b/e2e/fixtures/agent-cancellation/agent/subagents/sleeper/instructions.mdindex 2a4996784..3f07f0566 100644--- a/e2e/fixtures/agent-cancellation/agent/subagents/sleeper/instructions.md+++ b/e2e/fixtures/agent-cancellation/agent/subagents/sleeper/instructions.md@@ -5,5 +5,6 @@ You are a cancellation test sleeper.# Rules- If the message contains `GENERATED-PROGRAM-CHILD-HITL`, call `ask_question` exactly once with the question `What marker should the child return?`, then reply with `CHILD_HITL_RESULT=` followed by the answer.+- If the message contains `SLEEPER-FOLLOW-UP`, do not call any tool. Reply with exactly `SLEEPER-REMEMBERS=true` if an earlier message in this conversation asked you to wait for cancellation, otherwise `SLEEPER-REMEMBERS=false`.- Otherwise, call `wait-for-cancellation` exactly once, immediately, with no preamble.- Do not call any other tool.diff --git a/e2e/fixtures/agent-cancellation/evals/cancellation/cancel-agent-task.eval.ts b/e2e/fixtures/agent-cancellation/evals/cancellation/cancel-agent-task.eval.tsnew file mode 100644index 000000000..707f8a6e4--- /dev/null+++ b/e2e/fixtures/agent-cancellation/evals/cancellation/cancel-agent-task.eval.ts@@ -0,0 +1,33 @@+import { defineEval } from "eve/evals";++export default defineEval({+ description:+ "Cancelling an agent task cancels the agent's current turn; continuing it by taskId reaches the same conversation.",+ timeoutMs: 120_000,++ async test(t) {+ const turn = await t.send(+ [+ "Alice is checking that a paused helper keeps its notes. AGENT-TASK-CANCEL",+ 'Ask the sleeper agent with the message "Please wait for cancellation."',+ "Once it is waiting, stop that sleeper task with task_cancel.",+ 'Then continue the same sleeper task with its taskId and the message "SLEEPER-FOLLOW-UP", and report its reply.',+ ].join("\n"),+ );+ turn.expectOk();++ const started = turn.events.find((event) => event.type === "agent.started");+ if (started?.type !== "agent.started") throw new Error("The sleeper agent never started.");+ const cancelledTurn = await t.target.watchTurn(started.data.sessionId).result();+ cancelledTurn.event("turn.cancelled", { count: 1 });++ t.event("agent.started", { count: 1, data: { name: "sleeper" } });+ t.event("task.settled", { count: 1, data: { status: "cancelled" } });+ // The continued sleeper's own reply, not the parent's retelling of it.+ t.event("task.settled", {+ count: 1,+ data: { output: /SLEEPER-REMEMBERS=true/u, status: "completed" },+ });+ t.notEvent("turn.failed");+ },+});diff --git a/e2e/fixtures/agent-cancellation/evals/cancellation/cancel-subagent.eval.ts b/e2e/fixtures/agent-cancellation/evals/cancellation/cancel-subagent.eval.tsindex 153fd258d..b4180ddcc 100644--- a/e2e/fixtures/agent-cancellation/evals/cancellation/cancel-subagent.eval.ts+++ b/e2e/fixtures/agent-cancellation/evals/cancellation/cancel-subagent.eval.ts@@ -55,5 +55,6 @@ export default defineEval({// The eval watches both the parent and the sleeper session; each one's turn is cancelled once.t.event("turn.cancelled", { count: 2 });t.event("agent.started", { count: 1, data: { name: "sleeper" } });+ t.event("task.settled", { count: 1, data: { status: "cancelled" } });},});diff --git a/e2e/fixtures/agent-cancellation/evals/cancellation/generated-program-child-hitl.eval.ts b/e2e/fixtures/agent-cancellation/evals/cancellation/generated-program-child-hitl.eval.tsindex def2d1a37..c94086410 100644--- a/e2e/fixtures/agent-cancellation/evals/cancellation/generated-program-child-hitl.eval.ts+++ b/e2e/fixtures/agent-cancellation/evals/cancellation/generated-program-child-hitl.eval.ts@@ -19,9 +19,11 @@ export default defineEval({resumed.expectOk();t.succeeded();- t.calledTool("workflow", {+ t.calledTool("workflow", { count: 1 });+ // The workflow tool runs as a task: its result settles the task, not the call.+ t.event("task.settled", {count: 1,- output: /CHILD_HITL_RESULT=.*GENERATED-HITL-MARKER/su,+ data: { output: /CHILD_HITL_RESULT=.*GENERATED-HITL-MARKER/su, status: "completed" },});t.event("agent.started", { count: 1, data: { name: "sleeper" } });t.messageIncludes("CHILD_HITL_RESULT=");diff --git a/e2e/fixtures/agent-compaction-regressions/agent/agent.ts b/e2e/fixtures/agent-compaction-regressions/agent/agent.tsindex 49ba0277a..9042c53a0 100644--- a/e2e/fixtures/agent-compaction-regressions/agent/agent.ts+++ b/e2e/fixtures/agent-compaction-regressions/agent/agent.ts@@ -16,9 +16,10 @@ import { assistantHasReport } from "../report-evidence";import { HANDOFF_REFERENCE, REVIEW_REFERENCE } from "../release-reports";const TEST_CONTEXT_WINDOW_TOKENS = 32_000;-// The compiled fixture's instructions and 9 advertised tools occupy ~1,773-// tokens. Reserve them in addition to the summarizer's history budget.-const TEST_REQUEST_ENVELOPE_TOKENS = 1_773;+// The compiled fixture's instructions, task system block, and 11 advertised+// tools occupy ~2,113 tokens. Reserve them in addition to the summarizer's+// history budget.+const TEST_REQUEST_ENVELOPE_TOKENS = 2_113;// Fit the capped file-output exchange, while forcing the larger review and// handoff reports into the assistant checkpoint consumed by the script.const TEST_HISTORY_BUDGET_TOKENS = 900;diff --git a/e2e/fixtures/agent-prompt-cache/evals/parallel-review.eval.ts b/e2e/fixtures/agent-prompt-cache/evals/parallel-review.eval.tsindex f158bbe5a..60fd4a0fb 100644--- a/e2e/fixtures/agent-prompt-cache/evals/parallel-review.eval.ts+++ b/e2e/fixtures/agent-prompt-cache/evals/parallel-review.eval.ts@@ -60,10 +60,10 @@ function expectReviewSummary(turn: EveEvalTurn) {}async function expectParallelReviews(t: EveEvalContext, turn: EveEvalTurn) {- const calls = turn.events- .filter((event) => event.type === "subagent.called")+ const sessions = turn.events+ .filter((event) => event.type === "agent.started").filter(({ data }) => data.name === "reviewer");- const childIds = calls.map(({ data }) => data.childSessionId);+ const childIds = sessions.map(({ data }) => data.sessionId);assert.equal(childIds.length, 5, "no repeated delegation");assert.equal(new Set(childIds).size, 5, "five distinct child sessions");const children = await Promise.all(childIds.map((id) => t.target.watchTurn(id).result()));diff --git a/e2e/fixtures/agent-router/agent/agent.ts b/e2e/fixtures/agent-router/agent/agent.tsindex 318565de9..775472e01 100644--- a/e2e/fixtures/agent-router/agent/agent.ts+++ b/e2e/fixtures/agent-router/agent/agent.ts@@ -21,17 +21,18 @@ export default defineAgent({}return "AGENT-ROUTER-ROOT-COPY-OK";}- const result = request.toolResults.find((entry) => entry.name === "agent");- return result === undefined- ? {- toolCalls: [- {- name: "agent",- input: { message: "Return the root-copy marker." },- },- ],- }- : JSON.stringify(result.output);+ // agentRouter() runs each call as a task: a receipt now, the result in a+ // later <task_result> message once task_wait returns.+ const taskResult = request.messages.find(+ (message) => message.role === "user" && message.text.startsWith("<task_result"),+ );+ if (taskResult !== undefined) return taskResult.text;+ if (request.toolResults.some((entry) => entry.name === "agent")) {+ return { toolCalls: [{ name: "task_wait", input: {} }] };+ }+ return {+ toolCalls: [{ name: "agent", input: { message: "Return the root-copy marker." } }],+ };},}),modelContextWindowTokens: 1_000_000,diff --git a/e2e/fixtures/agent-router/evals/agent-router.eval.ts b/e2e/fixtures/agent-router/evals/agent-router.eval.tsindex eb8246f59..2fb37c1a8 100644--- a/e2e/fixtures/agent-router/evals/agent-router.eval.ts+++ b/e2e/fixtures/agent-router/evals/agent-router.eval.ts@@ -1,13 +1,17 @@import { defineEval } from "eve/evals";export default defineEval({- description: "agentRouter invokes the root-copy agent when it is the sole available target.",+ description:+ "agentRouter runs as a task that invokes the root-copy agent, and task_wait delivers its result.",async test(t) {const turn = await t.send("Route this task.");turn.expectOk();turn.messageIncludes("AGENT-ROUTER-ROOT-COPY-OK");turn.calledTool("agent", { count: 1 });+ turn.calledTool("task_wait", { count: 1 });+ turn.event("task.started", { count: 1, data: { kind: "tool", name: "agent" } });+ turn.event("task.settled", { count: 1, data: { status: "completed" } });turn.event("agent.started", { count: 1, data: { name: "agent" } });t.succeeded();t.noFailedActions();diff --git a/e2e/fixtures/agent-self-modification/evals/self-modification/harness.ts b/e2e/fixtures/agent-self-modification/evals/self-modification/harness.tsindex ac717ea7c..1a716b50f 100644--- a/e2e/fixtures/agent-self-modification/evals/self-modification/harness.ts+++ b/e2e/fixtures/agent-self-modification/evals/self-modification/harness.ts@@ -160,31 +160,32 @@ export class SelfModificationHarness {this.#turns.add(liveParent);const parent = await liveParent.result();parent.expectOk();- // The delegation blocks the turn, so it stays pending while the child waits on an approval- // proxied into this turn. Turn status cannot tell: every idle turn ends on session.waiting.- const callStatus = parent.inputRequests.length > 0 ? "pending" : "completed";- const call = parent.requireToolCall(SELF_MODIFICATION_AGENT, { status: callStatus });- const agentId = typeof call.input.agentId === "string" ? call.input.agentId : undefined;- const message = agentId === undefined ? undefined : call.input.message;- if (agentId !== undefined && (typeof message !== "string" || message.length === 0))+ const call = parent.requireToolCall(SELF_MODIFICATION_AGENT);+ const taskId = typeof call.input.taskId === "string" ? call.input.taskId : undefined;+ const message = taskId === undefined ? undefined : call.input.message;+ if (taskId !== undefined && (typeof message !== "string" || message.length === 0))throw new Error("Self-modification continuation omitted its message.");- const called = [...this.#turns]+ const sessionEvents = [...this.#turns].filter((turn) => turn.sessionId === parent.sessionId)- .flatMap((turn) => turn.events)- .find(- (event) =>- event.type === "subagent.called" &&- event.data.name === SELF_MODIFICATION_AGENT &&- (agentId === undefined- ? liveParent.events.includes(event)- : event.data.agentId === agentId),- );- if (called?.type !== "subagent.called") {+ .flatMap((turn) => turn.events);+ const task = sessionEvents.find(+ (event) =>+ event.type === "task.started" &&+ event.data.name === SELF_MODIFICATION_AGENT &&+ (taskId === undefined ? liveParent.events.includes(event) : event.data.taskId === taskId),+ );+ const started = sessionEvents.find(+ (event) =>+ event.type === "agent.started" &&+ task?.type === "task.started" &&+ event.data.taskId === task.data.taskId,+ );+ if (started?.type !== "agent.started") {throw new Error("Self-modification parent turn did not start its child agent.");}const child = await this.#readChild(- called.data.childSessionId,+ started.data.sessionId,typeof message === "string" ? message : undefined,);this.#t.calledSubagent(SELF_MODIFICATION_AGENT);@@ -302,7 +303,7 @@ export class SelfModificationHarness {for (const turn of this.#turns) {sessionIds.add(turn.sessionId);for (const event of turn.events) {- if (event.type === "subagent.called") sessionIds.add(event.data.childSessionId);+ if (event.type === "agent.started") sessionIds.add(event.data.sessionId);}}const signal = AbortSignal.timeout(CLEANUP_TIMEOUT_MS);diff --git a/e2e/fixtures/agent-self-modification/evals/self-modification/offer-repair.eval.ts b/e2e/fixtures/agent-self-modification/evals/self-modification/offer-repair.eval.tsindex bf228cce0..d7b023e09 100644--- a/e2e/fixtures/agent-self-modification/evals/self-modification/offer-repair.eval.ts+++ b/e2e/fixtures/agent-self-modification/evals/self-modification/offer-repair.eval.ts@@ -65,7 +65,7 @@ export default defineEval({authored.session,"That recommendation is wrong. Incoming stock should count toward the target, so it should recommend 50 units, not 80. What should we do?",);- offered.notEvent("subagent.called", { data: { name: "self-modification__agent" } });+ offered.notEvent("task.started", { data: { name: "self-modification__agent" } });t.judge("The response offers to delegate a repair of the incorrect tool and asks the user to confirm before starting it.",{ on: offered.message },diff --git a/e2e/fixtures/agent-self-modification/test/harness.scenario.test.mjs b/e2e/fixtures/agent-self-modification/test/harness.scenario.test.mjsindex 3fa79b14a..3d0ea11e1 100644--- a/e2e/fixtures/agent-self-modification/test/harness.scenario.test.mjs+++ b/e2e/fixtures/agent-self-modification/test/harness.scenario.test.mjs@@ -46,12 +46,9 @@ function context(target, signal = new AbortController().signal) {};}-/**- * Mirrors a recorded eval turn: idle turns end on session.waiting, and a blocking delegation is- * still pending only when its child's input request was proxied into the turn.- */+/** Mirrors a recorded eval turn: idle turns end on session.waiting. */function completedTurn(sessionId, events = [], { input = {}, inputRequests = [] } = {}) {- const call = { input, status: inputRequests.length > 0 ? "pending" : "completed" };+ const call = { input, status: "completed" };return {sessionId,events,@@ -66,6 +63,18 @@ function completedTurn(sessionId, events = [], { input = {}, inputRequests = []};}+/** The parent events of an agent call that starts task `taskId` and opens `childSessionId`. */+function agentCallEvents(childSessionId, taskId = "agent-1") {+ const name = "self-modification__agent";+ return [+ { type: "task.started", data: { callId: `call-${taskId}`, name, taskId, turnId: "turn-1" } },+ {+ type: "agent.started",+ data: { callId: `call-${taskId}`, name, sessionId: childSessionId, taskId, turnId: "turn-1" },+ },+ ];+}+function liveTurn(sessionId, events = []) {return {sessionId,@@ -138,11 +147,8 @@ test("close restores registry installer project files", async () => {test("close retires every session before restoring the complete source tree", async () => {const child = liveTurn("child");const verification = liveTurn("verification");- const parentEvent = {- type: "subagent.called",- data: { name: "self-modification__agent", childSessionId: child.sessionId },- };- const parent = liveTurn("parent", [parentEvent]);+ const parentEvents = agentCallEvents(child.sessionId);+ const parent = liveTurn("parent", parentEvents);await withHarness(async ({ harness, root, calls, target, close }) => {@@ -150,9 +156,8 @@ test("close retires every session before restoring the complete source tree", asparent.result = async () => {await new Promise((resolve) => setTimeout(resolve, 10));parentFinished = true;- return completedTurn(parent.sessionId, [parentEvent]);+ return completedTurn(parent.sessionId, parentEvents);};- parent.waitForEvent = async () => ({ data: parentEvent.data });target.watchTurn = () => {assert.equal(parentFinished, true);return child;@@ -219,19 +224,13 @@ test("one reset failure still retires other sessions and leaves unsafe source unif (path.includes("bad/reset")) return new Response("no", { status: 500 });return response({ revision: "revision" });};- const parentEvent = {- type: "subagent.called",- data: { name: "self-modification__agent", childSessionId: "bad" },- };+ const parentEvents = agentCallEvents("bad");// The public request path is used to populate both tracked sessions.const liveParent = {sessionId: "parent",- events: [parentEvent],- async waitForEvent() {- return { data: parentEvent.data };- },+ events: parentEvents,async result() {- return completedTurn("parent", [parentEvent]);+ return completedTurn("parent", parentEvents);},};target.watchTurn = () => ({@@ -397,71 +396,50 @@ test("apply rejects a rebuild response without a runtime revision", async () =>});});-test("request accepts a pending delegation while the parent turn waits on a proxied approval", async () => {- const called = {- type: "subagent.called",- data: { name: "self-modification__agent", childSessionId: "child" },+test("request follows a continued agent task past stale child turns", async () => {+ const initialParent = liveTurn("parent", agentCallEvents("child"));+ const initialChild = liveTurn("child");+ initialChild.session = { state: { streamIndex: 10 } };+ const message = "Repair the existing inventory tool.";+ const continuation = {+ type: "task.started",+ data: { callId: "call-2", name: "self-modification__agent", taskId: "agent-1" },};- const parent = liveTurn("parent", [called]);- parent.result = async () =>- completedTurn("parent", [called], { inputRequests: [{ requestId: "registry-approval" }] });- await withHarness(async ({ harness, target }) => {- target.watchTurn = () => liveTurn("child");- const run = await harness.request("Add browser automation.", { start: async () => parent });- assert.equal(run.child.sessionId, "child");+ const repairParent = liveTurn("parent", [continuation]);+ repairParent.result = async () =>+ completedTurn("parent", [continuation], { input: { taskId: "agent-1", message } });+ const diagnostic = liveTurn("child", [+ { type: "message.received", data: { message: "Diagnose only." } },+ ]);+ diagnostic.session = { state: { streamIndex: 20 } };+ diagnostic.result = async () => ({+ ...completedTurn("child", diagnostic.events),+ status: "waiting",});-});--for (const emitsCalled of [false, true]) {- test(`request follows a reused agent past stale turns (new called event: ${emitsCalled})`, async () => {- const called = {- type: "subagent.called",- data: { name: "self-modification__agent", agentId: "agent-1", childSessionId: "child" },- };- const initialParent = liveTurn("parent", [called]);- initialParent.waitForEvent = async () => called;- const initialChild = liveTurn("child");- initialChild.session = { state: { streamIndex: 10 } };- const message = "Repair the existing inventory tool.";- const repairParent = liveTurn("parent", emitsCalled ? [called] : []);- repairParent.waitForEvent = async () => {- throw new Error("Session reached session.waiting before the expected event.");+ const repaired = liveTurn("child", [+ ...diagnostic.events,+ { type: "message.received", data: { message } },+ ]);+ repaired.session = { state: { streamIndex: 30 } };+ const observed = [];+ await withHarness(async ({ harness, target }) => {+ const children = [initialChild, diagnostic, repaired];+ target.watchTurn = (sessionId, options) => {+ observed.push({ sessionId, ...options });+ return children.shift();};- repairParent.result = async () =>- completedTurn("parent", [], { input: { agentId: "agent-1", message } });- const diagnostic = liveTurn("child", [- { type: "message.received", data: { message: "Diagnose only." } },- ]);- diagnostic.session = { state: { streamIndex: 20 } };- diagnostic.result = async () => ({- ...completedTurn("child", diagnostic.events),- status: "waiting",+ await harness.request("Create the tool.", { start: async () => initialParent });+ const result = await harness.request("Please repair it.", {+ start: async () => repairParent,});- const repaired = liveTurn("child", [- ...diagnostic.events,- { type: "message.received", data: { message } },+ assert.deepEqual(result.child.events, repaired.events);+ assert.deepEqual(observed, [+ { sessionId: "child", startIndex: 0 },+ { sessionId: "child", startIndex: 10 },+ { sessionId: "child", startIndex: 20 },]);- repaired.session = { state: { streamIndex: 30 } };- const observed = [];- await withHarness(async ({ harness, target }) => {- const children = [initialChild, diagnostic, repaired];- target.watchTurn = (sessionId, options) => {- observed.push({ sessionId, ...options });- return children.shift();- };- await harness.request("Create the tool.", { start: async () => initialParent });- const result = await harness.request("Please repair it.", {- start: async () => repairParent,- });- assert.deepEqual(result.child.events, repaired.events);- assert.deepEqual(observed, [- { sessionId: "child", startIndex: 0 },- { sessionId: "child", startIndex: 10 },- { sessionId: "child", startIndex: 20 },- ]);- });});-}+});test("cleanup failure retains a lock that identifies the source backup", async (t) => {const root = await temporaryCheckout(t, "eve-selfmod-cleanup-failed-");diff --git a/e2e/fixtures/agent-session-limits/agent/agent.ts b/e2e/fixtures/agent-session-limits/agent/agent.tsindex c9cad500f..141729ba4 100644--- a/e2e/fixtures/agent-session-limits/agent/agent.ts+++ b/e2e/fixtures/agent-session-limits/agent/agent.ts@@ -9,4 +9,6 @@ export default defineAgent({limits: {maxInputTokensPerSession: 1,},+ // Without the built-in agent tool there are no task tools, so the one-call budget can't go to task_wait.+ tool: false,});diff --git a/e2e/fixtures/agent-session-limits/evals/limits/session-token-limit-approve.eval.ts b/e2e/fixtures/agent-session-limits/evals/limits/session-token-limit-approve.eval.tsindex 135a9a598..7ea914006 100644--- a/e2e/fixtures/agent-session-limits/evals/limits/session-token-limit-approve.eval.ts+++ b/e2e/fixtures/agent-session-limits/evals/limits/session-token-limit-approve.eval.ts@@ -13,7 +13,7 @@ export default defineEval({async test(t) {const conversation = await t.session();const active = await conversation.start(- 'Call the `hold-open` tool exactly once with marker "limit-race". Wait for its result, then reply with exactly "approved".',+ 'Call the `hold-open` tool exactly once with marker "limit-race". When the tool returns, reply with exactly "approved".',);await active.waitForEvent("actions.requested");diff --git a/e2e/fixtures/agent-subagents-hitl/agent/agent.ts b/e2e/fixtures/agent-subagents-hitl/agent/agent.tsindex 5d9b7f373..653b2e9a8 100644--- a/e2e/fixtures/agent-subagents-hitl/agent/agent.ts+++ b/e2e/fixtures/agent-subagents-hitl/agent/agent.ts@@ -13,33 +13,33 @@ function respond(request: MockModelRequest): MockModelResponse | string {: JSON.stringify(audit.output);}if (message.includes("Call the approval-child subagent exactly once")) {- const approval = request.toolResults.find((result) => result.name === "approval-child");- return approval === undefined- ? {- toolCalls: [- {- input: { message: "Ask whether to deploy, then wait for the answer." },- name: "approval-child",- },- ],- }- : String(approval.output);+ const approval = taskResultOf(request, "approval-child");+ if (approval !== undefined) return approval;+ if (hasReceipt(request, "approval-child")) return waitForTasks();+ return {+ toolCalls: [+ {+ input: { message: "Ask whether to deploy, then wait for the answer." },+ name: "approval-child",+ },+ ],+ };}if (message.includes("Call the stock-price subagent exactly once")) {- const quote = request.toolResults.find((result) => result.name === "stock-price");- return quote !== undefined- ? `The stock-price subagent returned: ${String(quote.output)}`- : {- toolCalls: [- {- input: {- message:- 'Call the get_stock_price tool exactly once with ticker "GOOG". After it returns, do not call any tool again; return the result.',- },- name: "stock-price",- },- ],- };+ const quote = taskResultOf(request, "stock-price");+ if (quote !== undefined) return `The stock-price subagent returned: ${quote}`;+ if (hasReceipt(request, "stock-price")) return waitForTasks();+ return {+ toolCalls: [+ {+ input: {+ message:+ 'Call the get_stock_price tool exactly once with ticker "GOOG". After it returns, do not call any tool again; return the result.',+ },+ name: "stock-price",+ },+ ],+ };}if (request.lastUserMessage?.includes(COLLISION_MARKER) !== true) {return `Mock reply: ${message}`;@@ -72,6 +72,25 @@ function respond(request: MockModelRequest): MockModelResponse | string {throw new Error("Mixed runtime-action step resumed before both tool results were available.");}+/** An agent call returns a receipt; its result arrives later in a `<task_result>` message. */+function taskResultOf(request: MockModelRequest, tool: string): string | undefined {+ const pattern = new RegExp(`<task_result [^>]*tool="${tool}"[^>]*>([\\s\\S]*?)</task_result>`);+ for (const message of [...request.messages].reverse()) {+ if (message.role !== "user") continue;+ const body = message.text.match(pattern)?.[1];+ if (body !== undefined) return body;+ }+ return undefined;+}++function hasReceipt(request: MockModelRequest, tool: string): boolean {+ return request.toolResults.some((result) => result.name === tool);+}++function waitForTasks(): MockModelResponse {+ return { toolCalls: [{ input: {}, name: "task_wait" }] };+}+export default defineAgent({...e2eAgentConfig(),// Parking coverage requires both actions in one step; children still use the matrix model.diff --git a/e2e/fixtures/agent-subagents-hitl/evals/mixed-runtime-action-approval.eval.ts b/e2e/fixtures/agent-subagents-hitl/evals/mixed-runtime-action-approval.eval.tsindex 0db4be71c..6d5053fc1 100644--- a/e2e/fixtures/agent-subagents-hitl/evals/mixed-runtime-action-approval.eval.ts+++ b/e2e/fixtures/agent-subagents-hitl/evals/mixed-runtime-action-approval.eval.ts@@ -40,9 +40,9 @@ export default defineEval({t.noFailedActions();t.calledTool("collision-gate", { count: 1, status: "completed" });t.calledSubagent("collision-child", { count: 1, status: "completed" });- t.event("subagent.completed", {+ t.event("task.settled", {count: 1,- data: { callId: "collision-child-call", subagentName: "collision-child" },+ data: { callId: "collision-child-call", status: "completed" },});},});diff --git a/e2e/fixtures/agent-subagents-hitl/evals/proxied-ask-text-response.eval.ts b/e2e/fixtures/agent-subagents-hitl/evals/proxied-ask-text-response.eval.tsindex 7ae1a484d..b74e9fbb7 100644--- a/e2e/fixtures/agent-subagents-hitl/evals/proxied-ask-text-response.eval.ts+++ b/e2e/fixtures/agent-subagents-hitl/evals/proxied-ask-text-response.eval.ts@@ -9,16 +9,16 @@ export default defineEval({"Call the approval-child subagent exactly once and relay its final result when it completes.",);let parent = started.session;- let called = started.events.find(- (event) => event.type === "subagent.called" && event.data.name === "approval-child",+ let child = started.events.find(+ (event) => event.type === "agent.started" && event.data.name === "approval-child",);- if (called?.type !== "subagent.called") {+ if (child?.type !== "agent.started") {const live = watchNextTurn(t, parent, "approval child dispatch wait");- called = await live.waitForEvent("subagent.called", { data: { name: "approval-child" } });+ child = await live.waitForEvent("agent.started", { data: { name: "approval-child" } });parent = live.session;}- if (called.type !== "subagent.called") throw new Error("Approval child was not called.");- const childTurn = t.target.watchTurn(called.data.childSessionId);+ if (child.type !== "agent.started") throw new Error("Approval child was not called.");+ const childTurn = t.target.watchTurn(child.data.sessionId);const pending = await waitForInput(t, parent);const request = pending.requireInputRequest({prompt: /Approve the deployment/i,@@ -26,7 +26,7 @@ export default defineEval({});const parkedChild = await childTurn.result();- const resumedChild = t.target.watchTurn(called.data.childSessionId, {+ const resumedChild = t.target.watchTurn(child.data.sessionId, {startIndex: parkedChild.session.state.streamIndex,});const approved = await pending.start("approve");diff --git a/e2e/fixtures/agent-subagents/agent/agent.ts b/e2e/fixtures/agent-subagents/agent/agent.tsindex 043fdd342..93bb40be4 100644--- a/e2e/fixtures/agent-subagents/agent/agent.ts+++ b/e2e/fixtures/agent-subagents/agent/agent.ts@@ -3,6 +3,12 @@ import { defineAgent, defineDynamic } from "eve";import { mockModel } from "eve/evals";import { WORKSPACE_FORWARDING_MARKER, WORKSPACE_LOOKUP_MESSAGE } from "../constants";+import {+ isNotebookDirective,+ isNotebookEntry,+ respondAsNotebookKeeper,+ respondAsNotebookParent,+} from "./lib/notebook.js";if (process.env.EVE_E2E_MODEL === "mock") {process.env.EVE_MOCK_AUTHORED_MODELS = "1";@@ -60,34 +66,40 @@ const workspaceDispatcher = mockModel({) {return "The workspace lookup was submitted.";}- const agentId = findAnnouncedAgentId(request.messages, "remote-loopback");- const requestCount = request.messages.filter(+ const requests = request.messages.filter((message) => message.role === "user" && message.text.includes(WORKSPACE_FORWARDING_MARKER),- ).length;- if (requestCount > 1 && agentId === undefined) {- throw new Error("Workspace continuation has no remote agent in the <agents> note.");+ );+ const requestCount = requests.length;+ // Only a continuation names the task, which the [Tasks] note lists.+ const continuing = requests.at(-1)?.text.includes("taskId") === true;+ const taskId = continuing ? findListedTaskId(request.messages, "remote-loopback") : undefined;+ if (continuing && taskId === undefined) {+ throw new Error("Workspace continuation has no remote-loopback task in the [Tasks] note.");}return {toolCalls: [{id: `workspace-lookup-${requestCount}`,name: "remote-loopback",- input: { agentId, message: WORKSPACE_LOOKUP_MESSAGE },+ input: { message: WORKSPACE_LOOKUP_MESSAGE, taskId },},],};},});-/** Reads the id the framework-injected `[Agents]` note lists for a parked child. */-function findAnnouncedAgentId(+const notebookParent = mockModel({ modelId: "notebook-parent", respond: respondAsNotebookParent });+// The remote keeper is a root session of this deployment, reached through remote-loopback.+const notebookKeeper = mockModel({ modelId: "notebook-keeper", respond: respondAsNotebookKeeper });+/** Reads the id of a tool's task from the latest framework-injected `[Tasks]` note. */+function findListedTaskId(messages: readonly { readonly role: string; readonly text: string }[],- name: string,+ tool: string,): string | undefined {- const announcement = [...messages]+ const note = [...messages].reverse()- .find((message) => message.role === "user" && message.text.startsWith("[Agents]"));- const pattern = new RegExp(`<agent id="([^"]+)" name="${name}">`);- return announcement?.text.match(pattern)?.[1];+ .find((message) => message.role === "user" && message.text.startsWith("[Tasks]"));+ const pattern = new RegExp(`<task id="([^"]+)" tool="${tool}"`);+ return note?.text.match(pattern)?.[1];}export default defineAgent({@@ -118,6 +130,12 @@ export default defineAgent({if (messages.some((message) => message.includes(WORKSPACE_FORWARDING_MARKER))) {return { model: workspaceDispatcher, modelContextWindowTokens: 1_000_000 };}+ if (messages.some(isNotebookEntry)) {+ return { model: notebookKeeper, modelContextWindowTokens: 1_000_000 };+ }+ if (messages.some(isNotebookDirective)) {+ return { model: notebookParent, modelContextWindowTokens: 1_000_000 };+ }return { model: defaultModel, modelContextWindowTokens };},},diff --git a/e2e/fixtures/agent-subagents/agent/lib/notebook.ts b/e2e/fixtures/agent-subagents/agent/lib/notebook.tsnew file mode 100644index 000000000..2236e2b98--- /dev/null+++ b/e2e/fixtures/agent-subagents/agent/lib/notebook.ts@@ -0,0 +1,196 @@+import {+ latestTaskResult,+ outputOf,+ playScript,+ taskIdFromReceipt,+ type ScriptedCall,+} from "@eve-e2e/config/mock-script";+import type { MockModelRequest, MockModelResponse } from "eve/evals";+import { defineTool } from "eve/tools";+import { never } from "eve/tools/approval";+import { z } from "zod";++import {+ CORRECTED_MEASUREMENT,+ NOTEBOOK_CORRECTION,+ NOTEBOOK_DIRECTIVES,+ NOTEBOOK_ENTRY,+ NOTEBOOK_NAME,+ type NotebookDirective,+} from "../../constants.js";++// The notebook continuation script. Over three parent turns, the parent asks a+// keeper agent to remember a name, gives the same task a review that it+// cancels, then asks the same task for the name again. Only a keeper whose+// conversation survived the cancel can answer.+//+// The correction script is one parent turn: the parent asks a keeper to+// measure a pier, then corrects the pier by `taskId` while the keeper's+// measurement is still running, and waits for the corrected answer. The+// measurement outlasts the parent's next step, so the correction reaches the+// keeper's first turn while it works and that turn reads it.++const REMEMBER_ENTRY = `${NOTEBOOK_ENTRY} Alice named the tide station notebook ${NOTEBOOK_NAME}. Remember that name.`;+const REVIEW_ENTRY = `${NOTEBOOK_ENTRY} Please review the notebook pages before Alice's next question.`;+const RECALL_ENTRY = `${NOTEBOOK_ENTRY} What name did Alice give the tide station notebook?`;+const MEASURE_ENTRY = `${NOTEBOOK_ENTRY} Please measure the tide depth at the north pier for Alice.`;++/** Whether a message is one of the parent's notebook directives, such as `NOTEBOOK-RECALL notebook-keeper`. */+export function isNotebookDirective(message: string): boolean {+ return NOTEBOOK_DIRECTIVES.some((directive) => message.startsWith(`${directive} `));+}++/** Whether a message is one the parent sent a keeper; eve wraps the first one in a preamble. */+export function isNotebookEntry(message: string): boolean {+ return message.includes(`${NOTEBOOK_ENTRY} `);+}++/** The parent: plays the calls for the latest directive against the keeper tool it names. */+export function respondAsNotebookParent(request: MockModelRequest): MockModelResponse | string {+ const latest = [...request.userMessages].reverse().find(isNotebookDirective);+ if (latest === undefined) throw new Error("The notebook parent received no directive.");+ const [directive, tool] = latest.split(/\s+/u) as [NotebookDirective, string];+ const { calls, finish } = parentTurn(directive, tool);+ return playScript(request, calls, () => `NOTEBOOK-REPLY ${finish(request)}`);+}++function parentTurn(+ directive: NotebookDirective,+ tool: string,+): {+ readonly calls: readonly ScriptedCall[];+ readonly finish: (request: MockModelRequest) => string | undefined;+} {+ const keeperTask = (request: MockModelRequest) => taskIdFromReceipt(request, "notebook-remember");+ switch (directive) {+ case "NOTEBOOK-REMEMBER":+ return {+ calls: [+ { id: "notebook-remember", input: () => ({ message: REMEMBER_ENTRY }), name: tool },+ { id: "notebook-remember-wait", name: "task_wait" },+ ],+ finish: (request) => latestTaskResult(request, tool),+ };+ case "NOTEBOOK-REVIEW":+ return {+ calls: [+ {+ id: "notebook-review",+ input: (request) => ({ message: REVIEW_ENTRY, taskId: keeperTask(request) }),+ name: tool,+ },+ { id: "notebook-review-wait", input: () => ({ timeout: 2_000 }), name: "task_wait" },+ {+ id: "notebook-cancel",+ input: (request) => ({ taskId: keeperTask(request) }),+ name: "task_cancel",+ },+ ],+ finish: (request) => outputOf(request, "notebook-cancel"),+ };+ case "NOTEBOOK-RECALL":+ return {+ calls: [+ {+ id: "notebook-recall",+ input: (request) => ({ message: RECALL_ENTRY, taskId: keeperTask(request) }),+ name: tool,+ },+ { id: "notebook-recall-wait", name: "task_wait" },+ ],+ finish: (request) => latestTaskResult(request, tool),+ };+ case "NOTEBOOK-CORRECT":+ return {+ calls: [+ { id: "notebook-measure", input: () => ({ message: MEASURE_ENTRY }), name: tool },+ {+ id: "notebook-correction",+ input: (request) => ({+ message: NOTEBOOK_CORRECTION,+ taskId: taskIdFromReceipt(request, "notebook-measure"),+ }),+ name: tool,+ },+ { id: "notebook-correction-wait", name: "task_wait" },+ ],+ finish: (request) => latestTaskResult(request, tool),+ };+ }+}++/**+ * A keeper, local or remote: saves the name, reviews until its turn is+ * cancelled, and answers the name from its own conversation.+ */+export function respondAsNotebookKeeper(request: MockModelRequest): MockModelResponse | string {+ const message = request.lastUserMessage ?? "";+ if (message.includes(REMEMBER_ENTRY)) return "NOTEBOOK-SAVED";+ if (message.includes(REVIEW_ENTRY)) {+ const reviewId = `notebook-review-${String(request.userMessageCount)}`;+ return playScript(+ request,+ [{ id: reviewId, name: "notebook-review" }],+ () => "NOTEBOOK-REVIEWED",+ );+ }+ if (message.includes(RECALL_ENTRY)) {+ const remembers = request.userMessages.some((entry) => entry.includes(REMEMBER_ENTRY));+ return `NOTEBOOK-NAME=${remembers ? NOTEBOOK_NAME : "unknown"}`;+ }+ if (message.includes(MEASURE_ENTRY)) {+ const measureId = `notebook-measure-${String(request.userMessageCount)}`;+ return playScript(request, [{ id: measureId, name: "notebook-measure" }], measuredPier);+ }+ if (message.includes(NOTEBOOK_CORRECTION)) return CORRECTED_MEASUREMENT;+ throw new Error(`The notebook keeper received an unexpected message: ${message}`);+}++/** Reports the pier of the latest instruction the keeper has read. */+function measuredPier(request: MockModelRequest): string {+ const corrected = request.userMessages.some((entry) => entry.includes(NOTEBOOK_CORRECTION));+ return corrected ? CORRECTED_MEASUREMENT : "NOTEBOOK-DEPTH north pier 3.1 m";+}++const REVIEW_FALLBACK_MS = 60_000;++/** The keeper's review: works until its turn is cancelled, far longer than the parent waits. */+export function notebookReviewTool() {+ return defineTool({+ description: `Test fixture: reviews notebook pages until the review is cancelled. Only call when a ${NOTEBOOK_ENTRY} message asks for a notebook review.`,+ inputSchema: z.object({}),+ approval: never(),+ execute: (_input, ctx) => reviewUntilCancelled(ctx.abortSignal),+ });+}++function reviewUntilCancelled(signal: AbortSignal): Promise<string> {+ return new Promise((resolve, reject) => {+ const finish = setTimeout(() => resolve("The review finished."), REVIEW_FALLBACK_MS);+ const cancel = (): void => {+ clearTimeout(finish);+ reject(signal.reason);+ };+ if (signal.aborted) cancel();+ else signal.addEventListener("abort", cancel, { once: true });+ });+}++/** Long enough that the parent's correction arrives while the measurement runs. */+const MEASURE_MS = 5_000;++/** The keeper's measurement: finishes on its own after a few seconds. */+export function notebookMeasureTool() {+ return defineTool({+ description: `Test fixture: measures the tide depth at a pier. Only call when a ${NOTEBOOK_ENTRY} message asks for a measurement.`,+ inputSchema: z.object({}),+ approval: never(),+ execute: () => measureAfterDelay(),+ });+}++function measureAfterDelay(): Promise<string> {+ return new Promise((resolve) => {+ setTimeout(() => resolve("The measurement finished."), MEASURE_MS);+ });+}diff --git a/e2e/fixtures/agent-subagents/agent/subagents/notebook-keeper/agent.ts b/e2e/fixtures/agent-subagents/agent/subagents/notebook-keeper/agent.tsnew file mode 100644index 000000000..a05130ca1--- /dev/null+++ b/e2e/fixtures/agent-subagents/agent/subagents/notebook-keeper/agent.ts@@ -0,0 +1,19 @@+import { defineAgent, defineDynamic } from "eve";+import { mockModel } from "eve/evals";++import { respondAsNotebookKeeper } from "../../lib/notebook.js";++const keeperModel = mockModel({ modelId: "notebook-keeper", respond: respondAsNotebookKeeper });++/** The local notebook keeper; the remote one is `remote-loopback` running the same script. */+export default defineAgent({+ description:+ "Test fixture: keeps Alice's tide station notebook notes. Call it only for NOTEBOOK directives.",+ // Selected per step: in mock mode this fixture replaces static authored+ // models with eve's bootstrap mock, which would drop the keeper's script.+ model: defineDynamic({+ events: {+ "step.started": () => ({ model: keeperModel, modelContextWindowTokens: 1_000_000 }),+ },+ }),+});diff --git a/e2e/fixtures/agent-subagents/agent/subagents/notebook-keeper/tools/notebook-measure.ts b/e2e/fixtures/agent-subagents/agent/subagents/notebook-keeper/tools/notebook-measure.tsnew file mode 100644index 000000000..3cc532472--- /dev/null+++ b/e2e/fixtures/agent-subagents/agent/subagents/notebook-keeper/tools/notebook-measure.ts@@ -0,0 +1,3 @@+import { notebookMeasureTool } from "../../../lib/notebook.js";++export default notebookMeasureTool();diff --git a/e2e/fixtures/agent-subagents/agent/subagents/notebook-keeper/tools/notebook-review.ts b/e2e/fixtures/agent-subagents/agent/subagents/notebook-keeper/tools/notebook-review.tsnew file mode 100644index 000000000..21581c751--- /dev/null+++ b/e2e/fixtures/agent-subagents/agent/subagents/notebook-keeper/tools/notebook-review.ts@@ -0,0 +1,3 @@+import { notebookReviewTool } from "../../../lib/notebook.js";++export default notebookReviewTool();diff --git a/e2e/fixtures/agent-subagents/agent/tools/notebook-measure.ts b/e2e/fixtures/agent-subagents/agent/tools/notebook-measure.tsnew file mode 100644index 000000000..206b10bbb--- /dev/null+++ b/e2e/fixtures/agent-subagents/agent/tools/notebook-measure.ts@@ -0,0 +1,5 @@+import { notebookMeasureTool } from "../lib/notebook.js";++// The remote notebook keeper is this deployment's root agent (see+// `agent/subagents/remote-loopback.ts`), so the root carries the keeper's tool.+export default notebookMeasureTool();diff --git a/e2e/fixtures/agent-subagents/agent/tools/notebook-review.ts b/e2e/fixtures/agent-subagents/agent/tools/notebook-review.tsnew file mode 100644index 000000000..d7f54c25a--- /dev/null+++ b/e2e/fixtures/agent-subagents/agent/tools/notebook-review.ts@@ -0,0 +1,5 @@+import { notebookReviewTool } from "../lib/notebook.js";++// The remote notebook keeper is this deployment's root agent (see+// `agent/subagents/remote-loopback.ts`), so the root carries the keeper's tool.+export default notebookReviewTool();diff --git a/e2e/fixtures/agent-subagents/constants.ts b/e2e/fixtures/agent-subagents/constants.tsindex 29b7cbf0a..4014ddeaf 100644--- a/e2e/fixtures/agent-subagents/constants.ts+++ b/e2e/fixtures/agent-subagents/constants.ts@@ -4,3 +4,20 @@ export const WORKSPACE_LOOKUP_MESSAGE = ["Report the returned name, or explain if access is denied.",].join(" ");export const WORKSPACE_FORWARDING_MARKER = "Shared workspace membership check.";++/** The directive words of the notebook scripts, one per parent turn. */+export const NOTEBOOK_DIRECTIVES = [+ "NOTEBOOK-REMEMBER",+ "NOTEBOOK-REVIEW",+ "NOTEBOOK-RECALL",+ "NOTEBOOK-CORRECT",+] as const;+export type NotebookDirective = (typeof NOTEBOOK_DIRECTIVES)[number];+/** Starts every message the parent sends a notebook keeper. */+export const NOTEBOOK_ENTRY = "NOTEBOOK-ENTRY";+/** The fact a keeper must still know after its task is cancelled and continued. */+export const NOTEBOOK_NAME = "Harbor Lumen 4482";+/** The parent's correction, sent by `taskId` while the keeper measures the pier. */+export const NOTEBOOK_CORRECTION = `${NOTEBOOK_ENTRY} Correction: Alice meant the south pier, not the north pier.`;+/** What a keeper reports once it measures the pier Alice meant after her correction. */+export const CORRECTED_MEASUREMENT = "NOTEBOOK-DEPTH south pier 4.2 m";diff --git a/e2e/fixtures/agent-subagents/evals/agent-continuation-local.eval.ts b/e2e/fixtures/agent-subagents/evals/agent-continuation-local.eval.tsnew file mode 100644index 000000000..4fd33ee67--- /dev/null+++ b/e2e/fixtures/agent-subagents/evals/agent-continuation-local.eval.ts@@ -0,0 +1,14 @@+import { defineEval } from "eve/evals";++import { continueKeeperAcrossTurns } from "./agent-continuation.shared";++/** Deterministic counterpart of `agent-messaging-local`, with a cancel between the turns. */+export default defineEval({+ description:+ "A local agent task is continued by taskId across turns and after task_cancel with its conversation intact.",+ timeoutMs: 120_000,+ async test(t) {+ await continueKeeperAcrossTurns(t, "notebook-keeper");+ t.noFailedActions();+ },+});diff --git a/e2e/fixtures/agent-subagents/evals/agent-continuation-remote.eval.ts b/e2e/fixtures/agent-subagents/evals/agent-continuation-remote.eval.tsnew file mode 100644index 000000000..01612d67d--- /dev/null+++ b/e2e/fixtures/agent-subagents/evals/agent-continuation-remote.eval.ts@@ -0,0 +1,18 @@+import { defineEval } from "eve/evals";++import { continueKeeperAcrossTurns } from "./agent-continuation.shared";++/**+ * Deterministic counterpart of `agent-messaging-remote`: the keeper is this+ * deployment's root agent reached over HTTP, and the cancel travels the+ * remote protocol.+ */+export default defineEval({+ description:+ "A remote agent task is continued by taskId across turns and after task_cancel with its conversation intact.",+ timeoutMs: 120_000,+ async test(t) {+ await continueKeeperAcrossTurns(t, "remote-loopback");+ t.noFailedActions();+ },+});diff --git a/e2e/fixtures/agent-subagents/evals/agent-continuation.shared.ts b/e2e/fixtures/agent-subagents/evals/agent-continuation.shared.tsnew file mode 100644index 000000000..cc92ad777--- /dev/null+++ b/e2e/fixtures/agent-subagents/evals/agent-continuation.shared.ts@@ -0,0 +1,64 @@+import type { EveEvalContext, EveEvalTurn } from "eve/evals";++import { NOTEBOOK_NAME } from "../constants";++/**+ * Drives the notebook script against one keeper agent over three parent+ * turns: remember a name, start a review on the same task and cancel it, then+ * ask the same task for the name. Every call must reach one task and one child+ * session, the cancel must end the child's review turn, and the name must+ * survive it.+ */+export async function continueKeeperAcrossTurns(t: EveEvalContext, tool: string): Promise<void> {+ const remembered = await t.send(`NOTEBOOK-REMEMBER ${tool} Alice shares the notebook name.`);+ remembered.expectOk();+ remembered.messageIncludes("NOTEBOOK-REPLY NOTEBOOK-SAVED");+ const childSessionId = requireChildSession(remembered, tool);+ const firstChildTurn = await t.target.watchTurn(childSessionId).result();++ const reviewed = await remembered.session.send(+ `NOTEBOOK-REVIEW ${tool} Alice asks for a review, then changes her mind.`,+ );+ reviewed.expectOk();+ reviewed.calledTool("task_cancel", { count: 1, output: { status: "cancelled" } });+ reviewed.event("task.settled", {+ count: 1,+ data: { callId: "notebook-review", status: "cancelled" },+ });+ const cancelledChildTurn = await t.target+ .watchTurn(childSessionId, { startIndex: firstChildTurn.session.state.streamIndex })+ .result();+ cancelledChildTurn.event("turn.cancelled", { count: 1 });++ const recalled = await reviewed.session.send(`NOTEBOOK-RECALL ${tool} Alice asks for the name.`);+ recalled.expectOk();+ recalled.event("task.settled", {+ count: 1,+ data: {+ callId: "notebook-recall",+ output: `NOTEBOOK-NAME=${NOTEBOOK_NAME}`,+ status: "completed",+ },+ });+ recalled.messageIncludes(`NOTEBOOK-REPLY NOTEBOOK-NAME=${NOTEBOOK_NAME}`);++ t.event("agent.started", { count: 1, data: { name: tool } });+ t.eventsSatisfy("each turn's call reaches the one task the first call started", (events) => {+ const calls = events.flatMap((event) =>+ event.type === "task.started" && event.data.name === tool ? [event.data] : [],+ );+ return (+ calls.length === 3 &&+ new Set(calls.map((call) => call.taskId)).size === 1 &&+ new Set(calls.map((call) => call.turnId)).size === 3+ );+ });+}++function requireChildSession(turn: EveEvalTurn, tool: string): string {+ const started = turn.events.find(+ (event) => event.type === "agent.started" && event.data.name === tool,+ );+ if (started?.type !== "agent.started") throw new Error(`${tool} never started a session.`);+ return started.data.sessionId;+}diff --git a/e2e/fixtures/agent-subagents/evals/agent-correction-local.eval.ts b/e2e/fixtures/agent-subagents/evals/agent-correction-local.eval.tsnew file mode 100644index 000000000..4602f7c25--- /dev/null+++ b/e2e/fixtures/agent-subagents/evals/agent-correction-local.eval.ts@@ -0,0 +1,13 @@+import { defineEval } from "eve/evals";++import { correctKeeperWhileItWorks } from "./agent-correction.shared";++export default defineEval({+ description:+ "A local agent corrected by taskId while its tool runs answers the correction and settles the parent's call.",+ timeoutMs: 120_000,+ async test(t) {+ await correctKeeperWhileItWorks(t, "notebook-keeper");+ t.noFailedActions();+ },+});diff --git a/e2e/fixtures/agent-subagents/evals/agent-correction-remote.eval.ts b/e2e/fixtures/agent-subagents/evals/agent-correction-remote.eval.tsnew file mode 100644index 000000000..ab96b28dd--- /dev/null+++ b/e2e/fixtures/agent-subagents/evals/agent-correction-remote.eval.ts@@ -0,0 +1,14 @@+import { defineEval } from "eve/evals";++import { correctKeeperWhileItWorks } from "./agent-correction.shared";++/** The keeper is this deployment's root agent reached over HTTP, so the correction travels the remote protocol. */+export default defineEval({+ description:+ "A remote agent corrected by taskId while its tool runs answers the correction and settles the parent's call.",+ timeoutMs: 120_000,+ async test(t) {+ await correctKeeperWhileItWorks(t, "remote-loopback");+ t.noFailedActions();+ },+});diff --git a/e2e/fixtures/agent-subagents/evals/agent-correction.shared.ts b/e2e/fixtures/agent-subagents/evals/agent-correction.shared.tsnew file mode 100644index 000000000..f670c6820--- /dev/null+++ b/e2e/fixtures/agent-subagents/evals/agent-correction.shared.ts@@ -0,0 +1,52 @@+import type { MessageStreamEvent } from "eve/client";+import type { EveEvalContext } from "eve/evals";+import { satisfies } from "eve/evals/expect";++import { CORRECTED_MEASUREMENT, NOTEBOOK_CORRECTION } from "../constants";++/**+ * Drives the correction script against one keeper agent: the parent corrects+ * the keeper by `taskId` while the keeper's first turn is still measuring. The+ * correction joins that running turn, so the turn reads it before it completes+ * and its reply settles the correction's call with the corrected measurement.+ */+export async function correctKeeperWhileItWorks(t: EveEvalContext, tool: string): Promise<void> {+ const corrected = await t.send(+ `NOTEBOOK-CORRECT ${tool} Alice corrects the pier she asked about.`,+ );+ corrected.expectOk();+ corrected.event("task.settled", {+ count: 1,+ data: { callId: "notebook-correction", output: CORRECTED_MEASUREMENT, status: "completed" },+ });+ corrected.messageIncludes(`NOTEBOOK-REPLY ${CORRECTED_MEASUREMENT}`);++ t.event("agent.started", { count: 1, data: { name: tool } });+ t.eventsSatisfy("the correction reaches the task the first call started", (events) => {+ const calls = events.flatMap((event) =>+ event.type === "task.started" && event.data.name === tool ? [event.data] : [],+ );+ return calls.length === 2 && new Set(calls.map((call) => call.taskId)).size === 1;+ });++ const started = corrected.events.find(+ (event) => event.type === "agent.started" && event.data.name === tool,+ );+ if (started?.type !== "agent.started") return;+ const firstTurn: MessageStreamEvent[] = [];+ for await (const event of corrected.session.agent(started).stream()) {+ firstTurn.push(event);+ if (event.type === "turn.completed" || event.type === "turn.failed") break;+ }+ t.check(+ firstTurn,+ satisfies(+ (events: readonly MessageStreamEvent[]) =>+ events.some(+ (event) =>+ event.type === "message.received" && event.data.message.includes(NOTEBOOK_CORRECTION),+ ),+ "the keeper's first turn reads the correction before it completes",+ ),+ );+}diff --git a/e2e/fixtures/agent-subagents/evals/agent-messaging-local.eval.ts b/e2e/fixtures/agent-subagents/evals/agent-messaging-local.eval.tsindex bf9d625ba..4ba2e04de 100644--- a/e2e/fixtures/agent-subagents/evals/agent-messaging-local.eval.ts+++ b/e2e/fixtures/agent-subagents/evals/agent-messaging-local.eval.ts@@ -5,7 +5,7 @@ const MEMORABLE_FACT = "The observatory locker code is ORBIT-CEDAR-7319.";/*** Cross-turn continuation of a local child: turn one delegates a fact to the* built-in agent subagent and lets it park; turn two re-messages the same- * child via its agentId. The fact can only come back if the child's session+ * child via its taskId. The fact can only come back if the child's session* survived the parent turn boundary.*/export default defineEval({@@ -25,7 +25,7 @@ export default defineEval({const continued = await started.session.send([- "Message that same agent again: call the agent subagent with the agentId shown in the latest <agents> block",+ "Message that same agent again: call the agent subagent again with the taskId of the task you started earlier",'and the message: "What exact fact did I ask you to remember? Reply with only the fact."',"Do not state the fact yourself. When the agent replies, reply with its exact output and no other text.",].join(" "),@@ -36,14 +36,15 @@ export default defineEval({t.succeeded();t.eventsSatisfy("both turns continue one child session", (events) => {const calls = events.flatMap((event) =>- event.type === "subagent.called" && event.data.name === "agent" ? [event.data] : [],+ event.type === "task.started" && event.data.name === "agent" ? [event.data] : [],);return (calls.length >= 2 &&- new Set(calls.map((call) => call.childSessionId)).size === 1 &&+ new Set(calls.map((call) => call.taskId)).size === 1 &&new Set(calls.map((call) => call.turnId)).size >= 2);});+ t.event("agent.started", { data: { name: "agent" }, count: 1 });t.noFailedActions();},});diff --git a/e2e/fixtures/agent-subagents/evals/agent-messaging-remote.eval.ts b/e2e/fixtures/agent-subagents/evals/agent-messaging-remote.eval.tsindex 9ba6190a8..9aa786e8f 100644--- a/e2e/fixtures/agent-subagents/evals/agent-messaging-remote.eval.ts+++ b/e2e/fixtures/agent-subagents/evals/agent-messaging-remote.eval.ts@@ -5,7 +5,7 @@ const MEMORABLE_FACT = "Alice named the tide station notebook Harbor Lumen 4482./*** Cross-turn continuation of a remote child over a real HTTP hop: turn one* delegates a fact to `remote-loopback`, which parks once it replies; turn two- * re-messages the same remote child via its agentId. The fact can only come+ * re-messages the same remote child via its taskId. The fact can only come* back if the continuation reached the same remote session.*/export default defineEval({@@ -24,7 +24,7 @@ export default defineEval({const second = await first.session.send([- "Message that same remote-loopback agent again: call it with the agentId shown in the latest <agents> block",+ "Message that same remote-loopback agent again: call it again with the taskId of the task you started earlier",'and the message: "What exact fact did I ask you to remember? Reply with only the fact."',"Do not state the fact yourself.","When it returns, reply with the agent's exact output and no other text.",@@ -36,16 +36,15 @@ export default defineEval({t.succeeded();t.eventsSatisfy("both turns continue one remote child session", (events) => {const calls = events.flatMap((event) =>- event.type === "subagent.called" && event.data.name === "remote-loopback"- ? [event.data]- : [],+ event.type === "task.started" && event.data.name === "remote-loopback" ? [event.data] : [],);return (calls.length >= 2 &&- new Set(calls.map((call) => call.childSessionId)).size === 1 &&+ new Set(calls.map((call) => call.taskId)).size === 1 &&new Set(calls.map((call) => call.turnId)).size >= 2);});+ t.event("agent.started", { data: { name: "remote-loopback" }, count: 1 });t.noFailedActions();},});diff --git a/e2e/fixtures/agent-subagents/evals/descendant-session-limit.eval.ts b/e2e/fixtures/agent-subagents/evals/descendant-session-limit.eval.tsindex 1a91c7359..594038573 100644--- a/e2e/fixtures/agent-subagents/evals/descendant-session-limit.eval.ts+++ b/e2e/fixtures/agent-subagents/evals/descendant-session-limit.eval.ts@@ -80,7 +80,7 @@ export default defineEval({`Do not call any tool or subagent. Reply with exactly ${ROOT_RECOVERY_TOKEN} and nothing else.`,);recovered.expectOk();- stopSession.event("subagent.called", { data: { name: "limited-worker" }, count: 1 });+ stopSession.event("task.started", { data: { name: "limited-worker" }, count: 1 });recovered.messageIncludes(ROOT_RECOVERY_TOKEN);},});diff --git a/e2e/fixtures/agent-subagents/evals/dynamic-subagent.eval.ts b/e2e/fixtures/agent-subagents/evals/dynamic-subagent.eval.tsindex f9ede37a3..557c8ab4b 100644--- a/e2e/fixtures/agent-subagents/evals/dynamic-subagent.eval.ts+++ b/e2e/fixtures/agent-subagents/evals/dynamic-subagent.eval.ts@@ -11,7 +11,7 @@ export default defineEval({const omitted = await selected.session.send("Call omitted-marker exactly once.");- omitted.notEvent("subagent.called", { data: { name: "omitted-marker" } });+ omitted.notEvent("task.started", { data: { name: "omitted-marker" } });omitted.noFailedActions();},});diff --git a/e2e/fixtures/agent-subagents/evals/remote-principal-forwarding.eval.ts b/e2e/fixtures/agent-subagents/evals/remote-principal-forwarding.eval.tsindex 8f800c477..35b7879df 100644--- a/e2e/fixtures/agent-subagents/evals/remote-principal-forwarding.eval.ts+++ b/e2e/fixtures/agent-subagents/evals/remote-principal-forwarding.eval.ts@@ -21,7 +21,7 @@ const CREATE_CHILD_MESSAGE = [const CONTINUE_CHILD_MESSAGE = [WORKSPACE_FORWARDING_MARKER,"A different user is making this request now.",- "Continue that same remote-loopback agent using its agentId with this message:",+ "Continue that same remote-loopback agent using its taskId with this message:",JSON.stringify(WORKSPACE_LOOKUP_MESSAGE),].join(" ");const CLARIFICATION = [@@ -30,7 +30,10 @@ const CLARIFICATION = ["Do not reuse previous answers; let the service deny access when no membership exists.",].join(" ");-/** Three users resume one remote child; each tool call resolves only its current caller's workspace membership. */+/**+ * Three users continue one remote child by its taskId; each call resolves only its own caller's+ * workspace membership.+ */export default defineEval({tags: ["principal-forwarding"],description:@@ -39,12 +42,12 @@ export default defineEval({// Alice creates the child and reads her workspace label.const aliceTurn = await t.send(CREATE_CHILD_MESSAGE);const aliceParent = await waitForRemoteChild(t, aliceTurn.session, aliceTurn);- const childSessionId = aliceParent.childSessionId;+ const { childSessionId, taskId } = aliceParent;const aliceChild = await t.target.watchTurn(childSessionId).result();await expectWorkspaceReads(t, aliceChild, ALICE_WORKSPACE_LABEL);let childEventCount = aliceChild.events.length;- // Bob continues the same child and must resolve Bob's workspace label, not Alice's.+ // Bob continues it by its taskId and must resolve Bob's workspace label, not Alice's.const bobTurn = await aliceParent.session.send(CONTINUE_CHILD_MESSAGE, {headers: { authorization: BOB_AUTHORIZATION },});@@ -52,7 +55,7 @@ export default defineEval({t,aliceParent.session,bobTurn,- childSessionId,+ aliceParent,BOB_AUTHORIZATION,);const bobChild = await t.target@@ -70,7 +73,7 @@ export default defineEval({t,bobParent.session,observerTurn,- childSessionId,+ aliceParent,OBSERVER_AUTHORIZATION,);const observerChild = await t.target@@ -87,7 +90,10 @@ export default defineEval({},});- t.event("subagent.called", { data: { name: "remote-loopback" }, count: 3 })+ t.event("task.started", { data: { kind: "agent", name: "remote-loopback", taskId }, count: 3 })+ .soft()+ .label("every caller continues the same task");+ t.event("agent.started", { data: { name: "remote-loopback" }, count: 1 }).soft().label("no repeated delegation");t.succeeded();@@ -119,13 +125,19 @@ async function expectWorkspaceReads(type SessionCursor = Pick<EveEvalSession, "respond" | "send" | "sessionId" | "state">;+/** The remote-loopback agent task and the remote session every call to it reaches. */+interface RemoteChild {+ readonly childSessionId: string;+ readonly taskId: string;+}+async function waitForRemoteChild(t: EveEvalContext,initial: SessionCursor,initialTurn: EveEvalTurn,- expectedSessionId?: string,+ expected?: RemoteChild,authorization?: string,-): Promise<{ readonly childSessionId: string; readonly session: SessionCursor }> {+): Promise<RemoteChild & { readonly session: SessionCursor }> {let session = initial;let turn = initialTurn;for (let attempt = 0; attempt < 5; attempt += 1) {@@ -133,15 +145,8 @@ async function waitForRemoteChild(throw new Error("Remote child wait has no parent session cursor.");}turn.expectOk();- const call = turn.events.find(- (event) => event.type === "subagent.called" && event.data.name === "remote-loopback",- );- if (call?.type === "subagent.called") {- if (expectedSessionId !== undefined && call.data.childSessionId !== expectedSessionId) {- throw new Error("The parent turn did not continue the existing remote child.");- }- return { childSessionId: call.data.childSessionId, session };- }+ const child = findRemoteChild(turn, expected);+ if (child !== undefined) return { ...child, session };turn.noFailedActions();if (attempt === 4) break;if (turn.inputRequests.length > 0) {@@ -164,3 +169,24 @@ async function waitForRemoteChild(}throw new Error("The parent did not call remote-loopback after five turns.");}++/** A later call reaches the task's session, which `agent.started` announced once with the task's ID. */+function findRemoteChild(turn: EveEvalTurn, expected?: RemoteChild): RemoteChild | undefined {+ for (const event of turn.events) {+ if (event.type !== "task.started" || event.data.name !== "remote-loopback") continue;+ if (expected !== undefined) {+ if (event.data.taskId !== expected.taskId) {+ throw new Error("The parent turn did not continue the existing remote-loopback task.");+ }+ return expected;+ }+ const started = turn.events.find(+ (candidate) =>+ candidate.type === "agent.started" && candidate.data.taskId === event.data.taskId,+ );+ if (started?.type === "agent.started") {+ return { childSessionId: started.data.sessionId, taskId: event.data.taskId };+ }+ }+ return undefined;+}diff --git a/e2e/fixtures/agent-subagents/evals/remote-subagent-stream.eval.ts b/e2e/fixtures/agent-subagents/evals/remote-subagent-stream.eval.tsindex ddf5da7ca..ae462da32 100644--- a/e2e/fixtures/agent-subagents/evals/remote-subagent-stream.eval.ts+++ b/e2e/fixtures/agent-subagents/evals/remote-subagent-stream.eval.ts@@ -1,7 +1,7 @@import {isCurrentTurnBoundaryEvent,+ type AgentStartedStreamEvent,type MessageStreamEvent,- type SubagentCalledStreamEvent,} from "eve/client";import { defineEval, type EveEvalContext, type EveEvalTurn } from "eve/evals";import { satisfies } from "eve/evals/expect";@@ -22,10 +22,10 @@ export default defineEval({async test(t) {const turn = await t.send(CREATE_CHILD_MESSAGE);turn.expectOk();- const called = await requireRemoteCall(t, turn);+ const started = await requireRemoteSession(t, turn);const childEvents: MessageStreamEvent[] = [];- for await (const event of turn.session.streamSubagent(called)) {+ for await (const event of turn.session.agent(started).stream()) {childEvents.push(event);if (isCurrentTurnBoundaryEvent(event)) break;}@@ -48,15 +48,15 @@ export default defineEval({},});-/** The parent may finish its turn before recording the dispatch; wait for it on the stream if so. */-async function requireRemoteCall(+/** The parent may finish its turn before recording the session; wait for it on the stream if so. */+async function requireRemoteSession(t: EveEvalContext,turn: EveEvalTurn,-): Promise<SubagentCalledStreamEvent> {+): Promise<AgentStartedStreamEvent> {for (const event of turn.events) {- if (event.type === "subagent.called" && event.data.name === "remote-loopback") return event;+ if (event.type === "agent.started" && event.data.name === "remote-loopback") return event;}return await t.target.watchTurn(turn.sessionId, { startIndex: turn.session.state.streamIndex })- .waitForEvent("subagent.called", { data: { name: "remote-loopback" } });+ .waitForEvent("agent.started", { data: { name: "remote-loopback" } });}diff --git a/e2e/fixtures/agent-subagents/evals/software-factory-workflow.eval.ts b/e2e/fixtures/agent-subagents/evals/software-factory-workflow.eval.tsindex 5874e0fb1..ea38c3fbf 100644--- a/e2e/fixtures/agent-subagents/evals/software-factory-workflow.eval.ts+++ b/e2e/fixtures/agent-subagents/evals/software-factory-workflow.eval.ts@@ -29,9 +29,11 @@ export default defineEval({turn.expectOk();t.succeeded();- t.calledTool("workflow", {+ t.calledTool("workflow", { count: 1 });+ // The workflow tool runs as a task: its result settles the task, not the call.+ t.event("task.settled", {count: 1,- output: (observed) => isDeepStrictEqual(observed, expected),+ data: { output: (observed) => isDeepStrictEqual(observed, expected), status: "completed" },});t.event("agent.started", { count: 1, data: { name: TRIAGE } });t.event("agent.started", { count: 1, data: { name: REVIEW } });diff --git a/e2e/fixtures/agent-subagents/evals/workflow-subagent-limit.eval.ts b/e2e/fixtures/agent-subagents/evals/workflow-subagent-limit.eval.tsindex 5b260ab07..d000dacd0 100644--- a/e2e/fixtures/agent-subagents/evals/workflow-subagent-limit.eval.ts+++ b/e2e/fixtures/agent-subagents/evals/workflow-subagent-limit.eval.ts@@ -46,10 +46,11 @@ export default defineEval({);t.succeeded();- t.calledTool("workflow", {+ t.calledTool("workflow", { count: 1, input: isFourCallProgram });+ // The workflow tool runs as a task: its result settles the task, not the call.+ t.event("task.settled", {count: 1,- input: isFourCallProgram,- output: isFourElementLimitResult,+ data: { output: isFourElementLimitResult, status: "completed" },});t.event("agent.started", { count: 3, data: { name: "echo-marker" } });t.messageIncludes("WORKFLOW_PROGRAM_SUBAGENT_LIMIT_REACHED");diff --git a/e2e/fixtures/agent-tasks/.gitignore b/e2e/fixtures/agent-tasks/.gitignorenew file mode 100644index 000000000..eb095f0f8--- /dev/null+++ b/e2e/fixtures/agent-tasks/.gitignore@@ -0,0 +1,10 @@+node_modules+.env*+.eve+.vercel+.next+.output+.nitro+dist+.DS_Store+*.tsbuildinfodiff --git a/e2e/fixtures/agent-tasks/.vercelignore b/e2e/fixtures/agent-tasks/.vercelignorenew file mode 100644index 000000000..357664320--- /dev/null+++ b/e2e/fixtures/agent-tasks/.vercelignore@@ -0,0 +1,6 @@+node_modules+.eve+.next+.output+.nitro+distdiff --git a/e2e/fixtures/agent-tasks/agent/agent.ts b/e2e/fixtures/agent-tasks/agent/agent.tsnew file mode 100644index 000000000..8236a703f--- /dev/null+++ b/e2e/fixtures/agent-tasks/agent/agent.ts@@ -0,0 +1,11 @@+import { e2eAgentConfig } from "@eve-e2e/config";+import { defineAgent } from "eve";++/**+ * Real-model release gate for task behavior: every eval here is tagged+ * `real-model`, because it checks how a live model plans around tasks.+ */+export default defineAgent({+ ...e2eAgentConfig(),+ description: "Coordinate reports, research, and release notes for Alice's team.",+});diff --git a/e2e/fixtures/agent-tasks/agent/instructions.md b/e2e/fixtures/agent-tasks/agent/instructions.mdnew file mode 100644index 000000000..3af2fbbd6--- /dev/null+++ b/e2e/fixtures/agent-tasks/agent/instructions.md@@ -0,0 +1,16 @@+# Identity++You coordinate reports, research, and release notes for Alice's small product+team.++# Tools++- Use `compile_report` to prepare one of the team's reports, such as the churn+ or latency report.+- Ask the `researcher` agent questions about product metrics.+- Ask the `reviewer` agent to check a release summary before it goes out.+- Use `publish_summary` only to publish a summary that the person asked you to+ publish.++Keep replies short and include report ids and finding ids exactly as you+receive them.diff --git a/e2e/fixtures/agent-tasks/agent/subagents/researcher/agent.ts b/e2e/fixtures/agent-tasks/agent/subagents/researcher/agent.tsnew file mode 100644index 000000000..5068a0f0c--- /dev/null+++ b/e2e/fixtures/agent-tasks/agent/subagents/researcher/agent.ts@@ -0,0 +1,8 @@+import { e2eSubagentConfig } from "@eve-e2e/config";+import { defineAgent } from "eve";++export default defineAgent({+ description:+ "Researches product metrics, such as churn by region and quarter, in the team's research archive.",+ ...e2eSubagentConfig(),+});diff --git a/e2e/fixtures/agent-tasks/agent/subagents/researcher/instructions.md b/e2e/fixtures/agent-tasks/agent/subagents/researcher/instructions.mdnew file mode 100644index 000000000..c4289f7c5--- /dev/null+++ b/e2e/fixtures/agent-tasks/agent/subagents/researcher/instructions.md@@ -0,0 +1,7 @@+You research product metrics for Alice's team.++For every question, call `search_archive` once with the question, including+the region and quarter it asks about. Then reply in two sentences: the first+starts with the `findingId` exactly as the archive returned it, and the second+summarizes the archive's note. If a later message changes the question, search+again for the new question and answer only that one.diff --git a/e2e/fixtures/agent-tasks/agent/subagents/researcher/tools/search_archive.ts b/e2e/fixtures/agent-tasks/agent/subagents/researcher/tools/search_archive.tsnew file mode 100644index 000000000..f730343f5--- /dev/null+++ b/e2e/fixtures/agent-tasks/agent/subagents/researcher/tools/search_archive.ts@@ -0,0 +1,22 @@+import { setTimeout } from "node:timers/promises";++import { defineTool } from "eve/tools";+import { never } from "eve/tools/approval";+import { z } from "zod";++import { findChurnNote } from "../../../../findings.ts";++const SEARCH_MS = 15_000;++/** A slow search, so a researcher task is still working when a new message arrives. */+export default defineTool({+ description: "Search the team's research archive for notes that answer a metrics question.",+ inputSchema: z.object({+ question: z.string().describe("The question, with region and quarter."),+ }),+ approval: never(),+ async execute({ question }, ctx) {+ await setTimeout(SEARCH_MS, undefined, { signal: ctx.abortSignal });+ return findChurnNote(question);+ },+});diff --git a/e2e/fixtures/agent-tasks/agent/subagents/reviewer/agent.ts b/e2e/fixtures/agent-tasks/agent/subagents/reviewer/agent.tsnew file mode 100644index 000000000..58bbeed2d--- /dev/null+++ b/e2e/fixtures/agent-tasks/agent/subagents/reviewer/agent.ts@@ -0,0 +1,7 @@+import { e2eSubagentConfig } from "@eve-e2e/config";+import { defineAgent } from "eve";++export default defineAgent({+ description: "Reviews a release summary and approves it or requests changes.",+ ...e2eSubagentConfig(),+});diff --git a/e2e/fixtures/agent-tasks/agent/subagents/reviewer/instructions.md b/e2e/fixtures/agent-tasks/agent/subagents/reviewer/instructions.mdnew file mode 100644index 000000000..6fbb2fe8c--- /dev/null+++ b/e2e/fixtures/agent-tasks/agent/subagents/reviewer/instructions.md@@ -0,0 +1,5 @@+You review release summaries for Alice's team.++Approve a summary when it names a version number and at least one change.+Otherwise request changes. Reply with `APPROVED` or `CHANGES REQUESTED`,+followed by one sentence explaining why.diff --git a/e2e/fixtures/agent-tasks/agent/tools/compile_report.ts b/e2e/fixtures/agent-tasks/agent/tools/compile_report.tsnew file mode 100644index 000000000..780e947cc--- /dev/null+++ b/e2e/fixtures/agent-tasks/agent/tools/compile_report.ts@@ -0,0 +1,32 @@+import { createHash } from "node:crypto";++import { defineWorkflowTool } from "eve/tools";+import { sleep } from "workflow";+import { z } from "zod";++/** A task: compiling takes long enough that the conversation can move on meanwhile. */+export default defineWorkflowTool({+ description:+ "Compile one of the team's reports, such as the churn or latency report. Takes about ten seconds; returns the report id and its headline.",+ inputSchema: z.object({+ topic: z.string().describe("What the report covers, such as churn or latency."),+ }),+ async task({ topic }) {+ "use workflow";++ await sleep("10s");+ return await summarizeReport(topic);+ },+});++/** The report id is derived from the topic, so evals can match it against the result. */+async function summarizeReport(topic: string) {+ "use step";++ const digest = createHash("sha256").update(topic.trim().toLowerCase()).digest("hex");+ return {+ headline: `The ${topic} report is ready for Monday's review.`,+ reportId: `RPT-${digest.slice(0, 6).toUpperCase()}`,+ topic,+ };+}diff --git a/e2e/fixtures/agent-tasks/agent/tools/publish_summary.ts b/e2e/fixtures/agent-tasks/agent/tools/publish_summary.tsnew file mode 100644index 000000000..12b86a2dc--- /dev/null+++ b/e2e/fixtures/agent-tasks/agent/tools/publish_summary.ts@@ -0,0 +1,13 @@+import { defineTool } from "eve/tools";+import { never } from "eve/tools/approval";+import { z } from "zod";++/** The side effect whose ordering the evals check: it must follow the review it depends on. */+export default defineTool({+ description: "Publish a release summary to the team's announcements channel.",+ inputSchema: z.object({ summary: z.string().describe("The exact summary text to publish.") }),+ approval: never(),+ async execute({ summary }) {+ return { published: true, summary };+ },+});diff --git a/e2e/fixtures/agent-tasks/evals/continues-an-agent.eval.ts b/e2e/fixtures/agent-tasks/evals/continues-an-agent.eval.tsnew file mode 100644index 000000000..3f41999a2--- /dev/null+++ b/e2e/fixtures/agent-tasks/evals/continues-an-agent.eval.ts@@ -0,0 +1,36 @@+import { defineEval } from "eve/evals";++import { taskStarts } from "./task-events";++/**+ * A follow-up about the same research goes to the researcher that already+ * has the context: the model continues its task by taskId in the next turn+ * instead of starting a new researcher.+ */+export default defineEval({+ description: "The model continues an agent instead of starting a new one.",+ tags: ["real-model"],+ async test(t) {+ const first = await t.send(+ "Please ask the researcher how churn looked in EMEA for Q3 and tell me what it found.",+ );+ first.expectOk();++ const followUp = await first.session.send(+ "Thanks. Please follow up with the researcher: how does that compare with Q2 for the same region?",+ );+ followUp.expectOk();++ t.event("agent.started", { count: 1, data: { name: "researcher" } });+ t.eventsSatisfy("both turns reach one researcher task", (events) => {+ const calls = taskStarts(events, "researcher");+ return (+ calls.length >= 2 &&+ new Set(calls.map((call) => call.taskId)).size === 1 &&+ new Set(calls.map((call) => call.turnId)).size === 2+ );+ });+ followUp.messageIncludes(/Q2/u);+ t.noFailedActions();+ },+});diff --git a/e2e/fixtures/agent-tasks/evals/evals.config.ts b/e2e/fixtures/agent-tasks/evals/evals.config.tsnew file mode 100644index 000000000..44ff3d9ef--- /dev/null+++ b/e2e/fixtures/agent-tasks/evals/evals.config.ts@@ -0,0 +1,6 @@+import { defineEvalConfig } from "eve/evals";++export default defineEvalConfig({+ // Each eval waits on tasks that take ten to fifteen seconds, sometimes twice.+ timeoutMs: 240_000,+});diff --git a/e2e/fixtures/agent-tasks/evals/fans-out-then-waits.eval.ts b/e2e/fixtures/agent-tasks/evals/fans-out-then-waits.eval.tsnew file mode 100644index 000000000..c6fada137--- /dev/null+++ b/e2e/fixtures/agent-tasks/evals/fans-out-then-waits.eval.ts@@ -0,0 +1,43 @@+import { defineEval } from "eve/evals";+import { equals } from "eve/evals/expect";++import { firstRequestOf, heldTurn, reportIdOf, settlementsOf, taskStarts } from "./task-events";++/**+ * Two independent reports: the model starts both before it waits, then waits+ * for every result before it answers, without replying in between.+ */+export default defineEval({+ description: "The model fans out independent tasks, then waits for every result.",+ tags: ["real-model"],+ async test(t) {+ const turn = await t.send(+ "Alice needs the churn report and the latency report for Monday's review. Please compile both and give me each report id with its headline.",+ );+ turn.expectOk();++ const started = taskStarts(turn.events, "compile_report");+ t.check(started.length, equals(2)).label("each report is compiled once");+ turn.eventsSatisfy("both reports start before the first wait", (events) => {+ const firstWait = firstRequestOf(events, "task_wait");+ const starts = events.flatMap((event, index) =>+ event.type === "task.started" && event.data.name === "compile_report" ? [index] : [],+ );+ return starts.length === 2 && (firstWait === -1 || Math.max(...starts) < firstWait);+ });+ turn.eventsSatisfy("the reply names every report id", (events) => {+ const settled = settlementsOf(+ events,+ started.map((call) => call.callId),+ );+ const reportIds = settled.flatMap((settlement) => reportIdOf(settlement) ?? []);+ const reply = turn.message ?? "";+ return reportIds.length === 2 && reportIds.every((reportId) => reply.includes(reportId));+ });+ turn.eventsSatisfy(+ "the model never replies while reports compile",+ (events) => !heldTurn(events),+ );+ t.noFailedActions();+ },+});diff --git a/e2e/fixtures/agent-tasks/evals/keeps-tasks-after-unrelated-message.eval.ts b/e2e/fixtures/agent-tasks/evals/keeps-tasks-after-unrelated-message.eval.tsnew file mode 100644index 000000000..ab9b566a2--- /dev/null+++ b/e2e/fixtures/agent-tasks/evals/keeps-tasks-after-unrelated-message.eval.ts@@ -0,0 +1,62 @@+import { defineEval } from "eve/evals";+import { equals, satisfies } from "eve/evals/expect";++import { assistantMessages, reportIdOf, settlementsOf, taskStarts } from "./task-events";++/** The expansion of QBR, however the model formats it. */+const QBR_EXPANSION = /business\W+review/iu;++/**+ * Right after the churn report task starts, Alice asks an unrelated question.+ * It arrives as steering during the model's next step, before any wait. The+ * model answers it, keeps the report running, and still delivers its id.+ */+export default defineEval({+ description: "The model keeps its tasks after an unrelated message.",+ tags: ["real-model"],+ async test(t) {+ const session = await t.session();+ const live = await session.start(+ "Please compile the churn report for Alice and tell me its report id when it's ready.",+ );+ await live.waitForEvent("task.started", { data: { name: "compile_report" } });++ const question = await live.session.start(+ "While that compiles, a quick unrelated question from Alice: what does QBR usually stand for?",+ { turnPolicy: "steer" },+ );+ const turn = await live.result();+ const answered = await question.result();+ turn.expectOk();++ turn.notCalledTool("task_cancel");+ const started = taskStarts(turn.events, "compile_report");+ t.check(started.length, equals(1)).label("the report is compiled once");+ const settled = settlementsOf(+ turn.events,+ started.map((call) => call.callId),+ );+ t.check(+ settled.map((settlement) => settlement.status),+ equals(["completed"]),+ ).label("the report task completes");+ const reportIds = settled.flatMap((settlement) => reportIdOf(settlement) ?? []);+ t.check(+ turn.message,+ satisfies(+ (reply: string | undefined) =>+ reportIds.length === 1 && reply?.includes(reportIds[0]!) === true,+ "the final reply names the report id",+ ),+ );+ // The answer may come in an interim message or the final reply.+ t.check(+ [...assistantMessages(turn.events), ...assistantMessages(answered.events)],+ satisfies(+ (messages: readonly string[]) => messages.some((message) => QBR_EXPANSION.test(message)),+ "Alice's unrelated question gets an answer",+ ),+ );+ t.noFailedActions();+ },+});diff --git a/e2e/fixtures/agent-tasks/evals/no-rush.eval.ts b/e2e/fixtures/agent-tasks/evals/no-rush.eval.tsnew file mode 100644index 000000000..21355cb20--- /dev/null+++ b/e2e/fixtures/agent-tasks/evals/no-rush.eval.ts@@ -0,0 +1,33 @@+import { defineEval } from "eve/evals";++import { firstSettlementOf, heldTurn, taskStarts } from "./task-events";++/**+ * Alice says there's no rush, so the model confirms the report is underway+ * instead of waiting on it. The turn rule still holds the turn: after the+ * reply the turn parks with `turn.waiting`, and the result arrives in the same+ * turn.+ */+export default defineEval({+ description: "The model doesn't wait on a task when told there's no rush.",+ tags: ["real-model"],+ async test(t) {+ const turn = await t.send(+ "Please start compiling the latency report for Alice. There's no rush, since she'll read it tomorrow, so don't wait on it; just confirm it's underway.",+ );+ turn.expectOk();++ turn.notCalledTool("task_wait");+ turn.eventsSatisfy("eve holds the turn after the reply", heldTurn);+ turn.eventsSatisfy("the model replies before the report is ready", (events) => {+ const callIds = taskStarts(events, "compile_report").map((call) => call.callId);+ const settled = firstSettlementOf(events, callIds);+ const replied = events.findIndex(+ (event) => event.type === "message.completed" && event.data.finishReason === "stop",+ );+ return callIds.length === 1 && replied >= 0 && replied < settled;+ });+ turn.event("task.settled", { count: 1, data: { status: "completed" } });+ t.noFailedActions();+ },+});diff --git a/e2e/fixtures/agent-tasks/evals/redirects-an-agent.eval.ts b/e2e/fixtures/agent-tasks/evals/redirects-an-agent.eval.tsnew file mode 100644index 000000000..6a6f66fe9--- /dev/null+++ b/e2e/fixtures/agent-tasks/evals/redirects-an-agent.eval.ts@@ -0,0 +1,45 @@+import { defineEval } from "eve/evals";++import { APAC_CHURN } from "../findings";+import { taskStarts } from "./task-events";++/**+ * While the researcher looks into EMEA, Alice corrects the region. The model+ * either corrects the running task by calling the researcher again with its+ * taskId, or stops it with task_cancel and asks again; either way the answer+ * is about APAC.+ */+export default defineEval({+ description: "The model corrects an agent by taskId, or cancels it, after a redirect.",+ tags: ["real-model"],+ async test(t) {+ const session = await t.session();+ const live = await session.start(+ "Please ask the researcher how churn looked in EMEA for Q3 and report back.",+ );+ const first = await live.waitForEvent("task.started", { data: { name: "researcher" } });++ const correction = await live.session.start(+ "Alice made a mistake: she meant APAC, not EMEA. Please get the Q3 churn for APAC instead.",+ { turnPolicy: "steer" },+ );+ const turn = await live.result();+ await correction.result();+ turn.expectOk();++ turn.eventsSatisfy(+ "the first researcher task is corrected by taskId or cancelled",+ (events) => {+ const corrected = taskStarts(events, "researcher").some(+ (call) => call.taskId === first.data.taskId && call.callId !== first.data.callId,+ );+ const cancelled = turn.toolCalls.some(+ (call) => call.name === "task_cancel" && call.input.taskId === first.data.taskId,+ );+ return corrected || cancelled;+ },+ );+ turn.messageIncludes(APAC_CHURN.findingId);+ t.noFailedActions();+ },+});diff --git a/e2e/fixtures/agent-tasks/evals/side-effect-after-result.eval.ts b/e2e/fixtures/agent-tasks/evals/side-effect-after-result.eval.tsnew file mode 100644index 000000000..38fb5fe7f--- /dev/null+++ b/e2e/fixtures/agent-tasks/evals/side-effect-after-result.eval.ts@@ -0,0 +1,30 @@+import { defineEval } from "eve/evals";++import { firstRequestOf, firstSettlementOf, taskStarts } from "./task-events";++const SUMMARY = "Version 4.2 adds the new export dialog and fixes two calendar sync bugs.";++/**+ * Publishing depends on the review, so the model waits for the reviewer's+ * result before it calls `publish_summary`.+ */+export default defineEval({+ description: "The model doesn't use a side-effect tool before the result it depends on.",+ tags: ["real-model"],+ async test(t) {+ const turn = await t.send(+ `Alice drafted this release summary: "${SUMMARY}" Please ask the reviewer to check it, and publish it with publish_summary only if the reviewer approves.`,+ );+ turn.expectOk();++ t.calledSubagent("reviewer", { count: 1, status: "completed" });+ turn.calledTool("publish_summary", { count: 1 });+ turn.eventsSatisfy("publishing waits for the review's result", (events) => {+ const reviewCallIds = taskStarts(events, "reviewer").map((call) => call.callId);+ const reviewed = firstSettlementOf(events, reviewCallIds);+ const published = firstRequestOf(events, "publish_summary");+ return reviewed >= 0 && published > reviewed;+ });+ t.noFailedActions();+ },+});diff --git a/e2e/fixtures/agent-tasks/evals/task-events.ts b/e2e/fixtures/agent-tasks/evals/task-events.tsnew file mode 100644index 000000000..526e35065--- /dev/null+++ b/e2e/fixtures/agent-tasks/evals/task-events.ts@@ -0,0 +1,74 @@+import type {+ MessageStreamEvent,+ TaskSettledStreamEvent,+ TaskStartedStreamEvent,+} from "eve/client";++/**+ * Whether eve held the turn: the model ended a step with a reply while its+ * tasks worked, and the turn parked with `turn.waiting` instead of ending. A+ * `turn.waiting` after a `task_wait` call is the model waiting, not a hold.+ */+export function heldTurn(events: readonly MessageStreamEvent[]): boolean {+ let replied = false;+ for (const event of events) {+ if (event.type === "message.completed") replied = event.data.finishReason === "stop";+ else if (event.type === "actions.requested") replied = false;+ else if (event.type === "turn.waiting" && replied) return true;+ }+ return false;+}++/** Every call that started or reached a task of `tool`, in stream order. */+export function taskStarts(+ events: readonly MessageStreamEvent[],+ tool: string,+): readonly TaskStartedStreamEvent["data"][] {+ return events.flatMap((event) =>+ event.type === "task.started" && event.data.name === tool ? [event.data] : [],+ );+}++/** How every call in `callIds` settled, in stream order. */+export function settlementsOf(+ events: readonly MessageStreamEvent[],+ callIds: readonly string[],+): readonly TaskSettledStreamEvent["data"][] {+ return events.flatMap((event) =>+ event.type === "task.settled" && callIds.includes(event.data.callId) ? [event.data] : [],+ );+}++/** The text of every assistant message that completed, interim or final, in stream order. */+export function assistantMessages(events: readonly MessageStreamEvent[]): readonly string[] {+ return events.flatMap((event) =>+ event.type === "message.completed" ? [event.data.message] : [],+ );+}++/** Index of the first `actions.requested` event that calls `tool`, or -1. */+export function firstRequestOf(events: readonly MessageStreamEvent[], tool: string): number {+ return events.findIndex(+ (event) =>+ event.type === "actions.requested" &&+ event.data.actions.some((action) => action.kind === "tool-call" && action.toolName === tool),+ );+}++/** Index of the first `task.settled` event for any call in `callIds`, or -1. */+export function firstSettlementOf(+ events: readonly MessageStreamEvent[],+ callIds: readonly string[],+): number {+ return events.findIndex(+ (event) => event.type === "task.settled" && callIds.includes(event.data.callId),+ );+}++/** The `reportId` a completed `compile_report` call returned. */+export function reportIdOf(settlement: TaskSettledStreamEvent["data"]): string | undefined {+ const output = settlement.output;+ if (typeof output !== "object" || output === null || !("reportId" in output)) return undefined;+ const reportId = output.reportId;+ return typeof reportId === "string" ? reportId : undefined;+}diff --git a/e2e/fixtures/agent-tasks/evals/waits-when-needed.eval.ts b/e2e/fixtures/agent-tasks/evals/waits-when-needed.eval.tsnew file mode 100644index 000000000..47d3c008b--- /dev/null+++ b/e2e/fixtures/agent-tasks/evals/waits-when-needed.eval.ts@@ -0,0 +1,28 @@+import { defineEval } from "eve/evals";++import { EMEA_CHURN } from "../findings";+import { heldTurn } from "./task-events";++/**+ * The answer depends on the researcher's result, so the model waits for it+ * with `task_wait` instead of ending its step while the task works.+ */+export default defineEval({+ description: "The model waits for an agent's result when its answer depends on it.",+ tags: ["real-model"],+ async test(t) {+ const turn = await t.send(+ "Bob asked Alice how churn looked in EMEA for Q3. Please ask the researcher and tell me what it found, so Alice can pass it on to Bob.",+ );+ turn.expectOk();++ t.calledSubagent("researcher", { status: "completed" });+ turn.calledTool("task_wait");+ turn.eventsSatisfy(+ "the model never replies while the researcher works",+ (events) => !heldTurn(events),+ );+ turn.messageIncludes(EMEA_CHURN.findingId);+ t.noFailedActions();+ },+});diff --git a/e2e/fixtures/agent-tasks/findings.ts b/e2e/fixtures/agent-tasks/findings.tsnew file mode 100644index 000000000..dcf6175eb--- /dev/null+++ b/e2e/fixtures/agent-tasks/findings.ts@@ -0,0 +1,30 @@+// The research archive's findings, shared by the researcher's tool and the+// evals that check a finding reached the final reply.++export interface ArchiveFinding {+ readonly findingId: string;+ readonly note: string;+}++export const EMEA_CHURN: ArchiveFinding = {+ findingId: "FND-EMEA-3K7",+ note: "EMEA churn fell to 2.1% in Q3, down from 2.6% in Q2, led by fewer annual-plan cancellations.",+};++export const APAC_CHURN: ArchiveFinding = {+ findingId: "FND-APAC-9Q2",+ note: "APAC churn rose to 3.4% in Q3, up from 2.9% in Q2, mostly among monthly self-serve plans.",+};++export const GENERAL_CHURN: ArchiveFinding = {+ findingId: "FND-GLOBAL-5M1",+ note: "Global churn held at 2.7% in Q3; the archive has regional breakdowns for EMEA and APAC.",+};++/** The finding for a question: the archive answers by region. */+export function findChurnNote(question: string): ArchiveFinding {+ const normalized = question.toUpperCase();+ if (normalized.includes("APAC")) return APAC_CHURN;+ if (normalized.includes("EMEA")) return EMEA_CHURN;+ return GENERAL_CHURN;+}diff --git a/e2e/fixtures/agent-tasks/package.json b/e2e/fixtures/agent-tasks/package.jsonnew file mode 100644index 000000000..e28ee688a--- /dev/null+++ b/e2e/fixtures/agent-tasks/package.json@@ -0,0 +1,26 @@+{+ "name": "agent-tasks",+ "version": "0.0.0",+ "private": true,+ "type": "module",+ "scripts": {+ "build": "eve build",+ "dev": "eve dev",+ "start": "eve start",+ "typecheck": "eve build --skip-sandbox-prewarm && tsc",+ "test:e2e": "eve eval --strict"+ },+ "dependencies": {+ "@eve-e2e/config": "workspace:*",+ "@workflow/world-postgres": "catalog:",+ "eve": "workspace:*",+ "zod": "catalog:"+ },+ "devDependencies": {+ "@types/node": "catalog:",+ "typescript": "catalog:"+ },+ "e2e": {+ "modelMatrix": "full"+ }+}diff --git a/e2e/fixtures/agent-tasks/tsconfig.json b/e2e/fixtures/agent-tasks/tsconfig.jsonnew file mode 100644index 000000000..53e7aebee--- /dev/null+++ b/e2e/fixtures/agent-tasks/tsconfig.json@@ -0,0 +1,21 @@+{+ "compilerOptions": {+ "target": "ES2022",+ "module": "esnext",+ "moduleResolution": "bundler",+ "outDir": "dist",+ "rootDir": ".",+ "strict": true,+ "esModuleInterop": true,+ "skipLibCheck": true,+ "forceConsistentCasingInFileNames": true,+ "declaration": false,+ "noEmit": true,+ "types": ["node", "eve/workflow-modules"],+ "allowImportingTsExtensions": true,+ "paths": {+ "@/*": ["./*"]+ }+ },+ "include": ["agent/**/*.ts", "evals/**/*.ts"]+}diff --git a/e2e/fixtures/agent-tools-sandbox/agent/lib/mock-responder.ts b/e2e/fixtures/agent-tools-sandbox/agent/lib/mock-responder.tsindex 6564a9054..db69b2c13 100644--- a/e2e/fixtures/agent-tools-sandbox/agent/lib/mock-responder.ts+++ b/e2e/fixtures/agent-tools-sandbox/agent/lib/mock-responder.ts@@ -38,7 +38,7 @@ export function respond(request: MockModelRequest): MockModelResponse | string {for (let index = 0; index < request.messages.length; index += 1) {const entry = request.messages[index]!;if (entry.role === "tool") lastToolResultIndex = index;- if (entry.role === "user" && !entry.text.trim().startsWith("[Agents]")) {+ if (entry.role === "user" && !isFrameworkMessage(entry.text)) {lastAuthoredUserIndex = index;}}@@ -49,7 +49,8 @@ export function respond(request: MockModelRequest): MockModelResponse | string {if (!turnHasToolResult) {return { toolCalls: [{ input: { message: subagent[2] }, name: subagent[1] }] };}- return toolOutput(request, subagent[1]);+ // The agent call returned a receipt; its result arrives in a <task_result> message.+ return taskResultOf(request, subagent[1]) ?? { toolCalls: [{ input: {}, name: "task_wait" }] };}const bash = BASH_DIRECTIVE.exec(message);@@ -76,6 +77,22 @@ export function respond(request: MockModelRequest): MockModelResponse | string {return `Mock reply: ${message}`;}+/** The `[Tasks]` note and `<task_result>` messages are eve's, not the user's. */+function isFrameworkMessage(text: string): boolean {+ const trimmed = text.trim();+ return trimmed.startsWith("[Tasks]") || trimmed.startsWith("<task_result");+}++function taskResultOf(request: MockModelRequest, tool: string): string | undefined {+ const pattern = new RegExp(`<task_result [^>]*tool="${tool}"[^>]*>([\\s\\S]*?)</task_result>`);+ for (const entry of [...request.messages].reverse()) {+ if (entry.role !== "user") continue;+ const body = entry.text.match(pattern)?.[1];+ if (body !== undefined) return body;+ }+ return undefined;+}+function bashStdout(request: MockModelRequest): string {const output = [...request.toolResults].reverse()diff --git a/e2e/fixtures/agent-tools-sandbox/evals/sandbox/typed-environment-capability.eval.ts b/e2e/fixtures/agent-tools-sandbox/evals/sandbox/typed-environment-capability.eval.tsindex 1feac8483..0c79459d4 100644--- a/e2e/fixtures/agent-tools-sandbox/evals/sandbox/typed-environment-capability.eval.ts+++ b/e2e/fixtures/agent-tools-sandbox/evals/sandbox/typed-environment-capability.eval.ts@@ -8,14 +8,14 @@ export default defineEval({"Ask the `deny-all` subagent with message: Verify the configured environment sandbox capability.",);turn.expectOk();- const called = turn.events.find(- (event) => event.type === "subagent.called" && event.data.name === "deny-all",+ const started = turn.events.find(+ (event) => event.type === "agent.started" && event.data.name === "deny-all",);- if (called?.type !== "subagent.called") {+ if (started?.type !== "agent.started") {throw new Error("Typed sandbox turn did not call the deny-all subagent.");}- const childTurn = await t.target.watchTurn(called.data.childSessionId).result();+ const childTurn = await t.target.watchTurn(started.data.sessionId).result();childTurn.expectOk();t.succeeded();diff --git a/e2e/fixtures/agent-workflow-tools/agent/agent.ts b/e2e/fixtures/agent-workflow-tools/agent/agent.tsindex 4e06a74fb..019543916 100644--- a/e2e/fixtures/agent-workflow-tools/agent/agent.ts+++ b/e2e/fixtures/agent-workflow-tools/agent/agent.ts@@ -1,7 +1,10 @@import { e2eAgentConfig } from "@eve-e2e/config";+import { latestTaskResult } from "@eve-e2e/config/mock-script";import { defineAgent } from "eve";import { mockModel, type MockModelRequest, type MockModelResponse } from "eve/evals";+import { respondToTaskScenario } from "./lib/task-scenarios.ts";+/*** Deterministic script: each directive names the workflow tool to call with* service "api"; once the turn holds a tool result the reply echoes it.@@ -38,6 +41,10 @@ function respond(request: MockModelRequest): MockModelResponse | string {],};}+ // The agent call returned a receipt; its result arrives in a <task_result> message.+ if (mode === "direct") {+ return latestTaskResult(request, tool) ?? { toolCalls: [{ name: "task_wait", input: {} }] };+ }const result = request.toolResults.find((entry) => entry.name === tool);return typeof result?.output === "string" ? result.output : JSON.stringify(result?.output);}@@ -46,6 +53,8 @@ function respond(request: MockModelRequest): MockModelResponse | string {[...request.userMessages].reverse().find((entry) => entry.startsWith("WORKFLOW-") || entry.includes("private-catalog")) ?? "";+ const scenario = respondToTaskScenario(request, directiveOf(message));+ if (scenario !== undefined) return scenario;if (message.includes("private-catalog")) {const result = request.toolResults.find((entry) => entry.name === "connection_search");if (result === undefined) {@@ -101,6 +110,11 @@ function respond(request: MockModelRequest): MockModelResponse | string {return "WORKFLOW-IDLE";}+/** A directive is the first word of its message; any text after it is for people reading it. */+function directiveOf(message: string): string {+ return message.trim().split(/\s+/u)[0] ?? "";+}+const base = e2eAgentConfig({ mock: respond });export default defineAgent({diff --git a/e2e/fixtures/agent-workflow-tools/agent/channels/mcp.ts b/e2e/fixtures/agent-workflow-tools/agent/channels/mcp.tsnew file mode 100644index 000000000..71456645f--- /dev/null+++ b/e2e/fixtures/agent-workflow-tools/agent/channels/mcp.ts@@ -0,0 +1,5 @@+import { none } from "eve/channels/auth";+import { mcpChannel } from "eve/channels/mcp";++// Fixture-only public access so the MCP eval needs no injected credentials.+export default mcpChannel({ auth: none() });diff --git a/e2e/fixtures/agent-workflow-tools/agent/hooks/subagent-audit.ts b/e2e/fixtures/agent-workflow-tools/agent/hooks/subagent-audit.tsindex cc1a6ddd0..b41e3bc68 100644--- a/e2e/fixtures/agent-workflow-tools/agent/hooks/subagent-audit.ts+++ b/e2e/fixtures/agent-workflow-tools/agent/hooks/subagent-audit.ts@@ -3,8 +3,8 @@ import { recordSubagentHook } from "../../subagent-hook-audit";export default defineHook({events: {- "subagent.called": (event, ctx) => recordSubagentHook("typed", event, ctx),- "subagent.completed": (event, ctx) => recordSubagentHook("typed", event, ctx),+ "task.started": (event, ctx) => recordSubagentHook("typed", event, ctx),+ "task.settled": (event, ctx) => recordSubagentHook("typed", event, ctx),"*": (event, ctx) => recordSubagentHook("wildcard", event, ctx),},});diff --git a/e2e/fixtures/agent-workflow-tools/agent/lib/plan-revisions.ts b/e2e/fixtures/agent-workflow-tools/agent/lib/plan-revisions.tsnew file mode 100644index 000000000..2d7748a32--- /dev/null+++ b/e2e/fixtures/agent-workflow-tools/agent/lib/plan-revisions.ts@@ -0,0 +1,19 @@+/** A revision request that keeps the plan task working until its work is cancelled. */+export const HOLD_REQUEST = "hold until cancelled";++/**+ * Stands in for revision work that honors cancellation: a hold request works+ * until `signal` aborts and then rejects, as an aborted fetch would.+ */+export async function revise(request: string, signal: AbortSignal): Promise<string> {+ if (request === HOLD_REQUEST) await rejectOnAbort(signal);+ return request;+}++function rejectOnAbort(signal: AbortSignal): Promise<never> {+ return new Promise((_, reject) => {+ const abort = () => reject(new Error("The revision was cancelled."));+ if (signal.aborted) abort();+ else signal.addEventListener("abort", abort, { once: true });+ });+}diff --git a/e2e/fixtures/agent-workflow-tools/agent/lib/plan.ts b/e2e/fixtures/agent-workflow-tools/agent/lib/plan.tsindex 378cf01e0..e07f894e2 100644--- a/e2e/fixtures/agent-workflow-tools/agent/lib/plan.ts+++ b/e2e/fixtures/agent-workflow-tools/agent/lib/plan.ts@@ -1,5 +1,8 @@import { createHash } from "node:crypto";+/** The `sign_off_plan` request that asks a person to sign off; any other is a note on the plan. */+export const SIGN_OFF_REQUEST = "sign off";+export function describePlan(service: string): string {return `deploy ${service}`;}diff --git a/e2e/fixtures/agent-workflow-tools/agent/lib/stage.ts b/e2e/fixtures/agent-workflow-tools/agent/lib/stage.tsnew file mode 100644index 000000000..db3dee6e1--- /dev/null+++ b/e2e/fixtures/agent-workflow-tools/agent/lib/stage.ts@@ -0,0 +1,15 @@+import { sleep } from "workflow";++import { describePlan, hashPlan } from "./plan.ts";++/**+ * Plans a deploy, then lets it settle for a few seconds: long enough that the+ * model's next step always runs while the task is still working. Call it from+ * a workflow body.+ */+export async function stageDeploy(service: string): Promise<{ digest: string; plan: string }> {+ const plan = describePlan(service);+ const digest = await hashPlan(plan);+ await sleep("3s");+ return { digest, plan };+}diff --git a/e2e/fixtures/agent-workflow-tools/agent/lib/task-scenarios.ts b/e2e/fixtures/agent-workflow-tools/agent/lib/task-scenarios.tsnew file mode 100644index 000000000..bbeb5ef9d--- /dev/null+++ b/e2e/fixtures/agent-workflow-tools/agent/lib/task-scenarios.ts@@ -0,0 +1,217 @@+import {+ latestTaskResult,+ outputOf,+ playScript,+ taskIdFromReceipt,+} from "@eve-e2e/config/mock-script";+import type { MockModelRequest, MockModelResponse } from "eve/evals";++import {+ DELEGATE_INTERIM_MESSAGE,+ ROLLOUT_INTERIM_MESSAGE,+ SIGN_OFF_INTERIM_MESSAGE,+ STAGE_INTERIM_MESSAGE,+} from "../../task-scenario-text.ts";+import { SIGN_OFF_REQUEST } from "./plan.ts";+import { HOLD_REQUEST } from "./plan-revisions.ts";++type Scenario = (request: MockModelRequest) => MockModelResponse | string;++/**+ * Task and steering scenarios for the root agent, keyed by the directive that+ * starts them. Each one is a fixed sequence of calls with stable ids, so evals+ * can assert on those ids.+ */+const SCENARIOS: Readonly<Record<string, Scenario>> = {+ "WORKFLOW-STAGE-WAIT": (request) =>+ playScript(+ request,+ [+ { id: "stage", input: apiService, name: "stage_deploy" },+ { id: "stage-wait", name: "task_wait" },+ ],+ () => report("WORKFLOW-STAGE-RESULT", latestTaskResult(request, "stage_deploy")),+ ),++ "WORKFLOW-STAGE-HOLD": (request) =>+ playScript(request, [{ id: "stage", input: apiService, name: "stage_deploy" }], () =>+ reportOnceSettled(request, "stage_deploy", "WORKFLOW-STAGE-RESULT", STAGE_INTERIM_MESSAGE),+ ),++ "WORKFLOW-ROLLOUT-HOLD": (request) =>+ playScript(request, [{ id: "rollout", input: apiService, name: "approve_rollout" }], () =>+ reportOnceSettled(+ request,+ "approve_rollout",+ "WORKFLOW-ROLLOUT-RESULT",+ ROLLOUT_INTERIM_MESSAGE,+ ),+ ),++ "WORKFLOW-CANARY-CANCEL": (request) =>+ playScript(+ request,+ [+ { id: "canary", input: apiService, name: "canary_deploy" },+ { id: "canary-cancel", input: taskOf("canary"), name: "task_cancel" },+ ],+ () => report("WORKFLOW-CANARY-RESULT", outputOf(request, "canary-cancel")),+ ),++ "WORKFLOW-PLAN-START": (request) =>+ playScript(+ request,+ [+ { id: "plan-draft", input: () => ({ request: "draft" }), name: "revise_plan" },+ { id: "plan-draft-wait", name: "task_wait" },+ ],+ () => report("WORKFLOW-PLAN-RESULT", latestTaskResult(request, "revise_plan")),+ ),++ // Holds the plan task busy, cancels that work, then revises the same task again.+ "WORKFLOW-PLAN-REVISE": (request) =>+ playScript(+ request,+ [+ { id: "plan-hold", input: revisionOf(HOLD_REQUEST), name: "revise_plan" },+ { id: "plan-hold-wait", input: () => ({ timeout: 1_000 }), name: "task_wait" },+ { id: "plan-cancel", input: taskOf("plan-draft"), name: "task_cancel" },+ { id: "plan-final", input: revisionOf("final"), name: "revise_plan" },+ { id: "plan-final-wait", name: "task_wait" },+ ],+ () => report("WORKFLOW-PLAN-RESULT", latestTaskResult(request, "revise_plan")),+ ),++ // Asks for sign-off in a resumable task, then ends the step so the turn holds on it.+ "WORKFLOW-SIGNOFF-HOLD": (request) =>+ playScript(+ request,+ [{ id: "signoff", input: () => ({ request: SIGN_OFF_REQUEST }), name: "sign_off_plan" }],+ () =>+ reportOnceSettled(+ request,+ "sign_off_plan",+ "WORKFLOW-SIGNOFF-RESULT",+ SIGN_OFF_INTERIM_MESSAGE,+ ),+ ),++ // The plan changes: cancel the pending sign-off, then note the change on the same task.+ "WORKFLOW-SIGNOFF-CANCEL": (request) =>+ playScript(+ request,+ [+ { id: "signoff-cancel", input: taskOf("signoff"), name: "task_cancel" },+ {+ id: "signoff-note",+ input: (current) => ({+ request: "rework the plan first",+ taskId: taskIdFromReceipt(current, "signoff"),+ }),+ name: "sign_off_plan",+ },+ { id: "signoff-note-wait", name: "task_wait" },+ ],+ () => report("WORKFLOW-SIGNOFF-RESULT", latestTaskResult(request, "sign_off_plan")),+ ),++ // Sends the notes task two notes, the first held for the second, so one reply answers both.+ "WORKFLOW-NOTES-BATCH": (request) =>+ playScript(+ request,+ [+ { id: "notes-draft", input: () => ({ more: true, note: "draft" }), name: "collect_notes" },+ {+ id: "notes-final",+ input: (current) => ({+ note: "final",+ taskId: taskIdFromReceipt(current, "notes-draft"),+ }),+ name: "collect_notes",+ },+ { id: "notes-wait", name: "task_wait" },+ ],+ () =>+ report(+ "WORKFLOW-NOTES-RESULT",+ `${String(countTaskResults(request, "collect_notes"))} ${latestTaskResult(request, "collect_notes") ?? "none"}`,+ ),+ ),++ "WORKFLOW-DELEGATE-STAGE": (request) =>+ playScript(+ request,+ [{ id: "delegate", input: () => ({ message: "Stage api." }), name: "workflow-stager" }],+ () =>+ reportOnceSettled(+ request,+ "workflow-stager",+ "WORKFLOW-DELEGATE-RESULT",+ DELEGATE_INTERIM_MESSAGE,+ ),+ ),++ "WORKFLOW-SLEEP-START": (request) =>+ playScript(request, [{ id: "nap", input: () => ({ seconds: 600 }), name: "sleep" }], () =>+ report("WORKFLOW-SLEEP-RESULT", outputOf(request, "nap")),+ ),++ "WORKFLOW-OFFER-START": (request) =>+ playScript(request, [{ id: "offer", input: apiService, name: "offer_deploy" }], () =>+ report("WORKFLOW-OFFER-RESULT", outputOf(request, "offer")),+ ),+};++/** The scripted response for a task or steering scenario, or `undefined` for any other directive. */+export function respondToTaskScenario(+ request: MockModelRequest,+ directive: string,+): MockModelResponse | string | undefined {+ return SCENARIOS[directive]?.(request);+}++function apiService(): { service: string } {+ return { service: "api" };+}++/** How many `<task_result>` blocks for `tool` the model has received. */+function countTaskResults(request: MockModelRequest, tool: string): number {+ const block = new RegExp(`<task_result [^>]*tool="${tool}"`, "g");+ let count = 0;+ for (const message of request.messages) {+ if (message.role === "user") count += [...message.text.matchAll(block)].length;+ }+ return count;+}++/** Input naming the task the receipt of `callId` started. */+function taskOf(callId: string): (request: MockModelRequest) => { taskId: string } {+ return (request) => ({ taskId: taskIdFromReceipt(request, callId) });+}++/** Input that sends the plan task started by `plan-draft` another revision. */+function revisionOf(revision: string) {+ return (request: MockModelRequest) => ({+ request: revision,+ taskId: taskIdFromReceipt(request, "plan-draft"),+ });+}++/**+ * Ends the model's step with text while the task still works, which holds the+ * turn; once the result arrives, reports it.+ */+function reportOnceSettled(+ request: MockModelRequest,+ tool: string,+ label: string,+ interim: string,+): string {+ const result = latestTaskResult(request, tool);+ return result === undefined ? interim : report(label, result);+}++function report(label: string, output: string | undefined): string {+ if (output === undefined) throw new Error(`${label}: the script expected a task result.`);+ return `${label} ${output}`;+}diff --git a/e2e/fixtures/agent-workflow-tools/agent/schedules/staged-deploy.ts b/e2e/fixtures/agent-workflow-tools/agent/schedules/staged-deploy.tsnew file mode 100644index 000000000..4c6f1b7ef--- /dev/null+++ b/e2e/fixtures/agent-workflow-tools/agent/schedules/staged-deploy.ts@@ -0,0 +1,11 @@+import { defineSchedule } from "eve/schedules";++/**+ * Fired on demand by `evals/held-turn.schedule.eval.ts`. The directive runs+ * the root agent's held-turn script: stage a deploy, write while the task+ * works, then report its result.+ */+export default defineSchedule({+ cron: "0 0 * * *",+ markdown: "WORKFLOW-STAGE-HOLD Stage the nightly api deploy and report its digest.",+});diff --git a/e2e/fixtures/agent-workflow-tools/agent/subagents/workflow-stager/agent.ts b/e2e/fixtures/agent-workflow-tools/agent/subagents/workflow-stager/agent.tsnew file mode 100644index 000000000..642666def--- /dev/null+++ b/e2e/fixtures/agent-workflow-tools/agent/subagents/workflow-stager/agent.ts@@ -0,0 +1,29 @@+import { latestTaskResult, playScript } from "@eve-e2e/config/mock-script";+import { defineAgent } from "eve";+import { mockModel, type MockModelRequest, type MockModelResponse } from "eve/evals";++import { STAGER_INTERIM_MESSAGE } from "../../../task-scenario-text.ts";++/**+ * Starts a staging task, ends its step with text while the task works, and+ * replies with the result once it arrives. The text step holds the child's+ * turn, and a child session reports that step as `"tool-calls"`, so only the+ * final reply reaches the parent.+ */+function respond(request: MockModelRequest): MockModelResponse | string {+ return playScript(+ request,+ [{ id: "child-stage", input: () => ({ service: "api" }), name: "stage_deploy" }],+ () => {+ const result = latestTaskResult(request, "stage_deploy");+ if (result === undefined) return STAGER_INTERIM_MESSAGE;+ return `WORKFLOW-CHILD-STAGED ${result}`;+ },+ );+}++export default defineAgent({+ description: "Stage a service deploy for the parent and report the staged plan.",+ model: mockModel(respond),+ modelContextWindowTokens: 1_000_000,+});diff --git a/e2e/fixtures/agent-workflow-tools/agent/subagents/workflow-stager/tools/stage_deploy.ts b/e2e/fixtures/agent-workflow-tools/agent/subagents/workflow-stager/tools/stage_deploy.tsnew file mode 100644index 000000000..bf05f3fa6--- /dev/null+++ b/e2e/fixtures/agent-workflow-tools/agent/subagents/workflow-stager/tools/stage_deploy.ts@@ -0,0 +1,15 @@+import { defineWorkflowTool } from "eve/tools";+import { z } from "zod";++import { stageDeploy } from "../../../lib/stage.ts";++/** The child's own staging task; subagents do not inherit the root's tools. */+export default defineWorkflowTool({+ description: "Stage a service deploy and report its plan digest.",+ inputSchema: z.strictObject({ service: z.string() }),+ async task({ service }) {+ "use workflow";++ return await stageDeploy(service);+ },+});diff --git a/e2e/fixtures/agent-workflow-tools/agent/tools/approve_rollout.ts b/e2e/fixtures/agent-workflow-tools/agent/tools/approve_rollout.tsnew file mode 100644index 000000000..e39337f6b--- /dev/null+++ b/e2e/fixtures/agent-workflow-tools/agent/tools/approve_rollout.ts@@ -0,0 +1,23 @@+import { defineWorkflowTool } from "eve/tools";+import { z } from "zod";++import { describePlan } from "../lib/plan.ts";++/** A task that asks a person to approve a rollout while the conversation continues. */+export default defineWorkflowTool({+ description: "Ask for approval to roll out a service, then report the decision.",+ inputSchema: z.strictObject({ service: z.string() }),+ async task({ service }, ctx) {+ "use workflow";++ const answer = await ctx.ask({+ display: "confirmation",+ options: [+ { id: "approve", label: "Roll out", style: "primary" },+ { id: "cancel", label: "Not now" },+ ],+ prompt: `Roll out ${describePlan(service)}?`,+ });+ return { approved: answer.status === "answered" && answer.optionId === "approve", service };+ },+});diff --git a/e2e/fixtures/agent-workflow-tools/agent/tools/canary_deploy.ts b/e2e/fixtures/agent-workflow-tools/agent/tools/canary_deploy.tsnew file mode 100644index 000000000..da413efdf--- /dev/null+++ b/e2e/fixtures/agent-workflow-tools/agent/tools/canary_deploy.ts@@ -0,0 +1,15 @@+import { defineWorkflowTool } from "eve/tools";+import { sleep } from "workflow";+import { z } from "zod";++/** A task that watches a canary far longer than any eval runs, so only a cancel ends it. */+export default defineWorkflowTool({+ description: "Roll out a canary for a service and watch it for an hour.",+ inputSchema: z.strictObject({ service: z.string() }),+ async task({ service }) {+ "use workflow";++ await sleep("1h");+ return { healthy: true, service };+ },+});diff --git a/e2e/fixtures/agent-workflow-tools/agent/tools/collect_notes.ts b/e2e/fixtures/agent-workflow-tools/agent/tools/collect_notes.tsnew file mode 100644index 000000000..d43adc7c8--- /dev/null+++ b/e2e/fixtures/agent-workflow-tools/agent/tools/collect_notes.ts@@ -0,0 +1,22 @@+import { defineWorkflowTool } from "eve/tools";+import { z } from "zod";++/**+ * Resumable task that collects notes on the rollout. A note sent with `more`+ * waits for the next one, so a single reply answers both calls.+ */+export default defineWorkflowTool({+ description: "Collect notes on the rollout; set more when another note follows.",+ inputSchema: z.strictObject({ more: z.boolean().optional(), note: z.string() }),+ async serve(receive, ctx) {+ "use workflow";++ const notes: string[] = [];+ for (;;) {+ const { input } = await receive();+ notes.push(input.note);+ if (input.more === true) continue;+ ctx.reply({ notes });+ }+ },+});diff --git a/e2e/fixtures/agent-workflow-tools/agent/tools/escalate_deploy.ts b/e2e/fixtures/agent-workflow-tools/agent/tools/escalate_deploy.tsindex 1e124dfd7..06817e468 100644--- a/e2e/fixtures/agent-workflow-tools/agent/tools/escalate_deploy.ts+++ b/e2e/fixtures/agent-workflow-tools/agent/tools/escalate_deploy.ts@@ -5,7 +5,7 @@ import { z } from "zod";import { describePlan } from "../lib/plan.ts";/**- * `ask` returns the hook, so the question can be raced against a deadline: if+ * `ask` returns a promise, so the question can be raced against a deadline: if* nobody answers before the sleep, the run withdraws the request and returns* a timeout instead of parking forever.*/diff --git a/e2e/fixtures/agent-workflow-tools/agent/tools/hold_deploy.ts b/e2e/fixtures/agent-workflow-tools/agent/tools/hold_deploy.tsindex 9fe4bf474..f1d96d7ca 100644--- a/e2e/fixtures/agent-workflow-tools/agent/tools/hold_deploy.ts+++ b/e2e/fixtures/agent-workflow-tools/agent/tools/hold_deploy.ts@@ -3,16 +3,22 @@ import { sleep } from "workflow";import { z } from "zod";/**- * Parks the turn on a long durable sleep until explicitly cancelled. Exercises- * cancellation cascading into a workflow tool run.+ * Parks the turn on a long durable sleep and rejects once the call's+ * `abortSignal` aborts. Exercises a cancel cascading into a workflow tool run,+ * and a steering message stopping a body that rejects.*/export default defineWorkflowTool({- description: "Hold a deploy open until cancelled.",+ description: "Hold a deploy open until the conversation moves on.",inputSchema: z.strictObject({ service: z.string() }),- async execute({ service }) {+ async execute({ service }, ctx) {"use workflow";- await sleep("10m");+ const stopped = new Promise<never>((_, reject) =>+ ctx.abortSignal.addEventListener("abort", () => reject(ctx.abortSignal.reason), {+ once: true,+ }),+ );+ await Promise.race([sleep("10m"), stopped]);return { held: service };},});diff --git a/e2e/fixtures/agent-workflow-tools/agent/tools/offer_deploy.ts b/e2e/fixtures/agent-workflow-tools/agent/tools/offer_deploy.tsnew file mode 100644index 000000000..39659cbf7--- /dev/null+++ b/e2e/fixtures/agent-workflow-tools/agent/tools/offer_deploy.ts@@ -0,0 +1,28 @@+import { defineWorkflowTool } from "eve/tools";+import { z } from "zod";++import { describePlan } from "../lib/plan.ts";++/**+ * Offers a deploy. A steering message aborts the call's `abortSignal`, which+ * withdraws the question, so the offer lapses once the conversation moves on.+ */+export default defineWorkflowTool({+ description: "Offer to deploy a service now; the offer lapses when a new message arrives.",+ inputSchema: z.strictObject({ service: z.string() }),+ async execute({ service }, ctx) {+ "use workflow";++ const answer = await ctx.ask({+ display: "confirmation",+ options: [+ { id: "approve", label: "Deploy now", style: "primary" },+ { id: "cancel", label: "Not now" },+ ],+ prompt: `Apply ${describePlan(service)} now?`,+ });+ if (answer.status === "cancelled") return { offer: "withdrawn", service };+ const approved = answer.status === "answered" && answer.optionId === "approve";+ return { offer: approved ? "accepted" : "declined", service };+ },+});diff --git a/e2e/fixtures/agent-workflow-tools/agent/tools/revise_plan.ts b/e2e/fixtures/agent-workflow-tools/agent/tools/revise_plan.tsnew file mode 100644index 000000000..33352bc24--- /dev/null+++ b/e2e/fixtures/agent-workflow-tools/agent/tools/revise_plan.ts@@ -0,0 +1,29 @@+import { defineWorkflowTool } from "eve/tools";+import { z } from "zod";++import { revise } from "../lib/plan-revisions.ts";++/**+ * Resumable task: one run keeps the plan across calls made with its taskId.+ * Each revision replies with every revision so far, so a result shows whether+ * later calls reached the same run.+ */+export default defineWorkflowTool({+ description: "Draft a rollout plan and revise it on request.",+ inputSchema: z.strictObject({ request: z.string() }),+ async serve(receive, ctx) {+ "use workflow";++ const revisions: string[] = [];+ for (;;) {+ const { input, abortSignal } = await receive();+ try {+ revisions.push(await revise(input.request, abortSignal));+ ctx.reply({ revisions });+ } catch (error) {+ // A cancel settles this stretch's calls; catching its abort keeps the task available.+ if (!abortSignal.aborted) throw error;+ }+ }+ },+});diff --git a/e2e/fixtures/agent-workflow-tools/agent/tools/sign_off_plan.ts b/e2e/fixtures/agent-workflow-tools/agent/tools/sign_off_plan.tsnew file mode 100644index 000000000..589f24f10--- /dev/null+++ b/e2e/fixtures/agent-workflow-tools/agent/tools/sign_off_plan.ts@@ -0,0 +1,38 @@+import { defineWorkflowTool } from "eve/tools";+import { z } from "zod";++import { describePlan, SIGN_OFF_REQUEST } from "../lib/plan.ts";++/**+ * Resumable task that asks a person to sign off on the rollout plan. Its+ * question takes the stretch's `abortSignal`, so a cancel withdraws it, and+ * the task keeps serving later calls.+ */+export default defineWorkflowTool({+ description: "Ask a person to sign off on the rollout plan, or record a note on it.",+ inputSchema: z.strictObject({ request: z.string() }),+ async serve(receive, ctx) {+ "use workflow";++ const notes: string[] = [];+ for (;;) {+ const { input } = await receive();+ if (input.request !== SIGN_OFF_REQUEST) {+ notes.push(input.request);+ ctx.reply({ notes });+ continue;+ }+ const answer = await ctx.ask({+ display: "confirmation",+ options: [+ { id: "approve", label: "Sign off", style: "primary" },+ { id: "cancel", label: "Needs changes" },+ ],+ prompt: `Sign off on ${describePlan("api")}?`,+ });+ // The cancel that withdrew the question settled its call, which takes no reply.+ if (answer.status === "cancelled") continue;+ ctx.reply({ signedOff: answer.status === "answered" && answer.optionId === "approve" });+ }+ },+});diff --git a/e2e/fixtures/agent-workflow-tools/agent/tools/sleep.ts b/e2e/fixtures/agent-workflow-tools/agent/tools/sleep.tsnew file mode 100644index 000000000..5d4aaf642--- /dev/null+++ b/e2e/fixtures/agent-workflow-tools/agent/tools/sleep.ts@@ -0,0 +1,3 @@+import { sleep } from "eve/tools/sleep";++export default sleep();diff --git a/e2e/fixtures/agent-workflow-tools/agent/tools/stage_deploy.ts b/e2e/fixtures/agent-workflow-tools/agent/tools/stage_deploy.tsnew file mode 100644index 000000000..8d305bc84--- /dev/null+++ b/e2e/fixtures/agent-workflow-tools/agent/tools/stage_deploy.ts@@ -0,0 +1,15 @@+import { defineWorkflowTool } from "eve/tools";+import { z } from "zod";++import { stageDeploy } from "../lib/stage.ts";++/** A task: the model gets a receipt at once, and the staged plan arrives as its result. */+export default defineWorkflowTool({+ description: "Stage a service deploy and report its plan digest.",+ inputSchema: z.strictObject({ service: z.string() }),+ async task({ service }) {+ "use workflow";++ return await stageDeploy(service);+ },+});diff --git a/e2e/fixtures/agent-workflow-tools/evals/canary-deploy.cancel.eval.ts b/e2e/fixtures/agent-workflow-tools/evals/canary-deploy.cancel.eval.tsnew file mode 100644index 000000000..d9852abd8--- /dev/null+++ b/e2e/fixtures/agent-workflow-tools/evals/canary-deploy.cancel.eval.ts@@ -0,0 +1,22 @@+import { defineEval } from "eve/evals";++/**+ * `canary_deploy` is a task that would watch its canary for an hour.+ * `task_cancel` stops it at once: the call settles as cancelled, no result is+ * ever delivered, and with nothing left working the turn ends.+ */+export default defineEval({+ description: "task_cancel stops a working task, which then never reports a result.",+ async test(t) {+ const turn = await t.send("WORKFLOW-CANARY-CANCEL");+ turn.expectOk();++ turn.event("task.started", { count: 1, data: { callId: "canary", name: "canary_deploy" } });+ turn.calledTool("task_cancel", { count: 1, output: { status: "cancelled" } });+ turn.event("task.settled", { count: 1, data: { callId: "canary", status: "cancelled" } });+ turn.notEvent("task.settled", { data: { status: "completed" } });+ turn.event("turn.completed", { count: 1 });+ turn.messageIncludes('WORKFLOW-CANARY-RESULT {"status":"cancelled"}');+ t.noFailedActions();+ },+});diff --git a/e2e/fixtures/agent-workflow-tools/evals/collect-notes.reply.eval.ts b/e2e/fixtures/agent-workflow-tools/evals/collect-notes.reply.eval.tsnew file mode 100644index 000000000..2cbbbccaf--- /dev/null+++ b/e2e/fixtures/agent-workflow-tools/evals/collect-notes.reply.eval.ts@@ -0,0 +1,31 @@+import { defineEval } from "eve/evals";++const NOTES = { notes: ["draft", "final"] };++/**+ * `collect_notes` is a `serve` tool that holds a note sent with `more` until+ * the next one arrives, then replies once for both. The model sends two notes+ * to one task and waits: the reply settles both calls in one step, so the wait+ * reports the task done, with nothing still working, and the model receives+ * the reply once.+ */+export default defineEval({+ description: "One reply that answers two calls settles both together and reaches the model once.",+ async test(t) {+ const turn = await t.send("WORKFLOW-NOTES-BATCH");+ turn.expectOk();+ turn.calledTool("collect_notes", { count: 2 });+ turn.calledTool("task_wait", {+ count: 1,+ output: /^collect_notes-\w{6} completed; its result follows\.$/u,+ });+ for (const callId of ["notes-draft", "notes-final"]) {+ turn.event("task.settled", {+ count: 1,+ data: { callId, output: NOTES, status: "completed" },+ });+ }+ turn.messageIncludes(`WORKFLOW-NOTES-RESULT 1 ${JSON.stringify(NOTES)}`);+ t.noFailedActions();+ },+});diff --git a/e2e/fixtures/agent-workflow-tools/evals/dynamic-skill-context.eval.ts b/e2e/fixtures/agent-workflow-tools/evals/dynamic-skill-context.eval.tsindex 27a4d8ec2..e9311c270 100644--- a/e2e/fixtures/agent-workflow-tools/evals/dynamic-skill-context.eval.ts+++ b/e2e/fixtures/agent-workflow-tools/evals/dynamic-skill-context.eval.ts@@ -28,15 +28,15 @@ function expectedAuth(actor: "alice" | "bob") {};}-/** The child's reply: a `subagent.completed` event for the model's agent tool, the tool result for `ctx.agent`. */+/** The child's reply: the agent tool's task result, or the waiting tool's result for `ctx.agent`. */function readChildOutput(turn: EveEvalTurn, mode: "direct" | "waiting"): string {if (mode === "waiting") {const output = turn.toolCalls.find((call) => call.name === "blocking_agent")?.output;if (typeof output !== "string") throw new Error("The waiting tool's child reply is missing.");return output;}- const completion = turn.events.find((event) => event.type === "subagent.completed");- if (completion?.type !== "subagent.completed")+ const completion = turn.events.find((event) => event.type === "task.settled");+ if (completion?.type !== "task.settled" || typeof completion.data.output !== "string")throw new Error("The delegated child's completion event is missing.");return completion.data.output;}diff --git a/e2e/fixtures/agent-workflow-tools/evals/held-turn.child.eval.ts b/e2e/fixtures/agent-workflow-tools/evals/held-turn.child.eval.tsnew file mode 100644index 000000000..75115e9fb--- /dev/null+++ b/e2e/fixtures/agent-workflow-tools/evals/held-turn.child.eval.ts@@ -0,0 +1,43 @@+import { defineEval } from "eve/evals";++import { STAGER_INTERIM_MESSAGE } from "../task-scenario-text";++const CHILD_REPLY = /^WORKFLOW-CHILD-STAGED /u;++/**+ * The root delegates to `workflow-stager`, whose own turn holds on a staging+ * task after writing text. The child's turn parks with `turn.waiting` as any+ * held turn does, but its held text step reports `"tool-calls"`, so the+ * parent's task receives only the child's final reply.+ */+export default defineEval({+ description: "A child session's held turn reports tool-calls and returns only its final reply.",+ async test(t) {+ const parent = await t.send("WORKFLOW-DELEGATE-STAGE");+ parent.expectOk();+ const started = parent.events.find(+ (event) => event.type === "agent.started" && event.data.name === "workflow-stager",+ );+ if (started?.type !== "agent.started") throw new Error("workflow-stager never started.");++ const child = await t.target.watchTurn(started.data.sessionId).result();+ child.expectOk();+ child.event("message.completed", {+ count: 1,+ data: { finishReason: "tool-calls", message: STAGER_INTERIM_MESSAGE },+ });+ child.event("message.completed", {+ count: 1,+ data: { finishReason: "stop", message: CHILD_REPLY },+ });+ child.event("turn.waiting", { count: 1 });+ child.event("turn.completed", { count: 1 });++ parent.event("task.settled", {+ count: 1,+ data: { callId: "delegate", output: CHILD_REPLY, status: "completed" },+ });+ parent.messageIncludes("WORKFLOW-DELEGATE-RESULT WORKFLOW-CHILD-STAGED");+ t.noFailedActions();+ },+});diff --git a/e2e/fixtures/agent-workflow-tools/evals/held-turn.mcp.eval.ts b/e2e/fixtures/agent-workflow-tools/evals/held-turn.mcp.eval.tsnew file mode 100644index 000000000..3276665a6--- /dev/null+++ b/e2e/fixtures/agent-workflow-tools/evals/held-turn.mcp.eval.ts@@ -0,0 +1,39 @@+import { defineEval } from "eve/evals";+import { equals, satisfies } from "eve/evals/expect";++import { callMcpTool, pollInvocation, type McpInvocation } from "./mcp-client";++/**+ * An MCP client starts the delegating script with `agent_start`. The root+ * agent's turn holds while `workflow-stager` works, so its interim text is not+ * the answer: `agent_get` reports `working` until the turn really ends, then+ * `completed` with the final reply.+ */+export default defineEval({+ description: "MCP agent_start with a delegating agent reports only the final reply.",+ async test(t) {+ const started = await callMcpTool(t.target, "agent_start", {+ message: "WORKFLOW-DELEGATE-STAGE Stage api through workflow-stager and report back.",+ });+ const states = await pollInvocation(t.target, started.invocationId, 60_000);+ const settled = states.at(-1)!;++ await t.require(settled.status, equals("completed"));+ t.check(+ settled.result,+ satisfies(+ (result: unknown) =>+ typeof result === "string" &&+ result.startsWith("WORKFLOW-DELEGATE-RESULT WORKFLOW-CHILD-STAGED "),+ "the completed result is the final reply",+ ),+ );+ t.check(+ states.slice(0, -1),+ satisfies(+ (earlier: readonly McpInvocation[]) => earlier.every((state) => state.status === "working"),+ "the invocation stays working while the turn is held",+ ),+ );+ },+});diff --git a/e2e/fixtures/agent-workflow-tools/evals/held-turn.question.eval.ts b/e2e/fixtures/agent-workflow-tools/evals/held-turn.question.eval.tsnew file mode 100644index 000000000..78f88113f--- /dev/null+++ b/e2e/fixtures/agent-workflow-tools/evals/held-turn.question.eval.ts@@ -0,0 +1,54 @@+import { defineEval } from "eve/evals";+import { equals, includes } from "eve/evals/expect";++import { staysInOneTurn } from "./held-turn.shared";++/**+ * `approve_rollout` is a task that asks a person to approve the rollout. The+ * model ends its step while the task works, so the turn holds, and the task's+ * question parks the open turn: `input.requested`, then `turn.waiting`, with+ * no turn end. `send()` stops there because a question is pending; answering+ * it resumes the same turn, which completes once with the task's result.+ */+export default defineEval({+ description:+ "A task's question during a held turn parks the turn, which completes once answered.",+ async test(t) {+ const parked = await t.send("WORKFLOW-ROLLOUT-HOLD");+ t.check(parked.status, equals("waiting")).label("send() stops at the pending question");+ // The hold may park the turn before or after the task asks; the question's+ // own `turn.waiting` is what ends `send()`.+ parked.eventsSatisfy("the task's question parks the open turn", (events) => {+ const question = events.findIndex(+ (event) => event.type === "input.requested" && event.data.taskId !== undefined,+ );+ return question >= 0 && events.at(-1)?.type === "turn.waiting";+ });+ parked.notEvent("turn.completed");+ parked.notEvent("session.waiting");+ const request = parked.session.requireInputRequest({ toolName: "approve_rollout" });++ const answered = await parked.session.respond([+ { optionId: "approve", requestId: request.requestId },+ ]);+ answered.expectOk();+ answered.event("input.resolved", {+ count: 1,+ data: { resolutions: [{ outcome: "answered", requestId: request.requestId }] },+ });+ answered.event("task.settled", {+ count: 1,+ data: { callId: "rollout", output: { approved: true, service: "api" }, status: "completed" },+ });+ answered.notEvent("turn.started");+ answered.event("turn.completed", { count: 1 });+ t.check(answered.message, includes(/^WORKFLOW-ROLLOUT-RESULT \{"approved":true/u)).label(+ "the answered turn's result is the final reply",+ );++ t.event("turn.started", { count: 1 });+ t.event("turn.completed", { count: 1 });+ t.eventsSatisfy("the parked turn resumes under its own id", staysInOneTurn);+ t.noFailedActions();+ },+});diff --git a/e2e/fixtures/agent-workflow-tools/evals/held-turn.root.eval.ts b/e2e/fixtures/agent-workflow-tools/evals/held-turn.root.eval.tsnew file mode 100644index 000000000..6d4c433e1--- /dev/null+++ b/e2e/fixtures/agent-workflow-tools/evals/held-turn.root.eval.ts@@ -0,0 +1,41 @@+import { defineEval } from "eve/evals";+import { includes } from "eve/evals/expect";++import { STAGE_INTERIM_MESSAGE } from "../task-scenario-text";+import { staysInOneTurn } from "./held-turn.shared";++/**+ * The model starts `stage_deploy`, then ends its step with text instead of+ * waiting. The turn rule holds the turn: the text completes as an ordinary+ * message, the stream reports `turn.waiting`, and the same turn resumes with+ * the result and completes once. `send()` reads through the wait, so the+ * turn's result is the final reply, not the text written before it.+ */+export default defineEval({+ description: "A root session's held turn parks with turn.waiting and reports its final reply.",+ async test(t) {+ const turn = await t.send("WORKFLOW-STAGE-HOLD");+ turn.expectOk();++ turn.event("message.completed", {+ count: 1,+ data: { finishReason: "stop", message: STAGE_INTERIM_MESSAGE },+ });+ turn.event("turn.waiting", { count: 1 });+ turn.eventOrder([+ { data: { message: STAGE_INTERIM_MESSAGE }, type: "message.completed" },+ { type: "turn.waiting" },+ { data: { status: "completed" }, type: "task.settled" },+ { data: { message: /^WORKFLOW-STAGE-RESULT / }, type: "message.completed" },+ { type: "turn.completed" },+ ]);+ turn.event("turn.started", { count: 1 });+ turn.event("turn.completed", { count: 1 });+ turn.eventsSatisfy("the held turn resumes under its own id", staysInOneTurn);+ turn.notCalledTool("task_wait");+ t.check(turn.message, includes(/^WORKFLOW-STAGE-RESULT \{.*"plan":"deploy api"/u)).label(+ "the turn's result is the final reply",+ );+ t.noFailedActions();+ },+});diff --git a/e2e/fixtures/agent-workflow-tools/evals/held-turn.schedule.eval.ts b/e2e/fixtures/agent-workflow-tools/evals/held-turn.schedule.eval.tsnew file mode 100644index 000000000..834094ee5--- /dev/null+++ b/e2e/fixtures/agent-workflow-tools/evals/held-turn.schedule.eval.ts@@ -0,0 +1,37 @@+import { defineEval } from "eve/evals";++import { STAGE_INTERIM_MESSAGE } from "../task-scenario-text";++/**+ * The `staged-deploy` schedule runs the held-turn script. A schedule's turn+ * parks with `turn.waiting` as any held turn does, but its held text step+ * reports `"tool-calls"`, so a channel would post only the final reply.+ *+ * Schedule dispatch is a dev route, so deployed targets skip this eval.+ */+export default defineEval({+ description: "A schedule's held turn reports tool-calls and posts only its final reply.",+ async test(t) {+ if (!t.target.capabilities.devRoutes) {+ t.skip("Target has no dev routes; schedule dispatch is dev-only.");+ }++ const dispatch = await t.target.dispatchSchedule("staged-deploy");+ const sessionId = dispatch.sessionIds[0];+ if (sessionId === undefined) throw new Error("The schedule started no session.");++ const session = await t.target.attachSession(sessionId);+ session.succeeded();+ session.event("message.completed", {+ count: 1,+ data: { finishReason: "tool-calls", message: STAGE_INTERIM_MESSAGE },+ });+ session.event("message.completed", {+ count: 1,+ data: { finishReason: "stop", message: /^WORKFLOW-STAGE-RESULT / },+ });+ session.event("turn.waiting", { count: 1 });+ session.event("task.settled", { count: 1, data: { status: "completed" } });+ session.event("turn.completed", { count: 1 });+ },+});diff --git a/e2e/fixtures/agent-workflow-tools/evals/held-turn.shared.ts b/e2e/fixtures/agent-workflow-tools/evals/held-turn.shared.tsnew file mode 100644index 000000000..8e6a3467b--- /dev/null+++ b/e2e/fixtures/agent-workflow-tools/evals/held-turn.shared.ts@@ -0,0 +1,12 @@+import type { MessageStreamEvent } from "eve/client";++/** Whether every turn-scoped event in `events` belongs to one turn. */+export function staysInOneTurn(events: readonly MessageStreamEvent[]): boolean {+ const turnIds = new Set<string>();+ for (const event of events) {+ const data: unknown = "data" in event ? event.data : undefined;+ if (typeof data !== "object" || data === null || !("turnId" in data)) continue;+ if (typeof data.turnId === "string") turnIds.add(data.turnId);+ }+ return turnIds.size === 1;+}diff --git a/e2e/fixtures/agent-workflow-tools/evals/hold-deploy.steer.eval.ts b/e2e/fixtures/agent-workflow-tools/evals/hold-deploy.steer.eval.tsnew file mode 100644index 000000000..8ce03e976--- /dev/null+++ b/e2e/fixtures/agent-workflow-tools/evals/hold-deploy.steer.eval.ts@@ -0,0 +1,36 @@+import { defineEval } from "eve/evals";++/**+ * `hold_deploy` rejects once its `abortSignal` aborts. A steering message+ * aborts it while the turn waits on the call, and the call settles as+ * `{ interrupted: true }` instead of failing. The same turn continues with+ * Alice's message.+ */+export default defineEval({+ description: "A steering message stops a waited workflow tool whose body rejects on abort.",+ async test(t) {+ const session = await t.session();+ const live = await session.start("WORKFLOW-HOLD-START");+ await live.waitForEvent("actions.requested", {+ data: {+ actions: (actions) =>+ actions.some(+ (action) => action.kind === "tool-call" && action.toolName === "hold_deploy",+ ),+ },+ });++ const update = await live.session.start("Alice asks Bob to read the rollout notes first.", {+ turnPolicy: "steer",+ });+ const turn = await live.result();+ await update.result();++ turn.calledTool("hold_deploy", { count: 1, output: { interrupted: true } });+ turn.event("message.received", { count: 2 });+ turn.event("turn.completed", { count: 1 });+ turn.notEvent("turn.cancelled");+ turn.messageIncludes('WORKFLOW-HOLD-RESULT {"interrupted":true}');+ t.noFailedActions();+ },+});diff --git a/e2e/fixtures/agent-workflow-tools/evals/mcp-client.ts b/e2e/fixtures/agent-workflow-tools/evals/mcp-client.tsnew file mode 100644index 000000000..d200fce10--- /dev/null+++ b/e2e/fixtures/agent-workflow-tools/evals/mcp-client.ts@@ -0,0 +1,81 @@+import type { EveEvalTargetHandle } from "eve/evals";++const MCP_PATH = "/eve/v1/mcp";+const MCP_PROTOCOL_VERSION = "2026-07-28";+const POLL_INTERVAL_MS = 500;++/** A durable invocation as the MCP channel's `agent_start` and `agent_get` report it. */+export interface McpInvocation {+ readonly invocationId: string;+ readonly result?: unknown;+ readonly status: string;+}++/** Calls one of the MCP channel's tools and returns its structured invocation state. */+export async function callMcpTool(+ target: EveEvalTargetHandle,+ name: string,+ args: Readonly<Record<string, unknown>>,+): Promise<McpInvocation> {+ const response = await target.fetch(MCP_PATH, {+ body: JSON.stringify({+ id: crypto.randomUUID(),+ jsonrpc: "2.0",+ method: "tools/call",+ params: { _meta: modernRequestMeta(), arguments: args, name },+ }),+ headers: {+ accept: "application/json, text/event-stream",+ "content-type": "application/json",+ "mcp-method": "tools/call",+ "mcp-name": name,+ "mcp-protocol-version": MCP_PROTOCOL_VERSION,+ },+ method: "POST",+ });+ const envelope = (await readJsonRpcResponse(response)) as {+ readonly result?: { readonly isError?: boolean; readonly structuredContent?: McpInvocation };+ };+ const result = envelope.result;+ if (result === undefined || result.isError === true || result.structuredContent === undefined) {+ throw new Error(`MCP tool ${name} failed: ${JSON.stringify(envelope)}`);+ }+ return result.structuredContent;+}++/** Polls `agent_get` until the invocation leaves `working`; returns every state it read. */+export async function pollInvocation(+ target: EveEvalTargetHandle,+ invocationId: string,+ timeoutMs: number,+): Promise<readonly McpInvocation[]> {+ const states: McpInvocation[] = [];+ const deadline = Date.now() + timeoutMs;+ while (Date.now() < deadline) {+ const state = await callMcpTool(target, "agent_get", { invocationId });+ states.push(state);+ if (state.status !== "working") return states;+ await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));+ }+ throw new Error(`Invocation ${invocationId} was still working after ${String(timeoutMs)} ms.`);+}++function modernRequestMeta(): Record<string, unknown> {+ return {+ "io.modelcontextprotocol/clientCapabilities": {},+ "io.modelcontextprotocol/clientInfo": { name: "eve-e2e", version: "0.0.0" },+ "io.modelcontextprotocol/protocolVersion": MCP_PROTOCOL_VERSION,+ };+}++/** Reads a JSON-RPC response sent as plain JSON or as one server-sent event. */+async function readJsonRpcResponse(response: Response): Promise<unknown> {+ const body = await response.text();+ if (!response.ok) throw new Error(`MCP HTTP ${String(response.status)}: ${body}`);+ if (!response.headers.get("content-type")?.includes("text/event-stream")) {+ return JSON.parse(body);+ }+ const data = body.split("\n").find((line) => line.startsWith("data: "));+ if (data === undefined) throw new Error("The MCP response carried no server-sent event.");+ return JSON.parse(data.slice("data: ".length));+}diff --git a/e2e/fixtures/agent-workflow-tools/evals/offer-deploy.withdraw.eval.ts b/e2e/fixtures/agent-workflow-tools/evals/offer-deploy.withdraw.eval.tsnew file mode 100644index 000000000..6ab363cf4--- /dev/null+++ b/e2e/fixtures/agent-workflow-tools/evals/offer-deploy.withdraw.eval.ts@@ -0,0 +1,39 @@+import { defineEval } from "eve/evals";++/**+ * A steering message aborts the `abortSignal` of the `offer_deploy` call the+ * turn waits on, which withdraws its question: `input.resolved` reports it as+ * cancelled, and the call returns that the offer was withdrawn.+ *+ * The withdrawal belongs to the parked turn, not to Alice's message, so the+ * eval follows the session stream to see it, as a channel does.+ */+export default defineEval({+ description: "A steering message withdraws a waited call's question as cancelled.",+ async test(t) {+ const parked = await t.send("WORKFLOW-OFFER-START");+ const request = parked.session.requireInputRequest({ toolName: "offer_deploy" });+ const afterQuestion = parked.session.state.streamIndex;++ const moved = await parked.session.send(+ "Alice wants Bob to review the plan before any deploy.",+ { turnPolicy: "steer" },+ );+ moved.expectOk();+ moved.calledTool("offer_deploy", { count: 1, output: { offer: "withdrawn" } });+ moved.messageIncludes('WORKFLOW-OFFER-RESULT {"offer":"withdrawn","service":"api"}');++ const followed = await t.target+ .watchTurn(parked.sessionId, { startIndex: afterQuestion })+ .result();+ followed.event("input.resolved", {+ count: 1,+ data: { resolutions: [{ outcome: "cancelled", requestId: request.requestId }] },+ });+ followed.eventOrder([+ { type: "input.resolved" },+ { data: { result: { toolName: "offer_deploy" } }, type: "action.result" },+ ]);+ t.noFailedActions();+ },+});diff --git a/e2e/fixtures/agent-workflow-tools/evals/revise-plan.serve.eval.ts b/e2e/fixtures/agent-workflow-tools/evals/revise-plan.serve.eval.tsnew file mode 100644index 000000000..328c65d4a--- /dev/null+++ b/e2e/fixtures/agent-workflow-tools/evals/revise-plan.serve.eval.ts@@ -0,0 +1,47 @@+import { defineEval } from "eve/evals";++/**+ * `revise_plan` is a `serve` tool whose run keeps every revision. Turn one+ * drafts the plan and ends with the task idle. Turn two sends the task work+ * that holds it busy, cancels that work, and revises the same task again: the+ * final result lists both revisions, so the body caught the cancelled+ * stretch's abort and kept its run and state.+ */+export default defineEval({+ description:+ "A resumable task is continued by taskId, cancelled, and continued again with its state intact.",+ timeoutMs: 90_000,+ async test(t) {+ const drafted = await t.send("WORKFLOW-PLAN-START");+ drafted.expectOk();+ drafted.calledTool("revise_plan", {+ count: 1,+ output: /^Started task revise_plan-\w{6}\. Call revise_plan again with taskId/u,+ });+ drafted.messageIncludes('WORKFLOW-PLAN-RESULT {"revisions":["draft"]}');++ const revised = await drafted.session.send("WORKFLOW-PLAN-REVISE");+ revised.expectOk();+ revised.calledTool("revise_plan", { count: 2, output: /^Sent to task revise_plan-\w{6}\.$/u });+ revised.calledTool("task_wait", { output: /^Stopped waiting after/u });+ revised.calledTool("task_cancel", { count: 1, output: { status: "cancelled" } });+ revised.event("task.settled", { count: 1, data: { callId: "plan-hold", status: "cancelled" } });+ revised.event("task.settled", {+ count: 1,+ data: {+ callId: "plan-final",+ output: { revisions: ["draft", "final"] },+ status: "completed",+ },+ });+ revised.messageIncludes('WORKFLOW-PLAN-RESULT {"revisions":["draft","final"]}');++ t.eventsSatisfy("every call reaches the one task the draft started", (events) => {+ const taskIds = events.flatMap((event) =>+ event.type === "task.started" ? [event.data.taskId] : [],+ );+ return taskIds.length === 3 && new Set(taskIds).size === 1;+ });+ t.noFailedActions();+ },+});diff --git a/e2e/fixtures/agent-workflow-tools/evals/sign-off-plan.cancel.eval.ts b/e2e/fixtures/agent-workflow-tools/evals/sign-off-plan.cancel.eval.tsnew file mode 100644index 000000000..3c50d71f4--- /dev/null+++ b/e2e/fixtures/agent-workflow-tools/evals/sign-off-plan.cancel.eval.ts@@ -0,0 +1,65 @@+import { defineEval } from "eve/evals";+import { equals } from "eve/evals/expect";++const ALICE_REWORK =+ "WORKFLOW-SIGNOFF-CANCEL Alice wants to rework the plan before anyone signs off.";++/**+ * `sign_off_plan` is a `serve` tool whose stretch asks a person to sign off.+ * The turn holds on the task until its question parks it. Alice then changes+ * the plan: the model cancels the task, which asks the session to withdraw+ * the question, and sends the same task a note. The session withdraws the+ * question, reports it `cancelled`, and tells the run, so the body returns to+ * `receive()` and answers the note on its own run.+ */+export default defineEval({+ description: "Cancelling a resumable task withdraws its question and keeps the task serving.",+ timeoutMs: 90_000,+ async test(t) {+ const parked = await t.send("WORKFLOW-SIGNOFF-HOLD");+ t.check(parked.status, equals("waiting")).label("send() stops at the pending question");+ const request = parked.session.requireInputRequest({ toolName: "sign_off_plan" });+ const afterQuestion = parked.session.state.streamIndex;++ const reworked = await parked.session.send(ALICE_REWORK, { turnPolicy: "steer" });+ reworked.expectOk();+ reworked.calledTool("task_cancel", { count: 1, output: { status: "cancelled" } });+ reworked.messageIncludes('WORKFLOW-SIGNOFF-RESULT {"notes":["rework the plan first"]}');++ // Follow the stream as a channel does: the question resolves once, as withdrawn.+ const followed = await t.target+ .watchTurn(parked.sessionId, { startIndex: afterQuestion })+ .result();+ followed.event("input.resolved", {+ count: 1,+ data: { resolutions: [{ outcome: "cancelled", requestId: request.requestId }] },+ });+ followed.event("task.settled", { count: 1, data: { callId: "signoff", status: "cancelled" } });+ followed.event("task.settled", {+ count: 1,+ data: {+ callId: "signoff-note",+ output: { notes: ["rework the plan first"] },+ status: "completed",+ },+ });+ followed.eventOrder([+ { type: "input.resolved" },+ { data: { callId: "signoff-note" }, type: "task.settled" },+ ]);++ // The watched stream repeats the session's events, so count distinct calls.+ t.eventsSatisfy("every call reaches the one task the sign-off started", (events) => {+ const starts = events.flatMap((event) => (event.type === "task.started" ? [event.data] : []));+ const callIds = new Set(starts.map((start) => start.callId));+ const taskIds = new Set(starts.map((start) => start.taskId));+ return (+ callIds.size === 2 &&+ callIds.has("signoff") &&+ callIds.has("signoff-note") &&+ taskIds.size === 1+ );+ });+ t.noFailedActions();+ },+});diff --git a/e2e/fixtures/agent-workflow-tools/evals/sleep.steer.eval.ts b/e2e/fixtures/agent-workflow-tools/evals/sleep.steer.eval.tsnew file mode 100644index 000000000..4825b7052--- /dev/null+++ b/e2e/fixtures/agent-workflow-tools/evals/sleep.steer.eval.ts@@ -0,0 +1,36 @@+import { defineEval } from "eve/evals";++/**+ * The provided `sleep` tool races its timer against the call's+ * `abortSignal`. A steering message ends a ten-minute sleep at once, and+ * the same turn continues with the message and the interrupted result.+ */+export default defineEval({+ description: "Steering ends a sleep early without cancelling the turn.",+ async test(t) {+ const session = await t.session();+ const live = await session.start("WORKFLOW-SLEEP-START");+ await live.waitForEvent("actions.requested", {+ data: {+ actions: (actions) =>+ actions.some((action) => action.kind === "tool-call" && action.toolName === "sleep"),+ },+ });++ const update = await live.session.start(+ "Alice has the numbers now, so there is no need to wait.",+ {+ turnPolicy: "steer",+ },+ );+ const turn = await live.result();+ await update.result();++ turn.calledTool("sleep", { count: 1, output: { interrupted: true } });+ turn.event("message.received", { count: 2 });+ turn.event("turn.completed", { count: 1 });+ turn.notEvent("turn.cancelled");+ turn.messageIncludes("WORKFLOW-SLEEP-RESULT Stopped early because a new message arrived.");+ t.noFailedActions();+ },+});diff --git a/e2e/fixtures/agent-workflow-tools/evals/stage-deploy.task.eval.ts b/e2e/fixtures/agent-workflow-tools/evals/stage-deploy.task.eval.tsnew file mode 100644index 000000000..a44e3afbf--- /dev/null+++ b/e2e/fixtures/agent-workflow-tools/evals/stage-deploy.task.eval.ts@@ -0,0 +1,33 @@+import { defineEval } from "eve/evals";++/**+ * `stage_deploy` defines `task()`. Its call returns a receipt, `task_wait`+ * parks the turn with `turn.waiting` until the task settles, and clients read+ * the outcome from `task.settled` while the result reaches the model before+ * the final reply.+ */+export default defineEval({+ description: "A task tool starts a task, task_wait waits on it, and its result is delivered.",+ async test(t) {+ const turn = await t.send("WORKFLOW-STAGE-WAIT");+ turn.expectOk();++ turn.calledTool("stage_deploy", { count: 1, output: /^Started task stage_deploy-\w{6}\.$/u });+ turn.event("task.started", { count: 1, data: { callId: "stage", name: "stage_deploy" } });+ turn.calledTool("task_wait", { count: 1, output: /stage_deploy-\w{6} completed/u });+ turn.event("task.settled", {+ count: 1,+ data: { callId: "stage", output: { plan: "deploy api" }, status: "completed" },+ });+ turn.eventOrder([+ { data: { callId: "stage" }, type: "task.started" },+ { type: "turn.waiting" },+ { data: { callId: "stage" }, type: "task.settled" },+ { data: { message: /^WORKFLOW-STAGE-RESULT / }, type: "message.completed" },+ { type: "turn.completed" },+ ]);+ turn.messageIncludes("WORKFLOW-STAGE-RESULT");+ turn.messageIncludes('"plan":"deploy api"');+ t.noFailedActions();+ },+});diff --git a/e2e/fixtures/agent-workflow-tools/evals/subagent-hook-context.eval.ts b/e2e/fixtures/agent-workflow-tools/evals/subagent-hook-context.eval.tsindex 09715a54f..661c2061a 100644--- a/e2e/fixtures/agent-workflow-tools/evals/subagent-hook-context.eval.ts+++ b/e2e/fixtures/agent-workflow-tools/evals/subagent-hook-context.eval.ts@@ -1,7 +1,7 @@import { defineEval } from "eve/evals";import type { SubagentHookObservation } from "../subagent-hook-audit";-// Only the model's agent tools publish subagent.* events; ctx.agent sessions publish agent.started.+// An agent tool call is a task: task.started and task.settled carry its callId.export default defineEval({description:"Delegation and later wildcard hooks continue after a typed hook writes parent state and throws.",@@ -33,10 +33,11 @@ export default defineEval({"both hook subscriptions receive the parent's exact child result once",(events) => {if (!Array.isArray(observations) || observations.length !== 4) return false;- const completion = events.find((event) => event.type === "subagent.completed");- if (completion?.type !== "subagent.completed") return false;- if (!completion.data.output.startsWith("WORKFLOW-CHILD:")) return false;- if (!initial.message?.includes(completion.data.output)) return false;+ const completion = events.find((event) => event.type === "task.settled");+ if (completion?.type !== "task.settled") return false;+ const output = completion.data.output;+ if (typeof output !== "string" || !output.startsWith("WORKFLOW-CHILD:")) return false;+ if (!initial.message?.includes(output)) return false;const records = observations as SubagentHookObservation[];return (records.every(@@ -46,13 +47,13 @@ export default defineEval({(["typed", "wildcard"] as const).every((subscriber) =>records.filter(- (record) => record.subscriber === subscriber && record.type === "subagent.called",+ (record) => record.subscriber === subscriber && record.type === "task.started",).length === 1 &&records.filter((record) =>record.subscriber === subscriber &&- record.type === "subagent.completed" &&- record.output === completion.data.output,+ record.type === "task.settled" &&+ record.output === output,).length === 1,));@@ -75,8 +76,8 @@ export default defineEval({record.sandboxCallId === record.callId,),);- t.event("subagent.called", { data: { name: "workflow-marker" }, count: 1 });- t.event("subagent.completed", { data: { subagentName: "workflow-marker" }, count: 1 });+ t.event("task.started", { data: { name: "workflow-marker" }, count: 1 });+ t.event("task.settled", { data: { status: "completed" }, count: 1 });t.notEvent("session.failed");t.notEvent("turn.failed");t.noFailedActions();diff --git a/e2e/fixtures/agent-workflow-tools/subagent-hook-audit.ts b/e2e/fixtures/agent-workflow-tools/subagent-hook-audit.tsindex c4a1c4245..8ed8b60a3 100644--- a/e2e/fixtures/agent-workflow-tools/subagent-hook-audit.ts+++ b/e2e/fixtures/agent-workflow-tools/subagent-hook-audit.ts@@ -3,7 +3,7 @@ import type { HookContext, HookEvent } from "eve/hooks";export interface SubagentHookObservation {readonly subscriber: "typed" | "wildcard";- readonly type: "subagent.called" | "subagent.completed";+ readonly type: "task.started" | "task.settled";readonly callId: string;readonly eventId: string;readonly sessionId: string;@@ -20,10 +20,7 @@ export async function recordSubagentHook(event: HookEvent,ctx: HookContext,): Promise<void> {- if (event.type !== "subagent.called" && event.type !== "subagent.completed") return;- if (event.type === "subagent.called" && ctx.session.id !== event.data.sessionId) {- throw new Error("Subagent hook received a different parent session.");- }+ if (event.type !== "task.started" && event.type !== "task.settled") return;const sandbox = await ctx.getSandbox();await sandbox.writeTextFile({path: `subagent-hook-${event.meta.id}-${subscriber}.txt`,@@ -37,10 +34,14 @@ export async function recordSubagentHook(callId: event.data.callId,eventId: event.meta.id,sessionId: ctx.session.id,- output: event.type === "subagent.completed" ? event.data.output : undefined,+ output: event.type === "task.settled" ? readOutput(event.data.output) : undefined,},]);if (subscriber === "typed") {throw new Error("Fixture subagent observer failed after recording its event.");}}++function readOutput(output: unknown): string | undefined {+ return typeof output === "string" ? output : undefined;+}diff --git a/e2e/fixtures/agent-workflow-tools/task-scenario-text.ts b/e2e/fixtures/agent-workflow-tools/task-scenario-text.tsnew file mode 100644index 000000000..a6efdc5fc--- /dev/null+++ b/e2e/fixtures/agent-workflow-tools/task-scenario-text.ts@@ -0,0 +1,17 @@+// Text the mock models write while a turn waits on a task, shared with the+// evals that check where it appears.++/** The root agent's text before its turn waits on `stage_deploy`. */+export const STAGE_INTERIM_MESSAGE = "Staging api now; I'll report back with the digest.";++/** The root agent's text before its turn waits on `approve_rollout`. */+export const ROLLOUT_INTERIM_MESSAGE = "Asked for approval to roll out api; I'll report back.";++/** The root agent's text before its turn waits on `sign_off_plan`. */+export const SIGN_OFF_INTERIM_MESSAGE = "Asked for sign-off on the api plan; I'll report back.";++/** The root agent's text before its turn waits on the `workflow-stager` agent. */+export const DELEGATE_INTERIM_MESSAGE = "Asked workflow-stager to stage api; I'll report back.";++/** The `workflow-stager` child's text before its own turn waits on its staging task. */+export const STAGER_INTERIM_MESSAGE = "Staging api for the parent now.";diff --git a/e2e/fixtures/e2e-config/package.json b/e2e/fixtures/e2e-config/package.jsonindex d3f33222d..c61cc8721 100644--- a/e2e/fixtures/e2e-config/package.json+++ b/e2e/fixtures/e2e-config/package.json@@ -6,7 +6,8 @@"exports": {".": "./src/index.ts","./instrumentation": "./src/instrumentation.ts",- "./instrumentation-otel": "./src/instrumentation-otel.ts"+ "./instrumentation-otel": "./src/instrumentation-otel.ts",+ "./mock-script": "./src/mock-script.ts"},"scripts": {"test:integration": "node --test test/*.integration.test.mjs",diff --git a/e2e/fixtures/e2e-config/src/mock-script.ts b/e2e/fixtures/e2e-config/src/mock-script.tsnew file mode 100644index 000000000..0e0eb7f9a--- /dev/null+++ b/e2e/fixtures/e2e-config/src/mock-script.ts@@ -0,0 +1,53 @@+// Helpers for scripted mock responders: a scenario is a fixed sequence of tool+// calls with stable ids, played one model step at a time.+import type { MockModelRequest, MockModelResponse } from "eve/evals";++/** One tool call of a scripted scenario. Its fixed id marks it as done once its result is in the prompt. */+export interface ScriptedCall {+ readonly id: string;+ readonly name: string;+ readonly input?: (request: MockModelRequest) => unknown;+}++/**+ * Plays a scenario one model step at a time: the first call without a result+ * runs next, and `finish` answers once every call has one.+ */+export function playScript(+ request: MockModelRequest,+ calls: readonly ScriptedCall[],+ finish: (request: MockModelRequest) => MockModelResponse | string,+): MockModelResponse | string {+ const done = new Set(request.toolResults.map((result) => result.id));+ const next = calls.find((call) => !done.has(call.id));+ if (next === undefined) return finish(request);+ return { toolCalls: [{ id: next.id, input: next.input?.(request) ?? {}, name: next.name }] };+}++/** The output of the call with `id`, as the model sees it. */+export function outputOf(request: MockModelRequest, id: string): string {+ const result = request.toolResults.find((entry) => entry.id === id);+ if (result === undefined) throw new Error(`The script expected a result for call "${id}".`);+ return typeof result.output === "string" ? result.output : JSON.stringify(result.output);+}++/** The task a receipt names, such as `Started task revise_plan-7k2m9q.` */+export function taskIdFromReceipt(request: MockModelRequest, callId: string): string {+ const taskId = /Started task (\S+?)\.(?:\s|$)/u.exec(outputOf(request, callId))?.[1];+ if (taskId === undefined) throw new Error(`Call "${callId}" returned no task receipt.`);+ return taskId;+}++/** The body of the latest `<task_result>` block for `tool`, once a result has arrived. */+export function latestTaskResult(request: MockModelRequest, tool: string): string | undefined {+ const pattern = new RegExp(+ `<task_result [^>]*tool="${tool}"[^>]*>([\\s\\S]*?)</task_result>`,+ "g",+ );+ for (const message of [...request.messages].reverse()) {+ if (message.role !== "user") continue;+ const bodies = [...message.text.matchAll(pattern)].map((match) => match[1]!);+ if (bodies.length > 0) return bodies.at(-1);+ }+ return undefined;+}diff --git a/packages/eve/extension-contracts/entrypoints/tool.ts b/packages/eve/extension-contracts/entrypoints/tool.tsindex 22c97d9f8..a981884c7 100644--- a/packages/eve/extension-contracts/entrypoints/tool.ts+++ b/packages/eve/extension-contracts/entrypoints/tool.ts@@ -7,6 +7,7 @@ export {toolOutputPart,toolResultFrom,type WorkflowStepToolContext,+ type WorkflowToolDefinition,} from "../../src/public/tools/index.ts";export {agentRouter,diff --git a/packages/eve/extension-contracts/reports/channel/v36.json b/packages/eve/extension-contracts/reports/channel/v36.jsonnew file mode 100644index 000000000..e2950982c--- /dev/null+++ b/packages/eve/extension-contracts/reports/channel/v36.json@@ -0,0 +1,21 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "channel",+ "epoch": 36,+ "sha256": "cc34474b5fe86ebe8c83e41fdb9412407d9ec1ee54597495df60d3e89ad48312",+ "exports": [+ "DELETE",+ "GET",+ "HEAD",+ "OPTIONS",+ "PATCH",+ "POST",+ "PUT",+ "WS",+ "createWebSocketUpgradeServer",+ "defineChannel",+ "disableRoute",+ "isChannel",+ "isDisabledRouteSentinel"+ ]+}diff --git a/packages/eve/extension-contracts/reports/connection/v30.json b/packages/eve/extension-contracts/reports/connection/v30.jsonnew file mode 100644index 000000000..cb3376a9c--- /dev/null+++ b/packages/eve/extension-contracts/reports/connection/v30.json@@ -0,0 +1,16 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "connection",+ "epoch": 30,+ "sha256": "f558d4b1efdd3a299938caf52e0770994cadd6e7024ef33bb849a7d7efc83c77",+ "exports": [+ "ConnectionAuthorizationFailedError",+ "ConnectionAuthorizationRequiredError",+ "defineDynamic",+ "defineInteractiveAuthorization",+ "defineMcpClientConnection",+ "defineOpenAPIConnection",+ "isConnectionAuthorizationFailedError",+ "isConnectionAuthorizationRequiredError"+ ]+}diff --git a/packages/eve/extension-contracts/reports/dynamicInstructions/v26.json b/packages/eve/extension-contracts/reports/dynamicInstructions/v26.jsonnew file mode 100644index 000000000..43c5d8ada--- /dev/null+++ b/packages/eve/extension-contracts/reports/dynamicInstructions/v26.json@@ -0,0 +1,7 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "dynamicInstructions",+ "epoch": 26,+ "sha256": "db3ae854d16ee38a536cf126987e9482f2e945c3dda0d334930dedaf2af5a596",+ "exports": ["defineDynamic"]+}diff --git a/packages/eve/extension-contracts/reports/dynamicSkill/v25.json b/packages/eve/extension-contracts/reports/dynamicSkill/v25.jsonnew file mode 100644index 000000000..a6c9c218a--- /dev/null+++ b/packages/eve/extension-contracts/reports/dynamicSkill/v25.json@@ -0,0 +1,7 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "dynamicSkill",+ "epoch": 25,+ "sha256": "f321cf3bb031ceecb321070d9ceabac197d3725d57f4d958acbe929ccb42eb27",+ "exports": ["defineDynamic"]+}diff --git a/packages/eve/extension-contracts/reports/dynamicTool/v58.json b/packages/eve/extension-contracts/reports/dynamicTool/v58.jsonnew file mode 100644index 000000000..018d5876c--- /dev/null+++ b/packages/eve/extension-contracts/reports/dynamicTool/v58.json@@ -0,0 +1,16 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "dynamicTool",+ "epoch": 58,+ "sha256": "216282f29895041308dd346c2857cb2e5a688d2276e46a844ea2ca5eb98ac1bf",+ "exports": [+ "DynamicToolEntry",+ "DynamicToolEvents",+ "DynamicToolResult",+ "DynamicToolSet",+ "auto",+ "defineDurableCallback",+ "defineDurableSchema",+ "defineDynamic"+ ]+}diff --git a/packages/eve/extension-contracts/reports/hook/v31.json b/packages/eve/extension-contracts/reports/hook/v31.jsonnew file mode 100644index 000000000..8b1da99fa--- /dev/null+++ b/packages/eve/extension-contracts/reports/hook/v31.json@@ -0,0 +1,7 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "hook",+ "epoch": 31,+ "sha256": "e094477a3738f9e4b73986b4339305dea05ee757972ff8862ccdc8a299b822fa",+ "exports": ["defineHook"]+}diff --git a/packages/eve/extension-contracts/reports/schedule/v18.json b/packages/eve/extension-contracts/reports/schedule/v18.jsonnew file mode 100644index 000000000..e2ec44d54--- /dev/null+++ b/packages/eve/extension-contracts/reports/schedule/v18.json@@ -0,0 +1,14 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "schedule",+ "epoch": 18,+ "sha256": "7ae3361ff7fb1f1c441d9acf328fc7bd1114a65f169c3a3ed64e73a2f6240c88",+ "exports": [+ "ScheduleDefinition",+ "ScheduleHandlerArgs",+ "ScheduleRunHandler",+ "ScheduleToFn",+ "TypedReceiveTarget",+ "defineSchedule"+ ]+}diff --git a/packages/eve/extension-contracts/reports/subagent/v23.json b/packages/eve/extension-contracts/reports/subagent/v23.jsonnew file mode 100644index 000000000..44148868a--- /dev/null+++ b/packages/eve/extension-contracts/reports/subagent/v23.json@@ -0,0 +1,23 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "subagent",+ "epoch": 23,+ "sha256": "b2584306f2cc295261aebc29ef12e0d132dc0a3cbd126e96e922e0379f381190",+ "exports": [+ "AgentCompactionDefinition",+ "AgentDefinition",+ "AgentModelDefinition",+ "AgentStaticModelDefinition",+ "DefinedAgent",+ "DynamicLocalSubagentDefinition",+ "DynamicSubagentDefinition",+ "RemoteAgentDefinition",+ "RemoteAgentDefinitionInput",+ "WorkspaceAgentDefinition",+ "WorkspaceAgentTransport",+ "defineAgent",+ "defineDynamic",+ "defineRemoteAgent",+ "defineWorkspaceAgent"+ ]+}diff --git a/packages/eve/extension-contracts/reports/tool/v61.json b/packages/eve/extension-contracts/reports/tool/v61.jsonnew file mode 100644index 000000000..d0ead107f--- /dev/null+++ b/packages/eve/extension-contracts/reports/tool/v61.json@@ -0,0 +1,28 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "tool",+ "epoch": 61,+ "sha256": "58b4202c85fc72d262aa57baa9fc0455af1f2fcf7b6cb4b7987fc52c342c1d4a",+ "exports": [+ "AgentRouterInput",+ "AgentRouterTool",+ "WorkflowStepToolContext",+ "WorkflowTool",+ "WorkflowToolDefinition",+ "WorkflowToolInput",+ "WorkflowToolOptions",+ "agentRouter",+ "defaultWebSearch",+ "defineTool",+ "defineWorkflowTool",+ "disableTool",+ "evaluate",+ "isDisabledToolSentinel",+ "isWebSearchToolDefinition",+ "toolOutput",+ "toolOutputPart",+ "toolResultFrom",+ "webSearch",+ "workflow"+ ]+}diff --git a/packages/eve/src/channel/types.ts b/packages/eve/src/channel/types.tsindex 43f086f93..f080570ea 100644--- a/packages/eve/src/channel/types.ts+++ b/packages/eve/src/channel/types.ts@@ -291,6 +291,8 @@ export interface SubagentInputRequestEvent {readonly requests: readonly InputRequest[];readonly sequence: number;readonly stepIndex: number;+ /** The task that asks, when a task's run forwards the request. */+ readonly taskId?: string;readonly turnId: string;}diff --git a/packages/eve/src/cli/dev/tui/runner.test.ts b/packages/eve/src/cli/dev/tui/runner.test.tsindex a75dbb2e4..5ee039600 100644--- a/packages/eve/src/cli/dev/tui/runner.test.ts+++ b/packages/eve/src/cli/dev/tui/runner.test.ts@@ -386,14 +386,23 @@ describe("registryHandoffAddress", () => {client,session: sessionYielding([{- type: "subagent.called",+ type: "task.started",data: {callId: "selfmod-call",- childSessionId: "child-session",- childStreamPath: "/eve/v1/session/child-session/stream",+ kind: "agent",name: "self-modification__agent",- sequence: 0,- sessionId: "parent-session",+ taskId: "self-modification__agent-selfmod-call",+ turnId: "parent-turn",+ },+ },+ {+ type: "agent.started",+ data: {+ callId: "selfmod-call",+ name: "self-modification__agent",+ sessionId: "child-session",+ streamPath: "/eve/v1/session/child-session/stream",+ taskId: "self-modification__agent-selfmod-call",turnId: "parent-turn",},},@@ -3567,7 +3576,7 @@ describe("EveTUIRunner renderer teardown", () => {expect(requestStop).toHaveBeenCalledOnce();});- it("finishes the section on the child's own turn boundary, before subagent.completed", async () => {+ it("finishes the section on the child's own turn boundary, before task.settled", async () => {const client = stubClient();vi.stubGlobal("fetch",@@ -3629,21 +3638,28 @@ describe("EveTUIRunner renderer teardown", () => {}),session: sessionYielding([{- type: "subagent.called",+ type: "task.started",data: {callId: "call-child",- childSessionId: "child-session",- childStreamPath: "/eve/v1/session/child-session/stream",+ kind: "agent",name: "weather-child",- sequence: 0,- sessionId: "parent-session",- toolName: "delegate_weather",+ taskId: "weather-child-call-child",turnId: "turn-parent",- workflowId: "workflow-parent",},},- // The parent stream never reports subagent.completed — the child's- // own boundary must finish the section.+ {+ type: "agent.started",+ data: {+ callId: "call-child",+ name: "weather-child",+ sessionId: "child-session",+ streamPath: "/eve/v1/session/child-session/stream",+ taskId: "weather-child-call-child",+ turnId: "turn-parent",+ },+ },+ // The parent stream never reports task.settled — the child's own+ // boundary must finish the section.{ type: "turn.completed", data: { sequence: 0, turnId: "turn-parent" } },{type: "session.waiting",@@ -3698,17 +3714,24 @@ describe("EveTUIRunner renderer teardown", () => {}),session: sessionYielding([{- type: "subagent.called",+ type: "task.started",data: {callId: "call-child",- childSessionId: "child-session",- childStreamPath: "/eve/v1/session/child-session/stream",+ kind: "agent",name: "weather-child",- sequence: 0,- sessionId: "parent-session",- toolName: "delegate_weather",+ taskId: "weather-child-call-child",+ turnId: "turn-parent",+ },+ },+ {+ type: "agent.started",+ data: {+ callId: "call-child",+ name: "weather-child",+ sessionId: "child-session",+ streamPath: "/eve/v1/session/child-session/stream",+ taskId: "weather-child-call-child",turnId: "turn-parent",- workflowId: "workflow-parent",},},{ type: "turn.completed", data: { sequence: 0, turnId: "turn-parent" } },@@ -4746,26 +4769,44 @@ describe("EveTUIRunner cancelled-turn subagent settling", () => {const session = sessionYielding([{- type: "subagent.called",+ type: "task.started",data: {callId: "call-a",- childSessionId: "child-a",- childStreamPath: "/eve/v1/session/child-a/stream",+ kind: "agent",name: "researcher",- sequence: 0,- sessionId: "parent-session",+ taskId: "researcher-call-a",+ turnId: "turn-a",+ },+ },+ {+ type: "agent.started",+ data: {+ callId: "call-a",+ name: "researcher",+ sessionId: "child-a",+ streamPath: "/eve/v1/session/child-a/stream",+ taskId: "researcher-call-a",turnId: "turn-a",},},{- type: "subagent.called",+ type: "task.started",data: {callId: "call-1",- childSessionId: "child-1",- childStreamPath: "/eve/v1/session/child-1/stream",+ kind: "agent",name: "researcher",- sequence: 1,- sessionId: "parent-session",+ taskId: "researcher-call-1",+ turnId: "turn-1",+ },+ },+ {+ type: "agent.started",+ data: {+ callId: "call-1",+ name: "researcher",+ sessionId: "child-1",+ streamPath: "/eve/v1/session/child-1/stream",+ taskId: "researcher-call-1",turnId: "turn-1",},},@@ -4796,8 +4837,8 @@ describe("EveTUIRunner cancelled-turn subagent settling", () => {expect(view.begin).toHaveBeenCalledWith({ callId: "call-a", name: "researcher" });expect(view.begin).toHaveBeenCalledWith({ callId: "call-1", name: "researcher" });- // `subagent.completed` never arrives for a cancelled delegation — the- // cancellation itself must close the section.+ // A cancelled call's section closes with the cancelled turn, not a+ // later `task.settled`.expect(view.complete).toHaveBeenCalledWith({ authoritative: true, callId: "call-1" });expect(view.complete).not.toHaveBeenCalledWith({ authoritative: true, callId: "call-a" });});diff --git a/packages/eve/src/cli/dev/tui/runner.ts b/packages/eve/src/cli/dev/tui/runner.tsindex f7d53e84d..91866ebed 100644--- a/packages/eve/src/cli/dev/tui/runner.ts+++ b/packages/eve/src/cli/dev/tui/runner.ts@@ -16,8 +16,8 @@ import {type SessionFailedStreamEvent,type StepCompletedStreamEvent,type MessageStreamEvent,- type SubagentCalledStreamEvent,- type SubagentCompletedStreamEvent,+ type AgentStartedStreamEvent,+ type TaskStartedStreamEvent,Client,ClientSession,} from "#client/index.js";@@ -589,18 +589,13 @@ export class EveTUIRunner {/** True only while the idle prompt owns terminal input. */#readingPrompt = false;/**- * callId → live state for one subagent dispatch. Persists across turn- * boundaries because a subagent dispatched in one turn may not emit- * `subagent.completed` until a later turn (e.g. after a HITL approval).- * Each run holds per-step text accumulators (so reasoning + message land- * in the same section per child step) and per-tool state.+ * callId → live state for one call to an agent task. Persists across turn+ * boundaries because a call made in one turn may not settle until a later+ * turn (e.g. after a HITL approval). Each run holds per-step text+ * accumulators (so reasoning + message land in the same section per child+ * step) and per-tool state.*/readonly #subagentPump: SubagentPump;- /**- * callId → AbortController for the parallel child-session stream pump- * launched on `subagent.called`. Cancelled on `subagent.completed`, when- * the session resets, or when the runner shuts down.- *//*** name → latest known state for one MCP connection* authorization lifecycle. Persists across turns because a turn that@@ -1625,8 +1620,11 @@ export class EveTUIRunner {events: steering ?? events,pendingInputRequests: this.#pendingInputRequests,turnState,- onSubagentCalled: (called) => this.#subagentPump.begin(called),- onSubagentCompleted: (callId) => this.#subagentPump.settle(callId),+ onTaskStarted: (event) =>+ this.#subagentPump.taskStarted(event, sourceSession?.state.sessionId),+ onAgentStarted: (event) =>+ this.#subagentPump.agentStarted(event, sourceSession?.state.sessionId),+ onTaskSettled: (callId) => this.#subagentPump.settle(callId),onTurnCancelled: (turnId) => this.#subagentPump.settleCancelledTurn(turnId),onConnectionAuthRequired: (event) => this.#handleConnectionAuthRequired(event),onConnectionAuthCompleted: (event) => this.#handleConnectionAuthCompleted(event),@@ -2104,8 +2102,9 @@ type EveStreamTranslatorInput = {onAssistantResponse?: () => void;pendingInputRequests: Map<string, InputRequest>;turnState: AgentTUITurnState;- onSubagentCalled?: (event: SubagentCalledStreamEvent) => void;- onSubagentCompleted?: (callId: string) => void;+ onTaskStarted?: (event: TaskStartedStreamEvent) => void;+ onAgentStarted?: (event: AgentStartedStreamEvent) => void;+ onTaskSettled?: (callId: string) => void;onTurnCancelled?: (turnId: string) => void;onConnectionAuthRequired?: (event: AuthorizationRequiredStreamEvent) => void;onConnectionAuthCompleted?: (event: AuthorizationCompletedStreamEvent) => void;@@ -2150,8 +2149,9 @@ async function* eveEventsToTUIStream(events,pendingInputRequests,turnState,- onSubagentCalled,- onSubagentCompleted,+ onTaskStarted,+ onAgentStarted,+ onTaskSettled,onTurnCancelled,onConnectionAuthRequired,onConnectionAuthCompleted,@@ -2540,26 +2540,20 @@ async function* eveEventsToTUIStream(yield { type: "turn-cancelled" };break;- case "subagent.called": {- // Re-delivery within this translator was filtered above; run creation- // and re-entry from a later translator live in the pump's begin().- onSubagentCalled?.(event as SubagentCalledStreamEvent);+ // Re-delivery within this translator was filtered above; run creation+ // and re-entry from a later translator live in the pump. The agent's+ // content is observed through its session's stream.+ case "task.started":+ onTaskStarted?.(event);break;- }- case "subagent.started":- case "subagent.event":- // `subagent.started` and `subagent.event` are not emitted by the- // current harness — the parent stream only sees `called` and- // `completed`. All intermediate child content is observed via- // the runner's parallel child-session stream pump.+ case "agent.started":+ onAgentStarted?.(event);break;- case "subagent.completed": {- const completed = event as SubagentCompletedStreamEvent;- onSubagentCompleted?.(completed.data.callId);+ case "task.settled":+ onTaskSettled?.(event.data.callId);break;- }case "authorization.required":onConnectionAuthRequired?.(event as AuthorizationRequiredStreamEvent);@@ -2708,10 +2702,9 @@ function isPostTurnVisibleEvent(event: MessageStreamEvent): boolean {case "step.completed":case "step.failed":case "step.started":- case "subagent.called":- case "subagent.completed":- case "subagent.event":- case "subagent.started":+ case "agent.started":+ case "task.settled":+ case "task.started":case "turn.completed":case "turn.failed":return true;diff --git a/packages/eve/src/cli/dev/tui/subagent-pump.test.ts b/packages/eve/src/cli/dev/tui/subagent-pump.test.tsindex d9db51544..31a5d57af 100644--- a/packages/eve/src/cli/dev/tui/subagent-pump.test.ts+++ b/packages/eve/src/cli/dev/tui/subagent-pump.test.ts@@ -5,7 +5,7 @@ import { stampTestEvent } from "#internal/testing/events.js";import {EVE_MESSAGE_STREAM_VERSION,EVE_STREAM_VERSION_HEADER,- type SubagentCalledStreamEvent,+ type AgentStartedStreamEvent,type UnstampedMessageStreamEvent,} from "#protocol/message.js";@@ -107,19 +107,51 @@ function pushableChildStream() {};}-function subagentCalled(callId: string, turnId = "turn-1"): SubagentCalledStreamEvent {- return {- type: "subagent.called",- data: {- callId,- childSessionId: `child_${callId}`,- childStreamPath: `/eve/v1/children/${callId}/stream`,- name: "researcher",- sequence: 1,- sessionId: "parent",- turnId,+interface AgentTaskOptions {+ readonly name?: string;+ readonly remote?: AgentStartedStreamEvent["data"]["remote"];+ readonly sessionId?: string;+ readonly streamPath?: string;+ readonly turnId?: string;+}++/** Starts an agent task the way the parent stream announces it: the call, then its session. */+function startAgentTask(+ pump: SubagentPump,+ callId: string,+ options: AgentTaskOptions = {},+): { readonly name: string; readonly taskId: string } {+ const name = options.name ?? "researcher";+ const taskId = `${name}-${callId}`;+ const turnId = options.turnId ?? "turn-1";+ callAgentTask(pump, { name, taskId }, callId, turnId);+ const data: AgentStartedStreamEvent["data"] = {+ callId,+ name,+ sessionId: options.sessionId ?? `child_${callId}`,+ streamPath: options.streamPath ?? `/eve/v1/children/${callId}/stream`,+ taskId,+ turnId,+ };+ if (options.remote !== undefined) data.remote = options.remote;+ pump.agentStarted({ data, type: "agent.started" }, "parent");+ return { name, taskId };+}++/** A later call to a task reaches the session the task already opened. */+function callAgentTask(+ pump: SubagentPump,+ task: { readonly name: string; readonly taskId: string },+ callId: string,+ turnId = "turn-1",+): void {+ pump.taskStarted(+ {+ data: { callId, kind: "agent", name: task.name, taskId: task.taskId, turnId },+ type: "task.started",},- } as SubagentCalledStreamEvent;+ "parent",+ );}function responseOf(events: readonly MessageStreamEvent[]): Response {@@ -192,8 +224,8 @@ describe("SubagentPump.settleCancelledTurn", () => {});const { pump, view } = createPump();- pump.begin(subagentCalled("child-a", "turn-a"));- pump.begin(subagentCalled("child-b", "turn-b"));+ startAgentTask(pump, "child-a", { turnId: "turn-a" });+ startAgentTask(pump, "child-b", { turnId: "turn-b" });await vi.waitFor(() => expect(requests).toHaveLength(2));pump.settleCancelledTurn("turn-b");@@ -213,7 +245,7 @@ describe("SubagentPump.settleCancelledTurn", () => {const requests = serveChildStreams(({ signal }) => child.response(signal));const { pump, view } = createPump();- pump.begin(subagentCalled("call-1"));+ startAgentTask(pump, "call-1");await vi.waitFor(() => expect(requests).toHaveLength(1));child.push(reasoningEvent("**Searching for current events**", 0));await vi.waitFor(() =>@@ -235,7 +267,7 @@ describe("SubagentPump.settleCancelledTurn", () => {await new Promise((resolve) => setTimeout(resolve, 10));expect(vi.mocked(view.upsertStep).mock.calls.length).toBe(updatesAfterSettle);- // The parent's late `subagent.completed` fallback settles as a no-op.+ // The call's late `task.settled` settles as a no-op.const completions = vi.mocked(view.complete).mock.calls.length;pump.settle("call-1");expect(vi.mocked(view.complete).mock.calls.length).toBe(completions);@@ -248,10 +280,10 @@ describe("SubagentPump completion", () => {const requests = serveChildStreams(({ signal }) => child.response(signal));const { pump, view } = createPump();- pump.begin(subagentCalled("call-1"));+ startAgentTask(pump, "call-1");pump.settle("call-1");expect(view.complete).toHaveBeenCalledWith({ authoritative: false, callId: "call-1" });- pump.begin(subagentCalled("call-1"));+ startAgentTask(pump, "call-1");expect(view.begin).toHaveBeenCalledOnce();await vi.waitFor(() => expect(requests).toHaveLength(1));@@ -294,7 +326,7 @@ describe("SubagentPump child stream transport", () => {const { pump, view } = createPump();try {- pump.begin(subagentCalled("call-1"));+ startAgentTask(pump, "call-1");await vi.waitFor(() =>expect(view.complete).toHaveBeenCalledWith({ authoritative: true, callId: "call-1" }),);@@ -357,21 +389,17 @@ describe("SubagentPump child stream transport", () => {);const onToolCompleted = vi.fn(async () => {});const { pump, view } = createPump({ onToolCompleted });- const first = subagentCalled("call-1");- first.data.childSessionId = "conversation-child";- first.data.name = "self-modification__agent";- const second = subagentCalled("call-2", "turn-2");- second.data.childSessionId = "conversation-child";- second.data.name = "self-modification__agent";-- pump.begin(first);+ const task = startAgentTask(pump, "call-1", {+ name: "self-modification__agent",+ sessionId: "conversation-child",+ });await vi.waitFor(() =>expect(view.complete).toHaveBeenCalledWith({ authoritative: true, callId: "call-1" }),);- pump.begin(second);+ callAgentTask(pump, task, "call-2", "turn-2");await vi.waitFor(() => expect(onToolCompleted).toHaveBeenCalledOnce());- expect(requests[1]).toMatchObject({ path: "/eve/v1/children/call-2/stream", startIndex: 1 });+ expect(requests[1]).toMatchObject({ path: "/eve/v1/children/call-1/stream", startIndex: 1 });expect(onToolCompleted).toHaveBeenCalledWith("self-modification__agent", "registry_add", {status: "needs-terminal",address: "channel/slack",@@ -386,15 +414,10 @@ describe("SubagentPump child stream transport", () => {: responseOf([reasoningEvent("second turn", 1), completedEvent(2)]),);const { pump, view } = createPump();- const first = subagentCalled("call-1");- first.data.childSessionId = "conversation-child";- const second = subagentCalled("call-2", "turn-2");- second.data.childSessionId = "conversation-child";-- pump.begin(first);+ const task = startAgentTask(pump, "call-1", { sessionId: "conversation-child" });await vi.waitFor(() => expect(requests).toHaveLength(1));pump.settle("call-1");- pump.begin(second);+ callAgentTask(pump, task, "call-2", "turn-2");await new Promise((resolve) => setTimeout(resolve, 10));expect(requests).toHaveLength(1);@@ -405,7 +428,7 @@ describe("SubagentPump child stream transport", () => {expect.objectContaining({ callId: "call-2", reasoning: "second turn" }),),);- expect(requests[1]).toMatchObject({ path: "/eve/v1/children/call-2/stream", startIndex: 1 });+ expect(requests[1]).toMatchObject({ path: "/eve/v1/children/call-1/stream", startIndex: 1 });});it("leaves connection authorization events to the parent runner", async () => {@@ -442,7 +465,7 @@ describe("SubagentPump child stream transport", () => {);const { pump, view } = createPump();- pump.begin(subagentCalled("call-1"));+ startAgentTask(pump, "call-1");await vi.waitFor(() =>expect(view.complete).toHaveBeenCalledWith({ authoritative: true, callId: "call-1" }),);@@ -464,7 +487,7 @@ describe("SubagentPump child stream transport", () => {);const { pump, view } = createPump();- pump.begin(subagentCalled("call-1"));+ startAgentTask(pump, "call-1");await vi.waitFor(() =>expect(view.complete).toHaveBeenCalledWith({ authoritative: true, callId: "call-1" }),);@@ -485,7 +508,7 @@ describe("SubagentPump child stream transport", () => {);const { pump, view } = createPump();- pump.begin(subagentCalled("call-1"));+ startAgentTask(pump, "call-1");await vi.advanceTimersByTimeAsync(60_000);expect(requests).toHaveLength(9);@@ -496,7 +519,7 @@ describe("SubagentPump child stream transport", () => {const requests = serveChildStreams(() => new Response("forbidden", { status: 403 }));const { pump, view } = createPump();- pump.begin(subagentCalled("call-1"));+ startAgentTask(pump, "call-1");await vi.waitFor(() => expect(requests).toHaveLength(1));await new Promise((resolve) => setTimeout(resolve, 10));@@ -509,17 +532,17 @@ describe("SubagentPump child stream transport", () => {it("uses the parent-authored child path and never the remote URL", async () => {const requests = serveChildStreams(durableChild([boundaryEvent(0)]));const { pump, view } = createPump({ host: "https://parent.example" });- const called = subagentCalled("remote-call");- called.data.childStreamPath = "/eve/v1/session/parent/subagents/remote-call/child/stream";- called.data.remote = { url: "https://remote.example/private" };-- pump.begin(called);+ const streamPath = "/eve/v1/session/parent/subagents/remote-call/child/stream";+ startAgentTask(pump, "remote-call", {+ remote: { url: "https://remote.example/private" },+ streamPath,+ });await vi.waitFor(() =>expect(view.complete).toHaveBeenCalledWith({ authoritative: true, callId: "remote-call" }),);expect(requests[0]!.url.origin).toBe("https://parent.example");- expect(requests[0]!.path).toBe(called.data.childStreamPath);+ expect(requests[0]!.path).toBe(streamPath);expect(requests.map(({ url }) => url.href).join(" ")).not.toContain("remote.example");});@@ -528,7 +551,7 @@ describe("SubagentPump child stream transport", () => {const requests = serveChildStreams(() => responseOf([]));const { pump } = createPump();- pump.begin(subagentCalled("call-1"));+ startAgentTask(pump, "call-1");await vi.waitFor(() => expect(requests).toHaveLength(1));pump.abortAll();await vi.advanceTimersByTimeAsync(10_000);diff --git a/packages/eve/src/cli/dev/tui/subagent-pump.ts b/packages/eve/src/cli/dev/tui/subagent-pump.tsindex f908d0260..6e89020c7 100644--- a/packages/eve/src/cli/dev/tui/subagent-pump.ts+++ b/packages/eve/src/cli/dev/tui/subagent-pump.ts@@ -1,7 +1,7 @@/**- * The subagent child-stream subsystem: for every `subagent.called` on the- * parent stream, a parallel pump over the child session folds its events- * into the renderer's nested subagent view. Extracted from the runner —+ * The subagent child-stream subsystem: for every call to an agent task on+ * the parent stream, a parallel pump over the agent's session folds its+ * events into the renderer's nested subagent view. Extracted from the runner —* the subsystem touches nothing but its own run state, the client, and the* {@link SubagentView} seam.*/@@ -10,8 +10,9 @@ import type { Client, StreamReconnectPolicy } from "#client/index.js";import {isCurrentTurnBoundaryEvent,type ActionResultStreamEvent,+ type AgentStartedStreamEvent,type MessageStreamEvent,- type SubagentCalledStreamEvent,+ type TaskStartedStreamEvent,} from "#protocol/message.js";/**@@ -74,8 +75,10 @@ export type SubagentRun = {parentTurnId: string;/** Parent completion is provisional; only a child boundary is authoritative. */status: "open" | "provisional" | "authoritative";- /** Dispatch event whose parent-origin child stream this run follows. */- called: SubagentCalledStreamEvent;+ /** The parent session, whose client follows the child stream. */+ parentSessionId: string;+ /** The agent task's session, whose stream this run follows. */+ started: AgentStartedStreamEvent;/*** One entry per logical "child message" — independent of the child's* `stepIndex` field, which the harness can reuse across multiple@@ -123,6 +126,11 @@ export interface SubagentPumpOptions {onToolCompleted?: (subagentName: string, toolName: string, output: unknown) => Promise<void>;}+/** An agent task: its session is announced once, and every call to the task reaches it. */+interface AgentTask {+ started?: AgentStartedStreamEvent;+}+export class SubagentPump {readonly #client: Client | undefined;readonly #view: SubagentView | undefined;@@ -131,6 +139,7 @@ export class SubagentPump {| ((subagentName: string, toolName: string, output: unknown) => Promise<void>)| undefined;readonly #runs = new Map<string, SubagentRun>();+ readonly #tasks = new Map<string, AgentTask>();readonly #pumps = new Map<string, AbortController>();/** Durable child cursor shared by repeated calls into one conversation subagent. */readonly #childStreamIndices = new Map<string, number>();@@ -145,36 +154,68 @@ export class SubagentPump {this.#onToolCompleted = options.onToolCompleted;}+ /** A call started or reached a task. A call to an agent task opens a section at once. */+ taskStarted(event: TaskStartedStreamEvent, parentSessionId: string | undefined): void {+ const { callId, kind, taskId, turnId } = event.data;+ if (kind !== "agent") return;+ const task = this.#tasks.get(taskId);+ if (task === undefined) {+ this.#tasks.set(taskId, {});+ return;+ }+ if (task.started !== undefined && parentSessionId !== undefined) {+ this.#begin({ callId, parentSessionId, parentTurnId: turnId, started: task.started });+ }+ }+/**- * The moment a dispatch is known to be a subagent call, its section- * header replaces the parent-level tool row (or its still-preparing- * placeholder — subagent dispatches never upgrade one, since their- * actions are not tool-call kind). Without this the placeholder is- * swept at the step boundary and nothing shows until the child's first- * content arrives. A later parent-stream translator may replay the call;- * re-entry only refreshes the name.+ * A run opened a session. The session an agent task opens is its agent's;+ * sessions other tools open have no section.*/- begin(called: SubagentCalledStreamEvent): void {- const callId = called.data.callId;+ agentStarted(started: AgentStartedStreamEvent, parentSessionId: string | undefined): void {+ const { callId, taskId, turnId } = started.data;+ const task = taskId === undefined ? undefined : this.#tasks.get(taskId);+ if (task === undefined) return;+ task.started ??= started;+ if (parentSessionId === undefined) return;+ this.#begin({ callId, parentSessionId, parentTurnId: turnId, started: task.started });+ }++ /**+ * The moment a call is known to reach an agent, its section header+ * replaces the parent-level tool row (or its still-preparing+ * placeholder). Without this the placeholder is swept at the step boundary+ * and nothing shows until the child's first content arrives. A later+ * parent-stream translator may replay the call; re-entry only refreshes+ * the name.+ */+ #begin(input: {+ readonly callId: string;+ readonly parentSessionId: string;+ readonly parentTurnId: string;+ readonly started: AgentStartedStreamEvent;+ }): void {+ const { callId, started } = input;const existing = this.#runs.get(callId);if (existing === undefined) {this.#runs.set(callId, {- name: called.data.name,- childSessionId: called.data.childSessionId,- parentTurnId: called.data.turnId,+ name: started.data.name,+ childSessionId: started.data.sessionId,+ parentSessionId: input.parentSessionId,+ parentTurnId: input.parentTurnId,status: "open",- called,+ started,steps: new Map(),currentSectionKey: null,nextSectionKey: 0,tools: new Map(),});} else {- existing.name = called.data.name;+ existing.name = started.data.name;}this.#view?.markChildToolCallId(callId);if (existing !== undefined && existing.status !== "open") return;- this.#view?.begin({ callId, name: called.data.name });+ this.#view?.begin({ callId, name: started.data.name });if (existing !== undefined) return;this.#activateOrQueue(callId);}@@ -194,6 +235,7 @@ export class SubagentPump {}this.#pumps.clear();this.#runs.clear();+ this.#tasks.clear();this.#childStreamIndices.clear();this.#activeChildCalls.clear();this.#queuedChildCalls.clear();@@ -248,13 +290,11 @@ export class SubagentPump {const { childSessionId } = run;let cursor = this.#childStreamIndices.get(childSessionId) ?? 0;try {- const events = client.sessions- .attach(run.called.data.sessionId)- .streamSubagent(run.called, {- signal: controller.signal,- startIndex: cursor,- streamReconnectPolicy: childStreamReconnectPolicy,- });+ const events = client.sessions.attach(run.parentSessionId).agent(run.started).stream({+ signal: controller.signal,+ startIndex: cursor,+ streamReconnectPolicy: childStreamReconnectPolicy,+ });for await (const event of events) {if (controller.signal.aborted) return;this.#childStreamIndices.set(childSessionId, (cursor += 1));@@ -269,8 +309,8 @@ export class SubagentPump {return;}} catch {- // Only a non-retryable failure ends the follower early; the parent's- // `subagent.completed` still settles the section.+ // Only a non-retryable failure ends the follower early; the call's+ // `task.settled` still settles the section.} finally {controller.abort();if (this.#pumps.get(callId) === controller) this.#pumps.delete(callId);@@ -339,8 +379,8 @@ export class SubagentPump {* Settles a subagent section: re-emits a finalized snapshot for any* still-streaming step (flipping its right-title off `streaming`), sweeps* preparing ghosts, and marks the section Done. The run's status field is- * the idempotency authority — the child's turn boundary and the parent's- * `subagent.completed` can both land here.+ * the idempotency authority — the child's turn boundary and the call's+ * `task.settled` can both land here.*/#finalizeRun(callId: string, authoritative: boolean): void {const run = this.#runs.get(callId);diff --git a/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts b/packages/eve/src/cli/dev/tui/terminal-renderer.test.tsindex b8d2db44b..830272da8 100644--- a/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts+++ b/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts@@ -1181,8 +1181,7 @@ describe("TerminalRenderer (inline scrollback)", () => {});await screen.waitForText("Delegate");- // Subagent dispatches never upgrade the placeholder (their actions are- // not tool-call kind) — subagent.called supersedes it with the section.+ // The agent's section supersedes the tool-call placeholder once agent.started arrives.renderer.markChildToolCallId("sub1");renderer.beginSubagent({ callId: "sub1", name: "agent" });await screen.waitForText("※ subagent(self)");diff --git a/packages/eve/src/client/agent-session.ts b/packages/eve/src/client/agent-session.tsnew file mode 100644index 000000000..39727f8d8--- /dev/null+++ b/packages/eve/src/client/agent-session.ts@@ -0,0 +1,56 @@+import { followStreamIterable } from "#client/open-stream.js";+import type { ClientSessionContext } from "#client/session.js";+import type { StreamOptions } from "#client/types.js";+import type { AgentStartedStreamEvent, MessageStreamEvent } from "#protocol/message.js";++/**+ * A session an agent run opened, reached through the parent session whose+ * stream announced it with `agent.started`. Get one with+ * `session.agent(started)`. Every read uses the parent's host and+ * credentials: a local child's own route, or the parent-origin proxy for a+ * remote child, which the parent deployment authenticates to the remote agent+ * after checking that it recorded the child.+ */+export class ClientAgentSession {+ /** The agent's name, as `agent.started` reports it. */+ readonly name: string;+ /** The child session's id. */+ readonly sessionId: string;+ /** The task whose run opened the session; absent when an `execute` call opened it. */+ readonly taskId: string | undefined;+ readonly #context: ClientSessionContext;+ readonly #streamPath: string;++ /** @internal */+ constructor(context: ClientSessionContext, started: AgentStartedStreamEvent) {+ this.#context = context;+ this.#streamPath = started.data.streamPath;+ this.name = started.data.name;+ this.sessionId = started.data.sessionId;+ this.taskId = started.data.taskId;+ }++ /**+ * Follows the child's durable event stream. Reading it never advances the+ * parent session's cursor. The child cursor starts at `0`; pass `startIndex`+ * to resume. Stop at a child turn boundary with `isCurrentTurnBoundaryEvent`.+ */+ stream(options?: StreamOptions): AsyncIterable<MessageStreamEvent> {+ const startIndex = options?.startIndex ?? 0;+ if (options?.follow === false && startIndex < 0) {+ throw new Error(+ "agent(started).stream({ follow: false }) requires a nonnegative startIndex; a tail-relative cursor cannot be bounded.",+ );+ }+ return followStreamIterable({+ follow: options?.follow,+ host: this.#context.host,+ path: this.#streamPath,+ redirect: this.#context.redirect,+ resolveHeaders: () => this.#context.resolveHeaders(),+ signal: options?.signal,+ startIndex,+ streamReconnectPolicy: options?.streamReconnectPolicy,+ });+ }+}diff --git a/packages/eve/src/client/index.ts b/packages/eve/src/client/index.tsindex a85da64f1..f309012a4 100644--- a/packages/eve/src/client/index.ts+++ b/packages/eve/src/client/index.ts@@ -10,6 +10,7 @@ export { ClientError } from "#client/client-error.js";export { defaultMessageReducer } from "#client/message-reducer.js";export { createDataUrlFilePart, createTextWithFileContent } from "#client/file-parts.js";export { MessageResponse } from "#client/message-response.js";+export { ClientAgentSession } from "#client/agent-session.js";export { ClientSession } from "#client/session.js";export {ClientSessions,@@ -130,10 +131,8 @@ export type {StepCompletedStreamEvent,StepFailedStreamEvent,StepStartedStreamEvent,- SubagentCalledStreamEvent,- SubagentChildEventStreamEvent,- SubagentCompletedStreamEvent,- SubagentStartedStreamEvent,+ TaskSettledStreamEvent,+ TaskStartedStreamEvent,TurnCancelledStreamEvent,TurnCompletedStreamEvent,TurnFailedStreamEvent,diff --git a/packages/eve/src/client/message-reducer.test.ts b/packages/eve/src/client/message-reducer.test.tsindex 3a7c1cd04..6f6b644c4 100644--- a/packages/eve/src/client/message-reducer.test.ts+++ b/packages/eve/src/client/message-reducer.test.ts@@ -18,9 +18,12 @@ import {createReasoningCompletedEvent,createResultCompletedEvent,createStepStartedEvent,+ createTaskSettledEvent,createTurnCancelledEvent,+ createTurnCompletedEvent,createTurnFailedEvent,type MessageStreamEvent,+ type TaskSettledStreamEvent,type UnstampedMessageStreamEvent,} from "#protocol/message.js";@@ -1279,6 +1282,64 @@ describe("defaultMessageReducer", () => {]);});+ describe("task tool parts", () => {+ function settleResearchTask(settled: TaskSettledStreamEvent["data"]) {+ const reducer = defaultMessageReducer();+ const data = reduceServerEvents(reducer, reducer.initial(), [+ createActionResultEvent({+ result: {+ callId: "call_1",+ kind: "tool-result",+ output: "Started task task_1.",+ toolName: "research",+ },+ sequence: 0,+ stepIndex: 0,+ turnId: "turn_1",+ }),+ createTurnCompletedEvent({ sequence: 0, turnId: "turn_1" }),+ createTaskSettledEvent(settled),+ ]);+ const [message] = data.messages;+ return { status: message?.metadata?.status, toolPart: message?.parts[1] };+ }++ it("replaces the receipt with the output of a completed task", () => {+ expect(+ settleResearchTask({+ callId: "call_1",+ output: { summary: "done" },+ status: "completed",+ taskId: "task_1",+ turnId: "turn_1",+ }),+ ).toMatchObject({+ status: "complete",+ toolPart: { output: { summary: "done" }, state: "output-available" },+ });+ });++ it("shows a failed or cancelled task as a tool error", () => {+ expect(+ settleResearchTask({+ callId: "call_1",+ error: { message: "Remote agent unavailable." },+ status: "failed",+ taskId: "task_1",+ turnId: "turn_1",+ }).toolPart,+ ).toMatchObject({ errorText: "Remote agent unavailable.", state: "output-error" });+ expect(+ settleResearchTask({+ callId: "call_1",+ status: "cancelled",+ taskId: "task_1",+ turnId: "turn_1",+ }).toolPart,+ ).toMatchObject({ errorText: "Task was cancelled.", state: "output-error" });+ });+ });+it("preserves separate participant messages received within one turn", () => {const reducer = defaultMessageReducer();const events = stampTestEvents([diff --git a/packages/eve/src/client/message-reducer.ts b/packages/eve/src/client/message-reducer.tsindex 0951af119..d3cddaa84 100644--- a/packages/eve/src/client/message-reducer.ts+++ b/packages/eve/src/client/message-reducer.ts@@ -28,6 +28,7 @@ import {upsertMessage,} from "#client/message-reducer-primitives.js";import { messageRun } from "#client/message-run-parts.js";+import { createSettledTaskPart } from "#client/message-task-parts.js";import type { InputResponse } from "#shared/input.js";import type { AuthorizationCompletedStreamEvent, InputResolution } from "#protocol/message.js";@@ -336,6 +337,12 @@ function reduceMessageData(data: EveMessageData, event: EveAgentReducerEvent): E);}+ case "task.settled": {+ const existing = findToolPart(data, event.data.callId);+ if (existing === undefined) return data;+ return replaceToolPart(data, createSettledTaskPart(existing, event));+ }+case "authorization.required":return updateAssistantMessage(data, event.data.turnId, (message) =>upsertPart(@@ -548,6 +555,24 @@ function updateToolPart(return upsertMessage(data, upsertPart(message, next));}+/**+ * Swaps a tool part in place without touching the message status: a task+ * usually settles after the turn that called it has completed.+ */+function replaceToolPart(data: EveMessageData, next: EveDynamicToolPart): EveMessageData {+ const message = data.messages.find((candidate) =>+ candidate.parts.some(+ (part) => part.type === "dynamic-tool" && part.toolCallId === next.toolCallId,+ ),+ );+ if (message === undefined) return data;++ return upsertMessage(data, {+ ...message,+ parts: message.parts.map((part) => (partKey(part) === partKey(next) ? next : part)),+ });+}+function completeAuthorization(data: EveMessageData,event: AuthorizationCompletedStreamEvent,diff --git a/packages/eve/src/client/message-task-parts.ts b/packages/eve/src/client/message-task-parts.tsnew file mode 100644index 000000000..82f7f1fd0--- /dev/null+++ b/packages/eve/src/client/message-task-parts.ts@@ -0,0 +1,36 @@+import type { TaskSettledStreamEvent } from "#protocol/message.js";+import type { EveDynamicToolPart } from "#client/message-reducer-types.js";+import { approvedApproval } from "#client/message-action-parts.js";++/**+ * Settles a task call's tool part, whose `action.result` was only the start+ * receipt. A cancelled task already ran, so it settles as an error rather than+ * `output-denied`, which marks calls that never ran.+ */+export function createSettledTaskPart(+ existing: EveDynamicToolPart,+ event: TaskSettledStreamEvent,+): EveDynamicToolPart {+ const settledPartBase = {+ approval: approvedApproval(existing),+ input: existing.input,+ stepIndex: existing.stepIndex,+ toolCallId: existing.toolCallId,+ toolMetadata: existing.toolMetadata,+ toolName: existing.toolName,+ type: "dynamic-tool" as const,+ };++ switch (event.data.status) {+ case "completed":+ return { ...settledPartBase, output: event.data.output, state: "output-available" };+ case "failed":+ return {+ ...settledPartBase,+ errorText: event.data.error?.message ?? "Task failed.",+ state: "output-error",+ };+ case "cancelled":+ return { ...settledPartBase, errorText: "Task was cancelled.", state: "output-error" };+ }+}diff --git a/packages/eve/src/client/session-utils.ts b/packages/eve/src/client/session-utils.tsindex 5fff24e8f..71b2ce8bd 100644--- a/packages/eve/src/client/session-utils.ts+++ b/packages/eve/src/client/session-utils.ts@@ -42,6 +42,8 @@ export function summarizeTurnEvents(if (isTurnSegmentBoundary(event, pendingInputRequests)) boundary = event;if (isTurnFailureEvent(event)) failure = event;if (isFinalMessageCompleted(event)) message = event.data.message ?? undefined;+ // Text completed before the turn parked was interim; the reply comes after it resumes.+ if (event.type === "turn.waiting") message = undefined;if (event.type === "input.requested") inputRequests.push(...event.data.requests);if (event.type === "authorization.required") {pendingAuthorizations.set(event.data.name, event.data);diff --git a/packages/eve/src/client/session.test.ts b/packages/eve/src/client/session.test.tsindex 8545ec0a3..a867cbbb2 100644--- a/packages/eve/src/client/session.test.ts+++ b/packages/eve/src/client/session.test.ts@@ -6,8 +6,8 @@ import type { ClientSessionState } from "#client/types.js";import {EVE_MESSAGE_STREAM_VERSION,EVE_STREAM_VERSION_HEADER,- createSubagentCalledEvent,- type SubagentCalledStreamEvent,+ createAgentStartedEvent,+ type AgentStartedStreamEvent,} from "#protocol/message.js";afterEach(() => {@@ -1359,23 +1359,18 @@ describe("ClientSession", () => {});});-describe("ClientSession.streamSubagent", () => {- function calledEvent(- input: { readonly remote?: boolean; readonly sessionId?: string } = {},- ): SubagentCalledStreamEvent {- return createSubagentCalledEvent({+describe("ClientSession.agent", () => {+ function startedEvent(input: { readonly remote?: boolean } = {}): AgentStartedStreamEvent {+ return createAgentStartedEvent({callId: "call_1",- childSessionId: "child_1",name: "research",+ parentSessionId: "session_1",remote:input.remote === false? undefined: { resolverId: "subagents/research", url: "https://remote.test" },- sequence: 1,- sessionId: input.sessionId ?? "session_1",- toolName: "research",+ sessionId: "child_1",turnId: "turn_1",- workflowId: "workflow_1",});}@@ -1399,7 +1394,7 @@ describe("ClientSession.streamSubagent", () => {});const types: string[] = [];- for await (const event of session.streamSubagent(calledEvent(), { follow: false })) {+ for await (const event of session.agent(startedEvent()).stream({ follow: false })) {types.push(event.type);}@@ -1424,7 +1419,7 @@ describe("ClientSession.streamSubagent", () => {const session = createSession(parentState);const types: string[] = [];- for await (const event of session.streamSubagent(calledEvent(), {+ for await (const event of session.agent(startedEvent()).stream({startIndex: 1,streamReconnectPolicy: { reconnect: false },})) {@@ -1444,7 +1439,7 @@ describe("ClientSession.streamSubagent", () => {});const session = createSession();- for await (const _event of session.streamSubagent(calledEvent({ remote: false }), {+ for await (const _event of session.agent(startedEvent({ remote: false })).stream({follow: false,})) {// Drain the bounded child stream.@@ -1452,16 +1447,4 @@ describe("ClientSession.streamSubagent", () => {expect(urls[0]!.pathname).toBe("/eve/v1/session/child_1/stream");});-- it("rejects a subagent event recorded before childStreamPath existed", () => {- const fetchMock = vi.spyOn(globalThis, "fetch");- const session = createSession();- const { childStreamPath: _, ...legacyData } = calledEvent().data;- const legacy = { ...calledEvent(), data: legacyData } as SubagentCalledStreamEvent;-- expect(() => session.streamSubagent(legacy)).toThrow(- "streamSubagent() requires a subagent.called event with childStreamPath, but call call_1 has none. The event was recorded by an older eve version.",- );- expect(fetchMock).not.toHaveBeenCalled();- });});diff --git a/packages/eve/src/client/session.ts b/packages/eve/src/client/session.tsindex f6af4cfcd..95401f4d0 100644--- a/packages/eve/src/client/session.ts+++ b/packages/eve/src/client/session.ts@@ -3,17 +3,14 @@ import {updatePendingAuthorizations,updatePendingInputRequests,} from "#client/session-utils.js";-import type {- AgentStartedStreamEvent,- MessageStreamEvent,- SubagentCalledStreamEvent,-} from "#protocol/message.js";+import type { AgentStartedStreamEvent, MessageStreamEvent } from "#protocol/message.js";import { EVE_SESSION_ID_HEADER } from "#protocol/message.js";import {EVE_SESSION_ROUTE_PATH,createEveSessionRoutePath,createEveSessionStreamRoutePath,} from "#protocol/routes.js";+import { ClientAgentSession } from "#client/agent-session.js";import { ClientError } from "#client/client-error.js";import { MessageResponse } from "#client/message-response.js";import { followStreamIterable, sleep } from "#client/open-stream.js";@@ -218,41 +215,13 @@ export class ClientSession {}/**- * Follows one delegated child's durable event stream through this parent session.- *- * Pass an `agent.started` or `subagent.called` event from this session. The- * client reads the child's stream path with this session's host and- * credentials: a local child's own stream route, or the parent-origin proxy- * for a remote child, which the parent deployment authenticates to the remote- * agent after checking that the parent recorded the child. Reading the child- * never advances this session's cursor. The child cursor starts at `0`; pass- * `startIndex` to resume. Stop at a child turn boundary with- * `isCurrentTurnBoundaryEvent`.- *- * @throws {Error} When a `subagent.called` event has no `childStreamPath`- * because an older eve version recorded it.+ * The session an agent run opened, as this session's stream announced it.+ * Pass an `agent.started` event from this session, then follow the child+ * with `stream()`; reads use this session's host and credentials, for local+ * and remote agents alike.*/- streamSubagent(- started: AgentStartedStreamEvent | SubagentCalledStreamEvent,- options?: StreamOptions,- ): AsyncIterable<MessageStreamEvent> {- const path = readChildStreamPath(started);- const startIndex = options?.startIndex ?? 0;- if (options?.follow === false && startIndex < 0) {- throw new Error(- "streamSubagent({ follow: false }) requires a nonnegative startIndex; a tail-relative cursor cannot be bounded.",- );- }- return followStreamIterable({- follow: options?.follow,- host: this.#context.host,- path,- redirect: this.#context.redirect,- resolveHeaders: () => this.#context.resolveHeaders(),- signal: options?.signal,- startIndex,- streamReconnectPolicy: options?.streamReconnectPolicy,- });+ agent(started: AgentStartedStreamEvent): ClientAgentSession {+ return new ClientAgentSession(this.#context, started);}[followSession](options: FollowSessionOptions): AsyncIterable<MessageStreamEvent> {@@ -384,17 +353,6 @@ export class ClientSession {}}-function readChildStreamPath(started: AgentStartedStreamEvent | SubagentCalledStreamEvent): string {- if (started.type === "agent.started") return started.data.streamPath;- // Events persisted before childStreamPath existed replay without it.- if (typeof started.data.childStreamPath !== "string") {- throw new Error(- `streamSubagent() requires a subagent.called event with childStreamPath, but call ${started.data.callId} has none. The event was recorded by an older eve version.`,- );- }- return started.data.childStreamPath;-}-/** @internal Follow continuously while the frontend owns the session. */export function followClientSession(session: ClientSession,diff --git a/packages/eve/src/client/subagent-stream.integration.test.ts b/packages/eve/src/client/subagent-stream.integration.test.tsindex 1a3a22101..5fd35a98b 100644--- a/packages/eve/src/client/subagent-stream.integration.test.ts+++ b/packages/eve/src/client/subagent-stream.integration.test.ts@@ -12,9 +12,9 @@ import {EVE_STREAM_CONTROL_VERSION_QUERY,EVE_STREAM_TAIL_INDEX_HEADER,EVE_STREAM_VERSION_HEADER,- createSubagentCalledEvent,+ createAgentStartedEvent,+ type AgentStartedStreamEvent,type MessageStreamEvent,- type SubagentCalledStreamEvent,} from "#protocol/message.js";import { EVE_SUBAGENT_STREAM_ROUTE_PATTERN } from "#protocol/routes.js";import { none } from "#public/channels/auth.js";@@ -27,9 +27,9 @@ afterEach(() => {vi.unstubAllGlobals();});-describe("ClientSession.streamSubagent through the parent proxy", () => {+describe("ClientSession.agent through the parent proxy", () => {it("reads a remote child's events through the parent channel with authored remote credentials", async () => {- const called = createCalled();+ const started = createStarted();const childEvents = [{ type: "turn.started", data: { turnId: "child-turn" } },{@@ -39,7 +39,7 @@ describe("ClientSession.streamSubagent through the parent proxy", () => {{ type: "turn.completed", data: { turnId: "child-turn" } },];const remoteRequests: { readonly url: string; readonly headers: Headers }[] = [];- const parentRoute = createParentRoute(stampTestEvent(called, 0));+ const parentRoute = createParentRoute(stampTestEvent(started, 0));vi.stubGlobal("fetch", async (input: string | URL | Request, init?: RequestInit) => {const url = new URL(input instanceof Request ? input.url : String(input));@@ -52,7 +52,7 @@ describe("ClientSession.streamSubagent through the parent proxy", () => {const session = new Client({ host: PARENT_ORIGIN }).sessions.attach("parent-1");const received: MessageStreamEvent[] = [];- for await (const event of session.streamSubagent(called, { follow: false })) {+ for await (const event of session.agent(started).stream({ follow: false })) {received.push(event);}@@ -76,8 +76,8 @@ describe("ClientSession.streamSubagent through the parent proxy", () => {});it("surfaces the parent's refusal when the child is not bound to that parent", async () => {- const called = createCalled();- const parentRoute = createParentRoute(stampTestEvent(createCalled({ callId: "other" }), 0));+ const started = createStarted();+ const parentRoute = createParentRoute(stampTestEvent(createStarted({ callId: "other" }), 0));const remoteFetch = vi.fn();vi.stubGlobal("fetch", async (input: string | URL | Request, init?: RequestInit) => {@@ -90,7 +90,7 @@ describe("ClientSession.streamSubagent through the parent proxy", () => {const session = new Client({ host: PARENT_ORIGIN }).sessions.attach("parent-1");const read = async () => {- for await (const _event of session.streamSubagent(called, {+ for await (const _event of session.agent(started).stream({streamReconnectPolicy: { reconnect: false },})) {// The proxy refuses before any child event exists.@@ -102,17 +102,14 @@ describe("ClientSession.streamSubagent through the parent proxy", () => {});});-function createCalled(overrides: { readonly callId?: string } = {}): SubagentCalledStreamEvent {- return createSubagentCalledEvent({+function createStarted(overrides: { readonly callId?: string } = {}): AgentStartedStreamEvent {+ return createAgentStartedEvent({callId: overrides.callId ?? "call-1",- childSessionId: "child-1",name: "research",+ parentSessionId: "parent-1",remote: { resolverId: "subagents/research", url: REMOTE_URL },- sequence: 1,- sessionId: "parent-1",- toolName: "research",+ sessionId: "child-1",turnId: "turn-1",- workflowId: "workflow-1",});}diff --git a/packages/eve/src/compiler/extension-compatibility.ts b/packages/eve/src/compiler/extension-compatibility.tsindex 49923547e..31506a9cc 100644--- a/packages/eve/src/compiler/extension-compatibility.ts+++ b/packages/eve/src/compiler/extension-compatibility.ts@@ -22,8 +22,8 @@ interface ExtensionCapabilityContract {const EXTENSION_CAPABILITY_CONTRACTS = {extension: { current: 1, supported: [1], dropped: {} },tool: {- current: 60,- supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 29, 30, 31, 32, 34, 35, 54, 55, 60],+ current: 61,+ supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 29, 30, 31, 32, 34, 35, 54, 55, 61],dropped: {14: "TaskExec.delegated was removed; migrate to workflow-backed background tools",15: "TaskExec replaces stageEffect with send",@@ -63,13 +63,14 @@ const EXTENSION_CAPABILITY_CONTRACTS = {57: "agentRouter() no longer accepts a model-facing outputSchema; structured subagent output is requested only through ctx.agent().",58: "Workflow tools no longer accept execution or return background task receipts; every call blocks until it settles.",59: "Workflow tools no longer accept execution or return background task receipts, and every call blocks until it settles. ctx.ask() no longer accepts dismissible and reports a withdrawn request as cancelled, workflow tool contexts carry interruptSignal, and ctx.agent(name) returns a session handle whose send() delivers a message and whose result() resolves the turn; ctx.agent(name, { message, agentId }) and AgentInput were removed. A ctx.ask() question parks the open turn with turn.waiting instead of ending it.",+ 60: "Workflow tools define exactly one of execute(input, ctx), task(input, ctx), or serve(receive, ctx): a task() call returns a receipt and runs as a task, a serve() call reaches a resumable task through receive() and its model input gains taskId, and stream events gained task.started and task.settled. Agent tools are serve() tools with taskId in place of agentId, and the subagent.* stream events were removed. ctx.interruptSignal and WorkflowTaskContext were removed: a steering message aborts the abortSignal of an execute call the turn waits on.",},},dynamicTool: {- current: 57,+ current: 58,supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 22, 31, 32, 33, 52, 54,- 57,+ 58,],dropped: {21: "Message and reasoning append events now expose deltas instead of cumulative snapshots.",@@ -102,11 +103,12 @@ const EXTENSION_CAPABILITY_CONTRACTS = {53: "SandboxSession no longer exposes setNetworkPolicy; pass the configured environment to ctx.getSandbox(environment) to access network policy capabilities",55: "Run mode was removed; sessions always park and ConversationContext no longer carries mode.",56: 'Background task execution was removed: subagent results no longer carry backgroundTask and message.completed always carries text. input.resolved reports outcome "cancelled" when a workflow tool withdraws a ctx.ask() request, and stream events gained agent.started, published when a workflow run opens a ctx.agent session, and turn.waiting, which parks the open turn instead of emitting turn.completed and session.waiting.',+ 57: "Stream events gained task.started and task.settled, and input.requested, authorization events, and agent.started carry the taskId of the task they come from. The subagent.called, subagent.completed, subagent.started, and subagent.event stream events were removed; agent calls report task.started, task.settled, and agent.started.",},},channel: {- current: 35,- supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 29, 31, 35],+ current: 36,+ supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 29, 31, 36],dropped: {12: "Message and reasoning append events now expose deltas instead of cumulative snapshots.",19: "Continuation rekey was removed; channel extensions must use additive continuation.alias instead.",@@ -123,19 +125,21 @@ const EXTENSION_CAPABILITY_CONTRACTS = {32: "Run mode and caller-supplied output schemas were removed from channel operations; sessions always park, and send options, audience inputs, and ConversationContext no longer carry mode, while from().send() and from().respond() no longer accept outputSchema.",33: "Background task delivery was removed: sends no longer accept taskDeliveryPolicy and message.completed always carries text.",34: 'Background task delivery was removed: sends no longer accept taskDeliveryPolicy and message.completed always carries text. input.resolved reports outcome "cancelled" when a workflow tool withdraws a ctx.ask() request, and stream events gained agent.started, published when a workflow run opens a ctx.agent session, and turn.waiting, which parks the open turn instead of emitting turn.completed and session.waiting.',+ 35: "Stream events gained task.started and task.settled, and input.requested, authorization events, and agent.started carry the taskId of the task they come from. The subagent.called, subagent.completed, subagent.started, and subagent.event stream events were removed; agent calls report task.started, task.settled, and agent.started.",},},schedule: {- current: 17,- supported: [1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 17],+ current: 18,+ supported: [1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 18],dropped: {5: "Message and reasoning append events now expose deltas instead of cumulative snapshots.",16: 'Background task delivery was removed: sends no longer accept taskDeliveryPolicy and message.completed always carries text. input.resolved reports outcome "cancelled" when a workflow tool withdraws a ctx.ask() request, and stream events gained agent.started, published when a workflow run opens a ctx.agent session, and turn.waiting, which parks the open turn instead of emitting turn.completed and session.waiting.',+ 17: "Stream events gained task.started and task.settled, and input.requested, authorization events, and agent.started carry the taskId of the task they come from. The subagent.called, subagent.completed, subagent.started, and subagent.event stream events were removed; agent calls report task.started, task.settled, and agent.started.",},},subagent: {- current: 22,- supported: [3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 19, 22],+ current: 23,+ supported: [3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 19, 23],dropped: {1: "Persistent subagent sessions are now the default and the experimental opt-in was removed",2: "Persistent subagent sessions are now the default and the experimental opt-in was removed",@@ -144,11 +148,12 @@ const EXTENSION_CAPABILITY_CONTRACTS = {18: "Removed experimental.instrumentationProviders; instrumentation is now always enabled for root agents.",20: "Run mode was removed and agent definitions no longer declare outputSchema; sessions always park, ConversationContext no longer carries mode, and structured output is requested per turn.",21: 'Background task execution was removed: subagent results no longer carry backgroundTask, message.completed always carries text, and experimental.tasks is gone. input.resolved reports outcome "cancelled" when a workflow tool withdraws a ctx.ask() request, and stream events gained agent.started, published when a workflow run opens a ctx.agent session, and turn.waiting, which parks the open turn instead of emitting turn.completed and session.waiting.',+ 22: "Stream events gained task.started and task.settled, and input.requested, authorization events, and agent.started carry the taskId of the task they come from. The subagent.called, subagent.completed, subagent.started, and subagent.event stream events were removed; agent calls report task.started, task.settled, and agent.started.",},},connection: {- current: 29,- supported: [1, 2, 3, 4, 5, 6, 7, 8, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 24, 26, 29],+ current: 30,+ supported: [1, 2, 3, 4, 5, 6, 7, 8, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 24, 26, 30],dropped: {9: "Dynamic connection resolvers no longer receive conversation or channel continuation data",10: "Message and reasoning append events now expose deltas instead of cumulative snapshots.",@@ -156,11 +161,12 @@ const EXTENSION_CAPABILITY_CONTRACTS = {25: "SandboxSession no longer exposes setNetworkPolicy; pass the configured environment to ctx.getSandbox(environment) to access network policy capabilities",27: "Run mode was removed; sessions always park and ConversationContext no longer carries mode.",28: 'Background task execution was removed: subagent results no longer carry backgroundTask and message.completed always carries text. input.resolved reports outcome "cancelled" when a workflow tool withdraws a ctx.ask() request, and stream events gained agent.started, published when a workflow run opens a ctx.agent session, and turn.waiting, which parks the open turn instead of emitting turn.completed and session.waiting.',+ 29: "Stream events gained task.started and task.settled, and input.requested, authorization events, and agent.started carry the taskId of the task they come from. The subagent.called, subagent.completed, subagent.started, and subagent.event stream events were removed; agent calls report task.started, task.settled, and agent.started.",},},hook: {- current: 30,- supported: [10, 11, 12, 13, 14, 15, 17, 18, 19, 20, 21, 22, 23, 25, 27, 30],+ current: 31,+ supported: [20, 21, 22, 23, 25, 27, 31],dropped: {1: "Model identity moved from session.started runtime metadata to step.started call attribution.",2: "Model identity moved from session.started runtime metadata to step.started call attribution.",@@ -171,31 +177,43 @@ const EXTENSION_CAPABILITY_CONTRACTS = {7: "Model identity moved from session.started runtime metadata to step.started call attribution.",8: "Model identity moved from session.started runtime metadata to step.started call attribution.",9: "Model identity moved from session.started runtime metadata to step.started call attribution.",+ 10: "The subagent.called, subagent.completed, subagent.started, and subagent.event hook events were removed; subscribe to task.started, task.settled, and agent.started.",+ 11: "The subagent.called, subagent.completed, subagent.started, and subagent.event hook events were removed; subscribe to task.started, task.settled, and agent.started.",+ 12: "The subagent.called, subagent.completed, subagent.started, and subagent.event hook events were removed; subscribe to task.started, task.settled, and agent.started.",+ 13: "The subagent.called, subagent.completed, subagent.started, and subagent.event hook events were removed; subscribe to task.started, task.settled, and agent.started.",+ 14: "The subagent.called, subagent.completed, subagent.started, and subagent.event hook events were removed; subscribe to task.started, task.settled, and agent.started.",+ 15: "The subagent.called, subagent.completed, subagent.started, and subagent.event hook events were removed; subscribe to task.started, task.settled, and agent.started.",16: "Message and reasoning append events now expose deltas instead of cumulative snapshots.",+ 17: "The subagent.called, subagent.completed, subagent.started, and subagent.event hook events were removed; subscribe to task.started, task.settled, and agent.started.",+ 18: "The subagent.called, subagent.completed, subagent.started, and subagent.event hook events were removed; subscribe to task.started, task.settled, and agent.started.",+ 19: "The subagent.called, subagent.completed, subagent.started, and subagent.event hook events were removed; subscribe to task.started, task.settled, and agent.started.",24: "Sandbox sessions no longer expose core identity and mutable networking is provider-specific.",26: "SandboxSession no longer exposes setNetworkPolicy; pass the configured environment to ctx.getSandbox(environment) to access network policy capabilities",28: "Background task execution was removed: subagent results no longer carry backgroundTask and message.completed always carries text.",29: 'Background task execution was removed: subagent results no longer carry backgroundTask and message.completed always carries text. input.resolved reports outcome "cancelled" when a workflow tool withdraws a ctx.ask() request, and stream events gained agent.started, published when a workflow run opens a ctx.agent session, and turn.waiting, which parks the open turn instead of emitting turn.completed and session.waiting.',+ 30: "Stream events gained task.started and task.settled, and input.requested, authorization events, and agent.started carry the taskId of the task they come from. The subagent.called, subagent.completed, subagent.started, and subagent.event hook events were removed; subscribe to task.started, task.settled, and agent.started.",},},skill: { current: 2, supported: [1, 2], dropped: {} },dynamicSkill: {- current: 24,- supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 24],+ current: 25,+ supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 25],dropped: {13: "Message and reasoning append events now expose deltas instead of cumulative snapshots.",22: "Run mode was removed; sessions always park and ConversationContext no longer carries mode.",23: 'Background task execution was removed: subagent results no longer carry backgroundTask and message.completed always carries text. input.resolved reports outcome "cancelled" when a workflow tool withdraws a ctx.ask() request, and stream events gained agent.started, published when a workflow run opens a ctx.agent session, and turn.waiting, which parks the open turn instead of emitting turn.completed and session.waiting.',+ 24: "Stream events gained task.started and task.settled, and input.requested, authorization events, and agent.started carry the taskId of the task they come from. The subagent.called, subagent.completed, subagent.started, and subagent.event stream events were removed; agent calls report task.started, task.settled, and agent.started.",},},instructions: { current: 2, supported: [1, 2], dropped: {} },dynamicInstructions: {- current: 25,- supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17, 18, 19, 20, 21, 22, 25],+ current: 26,+ supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17, 18, 19, 20, 21, 22, 26],dropped: {14: "Message and reasoning append events now expose deltas instead of cumulative snapshots.",23: "Run mode was removed; sessions always park and ConversationContext no longer carries mode.",24: 'Background task execution was removed: subagent results no longer carry backgroundTask and message.completed always carries text. input.resolved reports outcome "cancelled" when a workflow tool withdraws a ctx.ask() request, and stream events gained agent.started, published when a workflow run opens a ctx.agent session, and turn.waiting, which parks the open turn instead of emitting turn.completed and session.waiting.',+ 25: "Stream events gained task.started and task.settled, and input.requested, authorization events, and agent.started carry the taskId of the task they come from. The subagent.called, subagent.completed, subagent.started, and subagent.event stream events were removed; agent calls report task.started, task.settled, and agent.started.",},},config: { current: 1, supported: [1], dropped: {} },diff --git a/packages/eve/src/compiler/manifest.ts b/packages/eve/src/compiler/manifest.tsindex 318e8015b..419d20b43 100644--- a/packages/eve/src/compiler/manifest.ts+++ b/packages/eve/src/compiler/manifest.ts@@ -831,6 +831,7 @@ const compiledToolBehaviorSchema: z.ZodType<CompiledToolBehavior> = z.strict(),z.object({+ entryPoint: z.enum(["execute", "task", "serve"]),kind: z.literal("workflow-tool"),workflowId: z.string(),})diff --git a/packages/eve/src/compiler/normalize-manifest.test.ts b/packages/eve/src/compiler/normalize-manifest.test.tsindex 0f36a093c..2032becc2 100644--- a/packages/eve/src/compiler/normalize-manifest.test.ts+++ b/packages/eve/src/compiler/normalize-manifest.test.ts@@ -320,6 +320,7 @@ describe("compileAgentManifest source graph", () => {expect(compiled.tools.find((tool) => tool.name === "durable")?.behavior).toEqual({availability: [],handling: {+ entryPoint: "execute",kind: "workflow-tool",workflowId: "workflow//example/tool//execute",},@@ -355,11 +356,10 @@ describe("compileAgentManifest source graph", () => {hasExecute: false,});expect(graph.root.turnAgent.tools.find((tool) => tool.name === "agent")).toMatchObject({- rootOnly: true,- task: {- nodeId: "__root__",- workflowId: expect.stringContaining("subagentToolExecuteWorkflow"),+ behavior: {+ handling: { kind: "dispatch", target: { kind: "self-agent-call", nodeId: "__root__" } },},+ rootOnly: true,});expect(graph.root.turnAgent.tools.find((tool) => tool.name === "web_search")).toMatchObject({behavior: {@@ -696,6 +696,23 @@ describe("compileAgentManifest source graph", () => {);});+ it("reserves the task tools' names", async () => {+ const sourceRegistry = registry([+ {+ logicalPath: "tools/task_cancel.ts",+ loadNamespace: async () => ({+ default: defineTool({ description: "Cancel.", inputSchema: {}, execute: () => null }),+ }),+ },+ ]);++ await expect(+ compileAgentManifest(manifest(), { sourceRegistries: [sourceRegistry] }),+ ).rejects.toThrow(+ 'Tool "tools/task_cancel.ts" uses the reserved name "task_cancel". Rename its path; eve reserves "task_cancel" for its built-in task tool.',+ );+ });+it("projects a local subagent node once", async () => {let toolSourceIterations = 0;const child = createAgentSourceManifest({diff --git a/packages/eve/src/compiler/normalize-tool.ts b/packages/eve/src/compiler/normalize-tool.tsindex 0a17ae809..b63895312 100644--- a/packages/eve/src/compiler/normalize-tool.ts+++ b/packages/eve/src/compiler/normalize-tool.ts@@ -6,7 +6,7 @@ import {loadModuleBackedDefinition,type ModuleBackedDefinitionLoadOptions,} from "#compiler/normalize-helpers.js";-import { readWorkflowFunctionId } from "#internal/workflow/reference.js";+import { TASK_TOOL_NAMES } from "#execution/tasks/calls.js";/*** Compiled tool entry produced from one authored `tools/*.ts` file.@@ -54,6 +54,12 @@ export async function compileToolEntry(.replace(/^tools\//, "").replaceAll("/", "-");+ if (TASK_TOOL_NAMES.includes(toolName)) {+ throw new Error(+ `Tool "${source.logicalPath}" uses the reserved name "${toolName}". Rename its path; eve reserves "${toolName}" for its built-in task tool.`,+ );+ }+if (entry.kind === "disabled") {return { kind: "disabled", name: toolName };}@@ -101,20 +107,20 @@ export async function compileToolEntry(};}- const workflowId = readWorkflowFunctionId(entry.definition.execute);+ const { workflow } = entry.definition;const shape = {- suspend: workflowId === undefined ? ("none" as const) : ("workflow" as const),+ suspend: workflow === undefined ? ("none" as const) : ("workflow" as const),};return {kind: "tool",definition: {availableInSubagents: entry.definition.availableInSubagents,behavior:- workflowId === undefined+ workflow === undefined? entry.definition.behavior === undefined? { availability: [], shape }: { ...entry.definition.behavior, shape }- : { availability: [], handling: { kind: "workflow-tool", workflowId }, shape },+ : { availability: [], handling: { kind: "workflow-tool", ...workflow }, shape },description: entry.definition.description,exportName: source.exportName,hasExecute: entry.definition.hasExecute,diff --git a/packages/eve/src/context/dynamic-skill-lifecycle.test.ts b/packages/eve/src/context/dynamic-skill-lifecycle.test.tsindex 4edb4925d..3e1c0f469 100644--- a/packages/eve/src/context/dynamic-skill-lifecycle.test.ts+++ b/packages/eve/src/context/dynamic-skill-lifecycle.test.ts@@ -118,7 +118,7 @@ function writtenPaths(sandbox: ReturnType<typeof mockSandbox>): string[] {}describe("dispatchDynamicSkillEvent", () => {- it.each(["subagent.called", "subagent.completed", "turn.completed"] as const)(+ it.each(["task.started", "task.settled", "turn.completed"] as const)("does not access the sandbox to rebuild announcements on %s",async (type) => {const ctx = new ContextContainer();diff --git a/packages/eve/src/context/dynamic-subagent-lifecycle.test.ts b/packages/eve/src/context/dynamic-subagent-lifecycle.test.tsindex 897aa87e1..0f3f1a8a8 100644--- a/packages/eve/src/context/dynamic-subagent-lifecycle.test.ts+++ b/packages/eve/src/context/dynamic-subagent-lifecycle.test.ts@@ -185,9 +185,8 @@ describe("dynamic subagent lifecycle", () => {resolvers: [resolver],});expect(buildDynamicSubagentTools(ctx)[0]?.workflowId).toBe(- "workflow//eve//subagentToolExecuteWorkflow",+ "workflow//eve//agentToolServeWorkflow",);- expect(buildDynamicSubagentTools(ctx)[0]?.nodeId).toEqual(expect.any(String));await dispatchDynamicSubagentEvent({ctx,@@ -196,9 +195,8 @@ describe("dynamic subagent lifecycle", () => {resolvers: [resolver],});expect(buildDynamicSubagentTools(ctx)[0]?.workflowId).toBe(- "workflow//eve//subagentToolExecuteWorkflow",+ "workflow//eve//agentToolServeWorkflow",);- expect(buildDynamicSubagentTools(ctx)[0]?.nodeId).toEqual(expect.any(String));});it("exposes a dynamic selection without root configuration", async () => {@@ -224,7 +222,7 @@ describe("dynamic subagent lifecycle", () => {});expect(buildDynamicSubagentTools(ctx)[0]?.workflowId).toBe(- "workflow//eve//subagentToolExecuteWorkflow",+ "workflow//eve//agentToolServeWorkflow",);});@@ -294,7 +292,7 @@ describe("dynamic subagent lifecycle", () => {});expect(buildDynamicSubagentTools(ctx)[0]?.workflowId).toBe(- "workflow//eve//subagentToolExecuteWorkflow",+ "workflow//eve//agentToolServeWorkflow",);});@@ -341,7 +339,7 @@ describe("dynamic subagent lifecycle", () => {kind: "remote",prepared: {inputSchema: {- properties: { agentId: expect.any(Object) },+ properties: { message: expect.any(Object) },},},remoteAgent: {@@ -397,7 +395,7 @@ describe("dynamic subagent lifecycle", () => {});expect(buildDynamicSubagentTools(ctx)[0]?.workflowId).toBe(- "workflow//eve//subagentToolExecuteWorkflow",+ "workflow//eve//agentToolServeWorkflow",);});diff --git a/packages/eve/src/context/keys.ts b/packages/eve/src/context/keys.tsindex 213f5f177..e84e788a6 100644--- a/packages/eve/src/context/keys.ts+++ b/packages/eve/src/context/keys.ts@@ -144,6 +144,13 @@ export const ActivityRootTurnIdKey = new ContextKey<string>("eve.activityRootTurexport const ActivityPendingBlockersKey = new ContextKey<readonly string[]>("eve.activityPendingBlockers",);+/**+ * Call IDs that got `task.started` this turn, so their `action.result` is a+ * receipt that leaves the activity running. Not read from the task table: a+ * call leaves it once it settles, which can happen before its receipt is+ * published. Cleared at turn end.+ */+export const ActivityTaskCallsKey = new ContextKey<readonly string[]>("eve.activityTaskCalls");/*** Optional framework-owned caller callback captured when the session is created.diff --git a/packages/eve/src/evals/assertions/run.test.ts b/packages/eve/src/evals/assertions/run.test.tsindex 4fbf5a4ac..1455945c8 100644--- a/packages/eve/src/evals/assertions/run.test.ts+++ b/packages/eve/src/evals/assertions/run.test.ts@@ -315,28 +315,19 @@ describe("run assertions", () => {it("matches typed event counts and ordered event groups", async () => {const called = {- type: "subagent.called",- data: {- name: "child",- callId: "c",- childSessionId: "s",- sessionId: "p",- sequence: 1,- toolName: "subagent",- turnId: "t",- workflowId: "w",- },+ type: "task.started",+ data: { callId: "c", kind: "agent", name: "child", taskId: "child-1", turnId: "t" },} as UnstampedMessageStreamEvent;const completed = {- type: "subagent.completed",- data: { callId: "c", output: "ok", sequence: 2, subagentName: "child", turnId: "t" },+ type: "task.settled",+ data: { callId: "c", output: "ok", status: "completed", taskId: "child-1" },} as UnstampedMessageStreamEvent;const result = makeResult({ events: [called, called, completed] });expect((await Run.typedEvent({- type: "subagent.called",+ type: "task.started",data: { name: "child" },count: 2,}).evaluate(result)@@ -345,7 +336,7 @@ describe("run assertions", () => {expect((await Run.typedEvent({- type: "subagent.called",+ type: "task.started",data: { name: "child" },count: (count) => count >= 2,}).evaluate(result)@@ -355,8 +346,8 @@ describe("run assertions", () => {expect((await Run.eventOrder([- { type: "subagent.called", data: { name: "child" }, count: 2 },- { type: "subagent.completed", data: { subagentName: "child" } },+ { type: "task.started", data: { name: "child" }, count: 2 },+ { type: "task.settled", data: { taskId: "child-1" } },]).evaluate(result)).score,).toBe(1);@@ -364,13 +355,13 @@ describe("run assertions", () => {(await Run.eventOrder([{- type: "subagent.called",+ type: "task.started",data: { name: "child" },count: (count) => count >= 2,},{- type: "subagent.completed",- data: { subagentName: "child" },+ type: "task.settled",+ data: { taskId: "child-1" },count: (count) => count >= 1,},]).evaluate(result)@@ -380,7 +371,7 @@ describe("run assertions", () => {(await Run.eventsSatisfy("completion follows delegation",- (events) => events.at(-1)?.type === "subagent.completed",+ (events) => events.at(-1)?.type === "task.settled",).evaluate(result)).score,).toBe(1);@@ -388,29 +379,20 @@ describe("run assertions", () => {it("eventOrder rejects interleaved event groups", async () => {const called = {- type: "subagent.called",- data: {- name: "child",- callId: "c",- childSessionId: "s",- sessionId: "p",- sequence: 1,- toolName: "subagent",- turnId: "t",- workflowId: "w",- },+ type: "task.started",+ data: { callId: "c", kind: "agent", name: "child", taskId: "child-1", turnId: "t" },} as UnstampedMessageStreamEvent;const completed = {- type: "subagent.completed",- data: { callId: "c", output: "ok", sequence: 2, subagentName: "child", turnId: "t" },+ type: "task.settled",+ data: { callId: "c", output: "ok", status: "completed", taskId: "child-1" },} as UnstampedMessageStreamEvent;const result = makeResult({ events: [called, completed, called] });expect((await Run.eventOrder([- { type: "subagent.called", data: { name: "child" }, count: 2 },- { type: "subagent.completed", data: { subagentName: "child" } },+ { type: "task.started", data: { name: "child" }, count: 2 },+ { type: "task.settled", data: { taskId: "child-1" } },]).evaluate(result)).score,).toBe(0);diff --git a/packages/eve/src/evals/assertions/run.ts b/packages/eve/src/evals/assertions/run.tsindex 8ee86767a..34822d7df 100644--- a/packages/eve/src/evals/assertions/run.ts+++ b/packages/eve/src/evals/assertions/run.ts@@ -224,9 +224,10 @@ export function noFailedActions(): RunAssertion {}/**- * Asserts a subagent delegation to `name` occurred. Identity and remote- * metadata come from `subagent.called`; `output` comes from- * `subagent.completed`.+ * Asserts a call to the agent tool `name` occurred. Each call to an agent+ * task counts once: its status and `output` come from `task.settled`, and the+ * session and remote metadata from the task's `agent.started` once its+ * session opened.*/export function calledSubagent(name: string,diff --git a/packages/eve/src/evals/index.ts b/packages/eve/src/evals/index.tsindex 34f87fb43..75eafea72 100644--- a/packages/eve/src/evals/index.ts+++ b/packages/eve/src/evals/index.ts@@ -32,6 +32,7 @@ export type {AssertionResult,AssertionSeverity,EveEvalActionStatus,+ EveEvalAgentSession,EveEvalAssertions,EveEvalContext,EveEvalDerivedFacts,diff --git a/packages/eve/src/evals/match.ts b/packages/eve/src/evals/match.tsindex 4ef3381f9..6e3b1151b 100644--- a/packages/eve/src/evals/match.ts+++ b/packages/eve/src/evals/match.ts@@ -58,13 +58,13 @@ export type EveEvalSkillLoadMatchOptions = Omit<EveEvalToolCallMatchOptions, "in* Constraints applied to subagent calls by `t.calledSubagent`.*/export interface EveEvalSubagentCallMatchOptions {- /** Matcher over the runtime-action call id. */+ /** Matcher over the agent tool call id. */readonly callId?: EveEvalValueMatcher<string | undefined>;- /** Matcher over the durable child session id, when delegation started. */+ /** Matcher over the id of the agent's session. */readonly childSessionId?: EveEvalValueMatcher<string | undefined>;- /** Matcher over the `subagent.called` remote URL. */+ /** Matcher over the `agent.started` remote URL. */readonly remoteUrl?: EveEvalValueMatcher<string | undefined>;- /** Matcher over the `subagent.completed` output. */+ /** Matcher over the output of the call's `task.settled`. */readonly output?: EveEvalValueMatcher;/** Required lifecycle outcome. Defaults to `"completed"`. */readonly status?: EveEvalSubagentCall["status"];diff --git a/packages/eve/src/evals/mock-model.test.ts b/packages/eve/src/evals/mock-model.test.tsindex de81ab596..4f289fa9b 100644--- a/packages/eve/src/evals/mock-model.test.ts+++ b/packages/eve/src/evals/mock-model.test.ts@@ -68,7 +68,7 @@ describe("mockModel", () => {it("keeps framework scaffolding out of authored user messages", async () => {const requests: MockModelRequest[] = [];- const agents = "[Agents]\n<agents>\n</agents>";+ const tasks = "[Tasks]\n<tasks>\n</tasks>";const notice = ["[Pending approvals]","The following tool calls are awaiting approval and have not executed:",@@ -77,7 +77,7 @@ describe("mockModel", () => {const result = await generateText({messages: [{ content: "Run the mixed approval flow.", role: "user" },- { content: agents, role: "user" },+ { content: tasks, role: "user" },{ content: notice, role: "user" },],model: mockModel((request) => {@@ -91,7 +91,7 @@ describe("mockModel", () => {lastUserMessage: "Run the mixed approval flow.",messages: [{ role: "user", text: "Run the mixed approval flow." },- { role: "user", text: agents },+ { role: "user", text: tasks },{ role: "user", text: notice },],userMessageCount: 1,diff --git a/packages/eve/src/evals/mock-model.ts b/packages/eve/src/evals/mock-model.tsindex 3bf0cea81..5d2e14f44 100644--- a/packages/eve/src/evals/mock-model.ts+++ b/packages/eve/src/evals/mock-model.ts@@ -2,7 +2,7 @@ import type { LanguageModel } from "ai";import { MockLanguageModelV3 } from "ai/test";import { markMockModel } from "#internal/mock-model-identity.js";-import { AGENTS_SNIPPET_LABEL } from "#subagents/handles/prompt.js";+import { TASK_RESULT_TAG, TASKS_NOTE_LABEL } from "#execution/tasks/render.js";import { isPendingApprovalsSnippet } from "#harness/hitl/approval-prompt.js";type GenerateOptions = Parameters<MockLanguageModelV3["doGenerate"]>[0];@@ -177,9 +177,14 @@ function createRequest(options: GenerateOptions): MockModelRequest {};}+/** Framework-injected listings and task results, which no one authored. */function isFrameworkScaffolding(message: string): boolean {const text = message.trim();- return text.startsWith(AGENTS_SNIPPET_LABEL) || isPendingApprovalsSnippet(text);+ return (+ text.startsWith(TASKS_NOTE_LABEL) ||+ text.startsWith(TASK_RESULT_TAG) ||+ isPendingApprovalsSnippet(text)+ );}function extractMessageText(message: GenerateOptions["prompt"][number]): string {diff --git a/packages/eve/src/evals/runner/derive-run-facts.test.ts b/packages/eve/src/evals/runner/derive-run-facts.test.tsindex e91f7f5b3..e151fa648 100644--- a/packages/eve/src/evals/runner/derive-run-facts.test.ts+++ b/packages/eve/src/evals/runner/derive-run-facts.test.ts@@ -66,33 +66,30 @@ function actionResult(input: {};}-function subagentResult(input: {- callId: string;- subagentName: string;- output: unknown;- status: "completed" | "failed" | "rejected";-}): UnstampedMessageStreamEvent {- return {- type: "action.result",- data: {- result: {- callId: input.callId,- kind: "subagent-result",- origin: "child",- outcome: {- kind: "terminal",- result: { kind: "succeeded", output: input.output as never },- usageDelta: { cacheReadTokens: 0, cacheWriteTokens: 0, inputTokens: 0, outputTokens: 0 },- },- output: input.output as never,- subagentName: input.subagentName,- },- sequence: 1,- stepIndex: 0,- status: input.status,- turnId: "t1",- },+function taskStarted(+ callId: string,+ name: string,+ taskId: string,+ kind: "agent" | "tool",+): UnstampedMessageStreamEvent {+ return { type: "task.started", data: { callId, kind, name, taskId, turnId: "t1" } };+}++function agentStarted(+ callId: string,+ name: string,+ taskId: string,+ remote?: { readonly url: string },+): UnstampedMessageStreamEvent {+ const data = {+ callId,+ name,+ sessionId: `child-${callId}`,+ streamPath: `/stream/${callId}`,+ taskId,+ turnId: "t1",};+ return { type: "agent.started", data: remote === undefined ? data : { ...data, remote } };}function inputRequested(requestIds: readonly string[]): UnstampedMessageStreamEvent {@@ -347,137 +344,85 @@ describe("deriveRunFacts", () => {expect(facts.reasoningBlockCount).toBe(2);});- it("joins subagent.called with subagent.completed by call id", () => {- const events: UnstampedMessageStreamEvent[] = [- turnStarted("t1", 0),- {- type: "subagent.called",- data: {- callId: "c1",- childSessionId: "s1",- childStreamPath: "/eve/v1/session/s0/subagents/c1/s1/stream",- sessionId: "s0",- sequence: 1,- name: "weather",- remote: { url: "http://127.0.0.1:4001" },- toolName: "call_weather",- turnId: "t1",- workflowId: "w1",+ it("derives one subagent call per call to an agent task", () => {+ const facts = derive(+ [+ turnStarted("t1", 0),+ taskStarted("c1", "weather", "weather-1", "agent"),+ agentStarted("c1", "weather", "weather-1", { url: "http://127.0.0.1:4001" }),+ {+ type: "task.settled",+ data: {+ callId: "c1",+ output: "Sunny, 72F",+ status: "completed",+ taskId: "weather-1",+ turnId: "t1",+ },},- },- {- type: "subagent.completed",- data: { callId: "c1", output: "Sunny, 72F", subagentName: "weather" },- },- ];+ turnStarted("t2", 1),+ taskStarted("c2", "weather", "weather-1", "agent"),+ ],+ { sessionId: "s0" },+ );- const facts = derive(events, { sessionId: "s0" });expect(facts.subagentCalls).toEqual([{callId: "c1",- childSessionId: "s1",+ childSessionId: "child-c1",name: "weather",- remoteUrl: "http://127.0.0.1:4001",output: "Sunny, 72F",+ remoteUrl: "http://127.0.0.1:4001",+ sessionId: "s0",status: "completed",turnIndex: 0,+ },+ {+ callId: "c2",+ childSessionId: "child-c1",+ name: "weather",+ output: undefined,+ remoteUrl: "http://127.0.0.1:4001",sessionId: "s0",+ status: "working",+ turnIndex: 1,},]);- expect(facts.subagentCallCount).toBe(1);});- it("derives failed subagent calls from result-only events", () => {+ it("counts agent tasks by kind, not by the sessions tasks open", () => {const facts = derive([- turnStarted("t1", 0),- subagentResult({- callId: "c1",- subagentName: "weather",- output: { code: "REMOTE_AGENT_START_FAILED" },- status: "failed",- }),+ taskStarted("c1", "agent_router", "agent_router-1", "tool"),+ agentStarted("c1", "weather", "agent_router-1"),+ taskStarted("c2", "research", "research-1", "tool"),+ agentStarted("c2", "research", "research-1"),+ taskStarted("c3", "weather", "weather-1", "agent"),+ {+ type: "task.settled",+ data: {+ callId: "c3",+ error: { message: "Remote agent is unreachable." },+ status: "failed",+ taskId: "weather-1",+ turnId: "t1",+ },+ },]);expect(facts.subagentCalls).toEqual([{- callId: "c1",+ callId: "c3",+ childSessionId: undefined,name: "weather",- output: { code: "REMOTE_AGENT_START_FAILED" },+ output: undefined,+ remoteUrl: undefined,+ sessionId: undefined,status: "failed",turnIndex: 0,- sessionId: undefined,},]);});- it("extracts inline subagent calls from subagent.started events", () => {- const events: UnstampedMessageStreamEvent[] = [- {- type: "subagent.started",- data: { callId: "c1", subagentName: "inline-agent" },- },- ];- const facts = derive(events);- expect(facts.subagentCalls.map((call) => call.name)).toEqual(["inline-agent"]);- expect(facts.subagentCalls[0]?.status).toBe("working");- });-- it("preserves explicit cancellation even when the action reports failure or a late completion", () => {- const cancelled: UnstampedMessageStreamEvent = {- type: "action.result",- data: {- sequence: 1,- stepIndex: 0,- turnId: "t1",- status: "failed",- result: {- callId: "c1",- kind: "subagent-result",- origin: "child",- subagentName: "researcher",- isError: true,- output: "The agent invocation was cancelled.",- outcome: {- kind: "parked",- result: { kind: "cancelled" },- usageDelta: {- inputTokens: 0,- outputTokens: 0,- cacheReadTokens: 0,- cacheWriteTokens: 0,- },- },- },- },- };- const lateCompletion: UnstampedMessageStreamEvent = {- type: "subagent.completed",- data: { callId: "c1", subagentName: "researcher", output: "late result" },- };- for (const events of [[cancelled], [cancelled, lateCompletion]]) {- expect(derive(events).subagentCalls[0]).toMatchObject({- status: "cancelled",- output: "The agent invocation was cancelled.",- });- }- });-- it("records every subagent invocation separately", () => {- const events: UnstampedMessageStreamEvent[] = [- {- type: "subagent.started",- data: { callId: "c1", subagentName: "agent-a" },- },- {- type: "subagent.started",- data: { callId: "c2", subagentName: "agent-a" },- },- ];- const facts = derive(events);- expect(facts.subagentCalls.map((call) => call.name)).toEqual(["agent-a", "agent-a"]);- expect(facts.subagentCallCount).toBe(2);- });-it("captures failure code from session.failed event", () => {const events: UnstampedMessageStreamEvent[] = [{diff --git a/packages/eve/src/evals/runner/derive-run-facts.ts b/packages/eve/src/evals/runner/derive-run-facts.tsindex 9eb1a6580..819e8db57 100644--- a/packages/eve/src/evals/runner/derive-run-facts.ts+++ b/packages/eve/src/evals/runner/derive-run-facts.ts@@ -1,4 +1,8 @@-import type { MessageStreamEvent } from "#protocol/message.js";+import type {+ AgentStartedStreamEvent,+ MessageStreamEvent,+ TaskSettledStreamEvent,+} from "#protocol/message.js";import { LOAD_SKILL_TOOL_NAME } from "#runtime/skills/fragment-context.js";import type { InputRequest } from "#shared/input.js";import type { JsonObject, JsonValue } from "#shared/json.js";@@ -13,15 +17,12 @@ interface MutableToolCall {sessionId?: string;}-interface MutableSubagentCall {- callId: string;- childSessionId?: string;- name: string;- remoteUrl?: string;- output?: JsonValue;- status: EveEvalSubagentCall["status"];- turnIndex: number;- sessionId?: string;+/** One call to an agent task, as `task.started` reports it. */+interface AgentCall {+ readonly callId: string;+ readonly name: string;+ readonly taskId: string;+ readonly turnIndex: number;}/**@@ -48,9 +49,9 @@ const PARKING_EVENT_TYPES: ReadonlySet<MessageStreamEvent["type"]> = new Set([* Extracts derived execution facts from a completed run's stream events.** Tool calls pair each `actions.requested` entry with its matching- * `action.result` by call id; subagent calls join `subagent.called` /- * `subagent.started` with `subagent.completed` the same way. These facts- * power checks, scorers, and reporters.+ * `action.result` by call id. Subagent calls are the calls to agent tasks,+ * paired with their `task.settled` the same way. These facts power checks,+ * scorers, and reporters.*/export function deriveRunFacts(events: readonly MessageStreamEvent[],@@ -59,8 +60,9 @@ export function deriveRunFacts(const sessionId = options?.sessionId;const toolCalls: MutableToolCall[] = [];const toolCallsByCallId = new Map<string, MutableToolCall>();- const subagentCalls: MutableSubagentCall[] = [];- const subagentCallsByCallId = new Map<string, MutableSubagentCall>();+ const agentCalls: AgentCall[] = [];+ const settledTaskCalls = new Map<string, TaskSettledStreamEvent["data"]>();+ const agentSessions: AgentStartedStreamEvent["data"][] = [];const inputRequests: InputRequest[] = [];let turnIndex = -1;let messageCount = 0;@@ -84,22 +86,6 @@ export function deriveRunFacts(return call;};- const ensureSubagentCall = (callId: string, name: string): MutableSubagentCall => {- const existing = subagentCallsByCallId.get(callId);- if (existing !== undefined) return existing;-- const call: MutableSubagentCall = {- callId,- name,- status: "working",- turnIndex: Math.max(turnIndex, 0),- sessionId,- };- subagentCalls.push(call);- subagentCallsByCallId.set(callId, call);- return call;- };-for (const event of events) {switch (event.type) {case "turn.started": {@@ -124,43 +110,24 @@ export function deriveRunFacts(const call = ensureToolCall(result.callId, result.toolName, {});call.output = result.output;call.status = status;- // An agent tool runs as a workflow tool; its tool result settles the delegation.- const subagentCall = subagentCallsByCallId.get(result.callId);- if (subagentCall?.status === "working") {- subagentCall.output ??= result.output;- subagentCall.status = status === "rejected" ? "failed" : status;- }- } else if (result.kind === "subagent-result") {- const call = ensureSubagentCall(result.callId, result.subagentName);- call.output = call.output ?? result.output;- if (result.origin === "child" && result.outcome.result.kind === "cancelled") {- call.status = "cancelled";- } else {- call.status = status === "rejected" ? "failed" : status;- }}break;}- case "subagent.called": {- const call = ensureSubagentCall(event.data.callId, event.data.name);- call.childSessionId = event.data.childSessionId;- if (event.data.remote !== undefined) {- call.remoteUrl = event.data.remote.url;- }+ case "task.started": {+ const { callId, kind, name, taskId } = event.data;+ if (kind !== "agent") break;+ agentCalls.push({ callId, name, taskId, turnIndex: Math.max(turnIndex, 0) });break;}- case "subagent.started": {- ensureSubagentCall(event.data.callId, event.data.subagentName);+ case "task.settled": {+ settledTaskCalls.set(event.data.callId, event.data);break;}- case "subagent.completed": {- const call = ensureSubagentCall(event.data.callId, event.data.subagentName);- if (call.status !== "working") break;- call.output = event.data.output;- call.status = "completed";+ case "agent.started": {+ agentSessions.push(event.data);break;}@@ -191,10 +158,16 @@ export function deriveRunFacts(}}+ const subagentCalls = deriveSubagentCalls({+ agentCalls,+ agentSessions,+ sessionId,+ settledTaskCalls,+ });return {toolCalls: toolCalls as readonly EveEvalToolCall[],toolCallCount: toolCalls.length,- subagentCalls: subagentCalls as readonly EveEvalSubagentCall[],+ subagentCalls,subagentCallCount: subagentCalls.length,inputRequests,parked: endedParkedOnInput(events),@@ -204,6 +177,36 @@ export function deriveRunFacts(};}+/**+ * Every call to an agent task, with its session from the task's+ * `agent.started` once that session opened.+ */+function deriveSubagentCalls(input: {+ readonly agentCalls: readonly AgentCall[];+ readonly agentSessions: readonly AgentStartedStreamEvent["data"][];+ readonly sessionId: string | undefined;+ readonly settledTaskCalls: ReadonlyMap<string, TaskSettledStreamEvent["data"]>;+}): EveEvalSubagentCall[] {+ const agentSessionsByTaskId = new Map<string, AgentStartedStreamEvent["data"]>();+ for (const session of input.agentSessions) {+ if (session.taskId !== undefined) agentSessionsByTaskId.set(session.taskId, session);+ }+ return input.agentCalls.map((call) => {+ const session = agentSessionsByTaskId.get(call.taskId);+ const settled = input.settledTaskCalls.get(call.callId);+ return {+ callId: call.callId,+ childSessionId: session?.sessionId,+ name: call.name,+ output: settled?.output,+ remoteUrl: session?.remote?.url,+ sessionId: input.sessionId,+ status: settled?.status ?? "working",+ turnIndex: call.turnIndex,+ };+ });+}+/*** Returns empty derived facts, used when a case produced no events* (execution errors, transport failures).diff --git a/packages/eve/src/evals/runner/execute-task.test.ts b/packages/eve/src/evals/runner/execute-task.test.tsindex ab8b08405..3297ba466 100644--- a/packages/eve/src/evals/runner/execute-task.test.ts+++ b/packages/eve/src/evals/runner/execute-task.test.ts@@ -671,7 +671,7 @@ describe("executeTask", () => {sessionId: "parent-session",events: [turnStarted("parent-turn"),- subagentCalled("parent-turn", "child-session", "sleeper"),+ agentStarted("child-session", "sleeper"),turnCompleted("parent-turn"),sessionWaiting(),],@@ -711,12 +711,12 @@ describe("executeTask", () => {const parent = await conversation.start("delegate");expect(parent.sessionId).toBe("parent-session");- const called = await parent.waitForEvent("subagent.called", {+ const started = await parent.waitForEvent("agent.started", {data: { name: "sleeper" },});- expect(called.data.childSessionId).toBe("child-session");+ expect(started.data.sessionId).toBe("child-session");- const child = t.target.watchTurn(called.data.childSessionId);+ const child = t.target.watchTurn(started.data.sessionId);const requested = await child.waitForEvent("actions.requested", {data: {actions: (actions) =>@@ -734,9 +734,9 @@ describe("executeTask", () => {const [parentTurn, childTurn] = await Promise.all([parent.result(), child.result()]);expect(await parent.result()).toBe(parentTurn);- parentTurn.event("subagent.called", { count: 1 });+ parentTurn.event("agent.started", { count: 1 });childTurn.calledTool("wait-for-cancellation", { status: "pending", count: 1 });- await expect(parent.waitForEvent("subagent.completed")).rejects.toThrow(/session\.waiting/);+ await expect(parent.waitForEvent("task.settled")).rejects.toThrow(/session\.waiting/);const childFollowUp = await child.session.send("continue child");childFollowUp.messageIncludes("child continued");@@ -1134,23 +1134,15 @@ function actionsRequested(};}-function subagentCalled(- turnId: string,- childSessionId: string,- name: string,-): UnstampedMessageStreamEvent {+function agentStarted(sessionId: string, name: string): UnstampedMessageStreamEvent {return {data: {callId: "call_subagent",- childSessionId,- childStreamPath: `/eve/v1/session/${encodeURIComponent(childSessionId)}/stream`,- sessionId: "parent-session",- sequence: 1,name,- toolName: name,- turnId,- workflowId: "workflow_child",+ sessionId,+ streamPath: `/eve/v1/session/${encodeURIComponent(sessionId)}/stream`,+ turnId: "turn_1",},- type: "subagent.called",+ type: "agent.started",};}diff --git a/packages/eve/src/evals/session.ts b/packages/eve/src/evals/session.tsindex 3b05d6014..8c6917664 100644--- a/packages/eve/src/evals/session.ts+++ b/packages/eve/src/evals/session.ts@@ -15,7 +15,6 @@ import type {MessageStreamEvent,RuntimeTraceContext,AgentStartedStreamEvent,- SubagentCalledStreamEvent,TurnFailureStreamEvent,} from "#protocol/message.js";import { isTurnFailureEvent } from "#protocol/message.js";@@ -33,6 +32,7 @@ import { createOutputAssertions, createScopedAssertions } from "#evals/assertionimport { EvalRequirementFailed } from "#evals/control-flow.js";import { inputRequestMatches, matchesValue, toolCallMatches } from "#evals/match.js";import type {+ EveEvalAgentSession,EveEvalAssertions,EveEvalDerivedFacts,EveEvalLiveTurn,@@ -151,14 +151,16 @@ export class EvalSessionDriver implements EveEvalSession {return await this.#session.cancel();}- streamSubagent(- started: AgentStartedStreamEvent | SubagentCalledStreamEvent,- options: StreamOptions = {},- ): AsyncIterable<MessageStreamEvent> {- return this.#session.streamSubagent(started, {- ...options,- signal: options.signal ?? this.#signal,- });+ agent(started: AgentStartedStreamEvent): EveEvalAgentSession {+ const child = this.#session.agent(started);+ const signal = this.#signal;+ return {+ name: child.name,+ sessionId: child.sessionId,+ stream: (options: StreamOptions = {}) =>+ child.stream({ ...options, signal: options.signal ?? signal }),+ taskId: child.taskId,+ };}/** @internal */diff --git a/packages/eve/src/evals/types.ts b/packages/eve/src/evals/types.tsindex 208d326cb..3de9073e7 100644--- a/packages/eve/src/evals/types.ts+++ b/packages/eve/src/evals/types.ts@@ -1,12 +1,12 @@import type { Experimental_EvaluationModel as EvaluationModel } from "ai";import type { StandardSchemaV1 } from "#compiled/@standard-schema/spec/index.js";+import type { ClientAgentSession } from "#client/agent-session.js";import type {RuntimeIdentity,RuntimeTraceContext,MessageStreamEvent,AgentStartedStreamEvent,- SubagentCalledStreamEvent,} from "#protocol/message.js";import type {CancelSessionResult,@@ -14,7 +14,6 @@ import type {CreateSessionOptions,SendTurnInput,SendTurnOptions,- StreamOptions,} from "#client/types.js";import type { InputRequest, InputResponse } from "#shared/input.js";import type { JsonObject, JsonValue } from "#shared/json.js";@@ -51,21 +50,22 @@ export interface EveEvalToolCall {}/**- * One subagent delegation extracted from the captured stream- * (`subagent.called` / `subagent.started`, joined with `subagent.completed`).+ * One call to an agent task extracted from the captured stream: its+ * `task.started`, joined with its `task.settled` and the task's+ * `agent.started`.*/export interface EveEvalSubagentCall {- /** Runtime-action call id joining this delegation's lifecycle events, when observed. */+ /** The agent tool call's id, as on its task events. */readonly callId?: string;- /** Durable child session id for local and remote workflow delegations. */+ /** The agent's session id, shared by every call to one task; absent if it never opened. */readonly childSessionId?: string;/** Subagent name. */readonly name: string;- /** Remote agent URL for remote delegations (`subagent.called` remote metadata). */+ /** Remote agent URL for remote delegations (`agent.started` remote metadata). */readonly remoteUrl?: string;- /** Output from the matching `subagent.completed` event; `undefined` when the call never completed. */+ /** Output from the call's `task.settled`; `undefined` until the call completes. */readonly output?: JsonValue;- /** Delegation status inferred from the captured delegation events. */+ /** The call's task status: `working` until its `task.settled` arrives. */readonly status: "working" | "completed" | "failed" | "cancelled";/** Zero-based index of the turn the delegation happened in. */readonly turnIndex: number;@@ -328,16 +328,19 @@ interface EveEvalSessionDriver {/** Send one text turn with a local file attached as a data URL. */sendFile(text: string, filePath: string, mediaType?: string): Promise<EveEvalTurn>;/**- * Follow one delegated child's stream through this parent session, with the- * eval client's credentials. Local children use their own stream route; remote- * children use the parent-origin proxy.+ * The session an agent run opened, as this session's stream announced it with+ * `agent.started`. Its `stream()` follows the child through this parent session+ * with the eval client's credentials, and stops with the eval unless given a `signal`.*/- streamSubagent(- started: AgentStartedStreamEvent | SubagentCalledStreamEvent,- options?: StreamOptions,- ): AsyncIterable<MessageStreamEvent>;+ agent(started: AgentStartedStreamEvent): EveEvalAgentSession;}+/** A session an agent run opened, reached through the parent eval session. */+export type EveEvalAgentSession = Pick<+ ClientAgentSession,+ "name" | "sessionId" | "stream" | "taskId"+>;+/** One accepted session, exposed by `t.session()`, turns, and target attachment helpers. */export interface EveEvalSessionextends EveEvalSessionDriver, EveEvalAssertions, EveEvalOutputAssertions {}diff --git a/packages/eve/src/eve-channel/index.ts b/packages/eve/src/eve-channel/index.tsindex 73afda89d..dc49b32ea 100644--- a/packages/eve/src/eve-channel/index.ts+++ b/packages/eve/src/eve-channel/index.ts@@ -613,7 +613,6 @@ export function eveChannel(input: EveChannelInput): EveChannel {callId,childSessionId,childStreamPath,- parentSessionId,parent,});if (found === undefined) {diff --git a/packages/eve/src/eve-channel/support.ts b/packages/eve/src/eve-channel/support.tsindex a072864f0..4f189aa43 100644--- a/packages/eve/src/eve-channel/support.ts+++ b/packages/eve/src/eve-channel/support.ts@@ -36,13 +36,9 @@ interface RemoteAgentStreamCoordinates {readonly callId: string;readonly childSessionId: string;readonly childStreamPath: string;- readonly parentSessionId: string;}-/**- * Finds the remote child the parent session recorded for one proxy route, from- * its `agent.started` event or, for the model's agent tools, `subagent.called`.- */+/** Finds the remote child the parent session recorded for one proxy route, from its `agent.started` event. */export async function findRemoteAgentBinding(input: RemoteAgentStreamCoordinates & {readonly parent: {@@ -75,27 +71,15 @@ function readRemoteAgentBinding(event: MessageStreamEvent,coordinates: RemoteAgentStreamCoordinates,): RemoteAgentBinding | undefined {- if (event.type === "agent.started") {- const { data } = event;- // The stream path embeds the parent session id, so matching it binds the parent.- const matches =- data.callId === coordinates.callId &&- data.sessionId === coordinates.childSessionId &&- data.streamPath === coordinates.childStreamPath;- if (!matches || data.remote === undefined) return undefined;- return { name: data.name, ...data.remote };- }- if (event.type === "subagent.called") {- const { data } = event;- const matches =- data.sessionId === coordinates.parentSessionId &&- data.callId === coordinates.callId &&- data.childSessionId === coordinates.childSessionId &&- data.childStreamPath === coordinates.childStreamPath;- if (!matches || data.remote === undefined) return undefined;- return { name: data.toolName, ...data.remote };- }- return undefined;+ if (event.type !== "agent.started") return undefined;+ const { data } = event;+ // The stream path embeds the parent session id, so matching it binds the parent.+ const matches =+ data.callId === coordinates.callId &&+ data.sessionId === coordinates.childSessionId &&+ data.streamPath === coordinates.childStreamPath;+ if (!matches || data.remote === undefined) return undefined;+ return { name: data.name, ...data.remote };}export function normalizeEveCors(cors: EveChannelCors | undefined): ChannelCors {diff --git a/packages/eve/src/execution/activity-cohort.ts b/packages/eve/src/execution/activity-cohort.tsindex 76ac9b963..c2c1579fa 100644--- a/packages/eve/src/execution/activity-cohort.ts+++ b/packages/eve/src/execution/activity-cohort.ts@@ -6,6 +6,7 @@ import {ActivityObserverKey,ActivityPendingBlockersKey,ActivityRootTurnIdKey,+ ActivityTaskCallsKey,} from "#context/keys.js";import {activityRequestIdsForRootTurn,@@ -66,12 +67,22 @@ export function restoreAuthorizationActivity(input: {return ids;}-export function updateActivityBlockers(+/** Tracks the pending blockers and task calls that activity projection reads. */+export function updateActivityState(ctx: ContextContainer,event: UnstampedMessageStreamEvent,): void {if (!ctx.has(ActivityObserverKey)) return;- if (event.type === "input.requested") {+ if (event.type === "task.started") {+ addActivityTaskCall(ctx, event.data.callId);+ } else if (+ event.type === "turn.completed" ||+ event.type === "turn.failed" ||+ event.type === "turn.cancelled"+ ) {+ // Every receipt of the turn's task calls is published before the turn ends.+ ctx.delete(ActivityTaskCallsKey);+ } else if (event.type === "input.requested") {addActivityBlockers(ctx,event.data.requests.map((request) => request.requestId),@@ -95,6 +106,10 @@ export function clearActivityBlockers(ctx: ContextContainer, ids: readonly strinelse ctx.set(ActivityPendingBlockersKey, remaining);}+function addActivityTaskCall(ctx: ContextContainer, callId: string): void {+ ctx.set(ActivityTaskCallsKey, [...(ctx.get(ActivityTaskCallsKey) ?? []), callId]);+}+function addActivityBlockers(ctx: ContextContainer, ids: readonly string[]): void {ctx.set(ActivityPendingBlockersKey, [...new Set([...(ctx.get(ActivityPendingBlockersKey) ?? []), ...ids]),diff --git a/packages/eve/src/execution/activity-events.ts b/packages/eve/src/execution/activity-events.tsindex 91f758651..eb72a162e 100644--- a/packages/eve/src/execution/activity-events.ts+++ b/packages/eve/src/execution/activity-events.ts@@ -1,6 +1,10 @@import { normalizePresentationText } from "#shared/presentation-text.js";import { deriveChildActivityWorkId } from "#execution/activity-work-id.js";-import type { ActivityEventV1, ActivityWorkIdentityV1 } from "#protocol/activity.js";+import type {+ ActivityActionPhase,+ ActivityEventV1,+ ActivityWorkIdentityV1,+} from "#protocol/activity.js";import type { UnstampedMessageStreamEvent } from "#protocol/message.js";export function projectActivityEvents(input: {@@ -8,6 +12,8 @@ export function projectActivityEvents(input: {readonly event: UnstampedMessageStreamEvent;readonly eventId?: string;readonly lineage: ActivityWorkIdentityV1;+ /** Calls to tasks: their `action.result` is a receipt, and `task.settled` settles them. */+ readonly taskCallIds?: readonly string[];}): readonly ActivityEventV1[] {const { event, lineage } = input;if (event.type === "actions.requested") {@@ -87,8 +93,8 @@ export function projectActivityEvents(input: {}const id = actionId(lineage.id, result.callId);const label = activityLabel(event.data.presentation?.[result.callId]?.label);- return [- ...(label === undefined+ const labelUpdates =+ label === undefined? []: [{@@ -97,15 +103,14 @@ export function projectActivityEvents(input: {kind: "action.label.updated" as const,label,},- ]),- {- actionId: id,- eventId: `${id}:settled:${event.data.status}`,- kind: "action.settled",- outcome: event.data.status,- settledAt: input.at,- },- ];+ ];+ const isTaskReceipt = input.taskCallIds?.includes(result.callId) === true;+ if (isTaskReceipt) return labelUpdates;+ return [...labelUpdates, actionSettled(id, event.data.status, input.at)];+ }+ if (event.type === "task.settled") {+ const id = actionId(lineage.id, event.data.callId);+ return [actionSettled(id, event.data.status, input.at)];}if (event.type === "authorization.required") {const id = blockerId(@@ -246,6 +251,20 @@ export function projectActivityEvents(input: {return [];}+function actionSettled(+ id: string,+ outcome: Exclude<ActivityActionPhase, "running">,+ settledAt: string,+): ActivityEventV1 {+ return {+ actionId: id,+ eventId: `${id}:settled:${outcome}`,+ kind: "action.settled",+ outcome,+ settledAt,+ };+}+function activityLabel(value: string | undefined): string | undefined {if (value === undefined) return undefined;const normalized = normalizePresentationText(value);diff --git a/packages/eve/src/execution/activity-work-id.ts b/packages/eve/src/execution/activity-work-id.tsindex fc685751f..eab2d4ee6 100644--- a/packages/eve/src/execution/activity-work-id.ts+++ b/packages/eve/src/execution/activity-work-id.ts@@ -1,7 +1,5 @@import { createHash } from "node:crypto";-import { deriveAgentOperationId } from "#subagents/handles/operation-id.js";-export function deriveRootTurnActivityWorkId(input: {readonly sessionId: string;readonly turnId: string;@@ -14,7 +12,10 @@ export function deriveChildActivityWorkId(input: {readonly parentSessionId: string;readonly parentTurnId: string;}): string {- return `work:${deriveAgentOperationId(input)}`;+ const digest = createHash("sha256")+ .update(`${input.parentSessionId}\0${input.parentTurnId}\0${input.callId}`)+ .digest("hex");+ return `work:${digest}`;}function hashTuple(values: readonly string[]): string {diff --git a/packages/eve/src/execution/agent-sessions/context.ts b/packages/eve/src/execution/agent-sessions/context.tsindex 0d5e75ca2..58e3d349b 100644--- a/packages/eve/src/execution/agent-sessions/context.ts+++ b/packages/eve/src/execution/agent-sessions/context.ts@@ -2,7 +2,6 @@ import type {ActivityObserverConfig,ChannelInstrumentationProjection,RunSessionLimits,- SessionAuthContext,SessionCapabilities,SessionParent,} from "#channel/types.js";@@ -17,6 +16,7 @@ import {import type { SandboxState } from "#sandbox/state.js";import type { ConversationContext } from "#shared/conversation-context.js";import { resolveRemainingSessionTokenLimits } from "#subagents/token-budget.js";+import type { WorkflowAgentMetadata } from "#tools/workflow-definition.js";import {resolveToolCallAgentTrace,type AgentChildTraceDispatch,@@ -24,16 +24,20 @@ import {/*** What a workflow run needs to open `ctx.agent` sessions for its caller,- * captured from the calling session in the run's start input. The run never- * reads the session again: opening, sending to, and ending its sessions never- * pass through the caller.+ * captured from the calling session for one call: the run's start input+ * carries it for the call that started the run, and each later call to a+ * `serve` task carries its own. The run never reads the session again:+ * opening, sending to, and ending its sessions never pass through the caller.+ *+ * It is a session's lineage, bound when the session opens. Auth is not part+ * of it: each message carries the auth of the call that sends it.*/export interface AgentSessionContext {readonly activityObserver?: ActivityObserverConfig & {readonly workIdentity: ActivityWorkIdentityV1;};- /** The caller's principal, which every session runs as. */- readonly auth: SessionAuthContext | null;+ /** The agents the call may open, by name, which `ctx.agents` lists. */+ readonly agents: Readonly<Record<string, WorkflowAgentMetadata>>;readonly bundle: AgentSessionBundle;/** Forwarded unchanged, so a session asks a person only when its caller can. */readonly capabilities?: SessionCapabilities;@@ -41,7 +45,6 @@ export interface AgentSessionContext {readonly conversation?: ConversationContext;/** Dynamic agents the calling turn selected, by node id. */readonly dynamicSelections: DynamicSubagentSelections;- readonly initiatorAuth: SessionAuthContext | null;/** The token budget each session inherits: the caller's remaining quota. */readonly limits: RunSessionLimits;readonly localDevRequest?: LocalDevRequestProvenance;@@ -66,21 +69,20 @@ export interface AgentSessionSandbox {type CallerDispatch = Pick<PreparedCoordinationDispatch<unknown>,| "activityObserver"- | "auth"| "batch"| "bundle"| "capabilities"| "channelMetadata"| "dynamicSubagentSelections"| "inheritedConversation"- | "initiatorAuth"| "localDevRequest"| "sandboxSessionId"| "serializedContext"| "session"+ | "workflowAgents">;-/** Captures the agent session context for one workflow tool call's run. */+/** Captures the agent session context for one workflow tool call, in the step that admits it. */export function captureAgentSessionContext(caller: CallerDispatch,callId: string,@@ -88,7 +90,7 @@ export function captureAgentSessionContext(const { batch, session } = caller;return {activityObserver: caller.activityObserver,- auth: caller.auth,+ agents: caller.workflowAgents,bundle: {nodeId: caller.bundle.nodeId,source: serializeDurableCompiledArtifactsSource(caller.bundle.compiledArtifactsSource),@@ -97,7 +99,6 @@ export function captureAgentSessionContext(channelMetadata: caller.channelMetadata,conversation: caller.inheritedConversation,dynamicSelections: caller.dynamicSubagentSelections,- initiatorAuth: caller.initiatorAuth,limits: resolveRemainingSessionTokenLimits(session),localDevRequest: caller.localDevRequest,parent: {diff --git a/packages/eve/src/execution/tools/subagent/metadata.test.ts b/packages/eve/src/execution/agent-sessions/metadata.test.tssimilarity index 97%rename from packages/eve/src/execution/tools/subagent/metadata.test.tsrename to packages/eve/src/execution/agent-sessions/metadata.test.tsindex 16d045594..b975dd36b 100644--- a/packages/eve/src/execution/tools/subagent/metadata.test.ts+++ b/packages/eve/src/execution/agent-sessions/metadata.test.ts@@ -6,7 +6,7 @@ import {SessionDynamicSubagentSelectionsKey,TurnDynamicSubagentSelectionsKey,} from "#context/keys.js";-import { resolveWorkflowAgentMetadata } from "#execution/tools/subagent/metadata.js";+import { resolveWorkflowAgentMetadata } from "#execution/agent-sessions/metadata.js";import { BundleKey } from "#runtime/sessions/runtime-context-keys.js";describe("resolveWorkflowAgentMetadata", () => {diff --git a/packages/eve/src/execution/tools/subagent/metadata.ts b/packages/eve/src/execution/agent-sessions/metadata.tssimilarity index 100%rename from packages/eve/src/execution/tools/subagent/metadata.tsrename to packages/eve/src/execution/agent-sessions/metadata.tsdiff --git a/packages/eve/src/subagents/remote-dispatch.test.ts b/packages/eve/src/execution/agent-sessions/remote.test.tssimilarity index 86%rename from packages/eve/src/subagents/remote-dispatch.test.tsrename to packages/eve/src/execution/agent-sessions/remote.test.tsindex f6064f3cd..43ac0e2a4 100644--- a/packages/eve/src/subagents/remote-dispatch.test.ts+++ b/packages/eve/src/execution/agent-sessions/remote.test.ts@@ -5,14 +5,11 @@ import { readForwardedParentSessionBaggage } from "#protocol/baggage.js";import {cancelRemoteAgentTurn,continueRemoteAgentSession,- isAmbiguousRemoteAgentContinueError,- isRetryableRemoteAgentCancelError,- isRetryableRemoteAgentContinueError,resetRemoteAgentSession,resolveRemoteAgentForAction,resolveRemoteAgentStreamHeaders,startRemoteAgentSession,-} from "#subagents/remote-dispatch.js";+} from "#execution/agent-sessions/remote.js";import type { RuntimeRemoteAgentDispatchRequest } from "#shared/action-types.js";import type { ResolvedRuntimeRemoteAgentNode } from "#runtime/types.js";@@ -430,37 +427,6 @@ describe("startRemoteAgentSession", () => {expect(body.capabilities).toEqual({});});- it("ignores an empty requested outputSchema instead of forwarding it", async () => {- // An empty schema constrains nothing, but forwarding it flips the remote- // child into structured-output mode and discards its text reply; local- // subagent dispatch already drops it, and remote must match.- const fetchMock = vi.fn().mockResolvedValue(- new Response(- JSON.stringify({- ok: true,- protocolVersion: 2,- sessionId: "remote-session",- status: "accepted",- }),- {- status: 202,- },- ),- );- vi.stubGlobal("fetch", fetchMock);-- const action = createAction();- await startRemoteAgentSession({- action: { ...action, input: { ...action.input, outputSchema: {} } },- callbackBaseUrl: "https://caller.example.com",- remote: createRemoteAgent(),- session: { continuationToken: "eve:parent-token" },- });-- const body = JSON.parse(fetchMock.mock.calls[0]?.[1]?.body as string);- expect(body).not.toHaveProperty("outputSchema");- });-it("targets an active turn inbox when a callback token is supplied", async () => {const fetchMock = vi.fn().mockResolvedValue(new Response(@@ -911,7 +877,7 @@ describe("continueRemoteAgentSession", () => {});});- it("suggests receiver version skew without making a forwarded continuation permanent", async () => {+ it("suggests receiver version skew when a forwarded continuation is rejected", async () => {vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response(null, { status: 400 })));const current: SessionAuthContext = {attributes: { user_id: "U456" },@@ -939,55 +905,6 @@ describe("continueRemoteAgentSession", () => {message:'Remote agent "research" continue-session request failed with HTTP 400. The receiver may support forwarded principals only on session creation; upgrade it before retrying.',});- expect(isRetryableRemoteAgentContinueError(error)).toBe(true);- });-- it("classifies only missing-session continue failures as permanent", async () => {- const fetchMock = vi- .fn()- .mockResolvedValueOnce(new Response(null, { status: 503 }))- .mockResolvedValueOnce(new Response(null, { status: 401 }))- .mockResolvedValueOnce(- new Response(JSON.stringify({ code: "SESSION_NOT_RESUMABLE" }), { status: 410 }),- )- .mockResolvedValueOnce(new Response(null, { status: 404 }));- vi.stubGlobal("fetch", fetchMock);-- const continueInput = () => ({- auth: null,- callback: {- callId: "call-next",- subagentName: "research",- token: "parent-inbox",- url: "https://caller.example.com/eve/v1/callback/parent-inbox",- },- message: "follow up",- remote: createRemoteAgent(),- sessionId: "remote-session",- });- const transient = await continueRemoteAgentSession(continueInput()).catch(- (error: unknown) => error,- );- const rejected = await continueRemoteAgentSession(continueInput()).catch(- (error: unknown) => error,- );- const sessionNotResumable = await continueRemoteAgentSession(continueInput()).catch(- (error: unknown) => error,- );- const missing = await continueRemoteAgentSession(continueInput()).catch(- (error: unknown) => error,- );-- expect(isRetryableRemoteAgentContinueError(transient)).toBe(true);- expect(isAmbiguousRemoteAgentContinueError(transient)).toBe(true);- expect(isRetryableRemoteAgentContinueError(rejected)).toBe(true);- expect(isAmbiguousRemoteAgentContinueError(rejected)).toBe(false);- expect(isRetryableRemoteAgentContinueError(sessionNotResumable)).toBe(false);- expect(isAmbiguousRemoteAgentContinueError(sessionNotResumable)).toBe(false);- expect(isRetryableRemoteAgentContinueError(missing)).toBe(false);- expect(isAmbiguousRemoteAgentContinueError(missing)).toBe(false);- expect(isRetryableRemoteAgentContinueError(new TypeError("network unavailable"))).toBe(true);- expect(isAmbiguousRemoteAgentContinueError(new TypeError("network unavailable"))).toBe(true);});});@@ -1038,26 +955,6 @@ describe("cancelRemoteAgentTurn", () => {});});- it("sends the observed child turn guard", async () => {- const fetchMock = vi- .fn()- .mockResolvedValue(- Response.json({ ok: true, sessionId: "child-1", status: "accepted" }, { status: 202 }),- );- vi.stubGlobal("fetch", fetchMock);-- await cancelRemoteAgentTurn({- remote: createRemoteAgent(),- sessionId: "child-1",- turnId: "turn_child_7",- });-- expect(fetchMock).toHaveBeenCalledWith(- "https://remote.example.com/eve/v1/session/child-1/cancel",- expect.objectContaining({ body: JSON.stringify({ turnId: "turn_child_7" }), method: "POST" }),- );- });-it("preserves a prefixed remote base path on cancel-turn requests", async () => {const fetchMock = vi.fn()@@ -1104,28 +1001,6 @@ describe("cancelRemoteAgentTurn", () => {}).catch((caught: unknown) => caught);expect(error).toBeInstanceOf(Error);- expect(isRetryableRemoteAgentCancelError(error)).toBe(false);- });-- it("classifies only propagation and transient HTTP failures as retryable", async () => {- const fetchMock = vi- .fn()- .mockResolvedValueOnce(new Response(null, { status: 503 }))- .mockResolvedValueOnce(new Response(null, { status: 404 }));- vi.stubGlobal("fetch", fetchMock);-- const transient = await cancelRemoteAgentTurn({- remote: createRemoteAgent(),- sessionId: "remote-session",- }).catch((error: unknown) => error);- const permanent = await cancelRemoteAgentTurn({- remote: createRemoteAgent(),- sessionId: "remote-session",- }).catch((error: unknown) => error);-- expect(isRetryableRemoteAgentCancelError(transient)).toBe(true);- expect(isRetryableRemoteAgentCancelError(permanent)).toBe(false);- expect(isRetryableRemoteAgentCancelError(new TypeError("network unavailable"))).toBe(true);});});@@ -1147,6 +1022,7 @@ describe("resetRemoteAgentSession", () => {await expect(resetRemoteAgentSession({+ reason: "Parent session ended",remote: {...createRemoteAgent(),url: "https://remote.example.com/eve/researcher/",@@ -1182,10 +1058,18 @@ describe("resetRemoteAgentSession", () => {vi.stubGlobal("fetch", fetchMock);await expect(- resetRemoteAgentSession({ remote: createRemoteAgent(), sessionId: "remote-session" }),+ resetRemoteAgentSession({+ reason: "Parent session ended",+ remote: createRemoteAgent(),+ sessionId: "remote-session",+ }),).resolves.toEqual({ ok: true, status: "no_active_session" });await expect(- resetRemoteAgentSession({ remote: createRemoteAgent(), sessionId: "remote-session" }),+ resetRemoteAgentSession({+ reason: "Parent session ended",+ remote: createRemoteAgent(),+ sessionId: "remote-session",+ }),).rejects.toThrow("response was invalid");});});diff --git a/packages/eve/src/subagents/remote-dispatch.ts b/packages/eve/src/execution/agent-sessions/remote.tssimilarity index 81%rename from packages/eve/src/subagents/remote-dispatch.tsrename to packages/eve/src/execution/agent-sessions/remote.tsindex 9d06e6192..537cf910e 100644--- a/packages/eve/src/subagents/remote-dispatch.ts+++ b/packages/eve/src/execution/agent-sessions/remote.ts@@ -2,7 +2,6 @@ import { FatalError } from "#compiled/@workflow/core/index.js";import { z } from "#compiled/zod/index.js";import { CancelTurnResponseSchema } from "#protocol/cancel-turn.js";import { ResetResponseSchema, type ResetResponse } from "#protocol/reset-session.js";-import { AgentHandleError } from "#protocol/agent-handle-error.js";import {REMOTE_AGENT_PROTOCOL_MISMATCH,REMOTE_AGENT_PROTOCOL_VERSION,@@ -27,11 +26,7 @@ import type { HeadersValue } from "#client/types.js";import { createWorkflowCallbackUrl } from "#execution/workflow-callback-url.js";import { createRemoteAgentRouteUrl } from "#subagents/remote-route-url.js";import { formatTraceparent, writeAgentDispatchTracestate } from "#protocol/traceparent.js";-import {- formatSubagentInput,- normalizeRequestedOutputSchema,- type SubagentParentContext,-} from "#subagents/invocation.js";+import { formatSubagentInput, type SubagentParentContext } from "#subagents/invocation.js";import type { HarnessSession } from "#harness/types.js";import type { RuntimeRemoteAgentDispatchRequest } from "#shared/action-types.js";import type { RuntimeSubagentRegistry } from "#runtime/subagents/registry.js";@@ -58,16 +53,6 @@ type RemoteAgentSessionCoordinates = {readonly sessionId: string;};-class RemoteAgentCancelRequestError extends Error {- readonly retryable: boolean;-- constructor(message: string, options: { readonly retryable: boolean }) {- super(message);- this.name = "RemoteAgentCancelRequestError";- this.retryable = options.retryable;- }-}-export async function startRemoteAgentSession(input: {readonly action: RuntimeRemoteAgentDispatchRequest;/** The dispatching turn's session principal, forwarded when `remote.forwardPrincipal` is set. */@@ -127,7 +112,8 @@ export async function startRemoteAgentSession(input: {action: input.action,remote: input.remote,}),- outputSchema: normalizeRequestedOutputSchema(input.action.input.outputSchema),+ // `ctx.agent` already dropped an empty schema, so what arrives is one to honor.+ outputSchema: input.action.input.outputSchema as JsonObject | undefined,protocolVersion: REMOTE_AGENT_PROTOCOL_VERSION,};if (input.activityObserver !== undefined) requestBody.activityObserver = input.activityObserver;@@ -281,81 +267,16 @@ export async function continueRemoteAgentSession(input: {});if (!response.ok) {- const responseCode = await readRemoteAgentErrorCode(response);- const permanent =- response.status === 404 || responseCode === AgentHandleError.SessionNotResumable.code;const compatibilityHint =response.status === 400 && forwardedPrincipal !== undefined? " The receiver may support forwarded principals only on session creation; upgrade it before retrying.": "";- throw new RemoteAgentContinueRequestError(- `Remote agent "${input.remote.name}" continue-session request failed${- permanent ? " permanently" : ""- } with HTTP ${response.status}.${compatibilityHint}`,- {- deliveryAmbiguous: isAmbiguousRemoteContinueStatus(response.status),- retryable: !permanent,- },+ throw new Error(+ `Remote agent "${input.remote.name}" continue-session request failed with HTTP ${response.status}.${compatibilityHint}`,);}}-/**- * Failure of a continue-session request, classified at the HTTP boundary.- * Exported so tests can exercise {@link isRetryableRemoteAgentContinueError}- * with real instances instead of re-encoding the classification.- */-export class RemoteAgentContinueRequestError extends Error {- readonly deliveryAmbiguous: boolean;- readonly retryable: boolean;-- constructor(- message: string,- options: { readonly deliveryAmbiguous: boolean; readonly retryable: boolean },- ) {- super(message);- this.name = "RemoteAgentContinueRequestError";- this.deliveryAmbiguous = options.deliveryAmbiguous;- this.retryable = options.retryable;- }-}--/**- * Returns true when a failed continue request may be retried. Only a- * session that no longer exists (404 / SESSION_NOT_RESUMABLE) is permanent;- * transient HTTP and network failures stay retryable so the dispatch step- * keeps the agent handle and surfaces a retryable error instead of- * discarding it — the model decides whether to try the same agentId again- * (the step itself never re-sends: the callee may have accepted a delivery- * whose response was lost).- */-export function isRetryableRemoteAgentContinueError(error: unknown): boolean {- return !(error instanceof RemoteAgentContinueRequestError) || error.retryable;-}--/** Whether the callee may have accepted the continuation before delivery failed. */-export function isAmbiguousRemoteAgentContinueError(error: unknown): boolean {- return !(error instanceof RemoteAgentContinueRequestError) || error.deliveryAmbiguous;-}--function isAmbiguousRemoteContinueStatus(status: number): boolean {- return status === 408 || status === 425 || status >= 500;-}--async function readRemoteAgentErrorCode(response: Response): Promise<string | undefined> {- let body: unknown;- try {- body = await response.json();- } catch {- return undefined;- }- if (body === null || typeof body !== "object") {- return undefined;- }- const code = Reflect.get(body, "code");- return typeof code === "string" ? code : undefined;-}-function buildForwardedPrincipalField(input: {readonly auth?: SessionAuthContext | null;readonly initiatorAuth?: SessionAuthContext | null;@@ -379,22 +300,17 @@ function buildForwardedPrincipalField(input: {}export async function cancelRemoteAgentTurn(input: {- readonly headers?: Record<string, string>;readonly remote: Pick<ResolvedRuntimeRemoteAgentNode, "auth" | "headers" | "name" | "url">;readonly sessionId: string;- readonly turnId?: string;}): Promise<CancelTurnResult> {- const headers = input.headers ?? (await resolveRemoteAgentRequestHeaders(input.remote));const response = await fetch(createRemoteAgentCancelTurnUrl(input.remote, input.sessionId), {- body: input.turnId === undefined ? undefined : JSON.stringify({ turnId: input.turnId }),- headers,+ headers: await resolveRemoteAgentRequestHeaders(input.remote),method: "POST",});if (!response.ok) {- throw new RemoteAgentCancelRequestError(+ throw new Error(`Remote agent "${input.remote.name}" cancel-turn request failed with HTTP ${response.status}.`,- { retryable: isRetryableRemoteCancelStatus(response.status) },);}@@ -402,10 +318,7 @@ export async function cancelRemoteAgentTurn(input: {try {body = await response.json();} catch {- throw new RemoteAgentCancelRequestError(- `Remote agent "${input.remote.name}" cancel-turn response was not valid JSON.`,- { retryable: false },- );+ throw new Error(`Remote agent "${input.remote.name}" cancel-turn response was not valid JSON.`);}const result = CancelTurnResponseSchema.safeParse(body);@@ -413,10 +326,7 @@ export async function cancelRemoteAgentTurn(input: {!result.success ||(result.data.status === "accepted" && result.data.sessionId !== input.sessionId)) {- throw new RemoteAgentCancelRequestError(- `Remote agent "${input.remote.name}" cancel-turn response was invalid.`,- { retryable: false },- );+ throw new Error(`Remote agent "${input.remote.name}" cancel-turn response was invalid.`);}return result.data.status === "accepted"@@ -438,16 +348,15 @@ function setHeader(headers: Record<string, string>, name: string, value: string/** Retires one exact remote child session through eve's authenticated reset route. */export async function resetRemoteAgentSession(input: {- readonly headers?: Record<string, string>;- readonly reason?: string;+ readonly reason: string;readonly remote: Pick<ResolvedRuntimeRemoteAgentNode, "auth" | "headers" | "name" | "url">;readonly sessionId: string;}): Promise<ResetResponse> {- const headers = input.headers ?? (await resolveRemoteAgentRequestHeaders(input.remote));+ const headers = await resolveRemoteAgentRequestHeaders(input.remote);const response = await fetch(createRemoteAgentRouteUrl(input.remote.url, createEveSessionResetRoutePath(input.sessionId)),{- body: JSON.stringify({ reason: input.reason ?? "Parent session ended" }),+ body: JSON.stringify({ reason: input.reason }),headers: { "content-type": "application/json", ...headers },method: "POST",},@@ -467,10 +376,6 @@ export async function resetRemoteAgentSession(input: {return result.data;}-export function isRetryableRemoteAgentCancelError(error: unknown): boolean {- return !(error instanceof RemoteAgentCancelRequestError) || error.retryable;-}-export function resolveRemoteAgentForAction(input: {readonly dynamicRemoteAgent?: DynamicRemoteAgentConfig;readonly nodeId: string;@@ -529,8 +434,8 @@ export function resolveRemoteAgentForAction(input: {/*** Resolves authored outbound headers for a server-authored remote child event.*- * `resolverId` is the key persisted on the `subagent.called` event (see- * `SubagentCalledStreamEvent`): it identifies the authored credential+ * `resolverId` is the key persisted on the `agent.started` event (see+ * `AgentStartedStreamEvent`): it identifies the authored credential* functions, never their resolved values. Lookup order mirrors how dispatch* chose the key — first as a subagent node id (static remote definition),* then as a `credentialsStepId` in the step registry (dynamic remote@@ -640,10 +545,6 @@ function createRemoteAgentContinueUrl(return createRemoteAgentRouteUrl(remote.url, createEveSessionRoutePath(sessionId));}-function isRetryableRemoteCancelStatus(status: number): boolean {- return status === 408 || status === 425 || status === 429 || status >= 500;-}-async function resolveRemoteAgentRequestHeaders(remote: Pick<ResolvedRuntimeRemoteAgentNode, "auth" | "headers">,): Promise<Record<string, string>> {diff --git a/packages/eve/src/execution/agent-sessions/session.ts b/packages/eve/src/execution/agent-sessions/session.tsindex c88090134..3f3f80ba0 100644--- a/packages/eve/src/execution/agent-sessions/session.ts+++ b/packages/eve/src/execution/agent-sessions/session.ts@@ -10,12 +10,13 @@ import {endAgentSessionsStep,openAgentSessionStep,sendAgentSessionMessageStep,- type AgentSessionAddress,type AgentSessionMessage,+ type OpenedAgentSession,} from "#execution/agent-sessions/steps.js";import { disposeHook } from "#execution/hook-ownership.js";import type { WorkflowToolRunContext } from "#execution/tools/workflow/ask.js";import type { RuntimeSubagentResult } from "#shared/action-types.js";+import { toErrorMessage } from "#shared/errors.js";import { normalizeRequestedOutputSchema } from "#subagents/invocation.js";import { serializeOutputSchema } from "#tools/schema-emission.js";import type {@@ -40,7 +41,7 @@ export function createAgentSessions(run: WorkflowToolRunContext): {readonly close: () => Promise<void>;readonly open: (name: string) => AgentSession;} {- const opened: AgentSessionAddress[] = [];+ const sessions: OpenedAgentSession[] = [];let handles = 0;return {open: (name) => {@@ -49,40 +50,45 @@ export function createAgentSessions(run: WorkflowToolRunContext): {}const key = `${run.from.runId}:${String(handles)}`;handles += 1;- return new RunAgentSession({ key, name, opened, run });+ return new RunAgentSession({ key, name, run, sessions });},close: async () => {- if (opened.length === 0) return;- await endAgentSessionsStep({ context: run.agentContext, sessions: opened });+ if (sessions.length === 0) return;+ await endAgentSessionsStep({ sessions });},};}-/** One turn of a session: its result and questions arrive on the turn's own hook. */-interface AgentTurn {+/**+ * A sent message awaiting its reply. The reply, and the questions asked while+ * the agent works on the message, arrive on the message's own hook.+ */+interface AwaitedReply {+ readonly ended: Promise<AgentTurnEnd>;readonly hook: Hook<AgentTurnReply>;- readonly response: AgentResponse<unknown>;+ readonly settle: (end: AgentTurnEnd) => void;}class RunAgentSession implements AgentSession {readonly #key: string;readonly #name: string;- /** Every session the run opened, which it ends when it finishes. */- readonly #opened: AgentSessionAddress[];readonly #run: WorkflowToolRunContext;- #address: Promise<AgentSessionAddress> | undefined;- #turn: AgentTurn | undefined;+ /** Every session the run opened, which it ends when it finishes. */+ readonly #sessions: OpenedAgentSession[];+ #opened: Promise<OpenedAgentSession> | undefined;+ /** Oldest first. */+ readonly #awaited: AwaitedReply[] = [];constructor(input: {readonly key: string;readonly name: string;- readonly opened: AgentSessionAddress[];readonly run: WorkflowToolRunContext;+ readonly sessions: OpenedAgentSession[];}) {this.#key = input.key;this.#name = input.name;- this.#opened = input.opened;this.#run = input.run;+ this.#sessions = input.sessions;}async send<TOutput = unknown>(@@ -97,35 +103,37 @@ class RunAgentSession implements AgentSession {const outputSchema = normalizeRequestedOutputSchema(serializeOutputSchema(options.outputSchema),);- const running = this.#turn;- const turn = running ?? this.#startTurn(outputSchema !== undefined);+ const reply = this.#awaitReply(outputSchema !== undefined);try {await this.#deliver({- context: this.#run.agentContext,+ auth: this.#run.auth,message,outputSchema,- replyTo: turn.hook.token,+ replyTo: reply.hook.token,});} catch (error) {- if (running === undefined) await this.#closeTurn(turn);+ this.#awaited.splice(this.#awaited.indexOf(reply), 1);+ await releaseHook(reply.hook);throw error;}- if (options.signal !== undefined) this.#cancelTurnOnAbort(turn, options.signal);- return turn.response as AgentResponse<TOutput>;+ if (options.signal !== undefined) this.#cancelTurnOnAbort(reply, options.signal);+ const response: AgentResponse<unknown> = { result: () => reply.ended.then(unwrapTurnEnd) };+ return response as AgentResponse<TOutput>;}- #startTurn(expectsData: boolean): AgentTurn {+ #awaitReply(expectsData: boolean): AwaitedReply {const hook = createHook<AgentTurnReply>();- const ended = this.#readTurn(hook, expectsData);- const turn: AgentTurn = {- hook,- response: { result: () => ended.then(unwrapTurnEnd) },- };- this.#turn = turn;- return turn;+ let settle: (end: AgentTurnEnd) => void = () => {};+ const ended = new Promise<AgentTurnEnd>((resolve) => {+ settle = resolve;+ });+ const reply: AwaitedReply = { ended, hook, settle };+ this.#awaited.push(reply);+ void this.#readTurn(hook, expectsData).then((end) => this.#settleThrough(reply, end));+ return reply;}- /** Forwards the turn's questions up to the session and settles with its result. */+ /** Forwards the turn's questions up to the session and returns its end. */async #readTurn(hook: Hook<AgentTurnReply>, expectsData: boolean): Promise<AgentTurnEnd> {try {for await (const reply of hook) {@@ -151,49 +159,63 @@ class RunAgentSession implements AgentSession {};} catch (error) {return { error, kind: "failed" };- } finally {- await this.#closeTurn({ hook });}}- async #closeTurn(turn: Pick<AgentTurn, "hook">): Promise<void> {- if (this.#turn?.hook === turn.hook) this.#turn = undefined;- try {- await disposeHook(turn.hook);- } catch {- // The turn already has its outcome; releasing its hook is best effort.+ /**+ * A turn reports to the latest message it read, and the messages sent before+ * it that still await a reply joined the same turn, so its end settles them+ * all. A message the agent reads only after its turn ended starts the next+ * turn and gets that turn's reply.+ */+ async #settleThrough(reply: AwaitedReply, end: AgentTurnEnd): Promise<void> {+ const index = this.#awaited.indexOf(reply);+ if (index < 0) return;+ for (const settled of this.#awaited.splice(0, index + 1)) {+ settled.settle(end);+ await releaseHook(settled.hook);}}async #deliver(message: AgentSessionMessage): Promise<void> {- if (this.#address === undefined) {- this.#address = this.#open(message);- await this.#address;+ if (this.#opened === undefined) {+ this.#opened = this.#open(message);+ await this.#opened;return;}- const address = await this.#address;- await sendAgentSessionMessageStep({ ...message, address });+ const opened = await this.#opened;+ await sendAgentSessionMessageStep({ ...message, ...opened });}- async #open(message: AgentSessionMessage): Promise<AgentSessionAddress> {+ /**+ * Opens the session as a child of the call the run serves now. Its lineage+ * and trace come from that call, and its later messages keep them even when+ * the run serves another call by then; each message carries its own auth.+ */+ async #open(message: AgentSessionMessage): Promise<OpenedAgentSession> {+ const { agentContext: context, from } = this.#run;try {- const address = await openAgentSessionStep({ ...message, key: this.#key, name: this.#name });- this.#opened.push(address);- await this.#run.owner.send({ from: this.#run.from, kind: "agent-started", session: address });- return address;+ const address = await openAgentSessionStep({+ ...message,+ context,+ key: this.#key,+ name: this.#name,+ });+ const opened = { address, context };+ this.#sessions.push(opened);+ await this.#run.owner.send({ from, kind: "agent-started", session: address });+ return opened;} catch (error) {- this.#address = undefined;+ this.#opened = undefined;throw error;}}/** Aborting cancels only the turn the message went to, never a later one. */- #cancelTurnOnAbort(turn: AgentTurn, signal: AbortSignal): void {+ #cancelTurnOnAbort(reply: AwaitedReply, signal: AbortSignal): void {const cancel = (): void => {- if (this.#turn !== turn || this.#address === undefined) return;- void this.#address- .then((address) => cancelAgentSessionTurnStep({ address, context: this.#run.agentContext }))- .catch(() => {});+ if (!this.#awaited.includes(reply) || this.#opened === undefined) return;+ void this.#opened.then((opened) => cancelAgentSessionTurnStep(opened)).catch(() => {});};if (signal.aborted) {cancel();@@ -203,6 +225,14 @@ class RunAgentSession implements AgentSession {}}+async function releaseHook(hook: Hook<AgentTurnReply>): Promise<void> {+ try {+ await disposeHook(hook);+ } catch {+ // The reply already has its outcome; releasing its hook is best effort.+ }+}+function unwrapTurnEnd(end: AgentTurnEnd): AgentMessageResult<unknown> {if (end.kind === "failed") throw end.error;return end.result;@@ -210,15 +240,19 @@ function unwrapTurnEnd(end: AgentTurnEnd): AgentMessageResult<unknown> {const NO_REPLY = { data: undefined, message: undefined } as const;+function failedTurn(error: unknown): AgentMessageResult<unknown> {+ return { ...NO_REPLY, error: { message: toErrorMessage(error) }, status: "failed" };+}+function toAgentMessageResult(result: RuntimeSubagentResult,expectsData: boolean,): AgentMessageResult<unknown> {- if (result.origin !== "child") return { ...NO_REPLY, status: "failed" };+ if (result.origin !== "child") return failedTurn(result.output);const { outcome } = result;switch (outcome.result.kind) {case "failed":- return { ...NO_REPLY, status: "failed" };+ return failedTurn(outcome.result.error);case "cancelled":return { ...NO_REPLY, status: "waiting" };case "succeeded": {diff --git a/packages/eve/src/execution/agent-sessions/steps.ts b/packages/eve/src/execution/agent-sessions/steps.tsindex eadf2ed8a..04212060f 100644--- a/packages/eve/src/execution/agent-sessions/steps.ts+++ b/packages/eve/src/execution/agent-sessions/steps.ts@@ -1,10 +1,14 @@-import { FatalError, getWorkflowMetadata } from "#compiled/@workflow/core/index.js";+import { getWorkflowMetadata } from "#compiled/@workflow/core/index.js";import { ContextContainer, contextStorage } from "#context/container.js";+import type { SessionAuth } from "#context/session-context.js";import type { AgentSessionContext } from "#execution/agent-sessions/context.js";-import { resolveAgentAction, resolveAgentStartTarget } from "#execution/agent-sessions/target.js";+import {+ resolveAgentAction,+ resolveAgentStartTarget,+ type SubagentStartTarget,+} from "#execution/agent-sessions/target.js";import { deriveChildActivityObserverConfig } from "#execution/activity-work.js";import { sessionInboxHookToken } from "#execution/session-inbox/address.js";-import type { SubagentStartTarget } from "#execution/tools/subagent/start.js";import {createWorkflowCallbackUrl,resolveWorkflowCallbackBaseUrl,@@ -21,7 +25,6 @@ import { resolveDurableCompiledArtifactsSource } from "#runtime/durable-compiledimport { getCompiledRuntimeAgentBundle } from "#runtime/sessions/compiled-agent-cache.js";import type { CompiledBundle } from "#runtime/sessions/runtime-context-keys.js";import type { ResolvedRuntimeRemoteAgentNode } from "#runtime/types.js";-import { toErrorMessage } from "#shared/errors.js";import type { JsonObject } from "#shared/json.js";import type { SubagentParentContext } from "#subagents/invocation.js";import {@@ -30,7 +33,7 @@ import {resetRemoteAgentSession,resolveRemoteAgentForAction,startRemoteAgentSession,-} from "#subagents/remote-dispatch.js";+} from "#execution/agent-sessions/remote.js";import { buildSubagentRunInput } from "#subagents/tool.js";import { resolveConversationId } from "#shared/conversation-identity.js";@@ -57,20 +60,35 @@ export type AgentSessionAddress =readonly url: string;};-/** One message to a session; its turn's result and questions arrive on `replyTo`. */-export interface AgentSessionMessage {+/** A session a run opened, with the context of the call that opened it: its lineage. */+export interface OpenedAgentSession {+ readonly address: AgentSessionAddress;readonly context: AgentSessionContext;+}++/**+ * One message to a session, as the call that sends it: the session runs the+ * message with that call's auth. Its turn's result and questions arrive on+ * `replyTo`.+ */+export interface AgentSessionMessage {+ readonly auth: SessionAuth;readonly message: string;readonly outputSchema?: JsonObject;readonly replyTo: string;}/**- * Opens a run's session with its first message. `key` names the handle within- * the run, so a retried step reaches the same session instead of a second one.+ * Opens a run's session with its first message, as a child of the call whose+ * `context` it binds. `key` names the handle within the run, so a retried step+ * reaches the same session instead of a second one.*/export async function openAgentSessionStep(- input: AgentSessionMessage & { readonly key: string; readonly name: string },+ input: AgentSessionMessage & {+ readonly context: AgentSessionContext;+ readonly key: string;+ readonly name: string;+ },): Promise<AgentSessionAddress> {"use step";@@ -82,25 +100,25 @@ export async function openAgentSessionStep(dynamicSelections: context.dynamicSelections,input: { message: input.message, outputSchema: input.outputSchema, target: input.name },});- const plan = resolveAgentStartTarget({+ const target = resolveAgentStartTarget({action,bundle,dynamicSelections: context.dynamicSelections,isRootSession: context.parent.rootSessionId === context.parent.sessionId,});- if (plan.kind === "reject") {- throw new FatalError(toErrorMessage(plan.result.output));- }- const start = { bundle, context, key: input.key, replyTo: input.replyTo };- if (plan.target.kind === "remote") {- return await startRemoteSession({ ...start, target: plan.target });+ const start = { auth: input.auth, bundle, context, key: input.key, replyTo: input.replyTo };+ if (target.kind === "remote") {+ return await startRemoteSession({ ...start, target });}- return await startLocalSession({ ...start, target: plan.target });+ return await startLocalSession({ ...start, target });}-/** Sends a later message; it joins the session's running turn or starts the next. */+/**+ * Sends a later message; it joins the session's running turn or starts the+ * next. It keeps the session's lineage and carries its own auth.+ */export async function sendAgentSessionMessageStep(- input: AgentSessionMessage & { readonly address: AgentSessionAddress },+ input: AgentSessionMessage & OpenedAgentSession,): Promise<void> {"use step";@@ -109,7 +127,7 @@ export async function sendAgentSessionMessageStep(const remote = await resolveSessionRemote(context, address);await continueRemoteAgentSession({activityObserver: context.activityObserver,- auth: context.auth,+ auth: input.auth.current,callback: {callId: context.parent.callId,subagentName: address.name,@@ -128,7 +146,7 @@ export async function sendAgentSessionMessageStep(}const result = await dispatchWorkflowSessionCommand({command: {- auth: context.auth,+ auth: input.auth.current,caller: {activityObserver: context.activityObserver,callId: context.parent.callId,@@ -146,10 +164,7 @@ export async function sendAgentSessionMessageStep(}/** Cancels a session's running turn; the turn still reports, as cancelled. */-export async function cancelAgentSessionTurnStep(input: {- readonly address: AgentSessionAddress;- readonly context: AgentSessionContext;-}): Promise<void> {+export async function cancelAgentSessionTurnStep(input: OpenedAgentSession): Promise<void> {"use step";const { address } = input;@@ -170,18 +185,14 @@ export async function cancelAgentSessionTurnStep(input: {/** Ends a run's sessions when the run finishes, cancelling any turn still running. */export async function endAgentSessionsStep(input: {- readonly context: AgentSessionContext;- readonly sessions: readonly AgentSessionAddress[];+ readonly sessions: readonly OpenedAgentSession[];}): Promise<void> {"use step";- await Promise.all(input.sessions.map((address) => endAgentSession(input.context, address)));+ await Promise.all(input.sessions.map(endAgentSession));}-async function endAgentSession(- context: AgentSessionContext,- address: AgentSessionAddress,-): Promise<void> {+async function endAgentSession({ address, context }: OpenedAgentSession): Promise<void> {try {if (address.kind === "remote") {const remote = await resolveSessionRemote(context, address);@@ -205,6 +216,7 @@ async function endAgentSession(}interface SessionStart<Target extends SubagentStartTarget> {+ readonly auth: SessionAuth;readonly bundle: CompiledBundle;readonly context: AgentSessionContext;readonly key: string;@@ -215,18 +227,18 @@ interface SessionStart<Target extends SubagentStartTarget> {async function startLocalSession(input: SessionStart<Extract<SubagentStartTarget, { readonly kind: "local" }>>,): Promise<AgentSessionAddress> {- const { bundle, context, target } = input;+ const { auth, bundle, context, target } = input;const { action } = target;const { childContinuationToken, runInput } = buildSubagentRunInput({action,activityObserver: context.activityObserver,- auth: context.auth,+ auth: auth.current,capabilities: context.capabilities,channelMetadata: context.channelMetadata,continuationKey: input.key,graph: bundle.graph,inheritedConversation: context.conversation,- initiatorAuth: context.initiatorAuth,+ initiatorAuth: auth.initiator,limits: context.limits,parent: createParentContext(context, input.replyTo),sandboxSessionId: context.sandbox.sessionId,@@ -253,7 +265,7 @@ async function startLocalSession(async function startRemoteSession(input: SessionStart<Extract<SubagentStartTarget, { readonly kind: "remote" }>>,): Promise<AgentSessionAddress> {- const { bundle, context, target } = input;+ const { auth, bundle, context, target } = input;const { action } = target;const remote = resolveRemoteAgentForAction({dynamicRemoteAgent: target.dynamicRemoteAgent,@@ -272,9 +284,9 @@ async function startRemoteSession(parentSessionId: context.parent.sessionId,parentTurnId: context.parent.turn.id,}),- auth: context.auth,+ auth: auth.current,callbackBaseUrl,- initiatorAuth: context.initiatorAuth,+ initiatorAuth: auth.initiator,operationId: `agent-session:${input.key}`,originAudience: context.trace.originAudience,parent: createParentContext(context, input.replyTo),diff --git a/packages/eve/src/execution/agent-sessions/target.ts b/packages/eve/src/execution/agent-sessions/target.tsindex a0b725d16..afc57454d 100644--- a/packages/eve/src/execution/agent-sessions/target.ts+++ b/packages/eve/src/execution/agent-sessions/target.ts@@ -1,18 +1,14 @@import { FatalError } from "#compiled/@workflow/core/index.js";import type { DurableDynamicSubagentSelection } from "#context/keys.js";-import {- createRecursiveAgentRootOnlyResult,- createUnavailableDynamicSubagentResult,- getSubagentName,-} from "#execution/dispatch-action-failures.js";-import type { SubagentStartTarget } from "#execution/tools/subagent/start.js";import { createLogger } from "#internal/logging.js";import { ROOT_RUNTIME_AGENT_NODE_ID } from "#runtime/graph.js";import type { CompiledBundle } from "#runtime/sessions/runtime-context-keys.js";+import type { DynamicSubagentAgentConfig } from "#runtime/subagents/dynamic-agent-config.js";+import type { DynamicRemoteAgentConfig } from "#runtime/subagents/dynamic-remote-agent-config.js";import type {RuntimeAgentDispatchRequest,- RuntimeSubagentDispatchFailure,+ RuntimeRemoteAgentDispatchRequest,RuntimeSubagentDispatchRequest,} from "#shared/action-types.js";import type { JsonObject } from "#shared/json.js";@@ -25,15 +21,24 @@ export type DynamicSubagentSelections = Readonly<Record<string, DurableDynamicSu/** One message to an agent, addressed by its invocation name. */export interface AgentActionInput {- readonly agentId?: string;readonly message: string;readonly outputSchema?: JsonObject;readonly target: string;}-export type AgentStartPlan =- | { readonly kind: "reject"; readonly result: RuntimeSubagentDispatchFailure }- | { readonly kind: "start"; readonly target: SubagentStartTarget };+/** Where a new session with an agent starts: in this deployment, or at a remote agent. */+export type SubagentStartTarget =+ | {+ readonly kind: "local";+ readonly action: RuntimeSubagentDispatchRequest;+ readonly dynamicSubagentAgentConfig?: DynamicSubagentAgentConfig;+ readonly source: SubagentInputSource;+ }+ | {+ readonly kind: "remote";+ readonly action: RuntimeRemoteAgentDispatchRequest;+ readonly dynamicRemoteAgent?: DynamicRemoteAgentConfig;+ };/*** Resolves an agent name against the calling agent's registry, its dynamic@@ -50,11 +55,9 @@ export function resolveAgentAction(input: {throw new FatalError(`Agent target "${input.input.target}" is not available to this agent.`);}const actionInput: {- agentId?: string;message: string;outputSchema?: JsonObject;} = { message: input.input.message };- if (input.input.agentId !== undefined) actionInput.agentId = input.input.agentId;if (input.input.outputSchema !== undefined) actionInput.outputSchema = input.input.outputSchema;const common = {callId: input.callId,@@ -91,15 +94,15 @@ function findAgentDefinition(}/**- * Plans a fresh child for a dispatch request, rejecting a dynamic agent whose- * selection changed and a root copy outside the root session.+ * Plans a fresh child for a dispatch request. A dynamic agent whose selection+ * changed and a root copy outside the root session can't start.*/export function resolveAgentStartTarget(input: {readonly action: RuntimeAgentDispatchRequest;readonly bundle: CompiledBundle;readonly dynamicSelections: DynamicSubagentSelections;readonly isRootSession: boolean;-}): AgentStartPlan {+}): SubagentStartTarget {const { action } = input;const registry = input.bundle.subagentRegistry.subagentsByNodeId;const isDynamicSubagent =@@ -116,9 +119,11 @@ export function resolveAgentStartTarget(input: {log.warn("dynamic subagent call blocked after availability changed", {callId: action.callId,nodeId: action.nodeId,- subagentName: getSubagentName(action),+ subagentName: action.name,});- return { kind: "reject", result: createUnavailableDynamicSubagentResult(action) };+ throw new FatalError(+ `Subagent "${action.name}" is not available in the current session context.`,+ );}if (isRecursiveAgentAction(action, registry) && !input.isRootSession) {log.warn("recursive agent call blocked outside the root session", {@@ -126,19 +131,16 @@ export function resolveAgentStartTarget(input: {nodeId: action.nodeId,subagentName: action.subagentName,});- return { kind: "reject", result: createRecursiveAgentRootOnlyResult(action) };+ throw new FatalError('The built-in "agent" tool is only available to the root session.');}if (action.kind === "remote-agent-call") {return {- kind: "start",- target: {- action,- dynamicRemoteAgent:- dynamicSubagentSelection?.kind === "remote"- ? dynamicSubagentSelection.remoteAgent- : undefined,- kind: "remote",- },+ action,+ dynamicRemoteAgent:+ dynamicSubagentSelection?.kind === "remote"+ ? dynamicSubagentSelection.remoteAgent+ : undefined,+ kind: "remote",};}const dynamicAgentConfig =@@ -151,10 +153,7 @@ export function resolveAgentStartTarget(input: {(registered?.definition.kind === "subagent" ? registered.definition.description : undefined);const source: SubagentInputSource =description === undefined ? { type: "runtime" } : { description, type: "local" };- return {- kind: "start",- target: { action, dynamicSubagentAgentConfig: dynamicAgentConfig, kind: "local", source },- };+ return { action, dynamicSubagentAgentConfig: dynamicAgentConfig, kind: "local", source };}function isRecursiveAgentAction(diff --git a/packages/eve/src/execution/cancel-descendant-turns-step.test.ts b/packages/eve/src/execution/cancel-descendant-turns-step.test.tsdeleted file mode 100644index a51b1c796..000000000--- a/packages/eve/src/execution/cancel-descendant-turns-step.test.ts+++ /dev/null@@ -1,364 +0,0 @@-import { cancelWorkflowToolRun } from "#execution/tools/workflow/cancel.js";-import { afterEach, describe, expect, it, vi } from "vitest";--import { deserializeContext } from "#context/serialize.js";-import { cancelDescendantTurnsStep } from "#execution/cancel-descendant-turns-step.js";-import { createDurableSessionState } from "#execution/durable-session-store.js";-import {- cancelRemoteAgentTurn,- isRetryableRemoteAgentCancelError,- resolveRemoteAgentForAction,-} from "#subagents/remote-dispatch.js";-import { requestWorkflowTurnCancellation } from "#execution/workflow-runtime.js";-import { AGENT_HANDLES_STATE_KEY, type AgentHandle } from "#subagents/handles/store.js";-import type { HarnessSession } from "#harness/types.js";--vi.mock("#execution/tools/workflow/cancel.js", () => ({ cancelWorkflowToolRun: vi.fn() }));--vi.mock("#context/serialize.js", () => ({- deserializeContext: vi.fn(),-}));--vi.mock("./workflow-runtime.js", () => ({- requestWorkflowTurnCancellation: vi.fn(),-}));--vi.mock("../subagents/remote-dispatch.js", () => ({- cancelRemoteAgentTurn: vi.fn(),- isRetryableRemoteAgentCancelError: vi.fn(),- resolveRemoteAgentForAction: vi.fn(),-}));--const LOCAL_RUNNING_HANDLE: AgentHandle = {- address: {- continuationToken: "subagent:parent:call-local",- kind: "agent/local",- sessionId: "local-child",- },- identity: {- id: "ag_local:aaaaaaaaaaaa",- name: "local",- nodeId: "subagents/local",- },- operation: {- callId: "call-local",- id: "op-local",- kind: "start",- parentTurnId: "turn_0",- },- phase: "running",-};--const REMOTE_RUNNING_HANDLE: AgentHandle = {- address: {- callbackBaseUrl: "https://parent.example.com",- kind: "agent/remote",- sessionId: "remote-child",- url: "https://remote.example.com",- },- identity: {- id: "ag_remote:bbbbbbbbbbbb",- name: "remote",- nodeId: "subagents/remote.ts",- },- operation: {- callId: "call-remote",- id: "op-remote",- kind: "start",- parentTurnId: "turn_0",- },- phase: "running",-};--const remote = {- kind: "remote",- name: "remote",- nodeId: "subagents/remote.ts",- path: "/custom-create-path",- url: "https://registry.example.com",-} as const;--afterEach(() => {- vi.clearAllMocks();- vi.useRealTimers();-});--describe("cancelDescendantTurnsStep", () => {- it("cancels every running local and remote child in parallel", async () => {- installRemoteRegistry();- vi.mocked(resolveRemoteAgentForAction).mockReturnValue(remote as never);- vi.mocked(requestWorkflowTurnCancellation).mockResolvedValue({- sessionId: "local-child",- status: "accepted",- });- vi.mocked(cancelRemoteAgentTurn).mockResolvedValue({- sessionId: "remote-child",- status: "accepted",- });-- await cancelDescendantTurnsStep({- serializedContext: { context: "parent" },- sessionState: createRunningState(),- });-- expect(requestWorkflowTurnCancellation).toHaveBeenCalledWith({- sessionId: "local-child",- });- expect(resolveRemoteAgentForAction).toHaveBeenCalledWith({- dynamicRemoteAgent: undefined,- nodeId: REMOTE_RUNNING_HANDLE.identity.nodeId,- registry: expect.any(Map),- remoteAgentName: REMOTE_RUNNING_HANDLE.identity.name,- });- // Cancels at the dispatch-recorded URL, not the registry URL.- expect(cancelRemoteAgentTurn).toHaveBeenCalledWith({- remote: { ...remote, url: "https://remote.example.com" },- sessionId: "remote-child",- });- });-- it("signals owned children while their workflow is still unwinding", async () => {- const settlement = Promise.withResolvers<void>();- vi.mocked(cancelWorkflowToolRun).mockReturnValueOnce(settlement.promise);- vi.mocked(requestWorkflowTurnCancellation).mockResolvedValue({- status: "accepted",- sessionId: "local-child",- });- const cancellation = cancelDescendantTurnsStep({- serializedContext: {},- sessionState: createDurableSessionState({- session: createSession({- "eve.harness.emission": {- turnId: "turn_0",- stepIndex: 0,- sequence: 0,- sessionStarted: true,- },- "eve.workflowTool": {- version: 4,- runs: [- {- callId: "call",- toolName: "research",- origin: { turnId: "turn_0", stepIndex: 0 },- address: { runId: "workflow", hookToken: "hook" },- },- ],- },- [AGENT_HANDLES_STATE_KEY]: {- handles: [- {- phase: "claimed",- ownerId: "workflow",- operationId: "op",- identity: LOCAL_RUNNING_HANDLE.identity,- address: LOCAL_RUNNING_HANDLE.address,- },- ],- },- }),- }),- });- await Promise.resolve();- expect(cancelWorkflowToolRun).toHaveBeenCalled();- expect(requestWorkflowTurnCancellation).toHaveBeenCalledWith({ sessionId: "local-child" });- settlement.resolve();- await cancellation;- });-- it("does not deserialize remote context for local-only descendants", async () => {- vi.mocked(requestWorkflowTurnCancellation).mockResolvedValue({- sessionId: "local-child",- status: "accepted",- });-- await cancelDescendantTurnsStep({- serializedContext: {},- sessionState: createRunningState({ includeRemote: false }),- });-- expect(requestWorkflowTurnCancellation).toHaveBeenCalledWith({- sessionId: "local-child",- });- expect(deserializeContext).not.toHaveBeenCalled();- });-- it("uses the selected dynamic remote config when cancelling", async () => {- const dynamicRemoteAgent = {- description: "Selected remote.",- path: "/eve/v1/session",- url: "https://selected.example.com",- };- installRemoteRegistry({- agentConfig: undefined,- kind: "remote",- prepared: {} as never,- remoteAgent: dynamicRemoteAgent,- });- vi.mocked(resolveRemoteAgentForAction).mockReturnValue(remote as never);- vi.mocked(requestWorkflowTurnCancellation).mockResolvedValue({- sessionId: "local-child",- status: "accepted",- });- vi.mocked(cancelRemoteAgentTurn).mockResolvedValue({- sessionId: "remote-child",- status: "accepted",- });-- await cancelDescendantTurnsStep({- serializedContext: {},- sessionState: createRunningState(),- });-- expect(resolveRemoteAgentForAction).toHaveBeenCalledWith({- dynamicRemoteAgent,- nodeId: REMOTE_RUNNING_HANDLE.identity.nodeId,- registry: expect.any(Map),- remoteAgentName: REMOTE_RUNNING_HANDLE.identity.name,- });- });-- it("skips parked handles: an idle child has no turn to cancel", async () => {- const session = createSession({- [AGENT_HANDLES_STATE_KEY]: {- handles: [- {- address: LOCAL_RUNNING_HANDLE.address,- identity: LOCAL_RUNNING_HANDLE.identity,- lastStatus: "waiting",- phase: "parked",- },- ],- },- });-- await cancelDescendantTurnsStep({- serializedContext: {},- sessionState: createDurableSessionState({ session }),- });-- expect(requestWorkflowTurnCancellation).not.toHaveBeenCalled();- expect(cancelRemoteAgentTurn).not.toHaveBeenCalled();- });-- it("retries no-active-turn responses during the child adoption window", async () => {- vi.useFakeTimers();- installRemoteRegistry();- vi.mocked(resolveRemoteAgentForAction).mockReturnValue(remote as never);- vi.mocked(requestWorkflowTurnCancellation)- .mockResolvedValueOnce({ status: "no_active_turn" })- .mockResolvedValueOnce({ sessionId: "local-child", status: "accepted" });- vi.mocked(cancelRemoteAgentTurn)- .mockResolvedValueOnce({ status: "no_active_turn" })- .mockResolvedValueOnce({ sessionId: "remote-child", status: "accepted" });-- const cancellation = cancelDescendantTurnsStep({- serializedContext: {},- sessionState: createRunningState(),- });- await vi.advanceTimersByTimeAsync(3_000);- await cancellation;-- expect(requestWorkflowTurnCancellation).toHaveBeenCalledTimes(2);- expect(cancelRemoteAgentTurn).toHaveBeenCalledTimes(2);- });-- it("contains unexpected local failures and exhausted remote failures", async () => {- vi.useFakeTimers();- installRemoteRegistry();- vi.mocked(resolveRemoteAgentForAction).mockReturnValue(remote as never);- vi.mocked(requestWorkflowTurnCancellation).mockRejectedValue(- new Error("local hook storage unavailable"),- );- vi.mocked(cancelRemoteAgentTurn).mockRejectedValue(new TypeError("remote unavailable"));- vi.mocked(isRetryableRemoteAgentCancelError).mockReturnValue(true);- const error = vi.spyOn(console, "error").mockImplementation(() => {});-- const cancellation = cancelDescendantTurnsStep({- serializedContext: {},- sessionState: createRunningState(),- });- await vi.advanceTimersByTimeAsync(10_000);- await expect(cancellation).resolves.toBeUndefined();-- expect(requestWorkflowTurnCancellation).toHaveBeenCalledOnce();- expect(cancelRemoteAgentTurn).toHaveBeenCalledTimes(8);- expect(error).toHaveBeenCalledWith(- "[eve:execution.cancel-descendant-turns] failed to cancel local descendant turn",- expect.objectContaining({ callId: "call-local", childSessionId: "local-child" }),- );- expect(error).toHaveBeenCalledWith(- "[eve:execution.cancel-descendant-turns] failed to cancel remote descendant turn",- expect.objectContaining({ callId: "call-remote", childSessionId: "remote-child" }),- );- });-- it("warns loudly when a descendant cancel is never accepted", async () => {- vi.useFakeTimers();- vi.mocked(requestWorkflowTurnCancellation).mockResolvedValue({- status: "no_active_turn",- });- const warn = vi.spyOn(console, "warn").mockImplementation(() => {});-- const cancellation = cancelDescendantTurnsStep({- serializedContext: {},- sessionState: createRunningState({ includeRemote: false }),- });- await vi.advanceTimersByTimeAsync(10_000);- await expect(cancellation).resolves.toBeUndefined();-- expect(requestWorkflowTurnCancellation).toHaveBeenCalledTimes(8);- expect(warn).toHaveBeenCalledWith(- "[eve:execution.cancel-descendant-turns] descendant cancel was never accepted; the child may run to completion",- expect.objectContaining({- childSessionId: "local-child",- finalStatus: "no_active_turn",- }),- );- });-- it("treats sessions without a handle store as having no descendants", async () => {- await cancelDescendantTurnsStep({- serializedContext: {},- sessionState: createDurableSessionState({ session: createSession() }),- });-- expect(requestWorkflowTurnCancellation).not.toHaveBeenCalled();- expect(cancelRemoteAgentTurn).not.toHaveBeenCalled();- expect(deserializeContext).not.toHaveBeenCalled();- });-});--function installRemoteRegistry(selection?: unknown): void {- vi.mocked(deserializeContext).mockResolvedValue({- get: vi.fn(() =>- selection === undefined ? undefined : { [REMOTE_RUNNING_HANDLE.identity.nodeId]: selection },- ),- require: vi.fn(() => ({- subagentRegistry: {- subagentsByNodeId: new Map([[REMOTE_RUNNING_HANDLE.identity.nodeId, remote]]),- },- })),- } as never);-}--function createRunningState(input: { readonly includeRemote?: boolean } = {}) {- const includeRemote = input.includeRemote ?? true;- const handles = includeRemote- ? [LOCAL_RUNNING_HANDLE, REMOTE_RUNNING_HANDLE]- : [LOCAL_RUNNING_HANDLE];- return createDurableSessionState({- session: createSession({ [AGENT_HANDLES_STATE_KEY]: { handles } }),- });-}--function createSession(state?: HarnessSession["state"]): HarnessSession {- return {- agent: { modelReference: { id: "test-model" }, system: "", tools: [] },- compaction: { recentWindowSize: 10, threshold: 100_000 },- continuationToken: "http:parent",- history: [],- sessionId: "parent",- state,- };-}diff --git a/packages/eve/src/execution/cancel-descendant-turns-step.ts b/packages/eve/src/execution/cancel-descendant-turns-step.tsindex e94006fc6..e70c41e5b 100644--- a/packages/eve/src/execution/cancel-descendant-turns-step.ts+++ b/packages/eve/src/execution/cancel-descendant-turns-step.ts@@ -1,47 +1,20 @@import { getPendingCoordinationBatch } from "#harness/coordination.js";-import type { CancelTurnResult } from "#channel/types.js";-import { deserializeContext } from "#context/serialize.js";-import { BundleKey } from "#runtime/sessions/runtime-context-keys.js";import { readDurableSession, type DurableSessionState } from "#execution/durable-session-store.js";-import {- cancelRemoteAgentTurn,- isRetryableRemoteAgentCancelError,- resolveRemoteAgentForAction,-} from "#subagents/remote-dispatch.js";import { cancelWorkflowToolRun } from "#execution/tools/workflow/cancel.js";-import { requestWorkflowTurnCancellation } from "#execution/workflow-runtime.js";import {getBlockingWorkflowToolRuns,type BlockingWorkflowToolRun,} from "#harness/workflow-tool-runs.js";--import { getAgentHandleStore, type AgentHandle } from "#subagents/handles/store.js";import { createLogger, logError } from "#internal/logging.js";-import type { RuntimeSubagentRegistry } from "#runtime/subagents/registry.js";-import { getDynamicSubagentSelection } from "#context/dynamic-subagent-lifecycle.js";-import type { ContextContainer } from "#context/container.js";-// Retry through transient world contention (queue wakes, hook-claim-// conflicts), then log loudly: a silently dropped cancel leaves the child-// running to completion with no trace of why.-const CANCEL_ATTEMPTS = 8;-const CANCEL_RETRY_INITIAL_DELAY_MS = 250;-const CANCEL_RETRY_MAX_DELAY_MS = 1_500;const log = createLogger("execution.cancel-descendant-turns");-type RunningAgentHandle = Extract<AgentHandle, { phase: "claimed" | "running" }>;--/**- * Cancels every running delegated child recorded in the agent handle store- * and every workflow tool run the turn is waiting on.- */+/** Cancels every workflow tool run the turn is waiting on. */export async function cancelDescendantTurnsStep(input: {- readonly serializedContext: Record<string, unknown>;readonly sessionState: DurableSessionState;}): Promise<void> {"use step";- let running: readonly RunningAgentHandle[];let workflowToolRuns: readonly BlockingWorkflowToolRun[];try {const session = readDurableSession(input.sessionState);@@ -50,12 +23,6 @@ export async function cancelDescendantTurnsStep(input: {getPendingCoordinationBatch(session.state)?.event.turnId ??input.sessionState.emissionState.turnId,);- const workflowOwnerIds = new Set(workflowToolRuns.map((run) => run.address.runId));- running = (getAgentHandleStore(session.state)?.handles ?? []).filter(- (handle): handle is RunningAgentHandle =>- handle.phase === "running" ||- (handle.phase === "claimed" && workflowOwnerIds.has(handle.ownerId)),- );} catch (error) {logError(log, "failed to read pending descendants during cancellation", error, {sessionId: input.sessionState.sessionId,@@ -63,125 +30,12 @@ export async function cancelDescendantTurnsStep(input: {return;}- let remoteContext:- | Promise<{- readonly ctx: ContextContainer;- readonly registry: RuntimeSubagentRegistry["subagentsByNodeId"];- }>- | undefined;- const getRemoteContext = () =>- (remoteContext ??= deserializeContext(input.serializedContext).then((ctx) => ({- ctx,- registry: ctx.require(BundleKey).subagentRegistry.subagentsByNodeId,- })));-- await Promise.all([- ...workflowToolRuns.map((record) =>- cancelWorkflowToolRun(record.address, "The turn that called the tool was cancelled."),+ await Promise.all(+ workflowToolRuns.map((record) =>+ cancelWorkflowToolRun(record.address, {+ kind: "cancel",+ reason: "The turn that called the tool was cancelled.",+ }),),- ...running.map((handle) =>- handle.address.kind === "agent/remote"- ? cancelRemoteDescendant({ handle, remoteContext: getRemoteContext() })- : cancelLocalDescendant({ handle }),- ),- ]);-}--async function cancelLocalDescendant(input: {- readonly handle: RunningAgentHandle;-}): Promise<void> {- const { handle } = input;- try {- const final = await requestCancellationWithRetry({- request: () => requestWorkflowTurnCancellation({ sessionId: handle.address.sessionId }),- shouldRetryError: () => false,- });- if (final.status !== "accepted") {- log.warn("descendant cancel was never accepted; the child may run to completion", {- callId: readHandleCallId(handle),- childSessionId: handle.address.sessionId,- finalStatus: final.status,- subagentName: handle.identity.name,- });- }- } catch (error) {- logError(log, "failed to cancel local descendant turn", error, {- callId: readHandleCallId(handle),- childSessionId: handle.address.sessionId,- subagentName: handle.identity.name,- });- }-}--async function cancelRemoteDescendant(input: {- readonly remoteContext: Promise<{- readonly ctx: ContextContainer;- readonly registry: RuntimeSubagentRegistry["subagentsByNodeId"];- }>;- readonly handle: RunningAgentHandle;-}): Promise<void> {- const { handle } = input;- if (handle.address.kind !== "agent/remote") {- return;- }- const childUrl = handle.address.url;- try {- const { ctx, registry } = await input.remoteContext;- const selection = getDynamicSubagentSelection(ctx, handle.identity.nodeId);- const resolved = await resolveRemoteAgentForAction({- dynamicRemoteAgent: selection?.kind === "remote" ? selection.remoteAgent : undefined,- nodeId: handle.identity.nodeId,- remoteAgentName: handle.identity.name,- registry,- });- // Cancel where the child actually runs: the registry URL may point at a- // newer deployment than the one that adopted this child, so the- // dispatch-recorded URL wins — mirroring continuation delivery.- const remote = { ...resolved, url: childUrl };-- const final = await requestCancellationWithRetry({- request: () => cancelRemoteAgentTurn({ remote, sessionId: handle.address.sessionId }),- shouldRetryError: isRetryableRemoteAgentCancelError,- });- if (final.status !== "accepted") {- log.warn("remote descendant cancel was never accepted; the child may run to completion", {- callId: readHandleCallId(handle),- childSessionId: handle.address.sessionId,- finalStatus: final.status,- remoteAgentName: handle.identity.name,- });- }- } catch (error) {- logError(log, "failed to cancel remote descendant turn", error, {- callId: readHandleCallId(handle),- childSessionId: handle.address.sessionId,- remoteAgentName: handle.identity.name,- });- }-}--function readHandleCallId(handle: RunningAgentHandle): string | undefined {- return handle.phase === "running" ? handle.operation.callId : handle.callId;-}--async function requestCancellationWithRetry(input: {- readonly request: () => Promise<CancelTurnResult>;- readonly shouldRetryError: (error: unknown) => boolean;-}): Promise<CancelTurnResult> {- let delayMs = CANCEL_RETRY_INITIAL_DELAY_MS;- let lastResult: CancelTurnResult = { status: "no_active_turn" };-- for (let attempt = 1; attempt <= CANCEL_ATTEMPTS; attempt += 1) {- try {- lastResult = await input.request();- if (lastResult.status === "accepted" || attempt === CANCEL_ATTEMPTS) return lastResult;- } catch (error) {- if (!input.shouldRetryError(error) || attempt === CANCEL_ATTEMPTS) throw error;- }-- await new Promise((resolve) => setTimeout(resolve, delayMs));- delayMs = Math.min(delayMs * 2, CANCEL_RETRY_MAX_DELAY_MS);- }-- return lastResult;+ );}diff --git a/packages/eve/src/execution/coordination-dispatch-shared.ts b/packages/eve/src/execution/coordination-dispatch-shared.tsindex bf40fb293..c87e795a0 100644--- a/packages/eve/src/execution/coordination-dispatch-shared.ts+++ b/packages/eve/src/execution/coordination-dispatch-shared.ts@@ -12,19 +12,16 @@ import {LocalDevRequestKey,type LocalDevRequestProvenance,ParentSessionKey,- SandboxKey,} from "#context/keys.js";import { ConversationContextKey } from "#shared/conversation-context.js";import { ContextContainer } from "#context/container.js";-import { withContextScope } from "#context/run-step.js";import {BundleKey,ChannelKey,type CompiledBundle,} from "#runtime/sessions/runtime-context-keys.js";import { deserializeContext } from "#context/serialize.js";-import type { RuntimeSession } from "#subagents/handle-dispatch.js";-import { getAgentHandleStore } from "#subagents/handles/store.js";+import type { HarnessSession } from "#harness/types.js";import { deriveRootTurnActivityWorkId } from "#execution/activity-work-id.js";import {assertUniqueCoordinationCallIds,@@ -44,23 +41,23 @@ import { hydrateDurableSession } from "#execution/session.js";import { buildSubagentRunInput } from "#subagents/tool.js";import { resolveEffectiveAgentRuntime } from "#execution/effective-agent-config.js";import type { WorkflowToolRunOwner } from "#execution/tools/workflow/messages.js";-import { resolveWorkflowAgentMetadata } from "#execution/tools/subagent/metadata.js";+import { resolveWorkflowAgentMetadata } from "#execution/agent-sessions/metadata.js";import { readDynamicSubagentSelections } from "#context/dynamic-subagent-lifecycle.js";import type { DynamicSubagentSelections } from "#execution/agent-sessions/target.js";import type { WorkflowAgentMetadata } from "#tools/workflow-definition.js";/** Input shared by direct and Workflow-originated owner-side dispatch. */export interface CoordinationDispatchInput {- readonly callbackBaseUrl?: string;readonly workflowToolRunOwner: WorkflowToolRunOwner;readonly sessionWritable: WritableStream<Uint8Array>;readonly serializedContext: Record<string, unknown>;readonly sessionState: DurableSessionState;}-/** Owner-side results and the updated session. */+/** Owner-side results and the updated context and session. */export interface CoordinationDispatchResult {readonly results: readonly RuntimeActionResult[];+ readonly serializedContext: Record<string, unknown>;readonly sessionState: DurableSessionState;}@@ -77,8 +74,6 @@ export interface PreparedCoordinationDispatch<PlanEntry = RuntimeWorkflowTaskReqreadonly inheritedConversation: Parameters<typeof buildSubagentRunInput>[0]["inheritedConversation"];- /** Number of local children sharing the parent's remaining token quota. */- readonly fanoutSize: number;readonly initiatorAuth: Parameters<typeof buildSubagentRunInput>[0]["initiatorAuth"];/** Inherited originating-client metadata for the dev-TUI hint. */readonly localDevRequest?: LocalDevRequestProvenance;@@ -90,7 +85,7 @@ export interface PreparedCoordinationDispatch<PlanEntry = RuntimeWorkflowTaskReqreadonly sandboxSessionId: string;readonly serializedContext: Record<string, unknown>;readonly plan: readonly PlanEntry[];- readonly session: RuntimeSession;+ readonly session: HarnessSession;readonly sessionState: DurableSessionState;readonly workflowAgents: Readonly<Record<string, WorkflowAgentMetadata>>;}@@ -118,7 +113,6 @@ export async function prepareCoordinationDispatch(input: {const prepared = await prepareActionDispatch({batch: {event,- localFanoutSize: pending.localFanoutSize,requests,},ctx,@@ -148,7 +142,6 @@ interface DispatchBatch {readonly stepIndex: number;readonly turnId: string;};- readonly localFanoutSize?: number;readonly requests: readonly { readonly callId: string }[];}@@ -156,17 +149,12 @@ export async function prepareActionDispatch<PlanEntry>(input: {readonly batch: DispatchBatch;readonly ctx: ContextContainer;readonly durableSession: Awaited<ReturnType<typeof readDurableSession>>;- readonly fanoutSize?: number;readonly plan: (input: {readonly bundle: CompiledBundle;readonly ctx: ContextContainer;readonly requests: DispatchBatch["requests"];- readonly session: RuntimeSession;+ readonly session: HarnessSession;}) => readonly PlanEntry[];- readonly planReusesOwnerSandbox?: (input: {- readonly bundle: CompiledBundle;- readonly plan: readonly PlanEntry[];- }) => boolean;readonly serializedContext: Record<string, unknown>;}): Promise<Omit<PreparedCoordinationDispatch<PlanEntry>, "sessionState">> {const { batch, durableSession } = input;@@ -175,7 +163,7 @@ export async function prepareActionDispatch<PlanEntry>(input: {const ctx = input.ctx;const bundle = ctx.require(BundleKey);const effectiveAgent = resolveEffectiveAgentRuntime(bundle, ctx);- let session = hydrateDurableSession({+ const session = hydrateDurableSession({compactionOverrides: {thresholdPercent: effectiveAgent.thresholdPercent,},@@ -184,9 +172,6 @@ export async function prepareActionDispatch<PlanEntry>(input: {});const adapter = ctx.require(ChannelKey);- // A corrupt handle store and rejected actions must resolve before sandbox- // initialization, which can provision provider resources and run preparation.- getAgentHandleStore(durableSession.state);const plan = input.plan({bundle,ctx,@@ -195,17 +180,6 @@ export async function prepareActionDispatch<PlanEntry>(input: {});const sandboxSessionId = resolveActiveSandboxSessionId(adapter.state, session.sessionId);- if (input.planReusesOwnerSandbox?.({ bundle, plan }) === true) {- try {- const scoped = await withContextScope(ctx, session, async (enrichedSession) => {- await ctx.require(SandboxKey).get();- return { result: undefined, session: enrichedSession };- });- session = scoped.session;- } finally {- ctx.clearVirtualContext();- }- }return {adapter,@@ -217,7 +191,6 @@ export async function prepareActionDispatch<PlanEntry>(input: {channelMetadata: ctx.get(ChannelInstrumentationKey),dynamicSubagentSelections: readDynamicSubagentSelections(ctx),inheritedConversation: ctx.get(ConversationContextKey),- fanoutSize: input.fanoutSize ?? batch.localFanoutSize ?? 0,initiatorAuth: ctx.get(InitiatorAuthKey) ?? null,localDevRequest: ctx.get(LocalDevRequestKey),parentSession: ctx.get(ParentSessionKey),@@ -236,7 +209,7 @@ export async function prepareActionDispatch<PlanEntry>(input: {function resolvePreparedActivity(activityObserver: ActivityObserverConfig | undefined,- session: RuntimeSession,+ session: HarnessSession,turnId: string,): (ActivityObserverConfig & { readonly workIdentity: ActivityWorkIdentityV1 }) | undefined {if (activityObserver === undefined) return undefined;diff --git a/packages/eve/src/execution/coordination-dispatch-step.ts b/packages/eve/src/execution/coordination-dispatch-step.tsindex 651027787..64fecd947 100644--- a/packages/eve/src/execution/coordination-dispatch-step.ts+++ b/packages/eve/src/execution/coordination-dispatch-step.ts@@ -6,9 +6,13 @@ import {type CoordinationDispatchResult,} from "#execution/coordination-dispatch-shared.js";import { createDurableSessionState } from "#execution/durable-session-store.js";-import { startWorkflowTask } from "#execution/tools/workflow/start.js";+import { publishSessionEvents } from "#execution/publish-session-events.js";+import { startWorkflowTask, type StartWorkflowTaskInput } from "#execution/tools/workflow/start.js";+import { sendToTask, startTaskRun } from "#execution/tasks/start.js";import { captureAgentSessionContext } from "#execution/agent-sessions/context.js";+import type { TaskStartedStreamEvent } from "#protocol/message.js";import type { RuntimeActionResult } from "#shared/action-types.js";+import type { HarnessSession } from "#harness/types.js";type CoordinationDispatchStepInput = CoordinationDispatchInput & {readonly action: "park";@@ -26,6 +30,7 @@ export async function dispatchCoordinationStep(if (prepared === undefined) {return {results: [],+ serializedContext: input.serializedContext,sessionState: input.sessionState,};}@@ -33,28 +38,55 @@ export async function dispatchCoordinationStep(const { batch, session } = prepared;let nextSession = session;const results: RuntimeActionResult[] = [];+ const started: TaskStartedStreamEvent[] = [];for (const task of prepared.plan) {- const started = await startWorkflowTask({+ const start = {agentContext: captureAgentSessionContext(prepared, task.callId),- agents: prepared.workflowAgents,- auth: prepared.auth,+ auth: { current: prepared.auth, initiator: prepared.initiatorAuth },batchEvent: batch.event,- initiatorAuth: prepared.initiatorAuth,owner: input.workflowToolRunOwner,parentSession: prepared.parentSession,session: nextSession,task,- });- nextSession = started.session;- if (started.result !== undefined) results.push(started.result);+ };+ const dispatched = await dispatchWorkflowCall(start);+ nextSession = dispatched.session;+ if (dispatched.result !== undefined) results.push(dispatched.result);+ if (dispatched.started !== undefined) started.push(dispatched.started);}- return {- results,- sessionState:- nextSession === session- ? prepared.sessionState- : createDurableSessionState({ session: nextSession }),- };+ const published = await publishSessionEvents(+ {+ serializedContext: input.serializedContext,+ sessionState:+ nextSession === session+ ? prepared.sessionState+ : createDurableSessionState({ session: nextSession }),+ sessionWritable: input.sessionWritable,+ },+ started,+ );+ return { results, ...published };+}++/**+ * Starts the run the call's entry point names, or sends a call with `taskId`+ * to the running `serve` task it names.+ */+async function dispatchWorkflowCall(start: StartWorkflowTaskInput): Promise<{+ readonly result?: RuntimeActionResult;+ readonly session: HarnessSession;+ readonly started?: TaskStartedStreamEvent;+}> {+ const { entry } = start.task;+ switch (entry.entryPoint) {+ case "execute":+ return await startWorkflowTask(start);+ case "task":+ case "serve":+ return await startTaskRun({ ...start, entry });+ case "receive":+ return await sendToTask({ ...start, taskId: entry.taskId });+ }}diff --git a/packages/eve/src/execution/dispatch-action-failures.ts b/packages/eve/src/execution/dispatch-action-failures.tsdeleted file mode 100644index d5e866b66..000000000--- a/packages/eve/src/execution/dispatch-action-failures.ts+++ /dev/null@@ -1,63 +0,0 @@-import { REMOTE_AGENT_START_FAILED } from "#subagents/agent-handle-errors.js";-import type {- RuntimeRemoteAgentDispatchRequest,- RuntimeSubagentDispatchRequest,- RuntimeSubagentDispatchFailure,-} from "#shared/action-types.js";-import { toErrorMessage } from "#shared/errors.js";--export function createUnavailableDynamicSubagentResult(- action: RuntimeSubagentDispatchRequest | RuntimeRemoteAgentDispatchRequest,-): RuntimeSubagentDispatchFailure {- const subagentName = getSubagentName(action);- return {- callId: action.callId,- isError: true,- kind: "subagent-result",- origin: "dispatch",- output: {- code: "SUBAGENT_UNAVAILABLE",- message: `Subagent "${subagentName}" is not available in the current session context.`,- },- subagentName,- };-}--export function getSubagentName(- action: RuntimeSubagentDispatchRequest | RuntimeRemoteAgentDispatchRequest,-): string {- return action.kind === "remote-agent-call" ? action.remoteAgentName : action.subagentName;-}--export function createRemoteAgentStartFailureResult(input: {- readonly action: RuntimeRemoteAgentDispatchRequest;- readonly error: unknown;-}): RuntimeSubagentDispatchFailure {- return {- callId: input.action.callId,- isError: true,- kind: "subagent-result",- origin: "dispatch",- output: {- code: REMOTE_AGENT_START_FAILED,- message: toErrorMessage(input.error),- },- subagentName: input.action.remoteAgentName,- };-}--export function createRecursiveAgentRootOnlyResult(- action: RuntimeSubagentDispatchRequest,-): RuntimeSubagentDispatchFailure {- return {- callId: action.callId,- isError: true,- kind: "subagent-result",- origin: "dispatch",- output: {- code: "RECURSIVE_AGENT_ROOT_ONLY",- message: 'The built-in "agent" tool is only available to the root session.',- },- subagentName: action.subagentName,- };-}diff --git a/packages/eve/src/execution/dispatch-start-operation.ts b/packages/eve/src/execution/dispatch-start-operation.tsdeleted file mode 100644index d4da5532d..000000000--- a/packages/eve/src/execution/dispatch-start-operation.ts+++ /dev/null@@ -1,37 +0,0 @@-import { deriveAgentOperationId } from "#subagents/handles/operation-id.js";-import {- deriveAgentId,- type AgentIdentity,- type StartOperation,-} from "#subagents/handles/store.js";--/**- * Mints deterministic parent-controlled ownership data before the child exists,- * so durable step replays derive the same handle record.- */-export function mintStartOperation(input: {- readonly callId: string;- readonly name: string;- readonly nodeId: string;- readonly parentSessionId: string;- readonly parentTurnId: string;-}): { readonly identity: AgentIdentity; readonly operation: StartOperation } {- const operationId = deriveAgentOperationId({- callId: input.callId,- parentSessionId: input.parentSessionId,- parentTurnId: input.parentTurnId,- });- return {- identity: {- id: deriveAgentId(input.name, operationId),- name: input.name,- nodeId: input.nodeId,- },- operation: {- callId: input.callId,- id: operationId,- kind: "start",- parentTurnId: input.parentTurnId,- },- };-}diff --git a/packages/eve/src/execution/dynamic-workflow/tool.ts b/packages/eve/src/execution/dynamic-workflow/tool.tsindex 428c70624..310b4e504 100644--- a/packages/eve/src/execution/dynamic-workflow/tool.ts+++ b/packages/eve/src/execution/dynamic-workflow/tool.ts@@ -8,7 +8,7 @@ export interface WorkflowProgramToolInput {}/** Static workflow executor used by the provided `workflow` tool. */-export async function executeWorkflowProgram(+export async function runWorkflowProgramTask(input: WorkflowProgramToolInput,ctx: WorkflowToolContext,): Promise<JsonValue> {diff --git a/packages/eve/src/execution/dynamic-workflow/workflow.ts b/packages/eve/src/execution/dynamic-workflow/workflow.tsindex 7e5d4b3f8..896865970 100644--- a/packages/eve/src/execution/dynamic-workflow/workflow.ts+++ b/packages/eve/src/execution/dynamic-workflow/workflow.ts@@ -80,7 +80,9 @@ async function callProgramAgent(.send<JsonValue>(message, { outputSchema, signal: ctx.abortSignal });const result = await response.result();if (result.status === "failed") {- throw new Error(`Agent "${call.target}" failed to handle the message.`);+ throw new Error(+ `Agent "${call.target}" failed to handle the message: ${result.error?.message ?? "no reason given"}`,+ );}if (outputSchema !== undefined) return result.data ?? null;return result.message ?? null;diff --git a/packages/eve/src/execution/legacy-session/interrupt-step.ts b/packages/eve/src/execution/legacy-session/interrupt-step.tsindex 89cfa091f..92747b804 100644--- a/packages/eve/src/execution/legacy-session/interrupt-step.ts+++ b/packages/eve/src/execution/legacy-session/interrupt-step.ts@@ -24,10 +24,7 @@ export async function interruptLegacySessionStep(prepared: PreparedLegacySession},};try {- await terminateChildSessionsStep({- sessionState: originalState,- serializedContext: prepared.serializedContext,- });+ await terminateChildSessionsStep({ sessionState: originalState });} catch (error) {logError(createLogger("execution.legacy-session"),diff --git a/packages/eve/src/execution/multi-agent-callback-routing.scenario.test.ts b/packages/eve/src/execution/multi-agent-callback-routing.scenario.test.tsindex 60ed2cb58..25c5a3ca1 100644--- a/packages/eve/src/execution/multi-agent-callback-routing.scenario.test.ts+++ b/packages/eve/src/execution/multi-agent-callback-routing.scenario.test.ts@@ -14,7 +14,7 @@ import {resolveInitialTurnCallerStep,} from "#subagents/parent-notification.js";import { REMOTE_AGENT_PROTOCOL_VERSION } from "#protocol/remote-agent-protocol.js";-import { startRemoteAgentSession } from "#subagents/remote-dispatch.js";+import { startRemoteAgentSession } from "#execution/agent-sessions/remote.js";import { resolveWorkflowCallbackBaseUrl } from "#execution/workflow-callback-url.js";import { authHookToken, CallbackBaseUrlKey, getHookUrl } from "#harness/authorization.js";import {diff --git a/packages/eve/src/execution/node-step.test.ts b/packages/eve/src/execution/node-step.test.tsindex 242f0fc02..6a516e043 100644--- a/packages/eve/src/execution/node-step.test.ts+++ b/packages/eve/src/execution/node-step.test.ts@@ -266,11 +266,11 @@ describe("createNodeHarnessTools", () => {expect(agentTool?.description).toContain("split a large task into independent pieces");expect(agentTool?.description).toContain("multiple `agent` calls in one response");expect(agentTool?.description).toContain("run a small fixed set in parallel");- expect(agentTool?.description).toContain("include essential context");+ expect(agentTool?.description).toContain("put everything it needs in message");expect(agentTool?.description).toContain("non-overlapping scopes");- expect(agentTool?.description).not.toContain("eve");+ expect(agentTool?.description).not.toMatch(/\beve\b/);expect(agentTool?.execute).toBeUndefined();- expect(agentTool?.workflowId).toBe("workflow//eve//subagentToolExecuteWorkflow");+ expect(agentTool?.workflowId).toBe("workflow//eve//agentToolServeWorkflow");});it("keeps an authored agent tool separate from self-delegation", async () => {@@ -317,8 +317,7 @@ describe("createNodeHarnessTools", () => {});for (const name of ["research", "reviewer"]) {expect(tools.get(name)?.execute).toBeUndefined();- expect(tools.get(name)?.nodeId).toEqual(expect.any(String));- expect(tools.get(name)?.workflowId).toBe("workflow//eve//subagentToolExecuteWorkflow");+ expect(tools.get(name)?.workflowId).toBe("workflow//eve//agentToolServeWorkflow");}});});diff --git a/packages/eve/src/execution/node-step.ts b/packages/eve/src/execution/node-step.tsindex b5a755149..fc29b0b96 100644--- a/packages/eve/src/execution/node-step.ts+++ b/packages/eve/src/execution/node-step.ts@@ -19,7 +19,8 @@ import {import type { RuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";import type { ResolvedRuntimeAgentNode } from "#runtime/graph.js";import type { HistoryViewProjector, PreparedHistoryView } from "#shared/history-view.js";-import type { PreparedRuntimeTool, PreparedRuntimeWorkflowTask } from "#runtime/sessions/turn.js";+import type { PreparedRuntimeTool } from "#runtime/sessions/turn.js";+import { workflowIdForHandling } from "#runtime/subagents/workflow-reference.js";import { findRegisteredRuntimeTool } from "#runtime/tools/registry.js";import type { ResolvedToolDefinition } from "#runtime/types.js";import { createToolExecuteWithAuth } from "#execution/tool-auth.js";@@ -185,7 +186,7 @@ function createRuntimeDynamicModelEventDispatcher(* Resolves unified {@link HarnessToolDefinition}s from the node's registries.** For authored tools: copies all lifecycle fields from the resolved definition.- * Prepared workflow-task tools share the workflow-tool harness path.+ * Prepared workflow-backed tools share the workflow-tool harness path.* Tools without `execute` (provider-managed) get entries with schema but no execute.*/export function createNodeHarnessTools(input: {@@ -212,8 +213,9 @@ function resolveHarnessToolDefinition(input: {readonly tool: PreparedRuntimeTool;}): HarnessToolDefinition | null {const registeredTool = findRegisteredRuntimeTool(input.node.toolRegistry, input.tool.name);+ const workflowId = workflowIdForHandling(input.tool.behavior?.handling);- if (isPreparedRuntimeWorkflowTool(input.tool)) {+ if (workflowId !== undefined) {if (registeredTool === null) {return createPreparedWorkflowToolHarnessDefinition(input.tool);}@@ -224,8 +226,7 @@ function resolveHarnessToolDefinition(input: {definition: registeredTool.definition,rootOnly: input.tool.rootOnly,}),- nodeId: input.tool.task.nodeId,- workflowId: input.tool.task.workflowId,+ workflowId,});}@@ -245,16 +246,6 @@ function resolveHarnessToolDefinition(input: {});}-type PreparedRuntimeWorkflowTool = PreparedRuntimeTool & {- readonly task: PreparedRuntimeWorkflowTask;-};--function isPreparedRuntimeWorkflowTool(- tool: PreparedRuntimeTool,-): tool is PreparedRuntimeWorkflowTool {- return tool.task !== undefined;-}-function createRegisteredHarnessToolDefinition(input: {readonly behavior?: HarnessToolDefinition["behavior"];readonly definition: ResolvedToolDefinition;diff --git a/packages/eve/src/execution/publish-session-events.ts b/packages/eve/src/execution/publish-session-events.tsindex b11b21e6b..ef92722a6 100644--- a/packages/eve/src/execution/publish-session-events.ts+++ b/packages/eve/src/execution/publish-session-events.ts@@ -221,7 +221,7 @@ function openSessionEventStream(input: {return {adapterCtx,async emit(event) {- if (origin === "own") activityCohort.updateActivityBlockers(ctx, event);+ if (origin === "own") activityCohort.updateActivityState(ctx, event);const routed = await callAdapterEventHandler(adapter, event, adapterCtx);setChannelContext(ctx, { ...adapter, state: { ...adapterCtx.state } });const stamped = stampMessageStreamEvent(diff --git a/packages/eve/src/execution/session-activity-projection.test.ts b/packages/eve/src/execution/session-activity-projection.test.tsindex aeee59195..102203574 100644--- a/packages/eve/src/execution/session-activity-projection.test.ts+++ b/packages/eve/src/execution/session-activity-projection.test.ts@@ -1,6 +1,7 @@import { afterEach, describe, expect, it, vi } from "vitest";-import { ActivityObserverKey } from "#context/keys.js";+import { ActivityObserverKey, ActivityTaskCallsKey } from "#context/keys.js";+import { updateActivityState } from "#execution/activity-cohort.js";import { ContextContainer } from "#context/container.js";import {observeSessionActivity,@@ -22,6 +23,17 @@ function turnEvent(type: "turn.started" | "turn.completed", turnId = "turn-1"):};}+function context(): ContextContainer {+ const ctx = new ContextContainer();+ ctx.set(ActivityObserverKey, {+ sink: {+ url: "https://agent.example.com/eve/v1/activity/abcdefghijklmnopqrstuvwxyz123456",+ version: 1,+ },+ });+ return ctx;+}+function reduceProjection(input: {readonly events: readonly MessageStreamEvent[];readonly sessionId: string;@@ -118,6 +130,60 @@ describe("projectSessionActivity", () => {expect(snapshot.pendingSettlements).toEqual({});});+ it("keeps a task call running from its receipt until task.settled", () => {+ const ctx = context();+ const coordinates = { sequence: 0, stepIndex: 0, turnId: "turn-1" };+ const call = { callId: "call-1", taskId: "task-1", turnId: "turn-1" };+ const receipt: MessageStreamEvent = {+ data: {+ ...coordinates,+ result: { callId: "call-1", kind: "tool-result", output: "Started", toolName: "report" },+ status: "completed",+ },+ meta: { at, id: "receipt" },+ type: "action.result",+ };+ const settled: MessageStreamEvent = {+ data: { ...call, error: { message: "Source unavailable." }, status: "failed" },+ meta: { at, id: "task-settled" },+ type: "task.settled",+ };+ const events: MessageStreamEvent[] = [+ {+ data: {+ ...coordinates,+ actions: [{ callId: "call-1", input: {}, kind: "tool-call", toolName: "report" }],+ },+ meta: { at, id: "actions" },+ type: "actions.requested",+ },+ {+ data: { ...call, kind: "tool", name: "report" },+ meta: { at, id: "task-started" },+ type: "task.started",+ },+ receipt,+ ];+ const reduce = (snapshot: ActivitySnapshotV1, event: MessageStreamEvent) => {+ updateActivityState(ctx, event);+ return reduceActivityBatch(snapshot, {+ events: projectSessionActivity({+ event,+ sessionId: "session-1",+ taskCallIds: ctx.get(ActivityTaskCallsKey),+ }),+ version: 1,+ });+ };+ const actionId = `action:${deriveRootTurnActivityWorkId({ sessionId: "session-1", turnId: "turn-1" })}:call-1`;++ const afterReceipt = events.reduce(reduce, createActivitySnapshot());+ expect(afterReceipt.actions[actionId]).toMatchObject({ phase: "running" });++ const afterSettled = reduce(afterReceipt, settled);+ expect(afterSettled.actions[actionId]).toMatchObject({ phase: "failed" });+ });+it("uses the durable partial event id for activity updates", () => {const event: MessageStreamEvent = {data: {@@ -238,17 +304,6 @@ describe("projectSessionActivity", () => {describe("observeSessionActivity", () => {afterEach(() => vi.unstubAllGlobals());- function context(): ContextContainer {- const ctx = new ContextContainer();- ctx.set(ActivityObserverKey, {- sink: {- url: "https://agent.example.com/eve/v1/activity/abcdefghijklmnopqrstuvwxyz123456",- version: 1,- },- });- return ctx;- }-it("does not submit events with no activity projection", async () => {const fetchMock = vi.fn();vi.stubGlobal("fetch", fetchMock);diff --git a/packages/eve/src/execution/session-activity-projection.ts b/packages/eve/src/execution/session-activity-projection.tsindex 5fe3c7414..169adc88d 100644--- a/packages/eve/src/execution/session-activity-projection.ts+++ b/packages/eve/src/execution/session-activity-projection.ts@@ -3,6 +3,7 @@ import {ActivityObserverKey,ActivityPendingBlockersKey,ActivityRootTurnIdKey,+ ActivityTaskCallsKey,} from "#context/keys.js";import { projectActivityEvents } from "#execution/activity-events.js";import { deriveRootTurnActivityWorkId } from "#execution/activity-work-id.js";@@ -24,6 +25,7 @@ export async function observeSessionActivity(input: {rootTurnId: input.ctx.get(ActivityRootTurnIdKey),sessionId: input.sessionId,suppressRootSettlement: (input.ctx.get(ActivityPendingBlockersKey)?.length ?? 0) > 0,+ taskCallIds: input.ctx.get(ActivityTaskCallsKey),workIdentity: observer.workIdentity,}),sink: observer.sink,@@ -35,6 +37,7 @@ export function projectSessionActivity(input: {readonly rootTurnId?: string;readonly sessionId: string;readonly suppressRootSettlement?: boolean;+ readonly taskCallIds?: readonly string[];readonly workIdentity?: ActivityWorkIdentityV1;}): readonly ActivityEventV1[] {const work = workFor(input);@@ -68,6 +71,7 @@ export function projectSessionActivity(input: {event: input.event,eventId: input.event.meta.id,lineage: work,+ taskCallIds: input.taskCallIds,}),);return events;diff --git a/packages/eve/src/execution/session-inbox/inbox.ts b/packages/eve/src/execution/session-inbox/inbox.tsindex 0d4761575..c0668daf4 100644--- a/packages/eve/src/execution/session-inbox/inbox.ts+++ b/packages/eve/src/execution/session-inbox/inbox.ts@@ -37,6 +37,8 @@ export interface SessionInboxReader {/** Removes every payload accepted so far, in arrival order. */drain(): SessionInboxPayload[];hasPending(): boolean;+ /** Resolves once a payload is ready or the inbox closes, without consuming anything. */+ whenPending(): Promise<void>;/*** Called from the pump the moment an interrupt (`cancel`, `reset`,* `session-timeout`) is accepted, ahead of any consumer read. Handlers must@@ -46,6 +48,11 @@ export interface SessionInboxReader {onInterrupt(handler: (payload: SessionInboxPayload) => void): () => void;/** Observes deliveries without consuming them; replays unread deliveries on subscription. */onDelivery(handler: (payload: SessionInboxPayload) => void): () => void;+ /**+ * Observes runs' `agent-started` messages without consuming them; replays+ * unread ones on subscription. Handlers must be synchronous.+ */+ onAgentStarted(handler: (message: WorkflowToolRunAgentStarted) => void): () => void;restore(payloads: readonly SessionInboxPayload[]): void;}@@ -80,6 +87,7 @@ export function createSessionInbox(sessionId: string): SessionInboxHandle {const waiters = new Set<() => void>();const interruptHandlers = new Set<(payload: SessionInboxPayload) => void>();const deliveryHandlers = new Set<(payload: SessionInboxPayload) => void>();+ const agentStartedHandlers = new Set<(message: WorkflowToolRunAgentStarted) => void>();let failure: { error: unknown } | undefined;const notify = (): void => {@@ -102,6 +110,8 @@ export function createSessionInbox(sessionId: string): SessionInboxHandle {for (const handler of deliveryHandlers) handler(result.value);if (isInterrupt(result.value))for (const handler of interruptHandlers) handler(result.value);+ if (isAgentStarted(result.value))+ for (const handler of agentStartedHandlers) handler(result.value);notify();}} catch (error) {@@ -174,6 +184,9 @@ export function createSessionInbox(sessionId: string): SessionInboxHandle {if (failure !== undefined) throw failure.error;return queue.length > 0;},+ async whenPending() {+ while (failure === undefined && queue.length === 0 && !closed()) await wait();+ },onInterrupt(handler) {interruptHandlers.add(handler);return () => interruptHandlers.delete(handler);@@ -184,6 +197,11 @@ export function createSessionInbox(sessionId: string): SessionInboxHandle {if (payload.kind === "send" || payload.kind === "deliver") handler(payload);return () => deliveryHandlers.delete(handler);},+ onAgentStarted(handler) {+ agentStartedHandlers.add(handler);+ for (const payload of queue) if (isAgentStarted(payload)) handler(payload);+ return () => agentStartedHandlers.delete(handler);+ },restore(payloads) {if (sources.length === 0)throw new Error("Cannot restore session commands before reclaiming the session hooks.");@@ -211,10 +229,22 @@ export function createSessionInbox(sessionId: string): SessionInboxHandle {};}+/** A run's report that it opened a session, which the session publishes as `agent.started`. */+export type WorkflowToolRunAgentStarted = Extract<+ WorkflowToolRunMessage,+ { readonly kind: "agent-started" }+>;++function isAgentStarted(value: SessionInboxPayload): value is WorkflowToolRunAgentStarted {+ return value.kind === "agent-started";+}+export function isWorkflowMessage(value: SessionInboxPayload): value is WorkflowToolRunMessage {return (value.kind === "agent-started" ||+ value.kind === "started" ||value.kind === "report" ||+ value.kind === "reply" ||value.kind === "request" ||value.kind === "withdraw" ||value.kind === "outcome"diff --git a/packages/eve/src/execution/session-workflow-tool-run.test.ts b/packages/eve/src/execution/session-workflow-tool-run.test.tsdeleted file mode 100644index 52a508b06..000000000--- a/packages/eve/src/execution/session-workflow-tool-run.test.ts+++ /dev/null@@ -1,91 +0,0 @@-import { beforeEach, expect, it, vi } from "vitest";--import { handleWorkflowToolRunMessage } from "#execution/session-workflow-tool-run.js";-import { applyTaskAgentRequest } from "#execution/tools/subagent/task-agent-requests.js";-import { cancelAgentInvocationOwnerStep } from "#execution/tools/subagent/task-cancel.js";-import { releaseAgentInvocationOwnerStep } from "#execution/tools/subagent/invoke-step.js";-import { registerWorkflowToolRun } from "#harness/workflow-tool-runs.js";-import { createTestSessionState } from "#internal/testing/session-state.js";-import { SessionStateCursor } from "#execution/session/state-cursor.js";--vi.mock("#execution/tools/subagent/task-agent-requests.js", () => ({- applyTaskAgentRequest: vi.fn(),-}));-vi.mock("#execution/tools/subagent/task-cancel.js", () => ({- cancelAgentInvocationOwnerStep: vi.fn(),-}));-vi.mock("#execution/tools/subagent/invoke-step.js", () => ({- releaseAgentInvocationOwnerStep: vi.fn(),-}));--beforeEach(() => vi.resetAllMocks());--it("settles the agent request once and treats workflow completion as an ordinary tool result", async () => {- const sessionState = createTestSessionState();- const session = registerWorkflowToolRun(sessionState.snapshot.session, {- callId: "call",- toolName: "agent",- origin: { turnId: "turn", stepIndex: 0 },- address: { runId: "run", hookToken: "control" },- });- const state = { ...sessionState, snapshot: { session } };- const cursor = new SessionStateCursor({- sessionState: state,- serializedContext: {},- sessionWritable: new WritableStream<Uint8Array>(),- inbox: { claimSessionHooks: vi.fn() },- });- const from = {- callId: "call",- execution: "blocking" as const,- input: {},- runId: "run",- sequence: 0,- stepIndex: 0,- toolName: "agent",- turnId: "turn",- };- const result = {- callId: "call",- kind: "subagent-result" as const,- origin: "child" as const,- subagentName: "agent",- output: "done",- outcome: {- kind: "parked" as const,- result: { kind: "succeeded" as const, output: "done" },- usageDelta: { inputTokens: 2, outputTokens: 3, cacheReadTokens: 0, cacheWriteTokens: 0 },- },- };- vi.mocked(applyTaskAgentRequest).mockResolvedValue({- serializedContext: {},- sessionState: state,- });- vi.mocked(releaseAgentInvocationOwnerStep).mockResolvedValue({ sessionState: state });-- await handleWorkflowToolRunMessage({- callbackMetadataUrl: "https://parent.example",- cursor,- message: {- kind: "request",- from,- replyTo: "reply",- request: { kind: "agent-settled", result },- },- });- const outcome = await handleWorkflowToolRunMessage({- callbackMetadataUrl: "https://parent.example",- cursor,- message: { kind: "outcome", from, result: { status: "completed", output: "done" } },- });-- expect(applyTaskAgentRequest).toHaveBeenCalledTimes(1);- expect(outcome).toEqual({- kind: "tool-result",- callId: "call",- toolName: "agent",- output: "done",- });- expect(cancelAgentInvocationOwnerStep).toHaveBeenCalledOnce();- expect(releaseAgentInvocationOwnerStep).toHaveBeenCalledOnce();-});diff --git a/packages/eve/src/execution/session-workflow-tool-run.ts b/packages/eve/src/execution/session-workflow-tool-run.tsindex e60697918..c484b8750 100644--- a/packages/eve/src/execution/session-workflow-tool-run.ts+++ b/packages/eve/src/execution/session-workflow-tool-run.ts@@ -12,12 +12,7 @@ import type {WorkflowToolRunWithdrawMessage,} from "#execution/tools/workflow/messages.js";import { withdrawWorkflowToolRunQuestionStep } from "#execution/tools/workflow/withdraw-step.js";-import { resolveWorkflowCallbackBaseUrl } from "#execution/workflow-callback-url.js";import type { SessionStateCursor } from "#execution/session/state-cursor.js";-import { applyTaskAgentRequest } from "#execution/tools/subagent/task-agent-requests.js";-import { cancelAgentInvocationOwnerStep } from "#execution/tools/subagent/task-cancel.js";-import { releaseAgentInvocationOwnerStep } from "#execution/tools/subagent/invoke-step.js";-import { resumeHookStep } from "#execution/tools/workflow/resume-hook-step.js";import {workflowToolRunOutcomeToToolResult,workflowToolRunRequestToInputRequestPayload,@@ -31,7 +26,6 @@ import type { WorkflowAskRoute } from "#harness/proxy-input-requests.js";import type { RuntimeActionResult } from "#shared/action-types.js";interface HandlerInput<T> {- readonly callbackMetadataUrl: string;readonly cursor: SessionStateCursor;readonly message: T;}@@ -41,6 +35,10 @@ export async function handleWorkflowToolRunMessage(): Promise<RuntimeActionResult | undefined> {const { message } = input;switch (message.kind) {+ // Only task runs report started or reply, and the session applies those to the task table.+ case "started":+ case "reply":+ return undefined;case "outcome":return await handleWorkflowToolRunOutcome({ ...input, message });case "request":@@ -84,22 +82,6 @@ async function handleWorkflowToolRunOutcome(const result = workflowToolRunOutcomeToToolResult(message);- // A failed or cancelled workflow may leave an agent invocation unfinished.- await cancelAgentInvocationOwnerStep({- ownerId: message.from.runId,- serializedContext: cursor.serializedContext,- sessionState: cursor.sessionState,- });- const released = await releaseAgentInvocationOwnerStep({- cancelled: message.result.status === "cancelled",- ownerId: message.from.runId,- sessionState: cursor.sessionState,- });- await cursor.apply({- serializedContext: cursor.serializedContext,- sessionState: released.sessionState,- });-return isInboxToolResultFromRecordedWorkflowToolRun(cursor.sessionState.snapshot.session.state,result,@@ -112,45 +94,6 @@ async function handleWorkflowToolRunRequest(input: HandlerInput<WorkflowToolRunRequestMessage>,): Promise<void> {const { cursor, message } = input;- if (message.request.kind === "agent-invoke" || message.request.kind === "agent-settled") {- const recorded = findBlockingWorkflowToolRun(- cursor.sessionState.snapshot.session.state,- message.from.callId,- message.from.turnId,- );- if (recorded?.address.runId !== message.from.runId) {- if (message.request.kind === "agent-invoke") {- await resumeHookStep(message.replyTo, {- kind: "runtime-action-result",- results: [- {- callId: message.request.invocationId,- isError: true,- kind: "subagent-result",- origin: "dispatch",- output: {- code: "AGENT_INVOCATION_NOT_ADMITTED",- message: "The workflow tool run no longer owns this agent invocation.",- },- subagentName: message.request.input.target,- },- ],- });- }- return;- }- await cursor.apply(- await applyTaskAgentRequest(- {- ownerId: message.from.runId,- replyTo: message.replyTo,- request: message.request,- },- requestContext(input),- ),- );- return;- }if (message.request.kind === "authorization-request") {const request = message.request;await deliverWorkflowAuthorization({ ...message, request }, async () => {@@ -207,10 +150,3 @@ function createWorkflowAskRoute(runId: from.runId,};}--function requestContext(input: HandlerInput<unknown>) {- return {- callbackBaseUrl: resolveWorkflowCallbackBaseUrl(input.callbackMetadataUrl),- ...input.cursor.stepState(),- };-}diff --git a/packages/eve/src/execution/session/admission.ts b/packages/eve/src/execution/session/admission.tsindex a993bcdff..ae9988019 100644--- a/packages/eve/src/execution/session/admission.ts+++ b/packages/eve/src/execution/session/admission.ts@@ -8,10 +8,7 @@ import {SessionInboxPayloadError,} from "#execution/session-inbox/protocol.js";import { reportDroppedWirePayloadStep } from "#execution/report-dropped-wire-payload-step.js";-import type { SessionStateCursor } from "#execution/session/state-cursor.js";import type { WorkflowToolRunMessage } from "#execution/tools/workflow/messages.js";-import { findRunningAgentHandle } from "#subagents/handles/query.js";-import { runProxySubagentEventStep } from "#subagents/event-proxy-step.js";/** One canonical admission result, after wire decoding but before turn policy. */type SessionAdmission =@@ -29,7 +26,6 @@ type SessionAdmission =export async function admitSessionInboxPayload(value: SessionInboxPayload,input: {- readonly cursor: SessionStateCursor;readonly queue: SessionInputQueue;},): Promise<SessionAdmission> {@@ -40,21 +36,8 @@ export async function admitSessionInboxPayload(input.queue.enqueueAuthorization(value.payloads);return { kind: "consumed" };}+ // A child's questions reach the session only through the run that opened it.if (value.kind === "subagent-input-request" || value.kind === "subagent-authorization-event") {- const handle = findRunningAgentHandle(input.cursor.sessionState.snapshot.session.state, {- callId: value.callId,- });- if (- handle?.identity.name === value.subagentName &&- handle.address.sessionId === value.childSessionId- ) {- await input.cursor.apply(- await runProxySubagentEventStep({- hookPayload: value,- ...input.cursor.stepState(),- }),- );- }return { kind: "consumed" };}diff --git a/packages/eve/src/execution/session/entry.integration.test.ts b/packages/eve/src/execution/session/entry.integration.test.tsindex ae5ee1f8d..8fd676cac 100644--- a/packages/eve/src/execution/session/entry.integration.test.ts+++ b/packages/eve/src/execution/session/entry.integration.test.ts@@ -431,7 +431,7 @@ describe("workflowEntry integration", () => {});});- it("notifies each delegated conversation turn and remains available via agentId", async () => {+ it("notifies the caller of each delegated conversation turn", async () => {const runtime = await createTestRuntime({agent: { name: "workflow-entry-delegated-conversation" },});diff --git a/packages/eve/src/execution/session/finalization.ts b/packages/eve/src/execution/session/finalization.tsindex f3ad201f9..5371d3964 100644--- a/packages/eve/src/execution/session/finalization.ts+++ b/packages/eve/src/execution/session/finalization.ts@@ -35,7 +35,7 @@ export async function finalizeSession(): Promise<WorkflowEntryResult> {const { serializedContext, sessionState } = context.cursor;if (sessionState !== undefined) {- await terminateChildSessionsStep({ serializedContext, sessionState });+ await terminateChildSessionsStep({ sessionState });}if (outcome.kind === "expired") {await emitTerminalSessionCompletionStep({diff --git a/packages/eve/src/execution/session/handoff-steps.ts b/packages/eve/src/execution/session/handoff-steps.tsindex f575e209e..4eb9a66ca 100644--- a/packages/eve/src/execution/session/handoff-steps.ts+++ b/packages/eve/src/execution/session/handoff-steps.ts@@ -11,14 +11,12 @@ import { getResolvedRuntimeAgentNode } from "#runtime/graph.js";import { BundleKey } from "#runtime/sessions/runtime-context-keys.js";import { getSandboxEnvironmentRuntime } from "#shared/sandbox-environment.js";import { isObject } from "#shared/guards.js";-import { getAgentHandleStore } from "#subagents/handles/store.js";/** Parses retained work with this deployment's code before deciding whether it can move. */export function isSessionStateIdleForHandoff(sessionState: DurableSessionState): boolean {const { state } = readDurableSession(sessionState);// Decoding the run registry rejects corrupt state before any busy-work shortcut.const workflowToolRuns = getBlockingWorkflowToolRuns(state);- const handles = getAgentHandleStore(state);// These registries are deleted when work settles. Their ordinary readers// tolerate malformed values as absent; that must not authorize a handoff.@@ -38,13 +36,7 @@ export function isSessionStateIdleForHandoff(sessionState: DurableSessionState):(!isObject(proxyRequests) || Object.keys(proxyRequests).length > 0))return false;- return (- (handles === undefined ||- handles.handles.every(- (handle) => handle.phase === "parked" || handle.phase === "available",- )) &&- workflowToolRuns.length === 0- );+ return workflowToolRuns.length === 0;}/** Reads durable work using the source deployment's handoff contract. */diff --git a/packages/eve/src/execution/session/handoff.test.ts b/packages/eve/src/execution/session/handoff.test.tsindex eb571bc30..97b8ca6a8 100644--- a/packages/eve/src/execution/session/handoff.test.ts+++ b/packages/eve/src/execution/session/handoff.test.ts@@ -226,8 +226,10 @@ function createInbox(input: { released?: SessionInboxPayload[] } = {}): SessionIdispose: vi.fn(async () => {}),drain: vi.fn(() => []),hasPending: vi.fn(() => false),+ whenPending: () => new Promise<void>(() => {}),next: vi.fn(),onDelivery: vi.fn(() => () => {}),+ onAgentStarted: () => () => {},onInterrupt: vi.fn(() => () => {}),release: vi.fn(async () => input.released ?? []),restore: vi.fn(),diff --git a/packages/eve/src/execution/session/input-queue.ts b/packages/eve/src/execution/session/input-queue.tsindex fd88a1e0f..b6dbf4679 100644--- a/packages/eve/src/execution/session/input-queue.ts+++ b/packages/eve/src/execution/session/input-queue.ts@@ -1,6 +1,6 @@import type { DeliverHookPayload, DeliverPayload } from "#channel/types.js";import { coalesceDeliveries } from "#harness/messages.js";-import { jsonValuesEqual } from "#shared/json.js";+import { ANONYMOUS_PRINCIPAL, principalOf } from "#execution/session/principal.js";export type SessionControl = "clear" | "compact" | "expired" | "reset";@@ -109,15 +109,12 @@ export class SessionInputQueue {this.entries[index] = { delivery, kind: "delivery", sequence };}- takeSteering(- admitted: ReadonlySet<number>,- callerCallId: string | undefined,- ): TurnSelection | undefined {+ takeSteering(admitted: ReadonlySet<number>, turn: SteeringTurn): TurnSelection | undefined {const steering = this.entries.filter((entry): entry is QueuedDelivery =>entry.kind === "delivery" &&admitted.has(entry.sequence) &&- isSteeringDelivery(entry.delivery, callerCallId),+ isSteeringDelivery(entry.delivery, turn),);if (steering.length === 0) return undefined;this.retain((entry) => entry.kind !== "delivery" || !steering.includes(entry));@@ -183,24 +180,29 @@ export class SessionInputQueue {};}- /** One authenticated principal's consecutive deliveries share a turn, with at most one caller. */+ /**+ * Consecutive deliveries of one authenticated principal and one delegated+ * call share a turn, as they would steer it. Claims may change between+ * them; the turn runs with the latest.+ */private takeFollowingDeliveriesFrom(first: QueuedDelivery, index: number): QueuedDelivery[] {- const authenticated =- first.delivery.auth != null && first.delivery.auth.principalType !== "anonymous";+ const principal = principalOf(first.delivery.auth);const following: QueuedDelivery[] = [];- let caller = first.delivery.caller;+ let callId = first.delivery.caller?.callId;while (this.entries.length > index) {const next = this.entries[index];if (next?.kind !== "delivery" ||- !authenticated ||- !jsonValuesEqual(first.delivery.auth, next.delivery.auth) ||- (caller !== undefined && next.delivery.caller !== undefined)+ principal === ANONYMOUS_PRINCIPAL ||+ principalOf(next.delivery.auth) !== principal ||+ (callId !== undefined &&+ next.delivery.caller !== undefined &&+ next.delivery.caller.callId !== callId)) {break;}following.push(this.entries.splice(index, 1)[0] as QueuedDelivery);- caller ??= next.delivery.caller;+ callId ??= next.delivery.caller?.callId;}return following;}@@ -211,23 +213,30 @@ export class SessionInputQueue {}}-export function isSteeringDelivery(- delivery: DeliverHookPayload,- callerCallId: string | undefined,-): boolean {+/** The running turn a delivery may steer. */+export interface SteeringTurn {+ /** The call id of the delegated caller the turn answers, if any. */+ readonly callerCallId: string | undefined;+ readonly principal: string;+}++/**+ * Only the turn's own principal steers it; another principal's message waits+ * for the turn to end. A delivery without auth acts as the session's current+ * identity, which is the turn's.+ */+export function isSteeringDelivery(delivery: DeliverHookPayload, turn: SteeringTurn): boolean {return ((delivery.turnPolicy ?? "steer") === "steer" &&- (delivery.caller === undefined || delivery.caller.callId === callerCallId)+ (delivery.caller === undefined || delivery.caller.callId === turn.callerCallId) &&+ (delivery.auth === undefined || principalOf(delivery.auth) === turn.principal));}/** A steering delivery with a message for the model, not only answers to requests. */-export function isSteeringMessage(- delivery: DeliverHookPayload,- callerCallId: string | undefined,-): boolean {+export function isSteeringMessage(delivery: DeliverHookPayload, turn: SteeringTurn): boolean {return (- isSteeringDelivery(delivery, callerCallId) &&+ isSteeringDelivery(delivery, turn) &&delivery.payloads.some((payload) => payload.message !== undefined && payload.inputResponses === undefined,)diff --git a/packages/eve/src/execution/session/next-input.test.ts b/packages/eve/src/execution/session/next-input.test.tsindex 56364ea33..f0ad83d42 100644--- a/packages/eve/src/execution/session/next-input.test.ts+++ b/packages/eve/src/execution/session/next-input.test.ts@@ -37,6 +37,7 @@ function createMockInbox(reads: readonly ScriptedRead[]): SessionInbox {hasPending() {return remaining.length > 0;},+ whenPending: () => new Promise<void>(() => {}),async next() {const read = remaining.shift();if (read === undefined) throw new Error("Mock inbox exhausted.");@@ -46,6 +47,7 @@ function createMockInbox(reads: readonly ScriptedRead[]): SessionInbox {onDelivery() {return () => {};},+ onAgentStarted: () => () => {},onInterrupt() {return () => {};},@@ -94,6 +96,7 @@ function waitInput(inbox: SessionInbox): WaitInput {const cursor = createCursor(inbox);return {expectedAttemptIds: new Set(["attempt-1"]),+ hasWorkingTasks: () => false,inbox: inbox,cursor,queue: new SessionInputQueue(),@@ -119,20 +122,18 @@ function queueOf(...deliveries: DeliverHookPayload[]): SessionInputQueue {}describe("nextTurnDelivery", () => {- it("batches adjacent queued deliveries with equivalent auth", async () => {+ it("batches one principal's adjacent queued deliveries with their latest claims", async () => {const auth: SessionAuthContext = {- attributes: { scopes: ["read", "write"], team: "support" },+ attributes: { scopes: ["read"], team: "support" },authenticator: "slack",issuer: "workspace",principalId: "bob",principalType: "user",subject: "bob-subject",};+ const refreshed = { ...auth, attributes: { scopes: ["read", "write"], team: "support" } };const first = authenticatedDelivery("first", auth);- const second = authenticatedDelivery("second", {- ...auth,- attributes: { team: "support", scopes: ["read", "write"] },- });+ const second = authenticatedDelivery("second", refreshed);const input = batchingInputFor([first, second]);const next = await nextTurnDelivery(input);@@ -140,7 +141,7 @@ describe("nextTurnDelivery", () => {expect(next).toMatchObject({kind: "turn",delivery: {- auth,+ auth: refreshed,payloads: [...first.payloads, ...second.payloads],deliveryMetadata: [first.deliveryMetadata![0],@@ -213,22 +214,52 @@ describe("nextTurnDelivery", () => {expect(input.queue.pendingCount).toBe(0);});- it.each([- { authenticator: "other" },- { issuer: "other" },- { principalType: "service" },- { subject: "other" },- { attributes: { scopes: ["write"] } },- ])("does not batch when auth context changes: %j", async (change) => {+ it("batches one delegated call's queued messages and stops at another call", async () => {const auth = slackAuth("alice");- const first = authenticatedDelivery("first", auth);- const second = authenticatedDelivery("second", { ...auth, ...change });- const input = batchingInputFor([first, second]);+ const fromCall = (message: string, callId: string): DeliverHookPayload => ({+ ...authenticatedDelivery(message, auth),+ caller: {+ callId,+ replyTo: { kind: "hook", token: `${message}-reply` },+ subagentName: "keeper",+ },+ });+ const input = batchingInputFor([+ fromCall("first", "call-1"),+ fromCall("correction", "call-1"),+ fromCall("other", "call-2"),+ ]);- await expect(nextTurnDelivery(input)).resolves.toMatchObject({ delivery: first, kind: "turn" });- expect(input.queue.pendingCount).toBe(1);+ // The turn answers the latest message's reply address.+ await expect(nextTurnDelivery(input)).resolves.toMatchObject({+ delivery: {+ caller: { callId: "call-1", replyTo: { token: "correction-reply" } },+ payloads: [{ message: "first" }, { message: "correction" }],+ },+ kind: "turn",+ });+ await expect(nextTurnDelivery(input)).resolves.toMatchObject({+ delivery: { caller: { callId: "call-2" }, payloads: [{ message: "other" }] },+ kind: "turn",+ });});+ it.each([{ authenticator: "other" }, { issuer: "other" }, { principalType: "service" }])(+ "does not batch when the principal changes: %j",+ async (change) => {+ const auth = slackAuth("alice");+ const first = authenticatedDelivery("first", auth);+ const second = authenticatedDelivery("second", { ...auth, ...change });+ const input = batchingInputFor([first, second]);++ await expect(nextTurnDelivery(input)).resolves.toMatchObject({+ delivery: first,+ kind: "turn",+ });+ expect(input.queue.pendingCount).toBe(1);+ },+ );+it.each([null, undefined])("does not batch deliveries with auth %j", async (auth) => {const first: DeliverHookPayload = { auth, kind: "deliver", payloads: [{ message: "first" }] };const second: DeliverHookPayload = { auth, kind: "deliver", payloads: [{ message: "second" }] };diff --git a/packages/eve/src/execution/session/next-input.ts b/packages/eve/src/execution/session/next-input.tsindex 031e0f418..bb36a210a 100644--- a/packages/eve/src/execution/session/next-input.ts+++ b/packages/eve/src/execution/session/next-input.ts@@ -16,6 +16,8 @@ export type NextTurnInstruction =| { readonly kind: SessionControl }| { readonly kind: "closed" }| { readonly kind: "cancel-turn" }+ /** `session.cancel()` while no turn runs, but tasks are working. */+ | { readonly kind: "cancel-working-tasks" }| TurnSelection;/**@@ -29,6 +31,7 @@ export async function nextTurnDelivery(input: {readonly inbox: SessionInboxReader;readonly cursor: SessionStateCursor;readonly expectedAttemptIds?: ReadonlySet<string>;+ readonly hasWorkingTasks: () => boolean;readonly queue: SessionInputQueue;}): Promise<NextTurnInstruction> {const { inbox, cursor, queue } = input;@@ -61,5 +64,8 @@ export async function nextTurnDelivery(input: {freshSequence =wasIdle && admitted.kind === "delivery" ? admitted.admission.sequence : undefined;if (admitted.kind === "workflow") return { kind: "workflow", message: admitted.message };+ if (admitted.kind === "cancel" && input.hasWorkingTasks()) {+ return { kind: "cancel-working-tasks" };+ }}}diff --git a/packages/eve/src/execution/session/pending-turn-state.ts b/packages/eve/src/execution/session/pending-turn-state.tsindex ed94edb68..64ae7ab2f 100644--- a/packages/eve/src/execution/session/pending-turn-state.ts+++ b/packages/eve/src/execution/session/pending-turn-state.ts@@ -1,6 +1,7 @@import { getPendingAuthorization } from "#harness/authorization.js";import { hasPendingInputBatch } from "#harness/input-requests.js";-import { getPendingCoordinationBatch } from "#harness/coordination.js";+import { getPendingCoordinationBatch, pendingCoordinationCallIds } from "#harness/coordination.js";+import { pendingTaskToolCalls, type TaskToolCall } from "#execution/tasks/calls.js";import type { HarnessSession } from "#harness/types.js";/** Derives the workflow fields used to select the next action at the park boundary. */@@ -9,6 +10,7 @@ export function derivePendingState(session: HarnessSession): {readonly hasPendingAuthorization: boolean;readonly hasPendingInputBatch: boolean;readonly pendingCoordinationCallIds?: readonly string[];+ readonly pendingTaskToolCalls?: readonly TaskToolCall[];} {const batch = getPendingCoordinationBatch(session.state);const pendingAuth = getPendingAuthorization(session.state);@@ -22,6 +24,7 @@ export function derivePendingState(session: HarnessSession): {if (batch === undefined) return base;return {...base,- pendingCoordinationCallIds: batch.tasks.map((request) => request.callId),+ pendingCoordinationCallIds: pendingCoordinationCallIds(batch),+ pendingTaskToolCalls: pendingTaskToolCalls(batch.responseMessages),};}diff --git a/packages/eve/src/execution/session/principal.ts b/packages/eve/src/execution/session/principal.tsnew file mode 100644index 000000000..593db93eb--- /dev/null+++ b/packages/eve/src/execution/session/principal.ts@@ -0,0 +1,20 @@+import type { SessionAuthContext } from "#channel/types.js";++/** Every anonymous caller shares this one principal. */+export const ANONYMOUS_PRINCIPAL = "anonymous";++/**+ * Stable key for the principal a session identity acts as: only a turn's own+ * principal steers it, and one principal's queued messages share a turn.+ */+export function principalOf(auth: SessionAuthContext | null | undefined): string {+ if (auth === null || auth === undefined || auth.principalType === "anonymous") {+ return ANONYMOUS_PRINCIPAL;+ }+ return JSON.stringify([+ auth.authenticator,+ auth.issuer ?? null,+ auth.principalType,+ auth.principalId,+ ]);+}diff --git a/packages/eve/src/execution/session/program.ts b/packages/eve/src/execution/session/program.tsindex a5bb97a2a..d6a00b99d 100644--- a/packages/eve/src/execution/session/program.ts+++ b/packages/eve/src/execution/session/program.ts@@ -12,6 +12,8 @@ import { cancelDescendantTurnsStep } from "#execution/cancel-descendant-turns-stimport { SessionInputQueue } from "#execution/session/input-queue.js";import { SessionExecution } from "#execution/session/turn.js";import { SessionStateCursor } from "#execution/session/state-cursor.js";+import { cancelWorkingTasks, sessionTaskTable } from "#execution/tasks/session.js";+import { workingTasks } from "#execution/tasks/table.js";import type { TurnOutcome, TurnStepPayload } from "#execution/session/turn-step-types.js";import { settleCancelledTurnStep } from "#execution/settle-cancelled-turn-step.js";import { finalizeSession, type SessionTerminalOutcome } from "#execution/session/finalization.js";@@ -208,16 +210,24 @@ async function runSessionLoop(const nextParkedActivity = async (expectedAttemptIds: ReadonlySet<string>,- ): Promise<Exclude<NextTurnInstruction, { kind: "workflow" }>> => {+ ): Promise<Exclude<NextTurnInstruction, { kind: "workflow" | "cancel-working-tasks" }>> => {while (true) {const next = await nextTurnDelivery({cursor,expectedAttemptIds,+ hasWorkingTasks: () => workingTasks(sessionTaskTable(cursor)).length > 0,inbox,queue,});- if (next.kind !== "workflow") return next;- await execution.handleWorkflowMessage(next.message);+ if (next.kind === "workflow") {+ await execution.handleWorkflowMessage(next.message);+ continue;+ }+ if (next.kind === "cancel-working-tasks") {+ await cancelWorkingTasks(cursor);+ continue;+ }+ return next;}};@@ -233,7 +243,9 @@ async function runSessionLoop(});}progress.turnId = `turn_${String(turnIndex++)}`;- return await execution.runTurn(payload);+ const outcome = await execution.runTurn(payload, { caller });+ if (outcome.caller !== undefined) progress.caller = outcome.caller;+ return outcome;};const runDeliveredTurn = async (next: Extract<NextTurnInstruction, { kind: "turn" }>,@@ -338,9 +350,9 @@ async function runSessionLoop(continue;case "cancel-turn":await cancelDescendantTurnsStep({- serializedContext: cursor.serializedContext,sessionState: cursor.sessionState,});+ await cancelWorkingTasks(cursor);await settleCancelledTurn();// Cancellation consumes any outstanding caller; do not report the prior turn.action = { ...action, settled: undefined };diff --git a/packages/eve/src/execution/session/state-compatibility.test.ts b/packages/eve/src/execution/session/state-compatibility.test.tsindex 5d94c2c8c..bcfcdaf03 100644--- a/packages/eve/src/execution/session/state-compatibility.test.ts+++ b/packages/eve/src/execution/session/state-compatibility.test.ts@@ -1,7 +1,6 @@import { describe, expect, it } from "vitest";import { createTestSessionState } from "#internal/testing/session-state.js";import { isSessionStateIdleForHandoff } from "#execution/session/handoff-steps.js";-import type { AgentHandle, AgentHandlePhase } from "#subagents/handles/store.js";const run = {callId: "call",@@ -15,83 +14,16 @@ function checkpoint(state: Record<string, unknown>) {return { ...value, snapshot: { session: { ...value.snapshot.session, state } } };}-const identity = { id: "ag_researcher:operation", name: "researcher", nodeId: "agent" };-const address = {- continuationToken: "subagent:parent:call",- kind: "agent/local" as const,- sessionId: "child-session",-};-const startOperation = {- callId: "call",- id: "operation",- kind: "start" as const,- parentTurnId: "turn",-};--function handle(phase: AgentHandlePhase): AgentHandle {- switch (phase) {- case "starting":- return {- identity,- operation: startOperation,- phase,- target: { continuationToken: address.continuationToken, kind: "agent/local" },- };- case "running":- return { address, identity, operation: startOperation, phase };- case "parked":- return { address, identity, lastStatus: "Research complete", phase };- case "reserved":- return { identity, operationId: "operation", ownerId: "run", phase };- case "claimed":- return { address, identity, operationId: "operation", ownerId: "run", phase };- case "available":- return { address, identity, phase };- }-}-describe("handoff state inspection", () => {it("accepts additive framework metadata and opaque authored state", () => {expect(isSessionStateIdleForHandoff(checkpoint({- "eve.agent.handles": { handles: [], futureStore: true },authored: { version: "anything", values: [null, false] },}),),).toBe(true);});- it.each(["parked", "available"] as const)(- "allows an idle %s agent handle to cross a handoff",- (phase) => {- expect(- isSessionStateIdleForHandoff(- checkpoint({ "eve.agent.handles": { handles: [handle(phase)] } }),- ),- ).toBe(true);- },- );- it.each(["starting", "running", "reserved", "claimed"] as const)(- "refuses an active %s agent handle",- (phase) => {- expect(- isSessionStateIdleForHandoff(- checkpoint({ "eve.agent.handles": { handles: [handle(phase)] } }),- ),- ).toBe(false);- },- );- it("parses idle handles before accepting them", () => {- expect(() =>- isSessionStateIdleForHandoff(- checkpoint({- "eve.agent.handles": {- handles: [{ ...handle("parked"), address: { ...address, sessionId: "" } }],- },- }),- ),- ).toThrow("Corrupt agent handle store");- });it("parses workflow tool runs before checking for waiting work", () => {const incompatible = { ...run, address: { ...run.address, hookToken: 42 } };expect(() =>diff --git a/packages/eve/src/execution/session/step-agent-starts.ts b/packages/eve/src/execution/session/step-agent-starts.tsnew file mode 100644index 000000000..601b4d765--- /dev/null+++ b/packages/eve/src/execution/session/step-agent-starts.ts@@ -0,0 +1,64 @@+import type {+ SessionInboxPayload,+ SessionInboxReader,+ WorkflowToolRunAgentStarted,+} from "#execution/session-inbox/inbox.js";+import type { SessionStateCursor } from "#execution/session/state-cursor.js";+import { emitAgentStartedStep } from "#execution/tools/workflow/emit-workflow-tool-run-report-step.js";++/**+ * Publishes a run's `agent.started` as it arrives while a model step runs. The+ * step lasts as long as the model thinks, and clients follow a child from its+ * `agent.started`, so the event can't wait for the boundary.+ *+ * The step's result replaces the session state at the boundary, so nothing+ * published during it may change that state. `agent.started` reaches no+ * channel handler and changes no activity, so its publication leaves the+ * state as it found it and is not adopted. Every other run message waits for+ * the boundary.+ */+export class StepAgentStarts {+ private readonly cursor: SessionStateCursor;+ private readonly inbox: SessionInboxReader;+ private readonly published = new Set<SessionInboxPayload>();++ constructor(inbox: SessionInboxReader, cursor: SessionStateCursor) {+ this.cursor = cursor;+ this.inbox = inbox;+ }++ async publishWhile<T>(step: Promise<T>): Promise<T> {+ const arrivals: WorkflowToolRunAgentStarted[] = [];+ let wake: (() => void) | undefined;+ const unsubscribe = this.inbox.onAgentStarted((message) => {+ arrivals.push(message);+ wake?.();+ });+ const stepSettled = step.then(+ () => "settled" as const,+ () => "settled" as const,+ );+ try {+ while (true) {+ const message = arrivals.shift();+ if (message !== undefined) {+ await emitAgentStartedStep({ ...this.cursor.stepState(), message });+ this.published.add(message);+ continue;+ }+ const arrived = new Promise<"arrived">((resolve) => {+ wake = () => resolve("arrived");+ });+ if ((await Promise.race([stepSettled, arrived])) === "settled") break;+ }+ } finally {+ unsubscribe();+ }+ return await step;+ }++ /** Whether the payload was published already, so admission skips it. */+ consume(payload: SessionInboxPayload): boolean {+ return this.published.delete(payload);+ }+}diff --git a/packages/eve/src/execution/session/turn-event-handler.ts b/packages/eve/src/execution/session/turn-event-handler.tsindex c32c9dc1b..ada491949 100644--- a/packages/eve/src/execution/session/turn-event-handler.ts+++ b/packages/eve/src/execution/session/turn-event-handler.ts@@ -48,10 +48,8 @@ const HOOK_CANCELLABLE_EVENTS = {"step.completed": true,"step.failed": false,"step.started": true,- "subagent.called": false,- "subagent.completed": false,- "subagent.event": false,- "subagent.started": false,+ "task.settled": false,+ "task.started": false,"turn.cancelled": false,"turn.completed": false,"turn.failed": false,diff --git a/packages/eve/src/execution/session/turn-step-result.ts b/packages/eve/src/execution/session/turn-step-result.tsindex 52d3dfcf8..06bda5c3b 100644--- a/packages/eve/src/execution/session/turn-step-result.ts+++ b/packages/eve/src/execution/session/turn-step-result.ts@@ -33,6 +33,15 @@ export function resolveSessionStepResult(};}+ if (stepResult.held !== undefined) {+ return {+ action: "held",+ serializedContext: nextSerializedContext,+ sessionState: nextState,+ taskIds: stepResult.held.taskIds,+ };+ }+if (stepResult.next === null) {const pending = derivePendingState(stepResult.session);diff --git a/packages/eve/src/execution/session/turn-step-types.ts b/packages/eve/src/execution/session/turn-step-types.tsindex 51166d58b..587e6365f 100644--- a/packages/eve/src/execution/session/turn-step-types.ts+++ b/packages/eve/src/execution/session/turn-step-types.ts@@ -1,6 +1,6 @@-import type { DeliverHookPayload } from "#channel/types.js";+import type { DeliverHookPayload, TurnCaller } from "#channel/types.js";import type { DurableSessionState } from "#execution/durable-session-store.js";-import type { SessionStepState } from "#execution/publish-session-events.js";+import type { TaskToolCall } from "#execution/tasks/calls.js";import type { SettledTurn } from "#harness/types.js";import type { RuntimeActionResult } from "#shared/action-types.js";import type { TokenUsage } from "#shared/token-usage.js";@@ -23,10 +23,13 @@ export interface TurnStepPayload {}/** Input for one atomic, session-owner-executed turn step. */-export interface TurnStepInput extends SessionStepState {+export interface TurnStepInput {readonly abortSignal?: AbortSignal;readonly steeringSignal?: AbortSignal;readonly input: TurnStepPayload | undefined;+ readonly sessionWritable: WritableStream<Uint8Array>;+ readonly serializedContext: Record<string, unknown>;+ readonly sessionState: DurableSessionState;}interface DurableStepResultFields {@@ -44,19 +47,28 @@ export type DurableStepResult = (readonly usageDelta?: TokenUsage;}| { readonly action: "cancelled" | "steered" }+ /** The model ended the turn while tasks work; the turn waits for them. */+ | { readonly action: "held"; readonly taskIds: readonly string[] }| {readonly action: "park";readonly authorizationAttemptIds?: readonly string[];readonly hasPendingAuthorization: boolean;readonly hasPendingInputBatch: boolean;readonly pendingCoordinationCallIds?: readonly string[];+ readonly pendingTaskToolCalls?: readonly TaskToolCall[];readonly settled?: SettledTurn;}) &DurableStepResultFields;/** The only two ways a locally executed conversational turn can settle. */-export type TurnOutcome =+export type TurnOutcome = {+ /**+ * The delegated caller of the latest message the turn read. A caller's+ * later message awaits its reply at its own address, so the turn reports there.+ */+ readonly caller?: TurnCaller;+} & (| {readonly kind: "done";readonly output: unknown;@@ -69,4 +81,5 @@ export type TurnOutcome =readonly cancelled?: true;readonly kind: "park";readonly settled?: SettledTurn;- };+ }+);diff --git a/packages/eve/src/execution/session/turn-step.test.ts b/packages/eve/src/execution/session/turn-step.test.tsindex 3c6c011e9..873c80588 100644--- a/packages/eve/src/execution/session/turn-step.test.ts+++ b/packages/eve/src/execution/session/turn-step.test.ts@@ -678,6 +678,7 @@ describe("dispatchCoordinationStep", () => {callId: "call-1",executeInput: {},input: {},+ entry: { entryPoint: "execute" },kind: "workflow-task",toolName: "research",workflowId: "workflow//eve//research",diff --git a/packages/eve/src/execution/session/turn-waiting-step.ts b/packages/eve/src/execution/session/turn-waiting-step.tsnew file mode 100644index 000000000..8ec34b3f8--- /dev/null+++ b/packages/eve/src/execution/session/turn-waiting-step.ts@@ -0,0 +1,16 @@+import {+ publishSessionEvents,+ type PublishedSessionEvents,+ type SessionStepState,+} from "#execution/publish-session-events.js";+import { createTurnWaitingEvent } from "#protocol/message.js";++/** Publishes `turn.waiting` for the open turn the session workflow just parked. */+export async function publishTurnWaitingStep(+ target: SessionStepState,+): Promise<PublishedSessionEvents> {+ "use step";++ const { sequence, turnId } = target.sessionState.emissionState;+ return await publishSessionEvents(target, [createTurnWaitingEvent({ sequence, turnId })]);+}diff --git a/packages/eve/src/execution/session/turn.test.ts b/packages/eve/src/execution/session/turn.test.tsindex 50ceb088d..bc0c73a9f 100644--- a/packages/eve/src/execution/session/turn.test.ts+++ b/packages/eve/src/execution/session/turn.test.ts@@ -7,9 +7,11 @@ import { SessionExecution } from "#execution/session/turn.js";import { SessionStateCursor } from "#execution/session/state-cursor.js";import { cancelDescendantTurnsStep } from "#execution/cancel-descendant-turns-step.js";import { turnStep } from "#execution/session/turn-step.js";-import type { DeliverHookPayload, SessionCapabilities } from "#channel/types.js";+import type { DeliverHookPayload, SessionCapabilities, TurnCaller } from "#channel/types.js";import { dispatchCoordinationStep } from "#execution/coordination-dispatch-step.js";import { routeDeliverToChildren } from "#execution/route-child-delivery.js";+import { publishTurnWaitingStep } from "#execution/session/turn-waiting-step.js";+import { createTask, readTaskTable, writeTaskTable } from "#execution/tasks/table.js";vi.mock("#compiled/@workflow/core/index.js", async (importOriginal) => ({...(await importOriginal()),@@ -26,6 +28,12 @@ vi.mock("#execution/cancel-descendant-turns-step.js", () => ({vi.mock("#execution/route-child-delivery.js", () => ({routeDeliverToChildren: vi.fn(),}));+vi.mock("#execution/session/turn-waiting-step.js", () => ({+ publishTurnWaitingStep: vi.fn(async ({ serializedContext, sessionState }) => ({+ serializedContext,+ sessionState,+ })),+}));beforeEach(() => {vi.mocked(routeDeliverToChildren)@@ -47,9 +55,11 @@ describe("SessionExecution checkpoints", () => {claimSessionHooks: vi.fn(),drain: () => [],hasPending: () => false,+ whenPending: () => new Promise<void>(() => {}),next: vi.fn(),restore: vi.fn(),onDelivery: () => () => {},+ onAgentStarted: () => () => {},onInterrupt: () => () => {},};let signal: AbortSignal | undefined;@@ -86,12 +96,14 @@ describe("SessionExecution checkpoints", () => {claimSessionHooks: vi.fn(),drain: () => pending.splice(0),hasPending: () => pending.length > 0,+ whenPending: () => new Promise<void>(() => {}),next: vi.fn(),restore: vi.fn(),onDelivery: (handler) => {deliver = handler;return () => {};},+ onAgentStarted: () => () => {},onInterrupt: (handler) => {interrupt = handler;return () => {};@@ -146,8 +158,10 @@ describe("SessionExecution checkpoints", () => {return snapshot;},hasPending: () => pending.length > 0,+ whenPending: () => new Promise<void>(() => {}),next: vi.fn(),restore: vi.fn(),+ onAgentStarted: () => () => {},onInterrupt: () => () => {},onDelivery: (handler) => {notify = handler;@@ -196,8 +210,10 @@ describe("SessionExecution checkpoints", () => {claimSessionHooks: vi.fn(),drain: () => pending.splice(0),hasPending: () => pending.length > 0,+ whenPending: () => new Promise<void>(() => {}),next: vi.fn(),restore: vi.fn(),+ onAgentStarted: () => () => {},onInterrupt: () => () => {},onDelivery: (handler) => {notify = handler;@@ -241,6 +257,67 @@ describe("SessionExecution checkpoints", () => {expect(cancelDescendantTurnsStep).not.toHaveBeenCalled();});+ it("lets its caller's next message steer a turn whose input carries no caller", async () => {+ // A delegated session's first turn starts from its initial message; the+ // session binds the caller beside it.+ const firstCall: TurnCaller = {+ callId: "call-1",+ replyTo: { kind: "hook", token: "reply-1" },+ subagentName: "keeper",+ };+ const correction: DeliverHookPayload = {+ caller: { ...firstCall, replyTo: { kind: "hook", token: "reply-2" } },+ kind: "deliver",+ payloads: [{ message: "Alice meant the blue notebook." }],+ };+ let notify: (payload: SessionInboxPayload) => void = () => {};+ const pending: SessionInboxPayload[] = [];+ const inbox: SessionInbox = {+ claimedTokens: [],+ claimSessionHook: vi.fn(),+ claimSessionHooks: vi.fn(),+ drain: () => pending.splice(0),+ hasPending: () => pending.length > 0,+ whenPending: () => new Promise<void>(() => {}),+ next: vi.fn(),+ restore: vi.fn(),+ onAgentStarted: () => () => {},+ onInterrupt: () => () => {},+ onDelivery: (handler) => {+ notify = handler;+ return () => {};+ },+ };+ vi.mocked(turnStep)+ .mockReset()+ .mockImplementationOnce(async (input) => {+ pending.push(correction);+ notify(correction);+ expect(input.steeringSignal?.aborted).toBe(true);+ return {+ action: "steered",+ serializedContext: input.serializedContext,+ sessionState: input.sessionState,+ };+ })+ .mockImplementationOnce(async (input) => {+ expect(input.input?.delivery?.payloads).toEqual(correction.payloads);+ return {+ action: "done",+ serializedContext: input.serializedContext,+ sessionState: input.sessionState,+ };+ });++ await expect(+ createExecution({ inbox, sessionState: state("") }).runTurn(+ { delivery: { kind: "deliver", payloads: [{ message: "Fill Alice's notebook." }] } },+ { caller: firstCall },+ ),+ ).resolves.toMatchObject({ caller: correction.caller, kind: "done" });+ expect(turnStep).toHaveBeenCalledTimes(2);+ });+it.each([{ kind: "deliver", turnPolicy: "queue", payloads: [{ message: "Queued" }] },{@@ -258,8 +335,10 @@ describe("SessionExecution checkpoints", () => {claimSessionHooks: vi.fn(),drain: () => [],hasPending: () => false,+ whenPending: () => new Promise<void>(() => {}),next: vi.fn(),restore: vi.fn(),+ onAgentStarted: () => () => {},onInterrupt: () => () => {},onDelivery: (handler) => {notify = handler;@@ -291,8 +370,10 @@ describe("SessionExecution checkpoints", () => {.mockReturnValueOnce([{ kind: "cancel" }]).mockReturnValue([]),hasPending: vi.fn(() => false),+ whenPending: () => new Promise<void>(() => {}),next: vi.fn(() => new Promise<never>(() => {})),onDelivery: vi.fn(() => () => {}),+ onAgentStarted: () => () => {},onInterrupt: vi.fn(() => () => {}),restore: vi.fn(),};@@ -309,6 +390,7 @@ describe("SessionExecution checkpoints", () => {});vi.mocked(dispatchCoordinationStep).mockResolvedValue({results: [],+ serializedContext: {},sessionState,});@@ -319,7 +401,7 @@ describe("SessionExecution checkpoints", () => {).resolves.toMatchObject({ cancelled: true, kind: "park" });expect(dispatchCoordinationStep).toHaveBeenCalledTimes(1);expect(inbox.next).not.toHaveBeenCalled();- expect(cancelDescendantTurnsStep).toHaveBeenCalledWith({ serializedContext: {}, sessionState });+ expect(cancelDescendantTurnsStep).toHaveBeenCalledWith({ sessionState });});it("consumes the cancelling command while retaining accepted follow-ups", async () => {@@ -340,8 +422,10 @@ describe("SessionExecution checkpoints", () => {.mockReturnValueOnce([followUp, { kind: "cancel" }]).mockReturnValue([]),hasPending: vi.fn(() => false),+ whenPending: () => new Promise<void>(() => {}),next: vi.fn(() => new Promise<never>(() => {})),onDelivery: vi.fn(() => () => {}),+ onAgentStarted: () => () => {},onInterrupt: vi.fn((handler) => {interrupt = handler;return () => {};@@ -387,8 +471,10 @@ describe("SessionExecution checkpoints", () => {claimSessionHooks: vi.fn(),drain: vi.fn().mockReturnValueOnce([steering]).mockReturnValue([]),hasPending: vi.fn(() => false),+ whenPending: () => new Promise<void>(() => {}),next: vi.fn(() => new Promise<never>(() => {})),onDelivery: vi.fn(() => () => {}),+ onAgentStarted: () => () => {},onInterrupt: vi.fn(() => () => {}),restore: vi.fn(),};@@ -413,6 +499,7 @@ describe("SessionExecution checkpoints", () => {.mockReset().mockResolvedValue({results: [actionResult],+ serializedContext: {},sessionState,});@@ -443,8 +530,10 @@ describe("SessionExecution checkpoints", () => {claimSessionHooks: vi.fn(),drain: vi.fn().mockReturnValueOnce([followUp]).mockReturnValue([]),hasPending: vi.fn(() => false),+ whenPending: () => new Promise<void>(() => {}),next: vi.fn(() => new Promise<never>(() => {})),onDelivery: vi.fn(() => () => {}),+ onAgentStarted: () => () => {},onInterrupt: vi.fn(() => () => {}),restore: vi.fn(),};@@ -490,8 +579,10 @@ describe("SessionExecution checkpoints", () => {claimSessionHooks: vi.fn(),drain: vi.fn(() => []),hasPending: vi.fn(() => false),+ whenPending: () => new Promise<void>(() => {}),next: vi.fn(() => new Promise<never>(() => {})),onDelivery: vi.fn(() => () => {}),+ onAgentStarted: () => () => {},onInterrupt: vi.fn(() => () => {}),restore: vi.fn(),};@@ -537,9 +628,11 @@ describe("SessionExecution checkpoints", () => {claimSessionHooks: vi.fn(),drain: vi.fn().mockReturnValueOnce([cancel, followUp]).mockReturnValue([]),hasPending: () => false,+ whenPending: () => new Promise<void>(() => {}),next: vi.fn(),restore: vi.fn(),onDelivery: () => () => {},+ onAgentStarted: () => () => {},onInterrupt: (handler) => {interrupt = handler;return () => {};@@ -585,8 +678,10 @@ describe("SessionExecution checkpoints", () => {claimSessionHooks: vi.fn(),drain: vi.fn(() => []),hasPending: vi.fn(() => false),+ whenPending: () => new Promise<void>(() => {}),next: vi.fn(async () => runtimePayloads.shift()),onDelivery: vi.fn(() => () => {}),+ onAgentStarted: () => () => {},onInterrupt: vi.fn(() => () => {}),restore: vi.fn(),};@@ -601,6 +696,7 @@ describe("SessionExecution checkpoints", () => {});vi.mocked(dispatchCoordinationStep).mockResolvedValue({results: [],+ serializedContext: {},sessionState,});vi.mocked(routeDeliverToChildren).mockResolvedValue({@@ -621,6 +717,64 @@ describe("SessionExecution checkpoints", () => {);expect(queue.pendingCount).toBe(0);});++ it("reports turn.waiting once when task_wait parks on a working task", async () => {+ const base = state("");+ const working = createTask(readTaskTable(undefined), {+ callId: "task-call",+ kind: "tool",+ name: "research",+ resumable: false,+ turnId: "turn_0",+ });+ const sessionState: DurableSessionState = {+ ...base,+ snapshot: { session: writeTaskTable(base.snapshot.session, working.table) },+ };+ // An unrelated result keeps the wait going for a second pass before the cancel.+ const runtimePayloads: SessionInboxPayload[] = [+ { kind: "runtime-action-result", results: [] },+ { kind: "cancel" },+ ];+ const inbox: SessionInbox = {+ claimedTokens: [],+ claimSessionHook: vi.fn(),+ claimSessionHooks: vi.fn(),+ drain: vi.fn(() => []),+ hasPending: vi.fn(() => false),+ whenPending: () => new Promise<void>(() => {}),+ next: vi.fn(async () => runtimePayloads.shift()),+ onDelivery: vi.fn(() => () => {}),+ onAgentStarted: () => () => {},+ onInterrupt: vi.fn(() => () => {}),+ restore: vi.fn(),+ };+ vi.mocked(turnStep)+ .mockReset()+ .mockResolvedValue({+ action: "park",+ hasPendingAuthorization: false,+ hasPendingInputBatch: false,+ pendingCoordinationCallIds: ["wait-call"],+ pendingTaskToolCalls: [{ callId: "wait-call", kind: "task_wait" }],+ serializedContext: {},+ sessionState,+ });+ vi.mocked(dispatchCoordinationStep).mockResolvedValue({+ results: [],+ serializedContext: {},+ sessionState,+ });++ await expect(+ createExecution({ inbox, sessionState }).runTurn({+ delivery: { kind: "deliver", payloads: [{ message: "Wait for the research." }] },+ }),+ ).resolves.toEqual({ cancelled: true, kind: "park" });++ expect(publishTurnWaitingStep).toHaveBeenCalledTimes(1);+ expect(publishTurnWaitingStep).toHaveBeenCalledWith(expect.objectContaining({ sessionState }));+ });});function createExecution(input: {diff --git a/packages/eve/src/execution/session/turn.ts b/packages/eve/src/execution/session/turn.tsindex 8253a52e6..39abcdcb7 100644--- a/packages/eve/src/execution/session/turn.ts+++ b/packages/eve/src/execution/session/turn.ts@@ -1,16 +1,38 @@-import { getWorkflowMetadata } from "#compiled/@workflow/core/index.js";+import { sleep } from "#compiled/@workflow/core/index.js";-import type { DeliverHookPayload, SessionCapabilities } from "#channel/types.js";+import type {+ DeliverHookPayload,+ SessionAuthContext,+ SessionCapabilities,+ TurnCaller,+} from "#channel/types.js";import { cancelDescendantTurnsStep } from "#execution/cancel-descendant-turns-step.js";import { dispatchCoordinationStep } from "#execution/coordination-dispatch-step.js";import { routeDeliverToChildren } from "#execution/route-child-delivery.js";import { routeSelectedDelivery } from "#execution/session/route-selected-delivery.js";-import { isSteeringMessage, type SessionInputQueue } from "#execution/session/input-queue.js";+import {+ isSteeringMessage,+ type SessionInputQueue,+ type SteeringTurn,+} from "#execution/session/input-queue.js";+import { AuthKey } from "#context/keys.js";+import { TASK_WAIT_TOOL_NAME, taskToolResult, type TaskToolCall } from "#execution/tasks/calls.js";+import { principalOf } from "#execution/session/principal.js";+import { renderTaskWaitResult } from "#execution/tasks/render.js";+import {+ answerTaskCancel,+ cancelWorkingTasks,+ isTaskRunMessage,+ sessionTaskTable,+} from "#execution/tasks/session.js";+import { applyTaskRunMessageStep } from "#execution/tasks/steps.js";+import { taskWaitResult } from "#execution/tasks/table.js";import {sessionCommandHookToken,sessionInboxHookToken,} from "#execution/session-inbox/address.js";import type { SessionInboxPayload, SessionInboxReader } from "#execution/session-inbox/inbox.js";+import { publishTurnWaitingStep } from "#execution/session/turn-waiting-step.js";import { admitSessionInboxPayload } from "#execution/session/admission.js";import type { SessionStateCursor } from "#execution/session/state-cursor.js";import { handleWorkflowToolRunMessage } from "#execution/session-workflow-tool-run.js";@@ -22,7 +44,7 @@ import type {TurnOutcome,TurnStepPayload,} from "#execution/session/turn-step-types.js";-import { resolveWorkflowCallbackBaseUrl } from "#execution/workflow-callback-url.js";+import { StepAgentStarts } from "#execution/session/step-agent-starts.js";import { turnStep } from "#execution/session/turn-step.js";import { activeTurnId } from "#harness/active-turn-id.js";import { coalesceDeliveries } from "#harness/messages.js";@@ -32,7 +54,6 @@ import {findBlockingWorkflowToolRun,isInboxToolResultFromRecordedWorkflowToolRun,} from "#harness/workflow-tool-runs.js";-import { isInboxSubagentResultFromRunningHandle } from "#subagents/handles/query.js";import { resolveRuntimeActionResultsForCallIds } from "#runtime/actions/results.js";import type { RuntimeActionResult } from "#shared/action-types.js";@@ -73,15 +94,40 @@ export class SessionExecution {return this.input.cursor;}- async runTurn(delivery: TurnStepPayload | undefined): Promise<TurnOutcome> {- const turn = new ActiveTurn(this.input, delivery?.delivery?.caller?.callId);+ async runTurn(+ delivery: TurnStepPayload | undefined,+ options: {+ /**+ * The delegated caller the turn answers. The session binds it before the+ * turn, including for a first turn whose input carries no caller.+ */+ readonly caller?: TurnCaller;+ } = {},+ ): Promise<TurnOutcome> {+ const turn = new ActiveTurn(this.input, {+ caller: options.caller,+ principal: resolveTurnPrincipal(delivery, this.input.cursor.serializedContext),+ });try {- return await this.runTurnSteps(turn, delivery);+ const outcome = await this.runTurnSteps(turn, delivery);+ // Tasks run beside the turn, so their runs' messages still reach the session.+ await this.handleAdmittedTaskEvents(turn);+ // The turn rule holds a turn while its tasks work, so a turn that ends+ // anyway, such as by failing, cancels them.+ if (outcome.kind === "park" && outcome.settled !== undefined) {+ await cancelWorkingTasks(this.input.cursor);+ }+ return turn.caller === undefined ? outcome : { ...outcome, caller: turn.caller };} finally {turn.dispose();}}+ /** Applies what task runs reported while the model step ran, so the next step sees it. */+ private async handleAdmittedTaskEvents(turn: ActiveTurn): Promise<void> {+ for (const message of turn.takeTaskMessages()) await this.handleWorkflowMessage(message);+ }+private async runTurnSteps(turn: ActiveTurn,delivery: TurnStepPayload | undefined,@@ -90,12 +136,14 @@ export class SessionExecution {while (true) {const { cursor } = this.input;- const result: DurableStepResult = await turnStep({- ...cursor.stepState(),- abortSignal: turn.signal,- input: nextStepInput,- steeringSignal: turn.steeringSignal,- });+ const result: DurableStepResult = await turn.agentStarts.publishWhile(+ turnStep({+ ...cursor.stepState(),+ abortSignal: turn.signal,+ input: nextStepInput,+ steeringSignal: turn.steeringSignal,+ }),+ );const pendingCallIds =result.action === "park" ? result.pendingCoordinationCallIds : undefined;const turnCompleted = result.action === "park" && result.settled !== undefined;@@ -106,6 +154,7 @@ export class SessionExecution {});await turn.admitBoundary();turn.resetSteering();+ await this.handleAdmittedTaskEvents(turn);if (result.action === "cancelled") return await this.finishCancelledTurn();if (!turnCompleted && turn.signal.aborted && pendingCallIds === undefined) {@@ -122,10 +171,17 @@ export class SessionExecution {};}+ if (result.action === "held") {+ const woke = await this.waitForHeldTurn(turn);+ if (woke === "cancelled") return await this.finishCancelledTurn();+ const steering = await turn.takeSteering();+ nextStepInput = steering === undefined ? undefined : { delivery: steering };+ continue;+ }+if (pendingCallIds !== undefined && result.action === "park") {const dispatchResult = await dispatchCoordinationStep({action: result.action,- callbackBaseUrl: resolveWorkflowCallbackBaseUrl(getWorkflowMetadata().url),workflowToolRunOwner: {inbox: sessionInboxHookToken(sessionCommandHookToken(this.input.sessionId)),},@@ -137,6 +193,7 @@ export class SessionExecution {const runtimeResults = await this.waitForRuntimeActionResults({initialAcceptedAtMs,initialResults: dispatchResult.results,+ taskToolCalls: result.pendingTaskToolCalls ?? [],pendingCallIds,turn,});@@ -170,25 +227,58 @@ export class SessionExecution {async handleWorkflowMessage(message: WorkflowToolRunMessage,): Promise<RuntimeActionResult | undefined> {+ if (isTaskRunMessage(message)) {+ const { cursor } = this.input;+ await cursor.apply(await applyTaskRunMessageStep({ ...cursor.stepState(), message }));+ return undefined;+ }return await handleWorkflowToolRunMessage({- callbackMetadataUrl: getWorkflowMetadata().url,cursor: this.input.cursor,message,});}+ /** `session.cancel()` stops the turn, the calls it waits on, and every working task. */private async finishCancelledTurn(): Promise<TurnOutcome> {const { cursor } = this.input;await cancelDescendantTurnsStep({- serializedContext: cursor.serializedContext,sessionState: cursor.sessionState,});+ await cancelWorkingTasks(cursor);return { cancelled: true, kind: "park" };}+ /**+ * The model tried to end the turn while its tasks work. The turn parks as+ * `task_wait` would, until one of them settles or the turn is steered.+ */+ private async waitForHeldTurn(turn: ActiveTurn): Promise<"cancelled" | "woke"> {+ let interrupted = false;+ while (true) {+ const wake = { interrupted, timedOut: false };+ if (taskWaitResult(sessionTaskTable(this.input.cursor), wake) !== undefined) {+ return "woke";+ }+ const next = await turn.nextRuntimeEvent([]);+ if (next === "cancelled") return next;+ switch (next.kind) {+ case "steering":+ interrupted = true;+ continue;+ case "workflow":+ await this.handleWorkflowMessage(next.message);+ continue;+ case "runtime-action-result":+ case "timeout":+ continue;+ }+ }+ }+private async waitForRuntimeActionResults(input: {readonly initialAcceptedAtMs: number | undefined;readonly initialResults: readonly RuntimeActionResult[];+ readonly taskToolCalls: readonly TaskToolCall[];readonly pendingCallIds: readonly string[];readonly turn: ActiveTurn;}): Promise<RuntimeActionResultStepInput | "cancelled"> {@@ -199,8 +289,14 @@ export class SessionExecution {for (const result of results)acceptedAtMsByCallId.set(result.callId, input.initialAcceptedAtMs);}+ const accept = (result: RuntimeActionResult): void => {+ results.push(result);+ acceptedAtMsByCallId.set(result.callId, Date.now());+ };+ let taskWaits = await this.answerTaskToolCalls(input.taskToolCalls, accept);while (true) {+ taskWaits = this.resolveTaskWaits(taskWaits, interrupted, accept);const ready = resolveRuntimeActionResultsForCallIds({pendingCallIds: input.pendingCallIds,results,@@ -214,8 +310,15 @@ export class SessionExecution {};}- const next = await input.turn.nextRuntimeEvent();+ const timers = taskWaits.flatMap((wait) => (wait.timer === undefined ? [] : [wait.timer]));+ const next = await input.turn.nextRuntimeEvent(timers);if (next === "cancelled") return next;+ if (next.kind === "timeout") {+ for (const wait of taskWaits) {+ if (wait.callId === next.callId) wait.timedOut = true;+ }+ continue;+ }if (next.kind === "steering") {// Only the first steering message interrupts; later ones wait for the calls anyway.if (!interrupted) await this.interruptWaitedWorkflowCalls(input.pendingCallIds, results);@@ -224,15 +327,11 @@ export class SessionExecution {}if (next.kind === "runtime-action-result") {const snapshot = this.input.cursor.sessionState.snapshot.session.state;- const accepted = next.results.filter((result) => {- if (result.kind === "tool-result") {- return isInboxToolResultFromRecordedWorkflowToolRun(snapshot, result);- }- if (result.kind !== "subagent-result") return false;- return (- result.origin === "child" && isInboxSubagentResultFromRunningHandle(snapshot, result)- );- });+ const accepted = next.results.filter(+ (result) =>+ result.kind === "tool-result" &&+ isInboxToolResultFromRecordedWorkflowToolRun(snapshot, result),+ );if (accepted.length > 0) {const acceptedAtMs = Date.now();results.push(...accepted);@@ -242,14 +341,58 @@ export class SessionExecution {}const result = await this.handleWorkflowMessage(next.message);- if (result !== undefined) {- results.push(result);- acceptedAtMsByCallId.set(result.callId, Date.now());+ if (result !== undefined) accept(result);+ }+ }++ /** Answers every `task_wait` that can return now; returns the ones still waiting. */+ private resolveTaskWaits(+ waits: readonly TaskWait[],+ interrupted: boolean,+ accept: (result: RuntimeActionResult) => void,+ ): TaskWait[] {+ const table = sessionTaskTable(this.input.cursor);+ const waiting: TaskWait[] = [];+ for (const wait of waits) {+ const result = taskWaitResult(table, {+ interrupted,+ timedOut: wait.timedOut,+ });+ if (result === undefined) {+ waiting.push(wait);+ continue;}+ const text = renderTaskWaitResult(result, Date.now() - wait.startedAtMs);+ accept(taskToolResult(wait.callId, TASK_WAIT_TOOL_NAME, text));}+ return waiting;}- /** Fires the `interruptSignal` of every workflow tool call the wait has no result for yet. */+ /**+ * `task_cancel` is answered at once, and so is each `task_wait` that can+ * return now: a timeout of 0, a result already waiting, or nothing working.+ * Any other `task_wait` parks the open turn, reported once as+ * `turn.waiting`, and the turn resolves it alongside the step's other+ * deferred calls.+ */+ private async answerTaskToolCalls(+ calls: readonly TaskToolCall[],+ accept: (result: RuntimeActionResult) => void,+ ): Promise<TaskWait[]> {+ const waits: TaskWait[] = [];+ for (const call of calls) {+ if (call.kind === "task_wait") waits.push(startTaskWait(call));+ else accept(await answerTaskCancel(this.input.cursor, call));+ }+ const parked = this.resolveTaskWaits(waits, false, accept);+ if (parked.length > 0) {+ const { cursor } = this.input;+ await cursor.apply(await publishTurnWaitingStep(cursor.stepState()));+ }+ return parked;+ }++ /** Aborts the `abortSignal` of every workflow tool call the wait has no result for yet. */private async interruptWaitedWorkflowCalls(pendingCallIds: readonly string[],settled: readonly RuntimeActionResult[],@@ -265,13 +408,48 @@ export class SessionExecution {}}+/**+ * One `task_wait` call the turn is parked on. Its timeout is a durable sleep+ * the turn races against the inbox; nothing polls.+ */+interface TaskWait {+ readonly callId: string;+ readonly startedAtMs: number;+ /** Resolves with the call's id once the timeout passes; absent without a timeout. */+ readonly timer?: Promise<string>;+ /** A timeout of 0 has passed already: the wait returns whatever is ready. */+ timedOut: boolean;+}++function startTaskWait(call: Extract<TaskToolCall, { readonly kind: "task_wait" }>): TaskWait {+ const { callId, timeoutMs } = call;+ const timer =+ timeoutMs !== undefined && timeoutMs > 0 ? sleep(timeoutMs).then(() => callId) : undefined;+ return { callId, startedAtMs: Date.now(), timedOut: timeoutMs === 0, timer };+}+type RuntimeEvent =| { readonly kind: "runtime-action-result"; readonly results: readonly RuntimeActionResult[] }| { readonly kind: "workflow"; readonly message: WorkflowToolRunMessage }/** A steering message that answered no pending request arrived during the wait. */| { readonly kind: "steering" }+ /** A `task_wait` call's timeout passed. */+ | { readonly kind: "timeout"; readonly callId: string }| "cancelled";+/**+ * The principal of the delivery that starts or continues a turn. A delivery+ * without auth keeps the session's current identity, as the turn step does.+ */+function resolveTurnPrincipal(+ payload: TurnStepPayload | undefined,+ serializedContext: Record<string, unknown>,+): string {+ const auth = payload?.delivery?.auth;+ if (auth !== undefined) return principalOf(auth);+ return principalOf(serializedContext[AuthKey.name] as SessionAuthContext | null | undefined);+}+/*** Admission policy, cancellation, and steering for one active turn.* Deliveries admitted while a model step runs stay in the shared queue until@@ -289,19 +467,28 @@ class ActiveTurn {private readonly controller = new AbortController();private readonly expectedTurnId: string;private readonly input: SessionExecutionInput;- private readonly callerCallId: string | undefined;+ /** Who alone steers the turn: its principal, or its delegated caller. */+ private readonly identity: SteeringTurn;private readonly unsubscribe: () => void;private unsubscribeDelivery: () => void;+ readonly agentStarts: StepAgentStarts;private steeringController = new AbortController();+ /** The delegated caller of the latest message the turn read. */+ caller: TurnCaller | undefined;- constructor(input: SessionExecutionInput, callerCallId: string | undefined) {+ constructor(+ input: SessionExecutionInput,+ owner: { readonly caller: TurnCaller | undefined; readonly principal: string },+ ) {this.input = input;- this.callerCallId = callerCallId;+ this.caller = owner.caller;+ this.identity = { callerCallId: owner.caller?.callId, principal: owner.principal };this.expectedTurnId = activeTurnId(input.cursor.sessionState.emissionState);this.unsubscribe = input.inbox.onInterrupt((payload) => {if (this.cancelsThisTurn(payload)) this.abort();});this.unsubscribeDelivery = input.inbox.onDelivery(this.signalSteering);+ this.agentStarts = new StepAgentStarts(input.inbox, input.cursor);}private readonly signalSteering = (payload: SessionInboxPayload): void => {@@ -313,7 +500,7 @@ class ActiveTurn {}if (delivery.kind === "deliver" &&- isSteeringMessage(delivery, this.callerCallId) &&+ isSteeringMessage(delivery, this.identity) &&!this.input.cursor.sessionState.hasProxyInputRequests)this.steeringController.abort();@@ -351,7 +538,7 @@ class ActiveTurn {async takeSteering(): Promise<DeliverHookPayload | undefined> {const steering: DeliverHookPayload[] = [];while (true) {- const selection = this.input.queue.takeSteering(this.admitted, this.callerCallId);+ const selection = this.input.queue.takeSteering(this.admitted, this.identity);if (selection === undefined) break;for (const sequence of selection.sequences) this.admitted.delete(sequence);const routed = await routeSelectedDelivery(selection, this.input.cursor);@@ -362,21 +549,39 @@ class ActiveTurn {if (routed.kind === "turn") steering.push(routed.delivery);}if (steering.length === 0) return undefined;- return steering.length === 1 ? steering[0] : coalesceDeliveries(steering);+ const delivery = steering.length === 1 ? steering[0]! : coalesceDeliveries(steering);+ if (delivery.caller !== undefined) this.caller = delivery.caller;+ return delivery;+ }++ /** Removes the admitted task run messages, which the session applies to the task table at once. */+ takeTaskMessages(): WorkflowToolRunMessage[] {+ const taken: WorkflowToolRunMessage[] = [];+ const kept: RuntimeEvent[] = [];+ for (const event of this.runtimeResults) {+ const message = asTaskMessage(event);+ if (message === undefined) kept.push(event);+ else taken.push(message);+ }+ this.runtimeResults.splice(0, this.runtimeResults.length, ...kept);+ return taken;}/**- * Next runtime result, workflow message, or steering, admitting inbox traffic- * while waiting. Deliveries admitted before the wait began are routed first,- * so a message that arrived as the calls started still steers.+ * Next runtime result, workflow message, steering, or timeout, admitting+ * inbox traffic while waiting. Deliveries admitted before the wait began are+ * routed first, so a message that arrived as the calls started still steers.+ * `timers` are durable sleeps raced against the inbox.*/- async nextRuntimeEvent(): Promise<RuntimeEvent> {+ async nextRuntimeEvent(timers: readonly Promise<string>[]): Promise<RuntimeEvent> {while (true) {const steered = await this.routeAdmittedToChildren();if (this.signal.aborted) return "cancelled";if (steered) return { kind: "steering" };const event = this.runtimeResults.shift();if (event !== undefined) return event;+ const elapsed = await this.waitForInboxOrTimer(timers);+ if (elapsed !== undefined) return { callId: elapsed, kind: "timeout" };const payload = await this.input.inbox.next();if (payload === undefined)throw new Error("Session inbox closed before runtime actions completed.");@@ -384,6 +589,15 @@ class ActiveTurn {}}+ /** Resolves with the id of the call whose timer won, or `undefined` once inbox input is ready. */+ private async waitForInboxOrTimer(+ timers: readonly Promise<string>[],+ ): Promise<string | undefined> {+ if (timers.length === 0 || this.input.inbox.hasPending()) return undefined;+ const inboxReady = this.input.inbox.whenPending().then(() => undefined);+ return await Promise.race([inboxReady, ...timers]);+ }+private cancelsThisTurn(payload: SessionInboxPayload): boolean {if (payload.kind === "reset") return true;if (payload.kind !== "cancel") return false;@@ -391,6 +605,7 @@ class ActiveTurn {}private async admit(value: SessionInboxPayload): Promise<void> {+ if (this.agentStarts.consume(value)) return;const admitted = await admitSessionInboxPayload(value, this.input);switch (admitted.kind) {case "delivery":@@ -444,7 +659,7 @@ class ActiveTurn {this.admitted.delete(sequence);continue;}- if (isSteeringMessage(routed.remainder, this.callerCallId)) steered = true;+ if (isSteeringMessage(routed.remainder, this.identity)) steered = true;}return steered;}@@ -454,3 +669,11 @@ class ActiveTurn {this.controller.abort(new TurnCancelledError());}}++function asTaskMessage(event: RuntimeEvent): WorkflowToolRunMessage | undefined {+ if (event === "cancelled") return undefined;+ // Tasks run beside the turn, so everything their runs send, such as a+ // question, reaches the session at the next boundary rather than at turn end.+ if (event.kind === "workflow" && event.message.from.taskId !== undefined) return event.message;+ return undefined;+}diff --git a/packages/eve/src/execution/settle-cancelled-turn-step.integration.test.ts b/packages/eve/src/execution/settle-cancelled-turn-step.integration.test.tsdeleted file mode 100644index 66fdcba85..000000000--- a/packages/eve/src/execution/settle-cancelled-turn-step.integration.test.ts+++ /dev/null@@ -1,190 +0,0 @@-import { describe, expect, it, vi } from "vitest";--import { createTestRuntime } from "#internal/testing/app-harness.js";-import { createBundledRuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";-import { createDurableSessionState } from "#execution/durable-session-store.js";-import { settleCancelledTurnStep } from "#execution/settle-cancelled-turn-step.js";-import { setHarnessEmissionState } from "#harness/emission.js";-import { registerWorkflowToolRun } from "#harness/workflow-tool-runs.js";-import { deriveAgentOperationId } from "#subagents/handles/operation-id.js";-import {- AGENT_HANDLES_STATE_KEY,- deriveAgentId,- getAgentHandleStore,- type AgentHandle,-} from "#subagents/handles/store.js";-import type { HarnessSession } from "#harness/types.js";--const bindSessionInstrumentationSpy = vi.hoisted(() => vi.fn());-vi.mock("#instrumentation/runtime.js", async (importOriginal) => {- const actual = await importOriginal<typeof import("#instrumentation/runtime.js")>();- return {- ...actual,- bindSessionInstrumentation(input: Parameters<typeof actual.bindSessionInstrumentation>[0]) {- bindSessionInstrumentationSpy(input);- return actual.bindSessionInstrumentation(input);- },- };-});--/**- * The cancellation epilogue is the last write that can move a cancelled- * child's handle: `cancelDescendantTurnsStep` only requests cancellation,- * and the turn inbox a child settlement would resume is torn down with the- * cancelled turn. These tests pin the persisted handle store the epilogue- * leaves behind — a `running` handle surviving here would be permanent.- */--const PARENT_SESSION_ID = "parent-session-cancel-handles";-const CONTINUATION_TOKEN = "http:settle-cancel-handles";--const RUNNING_OPERATION_ID = deriveAgentOperationId({- callId: "call-1",- parentSessionId: PARENT_SESSION_ID,- parentTurnId: "turn-1",-});--const RUNNING_HANDLE: AgentHandle = {- address: {- continuationToken: "subagent:child-running",- kind: "agent/local",- sessionId: "child-session-running",- },- identity: {- id: deriveAgentId("research", RUNNING_OPERATION_ID),- name: "research",- nodeId: "subagents/research",- },- operation: {- callId: "call-1",- id: RUNNING_OPERATION_ID,- kind: "start",- parentTurnId: "turn-1",- },- phase: "running",-};--const PARKED_OPERATION_ID = deriveAgentOperationId({- callId: "call-0",- parentSessionId: PARENT_SESSION_ID,- parentTurnId: "turn-0",-});--const PARKED_HANDLE: AgentHandle = {- address: {- continuationToken: "subagent:child-parked",- kind: "agent/local",- sessionId: "child-session-parked",- },- identity: {- id: deriveAgentId("writer", PARKED_OPERATION_ID),- name: "writer",- nodeId: "subagents/writer",- },- lastStatus: "draft ready",- phase: "parked",-};--const CLAIMED_HANDLE: AgentHandle = {- address: {- continuationToken: "subagent:child-claimed",- kind: "agent/local",- sessionId: "child-session-claimed",- },- callId: "workflow-call",- identity: {- id: "ag_research:workflow",- name: "research",- nodeId: "subagents/research",- },- operationId: "workflow-operation",- ownerId: "workflow-run",- phase: "claimed",-};--function createCancelledTurnSession(handles: readonly AgentHandle[]): HarnessSession {- return setHarnessEmissionState(- {- agent: { modelReference: { id: "openai/gpt-5.4" }, system: "", tools: [] },- compaction: { recentWindowSize: 10, threshold: 100_000 },- continuationToken: CONTINUATION_TOKEN,- history: [],- outputSchema: { type: "object" },- sessionId: PARENT_SESSION_ID,- state: { [AGENT_HANDLES_STATE_KEY]: { handles } },- },- { sequence: 3, sessionStarted: true, stepIndex: 1, turnId: "turn-1" },- );-}--function buildSerializedContext(): Record<string, unknown> {- return {- "eve.auth": null,- "eve.bundle": { source: createBundledRuntimeCompiledArtifactsSource() },- "eve.channel": { kind: "http", state: {} },- "eve.continuationToken": CONTINUATION_TOKEN,- "eve.sessionId": PARENT_SESSION_ID,- };-}--describe("settleCancelledTurnStep handle store", () => {- it("parks abandoned running handles as cancelled and keeps parked ones", async () => {- bindSessionInstrumentationSpy.mockClear();- const runtime = await createTestRuntime({ agent: { name: "settle-cancel-handles" } });-- await runtime.run(async () => {- const result = await settleCancelledTurnStep({- sessionWritable: new WritableStream<Uint8Array>({ write() {} }),- serializedContext: buildSerializedContext(),- sessionState: createDurableSessionState({- session: createCancelledTurnSession([RUNNING_HANDLE, PARKED_HANDLE]),- }),- });-- expect(getAgentHandleStore(result.sessionState.snapshot.session.state)).toEqual({- handles: [- {- address: RUNNING_HANDLE.address,- identity: RUNNING_HANDLE.identity,- lastStatus: "(cancelled)",- phase: "parked",- },- PARKED_HANDLE,- ],- });- expect(result.sessionState.snapshot.session.outputSchema).toBeUndefined();- expect(bindSessionInstrumentationSpy).toHaveBeenCalledWith(- expect.objectContaining({ agentName: "settle-cancel-handles" }),- );- });- });-- it("releases a cancelled workflow claim with a resumable cancelled status", async () => {- const runtime = await createTestRuntime({ agent: { name: "settle-cancel-claim" } });-- await runtime.run(async () => {- const session = registerWorkflowToolRun(createCancelledTurnSession([CLAIMED_HANDLE]), {- callId: "workflow-call",- toolName: "Workflow",- origin: { turnId: "turn-1", stepIndex: 0 },- address: { runId: "workflow-run", hookToken: "workflow-hook" },- });- const result = await settleCancelledTurnStep({- sessionWritable: new WritableStream<Uint8Array>({ write() {} }),- serializedContext: buildSerializedContext(),- sessionState: createDurableSessionState({ session }),- });-- expect(getAgentHandleStore(result.sessionState.snapshot.session.state)).toEqual({- handles: [- {- address: CLAIMED_HANDLE.address,- identity: CLAIMED_HANDLE.identity,- lastStatus: "(cancelled)",- phase: "parked",- },- ],- });- });- });-});diff --git a/packages/eve/src/execution/settle-cancelled-turn-step.ts b/packages/eve/src/execution/settle-cancelled-turn-step.tsindex cfe9a34c8..10f3ff9fb 100644--- a/packages/eve/src/execution/settle-cancelled-turn-step.ts+++ b/packages/eve/src/execution/settle-cancelled-turn-step.ts@@ -1,4 +1,7 @@-import { getPendingCoordinationBatch } from "#harness/coordination.js";+import {+ commitCancelledCoordinationBatch,+ getPendingCoordinationBatch,+} from "#harness/coordination.js";import { deserializeContext, serializeContext } from "#context/serialize.js";import {createDurableSessionState,@@ -11,15 +14,7 @@ import { emitCancelledTurn } from "#harness/cancelled-turn-emission.js";import { clearPendingSessionLimitPrompt } from "#harness/input-requests.js";import { getHarnessEmissionState, setHarnessEmissionState } from "#harness/emission.js";import { clearAllProxyInputRequests } from "#harness/proxy-input-requests.js";-import {- abandonAgentInvocationOwners,- abandonRunningAgentTurns,-} from "#subagents/handles/transitions.js";-import { clearPendingCoordinationBatch } from "#harness/coordination.js";-import {- removeBlockingWorkflowToolRuns,- getBlockingWorkflowToolRuns,-} from "#harness/workflow-tool-runs.js";+import { removeBlockingWorkflowToolRuns } from "#harness/workflow-tool-runs.js";import { getTurnUsageState, toUsage } from "#harness/turn-tag-state.js";import type { TokenUsage } from "#shared/token-usage.js";@@ -52,7 +47,7 @@ export async function settleCancelledTurnStep(input: {}),);const emissionState = emitted.result;- let session = emitted.session;+ const session = emitted.session;// `clearPendingSessionLimitPrompt`: cancellation settles with the step's// input snapshot, which can resurrect an already-answered session-limit@@ -60,29 +55,16 @@ export async function settleCancelledTurnStep(input: {// discarded turn state). The pre-model gate re-raises the prompt while the// violation holds, so the next delivery gets a fresh prompt instead of// queueing forever behind a stale one.- //- // Descendant cancellation already ran and the cancelled turn's inbox is- // gone, so a child settlement can never reach this store again. This is the- // last write that can park turn-owned `running` and workflow-owned `claimed`- // handles.const owningTurnId =getPendingCoordinationBatch(session.state)?.event.turnId ??input.sessionState.emissionState.turnId;- const workflowToolRuns = getBlockingWorkflowToolRuns(session.state, owningTurnId);- session = abandonAgentInvocationOwners(- session,- new Set(workflowToolRuns.map((run) => run.address.runId)),- );const cancelledSession = reconcileSessionContinuationToken(ctx,setHarnessEmissionState(clearPendingSessionLimitPrompt(clearAllProxyInputRequests(- clearPendingCoordinationBatch(- removeBlockingWorkflowToolRuns(- abandonRunningAgentTurns({ ...session, outputSchema: undefined }),- owningTurnId,- ),+ commitCancelledCoordinationBatch(+ removeBlockingWorkflowToolRuns({ ...session, outputSchema: undefined }, owningTurnId),),),),diff --git a/packages/eve/src/execution/tasks/calls.ts b/packages/eve/src/execution/tasks/calls.tsnew file mode 100644index 000000000..ff81d84f2--- /dev/null+++ b/packages/eve/src/execution/tasks/calls.ts@@ -0,0 +1,78 @@+import type { ModelMessage } from "ai";++import type { RuntimeToolResultActionResult } from "#shared/action-types.js";+import type { JsonValue } from "#shared/json.js";++/**+ * Calls to the task tools. They defer out of the model step like+ * workflow tool calls; the session answers them instead of a workflow run.+ */+export type TaskToolCall =+ | { readonly callId: string; readonly kind: "task_wait"; readonly timeoutMs?: number }+ | { readonly callId: string; readonly kind: "task_cancel"; readonly taskId: string };++export const TASK_WAIT_TOOL_NAME = "task_wait";+export const TASK_CANCEL_TOOL_NAME = "task_cancel";++/** The task tools' names; authored tools cannot use them. */+export const TASK_TOOL_NAMES: readonly string[] = [TASK_WAIT_TOOL_NAME, TASK_CANCEL_TOOL_NAME];++/**+ * The task tool calls a parked step's response still waits on. The response+ * is the one record of these calls: a call without a result is pending, and+ * a call with invalid input already carries its error result. The names are+ * reserved, so no authored tool's call matches.+ */+export function pendingTaskToolCalls(messages: readonly ModelMessage[]): TaskToolCall[] {+ const answered = new Set<string>();+ for (const message of messages) {+ if (typeof message.content === "string") continue;+ for (const part of message.content) {+ if (part.type === "tool-result") answered.add(part.toolCallId);+ }+ }+ const calls: TaskToolCall[] = [];+ for (const message of messages) {+ if (message.role !== "assistant" || typeof message.content === "string") continue;+ for (const part of message.content) {+ if (part.type !== "tool-call" || answered.has(part.toolCallId)) continue;+ const input = typeof part.input === "object" && part.input !== null ? part.input : {};+ if (part.toolName === TASK_CANCEL_TOOL_NAME) {+ const taskId = String(Reflect.get(input, "taskId"));+ calls.push({ callId: part.toolCallId, kind: "task_cancel", taskId });+ } else if (part.toolName === TASK_WAIT_TOOL_NAME) {+ const timeout: unknown = Reflect.get(input, "timeout");+ calls.push(+ typeof timeout === "number"+ ? { callId: part.toolCallId, kind: "task_wait", timeoutMs: timeout }+ : { callId: part.toolCallId, kind: "task_wait" },+ );+ }+ }+ }+ return calls;+}++/** Why a `task_wait` call, or a held turn, stopped waiting. */+export type TaskWaitResult =+ | {+ readonly status: "settled";+ /** Tasks whose results follow; both lists are empty when nothing was working. */+ readonly settled: readonly {+ readonly id: string;+ readonly status: "completed" | "failed";+ }[];+ readonly working: readonly string[];+ }+ | { readonly status: "timeout" | "interrupt"; readonly working: readonly string[] };++export type TaskCancelResult = { readonly status: "cancelled" | "already_finished" };++// Built directly: the workflow body can't import the harness's result helpers.+export function taskToolResult(+ callId: string,+ toolName: string,+ output: JsonValue,+): RuntimeToolResultActionResult {+ return { callId, kind: "tool-result", output, toolName };+}diff --git a/packages/eve/src/execution/tasks/model-step.ts b/packages/eve/src/execution/tasks/model-step.tsnew file mode 100644index 000000000..7fda6faaf--- /dev/null+++ b/packages/eve/src/execution/tasks/model-step.ts@@ -0,0 +1,228 @@+import type { ModelMessage, SystemModelMessage } from "ai";++import { TASK_CANCEL_TOOL_NAME, TASK_WAIT_TOOL_NAME } from "#execution/tasks/calls.js";+import {+ renderModelOutputText,+ renderTaskResults,+ renderTasksNote,+ TASK_SYSTEM_BLOCK,+ TASKS_NOTE_LABEL,+ type ListedTask,+ type TaskResultBlock,+} from "#execution/tasks/render.js";+import {+ createTask,+ idleTasks,+ readTaskTable,+ takeTaskResults,+ workingTasks,+ writeTaskTable,+ type TaskRecord,+ type TaskResult,+} from "#execution/tasks/table.js";+import { splitTaskIdInput } from "#execution/tasks/task-id-input.js";+import { entryPointOf, isAgentTool, startsTasks } from "#execution/tasks/tool-entry-point.js";+import type { HarnessToolDefinition } from "#harness/execute-tool.js";+import { createFrameworkUserMessage, type HarnessModelMessage } from "#harness/messages.js";+import type { HarnessSession, HarnessToolMap } from "#harness/types.js";+import type { WorkflowToolCallEntry } from "#shared/action-types.js";+import type { JsonObject } from "#shared/json.js";+import { taskCancelTool } from "#tools/provided/task-cancel.js";+import { taskWaitTool } from "#tools/provided/task-wait.js";++// What the model step does for tasks: it offers the task tools, commits a+// record for each call that starts a task, delivers settled results, keeps the+// `[Tasks]` note current, and tells the turn rule which tasks still work.++export function isTaskTool(definition: HarnessToolDefinition | undefined): boolean {+ return (+ definition?.frameworkAction === "task-wait" || definition?.frameworkAction === "task-cancel"+ );+}++/** Whether the agent can start tasks, so the task tools and system block are offered. */+export function offersTasks(tools: HarnessToolMap): boolean {+ for (const definition of tools.values()) {+ if (startsTasks(definition)) return true;+ }+ return false;+}++/** Adds `task_wait` and `task_cancel` to a tool set that can start tasks. */+export function withTaskTools(tools: HarnessToolMap): HarnessToolMap {+ if (!offersTasks(tools)) return tools;+ return new Map([+ ...tools,+ [TASK_WAIT_TOOL_NAME, taskWaitTool],+ [TASK_CANCEL_TOOL_NAME, taskCancelTool],+ ]);+}++export function taskSystemMessages(tools: HarnessToolMap): SystemModelMessage[] {+ return offersTasks(tools) ? [{ content: TASK_SYSTEM_BLOCK, role: "system" }] : [];+}++/** A deferred call as the model made it, before the session knows what it enters. */+export interface DeferredCall {+ readonly callId: string;+ readonly definition: HarnessToolDefinition | undefined;+ /** The call's model input. */+ readonly input: JsonObject;+ readonly toolName: string;+ readonly turnId: string;+}++/** How a deferred call enters its workflow, with the tool's own input. */+export interface CommittedCallEntry {+ readonly entry: WorkflowToolCallEntry;+ readonly input: JsonObject;+ readonly session: HarnessSession;+}++/**+ * How a deferred call enters its workflow. A call that starts a task commits+ * the task's record alongside the call, so the run starts with its id; a+ * `serve` tool's call with `taskId` goes to that task's `receive()`, which the+ * session checks when it sends the call.+ */+export function commitCallEntry(session: HarnessSession, call: DeferredCall): CommittedCallEntry {+ const entryPoint = entryPointOf(call.definition);+ switch (entryPoint) {+ case "execute":+ return { entry: { entryPoint }, input: call.input, session };+ case "task":+ return commitTask(session, call, entryPoint, call.input);+ case "serve": {+ const { input, taskId } = splitTaskIdInput(call.input);+ if (taskId === undefined) return commitTask(session, call, entryPoint, input);+ return { entry: { entryPoint: "receive", taskId }, input, session };+ }+ }+}++function commitTask(+ session: HarnessSession,+ call: DeferredCall,+ entryPoint: "task" | "serve",+ input: JsonObject,+): CommittedCallEntry {+ const created = createTask(readTaskTable(session.state), {+ callId: call.callId,+ kind: isAgentTool(call.definition) ? "agent" : "tool",+ name: call.toolName,+ resumable: entryPoint === "serve",+ turnId: call.turnId,+ });+ return {+ entry: { entryPoint, taskId: created.taskId },+ input,+ session: writeTaskTable(session, created.table),+ };+}++export function workingTaskIds(session: HarnessSession): readonly string[] {+ return workingTasks(readTaskTable(session.state)).map((record) => record.id);+}++/**+ * The messages a model step appends for tasks, before any new input: one+ * `task.result` message with every settled result, then the+ * `[Tasks]` note when the listing changed. The results are marked delivered+ * in the same step. The message lives only in the model's history: clients+ * read outcomes from `task.settled`.+ */+export async function appendTaskContext(input: {+ readonly messages: readonly HarnessModelMessage[];+ readonly projectHistory: (+ messages: readonly ModelMessage[],+ state: HarnessSession["state"],+ ) => readonly ModelMessage[];+ readonly session: HarnessSession;+ readonly tools: HarnessToolMap;+}): Promise<{+ readonly messages: readonly HarnessModelMessage[];+ readonly session: HarnessSession;+}> {+ const appended: HarnessModelMessage[] = [];+ const delivery = await deliverTaskResults(input);+ if (delivery.message !== undefined) {+ appended.push(createFrameworkUserMessage("task.result", delivery.message));+ }+ const note = resolveTasksNote({+ messages: input.projectHistory([...input.messages, ...appended], delivery.session.state),+ session: delivery.session,+ });+ if (note !== undefined) appended.push(createFrameworkUserMessage("context.state", note));+ return { messages: appended, session: delivery.session };+}++/**+ * Takes every settled result for one `task.result` message and+ * marks them delivered in the same step that appends the message.+ */+async function deliverTaskResults(input: {+ readonly session: HarnessSession;+ readonly tools: HarnessToolMap;+}): Promise<{ readonly message?: string; readonly session: HarnessSession }> {+ const { table, taken } = takeTaskResults(readTaskTable(input.session.state));+ if (taken.length === 0) return { session: input.session };+ const blocks: TaskResultBlock[] = [];+ for (const record of taken) {+ for (const result of record.results) {+ blocks.push(await toResultBlock(record, result, input.tools.get(record.name)));+ }+ }+ return { message: renderTaskResults(blocks), session: writeTaskTable(input.session, table) };+}++async function toResultBlock(+ record: TaskRecord,+ result: TaskResult,+ definition: HarnessToolDefinition | undefined,+): Promise<TaskResultBlock> {+ const base = { taskId: record.id, tool: record.name };+ if (result.status === "failed") return { ...base, body: result.error, status: "failed" };+ return { ...base, body: await projectOutput(result.output, definition), status: "completed" };+}++async function projectOutput(+ output: unknown,+ definition: HarnessToolDefinition | undefined,+): Promise<string> {+ if (definition?.toModelOutput === undefined) return renderModelOutputText(output);+ try {+ return renderModelOutputText(await definition.toModelOutput(output));+ } catch {+ // A projection that throws must not wedge every later model step.+ return renderModelOutputText(output);+ }+}++/**+ * The `[Tasks]` note to append when the listing differs from the+ * latest one in history. Compaction drops old notes, so the listing returns.+ */+function resolveTasksNote(input: {+ readonly messages: readonly ModelMessage[];+ readonly session: HarnessSession;+}): string | undefined {+ const table = readTaskTable(input.session.state);+ const working = workingTasks(table).map(toListedTask);+ const idle = idleTasks(table).map(toListedTask);+ const latest = input.messages.findLast(isTasksNote);+ if (latest === undefined && working.length === 0 && idle.length === 0) return undefined;+ const rendered = renderTasksNote({ idle, working });+ return latest?.content === rendered ? undefined : rendered;+}++function toListedTask(record: TaskRecord): ListedTask {+ return { id: record.id, tool: record.name };+}++function isTasksNote(message: ModelMessage): boolean {+ return (+ message.role === "user" &&+ typeof message.content === "string" &&+ message.content.startsWith(TASKS_NOTE_LABEL)+ );+}diff --git a/packages/eve/src/execution/tasks/render.ts b/packages/eve/src/execution/tasks/render.tsnew file mode 100644index 000000000..a959707b9--- /dev/null+++ b/packages/eve/src/execution/tasks/render.ts@@ -0,0 +1,271 @@+import type { TaskWaitResult } from "#execution/tasks/calls.js";++// Every string the model reads about tasks lives in this file.++export const TASK_WAIT_DESCRIPTION =+ "Wait until one of your tasks has a result, a new message arrives, or timeout (in milliseconds) passes. Results arrive in a <task_result> message right after this call returns. Waiting never stops a task. Omit timeout to wait until a result or a message arrives; a timeout of 0 returns at once with any results that are ready.";++export const TASK_WAIT_TIMEOUT_DESCRIPTION = "How long to wait, in milliseconds.";++export const TASK_CANCEL_DESCRIPTION =+ "Stop a task's current work. That work never reports back; if it already had a result, that result is still delivered. An agent, or any task that accepts more input, stays available: call its tool with its taskId to give it new work.";++export const TASK_CANCEL_TASK_ID_DESCRIPTION = "The id of the task to stop.";++export const TASK_SYSTEM_BLOCK =+ "Every subagent call and some tools start a task and return its id right away; the task keeps working while you continue. Results arrive in <task_result> messages. When you need a result to continue, call task_wait; it returns when any task has a result. Start independent tasks first, then wait. To correct or continue an agent, or any task that accepts more input, call its tool again with its taskId. If you don't need a task's result yet, reply now instead of calling task_wait: your turn stays open while your tasks work, and eve gives you their results when they finish. A new message never stops your tasks: answer it if it asks you something, decide whether it changes the work, then keep the tasks, correct an agent with taskId, or stop a task with task_cancel. Never use sleep to wait for a task.";++/** Appended to a `serve` tool's description. */+export const SERVE_TOOL_DESCRIPTION =+ "To send this task more input, call this tool again with its taskId; without taskId, each call starts a new task.";++/** Appended to an agent tool's description, in place of the `serve` tool sentence. */+export const AGENT_SERVE_TOOL_DESCRIPTION =+ "It does not see this conversation, so put everything it needs in message. To correct or continue an agent task, call this tool again with its taskId; without taskId, each call starts a new agent.";++/** Describes the `taskId` eve adds to a `serve` tool's model input. */+export const TASK_ID_INPUT_DESCRIPTION =+ "The id of a task this tool started, to send it this input. Omit it to start a new task.";++/** Labels the `context.state` note that lists the turn's tasks. */+export const TASKS_NOTE_LABEL = "[Tasks]";++/** Opens every block of a `task.result` message. */+export const TASK_RESULT_TAG = "<task_result";++/** The failure a task reports when its record could not be decoded. */+export const UNREADABLE_TASK_ERROR = "The task's state could not be read.";++const TASK_RESULTS_MAX_BYTES = 50 * 1024;+const TASK_RESULTS_MAX_LINES = 2_000;+const TRUNCATED_MARKER = "[truncated]";++/** The receipt for a call that starts a task; a resumable task's says how to reach it again. */+export function renderTaskReceipt(task: {+ readonly id: string;+ readonly resumable: boolean;+ readonly tool: string;+}): string {+ if (!task.resumable) return `Started task ${task.id}.`;+ return `Started task ${task.id}. Call ${task.tool} again with taskId ${task.id} to send it another message.`;+}++/** The receipt for a call that reaches a resumable task by its `taskId`. */+export function renderTaskSentReceipt(taskId: string): string {+ return `Sent to task ${taskId}.`;+}++export function renderUnknownTaskError(taskId: string, tool: string): string {+ return `No task "${taskId}" is available to ${tool}: it may have ended or belong to another tool. Start a new one by calling ${tool} without taskId.`;+}++export function renderTooManyTasksError(max: number, workingIds: readonly string[]): string {+ return `${String(max)} tasks are already working (${workingIds.join(", ")}). Wait with task_wait or stop one with task_cancel, then try again.`;+}++export function renderFinalOutputWhileWorkingError(workingIds: readonly string[]): string {+ return `You can't give your final output while tasks you started are working (${workingIds.join(", ")}). Wait for their results with task_wait, or stop a task with task_cancel, then call final_output.`;+}++/** What the model reads when `task_wait` returns after waiting `waitedMs`. */+export function renderTaskWaitResult(result: TaskWaitResult, waitedMs: number): string {+ switch (result.status) {+ case "settled":+ return renderSettledWait(result.settled, result.working);+ case "timeout":+ return `Stopped waiting after ${formatDuration(waitedMs)}; ${countWorking(result.working)}. ${resultsArriveLater(result.working.length)}`;+ case "interrupt":+ return `A new message arrived, so the wait ended after ${formatDuration(waitedMs)}; ${countWorking(result.working)}. Read the message, answer it if it asks you something, and decide whether it changes this work: ${interruptChoices(result.working.length)}`;+ }+}++function renderSettledWait(+ settled: Extract<TaskWaitResult, { readonly status: "settled" }>["settled"],+ working: readonly string[],+): string {+ if (settled.length === 0 && working.length === 0) return "No tasks are working.";+ const sentences: string[] = [];+ if (settled.length > 0) {+ const outcomes = settled.map((task) => `${task.id} ${task.status}`);+ const follows = settled.length === 1 ? "its result follows" : "their results follow";+ sentences.push(`${joinList(outcomes)}; ${follows}.`);+ }+ if (working.length > 0) {+ sentences.push(`${capitalize(countWorking(working))}: ${working.join(", ")}.`);+ }+ return sentences.join(" ");+}++function countWorking(working: readonly string[]): string {+ return working.length === 1+ ? "1 task is still working"+ : `${String(working.length)} tasks are still working`;+}++function resultsArriveLater(workingCount: number): string {+ return workingCount === 1+ ? "Its result arrives before your turn ends; wait again only if you need it now."+ : "Their results arrive before your turn ends; wait again only if you need them now.";+}++function interruptChoices(workingCount: number): string {+ const keep = workingCount === 1 ? "keep the task" : "keep the tasks";+ return `${keep}, call an agent again with its taskId to correct it, or stop a task with task_cancel.`;+}++/** One `<task_result>` block of a `task.result` message. */+export interface TaskResultBlock {+ readonly body: string;+ readonly status: "completed" | "failed";+ readonly taskId: string;+ readonly tool: string;+}++/**+ * The `task.result` message: one `<task_result>` block per result. All+ * bodies share one size budget; a body past it is cut and marked.+ */+export function renderTaskResults(results: readonly TaskResultBlock[]): string {+ const budget = { bytes: TASK_RESULTS_MAX_BYTES, lines: TASK_RESULTS_MAX_LINES };+ return results+ .map((result) => {+ const body = fitToBudget(escapeTaskResultBody(result.body), budget);+ const attributes = `id="${escapeAttribute(result.taskId)}" tool="${escapeAttribute(result.tool)}" status="${result.status}"`;+ return `${TASK_RESULT_TAG} ${attributes}>${body}</task_result>`;+ })+ .join("\n");+}++const TASK_RESULT_BLOCK = new RegExp(+ `${TASK_RESULT_TAG} id="([^"]*)" tool="([^"]*)" status="(completed|failed)">([\\s\\S]*?)</task_result>`,+ "g",+);++/**+ * The blocks of a `task.result` message, in order, as a deterministic mock+ * model reads them back; empty for any other text.+ */+export function readTaskResults(message: string): TaskResultBlock[] {+ return [...message.matchAll(TASK_RESULT_BLOCK)].map(([, taskId, tool, status, body]) => ({+ body: body!.replaceAll("<\\/task_result", "</task_result"),+ status: status as TaskResultBlock["status"],+ taskId: taskId!,+ tool: tool!,+ }));+}++function fitToBudget(body: string, budget: { bytes: number; lines: number }): string {+ const encoder = new TextEncoder();+ const lines = body.split("\n");+ const kept: string[] = [];+ for (const line of lines) {+ const cost = encoder.encode(line).byteLength + 1;+ if (budget.lines === 0 || cost > budget.bytes) {+ kept.push(TRUNCATED_MARKER);+ budget.lines = 0;+ budget.bytes = 0;+ break;+ }+ kept.push(line);+ budget.lines -= 1;+ budget.bytes -= cost;+ }+ return kept.join("\n");+}++function escapeTaskResultBody(body: string): string {+ return body.replaceAll("</task_result", "<\\/task_result");+}++/** The text of a tool's `toModelOutput` result, or of a raw output without one. */+export function renderModelOutputText(output: unknown): string {+ if (typeof output === "string") return output;+ if (isModelOutput(output)) {+ switch (output.type) {+ case "text":+ return String(output.value);+ case "json":+ return JSON.stringify(output.value);+ case "content":+ return renderContentParts(output.value);+ }+ }+ return JSON.stringify(output ?? null);+}++function renderContentParts(parts: unknown): string {+ if (!Array.isArray(parts)) return "";+ return parts+ .map((part: { type?: unknown; text?: unknown; filename?: unknown; mediaType?: unknown }) => {+ if (part.type === "text") return String(part.text);+ const label = typeof part.filename === "string" ? part.filename : String(part.mediaType);+ return `[file: ${label}]`;+ })+ .join("\n");+}++function isModelOutput(+ value: unknown,+): value is { readonly type: "text" | "json" | "content"; readonly value: unknown } {+ if (typeof value !== "object" || value === null) return false;+ const type = Reflect.get(value, "type");+ return (type === "text" || type === "json" || type === "content") && "value" in value;+}++/** A task as the `[Tasks]` note lists it. */+export interface ListedTask {+ readonly id: string;+ readonly tool: string;+}++/** The `[Tasks]` note: working tasks, then idle resumable tasks when there are any. */+export function renderTasksNote(input: {+ readonly idle: readonly ListedTask[];+ readonly working: readonly ListedTask[];+}): string {+ const lines = [TASKS_NOTE_LABEL, "<tasks>"];+ for (const task of input.working) {+ lines.push(`<task ${listedTaskAttributes(task)} status="working"/>`);+ }+ lines.push("</tasks>");+ if (input.idle.length > 0) {+ lines.push("<idle>");+ for (const task of input.idle) lines.push(`<task ${listedTaskAttributes(task)}/>`);+ lines.push("</idle>");+ }+ return lines.join("\n");+}++function listedTaskAttributes(task: ListedTask): string {+ return `id="${escapeAttribute(task.id)}" tool="${escapeAttribute(task.tool)}"`;+}++function formatDuration(ms: number): string {+ if (ms < 1_000) return `${String(Math.max(0, Math.round(ms)))}ms`;+ const totalSeconds = Math.round(ms / 1_000);+ const hours = Math.floor(totalSeconds / 3_600);+ const minutes = Math.floor((totalSeconds % 3_600) / 60);+ const seconds = totalSeconds % 60;+ const parts: string[] = [];+ if (hours > 0) parts.push(`${String(hours)}h`);+ if (minutes > 0) parts.push(`${String(minutes)}m`);+ if (seconds > 0) parts.push(`${String(seconds)}s`);+ return parts.join(" ");+}++function joinList(items: readonly string[]): string {+ if (items.length <= 1) return items.join("");+ return `${items.slice(0, -1).join(", ")} and ${items.at(-1)!}`;+}++function capitalize(text: string): string {+ return text.charAt(0).toUpperCase() + text.slice(1);+}++function escapeAttribute(value: string): string {+ return value+ .replaceAll("&", "&")+ .replaceAll('"', """)+ .replaceAll("<", "<")+ .replaceAll(">", ">");+}diff --git a/packages/eve/src/execution/tasks/session.ts b/packages/eve/src/execution/tasks/session.tsnew file mode 100644index 000000000..b29a2b0d8--- /dev/null+++ b/packages/eve/src/execution/tasks/session.ts@@ -0,0 +1,60 @@+import type { SessionStateCursor } from "#execution/session/state-cursor.js";+import {+ TASK_CANCEL_TOOL_NAME,+ taskToolResult,+ type TaskToolCall,+} from "#execution/tasks/calls.js";+import { renderUnknownTaskError } from "#execution/tasks/render.js";+import { cancelTasksStep, type TaskRunMessage } from "#execution/tasks/steps.js";+import {+ readTaskTable,+ taskCancelResult,+ taskToolName,+ workingTasks,+ type TaskTable,+} from "#execution/tasks/table.js";+import type { WorkflowToolRunMessage } from "#execution/tools/workflow/messages.js";+import type { RuntimeActionResult } from "#shared/action-types.js";++// What the session's workflow body does with tasks between steps: records+// change only in `steps.ts`, and these decide when to run them. They live apart+// because the workflow bundle keeps only the steps of a step module.++/** Whether a run's message changes a task record. */+export function isTaskRunMessage(message: WorkflowToolRunMessage): message is TaskRunMessage {+ if (message.from.taskId === undefined) return false;+ return message.kind === "started" || message.kind === "reply" || message.kind === "outcome";+}++/** The session's task table as the workflow body last committed it. */+export function sessionTaskTable(cursor: SessionStateCursor): TaskTable {+ return readTaskTable(cursor.sessionState.snapshot.session.state);+}++/**+ * Cancels every working task: a turn that ends anyway, such as by failing,+ * cancels the tasks it held on.+ */+export async function cancelWorkingTasks(cursor: SessionStateCursor): Promise<void> {+ const taskIds = workingTasks(sessionTaskTable(cursor)).map((record) => record.id);+ if (taskIds.length === 0) return;+ await cursor.apply(await cancelTasksStep({ ...cursor.stepState(), taskIds }));+}++export async function answerTaskCancel(+ cursor: SessionStateCursor,+ call: Extract<TaskToolCall, { readonly kind: "task_cancel" }>,+): Promise<RuntimeActionResult> {+ const result = taskCancelResult(sessionTaskTable(cursor), call.taskId);+ if (result === undefined) {+ const error = {+ code: "UNKNOWN_TASK",+ message: renderUnknownTaskError(call.taskId, taskToolName(call.taskId)),+ };+ return { ...taskToolResult(call.callId, TASK_CANCEL_TOOL_NAME, error), isError: true };+ }+ if (result.status === "cancelled") {+ await cursor.apply(await cancelTasksStep({ ...cursor.stepState(), taskIds: [call.taskId] }));+ }+ return taskToolResult(call.callId, TASK_CANCEL_TOOL_NAME, result);+}diff --git a/packages/eve/src/execution/tasks/start.ts b/packages/eve/src/execution/tasks/start.tsnew file mode 100644index 000000000..626cdc95a--- /dev/null+++ b/packages/eve/src/execution/tasks/start.ts@@ -0,0 +1,179 @@+import {+ renderTaskReceipt,+ renderTaskSentReceipt,+ renderTooManyTasksError,+ renderUnknownTaskError,+} from "#execution/tasks/render.js";+import { sendTaskRunCommands } from "#execution/tasks/steps.js";+import {+ findTask,+ isTaskAvailable,+ isTaskWorking,+ MAX_WORKING_TASKS,+ readTaskTable,+ recordTaskCall,+ recordTaskRun,+ removeTask,+ workingTasks,+ writeTaskTable,+ type TaskRecord,+ type TaskTable,+} from "#execution/tasks/table.js";+import {+ startFailureResult,+ startWorkflowToolCallRun,+ type StartWorkflowTaskInput,+} from "#execution/tools/workflow/start.js";+import { createRuntimeToolResultFromValue } from "#harness/action-result-helpers.js";+import { createLogger, logError } from "#internal/logging.js";+import type { HarnessSession } from "#harness/types.js";+import { createTaskStartedEvent, type TaskStartedStreamEvent } from "#protocol/message.js";+import type { RuntimeToolResultActionResult, WorkflowToolRunEntry } from "#shared/action-types.js";++const log = createLogger("execution.tasks");++type TaskDispatchInput = StartWorkflowTaskInput & { readonly taskId: string };++/** The call's answer, and the `task.started` event the dispatch step publishes for it. */+interface TaskDispatchResult {+ readonly result: RuntimeToolResultActionResult;+ readonly session: HarnessSession;+ readonly started?: TaskStartedStreamEvent;+}++/** The entry of a run that does a task's work. */+type TaskRunEntry = Extract<WorkflowToolRunEntry, { readonly taskId: string }>;++/**+ * Starts the run for a task its model step committed, once, and answers the+ * call with its receipt and the `task.started` event the dispatch step+ * publishes. Runs inside that step, where the task's cap is enforced: past+ * it, the record is dropped and the call fails.+ */+export async function startTaskRun(+ input: StartWorkflowTaskInput & { readonly entry: TaskRunEntry },+): Promise<TaskDispatchResult> {+ const { entry, session, task } = input;+ const { taskId } = entry;+ const dispatch = { ...input, taskId };+ const receipt = startReceipt(dispatch, entry.entryPoint === "serve");+ const table = readTaskTable(session.state);+ const record = findTask(table, taskId);+ // Cancelled before the session could start it: there is nothing to run.+ if (record === undefined || !isTaskWorking(record)) {+ return { result: receipt, session };+ }++ const overCap = tooManyTasks(dispatch, table);+ if (overCap !== undefined) {+ return { result: overCap, session: writeTaskTable(session, removeTask(table, taskId)) };+ }++ let address;+ try {+ address = await startWorkflowToolCallRun(input, entry);+ } catch (error) {+ logError(log, "task run failed to start", error, { taskId, toolName: task.toolName });+ return {+ result: startFailureResult(task, error),+ session: writeTaskTable(session, removeTask(table, taskId)),+ };+ }++ return {+ result: receipt,+ session: writeTaskTable(session, recordTaskRun(table, taskId, address)),+ started: taskStartedEvent(dispatch, record),+ };+}++/**+ * Sends a call to the `serve` task it names by `taskId`. The task must be+ * available to the tool, and a call that makes an idle task work again+ * counts toward the cap. The call is recorded, reported as started, and sent+ * to the task's run, whose body receives it from `receive()`.+ */+export async function sendToTask(input: TaskDispatchInput): Promise<TaskDispatchResult> {+ const { session, task, taskId } = input;+ const table = readTaskTable(session.state);+ const record = findTask(table, taskId);+ if (!isTaskAvailable(record, task.toolName)) {+ return { result: unknownTaskResult(input), session };+ }++ if (!isTaskWorking(record)) {+ const overCap = tooManyTasks(input, table);+ if (overCap !== undefined) return { result: overCap, session };+ }++ const recorded = recordTaskCall(table, taskId, {+ agentContext: input.agentContext,+ auth: input.auth,+ callId: task.callId,+ executeInput: task.executeInput,+ input: task.input,+ sequence: input.batchEvent.sequence,+ stepIndex: input.batchEvent.stepIndex,+ turnId: input.batchEvent.turnId,+ });+ if (recorded.send !== undefined) await sendTaskRunCommands(recorded.send);+ return {+ result: toolResult(input, renderTaskSentReceipt(taskId)),+ session: writeTaskTable(session, recorded.table),+ started: taskStartedEvent(input, record),+ };+}++/** The `TOO_MANY_TASKS` error when the session already runs as many tasks as it may. */+function tooManyTasks(+ input: TaskDispatchInput,+ table: TaskTable,+): RuntimeToolResultActionResult | undefined {+ const running = workingTasks(table).filter((candidate) => candidate.run !== undefined);+ if (running.length < MAX_WORKING_TASKS) return undefined;+ const runningIds = running.map((candidate) => candidate.id);+ return createRuntimeToolResultFromValue({+ callId: input.task.callId,+ isError: true,+ output: {+ code: "TOO_MANY_TASKS",+ message: renderTooManyTasksError(MAX_WORKING_TASKS, runningIds),+ },+ toolName: input.task.toolName,+ });+}++function unknownTaskResult(input: TaskDispatchInput): RuntimeToolResultActionResult {+ return createRuntimeToolResultFromValue({+ callId: input.task.callId,+ isError: true,+ output: {+ code: "UNKNOWN_TASK",+ message: renderUnknownTaskError(input.taskId, input.task.toolName),+ },+ toolName: input.task.toolName,+ });+}++function taskStartedEvent(input: TaskDispatchInput, record: TaskRecord): TaskStartedStreamEvent {+ return createTaskStartedEvent({+ callId: input.task.callId,+ kind: record.kind,+ name: input.task.toolName,+ taskId: input.taskId,+ turnId: input.batchEvent.turnId,+ });+}++function startReceipt(input: TaskDispatchInput, resumable: boolean): RuntimeToolResultActionResult {+ const receipt = renderTaskReceipt({ id: input.taskId, resumable, tool: input.task.toolName });+ return toolResult(input, receipt);+}++function toolResult(input: TaskDispatchInput, output: string): RuntimeToolResultActionResult {+ return createRuntimeToolResultFromValue({+ callId: input.task.callId,+ output,+ toolName: input.task.toolName,+ });+}diff --git a/packages/eve/src/execution/tasks/steps.ts b/packages/eve/src/execution/tasks/steps.tsnew file mode 100644index 000000000..bea49bb21--- /dev/null+++ b/packages/eve/src/execution/tasks/steps.ts@@ -0,0 +1,196 @@+import {+ readDurableSession,+ replaceDurableSessionSnapshot,+ type DurableSession,+ type DurableSessionState,+} from "#execution/durable-session-store.js";+import {+ cancelTask,+ findTask,+ finishTaskRun,+ markTaskRunStarted,+ readTaskTable,+ settleRemainingTaskCalls,+ settleTaskCalls,+ writeTaskTable,+ type TaskCall,+ type TaskOutcome,+ type TaskRunCommand,+ type TaskRunCommands,+ type TaskTable,+} from "#execution/tasks/table.js";+import { ignoreGoneTarget } from "#execution/tasks/workflow-target.js";+import {+ publishSessionEvents,+ relaySessionEvents,+ type PublishedSessionEvents,+ type SessionStepState,+} from "#execution/publish-session-events.js";+import type {+ WorkflowToolRunControlMessage,+ WorkflowToolRunMessage,+ WorkflowToolRunOutcomeMessage,+} from "#execution/tools/workflow/messages.js";+import { workflowToolRunFailureOutput } from "#execution/tools/workflow/owner-inbox.js";+import { withdrawWorkflowAsks } from "#execution/tools/workflow/withdraw-step.js";+import { clearProxyInputRequestsWhere } from "#harness/proxy-input-requests.js";+import { resumeHook } from "#internal/workflow/runtime.js";+import { createTaskSettledEvent, type TaskSettledStreamEvent } from "#protocol/message.js";++/** The messages a task's run sends that change its record. */+export type TaskRunMessage = Extract<+ WorkflowToolRunMessage,+ { readonly kind: "outcome" | "reply" | "started" }+>;++const TASK_CANCEL_REASON = "The task was cancelled.";++/** Applies one message from a task's run: started, a reply, or the run's outcome. */+export async function applyTaskRunMessageStep(+ input: SessionStepState & { readonly message: TaskRunMessage },+): Promise<PublishedSessionEvents> {+ "use step";++ const { message } = input;+ const taskId = message.from.taskId;+ let session = readDurableSession(input.sessionState);+ if (taskId === undefined) {+ return { serializedContext: input.serializedContext, sessionState: input.sessionState };+ }+ let table = readTaskTable(session.state);+ const events: TaskSettledStreamEvent[] = [];+ switch (message.kind) {+ case "started": {+ const started = markTaskRunStarted(table, taskId, message.from.runId);+ table = started.table;+ if (started.held !== undefined) await sendTaskRunCommands(started.held);+ break;+ }+ case "reply": {+ const outcome: TaskOutcome = { output: message.output, status: "completed" };+ const settled = settleTaskCalls(table, { callIds: message.callIds, outcome, taskId });+ table = settled.table;+ events.push(...settled.settled.map((call) => taskSettledEvent(taskId, call, outcome)));+ break;+ }+ case "outcome": {+ const outcome = toOutcome(message);+ const settled = settleRemainingTaskCalls(table, taskId, outcome);+ events.push(...settled.settled.map((call) => taskSettledEvent(taskId, call, outcome)));+ table = finishTaskRun(settled.table, taskId, message.from.runId);+ session = forgetRunQuestions(session, message.from.runId);+ break;+ }+ }+ return await publishSessionEvents(+ { ...input, sessionState: saveTable(input.sessionState, session, table) },+ events,+ );+}++/**+ * Cancels tasks: their calls settle as cancelled and their runs are told to+ * stop. A run ends itself within its cleanup deadline and reports cancelled.+ * A `task()` run's cancel settles its questions, so the session withdraws+ * them in the same step and accepts no answer after it. A `serve()` run+ * withdraws its stretch's questions itself, and the session decides each one.+ */+export async function cancelTasksStep(+ input: SessionStepState & { readonly taskIds: readonly string[] },+): Promise<PublishedSessionEvents> {+ "use step";++ const session = readDurableSession(input.sessionState);+ let table = readTaskTable(session.state);+ const events: TaskSettledStreamEvent[] = [];+ const stoppedRunIds = new Set<string>();+ for (const taskId of input.taskIds) {+ const resumable = findTask(table, taskId)?.resumable;+ const cancelled = cancelTask(table, taskId);+ table = cancelled.table;+ events.push(...cancelled.settled.map((call) => taskSettledEvent(taskId, call, CANCELLED)));+ if (cancelled.send === undefined) continue;+ if (resumable === false) stoppedRunIds.add(cancelled.send.run.runId);+ await sendTaskRunCommands(cancelled.send);+ }+ const withdrawn = withdrawWorkflowAsks(session, (_requestId, runId) => stoppedRunIds.has(runId));+ const relayed = await relaySessionEvents(+ { ...input, sessionState: saveTable(input.sessionState, withdrawn.session, table) },+ withdrawn.events,+ );+ return await publishSessionEvents({ ...input, ...relayed }, events);+}++const CANCELLED: TaskOutcome = { status: "cancelled" };++/** The `task.settled` event for one settled call. */+function taskSettledEvent(+ taskId: string,+ call: TaskCall,+ outcome: TaskOutcome,+): TaskSettledStreamEvent {+ const base = { callId: call.callId, taskId, turnId: call.turnId };+ switch (outcome.status) {+ case "completed":+ return createTaskSettledEvent({ ...base, output: outcome.output, status: "completed" });+ case "failed":+ return createTaskSettledEvent({+ ...base,+ error: { message: outcome.error },+ status: "failed",+ });+ case "cancelled":+ return createTaskSettledEvent({ ...base, status: "cancelled" });+ }+}++/**+ * Sends commands to a task's run, in order. A run that already finished takes+ * none; its outcome settles any call still waiting.+ */+export async function sendTaskRunCommands(commands: TaskRunCommands): Promise<void> {+ for (const command of commands.commands) {+ await ignoreGoneTarget(resumeHook(commands.run.hookToken, toControlMessage(command)));+ }+}++function toControlMessage(command: TaskRunCommand): WorkflowToolRunControlMessage {+ switch (command.kind) {+ case "cancel":+ return { kind: "cancel", reason: TASK_CANCEL_REASON };+ case "call":+ return { call: command.call, kind: "call" };+ }+}++function toOutcome(message: WorkflowToolRunOutcomeMessage): TaskOutcome {+ switch (message.result.status) {+ case "completed":+ return { output: message.result.output, status: "completed" };+ case "failed":+ return { error: failureMessage(message), status: "failed" };+ case "cancelled":+ return { status: "cancelled" };+ }+}++function failureMessage(message: WorkflowToolRunOutcomeMessage): string {+ const output = workflowToolRunFailureOutput(message);+ if (typeof output === "string") return output;+ const described =+ typeof output === "object" && output !== null ? Reflect.get(output, "message") : undefined;+ return typeof described === "string" ? described : JSON.stringify(output);+}++/** A finished run can no longer take answers, so its unanswered questions are dropped. */+function forgetRunQuestions(session: DurableSession, runId: string): DurableSession {+ return clearProxyInputRequestsWhere(session, (route) => route.workflowAsk?.runId === runId);+}++function saveTable(+ state: DurableSessionState,+ session: DurableSession,+ table: TaskTable,+): DurableSessionState {+ return replaceDurableSessionSnapshot({ session: writeTaskTable(session, table), state });+}diff --git a/packages/eve/src/execution/tasks/table.ts b/packages/eve/src/execution/tasks/table.tsnew file mode 100644index 000000000..8521f72ab--- /dev/null+++ b/packages/eve/src/execution/tasks/table.ts@@ -0,0 +1,505 @@+import type { TaskCancelResult, TaskWaitResult } from "#execution/tasks/calls.js";+import type { WorkflowToolRunCall } from "#execution/tools/workflow/messages.js";+import type { SessionStateMap } from "#harness/types.js";+import { isNonEmptyString, isObject } from "#shared/guards.js";+import type { JsonValue } from "#shared/json.js";+import type { TaskStartedStreamEvent } from "#protocol/message.js";+import { UNREADABLE_TASK_ERROR } from "#execution/tasks/render.js";++// The session's task table. Every write to a task record goes through this+// module; callers read with the helpers below and write with `writeTaskTable`.+// Readers run inside the workflow driver, so validation avoids schema runtimes.++const TASK_TABLE_STATE_KEY = "eve.taskTable";+const TASK_TABLE_VERSION = 1;++/** At most this many tasks work at once in one session: a backstop normal use shouldn't reach. */+export const MAX_WORKING_TASKS = 32;++/** Finished records kept so `task_cancel` can still answer `already_finished`. */+const MAX_FINISHED_RECORDS = 100;++/** Idle resumable tasks the `[Tasks]` note lists: the most recently used ones. */+const MAX_LISTED_IDLE_TASKS = 10;++const TASK_ID_ALPHABET = "0123456789abcdefghjkmnpqrstvwxyz";+const TASK_ID_SUFFIX_LENGTH = 6;++export interface TaskRunAddress {+ readonly hookToken: string;+ readonly runId: string;+}++/** The workflow run doing a task's work. `started` once its control hook can take commands. */+export interface TaskRun extends TaskRunAddress {+ readonly started: boolean;+}++/** A call the task admitted and hasn't settled, with the turn that made it. */+export interface TaskCall {+ readonly callId: string;+ readonly turnId: string;+}++/**+ * A command for a task's run. Commands go over the run's one control hook, so+ * the run sees calls and cancels in the order the session issued them.+ */+export type TaskRunCommand =+ | { readonly kind: "cancel" }+ | { readonly call: WorkflowToolRunCall; readonly kind: "call" };++/** Commands for one run, to send in order. */+export interface TaskRunCommands {+ readonly commands: readonly TaskRunCommand[];+ readonly run: TaskRunAddress;+}++/** How a task call ended, as `task.settled` reports it. */+export type TaskOutcome =+ | { readonly output: JsonValue; readonly status: "completed" }+ | { readonly error: string; readonly status: "failed" }+ | { readonly status: "cancelled" };++/**+ * An outcome the model receives, one per reply or run end, however many calls+ * it settled. Cancelled work never reports back.+ */+export type TaskResult = Exclude<TaskOutcome, { readonly status: "cancelled" }>;++export interface TaskRecord {+ readonly id: string;+ /** Whether the tool is an agent's, as `task.started` reports it. */+ readonly kind: TaskStartedStreamEvent["data"]["kind"];+ /** The tool whose call started the task. */+ readonly name: string;+ /** A `serve` tool's task: it takes more calls by its id, and is idle between results. */+ readonly resumable: boolean;+ /** Calls without a result. The task is working while any remain. */+ readonly calls: readonly TaskCall[];+ /** Results not yet delivered to the model. */+ readonly results: readonly TaskResult[];+ /** The task's run, from its start until it finishes. */+ readonly run?: TaskRun;+ /** Commands issued before the run could take them, sent in order once it reports started. */+ readonly held?: readonly TaskRunCommand[];+}++export interface TaskTable {+ readonly tasks: readonly TaskRecord[];+}++const EMPTY_TABLE: TaskTable = { tasks: [] };++export function readTaskTable(state: SessionStateMap | undefined): TaskTable {+ const stored = state?.[TASK_TABLE_STATE_KEY];+ if (!isObject(stored) || stored.version !== TASK_TABLE_VERSION || !Array.isArray(stored.tasks)) {+ return EMPTY_TABLE;+ }+ const tasks = Array.from(stored.tasks as unknown[]).flatMap((value) => {+ const record = decodeTaskRecord(value);+ return record === undefined ? [] : [record];+ });+ return { tasks };+}++export function writeTaskTable<T extends { readonly state?: SessionStateMap }>(+ session: T,+ table: TaskTable,+): T {+ const tasks = pruneFinishedRecords(table.tasks);+ if (tasks.length === 0) {+ const state = { ...session.state };+ delete state[TASK_TABLE_STATE_KEY];+ return { ...session, state: Object.keys(state).length === 0 ? undefined : state };+ }+ const stored = { tasks, version: TASK_TABLE_VERSION };+ return { ...session, state: { ...session.state, [TASK_TABLE_STATE_KEY]: stored } };+}++// ---------------------------------------------------------------------------+// Reads+// ---------------------------------------------------------------------------++export function findTask(table: TaskTable, taskId: string): TaskRecord | undefined {+ return table.tasks.find((record) => record.id === taskId);+}++export function isTaskWorking(record: TaskRecord): boolean {+ return record.calls.length > 0;+}++/** The tool a task id names: ids are `<tool>-<6 base32>`. */+export function taskToolName(taskId: string): string {+ const separator = taskId.lastIndexOf("-");+ return separator > 0 ? taskId.slice(0, separator) : taskId;+}++export function workingTasks(table: TaskTable): readonly TaskRecord[] {+ return table.tasks.filter(isTaskWorking);+}++/**+ * The most recently used idle resumable tasks, oldest first. The table keeps+ * records in order of use, so the last ones are the most recent.+ */+export function idleTasks(table: TaskTable): readonly TaskRecord[] {+ return table.tasks.filter(isResumableTaskIdle).slice(-MAX_LISTED_IDLE_TASKS);+}++/**+ * Whether a call may reach the task by its id: the task is resumable and+ * unfinished, and was started by this tool.+ */+export function isTaskAvailable(+ record: TaskRecord | undefined,+ toolName: string,+): record is TaskRecord & { readonly run: TaskRun } {+ return (+ record !== undefined && record.resumable && record.run !== undefined && record.name === toolName+ );+}++/** Tasks whose results the model has not received yet. */+export function tasksWithResults(table: TaskTable): readonly TaskRecord[] {+ return table.tasks.filter((record) => record.results.length > 0);+}++/**+ * What a wait on the turn's tasks returns now, or `undefined` to keep+ * waiting. A waiting result, or nothing left working, ends it first;+ * cancelled work never does.+ */+export function taskWaitResult(+ table: TaskTable,+ wake: { readonly interrupted: boolean; readonly timedOut: boolean },+): TaskWaitResult | undefined {+ const settled = tasksWithResults(table).map((record) => ({+ id: record.id,+ status: record.results.at(-1)!.status,+ }));+ const working = workingTasks(table).map((record) => record.id);+ if (settled.length > 0 || working.length === 0) return { settled, status: "settled", working };+ if (wake.interrupted) return { status: "interrupt", working };+ if (wake.timedOut) return { status: "timeout", working };+ return undefined;+}++/**+ * What `task_cancel` answers, or `undefined` for a task that doesn't exist.+ * `cancelled` means the caller cancels the working task.+ */+export function taskCancelResult(table: TaskTable, taskId: string): TaskCancelResult | undefined {+ const record = findTask(table, taskId);+ if (record === undefined) return undefined;+ return { status: isTaskWorking(record) ? "cancelled" : "already_finished" };+}++/** Runs that may still be doing work, including cancelled runs that haven't confirmed yet. */+export function liveTaskRuns(table: TaskTable): readonly TaskRunAddress[] {+ return table.tasks.flatMap((record) =>+ record.run === undefined ? [] : [toRunAddress(record.run)],+ );+}++// ---------------------------------------------------------------------------+// Transitions+// ---------------------------------------------------------------------------++/** Records a task for a call the model just made, with a new id. */+export function createTask(+ table: TaskTable,+ input: {+ readonly callId: string;+ readonly kind: TaskRecord["kind"];+ readonly name: string;+ readonly resumable: boolean;+ readonly turnId: string;+ },+): { readonly table: TaskTable; readonly taskId: string } {+ const taskId = createTaskId(table, input.name);+ const record: TaskRecord = {+ calls: [{ callId: input.callId, turnId: input.turnId }],+ id: taskId,+ kind: input.kind,+ name: input.name,+ results: [],+ resumable: input.resumable,+ };+ return { table: { ...table, tasks: [...table.tasks, record] }, taskId };+}++/** Drops a task that never started, such as one past the cap. */+export function removeTask(table: TaskTable, taskId: string): TaskTable {+ return { ...table, tasks: table.tasks.filter((record) => record.id !== taskId) };+}++export function recordTaskRun(table: TaskTable, taskId: string, run: TaskRunAddress): TaskTable {+ return updateTask(table, taskId, (record) => ({ ...record, run: { ...run, started: false } }));+}++/**+ * The run can take commands now. Commands issued before this were held on the+ * record; they are returned, in order, so the caller sends them.+ */+export function markTaskRunStarted(+ table: TaskTable,+ taskId: string,+ runId: string,+): { readonly held?: TaskRunCommands; readonly table: TaskTable } {+ const record = findTask(table, taskId);+ if (record?.run === undefined || record.run.runId !== runId || record.run.started) {+ return { table };+ }+ const run = { ...record.run, started: true };+ const next = updateTask(table, taskId, (current) => {+ const { held: _held, ...rest } = current;+ return { ...rest, run };+ });+ if (record.held === undefined) return { table: next };+ return { held: { commands: record.held, run: toRunAddress(run) }, table: next };+}++/**+ * Records a call that reaches an available task by its id: the task is+ * working until the call has a result. The call goes to a started run now, or+ * is held until the run reports started. The record moves to the end of the+ * table, which keeps records in order of use.+ */+export function recordTaskCall(+ table: TaskTable,+ taskId: string,+ call: WorkflowToolRunCall,+): { readonly send?: TaskRunCommands; readonly table: TaskTable } {+ const record = findTask(table, taskId);+ if (record?.run === undefined) return { table };+ const command: TaskRunCommand = { call, kind: "call" };+ const run = record.run;+ const admitted: TaskCall = { callId: call.callId, turnId: call.turnId };+ let updated: TaskRecord = { ...record, calls: [...record.calls, admitted] };+ if (!run.started) updated = { ...updated, held: [...(record.held ?? []), command] };+ const next = { ...table, tasks: [...removeTask(table, taskId).tasks, updated] };+ if (!run.started) return { table: next };+ return { send: { commands: [command], run: toRunAddress(run) }, table: next };+}++/**+ * Settles calls that share one outcome, as one reply does, in one step. Each+ * call settles once, with its own `task.settled`; the first outcome wins, so a+ * call already settled, including one its owner cancelled, is dropped. The+ * model receives the outcome once, since every call it settles would repeat it.+ */+export function settleTaskCalls(+ table: TaskTable,+ input: {+ readonly callIds: readonly string[];+ readonly outcome: TaskOutcome;+ readonly taskId: string;+ },+): { readonly settled: readonly TaskCall[]; readonly table: TaskTable } {+ const settling = new Set(input.callIds);+ const calls = findTask(table, input.taskId)?.calls ?? [];+ const settled = calls.filter((call) => settling.has(call.callId));+ if (settled.length === 0) return { settled, table };+ const { outcome } = input;+ const next = updateTask(table, input.taskId, (current) => ({+ ...current,+ calls: current.calls.filter((call) => !settling.has(call.callId)),+ results: outcome.status === "cancelled" ? current.results : [...current.results, outcome],+ }));+ return { settled, table: next };+}++/**+ * Settles every call still without a result with one outcome, as a run's+ * return or failure does: a task's one call, or every call a resumable task+ * received, or never received, since its last reply.+ */+export function settleRemainingTaskCalls(+ table: TaskTable,+ taskId: string,+ outcome: TaskOutcome,+): { readonly settled: readonly TaskCall[]; readonly table: TaskTable } {+ const callIds = findTask(table, taskId)?.calls.map((call) => call.callId) ?? [];+ return settleTaskCalls(table, { callIds, outcome, taskId });+}++/** The task's run finished; nothing is left to cancel. */+export function finishTaskRun(table: TaskTable, taskId: string, runId: string): TaskTable {+ return updateTask(table, taskId, (record) => {+ if (record.run?.runId !== runId) return record;+ const { held: _held, run: _run, ...rest } = record;+ return rest;+ });+}++/** What cancelling a task changed, and the command to send its run, if any. */+export interface TaskCancellation {+ readonly send?: TaskRunCommands;+ readonly settled: readonly TaskCall[];+ readonly table: TaskTable;+}++/**+ * Cancels a task's current work: its calls settle as cancelled and never+ * report back, and a live run is told to stop. A run that hasn't started+ * holds the cancel. A resumable task stays available and becomes idle.+ */+export function cancelTask(table: TaskTable, taskId: string): TaskCancellation {+ const record = findTask(table, taskId);+ if (record === undefined) return { settled: [], table };+ if (record.resumable) return cancelResumableTask(table, record);+ const settled = cancelledCalls(record);+ const run = record.run;+ const next = updateTask(table, taskId, (current) => {+ const cancelled: TaskRecord = { ...current, calls: [] };+ if (run === undefined || run.started) return cancelled;+ return { ...cancelled, held: [{ kind: "cancel" }] };+ });+ if (run === undefined || !run.started) return { settled, table: next };+ return { send: cancelCommand(run), settled, table: next };+}++/**+ * A resumable run aborts only its current stretch of work and stays parked for+ * later calls. Calls held for a run that hasn't started settle here, so only+ * the cancel is still held for it.+ */+function cancelResumableTask(table: TaskTable, record: TaskRecord): TaskCancellation {+ const run = record.run;+ if (run === undefined || !isTaskWorking(record)) return { settled: [], table };+ const settled = cancelledCalls(record);+ const next = updateTask(table, record.id, (current) => {+ const idle: TaskRecord = { ...current, calls: [] };+ return run.started ? idle : { ...idle, held: [{ kind: "cancel" }] };+ });+ if (!run.started) return { settled, table: next };+ return { send: cancelCommand(run), settled, table: next };+}++function cancelCommand(run: TaskRun): TaskRunCommands {+ return { commands: [{ kind: "cancel" }], run: toRunAddress(run) };+}++/**+ * Hands every undelivered result to the model, which receives each+ * once: `taken` is each record with its results, before they were cleared.+ */+export function takeTaskResults(table: TaskTable): {+ readonly taken: readonly TaskRecord[];+ readonly table: TaskTable;+} {+ const taken = tasksWithResults(table);+ const tasks = table.tasks.map((record) =>+ taken.includes(record) ? { ...record, results: [] } : record,+ );+ return { table: { ...table, tasks }, taken };+}++// ---------------------------------------------------------------------------+// Helpers+// ---------------------------------------------------------------------------++function updateTask(+ table: TaskTable,+ taskId: string,+ update: (record: TaskRecord) => TaskRecord,+): TaskTable {+ return {+ ...table,+ tasks: table.tasks.map((record) => (record.id === taskId ? update(record) : record)),+ };+}++/** A task the session never started reported no `task.started`, so it settles nothing. */+function cancelledCalls(record: TaskRecord): readonly TaskCall[] {+ return record.run === undefined ? [] : record.calls;+}++function toRunAddress(run: TaskRun): TaskRunAddress {+ return { hookToken: run.hookToken, runId: run.runId };+}++/** `<tool>-<6 base32>`, unique within the table. */+function createTaskId(table: TaskTable, name: string): string {+ while (true) {+ const bytes = crypto.getRandomValues(new Uint8Array(TASK_ID_SUFFIX_LENGTH));+ const suffix = Array.from(bytes, (byte) => TASK_ID_ALPHABET[byte % 32]).join("");+ const taskId = `${name}-${suffix}`;+ if (findTask(table, taskId) === undefined) return taskId;+ }+}++function isResumableTaskIdle(record: TaskRecord): boolean {+ return record.resumable && record.run !== undefined && !isTaskWorking(record);+}++function isFinishedRecord(record: TaskRecord): boolean {+ return record.calls.length === 0 && record.results.length === 0 && record.run === undefined;+}++function pruneFinishedRecords(tasks: readonly TaskRecord[]): readonly TaskRecord[] {+ const finished = tasks.filter(isFinishedRecord);+ const excess = finished.length - MAX_FINISHED_RECORDS;+ if (excess <= 0) return tasks;+ const dropped = new Set(finished.slice(0, excess));+ return tasks.filter((record) => !dropped.has(record));+}++function decodeTaskRecord(value: unknown): TaskRecord | undefined {+ if (isTaskRecord(value)) return value;+ // A record that can't be read fails its task, never the session.+ if (!isObject(value) || !isNonEmptyString(value.id) || !isNonEmptyString(value.name)) {+ return undefined;+ }+ return {+ calls: [],+ id: value.id,+ kind: value.kind === "agent" ? "agent" : "tool",+ name: value.name,+ results: [{ error: UNREADABLE_TASK_ERROR, status: "failed" }],+ resumable: false,+ };+}++function isTaskRecord(value: unknown): value is TaskRecord {+ return (+ isObject(value) &&+ isNonEmptyString(value.id) &&+ isNonEmptyString(value.name) &&+ (value.kind === "agent" || value.kind === "tool") &&+ typeof value.resumable === "boolean" &&+ Array.isArray(value.calls) &&+ Array.from(value.calls as unknown[]).every(isTaskCall) &&+ Array.isArray(value.results) &&+ Array.from(value.results as unknown[]).every(isTaskResult) &&+ (value.run === undefined || isTaskRun(value.run)) &&+ (value.held === undefined ||+ (Array.isArray(value.held) && Array.from(value.held as unknown[]).every(isTaskRunCommand)))+ );+}++function isTaskRunCommand(value: unknown): value is TaskRunCommand {+ if (!isObject(value)) return false;+ if (value.kind === "cancel") return true;+ return value.kind === "call" && isObject(value.call) && isNonEmptyString(value.call.callId);+}++function isTaskResult(value: unknown): value is TaskResult {+ if (!isObject(value)) return false;+ if (value.status === "completed") return "output" in value;+ return value.status === "failed" && typeof value.error === "string";+}++function isTaskRun(value: unknown): value is TaskRun {+ return (+ isObject(value) &&+ isNonEmptyString(value.runId) &&+ isNonEmptyString(value.hookToken) &&+ typeof value.started === "boolean"+ );+}++function isTaskCall(value: unknown): value is TaskCall {+ return isObject(value) && isNonEmptyString(value.callId) && typeof value.turnId === "string";+}diff --git a/packages/eve/src/execution/tasks/task-id-input.ts b/packages/eve/src/execution/tasks/task-id-input.tsnew file mode 100644index 000000000..b39ecd9a2--- /dev/null+++ b/packages/eve/src/execution/tasks/task-id-input.ts@@ -0,0 +1,50 @@+import {+ AGENT_SERVE_TOOL_DESCRIPTION,+ SERVE_TOOL_DESCRIPTION,+ TASK_ID_INPUT_DESCRIPTION,+} from "#execution/tasks/render.js";+import { isAgentTool } from "#execution/tasks/tool-entry-point.js";+import type { HarnessToolDefinition } from "#harness/execute-tool.js";+import type { JsonObject } from "#shared/json.js";+import { isToolSchema, withOptionalStringProperty } from "#tools/schema.js";++// A `serve` tool's model input is the tool's own input plus an optional+// `taskId`, which sends the call to the running task it names.++/** The model input property eve adds to every `serve` tool. */+export const TASK_ID_INPUT = "taskId";++/** The tool as the model sees it: its input gains `taskId`, and its description explains it. */+export function withTaskIdInput(definition: HarnessToolDefinition): HarnessToolDefinition {+ const schema = definition.inputSchema;+ if (!isToolSchema(schema)) {+ throw new Error(`Tool "${definition.name}" has no input schema eve can add taskId to.`);+ }+ const sentence = isAgentTool(definition) ? AGENT_SERVE_TOOL_DESCRIPTION : SERVE_TOOL_DESCRIPTION;+ return {+ ...definition,+ description: appendSentence(definition.description, sentence),+ inputSchema: withOptionalStringProperty(schema, {+ description: TASK_ID_INPUT_DESCRIPTION,+ name: TASK_ID_INPUT,+ }),+ };+}++/** A `serve` tool call's model input, split into the task it names and the tool's own input. */+export interface ServeCallInput {+ readonly input: JsonObject;+ readonly taskId?: string;+}++export function splitTaskIdInput(modelInput: JsonObject): ServeCallInput {+ const { [TASK_ID_INPUT]: taskId, ...input } = modelInput;+ if (typeof taskId !== "string") return { input };+ return { input, taskId };+}++function appendSentence(description: string, sentence: string): string {+ const trimmed = description.trimEnd();+ if (trimmed === "") return sentence;+ return `${trimmed} ${sentence}`;+}diff --git a/packages/eve/src/execution/tasks/tool-entry-point.ts b/packages/eve/src/execution/tasks/tool-entry-point.tsnew file mode 100644index 000000000..175c5041a--- /dev/null+++ b/packages/eve/src/execution/tasks/tool-entry-point.ts@@ -0,0 +1,35 @@+import type { HarnessToolDefinition } from "#harness/execute-tool.js";+import type { PreparedDispatchTarget } from "#tools/behavior.js";+import type { WorkflowToolEntryPoint } from "#tools/workflow-entry-point.js";++/**+ * The entry point a deferred tool's calls run through. Every agent tool is a+ * `serve` tool; tools that dispatch nowhere are called like `execute`.+ */+export function entryPointOf(+ definition: HarnessToolDefinition | undefined,+): WorkflowToolEntryPoint {+ const target = dispatchTargetOf(definition);+ if (target === undefined) return "execute";+ if (target.kind === "workflow-tool-call") return target.entryPoint;+ return "serve";+}++/** Whether calls to the tool run as tasks: every call to an agent, `task`, or `serve` tool. */+export function startsTasks(definition: HarnessToolDefinition | undefined): boolean {+ return entryPointOf(definition) !== "execute";+}++/** Whether the tool is an agent: a declared, remote, dynamic, or root-copy agent. */+export function isAgentTool(definition: HarnessToolDefinition | undefined): boolean {+ const target = dispatchTargetOf(definition);+ return target !== undefined && target.kind !== "workflow-tool-call";+}++function dispatchTargetOf(+ definition: HarnessToolDefinition | undefined,+): PreparedDispatchTarget | undefined {+ const handling = definition?.behavior?.handling;+ if (handling?.kind !== "dispatch") return undefined;+ return handling.target;+}diff --git a/packages/eve/src/execution/terminate-child-sessions-step.test.ts b/packages/eve/src/execution/terminate-child-sessions-step.test.tsdeleted file mode 100644index 4a9e14dbb..000000000--- a/packages/eve/src/execution/terminate-child-sessions-step.test.ts+++ /dev/null@@ -1,363 +0,0 @@-import { beforeEach, describe, expect, it, vi } from "vitest";--import { AGENT_HANDLES_STATE_KEY, type AgentHandle } from "#subagents/handles/store.js";-import type { DurableSessionState } from "#execution/durable-session-store.js";-import { terminateChildSessionsStep } from "#execution/terminate-child-sessions-step.js";--const COMPILED_BUNDLE = {- subagentRegistry: { subagentsByNodeId: new Map() },-};--const {- cancelRunMock,- deserializeContextMock,- getWorldMock,- getDynamicSubagentSelectionMock,- hydrateDurableSessionMock,- resetRemoteAgentSessionMock,- resolveRemoteAgentForActionMock,- resolveRemoteAgentStreamHeadersMock,- resolveEffectiveAgentRuntimeMock,-} = vi.hoisted(() => ({- cancelRunMock: vi.fn(),- deserializeContextMock: vi.fn(),- getWorldMock: vi.fn(),- getDynamicSubagentSelectionMock: vi.fn(),- hydrateDurableSessionMock: vi.fn(),- resetRemoteAgentSessionMock: vi.fn(),- resolveRemoteAgentForActionMock: vi.fn(),- resolveRemoteAgentStreamHeadersMock: vi.fn(),- resolveEffectiveAgentRuntimeMock: vi.fn(),-}));--vi.mock("#context/serialize.js", () => ({- deserializeContext: deserializeContextMock,-}));-vi.mock("#context/dynamic-subagent-lifecycle.js", () => ({- getDynamicSubagentSelection: getDynamicSubagentSelectionMock,-}));-vi.mock("#execution/effective-agent-config.js", () => ({- resolveEffectiveAgentRuntime: resolveEffectiveAgentRuntimeMock,-}));-vi.mock("#execution/session.js", () => ({- hydrateDurableSession: hydrateDurableSessionMock,-}));-vi.mock("#subagents/remote-dispatch.js", () => ({- resetRemoteAgentSession: resetRemoteAgentSessionMock,- resolveRemoteAgentForAction: resolveRemoteAgentForActionMock,- resolveRemoteAgentStreamHeaders: resolveRemoteAgentStreamHeadersMock,-}));-vi.mock("#internal/workflow/runtime.js", () => ({- cancelRun: cancelRunMock,- getWorld: getWorldMock,-}));--describe("terminateChildSessionsStep", () => {- beforeEach(() => {- cancelRunMock.mockReset();- cancelRunMock.mockResolvedValue(undefined);- deserializeContextMock.mockReset();- deserializeContextMock.mockResolvedValue({ require: vi.fn().mockReturnValue(COMPILED_BUNDLE) });- getWorldMock.mockReset();- getWorldMock.mockResolvedValue("world");- getDynamicSubagentSelectionMock.mockReset();- getDynamicSubagentSelectionMock.mockReturnValue(undefined);- hydrateDurableSessionMock.mockReset();- hydrateDurableSessionMock.mockReturnValue("runtime-session");- resetRemoteAgentSessionMock.mockReset();- resetRemoteAgentSessionMock.mockResolvedValue({ ok: true, status: "no_active_session" });- resolveRemoteAgentForActionMock.mockReset();- resolveRemoteAgentForActionMock.mockReturnValue({- description: "Research remotely",- kind: "remote",- name: "research",- nodeId: "subagents/research",- path: "/eve/v1/session",- url: "https://remote.example.com",- });- resolveRemoteAgentStreamHeadersMock.mockReset();- resolveRemoteAgentStreamHeadersMock.mockResolvedValue({ authorization: "Bearer fresh" });- resolveEffectiveAgentRuntimeMock.mockReset();- resolveEffectiveAgentRuntimeMock.mockReturnValue({ turnAgent: "turn-agent" });- });-- it("terminates running and parked local/self children", async () => {- const handles = [- runningHandle({ id: "ag_local:1", kind: "agent/local", sessionId: "session-local" }),- parkedHandle({ id: "ag_self:1", kind: "agent/self", sessionId: "session-self" }),- ];-- await terminateChildSessionsStep({- sessionState: makeSessionState(handles),- });-- expect(cancelRunMock).toHaveBeenCalledTimes(2);- expect(cancelRunMock).toHaveBeenNthCalledWith(1, "world", "session-local", {- cancelReason: "Parent session ended",- });- expect(cancelRunMock).toHaveBeenNthCalledWith(2, "world", "session-self", {- cancelReason: "Parent session ended",- });- });-- it("resets remote children and terminates local children", async () => {- await terminateChildSessionsStep({- serializedContext: { context: "serialized" },- sessionState: makeSessionState([- parkedHandle({ id: "ag_remote:1", kind: "agent/remote", sessionId: "session-remote" }),- runningHandle({ id: "ag_local:1", kind: "agent/local", sessionId: "session-local" }),- ]),- });-- expect(cancelRunMock).toHaveBeenCalledExactlyOnceWith("world", "session-local", {- cancelReason: "Parent session ended",- });- expect(resolveRemoteAgentForActionMock).toHaveBeenCalledWith({- dynamicRemoteAgent: undefined,- nodeId: "subagents/research",- registry: COMPILED_BUNDLE.subagentRegistry.subagentsByNodeId,- remoteAgentName: "research",- });- expect(resetRemoteAgentSessionMock).toHaveBeenCalledWith({- remote: expect.objectContaining({ url: "https://remote.example.com" }),- sessionId: "session-remote",- });- });-- it("does not send current credentials to a legacy child's previous URL", async () => {- resolveRemoteAgentForActionMock.mockReturnValue({- name: "research",- url: "https://new-remote.example.com",- });-- await terminateChildSessionsStep({- serializedContext: { context: "serialized" },- sessionState: makeSessionState([- parkedHandle({ id: "ag_remote:1", kind: "agent/remote", sessionId: "session-remote" }),- ]),- });-- expect(resetRemoteAgentSessionMock).toHaveBeenCalledWith({- headers: {},- remote: { name: "research", url: "https://remote.example.com" },- sessionId: "session-remote",- });- });-- it("uses fresh current credentials when a legacy child's URL still matches", async () => {- const auth = vi.fn();- const headers = vi.fn();- resolveRemoteAgentForActionMock.mockReturnValue({- auth,- headers,- name: "research",- url: "https://remote.example.com",- });-- await terminateChildSessionsStep({- serializedContext: { context: "serialized" },- sessionState: makeSessionState([- parkedHandle({ id: "ag_remote:1", kind: "agent/remote", sessionId: "session-remote" }),- ]),- });-- expect(resetRemoteAgentSessionMock).toHaveBeenCalledWith({- remote: expect.objectContaining({- auth,- headers,- name: "research",- url: "https://remote.example.com",- }),- sessionId: "session-remote",- });- });-- it("resets a remote child with its creation-time credential resolver", async () => {- await terminateChildSessionsStep({- serializedContext: { context: "serialized" },- sessionState: makeSessionState([- parkedHandle({- credentialResolver: { resolverId: "dynamic-credentials-step" },- id: "ag_remote:1",- kind: "agent/remote",- sessionId: "session-remote",- }),- ]),- });-- expect(getDynamicSubagentSelectionMock).not.toHaveBeenCalled();- expect(resolveRemoteAgentForActionMock).not.toHaveBeenCalled();- expect(resolveRemoteAgentStreamHeadersMock).toHaveBeenCalledWith({- bundle: COMPILED_BUNDLE,- name: "research",- resolverId: "dynamic-credentials-step",- url: "https://remote.example.com",- });- expect(resetRemoteAgentSessionMock).toHaveBeenCalledWith({- headers: { authorization: "Bearer fresh" },- remote: { name: "research", url: "https://remote.example.com" },- sessionId: "session-remote",- });- });-- it("does not invent credentials for a child created without a resolver", async () => {- await terminateChildSessionsStep({- serializedContext: { context: "serialized" },- sessionState: makeSessionState([- parkedHandle({- credentialResolver: {},- id: "ag_remote:1",- kind: "agent/remote",- sessionId: "session-remote",- }),- ]),- });-- expect(getDynamicSubagentSelectionMock).not.toHaveBeenCalled();- expect(resolveRemoteAgentStreamHeadersMock).not.toHaveBeenCalled();- expect(resetRemoteAgentSessionMock).toHaveBeenCalledWith({- headers: {},- remote: { name: "research", url: "https://remote.example.com" },- sessionId: "session-remote",- });- });-- it("skips a starting handle that has no session id yet", async () => {- await terminateChildSessionsStep({- sessionState: makeSessionState([- startingHandle({ id: "ag_local:starting", kind: "agent/local" }),- parkedHandle({ id: "ag_self:1", kind: "agent/self", sessionId: "session-self" }),- ]),- });-- expect(cancelRunMock).toHaveBeenCalledExactlyOnceWith("world", "session-self", {- cancelReason: "Parent session ended",- });- });-- it("continues terminating children after one termination fails", async () => {- const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});- cancelRunMock- .mockRejectedValueOnce(new Error("termination unavailable"))- .mockResolvedValueOnce(undefined);-- try {- await expect(- terminateChildSessionsStep({- sessionState: makeSessionState([- runningHandle({ id: "ag_child:1", kind: "agent/local", sessionId: "session-1" }),- parkedHandle({ id: "ag_child:2", kind: "agent/self", sessionId: "session-2" }),- ]),- }),- ).resolves.toBeUndefined();-- expect(cancelRunMock).toHaveBeenCalledTimes(2);- expect(errorSpy).toHaveBeenCalledWith(- "[eve:execution.terminate-child-sessions] failed to terminate child session",- expect.objectContaining({- agentId: "ag_child:1",- childSessionId: "session-1",- }),- );- } finally {- errorSpy.mockRestore();- }- });-});--type LocalAddressKind = "agent/local" | "agent/self";-type AddressKind = LocalAddressKind | "agent/remote";--function makeIdentity(id: string): { id: string; name: string; nodeId: string } {- return { id, name: "research", nodeId: "subagents/research" };-}--function makeAddress(- kind: AddressKind,- sessionId: string,- credentialResolver?: { readonly resolverId?: string },-) {- return kind === "agent/remote"- ? {- callbackBaseUrl: "https://parent.example.com",- credentialResolver,- kind,- sessionId,- url: "https://remote.example.com",- }- : { continuationToken: `${sessionId}:token`, kind, sessionId };-}--function runningHandle(input: {- readonly credentialResolver?: { readonly resolverId?: string };- readonly id: string;- readonly kind: AddressKind;- readonly sessionId: string;-}): AgentHandle {- return {- address: makeAddress(input.kind, input.sessionId, input.credentialResolver),- identity: makeIdentity(input.id),- operation: {- callId: "call-1",- id: `op-${input.id}`,- kind: "start",- parentTurnId: "turn-1",- },- phase: "running",- };-}--function parkedHandle(input: {- readonly credentialResolver?: { readonly resolverId?: string };- readonly id: string;- readonly kind: AddressKind;- readonly sessionId: string;-}): AgentHandle {- return {- address: makeAddress(input.kind, input.sessionId, input.credentialResolver),- identity: makeIdentity(input.id),- lastStatus: "ready",- phase: "parked",- };-}--function startingHandle(input: {- readonly id: string;- readonly kind: LocalAddressKind;-}): AgentHandle {- return {- identity: makeIdentity(input.id),- operation: {- callId: "call-1",- id: `op-${input.id}`,- kind: "start",- parentTurnId: "turn-1",- },- phase: "starting",- target: { continuationToken: "pending:token", kind: input.kind },- };-}--function makeSessionState(handles: readonly AgentHandle[]): DurableSessionState {- return {- continuationToken: "parent-token",- emissionState: {- sequence: 0,- sessionStarted: true,- stepIndex: 0,- turnId: "turn-1",- },- hasProxyInputRequests: false,- sessionId: "parent-session",- snapshot: {- session: {- agent: { system: "" },- continuationToken: "parent-token",- history: [],- sessionId: "parent-session",- state: { [AGENT_HANDLES_STATE_KEY]: { handles } },- },- },- version: 1,- };-}diff --git a/packages/eve/src/execution/terminate-child-sessions-step.ts b/packages/eve/src/execution/terminate-child-sessions-step.tsindex 0e20e94bf..ae1b3ef2a 100644--- a/packages/eve/src/execution/terminate-child-sessions-step.ts+++ b/packages/eve/src/execution/terminate-child-sessions-step.ts@@ -1,36 +1,24 @@-import { deserializeContext } from "#context/serialize.js";-import type { ContextContainer } from "#context/container.js";-import { getDynamicSubagentSelection } from "#context/dynamic-subagent-lifecycle.js";-import { readDurableSession, type DurableSessionState } from "#execution/durable-session-store.js";import {- resetRemoteAgentSession,- resolveRemoteAgentForAction,- resolveRemoteAgentStreamHeaders,-} from "#subagents/remote-dispatch.js";-import { getAgentHandleStore } from "#subagents/handles/store.js";+ readDurableSession,+ type DurableSession,+ type DurableSessionState,+} from "#execution/durable-session-store.js";+import { cancelWorkflowToolRun } from "#execution/tools/workflow/cancel.js";+import { liveTaskRuns, readTaskTable } from "#execution/tasks/table.js";import { createLogger, logError } from "#internal/logging.js";-import { cancelRun, getWorld } from "#internal/workflow/runtime.js";-import { BundleKey, type CompiledBundle } from "#runtime/sessions/runtime-context-keys.js";const log = createLogger("execution.terminate-child-sessions");/**- * Terminates children the parent holds handles to when the parent session- * ends.- *- * Every nonterminal `agent/local`/`agent/self` handle is covered: `running`- * and `parked` handles carry a confirmed address; a `starting` handle has- * no session id yet (the child may not exist), so it is skipped with a- * debug log rather than guessed at. Remote handles are retired through the- * authenticated session-reset route.+ * Session end ends every task, including cancelled runs that haven't+ * confirmed yet. Each run ends the agent sessions it opened.*/export async function terminateChildSessionsStep(input: {- readonly serializedContext?: Record<string, unknown>;readonly sessionState: DurableSessionState;}): Promise<void> {"use step";- let session;+ let session: DurableSession;try {session = readDurableSession(input.sessionState);} catch (error) {@@ -40,88 +28,12 @@ export async function terminateChildSessionsStep(input: {return;}- const handles = getAgentHandleStore(session.state)?.handles ?? [];- const hasRemoteHandle = handles.some(- (handle) => "address" in handle && handle.address.kind === "agent/remote",- );- let runtimeContext:- | {- readonly bundle: CompiledBundle;- readonly ctx: ContextContainer;- }- | undefined;- if (hasRemoteHandle) {- if (input.serializedContext === undefined) {- throw new Error("Child finalization requires serialized runtime context.");- }- const ctx = await deserializeContext(input.serializedContext);- runtimeContext = { bundle: ctx.require(BundleKey), ctx };- }-- if (handles.length === 0) {- return;- }+ await stopTaskRuns(session);+}- for (const handle of handles) {- if (!("address" in handle)) {- log.debug("skipping unaddressed child", {- agentId: handle.identity.id,- parentSessionId: session.sessionId,- });- continue;- }- try {- if (handle.address.kind === "agent/remote") {- if (handle.address.credentialResolver !== undefined) {- const resolverId = handle.address.credentialResolver.resolverId;- const headers =- resolverId === undefined- ? {}- : await resolveRemoteAgentStreamHeaders({- bundle: runtimeContext!.bundle,- name: handle.identity.name,- resolverId,- url: handle.address.url,- });- await resetRemoteAgentSession({- headers,- remote: { name: handle.identity.name, url: handle.address.url },- sessionId: handle.address.sessionId,- });- } else {- // Compatibility for handles written before resolver identity was persisted.- const selection = getDynamicSubagentSelection(- runtimeContext!.ctx,- handle.identity.nodeId,- );- const remote = resolveRemoteAgentForAction({- dynamicRemoteAgent: selection?.kind === "remote" ? selection.remoteAgent : undefined,- nodeId: handle.identity.nodeId,- registry: runtimeContext!.bundle.subagentRegistry.subagentsByNodeId,- remoteAgentName: handle.identity.name,- });- if (remote.url === handle.address.url) {- await resetRemoteAgentSession({ remote, sessionId: handle.address.sessionId });- } else {- await resetRemoteAgentSession({- headers: {},- remote: { name: handle.identity.name, url: handle.address.url },- sessionId: handle.address.sessionId,- });- }- }- } else {- await cancelRun(await getWorld(), handle.address.sessionId, {- cancelReason: "Parent session ended",- });- }- } catch (error) {- logError(log, "failed to terminate child session", error, {- agentId: handle.identity.id,- childSessionId: handle.address.sessionId,- kind: handle.address.kind,- parentSessionId: session.sessionId,- });- }- }+async function stopTaskRuns(session: DurableSession): Promise<void> {+ const runs = liveTaskRuns(readTaskTable(session.state));+ await Promise.all(+ runs.map((run) => cancelWorkflowToolRun(run, { kind: "end", reason: "The session ended." })),+ );}diff --git a/packages/eve/src/execution/tools/agent-router-workflow.ts b/packages/eve/src/execution/tools/agent-router-workflow.tsindex 53921019b..993bfbde8 100644--- a/packages/eve/src/execution/tools/agent-router-workflow.ts+++ b/packages/eve/src/execution/tools/agent-router-workflow.ts@@ -4,7 +4,7 @@ import type { WorkflowToolContext } from "#tools/workflow-definition.js";import type { AgentRouterInput } from "#execution/tools/agent-router.js";/** Routes one task through the complete workflow agent metadata snapshot. */-export async function executeAgentRouterTool(+export async function runAgentRouterTask(input: AgentRouterInput,ctx: WorkflowToolContext,): Promise<JsonValue> {diff --git a/packages/eve/src/execution/tools/agent-router.ts b/packages/eve/src/execution/tools/agent-router.tsindex 6a863aba9..86fc470d8 100644--- a/packages/eve/src/execution/tools/agent-router.ts+++ b/packages/eve/src/execution/tools/agent-router.ts@@ -1,6 +1,6 @@import { defineJsonSchema } from "#tools/schema.js";-export { executeAgentRouterTool } from "#execution/tools/agent-router-workflow.js";+export { runAgentRouterTask } from "#execution/tools/agent-router-workflow.js";export const AGENT_ROUTER_TOOL_DESCRIPTION ="Route a task to the best available subagent based on each subagent's declared description.";diff --git a/packages/eve/src/execution/tools/subagent/emit-event-step.integration.test.ts b/packages/eve/src/execution/tools/subagent/emit-event-step.integration.test.tsdeleted file mode 100644index a4827a3fe..000000000--- a/packages/eve/src/execution/tools/subagent/emit-event-step.integration.test.ts+++ /dev/null@@ -1,282 +0,0 @@-import { afterEach, beforeEach, expect, it, vi } from "vitest";--import { setLogRecordSubscriber, type LogRecord } from "#internal/logging.js";--import { ContextContainer, contextStorage, loadContext } from "#context/container.js";-import {- AuthKey,- DynamicSkillManifestKey,- SandboxKey,- SessionIdKey,- SessionKey,- SessionTitleKey,-} from "#context/keys.js";-import { deserializeContext, serializeContext } from "#context/serialize.js";-import { emitSubagentEventStep } from "#execution/tools/subagent/emit-event-step.js";-import { createSessionEventSink } from "#execution/publish-session-events.js";-import { createStubSandboxRegistry } from "#internal/testing/stub-sandbox-registry.js";-import { createTestSessionState } from "#internal/testing/session-state.js";-import type { MessageStreamEvent, UnstampedMessageStreamEvent } from "#protocol/message.js";-import type { HookContext, HookEvent, StreamEventHook } from "#public/definitions/hook.js";-import { createRuntimeHookRegistry } from "#runtime/hooks/registry.js";-import {- BundleKey,- ChannelKey,- type CompiledBundle,-} from "#runtime/sessions/runtime-context-keys.js";--vi.mock("#context/serialize.js", () => ({- deserializeContext: vi.fn(),- serializeContext: vi.fn(),-}));--const records: LogRecord[] = [];-beforeEach(() => {- vi.resetAllMocks();- records.length = 0;- setLogRecordSubscriber((record) => records.push(record));-});-afterEach(() => setLogRecordSubscriber(undefined));--const events: UnstampedMessageStreamEvent[] = [- {- type: "subagent.called",- data: {- callId: "call",- name: "research",- toolName: "research",- sessionId: "parent",- childSessionId: "child",- childStreamPath: "/child",- workflowId: "workflow",- turnId: "turn",- sequence: 0,- },- },- {- type: "subagent.completed",- data: { callId: "call", subagentName: "research", output: "done" },- },-];--it.each(- events.flatMap((event) =>- (["typed", "wildcard", "both"] as const).flatMap((subscription) =>- [false, true].map((fails) => ({ event, subscription, fails })),- ),- ),-)(- "restores parent context for $event.type ($subscription, hook fails: $fails)",- async ({ event, subscription, fails }) => {- const calls: string[] = [];- const ctx = new ContextContainer();- ctx.set(SessionIdKey, "parent");- ctx.set(AuthKey, null);- ctx.set(DynamicSkillManifestKey, {- policy: [- {- name: "policy",- description: "Parent delegation policy",- markdown: "Delegate carefully.",- },- ],- });- // SessionKey is virtual: a production deserializer cannot restore it.- expect(ctx.has(SessionKey)).toBe(false);- expect(ctx.has(SandboxKey)).toBe(false);- ctx.set(ChannelKey, {- kind: "test",- state: {},- [event.type](_data: unknown, adapterCtx: { state: unknown }) {- calls.push("adapter");- adapterCtx.state = { delivered: true };- },- });- const handler = (kind: string) => async (received: HookEvent, hookCtx: HookContext) => {- expect(hookCtx.session.id).toBe("parent");- expect(hookCtx.session.auth).toEqual({ current: null, initiator: null });- expect(received.type).toBe(event.type);- if (received.type === "subagent.completed") expect(received.data.output).toBe("done");- expect(loadContext()).toBe(ctx);- expect(received).toEqual(JSON.parse(new TextDecoder().decode(chunks[0])));- expect(ctx.has(SandboxKey)).toBe(true);- calls.push(kind);- ctx.set(SessionTitleKey, "Research event received");- if (fails) throw new Error("subagent subscriber failed");- };- const handlers: Record<string, StreamEventHook<MessageStreamEvent>> = {};- if (subscription !== "wildcard") handlers[event.type] = handler("typed");- if (subscription !== "typed") handlers["*"] = handler("wildcard");- const hookRegistry = createRuntimeHookRegistry([- {- slug: "subagent-events",- logicalPath: "hooks/subagent-events.ts",- sourceId: "hooks/subagent-events.ts",- sourceKind: "module",- exportName: undefined,- events: handlers,- },- ]);- const bundle: Partial<CompiledBundle> = {- graph: {- root: { nodeId: "__root__", sandboxRegistry: createStubSandboxRegistry() },- } as CompiledBundle["graph"],- resolvedAgent: { config: {} } as CompiledBundle["resolvedAgent"],- turnAgent: {- id: "parent",- model: { id: "openai/gpt-5.5" },- tools: [],- instructions: [],- workspaceSpec: { rootEntries: [] },- },- compiledArtifactsSource: { kind: "bundled" },- hookRegistry,- };- ctx.set(BundleKey, bundle as CompiledBundle);- vi.mocked(deserializeContext).mockResolvedValue(ctx);- vi.mocked(serializeContext).mockImplementation((context) =>- Object.fromEntries([...context.entries()].map(([key, value]) => [key.name, value])),- );- const chunks: Uint8Array[] = [];- const stream = new WritableStream<Uint8Array>({- write(chunk) {- expect(ctx.has(SessionKey)).toBe(true);- expect(ctx.has(SandboxKey)).toBe(true);- calls.push("stream");- chunks.push(chunk);- },- });- const sessionState = createTestSessionState({ sessionId: "parent" });- const emitted = emitSubagentEventStep({- event,- sessionWritable: stream,- serializedContext: {},- sessionState,- });- const firstHandler = subscription === "wildcard" ? "wildcard" : "typed";- const result = await emitted;- expect(result.serializedContext[SessionTitleKey.name]).toBe("Research event received");- expect(result.serializedContext[SessionKey.name]).toBeUndefined();- expect(result.serializedContext[SandboxKey.name]).toBeUndefined();- expect(result.sessionState.snapshot.session.sandboxState).toEqual({ session: null });- expect(result.serializedContext[DynamicSkillManifestKey.name]).toEqual(- ctx.require(DynamicSkillManifestKey),- );- expect(ctx.require(ChannelKey).state).toEqual({ delivered: true });- expect(calls).toEqual([- "adapter",- "stream",- firstHandler,- ...(subscription === "both" ? ["wildcard"] : []),- ]);- const subscribers = [firstHandler, ...(subscription === "both" ? ["wildcard"] : [])];- expect(records).toMatchObject(- fails- ? subscribers.map((subscriber) => ({- level: "error",- fields: {- hook: "subagent-events",- subscription: subscriber === "typed" ? event.type : "*",- eventType: event.type,- sessionId: "parent",- error: { message: expect.stringMatching(/^(?:Error: )?subagent subscriber failed$/) },- },- }))- : [],- );- expect(chunks).toHaveLength(1);- expect(new TextDecoder().decode(chunks[0])).toContain(`"type":"${event.type}"`);- expect(stream.locked).toBe(false);- },-);--it.each(events)(- "the event sink publishes $type without preparing hook or model context",- async (event) => {- const ctx = new ContextContainer();- ctx.set(SessionIdKey, "parent");- ctx.set(AuthKey, null);- ctx.set(ChannelKey, { kind: "test" });- const hook = vi.fn(() => {- throw new Error("publication invoked a hook");- });- const bundle: Partial<CompiledBundle> = {- get graph(): never {- throw new Error("publication read model configuration");- },- hookRegistry: createRuntimeHookRegistry([- {- slug: "audit",- logicalPath: "hooks/audit.ts",- sourceId: "hooks/audit.ts",- sourceKind: "module",- exportName: undefined,- events: { "*": hook },- },- ]),- };- ctx.set(BundleKey, bundle as CompiledBundle);- const chunks: Uint8Array[] = [];- const stream = new WritableStream<Uint8Array>({- write(chunk) {- chunks.push(chunk);- },- });- const sink = createSessionEventSink({- ctx,- sessionWritable: stream,- sessionId: "parent",- });- try {- await contextStorage.run(ctx, () => sink.emit(event));- } finally {- sink.release();- }- expect(hook).not.toHaveBeenCalled();- expect(ctx.has(SessionKey)).toBe(false);- expect(ctx.has(SandboxKey)).toBe(false);- expect(chunks).toHaveLength(1);- expect(stream.locked).toBe(false);- },-);--it("fails hook context setup before publishing so a retry cannot duplicate the event", async () => {- const ctx = new ContextContainer();- ctx.set(SessionIdKey, "parent");- ctx.set(AuthKey, null);- ctx.set(ChannelKey, { kind: "test" });- const hook = vi.fn();- const bundle: Partial<CompiledBundle> = {- resolvedAgent: { config: {} } as CompiledBundle["resolvedAgent"],- turnAgent: { id: "parent" } as CompiledBundle["turnAgent"],- hookRegistry: createRuntimeHookRegistry([- {- slug: "audit",- logicalPath: "hooks/audit.ts",- sourceId: "hooks/audit.ts",- sourceKind: "module",- exportName: undefined,- events: { "*": hook },- },- ]),- };- ctx.set(BundleKey, bundle as CompiledBundle);- vi.mocked(deserializeContext).mockResolvedValue(ctx);- const chunks: Uint8Array[] = [];- const stream = new WritableStream<Uint8Array>({- write(chunk) {- chunks.push(chunk);- },- });- await expect(- emitSubagentEventStep({- event: events[0]!,- sessionWritable: stream,- serializedContext: {},- sessionState: { ...createTestSessionState({ sessionId: "parent" }), version: 0 as never },- }),- ).rejects.toThrow("Unsupported session checkpoint");- expect(chunks).toHaveLength(0);- expect(hook).not.toHaveBeenCalled();- expect(stream.locked).toBe(false);-});diff --git a/packages/eve/src/execution/tools/subagent/emit-event-step.ts b/packages/eve/src/execution/tools/subagent/emit-event-step.tsdeleted file mode 100644index 1ba3fbcfc..000000000--- a/packages/eve/src/execution/tools/subagent/emit-event-step.ts+++ /dev/null@@ -1,15 +0,0 @@-import {- publishSessionEvents,- type PublishedSessionEvents,- type SessionStepState,-} from "#execution/publish-session-events.js";-import type { UnstampedMessageStreamEvent } from "#protocol/message.js";--/** Publishes a subagent notification without model preparation. */-export async function emitSubagentEventStep(- input: SessionStepState & { readonly event: UnstampedMessageStreamEvent },-): Promise<PublishedSessionEvents> {- "use step";-- return await publishSessionEvents(input, [input.event]);-}diff --git a/packages/eve/src/execution/tools/subagent/invoke-agent.test.ts b/packages/eve/src/execution/tools/subagent/invoke-agent.test.tsdeleted file mode 100644index 90918ff3c..000000000--- a/packages/eve/src/execution/tools/subagent/invoke-agent.test.ts+++ /dev/null@@ -1,545 +0,0 @@-import { beforeEach, describe, expect, it, vi } from "vitest";--import {- ask,- attachWorkflowToolRunContext,- WorkflowToolRunAsks,-} from "#execution/tools/workflow/ask.js";-import type { WorkflowToolRunRef } from "#execution/tools/workflow/messages.js";-import type { WorkflowToolRunInbox } from "#execution/tools/workflow/owner.js";-import type { AgentSessionContext } from "#execution/agent-sessions/context.js";-import {- invokeAgent,- type AgentInvocationReply,- type InternalAgentInput,- validateAgentInput,-} from "#execution/tools/subagent/invoke-agent.js";-import type { ToolContext } from "#tools/definition.js";--const mocks = vi.hoisted(() => ({- createHook: vi.fn(),- disposeHook: vi.fn(),- resumeHook: vi.fn(),-}));--vi.mock("#compiled/@workflow/core/index.js", async (importOriginal) => ({- ...(await importOriginal()),- createHook: mocks.createHook,-}));-vi.mock("#execution/hook-ownership.js", () => ({- disposeHook: mocks.disposeHook,-}));-vi.mock("#execution/tools/workflow/resume-hook-step.js", () => ({- resumeHookStep: (...args: unknown[]) => mocks.resumeHook(...args),-}));-beforeEach(() => vi.resetAllMocks());--const agentContext = {} as AgentSessionContext;--function runOwner(inbox: string): WorkflowToolRunInbox {- return {- sent: 0,- send: async (message) => {- await mocks.resumeHook(inbox, message);- },- };-}--function invokeResearch(- ctx: ToolContext,- input: Pick<InternalAgentInput, "message" | "outputSchema">,-) {- return invokeAgent(ctx, { ...input, target: "research" }, { invocationId: "call-1:agent-reply" });-}--describe("workflow helper context errors", () => {- it.each([- ["ordinary tool", { callId: "call-1", session: {} }],- ["channel handler", { from() {}, to() {}, waitUntil() {} }],- ["schedule handler", { to() {}, waitUntil() {}, appAuth: {} }],- ["missing context", undefined],- ["null context", null],- ])("rejects %s before creating hooks or dispatching work", async (_name, context) => {- const ctx = context as never;- expect(() => ask(ctx, { prompt: "Continue?" })).toThrow(- "ctx.ask() requires a defineWorkflowTool() executor context.",- );- expect(mocks.createHook).not.toHaveBeenCalled();- expect(mocks.resumeHook).not.toHaveBeenCalled();- });-});--describe("agent invocation input", () => {- it.each([null, [], "object"])("rejects a non-object output schema (%j)", (outputSchema) => {- expect(() =>- validateAgentInput({- message: "Review",- outputSchema: outputSchema as never,- target: "reviewer",- }),- ).toThrow('Agent tool "reviewer" `outputSchema` must be a JSON Schema object.');- });-});--describe("workflow agent invocation routing", () => {- it("stops waiting when the workflow body is cancelled", async () => {- const controller = new AbortController();- mocks.createHook.mockReturnValue({- [Symbol.asyncIterator]: () => ({ next: () => new Promise(() => {}) }),- token: "agent-reply",- });- const ctx = { abortSignal: controller.signal, callId: "call-1" } as ToolContext;- attachWorkflowToolRunContext(ctx, {- asks: new WorkflowToolRunAsks("run-1"),- control: "control",- from: {- callId: "call-1",- input: { message: "Find it" },- runId: "run-1",- sequence: 0,- stepIndex: 0,- toolName: "research",- turnId: "turn-1",- },- agentContext,- owner: runOwner("owner-inbox"),- });-- const result = invokeResearch(ctx, { message: "Find it" });- await vi.waitFor(() => expect(mocks.resumeHook).toHaveBeenCalledOnce());- controller.abort(new Error("task cancelled"));-- await expect(result).rejects.toThrow("task cancelled");- expect(mocks.disposeHook).toHaveBeenCalledOnce();- });-- it("sends the invocation through the task owner after admission", async () => {- const result = {- callId: "call-1:agent-reply",- kind: "subagent-result" as const,- origin: "child" as const,- outcome: {- kind: "parked" as const,- result: { kind: "succeeded" as const, output: { findings: ["available"] } },- usageDelta: {- cacheReadTokens: 0,- cacheWriteTokens: 0,- inputTokens: 0,- outputTokens: 0,- },- },- output: { findings: ["available"] },- subagentName: "research",- };- const replies: AgentInvocationReply[] = [- { kind: "runtime-action-result", results: [result] },- { kind: "agent-settled", callId: result.callId },- ];- mocks.createHook.mockReturnValue({- [Symbol.asyncIterator]: () => ({- next: async () =>- replies.length > 0- ? { done: false as const, value: replies.shift()! }- : { done: true as const, value: undefined },- }),- token: "agent-reply",- });- mocks.resumeHook.mockImplementation(async () => undefined);- const from: WorkflowToolRunRef = {- callId: "call-1",- input: { message: "Find it" },- runId: "run-1",- sequence: 0,- stepIndex: 0,- toolName: "research",- turnId: "turn-1",- };- const ctx = { callId: "call-1" } as ToolContext;- attachWorkflowToolRunContext(ctx, {- asks: new WorkflowToolRunAsks("run-1"),- control: "control",- from,- agentContext,- owner: runOwner("owner-inbox"),- });-- const outputSchema = {- properties: { findings: { items: { type: "string" }, type: "array" } },- required: ["findings"],- type: "object",- };- await expect(invokeResearch(ctx, { message: "Find it", outputSchema })).resolves.toEqual({- findings: ["available"],- });-- expect(mocks.resumeHook).toHaveBeenCalledWith("owner-inbox", {- kind: "request",- from,- replyTo: "agent-reply",- request: {- input: { message: "Find it", outputSchema, target: "research" },- invocationId: "call-1:agent-reply",- kind: "agent-invoke",- },- });- });-- it("waits for agent calls inside a blocking workflow tool", async () => {- const result = {- callId: "call-1:agent-reply",- kind: "subagent-result" as const,- origin: "child" as const,- outcome: {- kind: "parked" as const,- result: { kind: "succeeded" as const, output: "inline" },- usageDelta: {- cacheReadTokens: 0,- cacheWriteTokens: 0,- inputTokens: 0,- outputTokens: 0,- },- },- output: "inline",- subagentName: "research",- };- mocks.createHook.mockReturnValue({- [Symbol.asyncIterator]: () => ({- next: vi- .fn()- .mockResolvedValueOnce({- done: false,- value: { kind: "runtime-action-result", results: [result] },- })- .mockResolvedValueOnce({- done: false,- value: { kind: "agent-settled", callId: "call-1:agent-reply" },- })- .mockResolvedValue({ done: true }),- }),- token: "agent-reply",- });- const ctx = { callId: "call-1" } as ToolContext;- attachWorkflowToolRunContext(ctx, {- asks: new WorkflowToolRunAsks("run-1"),- control: "control",- from: {- callId: "call-1",- input: { message: "Find it" },- runId: "run-1",- sequence: 0,- stepIndex: 0,- toolName: "research",- turnId: "turn-1",- },- agentContext,- owner: runOwner("owner-inbox"),- });-- await expect(invokeResearch(ctx, { message: "Find it" })).resolves.toBe("inline");- expect(mocks.resumeHook).toHaveBeenCalledTimes(2);- expect(mocks.resumeHook).toHaveBeenNthCalledWith(1, "owner-inbox", {- kind: "request",- from: expect.objectContaining({ runId: "run-1" }),- replyTo: "agent-reply",- request: {- input: { message: "Find it", target: "research" },- invocationId: "call-1:agent-reply",- kind: "agent-invoke",- },- });- });-- it.each([false, true])(- "waits for settlement acknowledgement before returning a child result (error=%s)",- async (isError) => {- const acknowledgement = Promise.withResolvers<IteratorResult<AgentInvocationReply>>();- const childResult = {- callId: "call-1:agent-reply",- kind: "subagent-result",- origin: "child",- isError,- output: isError ? "failed" : "done",- subagentName: "research",- };- const next = vi- .fn()- .mockResolvedValueOnce({- done: false,- value: { kind: "runtime-action-result", results: [childResult] },- })- .mockImplementationOnce(() => acknowledgement.promise);- mocks.createHook.mockReturnValue({- token: "agent-reply",- [Symbol.asyncIterator]: () => ({ next }),- });- const ctx = { callId: "call-1" } as ToolContext;- attachWorkflowToolRunContext(ctx, {- asks: new WorkflowToolRunAsks("run-1"),- control: "control",- from: {- callId: "call-1",- input: {},- runId: "run-1",- sequence: 0,- stepIndex: 0,- toolName: "research",- turnId: "turn-1",- },- agentContext,- owner: runOwner("owner"),- });- const returned = vi.fn();- const output = invokeResearch(ctx, { message: "Find it" }).then(- (value) => {- returned();- return value;- },- (error) => {- returned();- return error;- },- );- await vi.waitFor(() => expect(next).toHaveBeenCalledTimes(2));- expect(returned).not.toHaveBeenCalled();- expect(mocks.disposeHook).not.toHaveBeenCalled();- acknowledgement.resolve({- done: false,- value: { kind: "agent-settled", callId: childResult.callId },- });- expect(await output).toBe(childResult.output);- expect(mocks.disposeHook).toHaveBeenCalledOnce();- },- );-- it("rejects dispatch failures without reporting a child settlement", async () => {- const failure = {- callId: "call-1:agent-reply",- isError: true as const,- kind: "subagent-result" as const,- origin: "dispatch" as const,- output: {- code: "REMOTE_AGENT_START_FAILED",- message: "The remote agent could not be started.",- },- subagentName: "research",- };- mocks.createHook.mockReturnValue({- [Symbol.asyncIterator]: () => ({- next: vi- .fn()- .mockResolvedValueOnce({- done: false,- value: { kind: "runtime-action-result", results: [failure] },- })- .mockResolvedValueOnce({- done: false,- value: { kind: "agent-settled", callId: "call-1:agent-reply" },- })- .mockResolvedValue({ done: true }),- }),- token: "agent-reply",- });- const ctx = { callId: "call-1" } as ToolContext;- attachWorkflowToolRunContext(ctx, {- asks: new WorkflowToolRunAsks("run-1"),- control: "control",- from: {- callId: "call-1",- input: { message: "Find it" },- runId: "run-1",- sequence: 0,- stepIndex: 0,- toolName: "research",- turnId: "turn-1",- },- agentContext,- owner: runOwner("owner-inbox"),- });-- await expect(invokeResearch(ctx, { message: "Find it" })).rejects.toEqual(failure.output);- expect(mocks.resumeHook).toHaveBeenCalledTimes(1);- expect(mocks.resumeHook).not.toHaveBeenCalledWith(- "owner-inbox",- expect.objectContaining({ request: expect.objectContaining({ kind: "agent-settled" }) }),- );- });-- it.each([false, true])(- "preserves child HITL coordinates and routes advertised inboxes: %s",- async (advertiseInbox) => {- const childRequest = (input: {- readonly requestId: string;- readonly stepIndex: number;- }): AgentInvocationReply => ({- callId: "call-1",- childContinuationToken: "child-continuation",- childSessionId: "child-1",- childSessionInbox: advertiseInbox ? { sessionId: "child-1" } : undefined,- event: {- requests: [- {- action: {- callId: input.requestId,- input: {},- kind: "tool-call",- toolName: "approval_gate",- },- kind: "tool-approval",- prompt: "Approve?",- requestId: input.requestId,- },- ],- sequence: 3,- stepIndex: input.stepIndex,- turnId: "turn-child",- },- kind: "subagent-input-request",- subagentName: "research",- });- const replies: AgentInvocationReply[] = [- childRequest({ requestId: "approval-1", stepIndex: 1 }),- childRequest({ requestId: "approval-2", stepIndex: 2 }),- {- kind: "runtime-action-result",- results: [- {- callId: "call-1:agent-reply",- kind: "subagent-result",- origin: "child",- output: "done",- subagentName: "research",- } as never,- ],- },- { kind: "agent-settled", callId: "call-1:agent-reply" },- ];- mocks.createHook.mockReturnValue({- [Symbol.asyncIterator]: () => ({- next: async () =>- replies.length > 0- ? { done: false as const, value: replies.shift()! }- : { done: true as const, value: undefined },- }),- token: "agent-reply",- });- mocks.resumeHook.mockImplementation(async () => undefined);- const from: WorkflowToolRunRef = {- callId: "call-1",- input: { message: "Find it" },- runId: "run-1",- sequence: 0,- stepIndex: 0,- toolName: "research",- turnId: "turn-parent",- };- const ctx = { callId: "call-1" } as ToolContext;- attachWorkflowToolRunContext(ctx, {- asks: new WorkflowToolRunAsks("run-1"),- control: "control",- from,- agentContext,- owner: runOwner("owner-inbox"),- });-- await expect(invokeResearch(ctx, { message: "Find it" })).resolves.toBe("done");-- expect(mocks.resumeHook).toHaveBeenNthCalledWith(2, "owner-inbox", {- kind: "request",- from,- replyTo: advertiseInbox ? "eve:inbox:v1:eve:session:child-1:inbox" : "child-continuation",- request: {- kind: "input-batch",- requests: [expect.objectContaining({ requestId: "approval-1" })],- },- requestCoordinates: { sequence: 3, stepIndex: 1, turnId: "turn-child" },- });- expect(mocks.resumeHook).toHaveBeenNthCalledWith(3, "owner-inbox", {- kind: "request",- from,- replyTo: advertiseInbox ? "eve:inbox:v1:eve:session:child-1:inbox" : "child-continuation",- request: {- kind: "input-batch",- requests: [expect.objectContaining({ requestId: "approval-2" })],- },- requestCoordinates: { sequence: 3, stepIndex: 2, turnId: "turn-child" },- });- },- );-- it("forwards child authorization as an owner authorization request", async () => {- const replies: AgentInvocationReply[] = [- {- callId: "call-1",- childSessionId: "child-1",- event: {- data: {- description: "Authorize Linear",- name: "linear",- sequence: 1,- stepIndex: 2,- turnId: "turn-child",- },- type: "authorization.required",- },- kind: "subagent-authorization-event",- subagentName: "research",- },- {- kind: "runtime-action-result",- results: [- {- callId: "call-1:agent-reply",- kind: "subagent-result",- origin: "child",- output: "done",- subagentName: "research",- } as never,- ],- },- { kind: "agent-settled", callId: "call-1:agent-reply" },- ];- mocks.createHook.mockReturnValue({- [Symbol.asyncIterator]: () => ({- next: async () =>- replies.length > 0- ? { done: false as const, value: replies.shift()! }- : { done: true as const, value: undefined },- }),- token: "agent-reply",- });- mocks.resumeHook.mockImplementation(async () => undefined);- const from: WorkflowToolRunRef = {- callId: "call-1",- input: { message: "Find it", target: "research" },- runId: "run-1",- sequence: 0,- stepIndex: 2,- toolName: "research",- turnId: "turn-1",- };- const ctx = { callId: "call-1" } as ToolContext;- attachWorkflowToolRunContext(ctx, {- asks: new WorkflowToolRunAsks("run-1"),- control: "control",- from,- agentContext,- owner: runOwner("owner-inbox"),- });-- await expect(invokeResearch(ctx, { message: "Find it" })).resolves.toBe("done");-- expect(mocks.resumeHook).toHaveBeenCalledWith("owner-inbox", {- kind: "request",- from,- replyTo: "agent-reply",- request: {- event: expect.objectContaining({ kind: "subagent-authorization-event" }),- kind: "authorization-request",- },- });- expect(mocks.resumeHook).not.toHaveBeenCalledWith(- "owner-inbox",- expect.objectContaining({ kind: "report" }),- );- });-});diff --git a/packages/eve/src/execution/tools/subagent/invoke-agent.ts b/packages/eve/src/execution/tools/subagent/invoke-agent.tsdeleted file mode 100644index fd1f14a7f..000000000--- a/packages/eve/src/execution/tools/subagent/invoke-agent.ts+++ /dev/null@@ -1,155 +0,0 @@-import { createHook } from "#compiled/@workflow/core/index.js";--import type { RuntimeActionResultHookPayload } from "#channel/types.js";-import {- forwardAgentSessionRequest,- type AgentSessionRequest,-} from "#execution/agent-sessions/requests.js";-import { readWorkflowToolRunOwner, readWorkflowToolRunRef } from "#execution/tools/workflow/ask.js";-import type { RuntimeSubagentChildResult, RuntimeSubagentResult } from "#shared/action-types.js";-import type { JsonValue } from "#shared/json.js";-import type { JsonObject } from "#shared/json.js";-import { disposeHook } from "#execution/hook-ownership.js";-import type { ToolContext } from "#tools/definition.js";--export type InternalAgentInput = {- readonly agentId?: string;- readonly message: string;- readonly outputSchema?: JsonObject;- readonly target: string;-};--/**- * Asks the owning session to spawn an agent for a workflow tool run. Spawning- * needs owner-held material (auth, capabilities, the agent handle- * store) that a workflow tool body never has.- */-export interface AgentInvocationRequest {- readonly input: InternalAgentInput;- readonly invocationId: string;- readonly kind: "agent-invoke";-}--/**- * Tells the owning session that an owner-spawned agent replied to the run, so- * the owner can release the handle it reserved for `agent-invoke`.- */-export interface AgentSettlementRequest {- readonly kind: "agent-settled";- readonly result: RuntimeSubagentChildResult;-}--export type AgentInvocationReply =- | AgentSessionRequest- | RuntimeActionResultHookPayload- | { readonly kind: "agent-settled"; readonly callId: string };--/**- * Invokes an agent for one of the model's agent tools, whose tool call id is- * the invocation id. The owning session spawns the child and leases its handle.- */-export async function invokeAgent(- ctx: ToolContext,- input: InternalAgentInput,- options: { readonly invocationId: string },-): Promise<JsonValue> {- validateAgentInput(input);- const run = readWorkflowToolRunRef(ctx);- const owner = readWorkflowToolRunOwner(ctx);- const replies = createHook<AgentInvocationReply>();- const { invocationId } = options;- try {- await owner.send({- kind: "request",- from: run,- replyTo: replies.token,- request: { input, invocationId, kind: "agent-invoke" },- });-- const iterator = replies[Symbol.asyncIterator]();- while (true) {- const next = await nextAgentReply(iterator, ctx.abortSignal);- if (next.done) break;- const reply = next.value;- if (reply.kind === "runtime-action-result") {- const result = reply.results.find(- (candidate): candidate is RuntimeSubagentResult =>- candidate.kind === "subagent-result" && candidate.callId === invocationId,- );- if (result !== undefined) {- if (result.origin === "child") {- await owner.send({- kind: "request",- from: run,- replyTo: replies.token,- request: { kind: "agent-settled", result },- });- // The enclosing workflow cannot finish before its owner applies settlement.- for (;;) {- const acknowledgement = await nextAgentReply(iterator, ctx.abortSignal);- if (acknowledgement.done)- throw new Error(`Agent "${input.target}" closed before settlement.`);- if (- acknowledgement.value.kind === "agent-settled" &&- acknowledgement.value.callId === invocationId- )- break;- }- }- if (result.isError === true) throw result.output;- return result.output;- }- continue;- }- if (reply.kind === "agent-settled") continue;- await forwardAgentSessionRequest({- from: run,- owner,- replyTo: replies.token,- request: reply,- });- }- } finally {- try {- await disposeHook(replies);- } catch {- // A result or invocation error is authoritative; reply-hook cleanup is best effort.- }- }- throw new Error(`Agent "${input.target}" closed without a result.`);-}--async function nextAgentReply(- iterator: AsyncIterator<AgentInvocationReply>,- signal: AbortSignal | undefined,-): Promise<IteratorResult<AgentInvocationReply>> {- if (signal === undefined) return await iterator.next();- if (signal.aborted) throw signal.reason;- let rejectAbort: ((reason: unknown) => void) | undefined;- const aborted = new Promise<never>((_resolve, reject) => {- rejectAbort = reject;- });- const abort = (): void => rejectAbort?.(signal.reason);- signal.addEventListener("abort", abort, { once: true });- try {- return await Promise.race([iterator.next(), aborted]);- } finally {- signal.removeEventListener("abort", abort);- }-}--export function validateAgentInput(input: InternalAgentInput): void {- if (typeof input.message !== "string" || input.message.trim() === "") {- throw new TypeError(`Agent tool "${input.target}" requires a non-empty \`message\`.`);- }- if (- input.outputSchema !== undefined &&- (typeof input.outputSchema !== "object" ||- input.outputSchema === null ||- Array.isArray(input.outputSchema))- ) {- throw new TypeError(- `Agent tool "${input.target}" \`outputSchema\` must be a JSON Schema object.`,- );- }-}diff --git a/packages/eve/src/execution/tools/subagent/invoke-preparation.test.ts b/packages/eve/src/execution/tools/subagent/invoke-preparation.test.tsdeleted file mode 100644index 13ca8d85a..000000000--- a/packages/eve/src/execution/tools/subagent/invoke-preparation.test.ts+++ /dev/null@@ -1,101 +0,0 @@-import { describe, expect, it } from "vitest";--import { planAgentDispatch } from "#execution/tools/subagent/invoke-preparation.js";-import { captureLogRecords } from "#internal/testing/log-records.js";--const localAction = {- callId: "call-1",- description: "Research",- input: { message: "Find it" },- kind: "subagent-call" as const,- name: "research",- nodeId: "subagents/research",- subagentName: "research",-};--function session(rootSessionId?: string) {- return {- agent: { dynamicModel: true as const, system: "", tools: [] },- compaction: { recentWindowSize: 5, threshold: 10_000 },- continuationToken: "parent-token",- history: [],- rootSessionId,- sessionId: "parent",- };-}--describe("planAgentDispatch", () => {- it("rejects recursive self-agent starts outside the root session", () => {- const logs = captureLogRecords();- expect(- planAgentDispatch({- action: { ...localAction, name: "agent", nodeId: "__root__", subagentName: "agent" },- bundle: {- subagentRegistry: { subagentsByNodeId: new Map() },- turnAgent: {},- } as never,- ctx: { get: () => undefined } as never,- session: session("root") as never,- }),- ).toMatchObject({- kind: "reject",- result: { output: { code: "RECURSIVE_AGENT_ROOT_ONLY" } },- });- expect(logs.records).toContainEqual(- expect.objectContaining({- level: "warn",- message: "recursive agent call blocked outside the root session",- }),- );- });-- it("rejects a dynamic target omitted from the current selection", () => {- const logs = captureLogRecords();- expect(- planAgentDispatch({- action: localAction,- bundle: {- subagentRegistry: {- dynamicNodeIds: new Set([localAction.nodeId]),- subagentsByNodeId: new Map(),- },- turnAgent: {},- } as never,- ctx: { get: () => undefined } as never,- session: session() as never,- }),- ).toMatchObject({ kind: "reject", result: { output: { code: "SUBAGENT_UNAVAILABLE" } } });- expect(logs.records).toContainEqual(- expect.objectContaining({- level: "warn",- message: "dynamic subagent call blocked after availability changed",- }),- );- });-- it("falls back to a fresh start for an unknown agentId", () => {- const logs = captureLogRecords();- expect(- planAgentDispatch({- action: { ...localAction, input: { agentId: "unknown", message: "Find it" } },- bundle: {- subagentRegistry: {- subagentsByNodeId: new Map([- [localAction.nodeId, { definition: { description: "Research", kind: "subagent" } }],- ]),- },- turnAgent: {},- } as never,- ctx: { get: () => undefined } as never,- knownAgentIds: [],- session: session() as never,- }),- ).toMatchObject({ kind: "start", target: { action: localAction, kind: "local" } });- expect(logs.records).toContainEqual(- expect.objectContaining({- level: "warn",- message: "unknown agentId on subagent call; starting a new agent",- }),- );- });-});diff --git a/packages/eve/src/execution/tools/subagent/invoke-preparation.ts b/packages/eve/src/execution/tools/subagent/invoke-preparation.tsdeleted file mode 100644index 444157c21..000000000--- a/packages/eve/src/execution/tools/subagent/invoke-preparation.ts+++ /dev/null@@ -1,141 +0,0 @@-import type { ContextReader } from "#context/key.js";-import { deserializeContext } from "#context/serialize.js";-import {- prepareActionDispatch,- type PreparedCoordinationDispatch,-} from "#execution/coordination-dispatch-shared.js";-import { readDurableSession, type DurableSessionState } from "#execution/durable-session-store.js";-import { activeTurnId } from "#harness/active-turn-id.js";-import { getHarnessEmissionState } from "#harness/emission.js";-import type {- RuntimeAgentDispatchRequest,- RuntimeSubagentDispatchFailure,-} from "#shared/action-types.js";-import type { AgentInvocationRequest } from "#execution/tools/subagent/invoke-agent.js";-import { BundleKey, type CompiledBundle } from "#runtime/sessions/runtime-context-keys.js";-import type { DynamicRemoteAgentConfig } from "#runtime/subagents/dynamic-remote-agent-config.js";-import {- isAgentHandleAction,- type RuntimeAgentHandleAction,- type RuntimeSession,-} from "#subagents/handle-dispatch.js";-import { getAgentHandleStore } from "#subagents/handles/store.js";-import {- getDynamicSubagentSelection,- readDynamicSubagentSelections,-} from "#context/dynamic-subagent-lifecycle.js";-import { resolveAgentAction, resolveAgentStartTarget } from "#execution/agent-sessions/target.js";-import type { SubagentStartTarget } from "#execution/tools/subagent/start.js";-import { createLogger } from "#internal/logging.js";--const log = createLogger("execution.agent-invocation");--type OwnerAgentDispatchPlanEntry =- | {- readonly kind: "resume";- readonly action: RuntimeAgentHandleAction;- readonly agentId: string;- readonly dynamicRemoteAgent?: DynamicRemoteAgentConfig;- }- | { readonly kind: "reject"; readonly result: RuntimeSubagentDispatchFailure }- | { readonly kind: "start"; readonly target: SubagentStartTarget };--/** Prepares one workflow-owner agent invocation from durable inputs. */-export async function prepareOwnerAgentInvocation(input: {- readonly invocation: AgentInvocationRequest["input"];- readonly invocationId: string;- readonly knownAgentIds?: readonly string[];- readonly serializedContext: Record<string, unknown>;- readonly sessionState: DurableSessionState;-}): Promise<Omit<PreparedCoordinationDispatch<OwnerAgentDispatchPlanEntry>, "sessionState">> {- const durableSession = readDurableSession(input.sessionState);- const ctx = await deserializeContext(input.serializedContext);- const event = getHarnessEmissionState(durableSession.state);- const action = resolveAgentAction({- bundle: ctx.require(BundleKey),- callId: input.invocationId,- dynamicSelections: readDynamicSubagentSelections(ctx),- input: input.invocation,- });- return await prepareActionDispatch({- batch: {- requests: [action],- event: { ...event, turnId: activeTurnId(event) },- },- ctx,- durableSession,- fanoutSize: 1,- plan: ({ bundle, ctx: planContext, session }) => [- planAgentDispatch({- action,- bundle,- ctx: planContext,- knownAgentIds: input.knownAgentIds,- session,- }),- ],- planReusesOwnerSandbox: ({ bundle, plan }) => ownerPlanReusesSandbox({ bundle, plan }),- serializedContext: input.serializedContext,- });-}--export function planAgentDispatch(input: {- readonly action: RuntimeAgentDispatchRequest;- readonly bundle: CompiledBundle;- readonly ctx: ContextReader;- readonly knownAgentIds?: readonly string[];- readonly session: RuntimeSession;-}): OwnerAgentDispatchPlanEntry {- const knownAgentIds = new Set(- input.knownAgentIds ??- (getAgentHandleStore(input.session.state)?.handles ?? []).map((handle) => handle.identity.id),- );- const rawAgentId = input.action.input.agentId;- const agentId =- typeof rawAgentId === "string" && rawAgentId.trim() !== "" ? rawAgentId : undefined;- if (agentId !== undefined && isAgentHandleAction(input.action)) {- if (knownAgentIds.has(agentId)) {- const dynamicSubagentSelection =- input.bundle.subagentRegistry.dynamicNodeIds?.has(input.action.nodeId) === true- ? getDynamicSubagentSelection(input.ctx, input.action.nodeId)- : undefined;- return {- action: input.action,- agentId,- dynamicRemoteAgent:- input.action.kind === "remote-agent-call" && dynamicSubagentSelection?.kind === "remote"- ? dynamicSubagentSelection.remoteAgent- : undefined,- kind: "resume",- };- }- log.warn("unknown agentId on subagent call; starting a new agent", {- agentId,- callId: input.action.callId,- });- }- return resolveAgentStartTarget({- action: input.action,- bundle: input.bundle,- dynamicSelections: readDynamicSubagentSelections(input.ctx),- isRootSession: input.session.rootSessionId === undefined,- });-}--function ownerPlanReusesSandbox(input: {- readonly bundle: CompiledBundle;- readonly plan: readonly OwnerAgentDispatchPlanEntry[];-}): boolean {- return input.plan.some((entry) => {- if (entry.kind !== "start" || entry.target.kind !== "local") return false;- const action = entry.target.action;- const isSelfDelegation =- action.subagentName === "agent" &&- !input.bundle.subagentRegistry.subagentsByNodeId.has(action.nodeId);- return (- isSelfDelegation ||- input.bundle.graph?.nodesByNodeId.get(action.nodeId)?.sandboxRegistry.sandbox.definition- .kind === "parent"- );- });-}diff --git a/packages/eve/src/execution/tools/subagent/invoke-step.integration.test.ts b/packages/eve/src/execution/tools/subagent/invoke-step.integration.test.tsdeleted file mode 100644index b86cc90d5..000000000--- a/packages/eve/src/execution/tools/subagent/invoke-step.integration.test.ts+++ /dev/null@@ -1,259 +0,0 @@-import { getTurnUsageState } from "#harness/turn-tag-state.js";-import { beforeEach, describe, expect, it, vi } from "vitest";--import { createDurableSessionState, readDurableSession } from "#execution/durable-session-store.js";-import {- dispatchAgentInvocation,- settleTaskAgentInvocationStep,-} from "#execution/tools/subagent/invoke-step.js";-import { prepareOwnerAgentInvocation } from "#execution/tools/subagent/invoke-preparation.js";-import { dispatchToClaimedAgentAddress } from "#subagents/handle-dispatch.js";-import { startSubagent } from "#execution/tools/subagent/start.js";-import { getAgentHandleStore, setAgentHandleStore } from "#subagents/handles/store.js";--vi.mock("#execution/tools/subagent/invoke-preparation.js", () => ({- prepareOwnerAgentInvocation: vi.fn(),-}));-vi.mock("#subagents/handle-dispatch.js", async (importOriginal) => ({- ...(await importOriginal()),- dispatchToClaimedAgentAddress: vi.fn(),-}));-vi.mock("#execution/tools/subagent/start.js", () => ({ startSubagent: vi.fn() }));--const address = {- continuationToken: "child-token",- kind: "agent/local" as const,- sessionId: "child-session",-};-const identity = { id: "agent-1", name: "research", nodeId: "subagents/research" };--describe("blocking workflow agent continuation", () => {- beforeEach(() => {- vi.clearAllMocks();- vi.mocked(prepareOwnerAgentInvocation).mockImplementation(async (input) => {- const session = readDurableSession(input.sessionState);- return {- adapter: {},- adapterCtx: {},- auth: null,- batch: { event: { sequence: 1, stepIndex: 0, turnId: "turn-1" } },- bundle: {},- capabilities: undefined,- channelMetadata: undefined,- fanoutSize: 1,- initiatorAuth: null,- parentTraceContext: undefined,- plan: [- {- action: {- callId: input.invocationId,- description: "Research",- input: input.invocation,- kind: "subagent-call",- name: "research",- nodeId: identity.nodeId,- subagentName: identity.name,- },- agentId: identity.id,- kind: "resume",- },- ],- sandboxSessionId: "parent",- serializedContext: {},- session: {- ...session,- compaction: { recentWindowSize: 5, threshold: 10_000 },- },- } as never;- });- vi.mocked(dispatchToClaimedAgentAddress).mockImplementation(async (input) => ({- address,- callId: input.action.callId,- kind: "called",- name: "research",- session: input.currentSession,- toolName: "research",- }));- });-- it("forwards inherited activity when starting a subagent", async () => {- const activityObserver = {- sink: { url: "https://parent.example/activity", version: 1 as const },- workIdentity: {- id: "work:slack",- kind: "subagent" as const,- name: "slack",- parentId: "work:root",- rootSessionId: "root-session",- rootTurnId: "root-turn",- },- };- vi.mocked(prepareOwnerAgentInvocation).mockResolvedValue({- activityObserver,- auth: null,- batch: { event: { sequence: 1, stepIndex: 0, turnId: "turn-1" } },- bundle: {},- capabilities: undefined,- channelMetadata: undefined,- fanoutSize: 1,- initiatorAuth: null,- localDevRequest: undefined,- parentTraceContext: undefined,- plan: [- {- kind: "start",- target: {- action: {- callId: "call-1",- description: "Research",- input: { message: "Search Slack", target: "slack" },- kind: "subagent-call",- name: "slack",- nodeId: "subagents/slack",- subagentName: "slack",- },- kind: "local",- source: { description: "Search Slack", type: "local" },- },- },- ],- sandboxSessionId: "parent",- serializedContext: {},- session: {- agent: { dynamicModel: true as const, system: "", tools: [] },- compaction: { recentWindowSize: 5, threshold: 10_000 },- continuationToken: "parent-token",- history: [],- sessionId: "parent",- },- } as never);- vi.mocked(startSubagent).mockResolvedValue({- address: { continuationToken: "child-token", kind: "agent/local", sessionId: "child" },- callId: "call-1",- kind: "called",- name: "slack",- session: {} as never,- toolName: "slack",- });-- await dispatchAgentInvocation({- callbackBaseUrl: "https://parent.example",- ownerId: "workflow-run-1",- replyTo: "reply-1",- request: {- input: { message: "Search Slack", target: "slack" },- invocationId: "call-1",- kind: "agent-invoke",- },- serializedContext: {},- sessionState: createDurableSessionState({- session: {- agent: { dynamicModel: true as const, system: "", tools: [] },- compaction: { recentWindowSize: 5, threshold: 10_000 },- continuationToken: "parent-token",- history: [],- sessionId: "parent",- },- }),- });-- expect(startSubagent).toHaveBeenCalledWith(expect.objectContaining({ activityObserver }));- });-- it("settles each invocation once and ignores an old result after the handle is reused", async () => {- const session = {- agent: { dynamicModel: true as const, system: "", tools: [] },- compaction: { recentWindowSize: 5, threshold: 10_000 },- continuationToken: "parent-token",- history: [],- sessionId: "parent",- state: setAgentHandleStore(undefined, {- handles: [{ address, identity, phase: "available" }],- }),- };- let sessionState = createDurableSessionState({ session });- let previousSettlement: Parameters<typeof settleTaskAgentInvocationStep>[0] | undefined;-- for (const [index, message] of ["first", "second"].entries()) {- const callId = `workflow-call:${String(index)}`;- const dispatched = await dispatchAgentInvocation({- callbackBaseUrl: "https://parent.example",- ownerId: "workflow-run-1",- replyTo: `reply-${String(index)}`,- request: {- input: { agentId: identity.id, message, target: identity.name },- invocationId: callId,- kind: "agent-invoke",- },- serializedContext: {},- sessionState,- });- expect(dispatched).toMatchObject({ agentId: identity.id, kind: "dispatched" });- if (dispatched.kind !== "dispatched") throw new Error("Expected dispatch.");- const claimed = getAgentHandleStore(dispatched.sessionState.snapshot.session.state)?.handles;- expect(claimed).toEqual([- expect.objectContaining({ identity, ownerId: "workflow-run-1", phase: "claimed" }),- ]);-- if (previousSettlement !== undefined) {- const stale = await settleTaskAgentInvocationStep({- ...previousSettlement,- sessionState: dispatched.sessionState,- });- expect(stale.settled).toBe(false);- expect(stale.completion).toBeUndefined();- expect(stale.sessionState).toBe(dispatched.sessionState);- }- const settlement: Parameters<typeof settleTaskAgentInvocationStep>[0] = {- serializedContext: dispatched.serializedContext ?? {},- ownerId: "workflow-run-1",- result: {- callId,- kind: "subagent-result",- origin: "child",- outcome: {- kind: "parked",- result: { kind: "succeeded", output: message },- usageDelta: {- cacheReadTokens: 0,- cacheWriteTokens: 0,- inputTokens: 2,- outputTokens: 3,- },- },- output: message,- subagentName: identity.name,- },- sessionState: dispatched.sessionState,- };- const settled = await settleTaskAgentInvocationStep(settlement);- expect(settled.settled).toBe(true);- expect(settled.completion).toEqual({- type: "subagent.completed",- data: { callId, subagentName: identity.name, output: message },- });- const restored = JSON.parse(JSON.stringify(settled.sessionState));- const duplicate = await settleTaskAgentInvocationStep({- ...settlement,- sessionState: restored,- });- expect(duplicate.settled).toBe(false);- expect(duplicate.completion).toBeUndefined();- expect(duplicate.sessionState).toBe(restored);- expect(getTurnUsageState(restored.snapshot.session.state)?.session).toMatchObject({- inputTokens: 2 * (index + 1),- outputTokens: 3 * (index + 1),- });- previousSettlement = settlement;- sessionState = settled.sessionState;- expect(getAgentHandleStore(sessionState.snapshot.session.state)?.handles).toEqual([- { address, identity, phase: "available" },- ]);- }-- expect(dispatchToClaimedAgentAddress).toHaveBeenCalledTimes(2);- expect(- vi.mocked(dispatchToClaimedAgentAddress).mock.calls.map(([input]) => input.handle.address),- ).toEqual([address, address]);- });-});diff --git a/packages/eve/src/execution/tools/subagent/invoke-step.test.ts b/packages/eve/src/execution/tools/subagent/invoke-step.test.tsdeleted file mode 100644index e7776a651..000000000--- a/packages/eve/src/execution/tools/subagent/invoke-step.test.ts+++ /dev/null@@ -1,402 +0,0 @@-import { beforeEach, describe, expect, it, vi } from "vitest";--import {- dispatchAgentInvocation,- releaseAgentInvocationOwnerStep,- settleTaskAgentInvocationStep,-} from "#execution/tools/subagent/invoke-step.js";-import { dispatchToClaimedAgentAddress } from "#subagents/handle-dispatch.js";-import { startSubagent } from "#execution/tools/subagent/start.js";-import { prepareOwnerAgentInvocation } from "#execution/tools/subagent/invoke-preparation.js";-import { readDurableSession } from "#execution/durable-session-store.js";-import { getAgentHandleStore, setAgentHandleStore } from "#subagents/handles/store.js";--vi.mock("#compiled/@workflow/core/index.js", async (importOriginal) => ({- ...(await importOriginal()),- getWorkflowMetadata: vi.fn(() => ({ url: "https://parent.example" })),-}));-vi.mock("#subagents/handle-dispatch.js", async (importOriginal) => ({- ...(await importOriginal()),- dispatchToClaimedAgentAddress: vi.fn(),-}));-vi.mock("#subagents/continuation-bundle.js", () => ({- createAgentContinuationBundle: vi.fn(() => ({ nodeId: "child" })),-}));-vi.mock("#execution/tools/subagent/start.js", () => ({- startSubagent: vi.fn(),-}));-vi.mock("#execution/tools/subagent/invoke-preparation.js", () => ({- prepareOwnerAgentInvocation: vi.fn(),-}));-vi.mock("#execution/durable-session-store.js", async (importOriginal) => ({- ...(await importOriginal()),- readDurableSession: vi.fn(),-}));-const action = {- callId: "call-1",- description: "Research",- input: { message: "Find it" },- kind: "subagent-call" as const,- name: "research",- nodeId: "subagents/research",- subagentName: "research",-};-const availableRecord = {- address: { continuationToken: "child", kind: "agent/local" as const, sessionId: "child" },- identity: { id: "agent-1", name: "research", nodeId: "subagents/research" },- phase: "available" as const,-};-const session = {- agent: { system: "" },- compaction: {},- continuationToken: "parent-token",- history: [],- sessionId: "parent",- state: setAgentHandleStore(undefined, { handles: [availableRecord] }),-};-const prepared = {- adapter: {},- adapterCtx: {},- auth: null,- batch: { event: { sequence: 1, stepIndex: 2, turnId: "turn-1" } },- bundle: {},- capabilities: undefined,- channelMetadata: undefined,- fanoutSize: 1,- initiatorAuth: null,- parentTraceContext: undefined,- sandboxSessionId: "parent",- serializedContext: {},- session,-};-const called = {- address: { continuationToken: "child", kind: "agent/local" as const, sessionId: "child" },- callId: "call-1",- kind: "called" as const,- name: "research",- session: session as never,- toolName: "research",-};-beforeEach(() => {- vi.clearAllMocks();- vi.mocked(readDurableSession).mockReturnValue(session as never);-});--describe("owner agent invocation dispatch", () => {- it("resumes an addressed agent through its owning task", async () => {- vi.mocked(prepareOwnerAgentInvocation).mockResolvedValue({- ...prepared,- plan: [{ action, agentId: "agent-1", kind: "resume" }],- } as never);- vi.mocked(dispatchToClaimedAgentAddress).mockResolvedValue(called);-- const dispatched = await dispatch();-- expect(dispatchToClaimedAgentAddress).toHaveBeenCalledWith(- expect.objectContaining({- handle: expect.objectContaining({- identity: availableRecord.identity,- phase: "claimed",- ownerId: "task-1",- }),- parentToken: "agent-reply",- }),- );- expect(dispatched).toMatchObject({ agentId: "agent-1", kind: "dispatched" });- expect(getAgentHandleStore(dispatched.sessionState.snapshot.session.state)?.handles).toEqual([- expect.objectContaining({- identity: availableRecord.identity,- phase: "claimed",- ownerId: "task-1",- }),- ]);- });-- it("reuses a continuation claim admitted before the workflow body starts", async () => {- const claimed = {- ...availableRecord,- callId: "call-1",- operationId: "admission-operation",- phase: "claimed" as const,- ownerId: "task-1",- };- const claimedSession = {- ...session,- state: setAgentHandleStore(undefined, { handles: [claimed] }),- };- vi.mocked(readDurableSession).mockReturnValue(claimedSession as never);- vi.mocked(prepareOwnerAgentInvocation).mockResolvedValue({- ...prepared,- session: claimedSession,- plan: [{ action, agentId: "agent-1", kind: "resume" }],- } as never);- vi.mocked(dispatchToClaimedAgentAddress).mockResolvedValue(called);-- await dispatch();-- expect(dispatchToClaimedAgentAddress).toHaveBeenCalledWith(- expect.objectContaining({ handle: claimed }),- );- });-- it("reuses one handle across blocking invocations with the same agentId", async () => {- vi.mocked(prepareOwnerAgentInvocation).mockResolvedValue({- ...prepared,- plan: [{ action, agentId: "agent-1", kind: "resume" }],- } as never);- vi.mocked(dispatchToClaimedAgentAddress).mockResolvedValue(called);-- const first = await dispatchAgentInvocation({- callbackBaseUrl: "https://parent.example",- replyTo: "first-reply",- request: {- input: { agentId: "agent-1", message: "First", target: "research" },- invocationId: "call-1:first",- kind: "agent-invoke",- },- ownerId: "workflow-run-1",- serializedContext: {},- sessionState: {} as never,- });- expect(first.kind).toBe("dispatched");- const firstHandle =- first.kind === "dispatched"- ? getAgentHandleStore(first.sessionState.snapshot.session.state)?.handles[0]- : undefined;- expect(firstHandle).toMatchObject({- identity: { id: "agent-1" },- ownerId: "workflow-run-1",- phase: "claimed",- });-- vi.mocked(readDurableSession).mockReturnValue({- ...session,- state: setAgentHandleStore(undefined, { handles: [availableRecord] }),- } as never);- const second = await dispatchAgentInvocation({- callbackBaseUrl: "https://parent.example",- replyTo: "second-reply",- request: {- input: { agentId: "agent-1", message: "Second", target: "research" },- invocationId: "call-1:second",- kind: "agent-invoke",- },- ownerId: "workflow-run-1",- serializedContext: {},- sessionState: {} as never,- });-- expect(second).toMatchObject({ agentId: "agent-1", kind: "dispatched" });- expect(dispatchToClaimedAgentAddress).toHaveBeenCalledTimes(2);- expect(- vi- .mocked(dispatchToClaimedAgentAddress)- .mock.calls.map(([input]) => input.handle.identity.id),- ).toEqual(["agent-1", "agent-1"]);- });-- it("starts a fresh agent with task-owned handle semantics", async () => {- const reserved = {- callId: "call-1",- identity: { id: "agent-receipt", name: "research", nodeId: "subagents/research" },- operationId: "receipt-operation",- phase: "reserved" as const,- ownerId: "task-1",- };- vi.mocked(readDurableSession).mockReturnValue({- ...session,- state: setAgentHandleStore(undefined, { handles: [reserved] }),- } as never);- vi.mocked(prepareOwnerAgentInvocation).mockResolvedValue({- ...prepared,- session: {- ...session,- state: setAgentHandleStore(undefined, { handles: [reserved] }),- },- plan: [{ kind: "start", target: { action, kind: "local", source: { type: "runtime" } } }],- } as never);- vi.mocked(startSubagent).mockResolvedValue(called);-- const dispatched = await dispatch();-- expect(startSubagent).toHaveBeenCalledWith(- expect.objectContaining({ parentContinuationToken: "agent-reply" }),- );- expect(dispatched).toMatchObject({ agentId: "agent-receipt", kind: "dispatched" });- expect(startSubagent).toHaveBeenCalledWith(- expect.objectContaining({- currentSession: expect.objectContaining({- state: expect.objectContaining({- "eve.agent.handles": { handles: [reserved] },- }),- }),- }),- );- expect(getAgentHandleStore(dispatched.sessionState.snapshot.session.state)?.handles).toEqual(- expect.arrayContaining([expect.objectContaining({ ownerId: "task-1", phase: "claimed" })]),- );- });-});--describe("owner agent settlement", () => {- it.each(["parked", "terminal"] as const)("applies a %s child outcome", async (kind) => {- const claimed = {- ...availableRecord,- callId: "call-1",- operationId: "operation-1",- phase: "claimed" as const,- ownerId: "task-1",- };- vi.mocked(readDurableSession).mockReturnValue({- ...session,- state: setAgentHandleStore(session.state, { handles: [claimed] }),- } as never);-- const settled = await settleTaskAgentInvocationStep({- serializedContext: {},- result: {- callId: "call-1",- kind: "subagent-result",- origin: "child",- outcome: {- kind,- result: { kind: "succeeded", output: "done" },- usageDelta: {- cacheReadTokens: 0,- cacheWriteTokens: 0,- inputTokens: 2,- outputTokens: 1,- },- },- output: "done",- subagentName: "research",- },- ownerId: "task-1",- sessionState: {} as never,- });-- expect(settled.completion).toEqual({- type: "subagent.completed",- data: { callId: "call-1", subagentName: "research", output: "done" },- });- const handles = getAgentHandleStore(settled.sessionState.snapshot.session.state)?.handles ?? [];- expect(handles).toEqual(- kind === "parked" ? [expect.objectContaining({ phase: "available" })] : [],- );- });-- it("releases every remaining claim for a completed workflow run", async () => {- const claimed = {- ...availableRecord,- callId: "call-1",- operationId: "operation-1",- ownerId: "workflow-run-1",- phase: "claimed" as const,- };- vi.mocked(readDurableSession).mockReturnValue({- ...session,- state: setAgentHandleStore(undefined, { handles: [claimed] }),- } as never);-- const released = await releaseAgentInvocationOwnerStep({- ownerId: "workflow-run-1",- sessionState: {} as never,- });-- expect(getAgentHandleStore(released.sessionState.snapshot.session.state)?.handles).toEqual([- availableRecord,- ]);- });-- it("parks every remaining claim for a cancelled workflow run", async () => {- const claimed = {- ...availableRecord,- callId: "call-1",- operationId: "operation-1",- ownerId: "workflow-run-1",- phase: "claimed" as const,- };- vi.mocked(readDurableSession).mockReturnValue({- ...session,- state: setAgentHandleStore(undefined, { handles: [claimed] }),- } as never);-- const released = await releaseAgentInvocationOwnerStep({- cancelled: true,- ownerId: "workflow-run-1",- sessionState: {} as never,- });-- expect(getAgentHandleStore(released.sessionState.snapshot.session.state)?.handles).toEqual([- {- address: availableRecord.address,- identity: availableRecord.identity,- lastStatus: "(cancelled)",- phase: "parked",- },- ]);- });-- it("keeps a cancelled parked child resumable after settlement", async () => {- const claimed = {- ...availableRecord,- callId: "call-1",- operationId: "operation-1",- phase: "claimed" as const,- ownerId: "workflow-run-1",- };- vi.mocked(readDurableSession).mockReturnValue({- ...session,- state: setAgentHandleStore(undefined, { handles: [claimed] }),- } as never);-- const settled = await settleTaskAgentInvocationStep({- serializedContext: {},- ownerId: "workflow-run-1",- result: {- callId: "call-1",- kind: "subagent-result",- origin: "child",- outcome: {- kind: "parked",- result: { kind: "cancelled" },- usageDelta: {- cacheReadTokens: 0,- cacheWriteTokens: 0,- inputTokens: 0,- outputTokens: 0,- },- },- output: "cancelled",- subagentName: "research",- },- sessionState: {} as never,- });-- expect(settled.completion).toBeUndefined();- expect(getAgentHandleStore(settled.sessionState.snapshot.session.state)?.handles).toEqual([- {- address: availableRecord.address,- identity: availableRecord.identity,- lastStatus: "(cancelled)",- phase: "parked",- },- ]);- });-});--async function dispatch() {- return await dispatchAgentInvocation({- callbackBaseUrl: "https://parent.example",- emit: vi.fn(),- replyTo: "agent-reply",- request: {- input: { message: "Find it", target: "research" },- invocationId: "call-1",- kind: "agent-invoke",- },- ownerId: "task-1",- serializedContext: {},- sessionState: {} as never,- });-}diff --git a/packages/eve/src/execution/tools/subagent/invoke-step.ts b/packages/eve/src/execution/tools/subagent/invoke-step.tsdeleted file mode 100644index eb083575a..000000000--- a/packages/eve/src/execution/tools/subagent/invoke-step.ts+++ /dev/null@@ -1,475 +0,0 @@-import {- createAgentErrorResult,- dispatchToClaimedAgentAddress,- type DispatchOutcome,-} from "#subagents/handle-dispatch.js";-import { createAgentContinuationBundle } from "#subagents/continuation-bundle.js";-import { startSubagent } from "#execution/tools/subagent/start.js";-import { prepareOwnerAgentInvocation } from "#execution/tools/subagent/invoke-preparation.js";-import type { AgentInvocationRequest } from "#execution/tools/subagent/invoke-agent.js";-import type { RuntimeSubagentResult } from "#shared/action-types.js";-import type { HandleEventFn } from "#harness/types.js";-import {- createSubagentCalledEvent,- type SubagentCalledStreamEvent,- type SubagentCompletedStreamEvent,-} from "#protocol/message.js";-import { workflowEntryReference } from "#execution/workflow-runtime.js";-import { getWorkflowMetadata } from "#compiled/@workflow/core/index.js";-import { resolveWorkflowCallbackBaseUrl } from "#execution/workflow-callback-url.js";-import { deriveAgentOperationId } from "#subagents/handles/operation-id.js";-import { mintStartOperation } from "#execution/dispatch-start-operation.js";-import {- readDurableSession,- replaceDurableSessionSnapshot,- type DurableSessionState,-} from "#execution/durable-session-store.js";-import { projectToDurableSession } from "#execution/session.js";-import {- getAgentHandleStore,- writeHandles,- type AgentHandle,- type AgentHandleStoreCommand,- type AgentHandleStoreCommandResult,- type TaskOwnedAgentHandle,-} from "#subagents/handles/store.js";-import { applyTaskAgentHandleCommand } from "#subagents/handles/transitions.js";-import { abandonAgentInvocationOwners } from "#subagents/handles/transitions.js";-import {- AGENT_BUSY,- AGENT_MISMATCH,- AGENT_UNREACHABLE,- formatAgentBusyMessage,-} from "#subagents/agent-handle-errors.js";-import type { RuntimeSubagentChildResult } from "#shared/action-types.js";-import { clearProxyInputRequestsForChild } from "#harness/proxy-input-requests.js";-import {- accumulateSessionUsage,- getTurnUsageState,- setTurnUsageState,-} from "#harness/turn-tag-state.js";-import { prepareAgentInvocationTrace } from "#tracing/agent-invocation-coordinator.js";-import {- flushAgentInvocationTraces,- settleAgentInvocationTrace,-} from "#tracing/agent-invocation-terminal.js";--export type AgentInvocationDispatchResult =- | {- readonly kind: "dispatched";- readonly agentId: string;- readonly event: SubagentCalledStreamEvent;- readonly serializedContext?: Record<string, unknown>;- readonly sessionState: DurableSessionState;- }- | {- readonly kind: "failed";- readonly result: RuntimeSubagentResult;- readonly serializedContext?: Record<string, unknown>;- readonly sessionState: DurableSessionState;- };--/** Dispatches one owner-scoped local or remote agent invocation. */-export async function dispatchAgentInvocation(input: {- readonly callbackBaseUrl: string;- readonly emit?: HandleEventFn;- readonly replyTo: string;- readonly request: AgentInvocationRequest;- readonly serializedContext: Record<string, unknown>;- readonly sessionState: DurableSessionState;- readonly ownerId: string;-}): Promise<AgentInvocationDispatchResult> {- const durableSession = readDurableSession(input.sessionState);- const agentHandles = getAgentHandleStore(durableSession.state)?.handles ?? [];- const prepared = await prepareOwnerAgentInvocation({- invocation: input.request.input,- invocationId: input.request.invocationId,- knownAgentIds: agentHandles.map((handle) => handle.identity.id),- serializedContext: input.serializedContext,- sessionState: input.sessionState,- });- const entry = prepared.plan[0];- if (entry === undefined) {- throw new Error("Agent invocation produced no executable plan entry.");- }- if (entry.kind === "reject") {- return {- kind: "failed",- result: entry.result,- serializedContext: input.serializedContext,- sessionState: input.sessionState,- };- }- const invocationAction = entry.kind === "start" ? entry.target.action : entry.action;- const tracing = prepareAgentInvocationTrace({- conversation: prepared.inheritedConversation,- invocation: invocationAction,- ownerId: input.ownerId,- serializedContext: input.serializedContext,- sessionId: prepared.session.sessionId,- sessionState: durableSession.state,- startTimeMs: Date.now(),- turnId: prepared.batch.event.turnId,- });- let session = prepared.session;- const currentAgentHandles = (): readonly AgentHandle[] =>- getAgentHandleStore(session.state)?.handles ?? [];- const sessionState = (): DurableSessionState =>- replaceDurableSessionSnapshot({- session: projectToDurableSession(session),- state: input.sessionState,- });- const failed = async (result: RuntimeSubagentResult): Promise<AgentInvocationDispatchResult> => ({- kind: "failed",- result,- serializedContext: await flushAgentInvocationTraces(tracing.fail(result)),- sessionState: sessionState(),- });- const applyHandleCommand = (command: AgentHandleStoreCommand): AgentHandleStoreCommandResult => {- const applied = applyTaskAgentHandleCommand(session, command);- session = applied.session;- return applied.result;- };- let outcome: DispatchOutcome;- let agentId: string;- if (entry.kind === "resume") {- const existingClaims = currentAgentHandles().filter(- (handle): handle is Extract<TaskOwnedAgentHandle, { readonly phase: "claimed" }> =>- handle.phase === "claimed" &&- handle.ownerId === input.ownerId &&- handle.callId === entry.action.callId &&- handle.identity.id === entry.agentId,- );- if (existingClaims.length > 1) {- throw new Error(- `Invocation owner "${input.ownerId}" has multiple claims for "${entry.action.callId}".`,- );- }- let claimed = existingClaims[0];- if (claimed === undefined) {- const operationId = deriveAgentOperationId({- callId: entry.action.callId,- parentSessionId: prepared.session.sessionId,- parentTurnId: prepared.batch.event.turnId,- });- const claim = applyHandleCommand({- agentId: entry.agentId,- callId: entry.action.callId,- expectedTarget: entry.action.kind === "remote-agent-call" ? "remote" : "local",- invokedName:- entry.action.kind === "remote-agent-call"- ? entry.action.remoteAgentName- : entry.action.subagentName,- kind: "claim",- operationId,- ownerId: input.ownerId,- });- claimed = readClaimedHandle(claim);- if (claimed === undefined) {- return failed(createTaskClaimError(entry.action, entry.agentId, claim));- }- }- const bundle = createAgentContinuationBundle({- action: entry.action,- bundle: prepared.bundle,- dynamicRemoteAgent: entry.dynamicRemoteAgent,- });- outcome = await dispatchToClaimedAgentAddress({- action: entry.action,- auth: prepared.auth,- bundle,- currentSession: session,- handle: claimed,- parentToken: input.replyTo,- });- if (outcome.kind === "error" && outcome.deliveryPermanent === true) {- applyHandleCommand({ agentId: entry.agentId, kind: "remove", ownerId: input.ownerId });- }- agentId = claimed.identity.id;- } else {- const action = entry.target.action;- const reserved = currentAgentHandles().filter(- (handle): handle is Extract<TaskOwnedAgentHandle, { readonly phase: "reserved" }> =>- handle.phase === "reserved" &&- handle.ownerId === input.ownerId &&- handle.callId === action.callId &&- handle.identity.name === action.name &&- handle.identity.nodeId === action.nodeId,- );- const start =- reserved.length === 1- ? { identity: reserved[0]!.identity, operation: { id: reserved[0]!.operationId } }- : mintStartOperation({- callId: action.callId,- name:- action.kind === "remote-agent-call" ? action.remoteAgentName : action.subagentName,- nodeId: action.nodeId,- parentSessionId: prepared.session.sessionId,- parentTurnId: prepared.batch.event.turnId,- });- if (reserved.length > 1) {- throw new Error(- `Invocation owner "${input.ownerId}" has multiple reservations for "${action.callId}".`,- );- }- if (reserved.length === 0) {- const reservation = applyHandleCommand({- identity: start.identity,- callId: action.callId,- kind: "reserve",- operationId: start.operation.id,- ownerId: input.ownerId,- });- if (reservation.kind !== "ready") {- throw new Error(`Agent handle store rejected start operation "${start.operation.id}".`);- }- }- outcome = await startSubagent({- auth: prepared.auth,- batchEvent: prepared.batch.event,- bundle: prepared.bundle,- callbackBaseUrl: input.callbackBaseUrl,- capabilities: prepared.capabilities,- channelMetadata: prepared.channelMetadata,- inheritedConversation: prepared.inheritedConversation,- currentSession: session,- fanoutSize: prepared.fanoutSize,- initiatorAuth: prepared.initiatorAuth,- localDevRequest: prepared.localDevRequest,- parentContinuationToken: input.replyTo,- activityObserver: prepared.activityObserver,- sandboxSessionId: prepared.sandboxSessionId,- session,- target: entry.target,- trace: tracing.dispatch,- });- agentId = start.identity.id;- if (outcome.kind === "error") {- applyHandleCommand({ agentId, kind: "remove", ownerId: input.ownerId });- } else {- const confirmed = applyHandleCommand({- address: outcome.address,- kind: "confirm",- operationId: start.operation.id,- ownerId: input.ownerId,- });- if (readClaimedHandle(confirmed) === undefined) {- throw new Error(- `Agent handle store could not confirm start operation "${start.operation.id}".`,- );- }- }- }-- if (outcome.kind === "error") {- return failed(outcome.result);- }-- const action = entry.kind === "resume" ? entry.action : entry.target.action;- const dynamicRemoteAgent =- entry.kind === "resume"- ? entry.dynamicRemoteAgent- : entry.target.kind === "remote"- ? entry.target.dynamicRemoteAgent- : undefined;- const event = createSubagentCalledEvent({- agentId,- callId: outcome.callId,- childSessionId: outcome.address.sessionId,- name: outcome.name,- remote:- outcome.address.kind === "agent/remote"- ? {- resolverId:- dynamicRemoteAgent === undefined- ? action.nodeId- : dynamicRemoteAgent.credentialsStepId,- url: outcome.address.url,- }- : undefined,- sequence: prepared.batch.event.sequence,- sessionId: prepared.session.sessionId,- toolName: outcome.toolName,- turnId: prepared.batch.event.turnId,- workflowId: workflowEntryReference.workflowId,- });- if (input.emit !== undefined) {- await input.emit(event);- }- return {- kind: "dispatched",- agentId,- event,- serializedContext: tracing.serializedContext,- sessionState: sessionState(),- };-}--/**- * Dispatches one workflow-owned agent request. The callback origin is- * parent-owned, so it is derived from this workflow's own metadata rather- * than accepted from the inbound request.- */-export async function dispatchTaskAgentInvocationStep(- input: Omit<Parameters<typeof dispatchAgentInvocation>[0], "callbackBaseUrl" | "emit">,-): Promise<AgentInvocationDispatchResult> {- "use step";-- return await dispatchAgentInvocation({- ...input,- callbackBaseUrl: resolveWorkflowCallbackBaseUrl(getWorkflowMetadata().url),- });-}--/** Applies an owner-scoped child settlement to the parent session's canonical state. */-export async function settleTaskAgentInvocationStep(input: {- readonly ownerId: string;- readonly result: RuntimeSubagentChildResult;- readonly serializedContext: Record<string, unknown>;- readonly sessionState: DurableSessionState;-}): Promise<{- readonly settled: boolean;- readonly completion?: SubagentCompletedStreamEvent;- readonly serializedContext: Record<string, unknown>;- readonly sessionState: DurableSessionState;-}> {- "use step";-- const durable = readDurableSession(input.sessionState);- const handles = getAgentHandleStore(durable.state)?.handles ?? [];- const handle = handles.find(- (candidate) =>- candidate.phase === "claimed" &&- candidate.ownerId === input.ownerId &&- candidate.callId === input.result.callId,- );- if (handle?.phase !== "claimed") {- return {- settled: false,- serializedContext: input.serializedContext,- sessionState: input.sessionState,- };- }- const serializedContext = await flushAgentInvocationTraces(- settleAgentInvocationTrace({- acceptedAtMs: Date.now(),- result: input.result,- serializedContext: input.serializedContext,- sessionId: durable.sessionId,- }),- );-- const nextHandles =- input.result.outcome.kind === "terminal"- ? handles.filter((candidate) => candidate !== handle)- : handles.map((candidate) =>- candidate === handle- ? input.result.outcome.result.kind === "cancelled"- ? {- address: handle.address,- identity: handle.identity,- lastStatus: "(cancelled)",- phase: "parked" as const,- }- : {- address: handle.address,- identity: handle.identity,- phase: "available" as const,- }- : candidate,- );- let session = writeHandles(durable, nextHandles);- if (input.result.outcome.kind === "terminal" && "continuationToken" in handle.address) {- session = clearProxyInputRequestsForChild(- session as Parameters<typeof clearProxyInputRequestsForChild>[0],- handle.address.continuationToken,- );- }- session = setTurnUsageState(- session,- accumulateSessionUsage({- previous: getTurnUsageState(session.state),- usage: input.result.outcome.usageDelta,- }),- );- const completion: SubagentCompletedStreamEvent | undefined =- input.result.outcome.result.kind !== "succeeded"- ? undefined- : {- type: "subagent.completed",- data: {- callId: input.result.callId,- subagentName: input.result.subagentName,- output:- typeof input.result.output === "string"- ? input.result.output- : JSON.stringify(input.result.output),- },- };- return {- settled: true,- completion,- serializedContext,- sessionState: replaceDurableSessionSnapshot({ session, state: input.sessionState }),- };-}--/** Releases any child leases still owned by a completed workflow-tool run. */-export async function releaseAgentInvocationOwnerStep(input: {- readonly cancelled?: boolean;- readonly ownerId: string;- readonly sessionState: DurableSessionState;-}): Promise<{ readonly sessionState: DurableSessionState }> {- "use step";-- const durable = readDurableSession(input.sessionState);- const session = input.cancelled- ? abandonAgentInvocationOwners(durable, new Set([input.ownerId]))- : applyTaskAgentHandleCommand(durable, {- kind: "release-owner",- ownerId: input.ownerId,- }).session;- return {- sessionState:- session === durable- ? input.sessionState- : replaceDurableSessionSnapshot({ session, state: input.sessionState }),- };-}--function readClaimedHandle(- result: AgentHandleStoreCommandResult,-): Extract<TaskOwnedAgentHandle, { phase: "claimed" }> | undefined {- const handle = result.kind === "ready" ? result.handle : undefined;- return handle?.phase === "claimed" ? handle : undefined;-}--function createTaskClaimError(- action: Parameters<typeof createAgentErrorResult>[0]["action"],- agentId: string,- result: AgentHandleStoreCommandResult,-): RuntimeSubagentResult {- if (result.kind === "mismatch") {- return createAgentErrorResult({- action,- code: AGENT_MISMATCH,- message: `Agent "${agentId}" no longer matches this subagent definition. Start a new agent instead.`,- });- }- if (result.kind === "busy") {- return createAgentErrorResult({- action,- code: AGENT_BUSY,- message: formatAgentBusyMessage({- agentId,- agentName: result.handle.identity.name,- ownerId: "ownerId" in result.handle ? result.handle.ownerId : undefined,- }),- });- }- return createAgentErrorResult({- action,- code: AGENT_UNREACHABLE,- message: `Agent with id "${agentId}" is no longer reachable.`,- });-}diff --git a/packages/eve/src/execution/tools/subagent/start.test.ts b/packages/eve/src/execution/tools/subagent/start.test.tsdeleted file mode 100644index 442197951..000000000--- a/packages/eve/src/execution/tools/subagent/start.test.ts+++ /dev/null@@ -1,71 +0,0 @@-import { beforeEach, describe, expect, it, vi } from "vitest";--import { startSubagent } from "#execution/tools/subagent/start.js";-import { startLocalSubagent } from "#subagents/start-local.js";-import { startRemoteSubagent } from "#subagents/start-remote.js";--vi.mock("#subagents/start-local.js", () => ({ startLocalSubagent: vi.fn() }));-vi.mock("#subagents/start-remote.js", () => ({ startRemoteSubagent: vi.fn() }));--beforeEach(() => {- vi.clearAllMocks();- vi.mocked(startLocalSubagent).mockResolvedValue({ kind: "error" } as never);- vi.mocked(startRemoteSubagent).mockResolvedValue({ kind: "error" } as never);-});--describe("startSubagent", () => {- it.each(["local", "remote"] as const)(- "passes one parent context to the %s child with the exact caller span",- async (kind) => {- const caller = {- spanId: "2".repeat(16),- traceFlags: 1,- traceId: "1".repeat(32),- };-- await startSubagent({- auth: null,- batchEvent: { sequence: 1, turnId: "turn-1" },- bundle: {} as never,- callbackBaseUrl: "https://parent.example",- capabilities: undefined,- channelMetadata: undefined,- currentSession: {} as never,- fanoutSize: 1,- initiatorAuth: null,- parentContinuationToken: "parent-token",- sandboxSessionId: "parent-session",- session: { rootSessionId: "root-session", sessionId: "parent-session" } as never,- trace: { originAudience: "private", parentTraceContext: caller },- target:- kind === "local"- ? {- action: { callId: "child-action" } as never,- kind,- source: { type: "runtime" },- }- : { action: { callId: "child-action" } as never, kind },- });-- const start = kind === "local" ? startLocalSubagent : startRemoteSubagent;- const other = kind === "local" ? startRemoteSubagent : startLocalSubagent;- expect(start).toHaveBeenCalledWith(- expect.objectContaining({- parent: {- conversationId: "root-session",- continuationToken: "parent-token",- lineage: {- callId: "child-action",- rootSessionId: "root-session",- sessionId: "parent-session",- turn: { id: "turn-1", sequence: 1 },- },- traceContext: caller,- originAudience: "private",- },- }),- );- expect(other).not.toHaveBeenCalled();- },- );-});diff --git a/packages/eve/src/execution/tools/subagent/start.ts b/packages/eve/src/execution/tools/subagent/start.tsdeleted file mode 100644index c85f8da86..000000000--- a/packages/eve/src/execution/tools/subagent/start.ts+++ /dev/null@@ -1,111 +0,0 @@-import type { ActivityObserverConfig } from "#channel/types.js";-import type { LocalDevRequestProvenance } from "#context/keys.js";-import type { ActivityWorkIdentityV1 } from "#protocol/activity.js";-import type { DynamicSubagentAgentConfig } from "#runtime/subagents/dynamic-agent-config.js";-import type { DynamicRemoteAgentConfig } from "#runtime/subagents/dynamic-remote-agent-config.js";-import type { CompiledBundle } from "#runtime/sessions/runtime-context-keys.js";-import type {- RuntimeRemoteAgentDispatchRequest,- RuntimeSubagentDispatchRequest,-} from "#shared/action-types.js";-import type { DispatchOutcome, RuntimeSession } from "#subagents/handle-dispatch.js";-import { startLocalSubagent } from "#subagents/start-local.js";-import { startRemoteSubagent } from "#subagents/start-remote.js";-import { buildSubagentRunInput, type SubagentInputSource } from "#subagents/tool.js";-import type { SubagentParentContext } from "#subagents/invocation.js";-import type { AgentChildTraceDispatch } from "#tracing/agent-invocation-coordinator.js";-import { resolveConversationId } from "#shared/conversation-identity.js";--export type SubagentStartTarget =- | {- readonly kind: "local";- readonly action: RuntimeSubagentDispatchRequest;- readonly dynamicSubagentAgentConfig?: DynamicSubagentAgentConfig;- readonly source: SubagentInputSource;- }- | {- readonly kind: "remote";- readonly action: RuntimeRemoteAgentDispatchRequest;- readonly dynamicRemoteAgent?: DynamicRemoteAgentConfig;- };--/** Starts one planned fresh child against its local or remote target. */-export async function startSubagent(input: {- readonly auth: Parameters<typeof buildSubagentRunInput>[0]["auth"];- readonly batchEvent: { readonly sequence: number; readonly turnId: string };- readonly bundle: CompiledBundle;- readonly callbackBaseUrl: string | undefined;- readonly capabilities: Parameters<typeof buildSubagentRunInput>[0]["capabilities"];- readonly channelMetadata: Parameters<typeof buildSubagentRunInput>[0]["channelMetadata"];- readonly inheritedConversation?: Parameters<- typeof buildSubagentRunInput- >[0]["inheritedConversation"];- readonly currentSession: RuntimeSession;- readonly fanoutSize: number;- readonly initiatorAuth: Parameters<typeof buildSubagentRunInput>[0]["initiatorAuth"];- /** Inherited originating-client metadata for the dev-TUI hint. */- readonly localDevRequest?: LocalDevRequestProvenance;- readonly parentContinuationToken: string | undefined;- readonly activityObserver?: ActivityObserverConfig & {- readonly workIdentity: ActivityWorkIdentityV1;- };- readonly sandboxSessionId: string;- readonly session: RuntimeSession;- readonly target: SubagentStartTarget;- readonly trace: AgentChildTraceDispatch;-}): Promise<DispatchOutcome> {- const { trace } = input;- const parent: SubagentParentContext = {- conversationId:- trace.conversationId ??- resolveConversationId(input.session.rootSessionId ?? input.session.sessionId),- lineage: {- callId: input.target.action.callId,- rootSessionId: input.session.rootSessionId ?? input.session.sessionId,- sessionId: input.session.sessionId,- turn: { id: input.batchEvent.turnId, sequence: input.batchEvent.sequence },- },- continuationToken: input.parentContinuationToken,- traceContext: trace.parentTraceContext,- originAudience: trace.originAudience,- };-- switch (input.target.kind) {- case "local":- return startLocalSubagent({- action: input.target.action,- auth: input.auth,- bundle: input.bundle,- capabilities: input.capabilities,- channelMetadata: input.channelMetadata,- inheritedConversation: input.inheritedConversation,- currentSession: input.currentSession,- dynamicSubagentAgentConfig: input.target.dynamicSubagentAgentConfig,- fanoutSize: input.fanoutSize,- initiatorAuth: input.initiatorAuth,- localDevRequest: input.localDevRequest,- parent,- activityObserver: input.activityObserver,- sandboxSessionId: input.sandboxSessionId,- session: input.session,- source: input.target.source,- });- case "remote":- return startRemoteSubagent({- action: input.target.action,- auth: input.auth,- bundle: input.bundle,- callbackBaseUrl: input.callbackBaseUrl,- currentSession: input.currentSession,- dynamicRemoteAgent: input.target.dynamicRemoteAgent,- initiatorAuth: input.initiatorAuth,- parent,- activityObserver: input.activityObserver,- session: input.session,- });- default: {- const _exhaustive: never = input.target;- return _exhaustive;- }- }-}diff --git a/packages/eve/src/execution/tools/subagent/task-agent-requests.test.ts b/packages/eve/src/execution/tools/subagent/task-agent-requests.test.tsdeleted file mode 100644index 28f62a3a0..000000000--- a/packages/eve/src/execution/tools/subagent/task-agent-requests.test.ts+++ /dev/null@@ -1,169 +0,0 @@-import { resumeHookStep } from "#execution/tools/workflow/resume-hook-step.js";-import { beforeEach, describe, expect, it, vi } from "vitest";--import { applyTaskAgentRequest } from "#execution/tools/subagent/task-agent-requests.js";-import {- dispatchTaskAgentInvocationStep,- settleTaskAgentInvocationStep,-} from "#execution/tools/subagent/invoke-step.js";-import { emitSubagentEventStep } from "#execution/tools/subagent/emit-event-step.js";-import type { RuntimeSubagentChildResult } from "#shared/action-types.js";--vi.mock("#execution/tools/subagent/invoke-step.js", () => ({- dispatchTaskAgentInvocationStep: vi.fn(),- settleTaskAgentInvocationStep: vi.fn(),-}));-vi.mock("#execution/tools/subagent/emit-event-step.js", () => ({- emitSubagentEventStep: vi.fn(),-}));-vi.mock("#execution/tools/workflow/resume-hook-step.js", () => ({- resumeHookStep: vi.fn(),-}));--const sessionState = { sessionId: "parent" } as never;-const result: RuntimeSubagentChildResult = {- callId: "nested",- kind: "subagent-result",- origin: "child",- outcome: {- kind: "parked",- result: { kind: "succeeded", output: "done" },- usageDelta: { cacheReadTokens: 0, cacheWriteTokens: 0, inputTokens: 2, outputTokens: 3 },- },- output: "done",- subagentName: "research",-};--beforeEach(() => vi.resetAllMocks());--describe("workflow-owned agent requests", () => {- it("reuses the settlement step's flushed trace context during workflow replay", async () => {- const serializedContext = { "eve.test": "before" };- const flushedContext = { "eve.test": "after" };- vi.mocked(settleTaskAgentInvocationStep).mockResolvedValue({- settled: false,- serializedContext: flushedContext,- sessionState,- });- const delivery = {- ownerId: "workflow-run",- replyTo: "reply",- request: { kind: "agent-settled" as const, result },- };- const context = { sessionWritable: {} as never, serializedContext, sessionState };- const settled = await applyTaskAgentRequest(delivery, context);-- expect(settleTaskAgentInvocationStep).toHaveBeenCalledWith({- ownerId: "workflow-run",- result,- serializedContext,- sessionState,- taskId: undefined,- });- expect(settled.serializedContext).toBe(flushedContext);- const replay = await applyTaskAgentRequest(delivery, context);- expect(replay).toEqual(settled);- });-- it.each([false, true])(- "waits for notification completion before acknowledgement and retains its state (fails: %s)",- async (fails) => {- const updatedState = { sessionId: "updated" } as never;- const hookState = { sessionId: "hooked" } as never;- const completion = {- type: "subagent.completed" as const,- data: { callId: "nested", subagentName: "research", output: "done" },- };- vi.mocked(settleTaskAgentInvocationStep).mockResolvedValue({- settled: true,- completion,- serializedContext: {},- sessionState: updatedState,- });- const notification =- Promise.withResolvers<Awaited<ReturnType<typeof emitSubagentEventStep>>>();- vi.mocked(emitSubagentEventStep).mockReturnValue(notification.promise);- const applying = applyTaskAgentRequest(- { ownerId: "workflow-run", replyTo: "reply", request: { kind: "agent-settled", result } },- { sessionWritable: {} as never, serializedContext: {}, sessionState },- );- await vi.waitFor(() => expect(emitSubagentEventStep).toHaveBeenCalledOnce());- expect(resumeHookStep).not.toHaveBeenCalled();- if (fails) {- const rejected = expect(applying).rejects.toThrow("notification runtime failed");- notification.reject(new Error("notification runtime failed"));- await rejected;- expect(emitSubagentEventStep).toHaveBeenCalledOnce();- expect(resumeHookStep).not.toHaveBeenCalled();- } else {- notification.resolve({ serializedContext: { hook: true }, sessionState: hookState });- expect(await applying).toEqual({- serializedContext: { hook: true },- sessionState: hookState,- });- expect(resumeHookStep).toHaveBeenCalledExactlyOnceWith(- "reply",- { kind: "agent-settled", callId: "nested" },- { ifPresent: true },- );- }- },- );-- it("does not acknowledge a failed settlement", async () => {- vi.mocked(settleTaskAgentInvocationStep).mockRejectedValue(new Error("write failed"));- await expect(- applyTaskAgentRequest(- { ownerId: "workflow-run", replyTo: "reply", request: { kind: "agent-settled", result } },- { sessionWritable: {} as never, serializedContext: {}, sessionState },- ),- ).rejects.toThrow("write failed");- expect(resumeHookStep).not.toHaveBeenCalled();- });-- it("retains existing context when replaying a dispatch result without tracing state", async () => {- const receiver = {- attributes: {},- authenticator: "test-idp",- principalId: "receiver",- principalType: "user",- };- const serializedContext = {- "eve.auth": receiver,- "eve.initiatorAuth": receiver,- "eve.test": "preserved",- };- const event = { type: "subagent.called" } as never;- vi.mocked(dispatchTaskAgentInvocationStep).mockResolvedValue({- agentId: "child",- event,- kind: "dispatched",- sessionState,- });- vi.mocked(emitSubagentEventStep).mockResolvedValue({- sessionState,- serializedContext,- });-- const applied = await applyTaskAgentRequest(- {- ownerId: "workflow-run",- replyTo: "reply",- request: {- input: { message: "Find it", target: "research" },- invocationId: "nested",- kind: "agent-invoke",- },- },- { sessionWritable: {} as never, serializedContext, sessionState },- );-- expect(emitSubagentEventStep).toHaveBeenCalledWith({- event,- sessionWritable: {},- serializedContext,- sessionState,- });- expect(applied.serializedContext).toBe(serializedContext);- });-});diff --git a/packages/eve/src/execution/tools/subagent/task-agent-requests.ts b/packages/eve/src/execution/tools/subagent/task-agent-requests.tsdeleted file mode 100644index 81481d84e..000000000--- a/packages/eve/src/execution/tools/subagent/task-agent-requests.ts+++ /dev/null@@ -1,97 +0,0 @@-import type { DurableSessionState } from "#execution/durable-session-store.js";-import { emitSubagentEventStep } from "#execution/tools/subagent/emit-event-step.js";-import {- dispatchTaskAgentInvocationStep,- settleTaskAgentInvocationStep,-} from "#execution/tools/subagent/invoke-step.js";-import { resumeHookStep } from "#execution/tools/workflow/resume-hook-step.js";-import type { WorkflowToolAgentRequest } from "#execution/tools/workflow/messages.js";--interface AgentRequestDelivery {- readonly ownerId: string;- /** The requesting run's reply hook. */- readonly replyTo: string;- readonly request: WorkflowToolAgentRequest;-}--interface TaskAgentRequestContext {- readonly sessionWritable: WritableStream<Uint8Array>;- readonly serializedContext: Record<string, unknown>;- readonly sessionState: DurableSessionState;-}--interface AppliedTaskAgentRequest {- readonly serializedContext: Record<string, unknown>;- readonly sessionState: DurableSessionState;-}--/**- * Applies one workflow-owned agent request to the parent session: `agent-invoke`- * spawns the child with parent-owned material and `agent-settled` releases the- * handle.- */-export async function applyTaskAgentRequest(- delivery: AgentRequestDelivery,- ctx: TaskAgentRequestContext,-): Promise<AppliedTaskAgentRequest> {- const { request } = delivery;- switch (request.kind) {- case "agent-settled": {- const settled = await settleTaskAgentInvocationStep({- ownerId: delivery.ownerId,- result: request.result,- serializedContext: ctx.serializedContext,- sessionState: ctx.sessionState,- });- let serializedContext = settled.serializedContext;- let sessionState = settled.sessionState;- if (settled.completion !== undefined) {- const emitted = await emitSubagentEventStep({- event: settled.completion,- sessionWritable: ctx.sessionWritable,- serializedContext,- sessionState: settled.sessionState,- });- serializedContext = emitted.serializedContext;- sessionState = emitted.sessionState;- }- await resumeHookStep(- delivery.replyTo,- { kind: "agent-settled", callId: request.result.callId },- { ifPresent: true },- );- return {- serializedContext,- sessionState,- };- }- case "agent-invoke": {- const dispatched = await dispatchTaskAgentInvocationStep({- ownerId: delivery.ownerId,- replyTo: delivery.replyTo,- request,- serializedContext: ctx.serializedContext,- sessionState: ctx.sessionState,- });- switch (dispatched.kind) {- case "dispatched": {- return await emitSubagentEventStep({- event: dispatched.event,- sessionWritable: ctx.sessionWritable,- serializedContext: dispatched.serializedContext ?? ctx.serializedContext,- sessionState: dispatched.sessionState,- });- }- case "failed":- await resumeHookStep(delivery.replyTo, {- kind: "runtime-action-result",- results: [dispatched.result],- });- return {- serializedContext: dispatched.serializedContext ?? ctx.serializedContext,- sessionState: dispatched.sessionState,- };- }- }- }-}diff --git a/packages/eve/src/execution/tools/subagent/task-cancel.ts b/packages/eve/src/execution/tools/subagent/task-cancel.tsdeleted file mode 100644index a4772d823..000000000--- a/packages/eve/src/execution/tools/subagent/task-cancel.ts+++ /dev/null@@ -1,71 +0,0 @@-import type { RuntimeSession } from "#subagents/handle-dispatch.js";-import { requestWorkflowTurnCancellation } from "#execution/workflow-runtime.js";-import { cancelRemoteAgentTurn, resolveRemoteAgentForAction } from "#subagents/remote-dispatch.js";-import { deserializeContext } from "#context/serialize.js";-import { BundleKey } from "#runtime/sessions/runtime-context-keys.js";-import { getAgentHandleStore, type AgentHandle } from "#subagents/handles/store.js";-import { readDurableSession, type DurableSessionState } from "#execution/durable-session-store.js";-import { getDynamicSubagentSelection } from "#context/dynamic-subagent-lifecycle.js";-import { createLogger, logError } from "#internal/logging.js";--const log = createLogger("execution.agent-invocation-cancel");--/** Cancels a child turn still claimed by a completed workflow-tool run. */-export async function cancelAgentInvocationOwnerStep(input: {- readonly ownerId: string;- readonly serializedContext: Record<string, unknown>;- readonly sessionState: DurableSessionState;-}): Promise<void> {- "use step";-- try {- await cancelAgentInvocationOwner({- ownerId: input.ownerId,- serializedContext: input.serializedContext,- session: readDurableSession(input.sessionState),- });- } catch (error) {- logError(log, "failed to cancel workflow-owned agent turn", error, { ownerId: input.ownerId });- }-}--async function cancelAgentInvocationOwner(input: {- readonly ownerId: string;- readonly serializedContext: Record<string, unknown>;- readonly session: Pick<RuntimeSession, "state">;-}): Promise<void> {- const handles = (getAgentHandleStore(input.session.state)?.handles ?? []).filter(- (candidate): candidate is Extract<AgentHandle, { phase: "claimed" }> =>- candidate.phase === "claimed" && candidate.ownerId === input.ownerId,- );- if (handles.length === 0) return;- let remoteContext: ReturnType<typeof deserializeContext> | undefined;- const results = await Promise.allSettled(- handles.map(async (handle) => {- if (handle.address.kind !== "agent/remote") {- await requestWorkflowTurnCancellation({ sessionId: handle.address.sessionId });- return;- }- remoteContext ??= deserializeContext(input.serializedContext);- const ctx = await remoteContext;- const bundle = ctx.require(BundleKey);- const selection = getDynamicSubagentSelection(ctx, handle.identity.nodeId);- const remote = resolveRemoteAgentForAction({- dynamicRemoteAgent: selection?.kind === "remote" ? selection.remoteAgent : undefined,- nodeId: handle.identity.nodeId,- registry: bundle.subagentRegistry.subagentsByNodeId,- remoteAgentName: handle.identity.name,- });- await cancelRemoteAgentTurn({- remote: { ...remote, url: handle.address.url },- sessionId: handle.address.sessionId,- });- }),- );- const failures = results.filter((result) => result.status === "rejected");- if (failures.length > 0)- throw new AggregateError(- failures.map((result) => result.reason),- "Failed to cancel owned agent turns.",- );-}diff --git a/packages/eve/src/execution/tools/workflow/ask.test.ts b/packages/eve/src/execution/tools/workflow/ask.test.tsindex 570a8f609..eb7d8e27f 100644--- a/packages/eve/src/execution/tools/workflow/ask.test.ts+++ b/packages/eve/src/execution/tools/workflow/ask.test.ts@@ -15,6 +15,7 @@ describe("ask", () => {attachWorkflowToolRunContext(ctx, {agentContext: { capabilities: { requestInput: false } } as AgentSessionContext,asks: new WorkflowToolRunAsks("run"),+ auth: { current: null, initiator: null },control: "control",from: {callId: "call",diff --git a/packages/eve/src/execution/tools/workflow/ask.ts b/packages/eve/src/execution/tools/workflow/ask.tsindex 521480196..a5e28687e 100644--- a/packages/eve/src/execution/tools/workflow/ask.ts+++ b/packages/eve/src/execution/tools/workflow/ask.ts@@ -1,3 +1,4 @@+import type { SessionAuth } from "#context/session-context.js";import type { AgentSessionContext } from "#execution/agent-sessions/context.js";import type {WorkflowToolRunAskDecision,@@ -16,15 +17,26 @@ import { workflowToolContextErrorMessage } from "#shared/workflow-tool-context.j// be different bundled copies of this module.const WORKFLOW_TOOL_RUN_CONTEXT = Symbol.for("eve.workflow-tool-run.context");+/**+ * The run a workflow body belongs to. Members that describe a call describe+ * the one the run serves now, which a `serve` task changes with each call, so+ * read them when they are used.+ */export interface WorkflowToolRunContext {/**- * What the run's caller lends it: the lineage and principal `ctx.agent`- * sessions run with, and whether `ctx.ask()` can reach a person.+ * What the call's caller lends it: the lineage a `ctx.agent` session opened+ * now binds, and whether `ctx.ask()` can reach a person.*/readonly agentContext: AgentSessionContext;readonly asks: WorkflowToolRunAsks;+ /** The auth of the call, which a message sent to a `ctx.agent` session now carries. */+ readonly auth: SessionAuth;/** The run's control hook, where the session sends its decisions on the run's questions. */readonly control: string;+ /**+ * The ref of the call the run serves now, which questions and sign-ins come+ * from. A `serve` task's changes with each call, so read it when sending.+ */readonly from: WorkflowToolRunRef;readonly owner: WorkflowToolRunInbox;}@@ -60,14 +72,6 @@ export function findWorkflowToolRunContext(value: unknown): WorkflowToolRunConte: undefined;}-export function readWorkflowToolRunRef(ctx: ToolContext): WorkflowToolRunRef {- return readWorkflowToolRunContext(ctx, "agent").from;-}--export function readWorkflowToolRunOwner(ctx: ToolContext): WorkflowToolRunInbox {- return readWorkflowToolRunContext(ctx, "agent").owner;-}-const CANCELLED: ToolInputResponse = { status: "cancelled" };const UNAVAILABLE: ToolInputResponse = { status: "unavailable" };@@ -150,6 +154,7 @@ export function ask(const { asks, control, owner } = context;const { answer, requestId } = asks.open();+ // A `serve` task's current call changes; the question stays the call's that asked it.const from = context.from;const sent = owner.send({kind: "request",diff --git a/packages/eve/src/execution/tools/workflow/body.test.ts b/packages/eve/src/execution/tools/workflow/body.test.tsindex 8ff141781..94491636a 100644--- a/packages/eve/src/execution/tools/workflow/body.test.ts+++ b/packages/eve/src/execution/tools/workflow/body.test.ts@@ -1,8 +1,8 @@import { expect, it, vi } from "vitest";import type { ToolContext } from "#tools/definition.js";import type { WorkflowToolContext } from "#tools/workflow-definition.js";-import { startWorkflowBody, type WorkflowBodyInput } from "#execution/tools/workflow/body.js";-import { readWorkflowToolRunRef, WorkflowToolRunAsks } from "#execution/tools/workflow/ask.js";+import { startCallBody, type WorkflowBodyInput } from "#execution/tools/workflow/body.js";+import { findWorkflowToolRunContext } from "#execution/tools/workflow/ask.js";import type { AgentSessionContext } from "#execution/agent-sessions/context.js";const mocks = vi.hoisted(() => ({ execute: vi.fn(), openAgent: vi.fn(), ask: vi.fn() }));@@ -15,45 +15,16 @@ vi.mock("#execution/agent-sessions/session.js", () => ({createAgentSessions: () => ({ close: async () => {}, open: mocks.openAgent }),}));-const agentContext = { capabilities: { requestInput: true } } as AgentSessionContext;-const owner = { send: vi.fn(), sent: 0 };--it("defaults agent metadata to an empty registry for older workflow payloads", async () => {- mocks.execute.mockImplementation(async (_input, ctx: WorkflowToolContext) => {- expect(ctx.agents).toEqual({});- return null;- });- await startWorkflowBody(- {- agentContext,- callId: "legacy-call",- hookToken: "control",- input: {},- session: {- auth: { current: null, initiator: null },- id: "session",- turn: { id: "turn", sequence: 1 },- },- stepIndex: 0,- toolName: "legacy",- workflowId: "workflow//test//legacy",- owner,- runId: "run",- },- {- abortSignal: new AbortController().signal,- interruptSignal: new AbortController().signal,- },- new WorkflowToolRunAsks("run"),- ).outcome;-});+const agentContext = {+ agents: { reviewer: { description: "Review deployments." } },+ capabilities: { requestInput: true },+} as Partial<AgentSessionContext> as AgentSessionContext;it("binds workflow-only methods to the run context", async () => {- const signal = new AbortController().signal;const input = {agentContext,- agents: { reviewer: { description: "Review deployments." } },callId: "call",+ entry: { entryPoint: "execute" },hookToken: "control",input: {},session: {@@ -64,17 +35,16 @@ it("binds workflow-only methods to the run context", async () => {stepIndex: 0,toolName: "deploy",workflowId: "workflow//test//execute",- owner,+ owner: { send: vi.fn(), sent: 0 },runId: "run",- } as WorkflowBodyInput & { runId: string };+ } as WorkflowBodyInput;const question = { prompt: "Continue?" };const target = "reviewer";const session = { send: vi.fn() };mocks.ask.mockResolvedValue({ optionId: "yes" });mocks.openAgent.mockReturnValue(session);mocks.execute.mockImplementation(async (_input, ctx: WorkflowToolContext & ToolContext) => {- expect(readWorkflowToolRunRef(ctx).runId).toBe("run");- expect(ctx.abortSignal).toBe(signal);+ expect(findWorkflowToolRunContext(ctx)?.from.runId).toBe("run");expect(ctx.agents).toEqual({ reviewer: { description: "Review deployments." } });expect(Object.isFrozen(ctx.agents)).toBe(true);expect(Object.isFrozen(ctx.agents.reviewer)).toBe(true);@@ -84,12 +54,9 @@ it("binds workflow-only methods to the run context", async () => {expect(mocks.openAgent).toHaveBeenCalledWith(target);return { answer };});- const interruptSignal = new AbortController().signal;- await expect(- startWorkflowBody(- input,- { abortSignal: signal, interruptSignal },- new WorkflowToolRunAsks("run"),- ).outcome,- ).resolves.toEqual({ status: "completed", output: { answer: { optionId: "yes" } } });+ const started = startCallBody(input);+ await expect(started.outcome).resolves.toEqual({+ status: "completed",+ output: { answer: { optionId: "yes" } },+ });});diff --git a/packages/eve/src/execution/tools/workflow/body.ts b/packages/eve/src/execution/tools/workflow/body.tsindex 32a28861f..18ff49508 100644--- a/packages/eve/src/execution/tools/workflow/body.ts+++ b/packages/eve/src/execution/tools/workflow/body.ts@@ -3,28 +3,35 @@ import { getWorkflowMetadata } from "#compiled/@workflow/core/index.js";import type { SessionContext } from "#context/session-context.js";import type { AgentSessionContext } from "#execution/agent-sessions/context.js";import { createAgentSessions } from "#execution/agent-sessions/session.js";-import type { AgentSession, WorkflowToolContext } from "#tools/workflow-definition.js";+import type {+ AgentSession,+ WorkflowSharedContext,+ WorkflowToolContext,+} from "#tools/workflow-definition.js";import {ask,attachWorkflowToolRunContext,- type WorkflowToolRunAsks,+ WorkflowToolRunAsks,+ type WorkflowToolRunContext,} from "#execution/tools/workflow/ask.js";import type {+ WorkflowBodyCommand,WorkflowToolRunOutcome,WorkflowToolRunRef,} from "#execution/tools/workflow/messages.js";import type { WorkflowToolRunInbox } from "#execution/tools/workflow/owner.js";import { normalizeSerializableError } from "#execution/workflow-errors.js";import { readRegisteredWorkflow } from "#execution/workflow-registry.js";+import type { WorkflowToolRunEntry } from "#shared/action-types.js";import type { JsonObject, JsonValue } from "#shared/json.js";import type { ToolContext } from "#tools/definition.js";export interface WorkflowBodyDefinition {- /** Everything the run needs to open `ctx.agent` sessions for its caller. */+ /** Everything the run needs to open `ctx.agent` sessions for its caller, and `ctx.agents`. */readonly agentContext: AgentSessionContext;- /** Snapshot added for new runs; absent only when resuming an older durable payload. */- readonly agents?: WorkflowToolContext["agents"];readonly callId: string;+ /** The entry point the run invokes, which decides the body's context. */+ readonly entry: WorkflowToolRunEntry;readonly executeInput?: JsonValue;readonly input: JsonObject;@@ -38,57 +45,129 @@ export interface WorkflowBodyInput extends WorkflowBodyDefinition {/** The run's control hook, which the session answers the body's questions on. */readonly hookToken: string;readonly owner: WorkflowToolRunInbox;+ readonly runId?: string;}-/** The call's signals, which commands on the run's control hook abort. */-export interface WorkflowBodyRun {- readonly abortSignal: AbortSignal;- readonly interruptSignal: AbortSignal;+/**+ * How the session's commands reach a running body. What a command means+ * depends on the entry point: a cancel ends an `execute` or `task` call, but+ * only the current stretch of work of a `serve` task.+ */+export interface WorkflowBodyControl {+ /** Aborts when the run stops for good; the run then settles as cancelled. */+ readonly runSignal: AbortSignal;+ /** The body is winding down cancelled work, which the run bounds with its cleanup deadline. */+ readonly unwinding: boolean;+ apply(command: WorkflowBodyCommand): void;}-/** A body the run started. */+/** A body the run started and how its commands reach it. */export interface StartedWorkflowBody {+ /** The body's pending questions, which the session's decisions settle. */+ readonly asks: WorkflowToolRunAsks;/** Releases what the body opened, such as its `ctx.agent` sessions, once the run ends. */close(): Promise<void>;+ readonly control: WorkflowBodyControl;readonly outcome: Promise<WorkflowToolRunOutcome>;}-type WorkflowToolExecute = (+type WorkflowCallContext = ToolContext & WorkflowToolContext;++/** What an `execute` call a steering message stopped settles with when its body rejects. */+const INTERRUPTED_OUTPUT = { interrupted: true } as const;++type WorkflowCallEntryPoint = (input: unknown,- ctx: WorkflowToolContext,+ ctx: WorkflowCallContext,) => Promise<JsonValue> | AsyncIterable<JsonValue>;-/** Starts one registered workflow body, which reports progress to its owner. */-export function startWorkflowBody(- input: WorkflowBodyInput & { readonly runId?: string },- run: WorkflowBodyRun,- asks: WorkflowToolRunAsks,-): StartedWorkflowBody {- const runContext = {+/**+ * The signals of an `execute` or `task` call, which the run's commands abort.+ * The body's `abortSignal` aborts on a cancel and on an interrupt; the run's+ * signal only on a cancel, because an interrupted call still settles with the+ * body's result.+ */+class WorkflowCallSignals implements WorkflowBodyControl {+ private readonly body = new AbortController();+ private readonly run = new AbortController();+ private readonly asks: WorkflowToolRunAsks;++ constructor(asks: WorkflowToolRunAsks) {+ this.asks = asks;+ }++ get abortSignal(): AbortSignal {+ return this.body.signal;+ }++ get runSignal(): AbortSignal {+ return this.run.signal;+ }++ /** A steering message stopped the body, and no cancel has. */+ get interrupted(): boolean {+ return this.body.signal.aborted && !this.run.signal.aborted;+ }++ get unwinding(): boolean {+ return this.run.signal.aborted;+ }++ apply(command: WorkflowBodyCommand): void {+ switch (command.kind) {+ case "cancel":+ case "end":+ // The session retired the call's questions when it stopped the call,+ // so it accepts no answer after this; settle them before the abort+ // would ask to withdraw them.+ this.asks.cancelAll();+ this.run.abort(new WorkflowToolRunCancelledError(command.reason));+ this.body.abort(this.run.signal.reason);+ return;+ case "interrupt":+ this.body.abort(new WorkflowToolRunInterruptedError());+ return;+ case "call":+ // Only a `serve` task takes later calls.+ return;+ }+ }+}++/** Starts the body of an `execute` or `task` call, which serves the call the run started with. */+export function startCallBody(input: WorkflowBodyInput): StartedWorkflowBody {+ const from = createWorkflowBodyRef(input);+ const asks = new WorkflowToolRunAsks(from.runId);+ const signals = new WorkflowCallSignals(asks);+ const run: WorkflowToolRunContext = {agentContext: input.agentContext,asks,+ auth: input.session.auth,control: input.hookToken,- from: createWorkflowBodyRef(input),+ from,owner: input.owner,};- const agentSessions = createAgentSessions(runContext);- const ctx = createWorkflowBodyContext(input, run, agentSessions.open);- attachWorkflowToolRunContext(ctx, runContext);+ const agentSessions = createAgentSessions(run);+ const ctx = createCallContext(input, signals, agentSessions.open);+ attachWorkflowToolRunContext(ctx, run);return {+ asks,close: agentSessions.close,- outcome: executeWorkflowBody(input, ctx, runContext.from),+ control: signals,+ outcome: executeCallBody(input, ctx, signals, from),};}-async function executeWorkflowBody(+/** Executes one call's registered workflow body and reports progress to its owner. */+async function executeCallBody(input: WorkflowBodyInput,- ctx: ToolContext & WorkflowToolContext,+ ctx: WorkflowCallContext,+ signals: WorkflowCallSignals,from: WorkflowToolRunRef,): Promise<WorkflowToolRunOutcome> {- const signal = ctx.abortSignal;try {- const execute = resolveWorkflowToolExecute(input);- const result = execute(input.executeInput ?? input.input, ctx);+ const entryPoint = resolveWorkflowEntryPoint<WorkflowCallEntryPoint>(input);+ const result = entryPoint(input.executeInput ?? input.input, ctx);let output: JsonValue;if (!isAsyncIterable(result)) {output = await result;@@ -105,21 +184,29 @@ async function executeWorkflowBody(}return { output, status: "completed" };} catch (error) {- if (signal.aborted) {- return {- reason:- signal.reason instanceof Error ? signal.reason.message : String(signal.reason ?? ""),- status: "cancelled",- };- }- return { error: normalizeSerializableError(error), status: "failed" };+ if (signals.interrupted) return { output: INTERRUPTED_OUTPUT, status: "completed" };+ return toFailedOutcome(error, signals.runSignal);+ }+}++/** A body's failure, or its cancellation when the run stopped. */+export function toFailedOutcome(error: unknown, runSignal: AbortSignal): WorkflowToolRunOutcome {+ if (runSignal.aborted) {+ const { reason } = runSignal;+ return {+ reason: reason instanceof Error ? reason.message : String(reason ?? ""),+ status: "cancelled",+ };}+ return { error: normalizeSerializableError(error), status: "failed" };}export function createWorkflowBodyRef(- input: WorkflowBodyDefinition & { readonly runId?: string },+ input: WorkflowBodyDefinition & {+ readonly runId?: string;+ },): WorkflowToolRunRef {- return {+ const ref: WorkflowToolRunRef = {callId: input.callId,input: input.input,runId: input.runId ?? getWorkflowMetadata().workflowRunId,@@ -128,42 +215,39 @@ export function createWorkflowBodyRef(toolName: input.toolName,turnId: input.session.turn.id,};+ return input.entry.entryPoint === "execute" ? ref : { ...ref, taskId: input.entry.taskId };}-function resolveWorkflowToolExecute(input: WorkflowBodyInput): WorkflowToolExecute {- const execute = readRegisteredWorkflow(input.workflowId);- if (typeof execute !== "function") {+export function resolveWorkflowEntryPoint<TEntryPoint>(input: WorkflowBodyInput): TEntryPoint {+ const entryPoint = readRegisteredWorkflow(input.workflowId);+ if (typeof entryPoint !== "function") {throw new Error(`Tool "${input.toolName}" is not registered as a workflow in this deployment (${input.workflowId}). The tool was renamed or removed after this run started.`,);}- return execute as WorkflowToolExecute;+ return entryPoint as TEntryPoint;}-function createWorkflowBodyContext(+/**+ * The members every entry point's context shares, bound to the run. `ask`+ * is the entry point's own, since what it may ask for depends on its calls.+ * The members that describe a call, `abortSignal`, `agents`, `callId`, and+ * `session` (whose turn is the call's), come from the entry point, which+ * knows its calls.+ */+export function createSharedContext(input: WorkflowBodyInput,- run: WorkflowBodyRun,agent: (name: string) => AgentSession,-): ToolContext & WorkflowToolContext {+ askPerson: WorkflowSharedContext["ask"],+): Omit<ToolContext & WorkflowSharedContext, "abortSignal" | "agents" | "callId" | "session"> {const unavailable = (member: string, hint: string): never => {throw new Error(`ctx.${member} is not available inside a workflow tool; ${hint}. Tool "${input.toolName}" runs as a durable workflow body, which only replays deterministic code.`,);};- const ctx: ToolContext & WorkflowToolContext = {+ return {agent,- agents: Object.freeze(- Object.fromEntries(- Object.entries(input.agents ?? {}).map(([name, metadata]) => [- name,- Object.freeze({ ...metadata }),- ]),- ),- ),- ask: (request, options) => ask(ctx, request, options),- abortSignal: run.abortSignal,- callId: input.callId,- interruptSignal: run.interruptSignal,+ ask: askPerson,getSandbox: () => unavailable("getSandbox()", "the session sandbox belongs to the turn"),getToken: () =>unavailable("getToken()", 'pass ctx directly to a "use step" helper to resolve credentials'),@@ -172,9 +256,38 @@ function createWorkflowBodyContext("requireAuth()",'pass ctx directly to a "use step" helper to request authorization',),- session: input.session,toolName: input.toolName,};+}++/** `ctx.agents` for a call: the agents its context lists, frozen. */+export function createAgentsView(context: AgentSessionContext): WorkflowSharedContext["agents"] {+ return Object.freeze(+ Object.fromEntries(+ Object.entries(context.agents).map(([name, metadata]) => [+ name,+ Object.freeze({ ...metadata }),+ ]),+ ),+ );+}++/**+ * The context of an `execute` or `task` call. They differ only in what aborts+ * `abortSignal`: the session interrupts only the `execute` calls a turn waits on.+ */+function createCallContext(+ input: WorkflowBodyInput,+ signals: WorkflowCallSignals,+ agent: (name: string) => AgentSession,+): WorkflowCallContext {+ const ctx: WorkflowCallContext = {+ ...createSharedContext(input, agent, (request, options) => ask(ctx, request, options)),+ abortSignal: signals.abortSignal,+ agents: createAgentsView(input.agentContext),+ callId: input.callId,+ session: input.session,+ };return ctx;}@@ -185,3 +298,18 @@ function isAsyncIterable(value: unknown): value is AsyncIterable<JsonValue> {typeof (value as AsyncIterable<JsonValue>)[Symbol.asyncIterator] === "function");}++export class WorkflowToolRunCancelledError extends Error {+ constructor(reason: string) {+ super(reason);+ this.name = "WorkflowToolRunCancelledError";+ }+}++/** Why an `execute` call's `abortSignal` aborted when a steering message arrived. */+export class WorkflowToolRunInterruptedError extends Error {+ constructor() {+ super("A new message arrived while the turn waited on this call.");+ this.name = "WorkflowToolRunInterruptedError";+ }+}diff --git a/packages/eve/src/execution/tools/workflow/cancel.test.ts b/packages/eve/src/execution/tools/workflow/cancel.test.tsindex 5cae3390f..0324f3d13 100644--- a/packages/eve/src/execution/tools/workflow/cancel.test.ts+++ b/packages/eve/src/execution/tools/workflow/cancel.test.ts@@ -20,6 +20,7 @@ vi.mock("#internal/logging.js", () => ({const world = {} as Awaited<ReturnType<typeof getWorld>>;const address = { hookToken: "generated-control-token", runId: "tool-run" };const reason = "The calling turn was cancelled.";+const cancel = { kind: "cancel" as const, reason };describe("cancelWorkflowToolRun", () => {beforeEach(() => {@@ -34,7 +35,7 @@ describe("cancelWorkflowToolRun", () => {afterEach(() => vi.useRealTimers());it("lets a registered workflow cancel cooperatively", async () => {- await cancelWorkflowToolRun(address, reason);+ await cancelWorkflowToolRun(address, cancel);expect(resumeHook).toHaveBeenCalledWith(address.hookToken, { kind: "cancel", reason });expect(cancelRun).not.toHaveBeenCalled();@@ -44,7 +45,7 @@ describe("cancelWorkflowToolRun", () => {vi.mocked(getRun).mockReturnValue({ status: Promise.resolve("running") } as ReturnType<typeof getRun>);- const cancelled = cancelWorkflowToolRun(address, reason);+ const cancelled = cancelWorkflowToolRun(address, cancel);await vi.advanceTimersByTimeAsync(2_000);expect(cancelRun).not.toHaveBeenCalled();await vi.runAllTimersAsync();@@ -67,7 +68,7 @@ describe("cancelWorkflowToolRun", () => {it("cancels by run ID before the control hook is registered", async () => {vi.mocked(resumeHook).mockRejectedValue(new HookNotFoundError(address.hookToken));- await cancelWorkflowToolRun(address, reason);+ await cancelWorkflowToolRun(address, cancel);expect(cancelRun).toHaveBeenCalledWith(world, address.runId, { cancelReason: reason });expect(logError).not.toHaveBeenCalled();@@ -77,7 +78,7 @@ describe("cancelWorkflowToolRun", () => {vi.mocked(resumeHook).mockRejectedValue(new HookNotFoundError(address.hookToken));vi.mocked(cancelRun).mockRejectedValue(new EntityConflictError("Run already completed"));- await expect(cancelWorkflowToolRun(address, reason)).resolves.toBeUndefined();+ await expect(cancelWorkflowToolRun(address, cancel)).resolves.toBeUndefined();expect(cancelRun).toHaveBeenCalledOnce();expect(logError).not.toHaveBeenCalled();@@ -87,7 +88,7 @@ describe("cancelWorkflowToolRun", () => {vi.mocked(resumeHook).mockRejectedValue(new Error("hook delivery unavailable"));vi.mocked(cancelRun).mockRejectedValue(new Error("run cancellation unavailable"));- await expect(cancelWorkflowToolRun(address, reason)).resolves.toBeUndefined();+ await expect(cancelWorkflowToolRun(address, cancel)).resolves.toBeUndefined();expect(cancelRun).toHaveBeenCalledWith(world, address.runId, { cancelReason: reason });expect(logError).toHaveBeenCalledTimes(2);diff --git a/packages/eve/src/execution/tools/workflow/cancel.ts b/packages/eve/src/execution/tools/workflow/cancel.tsindex 4b9b1fca6..773d4a6f6 100644--- a/packages/eve/src/execution/tools/workflow/cancel.ts+++ b/packages/eve/src/execution/tools/workflow/cancel.ts@@ -7,18 +7,24 @@ import { createLogger, logError } from "#internal/logging.js";const log = createLogger("execution.workflow-tool-run");+/** How a run is told to stop: `end` also finishes a `serve` task's run, which a cancel keeps. */+export type WorkflowToolRunStop = Extract<+ WorkflowToolRunControlMessage,+ { readonly kind: "cancel" | "end" }+>;+/**- * Asks the run to cancel itself, then bounds cooperative cleanup. Failures are+ * Asks the run to stop itself, then bounds cooperative cleanup. Failures are* logged: the caller has already committed cancellation of the calling turn.*/export async function cancelWorkflowToolRun(run: WorkflowToolRunAddress,- reason: string,+ stop: WorkflowToolRunStop,): Promise<void> {- const cancel: WorkflowToolRunControlMessage = { kind: "cancel", reason };+ const { reason } = stop;let signalled = false;try {- await resumeHook(run.hookToken, cancel);+ await resumeHook(run.hookToken, stop);signalled = true;} catch (error) {// A fresh run may not have registered its control hook yet.diff --git a/packages/eve/src/execution/tools/workflow/emit-workflow-tool-run-report-step.ts b/packages/eve/src/execution/tools/workflow/emit-workflow-tool-run-report-step.tsindex f77fbdf09..f3224e84b 100644--- a/packages/eve/src/execution/tools/workflow/emit-workflow-tool-run-report-step.ts+++ b/packages/eve/src/execution/tools/workflow/emit-workflow-tool-run-report-step.ts@@ -54,6 +54,7 @@ export async function emitAgentStartedStep(}: undefined,sessionId: session.sessionId,+ ...(from.taskId !== undefined && { taskId: from.taskId }),turnId: from.turnId,});return await publishSessionEvents(input, [event]);diff --git a/packages/eve/src/execution/tools/workflow/harness-definition.test.ts b/packages/eve/src/execution/tools/workflow/harness-definition.test.tsdeleted file mode 100644index 43eb55714..000000000--- a/packages/eve/src/execution/tools/workflow/harness-definition.test.ts+++ /dev/null@@ -1,21 +0,0 @@-import { describe, expect, it } from "vitest";--import { jsonSchema } from "ai";-import { createWorkflowToolHarnessDefinition } from "./harness-definition.js";--describe("createWorkflowToolHarnessDefinition", () => {- it("preserves agent identity on workflow-backed tools", () => {- expect(- createWorkflowToolHarnessDefinition({- definition: {- description: "Delegate research.",- execute: () => undefined,- inputSchema: jsonSchema({ type: "object" }),- name: "research",- },- nodeId: "subagents/research",- workflowId: "workflow//eve//subagentToolExecuteWorkflow",- }),- ).toMatchObject({ execute: undefined, nodeId: "subagents/research" });- });-});diff --git a/packages/eve/src/execution/tools/workflow/harness-definition.ts b/packages/eve/src/execution/tools/workflow/harness-definition.tsindex e33fe76d3..cef88b613 100644--- a/packages/eve/src/execution/tools/workflow/harness-definition.ts+++ b/packages/eve/src/execution/tools/workflow/harness-definition.ts@@ -1,26 +1,32 @@+import { withTaskIdInput } from "#execution/tasks/task-id-input.js";+import { entryPointOf } from "#execution/tasks/tool-entry-point.js";import type { HarnessToolDefinition } from "#harness/execute-tool.js";import type { PreparedRuntimeTool } from "#runtime/sessions/turn.js";+import { workflowIdForHandling } from "#runtime/subagents/workflow-reference.js";import type { JsonValue } from "#shared/json.js";import { UNSPECIFIED_INPUT_SCHEMA, toInputSchema, toOutputSchema } from "#tools/schema.js";export interface WorkflowToolHarnessDefinitionInput {readonly definition: HarnessToolDefinition;readonly executeInput?: (input: unknown) => JsonValue;- /** Selected agent definition's runtime graph ID; absent for authored workflow tools. */- readonly nodeId?: string;-readonly workflowId: string;}-/** Workflow tools run outside the model step, so the harness definition carries no `execute`. */+/**+ * Workflow tools run outside the model step, so the harness definition carries+ * no `execute`. A `serve` tool's model input gains `taskId`.+ */export function createWorkflowToolHarnessDefinition(input: WorkflowToolHarnessDefinitionInput,): HarnessToolDefinition {+ const definition =+ entryPointOf(input.definition) === "serve"+ ? withTaskIdInput(input.definition)+ : input.definition;return {- ...input.definition,+ ...definition,execute: undefined,executeInput: input.executeInput,- nodeId: input.nodeId,workflowId: input.workflowId,};}@@ -28,8 +34,9 @@ export function createWorkflowToolHarnessDefinition(export function createPreparedWorkflowToolHarnessDefinition(tool: PreparedRuntimeTool,): HarnessToolDefinition {- if (tool.task === undefined) {- throw new Error(`Prepared tool "${tool.name}" is not backed by a workflow task.`);+ const workflowId = workflowIdForHandling(tool.behavior?.handling);+ if (workflowId === undefined) {+ throw new Error(`Prepared tool "${tool.name}" is not backed by a workflow.`);}return createWorkflowToolHarnessDefinition({definition: {@@ -40,7 +47,6 @@ export function createPreparedWorkflowToolHarnessDefinition(outputSchema: toOutputSchema(tool.outputSchema),rootOnly: tool.rootOnly,},- nodeId: tool.task.nodeId,- workflowId: tool.task.workflowId,+ workflowId,});}diff --git a/packages/eve/src/execution/tools/workflow/interrupt.ts b/packages/eve/src/execution/tools/workflow/interrupt.tsindex d8fe5b910..7bb4096ee 100644--- a/packages/eve/src/execution/tools/workflow/interrupt.ts+++ b/packages/eve/src/execution/tools/workflow/interrupt.ts@@ -5,7 +5,7 @@ import type { WorkflowToolRunAddress } from "#execution/tools/workflow/types.js"const INTERRUPT: WorkflowToolRunControlMessage = { kind: "interrupt" };/**- * Fires the call's `interruptSignal`. A run that already finished has nothing+ * Aborts the `execute` call's `abortSignal`. A run that already finished has nothing* left to interrupt, so a missing hook is not an error.*/export async function interruptWorkflowToolRun(run: WorkflowToolRunAddress): Promise<void> {diff --git a/packages/eve/src/execution/tools/workflow/messages.ts b/packages/eve/src/execution/tools/workflow/messages.tsindex 4827b6dd6..91ccaf333 100644--- a/packages/eve/src/execution/tools/workflow/messages.ts+++ b/packages/eve/src/execution/tools/workflow/messages.ts@@ -1,9 +1,7 @@import type { SubagentAuthorizationEventHookPayload } from "#channel/types.js";+import type { SessionAuth } from "#context/session-context.js";+import type { AgentSessionContext } from "#execution/agent-sessions/context.js";import type { AgentSessionAddress } from "#execution/agent-sessions/steps.js";-import type {- AgentInvocationRequest,- AgentSettlementRequest,-} from "#execution/tools/subagent/invoke-agent.js";import type { InputRequest } from "#shared/input.js";import type { JsonObject, JsonValue } from "#shared/json.js";import type {@@ -16,12 +14,6 @@ export interface WorkflowToolRunOwner {readonly inbox: string;}-/**- * Requests the owner applies for the model's agent tools because they touch- * owner-held state: spawning an agent and releasing its handle afterwards.- */-export type WorkflowToolAgentRequest = AgentInvocationRequest | AgentSettlementRequest;-/*** A child authorization event the owner should display. Unlike input requests* it has no answer: the authorization callback completes against the child@@ -50,7 +42,6 @@ export interface WorkflowToolInputRequestBatch {}export type WorkflowToolRequest =- | WorkflowToolAgentRequest| WorkflowToolAuthorizationRequest| WorkflowToolAskRequest| InputRequest@@ -63,6 +54,8 @@ export interface WorkflowToolRunRef {readonly runId: string;readonly sequence: number;readonly stepIndex: number;+ /** Set when the run does a task's work; the session routes its messages by it. */+ readonly taskId?: string;readonly toolName: string;readonly turnId: string;}@@ -110,13 +103,54 @@ export interface WorkflowToolRunAgentStartedMessage {readonly session: AgentSessionAddress;}+/**+ * A `serve` body's reply, sent once for each `ctx.reply()`. It settles every+ * call the body received since its last reply, so the session settles them+ * together and the model receives the reply once.+ */+export interface WorkflowToolRunReplyMessage {+ /** The calls the reply settles, oldest first. */+ readonly callIds: readonly string[];+ /** The latest call the reply settles, which the body serves now. */+ readonly from: WorkflowToolRunRef;+ readonly output: JsonValue;+}++/** A task's run can take commands: its control hook is registered. */+export interface WorkflowToolRunStartedMessage {+ readonly from: WorkflowToolRunRef;+}+export type WorkflowToolRunMessage =| ({ readonly kind: "agent-started" } & WorkflowToolRunAgentStartedMessage)+ | ({ readonly kind: "started" } & WorkflowToolRunStartedMessage)| ({ readonly kind: "report" } & WorkflowToolRunReport)+ | ({ readonly kind: "reply" } & WorkflowToolRunReplyMessage)| ({ readonly kind: "request" } & WorkflowToolRunRequestMessage)| ({ readonly kind: "withdraw" } & WorkflowToolRunWithdrawMessage)| ({ readonly kind: "outcome" } & WorkflowToolRunOutcomeMessage);+/**+ * A later call to a `serve` task, which its run hands to `receive()`. It+ * carries everything the session knew of the call when it admitted it, as a+ * run's input does for the call that started it: the coordinates of the model+ * step that made it, the caller's auth, and the context of sessions opened+ * for it, with the agents it may open. Everything the run does while serving+ * the call comes from these.+ */+export interface WorkflowToolRunCall extends Pick<+ WorkflowToolRunRef,+ "callId" | "sequence" | "stepIndex" | "turnId"+> {+ /** Sessions opened while serving the call are its children, in its trace. */+ readonly agentContext: AgentSessionContext;+ /** The caller's auth the session admitted the call with, which messages sent while serving it carry. */+ readonly auth: SessionAuth;+ readonly executeInput?: JsonValue;+ /** The call's input, without the `taskId` that named the task. */+ readonly input: JsonObject;+}+/** A person's answer to a `ctx.ask()` question, as the session accepted it. */export type WorkflowToolRunAnswer = Extract<ToolInputResponse, { readonly status: "answered" }>;@@ -134,12 +168,19 @@ export type WorkflowToolRunAskDecision =| { readonly kind: "withdrawn"; readonly requestId: string };/**- * Commands the body applies, in the order the session sent them. `cancel`- * aborts the call's `abortSignal`; `interrupt` aborts its `interruptSignal`,- * because steering arrived while the turn waits on the call.+ * Commands the body applies, in the order the session sent them.+ *+ * - `cancel` stops the current work: an `execute` or `task` call's run, or a+ * `serve` task's current stretch of work, after which it waits for more calls.+ * - `end` stops the run for good, because the session ended.+ * - `interrupt` aborts an `execute` call's `abortSignal` without cancelling the+ * call, because steering arrived while the turn waits on it.+ * - `call` delivers a later call to a `serve` task.*/export type WorkflowBodyCommand =+ | { readonly kind: "call"; readonly call: WorkflowToolRunCall }| { readonly kind: "cancel"; readonly reason: string }+ | { readonly kind: "end"; readonly reason: string }| { readonly kind: "interrupt" };/**@@ -153,12 +194,15 @@ export function isWorkflowToolRunControlMessage(value: unknown,): value is WorkflowToolRunControlMessage {if (typeof value !== "object" || value === null) return false;- const { kind, reason, requestId, response } = value as Record<string, unknown>;+ const { call, kind, reason, requestId, response } = value as Record<string, unknown>;switch (kind) {case "interrupt":return true;case "cancel":+ case "end":return typeof reason === "string";+ case "call":+ return isWorkflowToolRunCall(call);case "answer":return typeof requestId === "string" && isWorkflowToolRunAnswer(response);case "withdrawn":@@ -194,3 +238,23 @@ function isToolInputResponseResponder(value: unknown): value is ToolInputResponstypeof principalType === "string");}++function isWorkflowToolRunCall(value: unknown): value is WorkflowToolRunCall {+ if (typeof value !== "object" || value === null) return false;+ const { agentContext, auth, callId, input, sequence, stepIndex, turnId } = value as Record<+ string,+ unknown+ >;+ return (+ typeof agentContext === "object" &&+ agentContext !== null &&+ typeof auth === "object" &&+ auth !== null &&+ typeof callId === "string" &&+ typeof input === "object" &&+ input !== null &&+ typeof sequence === "number" &&+ typeof stepIndex === "number" &&+ typeof turnId === "string"+ );+}diff --git a/packages/eve/src/execution/tools/workflow/owner-inbox.test.ts b/packages/eve/src/execution/tools/workflow/owner-inbox.test.tsindex bab83c36b..d7e0a7e9b 100644--- a/packages/eve/src/execution/tools/workflow/owner-inbox.test.ts+++ b/packages/eve/src/execution/tools/workflow/owner-inbox.test.ts@@ -76,20 +76,6 @@ describe("workflow-tool task input", () => {},});});-- it("does not normalize workflow agent requests as human input", () => {- expect(() =>- workflowToolRunRequestToInputRequestPayload({- from,- replyTo: "subagent:parent:call-1",- request: {- input: { message: "Find it", target: "research" },- invocationId: "call-1",- kind: "agent-invoke",- },- }),- ).toThrow("A workflow agent request cannot be normalized as human input.");- });});describe("workflow-tool task outcomes", () => {diff --git a/packages/eve/src/execution/tools/workflow/owner-inbox.ts b/packages/eve/src/execution/tools/workflow/owner-inbox.tsindex 8430e8dd6..2759252fa 100644--- a/packages/eve/src/execution/tools/workflow/owner-inbox.ts+++ b/packages/eve/src/execution/tools/workflow/owner-inbox.ts@@ -76,6 +76,7 @@ export function workflowToolRunRequestToInputRequestPayload(requests: workflowToolRunInputRequests(message),sequence: requestCoordinates?.sequence ?? from.sequence,stepIndex: requestCoordinates?.stepIndex ?? from.stepIndex,+ taskId: from.taskId,turnId: requestCoordinates?.turnId ?? from.turnId,},kind: "subagent-input-request",@@ -97,9 +98,6 @@ function normalizeInputRequest(requestId: string,): InputRequest {switch (request.kind) {- case "agent-invoke":- case "agent-settled":- throw new TypeError("A workflow agent request cannot be normalized as human input.");case "authorization-request":throw new TypeError("A workflow authorization event cannot be normalized as human input.");case "ask":diff --git a/packages/eve/src/execution/tools/workflow/serve.test.ts b/packages/eve/src/execution/tools/workflow/serve.test.tsnew file mode 100644index 000000000..60119f2dc--- /dev/null+++ b/packages/eve/src/execution/tools/workflow/serve.test.ts@@ -0,0 +1,295 @@+import { expect, it, vi } from "vitest";++import type { SessionAuth, SessionContext, SessionTurn } from "#context/session-context.js";+import type { AgentSessionContext } from "#execution/agent-sessions/context.js";+import { findWorkflowToolRunContext } from "#execution/tools/workflow/ask.js";+import type { WorkflowBodyInput } from "#execution/tools/workflow/body.js";+import { WORKFLOW_CANCELLATION_CLEANUP_MS } from "#execution/tools/workflow/cancellation-policy.js";+import type {+ WorkflowBodyCommand,+ WorkflowToolRunMessage,+ WorkflowToolRunRef,+} from "#execution/tools/workflow/messages.js";+import { startServeBody } from "#execution/tools/workflow/serve.js";+import { workflowToolRunWorkflow } from "#execution/tools/workflow/workflow.js";+import type { JsonValue } from "#shared/json.js";+import type {+ WorkflowServeCall,+ WorkflowServeContext,+ WorkflowServeReceive,+} from "#tools/workflow-definition.js";++const mocks = vi.hoisted(() => ({+ /** Commands the session sends the run's control hook. */+ commands: [] as WorkflowBodyCommand[],+ deliver: vi.fn<(inbox: string, message: WorkflowToolRunMessage) => Promise<void>>(),+ openAgent:+ vi.fn<+ (input: { readonly context: AgentSessionContext; readonly name: string }) => Promise<unknown>+ >(),+ sendAgent: vi.fn<(input: { readonly context: AgentSessionContext }) => Promise<void>>(),+ serve: vi.fn(),+ sleep: vi.fn<(ms: number) => Promise<void>>(),+ wakeCommands: () => {},+}));+vi.mock("#execution/workflow-registry.js", () => ({ readRegisteredWorkflow: () => mocks.serve }));+vi.mock("#execution/tools/workflow/resume-hook-step.js", () => ({+ resumeHookStep: mocks.deliver,+}));+vi.mock("#execution/agent-sessions/steps.js", () => ({+ openAgentSessionStep: mocks.openAgent,+ sendAgentSessionMessageStep: mocks.sendAgent,+}));+vi.mock("#compiled/@workflow/core/index.js", () => ({+ createHook: (options?: { readonly token?: string }) =>+ options?.token === "control"+ ? (async function* () {+ while (true) {+ const command = mocks.commands.shift();+ if (command !== undefined) yield command;+ else await new Promise<void>((resolve) => (mocks.wakeCommands = resolve));+ }+ })()+ : // Agent turns and the run's inbox never report; only what the run sends matters here.+ {+ [Symbol.asyncIterator]: () => ({ next: () => new Promise(() => {}) }),+ token: "agent-turn",+ },+ sleep: mocks.sleep,+}));++/** Alice, with the claims she has when she makes a call. */+function alice(role: string): SessionAuth {+ return {+ current: {+ attributes: { role },+ authenticator: "test",+ principalId: "alice",+ principalType: "user",+ },+ initiator: null,+ };+}++const reviewer = { description: "Review the plan." };+/** A dynamic agent the turn of a later call selected. */+const releaseCaptain = { description: "Coordinate the release." };++/** The context the session captured for a call, which sessions opened for it inherit. */+function agentContext(+ callId: string,+ turn: SessionTurn,+ agents: AgentSessionContext["agents"],+): AgentSessionContext {+ return {+ agents,+ capabilities: { requestInput: true },+ parent: { callId, rootSessionId: "session", sessionId: "session", turn },+ } as AgentSessionContext;+}++const input: WorkflowBodyInput = {+ agentContext: agentContext("call-1", { id: "turn", sequence: 1 }, { reviewer }),+ callId: "call-1",+ entry: { entryPoint: "serve", taskId: "plan-7k2m9q" },+ input: { request: "Draft the plan." },+ hookToken: "control",+ owner: { send: (message) => mocks.deliver("inbox", message), sent: 0 },+ runId: "run",+ session: {+ auth: alice("editor"),+ id: "session",+ turn: { id: "turn", sequence: 1 },+ },+ stepIndex: 0,+ toolName: "plan",+ workflowId: "workflow//test//plan",+};++/** A later call, made in its own turn, by Alice with the claims she has by then. */+function call(callId: string, request: string): WorkflowBodyCommand {+ const turn = { id: `turn-${callId}`, sequence: 2 };+ return {+ call: {+ agentContext: agentContext(callId, turn, { "release-captain": releaseCaptain, reviewer }),+ auth: alice("reviewer"),+ callId,+ input: { request },+ sequence: turn.sequence,+ stepIndex: 0,+ turnId: turn.id,+ },+ kind: "call",+ };+}++function aborted(signal: AbortSignal): Promise<void> {+ return new Promise((resolve) => signal.addEventListener("abort", () => resolve()));+}++it("serves every call to its task, one stretch of work at a time, until the session ends", async () => {+ const received: WorkflowServeCall<JsonValue>[] = [];+ const pendings: Promise<WorkflowServeCall<JsonValue>>[] = [];+ let servingSecond:+ | {+ agents: WorkflowServeContext["agents"];+ ref: WorkflowToolRunRef | undefined;+ session: SessionContext["session"];+ }+ | undefined;+ mocks.serve.mockImplementation(+ async (receive: WorkflowServeReceive<JsonValue>, ctx: WorkflowServeContext<JsonValue>) => {+ received.push(await receive());+ const review = ctx.agent("reviewer");+ await review.send("Review the draft.");+ const pending = receive();+ pendings.push(pending, receive());+ received.push(await pending);+ servingSecond = {+ agents: ctx.agents,+ ref: findWorkflowToolRunContext(ctx)?.from,+ session: ctx.session,+ };+ await review.send("Check the rollback step.");+ await ctx.agent("release-captain").send("Schedule the rollback drill.");+ ctx.reply("revised plan");+ const third = await receive();+ received.push(third);+ await aborted(third.abortSignal);+ received.push(await receive());+ return await receive();+ },+ );+ mocks.openAgent.mockImplementation(async ({ name }) => ({+ kind: "local",+ name,+ nodeId: name,+ sessionId: `${name}-session`,+ }));+ const started = startServeBody(input);++ await vi.waitFor(() => expect(pendings).toHaveLength(2));+ started.control.apply(call("call-2", "Add a rollback step."));+ await vi.waitFor(() => expect(mocks.deliver).toHaveBeenCalledTimes(3));+ started.control.apply(call("call-3", "Move it to Friday."));+ await vi.waitFor(() => expect(received).toHaveLength(3));+ started.control.apply({ kind: "cancel", reason: "The task was cancelled." });+ started.control.apply(call("call-4", "Keep it on Thursday."));+ await vi.waitFor(() => expect(received).toHaveLength(4));+ started.control.apply({ kind: "end", reason: "The session ended." });++ await expect(started.outcome).resolves.toEqual({+ reason: "The session ended.",+ status: "cancelled",+ });+ expect(pendings[0]).toBe(pendings[1]);+ expect(received.map(({ callId, input }) => ({ callId, input }))).toEqual([+ { callId: "call-1", input: { request: "Draft the plan." } },+ { callId: "call-2", input: { request: "Add a rollback step." } },+ { callId: "call-3", input: { request: "Move it to Friday." } },+ { callId: "call-4", input: { request: "Keep it on Thursday." } },+ ]);+ const replies = mocks.deliver.mock.calls.flatMap(([inbox, message]) =>+ message.kind === "reply"+ ? [+ {+ callIds: message.callIds,+ inbox,+ output: message.output,+ turnId: message.from.turnId,+ },+ ]+ : [],+ );+ // One reply settles both calls it answers, together.+ expect(replies).toEqual([+ {+ callIds: ["call-1", "call-2"],+ inbox: "inbox",+ output: "revised plan",+ turnId: "turn-call-2",+ },+ ]);+ // Questions, sign-ins, `agent.started`, `ctx.session`, and `ctx.agents`+ // while serving a later call describe that call, not the call that started+ // the task.+ expect(servingSecond).toMatchObject({+ agents: { "release-captain": releaseCaptain, reviewer },+ ref: { callId: "call-2", taskId: "plan-7k2m9q", turnId: "turn-call-2" },+ session: { auth: alice("reviewer"), turn: { id: "turn-call-2", sequence: 2 } },+ });+ // A session is the child of the call served when it opened, and each+ // message to it carries the auth of the call served when it was sent.+ const firstCall = { callId: "call-1", turn: { id: "turn", sequence: 1 } };+ expect(mocks.openAgent.mock.calls.map(([opened]) => opened)).toMatchObject([+ { auth: alice("editor"), context: { parent: firstCall }, name: "reviewer" },+ {+ auth: alice("reviewer"),+ context: { parent: { callId: "call-2", turn: { id: "turn-call-2", sequence: 2 } } },+ name: "release-captain",+ },+ ]);+ expect(mocks.sendAgent.mock.calls.map(([sent]) => sent)).toMatchObject([+ {+ address: { sessionId: "reviewer-session" },+ auth: alice("reviewer"),+ context: { parent: firstCall },+ message: "Check the rollback step.",+ },+ ]);+ const [first, second, third, fourth] = received.map((served) => served.abortSignal);+ // A call that arrives while the task works joins its stretch; a cancel ends+ // only that stretch, and the next call starts a new one.+ expect(second).toBe(first);+ expect(third).not.toBe(first);+ expect(third?.aborted).toBe(true);+ expect(fourth).not.toBe(third);+ expect(first?.aborted).toBe(false);+ expect(fourth?.aborted).toBe(true);+});++it.each([+ {+ body: "ignores the cancel",+ outcome: {+ reason:+ "The task was cancelled and its serve body didn't return to receive() within 30 seconds.",+ status: "cancelled",+ },+ serve: async (receive: WorkflowServeReceive<JsonValue>) => {+ await receive();+ return await new Promise<JsonValue>(() => {});+ },+ },+ {+ body: "returns to receive()",+ outcome: { output: { request: "Keep it on Thursday." }, status: "completed" },+ serve: async (receive: WorkflowServeReceive<JsonValue>) => {+ await aborted((await receive()).abortSignal);+ return (await receive()).input;+ },+ },+])("bounds a cancelled stretch whose body $body", async ({ outcome, serve }) => {+ const deadline = Promise.withResolvers<void>();+ mocks.sleep.mockReturnValue(deadline.promise);+ mocks.serve.mockImplementation(serve);+ const run = workflowToolRunWorkflow({ ...input, owner: { inbox: "session" } });+ const send = (command: WorkflowBodyCommand): void => {+ mocks.commands.push(command);+ mocks.wakeCommands();+ };++ send({ kind: "cancel", reason: "The task was cancelled." });+ await vi.waitFor(() =>+ expect(mocks.sleep).toHaveBeenCalledWith(WORKFLOW_CANCELLATION_CLEANUP_MS),+ );+ deadline.resolve();+ send(call("call-2", "Keep it on Thursday."));+ await run;++ expect(mocks.deliver).toHaveBeenLastCalledWith(+ "session",+ expect.objectContaining({ kind: "outcome", result: outcome }),+ expect.anything(),+ );+});diff --git a/packages/eve/src/execution/tools/workflow/serve.ts b/packages/eve/src/execution/tools/workflow/serve.tsnew file mode 100644index 000000000..406d04032--- /dev/null+++ b/packages/eve/src/execution/tools/workflow/serve.ts@@ -0,0 +1,382 @@+import type { SessionContext } from "#context/session-context.js";+import type { AgentSessionContext } from "#execution/agent-sessions/context.js";+import { createAgentSessions } from "#execution/agent-sessions/session.js";+import {+ ask,+ attachWorkflowToolRunContext,+ WorkflowToolRunAsks,+ type WorkflowToolRunContext,+} from "#execution/tools/workflow/ask.js";+import {+ createAgentsView,+ createSharedContext,+ createWorkflowBodyRef,+ resolveWorkflowEntryPoint,+ toFailedOutcome,+ WorkflowToolRunCancelledError,+ type StartedWorkflowBody,+ type WorkflowBodyControl,+ type WorkflowBodyInput,+} from "#execution/tools/workflow/body.js";+import type {+ WorkflowBodyCommand,+ WorkflowToolRunCall,+ WorkflowToolRunOutcome,+ WorkflowToolRunRef,+} from "#execution/tools/workflow/messages.js";+import type { WorkflowToolRunInbox } from "#execution/tools/workflow/owner.js";+import type { JsonValue } from "#shared/json.js";+import type { ToolContext } from "#tools/definition.js";+import type {+ AgentSession,+ WorkflowServeCall,+ WorkflowServeContext,+ WorkflowServeReceive,+ WorkflowSharedContext,+} from "#tools/workflow-definition.js";++type ServeContext = ToolContext & WorkflowServeContext<JsonValue>;++type ServeEntryPoint = (+ receive: WorkflowServeReceive<JsonValue>,+ ctx: ServeContext,+) => Promise<JsonValue>;++/**+ * A call the body serves: the ref its reply is sent from, the session as the+ * call sees it, the context of the sessions opened while serving it, and the+ * agents it may open.+ */+interface ServedCall {+ readonly agentContext: AgentSessionContext;+ readonly agents: WorkflowSharedContext["agents"];+ readonly call: WorkflowServeCall<JsonValue>;+ readonly from: WorkflowToolRunRef;+ /** The run's session in the call's turn, with the auth the call was admitted with. */+ readonly session: SessionContext["session"];+}++interface PendingReceive {+ readonly promise: Promise<WorkflowServeCall<JsonValue>>;+ readonly reject: (error: Error) => void;+ readonly resolve: (call: WorkflowServeCall<JsonValue>) => void;+}++/**+ * The calls a `serve` body receives. The first arrives with the run and+ * resolves the first `receive()` in memory; later calls arrive as `call`+ * commands on the run's control hook, in the order the session sent them.+ * `ctx.reply()` settles every call received so far, and the body's outcome+ * settles the rest.+ *+ * The task works in stretches: a stretch starts when a call arrives while+ * every earlier call has a result, and ends when a reply or a cancel leaves+ * none without one. Calls in one stretch share its `abortSignal`. A cancel+ * aborts the stretch and keeps the run; `end` stops the run for good.+ */+class WorkflowServeCalls implements WorkflowBodyControl {+ /**+ * The body's questions. A cancel keeps the run, so it withdraws them+ * through the stretch's `abortSignal`, and the session decides each one.+ */+ readonly asks: WorkflowToolRunAsks;+ private readonly run = new AbortController();+ private readonly first: ServedCall;+ /** The run's ref and session; each served call replaces the fields that describe the call. */+ private readonly runRef: WorkflowToolRunRef;+ private readonly runSession: SessionContext["session"];+ private readonly owner: WorkflowToolRunInbox;+ private readonly toolName: string;+ private readonly seenCallIds: Set<string>;+ private firstReceived = false;+ /** Calls that arrived and wait for the body's `receive()`, oldest first. */+ private arrived: ServedCall[] = [];+ /** Calls the body received that have no result yet; the first counts from the start. */+ private waiting: ServedCall[];+ /** The latest call the body received: the last of `waiting` while any call has no result. */+ private latest: ServedCall;+ private pendingReceive: PendingReceive | undefined;+ /** The current stretch of work: set while any call has no result. */+ private stretch: AbortController | undefined;+ /** A cancel stopped the body at work; it unwinds until it calls `receive()` again. */+ private unwindingCancel = false;+ private endedBy: Error | undefined;+ private replies: Promise<void> = Promise.resolve();++ constructor(input: WorkflowBodyInput) {+ this.runRef = createWorkflowBodyRef(input);+ this.asks = new WorkflowToolRunAsks(this.runRef.runId);+ this.runSession = input.session;+ this.owner = input.owner;+ this.toolName = input.toolName;+ this.seenCallIds = new Set([input.callId]);+ this.first = this.serve({+ agentContext: input.agentContext,+ auth: input.session.auth,+ callId: this.runRef.callId,+ executeInput: input.executeInput,+ input: this.runRef.input,+ sequence: this.runRef.sequence,+ stepIndex: this.runRef.stepIndex,+ turnId: this.runRef.turnId,+ });+ this.waiting = [this.first];+ this.latest = this.first;+ }++ get runSignal(): AbortSignal {+ return this.run.signal;+ }++ get unwinding(): boolean {+ return this.run.signal.aborted || this.unwindingCancel;+ }++ /** The signal of the work in progress, for framework waits started on the body's behalf. */+ get currentSignal(): AbortSignal {+ return this.stretch?.signal ?? this.run.signal;+ }++ /**+ * The call the body serves now: the latest call it received. Steps,+ * questions, sign-ins, and `agent.started` belong to this call, so they+ * carry its `callId` and turn; `ctx.session` is its view of the session,+ * `ctx.agents` lists the agents it may open, a session opened now is its+ * child, and a message sent now carries its auth.+ */+ get current(): ServedCall {+ return this.latest;+ }++ apply(command: WorkflowBodyCommand): void {+ switch (command.kind) {+ case "call":+ this.accept(command.call);+ return;+ case "cancel":+ this.cancel(new WorkflowToolRunCancelledError(command.reason));+ return;+ case "end":+ this.end(new WorkflowToolRunCancelledError(command.reason));+ return;+ case "interrupt":+ // Steering never interrupts a task.+ return;+ }+ }++ receive(): Promise<WorkflowServeCall<JsonValue>> {+ // The first call may be cancelled already, so taking it ends no unwinding.+ if (!this.firstReceived) {+ this.firstReceived = true;+ return Promise.resolve(this.first.call);+ }+ this.unwindingCancel = false;+ if (this.pendingReceive !== undefined) return this.pendingReceive.promise;+ if (this.endedBy !== undefined) return Promise.reject(this.endedBy);+ const next = this.arrived.shift();+ if (next !== undefined) {+ this.take(next);+ return Promise.resolve(next.call);+ }+ this.pendingReceive = createPendingReceive();+ return this.pendingReceive.promise;+ }++ reply(output: JsonValue): void {+ const settled = this.waiting;+ if (settled.length === 0) return;+ this.waiting = [];+ if (this.arrived.length === 0) this.stretch = undefined;+ const previous = this.replies;+ this.replies = previous.then(() => this.deliverReply(settled, output));+ }++ assertWaiting(): void {+ if (this.waiting.length > 0) return;+ throw new Error(+ `ctx.ask() needs a call waiting for a result, but tool "${this.toolName}" already replied to every call it received.`,+ );+ }++ /** Waits for in-flight replies, so the outcome can never overtake them. */+ async flush(): Promise<void> {+ await this.replies;+ }++ /** A later call reached the run. Redelivered calls are ignored. */+ private accept(call: WorkflowToolRunCall): void {+ if (this.endedBy !== undefined || this.seenCallIds.has(call.callId)) return;+ this.seenCallIds.add(call.callId);+ const served = this.serve(call);+ const pending = this.pendingReceive;+ if (pending === undefined) {+ this.arrived.push(served);+ return;+ }+ this.pendingReceive = undefined;+ this.take(served);+ pending.resolve(served.call);+ }++ /** The body received a call: it waits for a result and is the call served now. */+ private take(served: ServedCall): void {+ this.waiting.push(served);+ this.latest = served;+ }++ /**+ * The session cancelled the current work. It already settled the calls as+ * cancelled, so they leave the run, and a later reply is dropped.+ */+ private cancel(reason: Error): void {+ // A body already waiting in `receive()` has nothing to unwind.+ if (this.pendingReceive === undefined) this.unwindingCancel = true;+ this.stretch?.abort(reason);+ this.stretch = undefined;+ this.waiting = [];+ this.arrived = [];+ }++ /** The session ended: the work in progress aborts and no call arrives anymore. */+ private end(reason: Error): void {+ // The session is gone and decides no question anymore; settle them before+ // the aborts would ask to withdraw them.+ this.asks.cancelAll();+ this.endedBy = reason;+ this.run.abort(reason);+ this.stretch?.abort(reason);+ const pending = this.pendingReceive;+ this.pendingReceive = undefined;+ pending?.reject(reason);+ }++ /** A call joins the running stretch, or starts the next one when every call has its result. */+ private serve(call: WorkflowToolRunCall): ServedCall {+ this.stretch ??= new AbortController();+ return {+ agentContext: call.agentContext,+ agents: createAgentsView(call.agentContext),+ call: {+ abortSignal: this.stretch.signal,+ callId: call.callId,+ input: call.executeInput ?? call.input,+ },+ from: {+ ...this.runRef,+ callId: call.callId,+ input: call.input,+ sequence: call.sequence,+ stepIndex: call.stepIndex,+ turnId: call.turnId,+ },+ session: {+ ...this.runSession,+ auth: call.auth,+ turn: { id: call.turnId, sequence: call.sequence },+ },+ };+ }++ /**+ * One `reply` message for every call the reply settles: the session settles+ * them in one step, so no wait wakes on one of them while the rest look+ * unanswered.+ */+ private async deliverReply(calls: readonly ServedCall[], output: JsonValue): Promise<void> {+ const latest = calls.at(-1);+ if (latest === undefined) return;+ const callIds = calls.map((served) => served.from.callId);+ await this.owner.send({ callIds, from: latest.from, kind: "reply", output });+ }+}++/** Starts a `serve` body, which runs once for its task and serves every call to it. */+export function startServeBody(input: WorkflowBodyInput): StartedWorkflowBody {+ const calls = new WorkflowServeCalls(input);+ const run: WorkflowToolRunContext = {+ get agentContext() {+ return calls.current.agentContext;+ },+ asks: calls.asks,+ get auth() {+ return calls.current.session.auth;+ },+ control: input.hookToken,+ get from() {+ return calls.current.from;+ },+ owner: input.owner,+ };+ const agentSessions = createAgentSessions(run);+ const ctx = createServeContext(input, calls, agentSessions.open);+ attachWorkflowToolRunContext(ctx, run);+ return {+ asks: calls.asks,+ close: agentSessions.close,+ control: calls,+ outcome: executeServeBody(input, calls, ctx),+ };+}++async function executeServeBody(+ input: WorkflowBodyInput,+ calls: WorkflowServeCalls,+ ctx: ServeContext,+): Promise<WorkflowToolRunOutcome> {+ let outcome: WorkflowToolRunOutcome;+ try {+ const serve = resolveWorkflowEntryPoint<ServeEntryPoint>(input);+ const output = await serve(() => calls.receive(), ctx);+ outcome = { output, status: "completed" };+ } catch (error) {+ outcome = toFailedOutcome(error, calls.runSignal);+ }+ // Outside the try: a reply that never reached the run fails the run instead+ // of letting the outcome settle its calls in the reply's place.+ await calls.flush();+ return outcome;+}++/**+ * The context of a `serve` task. Framework waits and steps started through it+ * belong to the call served now, so its internal `abortSignal` follows the+ * current stretch of work, and its `agents`, `callId`, and `session` the+ * latest call received.+ */+function createServeContext(+ input: WorkflowBodyInput,+ calls: WorkflowServeCalls,+ agent: (name: string) => AgentSession,+): ServeContext {+ const ctx: ServeContext = {+ ...createSharedContext(input, agent, (request, options) => {+ calls.assertWaiting();+ return ask(ctx, request, options);+ }),+ get abortSignal() {+ return calls.currentSignal;+ },+ get agents() {+ return calls.current.agents;+ },+ get callId() {+ return calls.current.from.callId;+ },+ get session() {+ return calls.current.session;+ },+ reply: (output) => calls.reply(output),+ };+ return ctx;+}++function createPendingReceive(): PendingReceive {+ let resolve!: (call: WorkflowServeCall<JsonValue>) => void;+ let reject!: (error: Error) => void;+ const promise = new Promise<WorkflowServeCall<JsonValue>>((resolvePromise, rejectPromise) => {+ resolve = resolvePromise;+ reject = rejectPromise;+ });+ return { promise, reject, resolve };+}diff --git a/packages/eve/src/execution/tools/workflow/start.test.ts b/packages/eve/src/execution/tools/workflow/start.test.tsindex f01325d01..b25e671d9 100644--- a/packages/eve/src/execution/tools/workflow/start.test.ts+++ b/packages/eve/src/execution/tools/workflow/start.test.ts@@ -15,8 +15,8 @@ vi.mock("#execution/workflow-runtime.js", () => ({const input: Omit<WorkflowToolRunInput, "hookToken"> = {agentContext: {} as AgentSessionContext,- agents: { reviewer: { description: "Review deployments." } },callId: "call-1",+ entry: { entryPoint: "execute" },input: { service: "api" },owner: { inbox: "owner-inbox" },session: {diff --git a/packages/eve/src/execution/tools/workflow/start.ts b/packages/eve/src/execution/tools/workflow/start.tsindex 26c22f76b..c2d639a34 100644--- a/packages/eve/src/execution/tools/workflow/start.ts+++ b/packages/eve/src/execution/tools/workflow/start.ts@@ -3,10 +3,11 @@ import type { AgentSessionContext } from "#execution/agent-sessions/context.js";import { createRuntimeToolResultFromValue } from "#harness/action-result-helpers.js";import { registerWorkflowToolRun } from "#harness/workflow-tool-runs.js";import { createLogger, logError } from "#internal/logging.js";-import type { RuntimeSession } from "#subagents/handle-dispatch.js";+import type { HarnessSession } from "#harness/types.js";import type {RuntimeToolResultActionResult,RuntimeWorkflowTaskRequest,+ WorkflowToolRunEntry,} from "#shared/action-types.js";import { toError } from "#shared/errors.js";import type {@@ -25,48 +26,74 @@ const log = createLogger("execution.workflow-tool-run");export async function startWorkflowToolRun(input: Omit<WorkflowToolRunInput, "hookToken">,): Promise<WorkflowToolRunAddress> {- const hookToken = crypto.randomUUID();+ const hookToken =+ input.entry.entryPoint === "execute"+ ? crypto.randomUUID()+ : taskRunHookToken(input.session.id, input.entry.taskId);const run = await startWorkflowOnCurrentDeployment(workflowToolRunWorkflowReference, [{ ...input, hookToken },]);return { hookToken, runId: run.runId };}-/** Starts one durable workflow task and records it on the owning session. */-export async function startWorkflowTask(input: {+/**+ * A task's run takes the session's commands, including later calls to a+ * `serve` task, on a hook named for the task: at most one run can hold it, so+ * a retried start can never leave a second run taking the task's calls.+ */+function taskRunHookToken(sessionId: string, taskId: string): string {+ return `eve:task:${sessionId}:${taskId}`;+}++/** Everything the session knows when it starts one workflow tool call's run. */+export interface StartWorkflowTaskInput {+ /** Captured for this call, as the context of the sessions opened for it. */readonly agentContext: AgentSessionContext;- readonly agents: WorkflowToolRunInput["agents"];- readonly auth: SessionAuth["current"];+ /** The caller's auth the session admits the call with. */+ readonly auth: SessionAuth;readonly batchEvent: {readonly sequence: number;readonly stepIndex: number;readonly turnId: string;};- readonly initiatorAuth: SessionAuth["initiator"];readonly owner: WorkflowToolRunOwner;readonly parentSession: SessionParent | undefined;- readonly session: RuntimeSession;+ readonly session: HarnessSession;readonly task: RuntimeWorkflowTaskRequest;-}): Promise<{ readonly result?: RuntimeToolResultActionResult; readonly session: RuntimeSession }> {+}++/** Starts the run for one call, which invokes `entry`. */+export async function startWorkflowToolCallRun(+ input: StartWorkflowTaskInput,+ entry: WorkflowToolRunEntry,+): Promise<WorkflowToolRunAddress> {+ const { task, batchEvent, session } = input;+ return await startWorkflowToolRun({+ agentContext: input.agentContext,+ callId: task.callId,+ entry,+ executeInput: task.executeInput,+ input: task.input,+ owner: input.owner,+ session: {+ auth: input.auth,+ id: session.sessionId,+ parent: input.parentSession,+ turn: { id: batchEvent.turnId, sequence: batchEvent.sequence },+ },+ stepIndex: batchEvent.stepIndex,+ toolName: task.toolName,+ workflowId: task.workflowId,+ });+}++/** Starts the run of an `execute` call the turn waits on and records it on the owning session. */+export async function startWorkflowTask(+ input: StartWorkflowTaskInput,+): Promise<{ readonly result?: RuntimeToolResultActionResult; readonly session: HarnessSession }> {const { task, batchEvent, session } = input;try {- const started = await startWorkflowToolRun({- agentContext: input.agentContext,- agents: input.agents,- callId: task.callId,- executeInput: task.executeInput,- input: task.input,- owner: input.owner,- session: {- auth: { current: input.auth, initiator: input.initiatorAuth },- id: session.sessionId,- parent: input.parentSession,- turn: { id: batchEvent.turnId, sequence: batchEvent.sequence },- },- stepIndex: batchEvent.stepIndex,- toolName: task.toolName,- workflowId: task.workflowId,- });+ const started = await startWorkflowToolCallRun(input, { entryPoint: "execute" });return {session: registerWorkflowToolRun(session, {callId: task.callId,@@ -80,14 +107,19 @@ export async function startWorkflowTask(input: {callId: task.callId,toolName: task.toolName,});- return {- result: createRuntimeToolResultFromValue({- callId: task.callId,- isError: true,- output: toError(error),- toolName: task.toolName,- }),- session,- };+ return { result: startFailureResult(task, error), session };}}++/** The call's tool result when its run could not start. */+export function startFailureResult(+ task: RuntimeWorkflowTaskRequest,+ error: unknown,+): RuntimeToolResultActionResult {+ return createRuntimeToolResultFromValue({+ callId: task.callId,+ isError: true,+ output: toError(error),+ toolName: task.toolName,+ });+}diff --git a/packages/eve/src/execution/tools/workflow/step.ts b/packages/eve/src/execution/tools/workflow/step.tsindex 0cf4335d8..aea6aa756 100644--- a/packages/eve/src/execution/tools/workflow/step.ts+++ b/packages/eve/src/execution/tools/workflow/step.ts@@ -225,6 +225,7 @@ async function reportAuthorization(name: challenge.name,sequence: run.from.sequence,stepIndex: run.from.stepIndex,+ taskId: run.from.taskId,turnId: run.from.turnId,authorization: challenge.challenge,};diff --git a/packages/eve/src/execution/tools/workflow/workflow-owner-blocking.ts b/packages/eve/src/execution/tools/workflow/workflow-owner-blocking.tsindex b288792a4..fc425af80 100644--- a/packages/eve/src/execution/tools/workflow/workflow-owner-blocking.ts+++ b/packages/eve/src/execution/tools/workflow/workflow-owner-blocking.ts@@ -1,49 +1,26 @@import { createHook } from "#compiled/@workflow/core/index.js";-import type { WorkflowToolRunAsks } from "#execution/tools/workflow/ask.js";import {createChannelReader,type ChannelReader,} from "#execution/tools/workflow/owner-channels.js";import type {- WorkflowBodyCommand,- WorkflowToolRunControlMessage,WorkflowToolRunMessage,+ WorkflowToolRunControlMessage,} from "#execution/tools/workflow/messages.js";import { resumeHookStep } from "#execution/tools/workflow/resume-hook-step.js";import type { WorkflowToolRunInput } from "#execution/tools/workflow/types.js";export interface BlockingWorkflowOwner {+ /** The session's commands, from the run's control hook. */readonly commands: ChannelReader<"control", WorkflowToolRunControlMessage>;- /** The call's `interruptSignal`: steering arrived while the turn waits on the call. */- readonly interruptSignal: AbortSignal;- readonly signal: AbortSignal;- handleCommand(command: WorkflowBodyCommand): void;handleMessage(message: WorkflowToolRunMessage): Promise<void>;}-/** Routes invocation messages to the waiting turn and accepts cancellation and interrupts. */-export function createBlockingWorkflow(- input: WorkflowToolRunInput,- asks: WorkflowToolRunAsks,-): BlockingWorkflowOwner {- const controller = new AbortController();- const interrupt = new AbortController();+/** The run's link to its session: commands arrive on its control hook, and its messages go to the session's inbox. */+export function createBlockingWorkflow(input: WorkflowToolRunInput): BlockingWorkflowOwner {const hook = createHook<WorkflowToolRunControlMessage>({ token: input.hookToken });return {commands: createChannelReader("control", hook),- interruptSignal: interrupt.signal,- signal: controller.signal,- handleCommand(command: WorkflowBodyCommand) {- if (command.kind === "interrupt") {- interrupt.abort();- return;- }- // The session retired the call's questions when it stopped the call,- // so it accepts no answer after this; settle them before the abort- // would ask to withdraw them.- asks.cancelAll();- controller.abort(new WorkflowToolRunCancelledError(command.reason));- },handleMessage(message: WorkflowToolRunMessage) {return resumeHookStep(input.owner.inbox, message, {ifPresent: message.kind === "outcome" && message.result.status === "cancelled",@@ -51,10 +28,3 @@ export function createBlockingWorkflow(},};}--class WorkflowToolRunCancelledError extends Error {- constructor(reason: string) {- super(reason);- this.name = "WorkflowToolRunCancelledError";- }-}diff --git a/packages/eve/src/execution/tools/workflow/workflow.test.ts b/packages/eve/src/execution/tools/workflow/workflow.test.tsindex 4a530c16c..bc3d93d69 100644--- a/packages/eve/src/execution/tools/workflow/workflow.test.ts+++ b/packages/eve/src/execution/tools/workflow/workflow.test.ts@@ -4,22 +4,23 @@ import type {WorkflowToolRunControlMessage,WorkflowToolRunMessage,} from "#execution/tools/workflow/messages.js";-import { WorkflowToolRunAsks } from "#execution/tools/workflow/ask.js";import { workflowToolRunWorkflow } from "#execution/tools/workflow/workflow.js";import type { AgentSessionContext } from "#execution/agent-sessions/context.js";const mocks = vi.hoisted(() => ({sleep: vi.fn(),- control: vi.fn(),+ owner: vi.fn(),deliver: vi.fn(),runBody: vi.fn(),+ applyCommand: vi.fn(),+ body: { runSignal: new AbortController().signal },openWorkflowToolRunOwnerInbox: vi.fn(),}));vi.mock("#compiled/@workflow/core/index.js", () => ({ sleep: mocks.sleep }));vi.mock("#execution/tools/workflow/workflow-owner-blocking.js", () => ({- createBlockingWorkflow: mocks.control,+ createBlockingWorkflow: mocks.owner,}));vi.mock("#execution/tools/workflow/resume-hook-step.js", () => ({ resumeHookStep: mocks.deliver }));@@ -39,9 +40,16 @@ vi.mock("#execution/tools/workflow/body.js", () => ({toolName: input.toolName,turnId: input.session.turn.id,}),- startWorkflowBody: (...args: unknown[]) => ({+ startCallBody: (input: unknown) => ({close: async () => {},- outcome: mocks.runBody(...args),+ control: {+ apply: mocks.applyCommand,+ runSignal: mocks.body.runSignal,+ get unwinding() {+ return mocks.body.runSignal.aborted;+ },+ },+ outcome: mocks.runBody(input),}),}));vi.mock("#execution/tools/workflow/owner.js", () => ({@@ -55,6 +63,7 @@ const input = {hookToken: "control",owner: { inbox: "parent" },callId: "call-1",+ entry: { entryPoint: "execute" as const },input: {},session: {auth: { current: null, initiator: null },@@ -111,11 +120,7 @@ it("emits every persisted report before the terminal outcome", async () => {},{ ifPresent: false },);- expect(mocks.runBody).toHaveBeenCalledWith(- expect.objectContaining({ owner: invocationOwner }),- { abortSignal: expect.any(AbortSignal), interruptSignal: expect.any(AbortSignal) },- expect.any(WorkflowToolRunAsks),- );+ expect(mocks.runBody).toHaveBeenCalledWith(expect.objectContaining({ owner: invocationOwner }));});it.each(["completed", "failed", "cancelled", "throw", "blocked"] as const)(@@ -207,9 +212,8 @@ it("preserves the pending inbox read across cancellation and drains the report bfunction setControl(controller: AbortController) {const { signal } = controller;- mocks.control.mockReturnValue({- interruptSignal: new AbortController().signal,- signal,+ mocks.body.runSignal = signal;+ mocks.owner.mockReturnValue({commands: createChannelReader("control",(async function* () {@@ -221,7 +225,6 @@ function setControl(controller: AbortController) {await new Promise<void>(() => {});})(),),- handleCommand: vi.fn(),handleMessage: (message: WorkflowToolRunMessage) =>mocks.deliver("parent", message, {ifPresent: message.kind === "outcome" && message.result.status === "cancelled",@@ -259,13 +262,9 @@ it("applies cancellation buffered during the last report delivery before publishawait vi.waitFor(() => expect(commands.landed).toHaveLength(1));}});- mocks.control.mockReturnValue({- interruptSignal: new AbortController().signal,- commands,- signal: controller.signal,- handleMessage: deliver,- handleCommand: () => controller.abort(new Error("stop")),- });+ mocks.owner.mockReturnValue({ commands, handleMessage: deliver });+ mocks.body.runSignal = controller.signal;+ mocks.applyCommand.mockImplementation(() => controller.abort(new Error("stop")));mocks.sleep.mockReturnValue(new Promise<void>(() => {}));mocks.openWorkflowToolRunOwnerInbox.mockReturnValue({owner: { send: vi.fn(), sent: 1 },@@ -291,13 +290,11 @@ it("applies cancellation buffered during the last report delivery before publish});it("keeps waiting for the body after the control hook closes", async () => {- mocks.control.mockReturnValue({- interruptSignal: new AbortController().signal,- signal: new AbortController().signal,+ mocks.owner.mockReturnValue({commands: createChannelReader("control", (async function* () {})()),- handleCommand: vi.fn(),handleMessage: mocks.deliver,});+ mocks.body.runSignal = new AbortController().signal;mocks.runBody.mockResolvedValue({ status: "completed", output: "done" });mocks.openWorkflowToolRunOwnerInbox.mockReturnValue({owner: { send: vi.fn(), sent: 0 },diff --git a/packages/eve/src/execution/tools/workflow/workflow.ts b/packages/eve/src/execution/tools/workflow/workflow.tsindex 257bbaa83..c83dda1b3 100644--- a/packages/eve/src/execution/tools/workflow/workflow.ts+++ b/packages/eve/src/execution/tools/workflow/workflow.ts@@ -1,8 +1,12 @@import { WORKFLOW_CANCELLATION_CLEANUP_MS } from "#execution/tools/workflow/cancellation-policy.js";import { sleep } from "#compiled/@workflow/core/index.js";import { normalizeSerializableError } from "#execution/workflow-errors.js";-import { createWorkflowBodyRef, startWorkflowBody } from "#execution/tools/workflow/body.js";-import { WorkflowToolRunAsks } from "#execution/tools/workflow/ask.js";+import {+ createWorkflowBodyRef,+ startCallBody,+ type StartedWorkflowBody,+ type WorkflowBodyInput,+} from "#execution/tools/workflow/body.js";import {isWorkflowToolRunAskDecision,isWorkflowToolRunControlMessage,@@ -14,25 +18,23 @@ import {type ChannelReader,} from "#execution/tools/workflow/owner-channels.js";import { openWorkflowToolRunOwnerInbox } from "#execution/tools/workflow/owner.js";-import {- createBlockingWorkflow,- type BlockingWorkflowOwner,-} from "#execution/tools/workflow/workflow-owner-blocking.js";+import { createBlockingWorkflow } from "#execution/tools/workflow/workflow-owner-blocking.js";+import { resumeHookStep } from "#execution/tools/workflow/resume-hook-step.js";+import { startServeBody } from "#execution/tools/workflow/serve.js";import type { WorkflowToolRunInput } from "#execution/tools/workflow/types.js";+const SERVE_CLEANUP_EXPIRED =+ "The task was cancelled and its serve body didn't return to receive() within 30 seconds.";+/** Owns command intake, body execution, and settlement for one workflow tool call. */export async function workflowToolRunWorkflow(input: WorkflowToolRunInput): Promise<void> {"use workflow";- const asks = new WorkflowToolRunAsks(createWorkflowBodyRef(input).runId);- const owner = createBlockingWorkflow(input, asks);- const { signal } = owner;+ const owner = createBlockingWorkflow(input);const inbox = openWorkflowToolRunOwnerInbox();- const started = startWorkflowBody(- { ...input, owner: inbox.owner },- { abortSignal: signal, interruptSignal: owner.interruptSignal },- asks,- );+ if (input.entry.entryPoint !== "execute") await reportTaskStarted(input);+ const started = startWorkflowBody({ ...input, owner: inbox.owner });+ const signal = started.control.runSignal;const body: ChannelReader<"body", WorkflowToolRunOutcome> = createChannelReader("body",awaitBodyOutcome(started.outcome),@@ -47,7 +49,7 @@ export async function workflowToolRunWorkflow(input: WorkflowToolRunInput): Prom// inbox is gone, which is exactly when what the body opened must stop.try {while (true) {- if (signal.aborted) {+ if (started.control.unwinding) {cleanupDeadline ??= sleep(WORKFLOW_CANCELLATION_CLEANUP_MS).then(() => "cancel");}if (@@ -79,7 +81,16 @@ export async function workflowToolRunWorkflow(input: WorkflowToolRunInput): Promoutcome = { status: "failed", error: normalizeSerializableError(error) };break;}- if (read === "cancel") break;+ if (read === "cancel") {+ // A serve body can return to receive() before its deadline.+ if (!started.control.unwinding) {+ cleanupDeadline = undefined;+ continue;+ }+ // One that doesn't ends with its task.+ if (!signal.aborted) started.control.apply({ kind: "end", reason: SERVE_CLEANUP_EXPIRED });+ break;+ }if (read.next.done) {if (read.channel === "control") {commandsOpen = false;@@ -93,7 +104,9 @@ export async function workflowToolRunWorkflow(input: WorkflowToolRunInput): Promreturn;}if (read.channel === "control") {- applyControlMessage(owner, asks, read.next.value);+ // The deadline counts from the cancel the body is unwinding now.+ if (!started.control.unwinding) cleanupDeadline = undefined;+ applyControlMessage(started, read.next.value);continue;}if (read.channel === "body") {@@ -124,22 +137,42 @@ export async function workflowToolRunWorkflow(input: WorkflowToolRunInput): Prom}}+/**+ * Tells the session a task's run can take commands. Sending suspends the run,+ * which registers its control hook before the session hears of it, so a cancel+ * the session held until now reaches the body.+ */+async function reportTaskStarted(input: WorkflowToolRunInput): Promise<void> {+ await resumeHookStep(+ input.owner.inbox,+ { from: createWorkflowBodyRef(input), kind: "started" },+ { ifPresent: true },+ );+}+/*** Applies one message from the run's control hook. Decisions on questions and* commands share the hook, so the body sees them in the order the session* made them.*/-function applyControlMessage(- owner: BlockingWorkflowOwner,- asks: WorkflowToolRunAsks,- message: unknown,-): void {+function applyControlMessage(started: StartedWorkflowBody, message: unknown): void {if (!isWorkflowToolRunControlMessage(message)) return;if (isWorkflowToolRunAskDecision(message)) {- asks.settle(message);+ started.asks.settle(message);return;}- owner.handleCommand(message);+ started.control.apply(message);+}++/** Starts the body the run's entry point names. */+function startWorkflowBody(input: WorkflowBodyInput): StartedWorkflowBody {+ switch (input.entry.entryPoint) {+ case "execute":+ case "task":+ return startCallBody(input);+ case "serve":+ return startServeBody(input);+ }}async function* awaitBodyOutcome(diff --git a/packages/eve/src/harness/coordination.test.ts b/packages/eve/src/harness/coordination.test.tsindex c391a7737..fbc0620f8 100644--- a/packages/eve/src/harness/coordination.test.ts+++ b/packages/eve/src/harness/coordination.test.ts@@ -1,20 +1,12 @@-import {- isInboxSubagentResultFromRunningHandle,- isResultBoundToRunningHandle,-} from "#subagents/handles/query.js";import { describe, expect, it } from "vitest";import { createPresentedRuntimeActionRequestFromToolCall } from "#harness/action-presentation.js";import {createCoordinationRequestFromToolCall,createRuntimeActionRequestFromToolCall,- getPendingCoordinationBatch,resolvePendingCoordination,resolveToolCallInputObject,setPendingCoordinationBatch,} from "#harness/coordination.js";-import { deriveAgentOperationId } from "#subagents/handles/operation-id.js";-import { deriveAgentId, getAgentHandleStore } from "#subagents/handles/store.js";-import { confirmAgentStarted, prepareAgentStart } from "#subagents/handles/transitions.js";import { getProxyInputRequests, upsertProxyInputRequests } from "#harness/proxy-input-requests.js";import {getBlockingWorkflowToolRuns,@@ -22,26 +14,13 @@ import {} from "#harness/workflow-tool-runs.js";import { toolOutput } from "#tools/model-output.js";-import { getSessionTokenUsage, setTurnUsageState } from "#harness/turn-tag-state.js";+import { setTurnUsageState } from "#harness/turn-tag-state.js";import type { HarnessSession } from "#harness/types.js";-import type { UnstampedMessageStreamEvent } from "#protocol/message.js";import { isRuntimeWorkflowToolAction } from "#shared/action-types.js";const REQUEST_EVENT = { sequence: 0, stepIndex: 0, turnId: "turn_0" };-const CHILD_SESSION_ID = "local-child-123456789012";const CHILD_CONTINUATION_TOKEN = "subagent:private-token";-const ZERO_USAGE = {- cacheReadTokens: 0,- cacheWriteTokens: 0,- inputTokens: 0,- outputTokens: 0,-} as const;-const OPERATION_ID = deriveAgentOperationId({- callId: "call-1",- parentSessionId: "test-session",- parentTurnId: "turn_0",-});describe("createRuntimeActionRequestFromToolCall", () => {const loadSkillCall = {@@ -236,6 +215,8 @@ describe("createCoordinationRequestFromToolCall", () => {it("lowers blocking workflow tools to workflow tasks", () => {expect(createCoordinationRequestFromToolCall({+ entry: { entryPoint: "execute" },+ input: toolCall.input,toolCall,tools: new Map([[@@ -253,6 +234,7 @@ describe("createCoordinationRequestFromToolCall", () => {callId: "call-1",executeInput: undefined,input: { message: "research this" },+ entry: { entryPoint: "execute" },kind: "workflow-task",toolName: "researcher",workflowId: "workflow://subagent-tool",@@ -289,6 +271,7 @@ function createParkedSession(): HarnessSession {callId: "call-1",executeInput: { message: "go", target: "researcher" },input: { description: "Research the topic", message: "go" },+ entry: { entryPoint: "execute" },kind: "workflow-task",toolName: "researcher",workflowId: "workflow://subagent-tool",@@ -304,6 +287,7 @@ describe("coordination batch identity", () => {it("rejects duplicate call ids before persisting the batch", () => {const task = {callId: "duplicate-call",+ entry: { entryPoint: "execute" as const },executeInput: { message: "go", target: "researcher" },input: { message: "go" },kind: "workflow-task" as const,@@ -322,155 +306,7 @@ describe("coordination batch identity", () => {});});-/** Parked session whose call-1 child is owned by a running agent handle. */-function createSessionWithRunningChild(): HarnessSession {- const prepared = prepareAgentStart(createParkedSession(), {- identity: {- id: deriveAgentId("researcher", OPERATION_ID),- name: "researcher",- nodeId: "subagents/researcher",- },- operation: {- callId: "call-1",- id: OPERATION_ID,- kind: "start",- parentTurnId: "turn_0",- },- target: { continuationToken: CHILD_CONTINUATION_TOKEN, kind: "agent/local" },- });- return confirmAgentStarted(prepared, {- address: {- continuationToken: CHILD_CONTINUATION_TOKEN,- kind: "agent/local",- sessionId: CHILD_SESSION_ID,- },- operationId: OPERATION_ID,- });-}-describe("resolvePendingCoordination", () => {- it("settles the running handle terminally and deletes it with the batch", async () => {- const session = createSessionWithRunningChild();-- const resolved = await resolvePendingCoordination({- session,- stepInput: {- runtimeActionResults: [- {- callId: "call-1",- kind: "subagent-result",- origin: "child",- outcome: {- kind: "terminal",- result: { kind: "succeeded", output: "done" },- usageDelta: ZERO_USAGE,- },- output: "done",- subagentName: "researcher",- },- ],- },- });-- expect(resolved.outcome).toBe("resolved");- expect(getPendingCoordinationBatch(resolved.session.state)).toBeUndefined();- expect(getAgentHandleStore(resolved.session.state)).toEqual({ handles: [] });- });-- it("settles a failed child result terminally as well", async () => {- const session = createSessionWithRunningChild();-- const resolved = await resolvePendingCoordination({- session,- stepInput: {- runtimeActionResults: [- {- callId: "call-1",- isError: true,- kind: "subagent-result",- origin: "child",- outcome: {- kind: "terminal",- result: {- error: { code: "SESSION_FAILED", message: "child failed" },- kind: "failed",- },- usageDelta: ZERO_USAGE,- },- output: { code: "SESSION_FAILED", message: "child failed" },- subagentName: "researcher",- },- ],- },- });-- expect(resolved.outcome).toBe("resolved");- expect(getAgentHandleStore(resolved.session.state)).toEqual({ handles: [] });- });-- it("does not report a cancelled child outcome as successful completion", async () => {- const events: UnstampedMessageStreamEvent[] = [];- await resolvePendingCoordination({- emit: async (event) => {- events.push(event);- },- session: createSessionWithRunningChild(),- stepInput: {- runtimeActionResults: [- {- callId: "call-1",- kind: "subagent-result",- origin: "child",- subagentName: "researcher",- output: "cancelled",- outcome: { kind: "parked", result: { kind: "cancelled" }, usageDelta: ZERO_USAGE },- },- ],- },- });- expect(events.some((event) => event.type === "subagent.completed")).toBe(false);- });-- it("clears the child's proxy-input entries before settling its handle", async () => {- const session = upsertProxyInputRequests({- entries: [- [- "request-1",- {- childContinuationToken: CHILD_CONTINUATION_TOKEN,- event: REQUEST_EVENT,- kind: "question",- },- ],- ],- forChildContinuationToken: CHILD_CONTINUATION_TOKEN,- session: createSessionWithRunningChild(),- });-- const resolved = await resolvePendingCoordination({- session,- stepInput: {- runtimeActionResults: [- {- callId: "call-1",- kind: "subagent-result",- origin: "child",- outcome: {- kind: "terminal",- result: { kind: "succeeded", output: "done" },- usageDelta: ZERO_USAGE,- },- output: "done",- subagentName: "researcher",- },- ],- },- });-- expect(resolved.outcome).toBe("resolved");- expect(getProxyInputRequests(resolved.session.state).size).toBe(0);- });-it("forgets a finished workflow tool run and withdraws only its unanswered requests", async () => {const parked = setPendingCoordinationBatch({event: { sequence: 0, stepIndex: 0, turnId: "turn_0" },@@ -480,6 +316,7 @@ describe("resolvePendingCoordination", () => {{callId: "call-1",input: { service: "api" },+ entry: { entryPoint: "execute" },kind: "workflow-task",toolName: "deploy",workflowId: "workflow//./agent/tools/deploy//execute",@@ -545,6 +382,7 @@ describe("resolvePendingCoordination", () => {{callId: "call-1",input: { service: "api" },+ entry: { entryPoint: "execute" },kind: "workflow-task",toolName: "deploy",workflowId: "workflow//./agent/tools/deploy//execute",@@ -584,398 +422,6 @@ describe("resolvePendingCoordination", () => {expect(JSON.stringify(toolMessage?.content)).toContain("deployed to https://api.example");expect(JSON.stringify(toolMessage?.content)).not.toContain('"deployed":true');});-- it("accepts a dispatch-origin failure result by callId", async () => {- const resolved = await resolvePendingCoordination({- session: createParkedSession(),- stepInput: {- runtimeActionResults: [- {- callId: "call-1",- isError: true,- kind: "subagent-result",- origin: "dispatch",- output: { code: "SUBAGENT_START_FAILED", message: "boom" },- subagentName: "researcher",- },- ],- },- });-- expect(resolved.outcome).toBe("resolved");- expect(getPendingCoordinationBatch(resolved.session.state)).toBeUndefined();- });-- it("draws completed child usage down against the parent's session totals", async () => {- const session = createSessionWithRunningChild();-- const resolved = await resolvePendingCoordination({- session,- stepInput: {- runtimeActionResults: [- {- callId: "call-1",- kind: "subagent-result",- origin: "child",- outcome: {- kind: "terminal",- result: { kind: "succeeded", output: "done" },- usageDelta: {- cacheReadTokens: 10,- cacheWriteTokens: 5,- inputTokens: 4_000,- outputTokens: 400,- },- },- output: "done",- subagentName: "researcher",- usage: {- cacheReadTokens: 10,- cacheWriteTokens: 5,- inputTokens: 4_000,- outputTokens: 400,- },- },- ],- },- });-- expect(resolved.outcome).toBe("resolved");- expect(getSessionTokenUsage(resolved.session)).toMatchObject({- inputTokens: 5_000,- outputTokens: 500,- });- });-- it("keeps a parked handle resumable — even for a failed turn — and deletes a terminal one", async () => {- const session = createSessionWithRunningChild();- const agentId = deriveAgentId("researcher", OPERATION_ID);-- const parkedResolve = await resolvePendingCoordination({- session,- stepInput: {- runtimeActionResults: [- {- callId: "call-1",- isError: true,- kind: "subagent-result",- origin: "child",- outcome: {- kind: "parked",- result: {- error: { code: "SUBAGENT_EXECUTION_FAILED", message: "schema not fulfilled" },- kind: "failed",- },- usageDelta: {- cacheReadTokens: 0,- cacheWriteTokens: 0,- inputTokens: 0,- outputTokens: 0,- },- },- output: { code: "SUBAGENT_EXECUTION_FAILED", message: "schema not fulfilled" },- subagentName: "researcher",- },- ],- },- });-- expect(parkedResolve.outcome).toBe("resolved");- expect(getAgentHandleStore(parkedResolve.session.state)?.handles).toEqual([- expect.objectContaining({ phase: "parked" }),- ]);-- // The parked handle stays resumable through the owner-scoped store.- const continueOperationId = deriveAgentOperationId({- callId: "call-2",- parentSessionId: "test-session",- parentTurnId: "turn_1",- });- const parkedHandle = getAgentHandleStore(parkedResolve.session.state)?.handles[0];- if (parkedHandle?.phase !== "parked") throw new Error("expected parked handle");- const continuedSession = {- ...parkedResolve.session,- state: {- ...parkedResolve.session.state,- "eve.agent.handles": {- handles: [- {- address: parkedHandle.address,- identity: parkedHandle.identity,- operation: {- callId: "call-2",- id: continueOperationId,- kind: "continue",- parentTurnId: "turn_1",- previousStatus: parkedHandle.lastStatus,- },- phase: "running",- },- ],- },- },- } as HarnessSession;-- // A terminal failure on the follow-up turn deletes the handle.- const secondBatch = setPendingCoordinationBatch({- tasks: [- {- callId: "call-2",- executeInput: { agentId, message: "continue", target: "researcher" },- input: { agentId, message: "continue" },- kind: "workflow-task",- toolName: "researcher",- workflowId: "workflow://subagent-tool",- },- ],- event: { sequence: 1, stepIndex: 0, turnId: "turn_1" },- responseMessages: [],- session: continuedSession,- });- const terminalResolve = await resolvePendingCoordination({- session: secondBatch,- stepInput: {- runtimeActionResults: [- {- callId: "call-2",- isError: true,- kind: "subagent-result",- origin: "child",- outcome: {- kind: "terminal",- result: {- error: { code: "SUBAGENT_EXECUTION_FAILED", message: "child crashed" },- kind: "failed",- },- usageDelta: {- cacheReadTokens: 0,- cacheWriteTokens: 0,- inputTokens: 0,- outputTokens: 0,- },- },- output: { code: "SUBAGENT_EXECUTION_FAILED", message: "child crashed" },- subagentName: "researcher",- },- ],- },- });-- expect(terminalResolve.outcome).toBe("resolved");- expect(getAgentHandleStore(terminalResolve.session.state)).toEqual({ handles: [] });- });-- it("folds each turn's usage delta once so a two-turn child never double-counts", async () => {- // Turn 1: the child spent 4000/400 and parked.- const session = createSessionWithRunningChild();- const agentId = deriveAgentId("researcher", OPERATION_ID);- const firstResolve = await resolvePendingCoordination({- session,- stepInput: {- runtimeActionResults: [- {- callId: "call-1",- kind: "subagent-result",- origin: "child",- outcome: {- kind: "parked",- result: { kind: "succeeded", output: "first answer" },- usageDelta: {- cacheReadTokens: 0,- cacheWriteTokens: 0,- inputTokens: 4_000,- outputTokens: 400,- },- },- output: "first answer",- subagentName: "researcher",- // Cumulative child-session totals: folding these instead of the- // delta would double-count turn 1 on the next settlement.- usage: {- cacheReadTokens: 0,- cacheWriteTokens: 0,- inputTokens: 4_000,- outputTokens: 400,- },- },- ],- },- });- expect(getSessionTokenUsage(firstResolve.session)).toMatchObject({- inputTokens: 5_000,- outputTokens: 500,- });-- // Turn 2: the child spent another 1000/100 (cumulative 5000/500).- const parkedHandle = getAgentHandleStore(firstResolve.session.state)?.handles[0];- if (parkedHandle?.phase !== "parked") throw new Error("expected parked handle");- const continuedSession = {- ...firstResolve.session,- state: {- ...firstResolve.session.state,- "eve.agent.handles": {- handles: [- {- address: parkedHandle.address,- identity: parkedHandle.identity,- operation: {- callId: "call-2",- id: deriveAgentOperationId({- callId: "call-2",- parentSessionId: "test-session",- parentTurnId: "turn_1",- }),- kind: "continue",- parentTurnId: "turn_1",- previousStatus: parkedHandle.lastStatus,- },- phase: "running",- },- ],- },- },- } as HarnessSession;- const secondBatch = setPendingCoordinationBatch({- tasks: [- {- callId: "call-2",- executeInput: { agentId, message: "continue", target: "researcher" },- input: { agentId, message: "continue" },- kind: "workflow-task",- toolName: "researcher",- workflowId: "workflow://subagent-tool",- },- ],- event: { sequence: 1, stepIndex: 0, turnId: "turn_1" },- responseMessages: [],- session: continuedSession,- });- const secondResolve = await resolvePendingCoordination({- session: secondBatch,- stepInput: {- runtimeActionResults: [- {- callId: "call-2",- kind: "subagent-result",- origin: "child",- outcome: {- kind: "parked",- result: { kind: "succeeded", output: "second answer" },- usageDelta: {- cacheReadTokens: 0,- cacheWriteTokens: 0,- inputTokens: 1_000,- outputTokens: 100,- },- },- output: "second answer",- subagentName: "researcher",- usage: {- cacheReadTokens: 0,- cacheWriteTokens: 0,- inputTokens: 5_000,- outputTokens: 500,- },- },- ],- },- });-- // Own 1000/100 + turn deltas (4000+1000)/(400+100) — never the child's- // cumulative 5000/500 twice.- expect(getSessionTokenUsage(secondResolve.session)).toMatchObject({- inputTokens: 6_000,- outputTokens: 600,- });- });-- it("leaves the parent's totals untouched when the child reports a zero usage delta", async () => {- const session = createSessionWithRunningChild();-- const resolved = await resolvePendingCoordination({- session,- stepInput: {- runtimeActionResults: [- {- callId: "call-1",- kind: "subagent-result",- origin: "child",- outcome: {- kind: "terminal",- result: { kind: "succeeded", output: "done" },- usageDelta: ZERO_USAGE,- },- output: "done",- subagentName: "researcher",- },- ],- },- });-- expect(resolved.outcome).toBe("resolved");- expect(getSessionTokenUsage(resolved.session)).toMatchObject({- inputTokens: 1_000,- outputTokens: 100,- });- });-});--describe("result-to-handle binding", () => {- const boundResult = {- callId: "call-1",- kind: "subagent-result",- origin: "child",- outcome: {- kind: "terminal",- result: { kind: "succeeded", output: "done" },- usageDelta: ZERO_USAGE,- },- output: "done",- subagentName: "researcher",- } as const;-- it("accepts only results a running handle binds by callId", () => {- // Possession of the callback token authorizes settlement; binding is by- // callId alone. A callId with no running handle — one whose dispatch- // already failed — finds nothing and cannot overwrite the- // dispatch-produced error result.- const state = createSessionWithRunningChild().state;-- for (const bound of [isResultBoundToRunningHandle, isInboxSubagentResultFromRunningHandle]) {- expect(bound(state, boundResult)).toBe(true);- expect(bound(state, { ...boundResult, callId: "call-other" })).toBe(false);- }- expect(- isResultBoundToRunningHandle(state, {- callId: "call-1",- kind: "tool-result",- output: "",- toolName: "x",- }),- ).toBe(true);- expect(- isInboxSubagentResultFromRunningHandle(state, {- ...boundResult,- callId: "call-unknown",- }),- ).toBe(false);- });-- it("trusts dispatch-origin results on the parent step path", () => {- // The subagent-only inbox type cannot represent dispatch failures. These- // parent-synthesized results enter through the trusted step-result path.- const dispatchFailure = {- callId: "call-1",- isError: true,- kind: "subagent-result",- origin: "dispatch",- output: { code: "SUBAGENT_START_FAILED", message: "boom" },- subagentName: "researcher",- } as const;- const state = createSessionWithRunningChild().state;-- expect(isResultBoundToRunningHandle(state, dispatchFailure)).toBe(true);- });});describe("resolveToolCallInputObject", () => {diff --git a/packages/eve/src/harness/coordination.ts b/packages/eve/src/harness/coordination.tsindex eb8f2f569..1c9dee26b 100644--- a/packages/eve/src/harness/coordination.ts+++ b/packages/eve/src/harness/coordination.ts@@ -1,32 +1,25 @@import type { ModelMessage, ToolSet, TypedToolCall } from "ai";-import { createActionResultEvent, type UnstampedMessageStreamEvent } from "#protocol/message.js";+import { createActionResultEvent } from "#protocol/message.js";import { resolveRuntimeActionResultsForCallIds } from "#runtime/actions/results.js";import type {RuntimeActionRequest,RuntimeActionResult,RuntimeWorkflowTaskRequest,+ WorkflowToolCallEntry,} from "#shared/action-types.js";import { markRuntimeWorkflowToolAction } from "#shared/action-types.js";import { parseJsonObject, type JsonObject } from "#shared/json.js";-import type { AgentTurnOutcome } from "#shared/agent-turn-outcome.js";-import { findRunningAgentHandle, isResultBoundToRunningHandle } from "#subagents/handles/query.js";-import { settleAgentTurn } from "#subagents/handles/transitions.js";-import {- clearProxyInputRequestsForChild,- clearProxyInputRequestsWhere,-} from "#harness/proxy-input-requests.js";+import { clearProxyInputRequestsWhere } from "#harness/proxy-input-requests.js";import {findBlockingWorkflowToolRun,removeBlockingWorkflowToolRuns,} from "#harness/workflow-tool-runs.js";+import { validateHarnessModelMessages } from "#harness/messages.js";import { normalizeToolModelOutput } from "#harness/tool-model-output.js";import type { HarnessToolDefinition } from "#harness/execute-tool.js";-import {- accumulateSessionUsage,- getTurnUsageState,- setTurnUsageState,-} from "#harness/turn-tag-state.js";+import { pendingTaskToolCalls } from "#execution/tasks/calls.js";+import { startsTasks } from "#execution/tasks/tool-entry-point.js";import type {HarnessEmitFn,HarnessSession,@@ -39,17 +32,6 @@ const PENDING_COORDINATION_BATCH_KEY = "eve.runtime.pendingCoordinationBatch";type ToolResponsePart = Extract<ModelMessage, { role: "tool" }>["content"][number];type ToolResultPart = Extract<ToolResponsePart, { type: "tool-result" }>;-/**- * Lifecycle outcome from a subagent result. Only `child`-origin results- * carry one; parent-synthesized dispatch failures never do, and their type- * omits the field entirely.- */-function readSubagentResultOutcome(- result: Extract<RuntimeActionResult, { kind: "subagent-result" }>,-): AgentTurnOutcome | undefined {- return result.origin === "child" ? result.outcome : undefined;-}-/*** Serializable event coordinates for one pending coordination batch.*@@ -62,18 +44,11 @@ interface PendingCoordinationEventMetadata {readonly turnId: string;}-/**- * Serializable pending coordination batch stored on `session.state`.- *- * Child ownership does not live here: the agent handle store records every- * dispatched child (from before its start side effect) and is the sole- * authority for continuing, settling, and cancelling children.- */+/** Serializable pending coordination batch stored on `session.state`. */export interface PendingCoordinationBatch {- /** Authored-tool and subagent workflow tasks pending coordination. */+ /** Workflow tool runs pending coordination, including agent tools. */readonly tasks: readonly RuntimeWorkflowTaskRequest[];readonly event: PendingCoordinationEventMetadata;- readonly localFanoutSize?: number;readonly responseMessages: readonly ModelMessage[];}@@ -119,13 +94,46 @@ export function clearPendingCoordinationBatch(session: HarnessSession): HarnessSreturn { ...session, state: Object.keys(state).length > 0 ? state : undefined };}+/** What the model reads for a call its turn's cancellation stopped before the call settled. */+export const CANCELLED_CALL_RESULT = "The turn was cancelled before this call finished.";++/**+ * Moves a cancelled turn's pending batch into history instead of dropping it.+ * The model keeps the calls it made, each answered as cancelled, so it sees+ * that the work started and stopped rather than a request left unanswered.+ */+export function commitCancelledCoordinationBatch(session: HarnessSession): HarnessSession {+ const batch = getPendingCoordinationBatch(session.state);+ if (batch === undefined) return session;+ const cancelledCalls = [+ ...batch.tasks.map((task) => ({ callId: task.callId, toolName: task.toolName })),+ ...pendingTaskToolCalls(batch.responseMessages).map((call) => ({+ callId: call.callId,+ toolName: call.kind,+ })),+ ];+ const cancelledResults = cancelledCalls.map(({ callId, toolName }): ToolResultPart => ({+ output: { type: "text", value: CANCELLED_CALL_RESULT },+ toolCallId: callId,+ toolName,+ type: "tool-result",+ }));+ const history = validateHarnessModelMessages([+ ...session.history,+ ...batch.responseMessages,+ ...(cancelledResults.length === 0+ ? []+ : [{ content: cancelledResults, role: "tool" as const }]),+ ]);+ return clearPendingCoordinationBatch({ ...session, history });+}+/*** Stores one pending coordination batch on the session.*/export function setPendingCoordinationBatch(input: {readonly tasks: readonly RuntimeWorkflowTaskRequest[];readonly event: PendingCoordinationEventMetadata;- readonly localFanoutSize?: number;readonly responseMessages: readonly ModelMessage[];readonly session: HarnessSession;}): HarnessSession {@@ -134,7 +142,6 @@ export function setPendingCoordinationBatch(input: {state[PENDING_COORDINATION_BATCH_KEY] = {tasks: [...input.tasks],event: input.event,- localFanoutSize: input.localFanoutSize,responseMessages: [...input.responseMessages],} satisfies PendingCoordinationBatch;@@ -169,22 +176,16 @@ function resolveReadyCoordinationResults(input: {return undefined;}- return resolveResultsForCoordinationBatch({- batch,+ return resolveRuntimeActionResultsForCallIds({+ pendingCallIds: pendingCoordinationCallIds(batch),results: input.results,- state: input.session.state,});}-function resolveResultsForCoordinationBatch(input: {- readonly batch: PendingCoordinationBatch;- readonly results: readonly RuntimeActionResult[];- readonly state: SessionStateMap | undefined;-}): RuntimeActionResult[] | undefined {- return resolveRuntimeActionResultsForCallIds({- pendingCallIds: input.batch.tasks.map((request) => request.callId),- results: input.results.filter((result) => isResultBoundToRunningHandle(input.state, result)),- });+/** Every call a pending batch waits on: workflow runs and task tool calls. */+export function pendingCoordinationCallIds(batch: PendingCoordinationBatch): readonly string[] {+ const taskToolCallIds = pendingTaskToolCalls(batch.responseMessages).map((call) => call.callId);+ return [...batch.tasks.map((request) => request.callId), ...taskToolCallIds];}/**@@ -192,8 +193,8 @@ function resolveResultsForCoordinationBatch(input: {** When all expected runtime action results are present, this appends the* stored assistant tool-call messages plus synthesized tool-result messages to- * history, clears the pending batch, and emits `subagent.completed` and- * `action.result` events back onto the parent stream.+ * history, clears the pending batch, and emits `action.result` events back+ * onto the parent stream.*/export async function resolvePendingCoordination(input: {readonly emit?: HarnessEmitFn;@@ -225,39 +226,7 @@ export async function resolvePendingCoordination(input: {};}- // Settle each bound child result against its running handle from the- // outcome the child engine reported: `parked` keeps the handle (the child- // is idle and resumable), `terminal` deletes it. Before a terminal- // deletion the proxy-input entry keyed by the child's continuation token- // is cleared (the handle is the only record of that token) so future- // deliveries don't route responses to a dead child.let nextSession: HarnessSession = input.session;- for (const result of readyResults) {- // Dispatch failures never settle handles: the dispatch step already- // rejected (deleted) the handle when it synthesized the failure.- if (result.kind !== "subagent-result" || result.origin !== "child") {- continue;- }- const handle = findRunningAgentHandle(nextSession.state, { callId: result.callId });- if (handle === undefined) {- continue;- }- const outcome = readSubagentResultOutcome(result);- if (outcome === undefined) {- continue;- }- if (outcome.kind === "terminal" && "continuationToken" in handle.address) {- nextSession = clearProxyInputRequestsForChild(nextSession, handle.address.continuationToken);- }- const settled = settleAgentTurn(nextSession, {- operationId: handle.operation.id,- outcome,- });- if (settled.kind === "settled") {- nextSession = settled.session;- }- }-// Drop a finished run's unanswered requests so a late click cannot reach it.for (const result of readyResults) {if (result.kind !== "tool-result") continue;@@ -284,48 +253,8 @@ export async function resolvePendingCoordination(input: {state: Object.keys(state).length > 0 ? state : undefined,};- // Draw settled child spend down against the parent's session totals so- // the session token limits and the remaining-quota budget granted to later- // delegations account for what the tree has already spent. Every outcome- // carries the child turn's `usageDelta`, folded exactly once per settled- // result (each batch resolves once), so repeated turns of a persistent- // child never double-count earlier turns. Only child-produced results- // carry an outcome; parent-side dispatch failures never do.- for (const result of readyResults) {- if (result.kind !== "subagent-result") {- continue;- }- const outcome = readSubagentResultOutcome(result);- if (outcome === undefined) {- continue;- }- nextSession = setTurnUsageState(- nextSession,- accumulateSessionUsage({- previous: getTurnUsageState(nextSession.state),- usage: outcome.usageDelta,- }),- );- }-if (input.emit !== undefined) {for (const result of readyResults) {- if (- result.kind === "subagent-result" &&- result.origin === "child" &&- result.outcome.result.kind === "succeeded"- ) {- const data = {- callId: result.callId,- output: typeof result.output === "string" ? result.output : JSON.stringify(result.output),- subagentName: result.subagentName,- };- await input.emit({- data,- type: "subagent.completed",- } satisfies Extract<UnstampedMessageStreamEvent, { type: "subagent.completed" }>);- }-await input.emit(createActionResultEvent({result,@@ -408,8 +337,13 @@ export function createRuntimeActionRequestFromToolCall(input: {return definition?.workflowId === undefined ? action : markRuntimeWorkflowToolAction(action);}-/** Projects one deferred harness tool call into a workflow run request. */+/**+ * Projects one deferred harness tool call into a workflow run request. The+ * input is the tool's own, without anything eve added to its model input.+ */export function createCoordinationRequestFromToolCall(input: {+ readonly entry: WorkflowToolCallEntry;+ readonly input: JsonObject;readonly toolCall: TypedToolCall<ToolSet>;readonly tools: HarnessToolMap;}): RuntimeWorkflowTaskRequest {@@ -417,14 +351,11 @@ export function createCoordinationRequestFromToolCall(input: {if (definition?.workflowId === undefined) {throw new Error(`Deferred tool "${input.toolCall.toolName}" has no workflow.`);}- const inputObject = resolveToolCallInputObject(input.toolCall.input, {- callId: input.toolCall.toolCallId,- toolName: input.toolCall.toolName,- });return {callId: input.toolCall.toolCallId,- executeInput: definition.executeInput?.(inputObject),- input: inputObject,+ entry: input.entry,+ executeInput: definition.executeInput?.(input.input),+ input: input.input,kind: "workflow-task",toolName: input.toolCall.toolName,workflowId: definition.workflowId,@@ -475,7 +406,12 @@ async function projectToolResultOutput(result: Extract<RuntimeActionResult, { kind: "tool-result" }>,definition: HarnessToolDefinition | undefined,): Promise<ToolResultPart["output"]> {- if (result.isError === true || definition?.toModelOutput === undefined) {+ // A task tool's call result is its receipt; `toModelOutput` projects the task's result.+ if (+ result.isError === true ||+ definition?.toModelOutput === undefined ||+ startsTasks(definition)+ ) {return toToolResultOutput(result);}return normalizeToolModelOutput({diff --git a/packages/eve/src/harness/emission.test.ts b/packages/eve/src/harness/emission.test.tsindex e8c2b8016..d969b33de 100644--- a/packages/eve/src/harness/emission.test.ts+++ b/packages/eve/src/harness/emission.test.ts@@ -472,7 +472,6 @@ describe("emitStreamContent action requests", () => {description: "Delegate work to a subagent.",inputSchema: jsonSchema({ type: "object" }),name: "delegate",- nodeId: "subagents/researcher",workflowId: "workflow//./agent/subagents/researcher//execute",},],diff --git a/packages/eve/src/harness/emission.ts b/packages/eve/src/harness/emission.tsindex 6cc3fc885..690925fdc 100644--- a/packages/eve/src/harness/emission.ts+++ b/packages/eve/src/harness/emission.ts@@ -258,6 +258,12 @@ interface EmittedStreamContent {interface StreamActionEmissionOptions {readonly excludedActionToolNames: ReadonlySet<string>;+ /**+ * A child's or schedule's turn is held while its tasks work, so a text step+ * can't end it: the step reports `"tool-calls"` and channels don't post it+ * as the reply.+ */+ readonly hidesHeldText?: boolean;readonly tools: HarnessToolMap;}@@ -297,6 +303,15 @@ export async function emitStreamContent(}}+/** A hidden held turn's text step isn't its reply, so it reports `"tool-calls"` as channels expect. */+function reportedFinishReason(+ finishReason: AssistantStepFinishReason,+ hidesHeldText: boolean,+): AssistantStepFinishReason {+ if (hidesHeldText && finishReason === "stop") return "tool-calls";+ return finishReason;+}+async function consumeStreamContent(emitFn: HarnessEmitFn,state: HarnessEmissionState,@@ -665,7 +680,7 @@ async function consumeStreamContent(if (finishReason !== "content-filter" && currentMessage.trim().length > 0) {await emitFn(createMessageCompletedEvent({- finishReason,+ finishReason: reportedFinishReason(finishReason, options?.hidesHeldText === true),message: currentMessage,sequence: state.sequence,stepIndex: state.stepIndex,diff --git a/packages/eve/src/harness/execute-tool.ts b/packages/eve/src/harness/execute-tool.tsindex 6ea91954c..cc0f5a9c9 100644--- a/packages/eve/src/harness/execute-tool.ts+++ b/packages/eve/src/harness/execute-tool.ts@@ -17,11 +17,9 @@ export interface HarnessToolDefinition {readonly execute?: (input: any, options: ToolExecuteOptions) => any;/** Optional JSON input substituted when this tool starts its workflow body. */readonly executeInput?: (input: unknown) => JsonValue;- readonly frameworkAction?: "load-skill";+ readonly frameworkAction?: "load-skill" | "task-cancel" | "task-wait";readonly inputSchema: FlexibleSchema;readonly name: string;- /** Selected agent definition's runtime graph ID; absent for authored workflow tools. */- readonly nodeId?: string;readonly approval?: Approval;readonly outputSchema?: FlexibleSchema;/**diff --git a/packages/eve/src/harness/messages.ts b/packages/eve/src/harness/messages.tsindex 65fc4fabe..ace0ab83c 100644--- a/packages/eve/src/harness/messages.ts+++ b/packages/eve/src/harness/messages.ts@@ -17,7 +17,8 @@ export type FrameworkMessageKind =| "context.compaction"| "memory.load"| "execution.continuation"- | "execution.retry";+ | "execution.retry"+ | "task.result";/** Semantic classification for every user-role message in model history. */export type UserMessageKind = "user" | FrameworkMessageKind;@@ -108,7 +109,8 @@ export function isFrameworkMessageKind(value: unknown): value is FrameworkMessagvalue === "context.compaction" ||value === "memory.load" ||value === "execution.continuation" ||- value === "execution.retry"+ value === "execution.retry" ||+ value === "task.result");}@@ -428,9 +430,10 @@ export function coalesceDeliveries<T extends DeliverLike>(items: readonly T[]):auth = item.auth;}if (item.caller !== undefined) {- if (caller !== undefined) {+ if (caller !== undefined && caller.callId !== item.caller.callId) {throw new Error("Cannot coalesce deliveries from different turns.");}+ // The same caller's later message awaits its reply at its own address.caller = item.caller;}payloads.push(...item.payloads);diff --git a/packages/eve/src/harness/provider-tool-history.test.ts b/packages/eve/src/harness/provider-tool-history.test.tsindex 5e8a9094d..33895a22e 100644--- a/packages/eve/src/harness/provider-tool-history.test.ts+++ b/packages/eve/src/harness/provider-tool-history.test.ts@@ -142,7 +142,7 @@ describe("normalizeProviderToolHistory", () => {expect(normalized.outcomeEndsResponse).toBe(true);});- it("normalizes provider-owned results when the turn also calls a local tool", () => {+ it("keeps local tool calls next to their results around provider-owned results", () => {const messages: ModelMessage[] = [{role: "assistant",@@ -166,6 +166,19 @@ describe("normalizeProviderToolHistory", () => {toolName: "read_file",input: { filePath: "/workspace/a.ts" },},+ {+ type: "tool-call",+ toolCallId: "search-2",+ toolName: "web_search",+ input: { query: "Follow-up result" },+ providerExecuted: true,+ },+ {+ type: "tool-result",+ toolCallId: "search-2",+ toolName: "web_search",+ output: { type: "json", value: { results: [] } },+ },],},{@@ -183,7 +196,7 @@ describe("normalizeProviderToolHistory", () => {const normalized = normalizeProviderToolHistory({messages,- providerExecutedOutcomeIds: new Set(["search-1"]),+ providerExecutedOutcomeIds: new Set(["search-1", "search-2"]),});expect(normalized.messages).toEqual([@@ -210,6 +223,29 @@ describe("normalizeProviderToolHistory", () => {},],},+ {+ role: "assistant",+ content: [+ {+ type: "tool-call",+ toolCallId: "search-2",+ toolName: "web_search",+ input: { query: "Follow-up result" },+ providerExecuted: false,+ },+ ],+ },+ {+ role: "tool",+ content: [+ {+ type: "tool-result",+ toolCallId: "search-2",+ toolName: "web_search",+ output: { type: "json", value: { results: [] } },+ },+ ],+ },{role: "assistant",content: [diff --git a/packages/eve/src/harness/provider-tool-history.ts b/packages/eve/src/harness/provider-tool-history.tsindex c2a68c1a3..d050cfa16 100644--- a/packages/eve/src/harness/provider-tool-history.ts+++ b/packages/eve/src/harness/provider-tool-history.ts@@ -9,6 +9,9 @@ import type { ModelMessage, ToolModelMessage } from "ai";* call lacks the matching marker or shares an assistant message with a local* tool call. Native provider-only call/result pairs remain untouched. Text* before a result remains before it; text after a result remains after it.+ * Local tool calls in a split message, with their approval requests, move to+ * its last assistant message, so the local results that follow the response+ * directly follow their calls.*/export function normalizeProviderToolHistory(input: {readonly messages: readonly ModelMessage[];@@ -40,6 +43,11 @@ export function normalizeProviderToolHistory(input: {let assistantContent: typeof message.content = [];let toolContent: ToolModelMessage["content"] = [];+ const localCallParts: typeof message.content = [];+ const localCallIds = new Set<string>();+ const splits = message.content.some(+ (part) => part.type === "tool-result" && toolCallIdsToNormalize.has(part.toolCallId),+ );const flushAssistant = (): void => {if (assistantContent.length === 0) return;@@ -56,6 +64,19 @@ export function normalizeProviderToolHistory(input: {if (part.type === "tool-result" && toolCallIdsToNormalize.has(part.toolCallId)) {flushAssistant();toolContent.push(part);+ } else if (+ splits &&+ part.type === "tool-call" &&+ part.providerExecuted !== true &&+ !toolCallIdsToNormalize.has(part.toolCallId)+ ) {+ // Local results arrive after the whole response. Keeping their calls+ // in an earlier split would put a later provider result between a+ // call and its result, which providers reject.+ localCallIds.add(part.toolCallId);+ localCallParts.push(part);+ } else if (part.type === "tool-approval-request" && localCallIds.has(part.toolCallId)) {+ localCallParts.push(part);} else {flushTool();assistantContent.push(@@ -73,8 +94,9 @@ export function normalizeProviderToolHistory(input: {position += 1;}- flushAssistant();flushTool();+ assistantContent.push(...localCallParts);+ flushAssistant();}return {diff --git a/packages/eve/src/harness/proxy-input-requests.test.ts b/packages/eve/src/harness/proxy-input-requests.test.tsindex 3c3c4411a..782785a32 100644--- a/packages/eve/src/harness/proxy-input-requests.test.ts+++ b/packages/eve/src/harness/proxy-input-requests.test.ts@@ -1,7 +1,6 @@import { describe, expect, it } from "vitest";import {- clearProxyInputRequestsForChild,getProxyInputRequests,hasProxyInputRequests,toProxyInputRequestEntries,@@ -217,45 +216,6 @@ describe("toProxyInputRequestEntries", () => {});});-describe("clearProxyInputRequestsForChild", () => {- it("removes only the target child's entries", () => {- let session = upsertProxyInputRequests({- entries: [- ["req-a", { childContinuationToken: "child-a", event: REQUEST_EVENT, kind: "question" }],- ],- forChildContinuationToken: "child-a",- session: createSession(),- });-- session = upsertProxyInputRequests({- entries: [- [- "req-b",- { childContinuationToken: "child-b", event: REQUEST_EVENT, kind: "tool-approval" },- ],- ],- forChildContinuationToken: "child-b",- session,- });-- session = clearProxyInputRequestsForChild(session, "child-a");- const entries = getProxyInputRequests(session.state);-- expect(entries.size).toBe(1);- expect(entries.get("req-b")).toEqual({- childContinuationToken: "child-b",- event: REQUEST_EVENT,- kind: "tool-approval",- });- });-- it("returns the same session when there is nothing to clear", () => {- const session = createSession();- const next = clearProxyInputRequestsForChild(session, "missing");- expect(next).toBe(session);- });-});-describe("getProxyInputRequests type safety", () => {it("returns an empty map when the session carries no proxy state", () => {const entries = getProxyInputRequests(createSession().state);diff --git a/packages/eve/src/harness/proxy-input-requests.ts b/packages/eve/src/harness/proxy-input-requests.tsindex 17c895444..253e91b9f 100644--- a/packages/eve/src/harness/proxy-input-requests.ts+++ b/packages/eve/src/harness/proxy-input-requests.ts@@ -127,20 +127,6 @@ export function upsertProxyInputRequestState(input: {return Object.keys(state).length > 0 ? state : undefined;}-/**- * Removes every entry for `childContinuationToken`. Called when a- * child subagent finishes so stale clicks no longer route to it.- */-export function clearProxyInputRequestsForChild(- session: HarnessSession,- childContinuationToken: string,-): HarnessSession {- return clearProxyInputRequestsWhere(- session,- (route) => route.childContinuationToken === childContinuationToken,- );-}-/** Removes every proxy route the predicate selects. */export function clearProxyInputRequestsWhere<T extends { readonly state?: SessionStateMap }>(session: T,diff --git a/packages/eve/src/harness/tool-loop.test.ts b/packages/eve/src/harness/tool-loop.test.tsindex 52ac9fe01..7edf6df2d 100644--- a/packages/eve/src/harness/tool-loop.test.ts+++ b/packages/eve/src/harness/tool-loop.test.ts@@ -70,12 +70,12 @@ import {appendPendingInputBatch,} from "#harness/input-requests.js";import { getDeferredStepInput } from "#harness/pending-input-batches.js";-import { getPendingCoordinationBatch } from "#harness/coordination.js";-import { AGENT_HANDLES_STATE_KEY } from "#subagents/handles/store.js";+import { getPendingCoordinationBatch, pendingCoordinationCallIds } from "#harness/coordination.js";import { PendingSkillAnnouncementKey } from "#context/dynamic-skill-lifecycle.js";import { deserializeContext, serializeContext } from "#context/serialize.js";import { stashToolInterrupt } from "#harness/tool-interrupts.js";import { appendMissingToolResultMessages, createToolLoopHarness } from "#harness/tool-loop.js";+import { createTask, writeTaskTable } from "#execution/tasks/table.js";import { SessionLimitDeclinedError, TurnCancelledError } from "#harness/turn-cancellation.js";import {getSessionUsageLimitViolation,@@ -1073,215 +1073,6 @@ describe("createToolLoopHarness", () => {expect(agentCall!.tools).not.toHaveProperty("Workflow");});- it("announces parked agents as user-role content before the user message, outside the system prompt", async () => {- setupMockAgent({- finishReason: "stop",- response: { messages: [{ content: "Hello!", role: "assistant" }] },- text: "Hello!",- toolCalls: [],- toolResults: [],- });-- const runStep = createToolLoopHarness(- createTestConfig(undefined, {- historyProjector: ({ messages }) => [...messages],- resolveModel: vi.fn().mockResolvedValue(- new MockLanguageModelV3({- modelId: "claude-sonnet-4-5",- provider: "anthropic.messages",- }),- ),- }),- );- const session = createTestSession({- state: {- [AGENT_HANDLES_STATE_KEY]: {- handles: [- {- address: {- continuationToken: "private-token",- kind: "agent/local",- sessionId: "child-session-123456789012",- },- identity: {- id: "ag_research:123456789012",- name: "research",- nodeId: "subagents/research",- },- lastStatus: "waiting",- phase: "parked",- },- ],- },- },- });-- const result = await runStep(session, { message: "Hi" });-- const { instructions } = vi.mocked(ToolLoopAgent).mock.calls[0]![0];- const agent = vi.mocked(ToolLoopAgent).mock.results[0]?.value as {- generate: ReturnType<typeof vi.fn>;- };- const messages = agent.generate.mock.calls[0]?.[0].messages as ModelMessage[];- // The volatile listing stays out of the system prompt (prompt cache) and- // rides history as a labeled, framework-injected user message.- expect(instructions).toBe("You are a test assistant.");- expect(messages).toContainEqual({- content: expect.stringContaining(- '<agent id="ag_research:123456789012" name="research">waiting</agent>',- ),- kind: "context.state",- role: "user",- });- // The announcement precedes the turn's actual user message.- expect(messages.at(-1)).toEqual({ content: "Hi", kind: "user" as const, role: "user" });- expect(messages.at(-2)).toEqual({- content: expect.stringContaining("[Agents]"),- kind: "context.state",- role: "user",- });- expect(JSON.stringify({ instructions, messages })).not.toContain("private-token");- expect(result.session.history).toContainEqual({- content: expect.stringContaining('<agent id="ag_research:123456789012"'),- kind: "context.state",- role: "user",- });- });-- it("skips the agents snippet when no handle is parked", async () => {- setupMockAgent({- finishReason: "stop",- response: { messages: [{ content: "Hello!", role: "assistant" }] },- text: "Hello!",- toolCalls: [],- toolResults: [],- });-- const runStep = createToolLoopHarness(createTestConfig());- const session = createTestSession({- state: {- [AGENT_HANDLES_STATE_KEY]: {- handles: [- {- identity: {- id: "ag_research:123456789012",- name: "research",- nodeId: "subagents/research",- },- operation: {- callId: "call-1",- id: "op-1",- kind: "start",- parentTurnId: "turn-1",- },- phase: "starting",- target: { continuationToken: "private-token", kind: "agent/local" },- },- ],- },- },- });-- await runStep(session, { message: "Hi" });-- const call = vi.mocked(ToolLoopAgent).mock.calls[0]?.[0];- const agent = vi.mocked(ToolLoopAgent).mock.results[0]?.value as {- generate: ReturnType<typeof vi.fn>;- };- const messages = agent.generate.mock.calls[0]?.[0].messages as ModelMessage[];- expect(JSON.stringify(call?.instructions ?? "")).not.toContain("<agents>");- expect(JSON.stringify(messages)).not.toContain("<agents>");- });-- // Regression: a child settling used to append the updated <agents> listing- // to history as an assistant message. On a resume with no new user input the- // request then ended with `assistant`, which Anthropic rejects ("this model- // does not support assistant message prefill"). The announcement is- // user-role content, so on a no-input resume it trails the tool results- // and the request stays user-final.- it("keeps a no-input resume provider-valid when a parked handle is announced", async () => {- setupMockAgent({- finishReason: "stop",- response: { messages: [{ content: "Done.", role: "assistant" }] },- text: "Done.",- toolCalls: [],- toolResults: [],- });-- const runStep = createToolLoopHarness(createTestConfig());- const session = createTestSession({- history: [- { content: "Delegate this.", kind: "user" as const, role: "user" },- {- content: [- {- input: { message: "do it" },- toolCallId: "call-1",- toolName: "research",- type: "tool-call",- },- ],- role: "assistant",- },- {- content: [- {- output: { type: "text", value: "child answered" },- toolCallId: "call-1",- toolName: "research",- type: "tool-result",- },- ],- role: "tool",- },- ],- state: {- [AGENT_HANDLES_STATE_KEY]: {- handles: [- {- address: {- continuationToken: "private-token",- kind: "agent/local",- sessionId: "child-session-123456789012",- },- identity: {- id: "ag_research:123456789012",- name: "research",- nodeId: "subagents/research",- },- lastStatus: "child answered",- phase: "parked",- },- ],- },- },- });-- const result = await runStep(session);-- const { instructions } = vi.mocked(ToolLoopAgent).mock.calls[0]![0];- const agent = vi.mocked(ToolLoopAgent).mock.results[0]?.value as {- generate: ReturnType<typeof vi.fn>;- };- const messages = agent.generate.mock.calls[0]?.[0].messages as ModelMessage[];- // The request ends user-final: the announcement trails the tool results.- expect(messages.at(-1)).toEqual({- content: expect.stringContaining('<agent id="ag_research:123456789012"'),- kind: "context.state",- role: "user",- });- expect(messages.filter((message) => message.role === "assistant")).toHaveLength(1);- // The volatile listing never rides the system prompt (prompt cache).- expect(JSON.stringify(instructions ?? "")).not.toContain("<agents>");- // The announcement persists append-only so the next step's diff gate- // sees it and does not re-announce an unchanged listing.- expect(result.session.history.at(-2)).toEqual({- content: expect.stringContaining("[Agents]"),- kind: "context.state",- role: "user",- });- });-it.each([undefined, "low", "provider-default"] as const)("uses dynamic model selection and reasoning (%s) for the model call",async (reasoning) => {@@ -1713,53 +1504,13 @@ describe("createToolLoopHarness", () => {),).toHaveLength(1);- const parkedWithRunningDelegate = {- ...parked.session,- state: {- ...parked.session.state,- [AGENT_HANDLES_STATE_KEY]: {- handles: [- {- address: {- continuationToken: "delegate-token",- kind: "agent/local",- sessionId: "delegate-session",- },- identity: {- id: "ag_delegate:delegate",- name: "delegate",- nodeId: "workers",- },- operation: {- callId: "delegate-1",- id: "delegate-operation",- kind: "start",- parentTurnId: "turn_0",- },- phase: "running",- },- ],- },- },- } satisfies HarnessSession;- const reparked = await runStep(parkedWithRunningDelegate, {+ const reparked = await runStep(parked.session, {runtimeActionResults: [{callId: "delegate-1",- kind: "subagent-result",- origin: "child",- outcome: {- kind: "terminal",- result: { kind: "succeeded", output: "delegated-done" },- usageDelta: {- cacheReadTokens: 0,- cacheWriteTokens: 0,- inputTokens: 0,- outputTokens: 0,- },- },+ kind: "tool-result",output: "delegated-done",- subagentName: "delegate",+ toolName: "delegate",},],});@@ -1769,10 +1520,90 @@ describe("createToolLoopHarness", () => {expect(hasPendingInputBatch(reparked.session.state)).toBe(true);const toolMessages = reparked.session.history.filter((message) => message.role === "tool");expect(JSON.stringify(toolMessages)).toContain("delegated-done");- expect(events.filter((event) => event.type === "subagent.completed")).toHaveLength(1);expect(events.at(-1)?.type).toBe("session.waiting");});+ it("waits on a task_wait parked beside an approval, but not on an invalid task_cancel", async () => {+ const gateToolCall = {+ input: { action: "run" },+ toolCallId: "gate-1",+ toolName: "add",+ type: "tool-call" as const,+ };+ const waitToolCall = {+ input: {},+ toolCallId: "wait-1",+ toolName: "task_wait",+ type: "tool-call" as const,+ };+ const invalidCancelToolCall = {+ input: "not an object",+ toolCallId: "cancel-1",+ toolName: "task_cancel",+ type: "tool-call" as const,+ };+ const assistantContent = [+ gateToolCall,+ { approvalId: "approval-gate", toolCallId: "gate-1", type: "tool-approval-request" as const },+ waitToolCall,+ invalidCancelToolCall,+ ];+ setupMockAgent({+ content: assistantContent,+ finishReason: "tool-calls",+ response: { messages: [{ content: assistantContent, role: "assistant" }] },+ responseMessages: [+ {+ content: [+ {+ output: { type: "text", value: "/workspace" },+ toolCallId: "call-1",+ toolName: "bash",+ type: "tool-result",+ },+ ],+ role: "tool",+ },+ { content: assistantContent, role: "assistant" },+ ],+ text: "",+ toolCalls: [gateToolCall, waitToolCall, invalidCancelToolCall],+ toolResults: [],+ });+ const workflowId = "workflow//./agent/tools/research//task";+ const tools: ToolLoopHarnessConfig["tools"] = new Map([+ ...createDelegationToolMap(),+ [+ "research",+ {+ behavior: {+ availability: [],+ handling: {+ kind: "dispatch",+ target: { entryPoint: "task", kind: "workflow-tool-call", workflowId },+ },+ },+ description: "Research in the background.",+ inputSchema: jsonSchema({ type: "object" }),+ name: "research",+ workflowId,+ },+ ],+ ]);++ const { emit } = createEventCollector();+ const runStep = createToolLoopHarness(createTestConfig(emit, { tools }));+ const parked = await runStep(createPendingBashApprovalSession(), {+ inputResponses: [{ optionId: "approve", requestId: "approval-1" }],+ });++ expect(parked.next).toBeNull();+ expect(hasPendingInputBatch(parked.session.state)).toBe(true);+ const batch = getPendingCoordinationBatch(parked.session.state);+ expect(batch?.tasks).toEqual([]);+ expect(pendingCoordinationCallIds(batch!)).toEqual(["wait-1"]);+ });+it("forwards the agent reasoning effort to the model call", async () => {setupMockAgent({finishReason: "stop",@@ -4594,6 +4425,41 @@ describe("createToolLoopHarness", () => {);});+ it("parks a delegated turn held by its working tasks with turn.waiting", async () => {+ setupMockAgent({+ finishReason: "stop",+ response: { messages: [{ content: "Checking now.", role: "assistant" }] },+ text: "Checking now.",+ toolCalls: [],+ toolResults: [],+ });+ const { emit, events } = createEventCollector();+ const runStep = createToolLoopHarness(createTestConfig(emit));+ const ctx = new ContextContainer();+ setDelegatedParent(ctx);+ const { table } = createTask(+ { tasks: [] },+ { callId: "call-task", kind: "tool", name: "research", resumable: false, turnId: "turn_0" },+ );++ const result = await contextStorage.run(ctx, () =>+ runStep(writeTaskTable(createTestSession(), table), { message: "Delegated turn" }),+ );++ expect(result.held).toBeDefined();+ expect(events).toContainEqual(+ expect.objectContaining({+ data: expect.objectContaining({ finishReason: "tool-calls", message: "Checking now." }),+ type: "message.completed",+ }),+ );+ expect(events.at(-1)).toEqual({+ data: { sequence: 0, turnId: "turn_0" },+ type: "turn.waiting",+ });+ expect(events.map((event) => event.type)).not.toContain("session.waiting");+ });+it("emits the full terminal failure cascade on an explicit Gateway invalid-request error", async () => {const logs = captureLogRecords();setupMockAgentError(@@ -6433,65 +6299,6 @@ describe("createToolLoopHarness", () => {expect(toolResult).toEqual(resumedToolResultMessage.content[0]);});- it("defers an agents announcement until an approved sibling tool has produced its result", async () => {- const toolResultMessage = {- content: [- {- output: { type: "text", value: "ok" },- toolCallId: "call-1",- toolName: "bash",- type: "tool-result",- },- ],- role: "tool",- };- setupMockAgent({- content: [],- finishReason: "stop",- response: { messages: [{ content: "Done.", role: "assistant" }] },- responseMessages: [toolResultMessage, { content: "Done.", role: "assistant" }],- text: "Done.",- toolCalls: [],- toolResults: [],- });-- const pending = createPendingBashApprovalSession();- const session = {- ...pending,- state: {- ...pending.state,- [AGENT_HANDLES_STATE_KEY]: {- handles: [- {- address: {- continuationToken: "private-token",- kind: "agent/local" as const,- sessionId: "child-session-123456789012",- },- identity: {- id: "ag_research:123456789012",- name: "research",- nodeId: "subagents/research",- },- lastStatus: "waiting",- phase: "parked" as const,- },- ],- },- },- };- const harness = createToolLoopHarness(createTestConfig(undefined, { tools: new Map() }));-- await harness(session, {- inputResponses: [{ optionId: "approve", requestId: "approval-1" }],- });-- const agent = vi.mocked(ToolLoopAgent).mock.results.at(-1)?.value;- if (agent === undefined) throw new Error("ToolLoopAgent mock did not return an instance.");- const messages = vi.mocked(agent.generate).mock.calls[0]?.[0].messages as ModelMessage[];- expect(JSON.stringify(messages)).not.toContain("[Agents]");- });-it("does not persist provider-executed deferred tool-results as generic tool messages", async () => {const toolCallId = "srvtoolu_01HhTt9QAEancMSj7jE8CXN7";const webSearchOutput = [diff --git a/packages/eve/src/harness/tool-loop.ts b/packages/eve/src/harness/tool-loop.tsindex 8bae640bc..9f5b0151d 100644--- a/packages/eve/src/harness/tool-loop.ts+++ b/packages/eve/src/harness/tool-loop.ts@@ -31,6 +31,7 @@ import {AuthKey,HistoryStateKey,ParentSessionKey,+ ScheduleIdKey,SessionCallbackKey,StaticModelReferenceKey,} from "#context/keys.js";@@ -64,12 +65,11 @@ import {createInputRequestedEvent,createResultCompletedEvent,createSessionWaitingEvent,+ createTurnWaitingEvent,type UnstampedMessageStreamEvent,} from "#protocol/message.js";import type { RuntimeTraceContext } from "#protocol/message.js";import type { HarnessToolDefinition } from "#harness/execute-tool.js";-import { resolveAgentsAnnouncement } from "#subagents/handles/prompt.js";-import { getAgentHandleStore } from "#subagents/handles/store.js";import type { InputRequest } from "#shared/input.js";import {hydrateSandboxAttachments,@@ -166,6 +166,15 @@ import {createMessageCompletedEvent,createStepStartedEvent,} from "#protocol/message.js";+import {+ appendTaskContext,+ commitCallEntry,+ isTaskTool,+ taskSystemMessages,+ withTaskTools,+ workingTaskIds,+} from "#execution/tasks/model-step.js";+import { renderFinalOutputWhileWorkingError } from "#execution/tasks/render.js";import {classifyModelCallError,ContentFilteredModelResponseError,@@ -192,8 +201,10 @@ import {createCoordinationRequestFromToolCall,getPendingCoordinationBatch,resolvePendingCoordination,+ resolveToolCallInputObject,setPendingCoordinationBatch,} from "#harness/coordination.js";+import type { RuntimeWorkflowTaskRequest } from "#shared/action-types.js";import {getInvalidToolCallInputError,isInvalidToolCall,@@ -495,6 +506,9 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {const parent = store?.get(ParentSessionKey);const callback = store?.get(SessionCallbackKey);const hasDelegatedCaller = parent !== undefined || callback !== undefined;+ // A child's caller and a schedule hear only the turn's real end, so a held+ // turn's text isn't posted as their reply. A person reads a root session.+ const hidesHeldText = hasDelegatedCaller || store?.get(ScheduleIdKey) !== undefined;let activeAttemptScope: InstrumentationAttempt | undefined;const instrumentedEmit =stepInstrumentation?.createHandleEvent({@@ -1101,21 +1115,15 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {}session = continuation.session;- // Announce the parked-agents listing as framework-injected user-role- // content, before any new user input so a message present on this step- // stays the turn's focus. On a no-input settle resume it trails the tool- // results, keeping the request user-final for providers that reject- // assistant-final histories. See resolveAgentsAnnouncement for the role- // rationale (assistant-final rejection, prompt-cache preservation).- const agentStore = getAgentHandleStore(session.state);if (!hasUnansweredToolCall(messages)) {- const announcement = resolveAgentsAnnouncement({- messages: projectHistory(messages, session.state),- store: agentStore,+ const taskContext = await appendTaskContext({+ messages,+ projectHistory,+ session,+ tools: config.tools,});- if (announcement !== undefined) {- messages.push(createFrameworkUserMessage("context.state", announcement));- }+ session = taskContext.session;+ messages.push(...taskContext.messages);}// Keep ephemeral client context at the same position across durable steps.@@ -1245,6 +1253,8 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {* `console.error(error)` handler inside `streamText`. Errors are* handled by the harness catch block and emitted as stream events.*/+ // The tools advertised to the latest model call; they decide which tool calls defer.+ let modelCallCoordinationTools = config.tools;const createRequestMessages = () => {// Persist framework announcements before the new input, or after earlier// tool results on a continuation, so later requests retain the full prefix.@@ -1256,6 +1266,7 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {if (ctx !== undefined) {currentMessages.addSystem(buildDynamicInstructionMessages(ctx));}+ currentMessages.addSystem(taskSystemMessages(modelCallCoordinationTools));currentMessages.addAnnouncements({availableSkills: ctx?.get(PendingSkillAnnouncementKey),});@@ -1361,7 +1372,6 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {suppressStepStartedEmission?: boolean;trailingUserNote?: string;};- let modelCallCoordinationTools = config.tools;let requestEnvelopeTokens = 0;let compactionFailure: { readonly error: unknown } | undefined;const throwIfCompactionFailed = () => {@@ -1370,10 +1380,12 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {const prepareModelTools = async (opts: ModelCallOptions) => {const harnessTools = buildHarnessToolsWithDynamicSubagents(config.tools, ctx);- const advertisedHarnessTools = getAdvertisedTools({- session,- tools: harnessTools,- });+ const advertisedHarnessTools = withTaskTools(+ getAdvertisedTools({+ session,+ tools: harnessTools,+ }),+ );modelCallCoordinationTools = advertisedHarnessTools;const flatTools = await buildToolSetWithProviderTools({@@ -1612,6 +1624,7 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {interruptStreamOnFailure(streamResult.fullStream, generation.signal),{excludedActionToolNames,+ hidesHeldText: hidesHeldText && workingTaskIds(session).length > 0,tools: presentationTools,},);@@ -2564,7 +2577,7 @@ async function handleStepResult(input: {session: baseSession,tools: input.coordinationTools,});- const tasks = ((result.toolCalls ?? []) as TypedToolCall<ToolSet>[])+ const deferredToolCalls = ((result.toolCalls ?? []) as TypedToolCall<ToolSet>[]).filter((toolCall) => !invalidInputToolCallIds.has(toolCall.toolCallId)).filter((toolCall) => isDeferredHarnessTool(input.coordinationTools.get(toolCall.toolName))).filter((toolCall) => {@@ -2577,15 +2590,16 @@ async function handleStepResult(input: {toolName: toolCall.toolName,});return false;- })- .map((toolCall) =>- createCoordinationRequestFromToolCall({- toolCall,- tools: advertisedCoordinationTools,- }),- );+ });+ const deferred = collectDeferredCalls({+ session: baseSession,+ toolCalls: deferredToolCalls,+ tools: advertisedCoordinationTools,+ turnId: emissionState.turnId,+ });+ const tasks = deferred.workflowRequests;- if (tasks.length > 0) {+ if (deferredToolCalls.length > 0) {// Stamp the live emission state onto the parked session so the// resume turn is classified as a continuation (turnId set), not a// fresh turn. Every other park path does this; without it the@@ -2604,7 +2618,7 @@ async function handleStepResult(input: {turnId: emissionState.turnId,},responseMessages,- session: { ...baseSession, history: validateHarnessModelMessages(promptMessages) },+ session: { ...deferred.session, history: validateHarnessModelMessages(promptMessages) },}),advanceStep(emissionState),),@@ -2619,7 +2633,7 @@ async function handleStepResult(input: {turnId: emissionState.turnId,},responseMessages: pendingResponseMessages,- session: { ...baseSession, history: parkedInputHistory },+ session: { ...deferred.session, history: parkedInputHistory },});// The coordination batch already owns the shared assistant response.@@ -2781,18 +2795,42 @@ async function handleStepResult(input: {// dangling tool_use the next provider call rejects, and drop the result.const calledFinalOutput =nextSession.outputSchema !== undefined && extractFinalOutput(result) !== undefined;+ const workingTasks = workingTaskIds(nextSession);+ const finalOutputRejected = calledFinalOutput && workingTasks.length > 0;+ let responseTail: readonly ModelMessage[] = continuationMessages;+ if (finalOutputRejected) {+ responseTail = rejectFinalOutput(continuationMessages, result, workingTasks);+ nextSession = {+ ...nextSession,+ history: validateHarnessModelMessages([...promptMessages, ...responseTail]),+ };+ }const continueLoop =- !calledFinalOutput &&- (continuationMessages.at(-1)?.role === "tool" ||+ (!calledFinalOutput || finalOutputRejected) &&+ (responseTail.at(-1)?.role === "tool" ||normalizedProviderHistory.outcomeEndsResponse ||hasRunnableDeferredStepInput(nextSession));- if (continueLoop) {+ const holdsTurn = !continueLoop && workingTasks.length > 0;+ if (continueLoop || holdsTurn) {if (emit) {emissionState = advanceStep(emissionState);nextSession = setHarnessEmissionState(nextSession, emissionState);}-+ // The turn rule: no turn ends while its tasks work. The session waits for+ // one to settle, then calls the model again in the same turn. The turn+ // stays open, so it parks with `turn.waiting` rather than completing.+ if (holdsTurn) {+ if (emit) {+ await emit(+ createTurnWaitingEvent({+ sequence: emissionState.sequence,+ turnId: emissionState.turnId,+ }),+ );+ }+ return { held: { taskIds: workingTasks }, next: null, session: nextSession };+ }return { next: runStep, session: nextSession };}@@ -2808,7 +2846,68 @@ async function handleStepResult(input: {}function isDeferredHarnessTool(tool: HarnessToolDefinition | undefined): boolean {- return tool?.workflowId !== undefined;+ return tool?.workflowId !== undefined || isTaskTool(tool);+}++/**+ * Turns a step's deferred calls into workflow runs, committing a task record+ * for each call that starts a task. Task tool calls stay in the response+ * alone: the session reads them from there.+ */+function collectDeferredCalls(input: {+ readonly session: HarnessSession;+ readonly toolCalls: readonly TypedToolCall<ToolSet>[];+ readonly tools: HarnessToolMap;+ readonly turnId: string;+}): {+ readonly session: HarnessSession;+ readonly workflowRequests: readonly RuntimeWorkflowTaskRequest[];+} {+ let { session } = input;+ const workflowRequests: RuntimeWorkflowTaskRequest[] = [];+ for (const toolCall of input.toolCalls) {+ const definition = input.tools.get(toolCall.toolName);+ if (isTaskTool(definition)) continue;+ const committed = commitCallEntry(session, {+ callId: toolCall.toolCallId,+ definition,+ input: resolveToolCallInputObject(toolCall.input, {+ callId: toolCall.toolCallId,+ toolName: toolCall.toolName,+ }),+ toolName: toolCall.toolName,+ turnId: input.turnId,+ });+ session = committed.session;+ workflowRequests.push(+ createCoordinationRequestFromToolCall({+ entry: committed.entry,+ input: committed.input,+ toolCall,+ tools: input.tools,+ }),+ );+ }+ return { session, workflowRequests };+}++/** Answers a `final_output` call made while tasks work with an error naming them. */+function rejectFinalOutput(+ responseMessages: readonly ModelMessage[],+ result: HarnessStepResult,+ workingTasks: readonly string[],+): ModelMessage[] {+ const call = (result.toolCalls ?? []).find(+ (toolCall) => toolCall.toolName === FINAL_OUTPUT_TOOL_NAME,+ );+ if (call === undefined) return [...responseMessages];+ const rejection: ToolResultPart = {+ output: { type: "error-text", value: renderFinalOutputWhileWorkingError(workingTasks) },+ toolCallId: call.toolCallId,+ toolName: FINAL_OUTPUT_TOOL_NAME,+ type: "tool-result",+ };+ return [...responseMessages, { content: [rejection], role: "tool" }];}const OUTPUT_SCHEMA_NOT_FULFILLED = {diff --git a/packages/eve/src/harness/types.ts b/packages/eve/src/harness/types.tsindex bdb9f2230..ba77120ee 100644--- a/packages/eve/src/harness/types.ts+++ b/packages/eve/src/harness/types.ts@@ -217,6 +217,11 @@ export interface StepResult {* across the park boundary so a delegated parent can be notified.*/readonly settledTurn?: SettledTurn;+ /**+ * Present when the model ended the turn while tasks are working. The turn+ * stays open until one settles.+ */+ readonly held?: { readonly taskIds: readonly string[] };}/**diff --git a/packages/eve/src/internal/authored-definition/schema-backed.ts b/packages/eve/src/internal/authored-definition/schema-backed.tsindex 6063809af..26746240e 100644--- a/packages/eve/src/internal/authored-definition/schema-backed.ts+++ b/packages/eve/src/internal/authored-definition/schema-backed.ts@@ -1,5 +1,12 @@-import { isWorkflowToolDefinition } from "#tools/workflow-definition.js";+import {+ isWorkflowToolDefinition,+ readWorkflowToolEntryPoints,+ type WorkflowToolEntryPoint,+} from "#tools/workflow-definition.js";import { readWorkflowFunctionId } from "#internal/workflow/reference.js";+import { TASK_ID_INPUT } from "#execution/tasks/task-id-input.js";+import { isObject } from "#shared/guards.js";+import type { JsonObject } from "#shared/json.js";import { isDisabledToolSentinel } from "#tools/definition.js";import { isWebSearchToolDefinition } from "#tools/provided/web-search.js";import {@@ -41,9 +48,16 @@ type NormalizedAuthoredTool = Readonly<readonly hasApproval: boolean;readonly hasExecute: boolean;readonly hasModelOutputProjection: boolean;+ readonly workflow?: CompiledWorkflowEntry;readonly workflowProgram?: WorkflowProgramOptions;}>;++/** The compiled entry point of a `defineWorkflowTool()` definition. */+interface CompiledWorkflowEntry {+ readonly entryPoint: WorkflowToolEntryPoint;+ readonly workflowId: string;+}type MutableNormalizedAuthoredTool = {-readonly [K in keyof NormalizedAuthoredTool]: NormalizedAuthoredTool[K];};@@ -95,14 +109,10 @@ export function normalizeToolDefinition(value: unknown, message: string): Normal}const record = expectObjectRecord(value, message);- const workflowId = readWorkflowFunctionId(record.execute);- if (isWorkflowToolDefinition(value)) {- if (workflowId === undefined) {- throw new Error(- `${message} defineWorkflowTool() requires a compiled workflow executor. Start execute with "use workflow" and export defineWorkflowTool() as the default export of a static tool module.`,- );- }- } else if (workflowId !== undefined) {+ const workflow = isWorkflowToolDefinition(value)+ ? readCompiledWorkflowEntry(record, message)+ : undefined;+ if (workflow === undefined && readWorkflowFunctionId(record.execute) !== undefined) {throw new Error(`${message} Workflow executors require defineWorkflowTool() from "eve/tools". Replace defineTool() or the bare tool object with defineWorkflowTool().`,);@@ -115,12 +125,12 @@ export function normalizeToolDefinition(value: unknown, message: string): Normal"auth","description","execute",- "execution","inputSchema","approval","approvalKey","outputSchema","toModelOutput",+ ...(workflow === undefined ? [] : [workflow.entryPoint]),],message,);@@ -128,10 +138,12 @@ export function normalizeToolDefinition(value: unknown, message: string): Normalrecord.inputSchema === undefined? null: serializeInputSchema(record.inputSchema as ToolSchemaSource);+ if (workflow?.entryPoint === "serve") assertNoOwnTaskIdInput(inputSchema, message);const outputSchema = serializeOutputSchema(record.outputSchema as ToolSchemaSource | undefined);const behavior = readToolBehavior(value);const workflowProgram = readWorkflowProgramOptions(value);- const hasExecute = record.execute !== undefined;+ // A workflow tool's entry point is its executor; the runtime loads the module for its hooks.+ const hasExecute = workflow !== undefined || record.execute !== undefined;if (!hasExecute && behavior?.handling?.kind !== "dispatch") {expectFunction(record.execute, message);}@@ -152,7 +164,9 @@ export function normalizeToolDefinition(value: unknown, message: string): Normalif (workflowProgram !== undefined) {definition.workflowProgram = workflowProgram;}- if (hasExecute) {+ if (workflow !== undefined) {+ definition.workflow = workflow;+ } else if (hasExecute) {definition.execute = expectFunction(record.execute, message) as ToolExecuteFn;}if (outputSchema !== undefined) {@@ -195,3 +209,28 @@ export function normalizeToolDefinition(value: unknown, message: string): Normaldefinition,};}++/** Reads the one entry point `defineWorkflowTool()` accepted, which the build compiled to a workflow. */+function readCompiledWorkflowEntry(+ record: Record<string, unknown>,+ message: string,+): CompiledWorkflowEntry {+ const [entryPoint] = readWorkflowToolEntryPoints(record);+ const workflowId =+ entryPoint === undefined ? undefined : readWorkflowFunctionId(record[entryPoint]);+ if (entryPoint === undefined || workflowId === undefined) {+ throw new Error(+ `${message} defineWorkflowTool() requires a compiled workflow executor. Start execute, task, or serve with "use workflow" and export defineWorkflowTool() as the default export of a static tool module.`,+ );+ }+ return { entryPoint, workflowId };+}++/** eve adds `taskId` to a `serve` tool's model input, so the tool's own input can't use it. */+function assertNoOwnTaskIdInput(inputSchema: JsonObject | null, message: string): void {+ const properties = inputSchema?.properties;+ if (!isObject(properties) || !(TASK_ID_INPUT in properties)) return;+ throw new Error(+ `${message} inputSchema declares "${TASK_ID_INPUT}", which eve adds to a serve tool's model input to send a call to a running task. Rename the field.`,+ );+}diff --git a/packages/eve/src/internal/authored-module-loader.integration.test.ts b/packages/eve/src/internal/authored-module-loader.integration.test.tsindex 8c9ab1fce..91aded93f 100644--- a/packages/eve/src/internal/authored-module-loader.integration.test.ts+++ b/packages/eve/src/internal/authored-module-loader.integration.test.ts@@ -123,6 +123,7 @@ export default ${definer}({ description: "Probe", inputSchema: {}, execute: run});const compiled = await compileAgentManifest(discovered.manifest);expect(compiled.tools.find((tool) => tool.name === "probe")?.behavior?.handling).toEqual({+ entryPoint: "execute",kind: "workflow-tool",workflowId: "workflow//./agent/lib/run//run",});diff --git a/packages/eve/src/internal/invocation/workflow-execution.ts b/packages/eve/src/internal/invocation/workflow-execution.tsindex e29b93aef..15bb24c77 100644--- a/packages/eve/src/internal/invocation/workflow-execution.ts+++ b/packages/eve/src/internal/invocation/workflow-execution.ts@@ -368,6 +368,10 @@ function projectInvocation(result = safeJson(event.data.message);}break;+ case "turn.waiting":+ // Text completed before the turn parked was interim; the reply comes after it resumes.+ result = undefined;+ break;case "turn.completed":settled = "completed";break;diff --git a/packages/eve/src/internal/nitro/routes/runtime-stack.ts b/packages/eve/src/internal/nitro/routes/runtime-stack.tsindex 527fd0bf8..5d99b577c 100644--- a/packages/eve/src/internal/nitro/routes/runtime-stack.ts+++ b/packages/eve/src/internal/nitro/routes/runtime-stack.ts@@ -1,6 +1,6 @@import type { Runtime } from "#channel/types.js";import { createWorkflowRuntime } from "#execution/workflow-runtime.js";-import { resolveRemoteAgentStreamHeaders } from "#subagents/remote-dispatch.js";+import { resolveRemoteAgentStreamHeaders } from "#execution/agent-sessions/remote.js";import type { RemoteAgentStreamHeadersResolver } from "#internal/nitro/routes/channel-route-context.js";import { getCompiledRuntimeAgentBundle } from "#runtime/sessions/compiled-agent-cache.js";import type { ResolvedChannelDefinition } from "#runtime/types.js";diff --git a/packages/eve/src/internal/testing/workflow-tool-run-harness.ts b/packages/eve/src/internal/testing/workflow-tool-run-harness.tsindex d16bb0b47..c9b31fd42 100644--- a/packages/eve/src/internal/testing/workflow-tool-run-harness.ts+++ b/packages/eve/src/internal/testing/workflow-tool-run-harness.ts@@ -3,7 +3,10 @@ import { createBundledRuntimeCompiledArtifactsSource } from "#runtime/compiled-aimport type { ResolvedToolDefinition } from "#runtime/types.js";import { serializeInputSchema, toInputSchema } from "#tools/schema.js";import { getRun } from "#internal/workflow/runtime.js";-import { type WorkflowToolDefinition, defineWorkflowTool } from "#tools/workflow-definition.js";+import {+ type WorkflowExecuteToolDefinition,+ defineWorkflowTool,+} from "#tools/workflow-definition.js";const DEPLOY_INPUT_SCHEMA = toInputSchema({additionalProperties: false,@@ -55,7 +58,7 @@ export async function createWorkflowToolRuntime(input: {loadNamespace: async () => ({default: defineWorkflowTool({description: `Deploys a service (${input.toolName}).`,- execute: input.execute as WorkflowToolDefinition["execute"],+ execute: input.execute as WorkflowExecuteToolDefinition["execute"],inputSchema: serializeInputSchema(input.inputSchema ?? DEPLOY_INPUT_SCHEMA) ?? {},}),}),diff --git a/packages/eve/src/internal/workflow-bundle/authored-workflow-directives.test.ts b/packages/eve/src/internal/workflow-bundle/authored-workflow-directives.test.tsindex 73c61a98d..6532f00c5 100644--- a/packages/eve/src/internal/workflow-bundle/authored-workflow-directives.test.ts+++ b/packages/eve/src/internal/workflow-bundle/authored-workflow-directives.test.ts@@ -56,6 +56,21 @@ describe("prepareAuthoredWorkflowDirectives", () => {expect(prepared.source).not.toContain("async execute(");});+ it("hoists a task method, the other workflow entry point", async () => {+ const source = toolModule(+ [" async *task({ service }) {", ' "use workflow";', " yield service;", " },"].join(+ "\n",+ ),+ );++ const prepared = await prepareAuthoredWorkflowDirectives({ filePath: FILE, source });++ expect(prepared.source).toContain(" task,\n toModelOutput: (output) => output,");+ expect(prepared.source).toContain(+ 'async function* task({ service }) {\n "use workflow";\n yield service;\n }',+ );+ });+it("hoists an arrow function execute property", async () => {const source = toolModule([diff --git a/packages/eve/src/internal/workflow-bundle/authored-workflow-directives.ts b/packages/eve/src/internal/workflow-bundle/authored-workflow-directives.tsindex a5f2bc73b..c14d8a1da 100644--- a/packages/eve/src/internal/workflow-bundle/authored-workflow-directives.ts+++ b/packages/eve/src/internal/workflow-bundle/authored-workflow-directives.ts@@ -3,8 +3,11 @@ import {mayContainWorkflowDirective,readWorkflowDirective,} from "#internal/workflow-bundle/workflow-directive-ast.js";+import { WORKFLOW_TOOL_ENTRY_POINTS } from "#tools/workflow-entry-point.js";-const HOISTED_EXECUTE_NAME = "execute";+const ENTRY_POINT_METHODS = new Intl.ListFormat("en", { type: "disjunction" }).format(+ WORKFLOW_TOOL_ENTRY_POINTS.map((name) => `"${name}"`),+);type AstNode = {async?: boolean;@@ -41,6 +44,13 @@ interface DirectiveFunctionNode {readonly fn: AstNode;}+/** A default-exported definition's entry-point method: its property and function. */+interface EntryPointMethod {+ readonly fn: AstNode;+ readonly name: string;+ readonly property: AstNode;+}+export interface AuthoredWorkflowDirectiveSource {readonly hasDirectives: boolean;readonly hasWorkflowDirective: boolean;@@ -49,9 +59,10 @@ export interface AuthoredWorkflowDirectiveSource {/*** The directive transform understands one shape: a top-level `async function`- * whose first statement is the directive. A marked `defineWorkflowTool` executor is hoisted- * into that shape here; every other placement is a build error, because an- * ignored directive would run side effects inline in a replayed body.+ * whose first statement is the directive. A marked `defineWorkflowTool` entry+ * point (`execute` or `task`) is hoisted into that shape here; every other+ * placement is a build error, because an ignored directive would run side+ * effects inline in a replayed body.*/export async function prepareAuthoredWorkflowDirectives(input: {readonly filePath: string;@@ -75,7 +86,7 @@ export async function prepareAuthoredWorkflowDirectives(input: {throw new Error(`${JSON.stringify(directive)} in "${input.filePath}" is a module-level directive. ` +`Put it as the first statement of the function it marks: a top-level "async function" declaration` +- ` or the "execute" method of a default-exported defineWorkflowTool().`,+ ` or the ${ENTRY_POINT_METHODS} method of a default-exported defineWorkflowTool().`,);}}@@ -92,15 +103,9 @@ export async function prepareAuthoredWorkflowDirectives(input: {if (declaration !== undefined) allowed.add(declaration);}- const executeProperty = findDefaultExportExecuteProperty(body);- const executeFunction =- executeProperty !== undefined &&- isAstNode(executeProperty.value) &&- isFunctionLike(executeProperty.value)- ? executeProperty.value- : undefined;- if (executeFunction !== undefined) {- allowed.add(executeFunction);+ const entryPoints = findDefaultExportEntryPoints(body);+ for (const entryPoint of entryPoints) {+ allowed.add(entryPoint.fn);}const found = collectDirectiveFunctions(program as AstNode);@@ -113,7 +118,7 @@ export async function prepareAuthoredWorkflowDirectives(input: {throw new Error(`${JSON.stringify(entry.directive)} in "${input.filePath}" marks ${describeFunction(entry.fn)}. ` +`Workflow directives must mark a top-level "async function" declaration` +- ` or the "execute" method of a default-exported defineWorkflowTool().`,+ ` or the ${ENTRY_POINT_METHODS} method of a default-exported defineWorkflowTool().`,);}if (entry.fn.async !== true) {@@ -122,16 +127,20 @@ export async function prepareAuthoredWorkflowDirectives(input: {`Declare it with "async function".`,);}- if (entry.fn === executeFunction && entry.directive !== "use workflow") {+ const entryPoint = entryPoints.find((candidate) => candidate.fn === entry.fn);+ if (entryPoint !== undefined && entry.directive !== "use workflow") {throw new Error(- `"use step" in "${input.filePath}" marks the default export's "execute" method. ` +- `A tool's "execute" can be a workflow ("use workflow"); steps are the helper functions it calls.`,+ `"use step" in "${input.filePath}" marks the default export's "${entryPoint.name}" method. ` ++ `A tool's "${entryPoint.name}" can be a workflow ("use workflow"); steps are the helper functions it calls.`,);}}- const hoist = found.find((entry) => entry.fn === executeFunction);- if (hoist === undefined || executeProperty === undefined) {+ // defineWorkflowTool() accepts one entry point, so only one is hoisted.+ const hoisted = entryPoints.find((entryPoint) =>+ found.some((entry) => entry.fn === entryPoint.fn),+ );+ if (hoisted === undefined) {return {hasDirectives: true,hasWorkflowDirective,@@ -139,37 +148,43 @@ export async function prepareAuthoredWorkflowDirectives(input: {};}- if (declaresTopLevelBinding(body, HOISTED_EXECUTE_NAME)) {+ if (declaresTopLevelBinding(body, hoisted.name)) {throw new Error(- `"use workflow" in "${input.filePath}" marks the "execute" method, but the module also declares a top-level "${HOISTED_EXECUTE_NAME}" binding. ` +- `eve hoists that method to a top-level "async function ${HOISTED_EXECUTE_NAME}"; rename the existing binding.`,+ `"use workflow" in "${input.filePath}" marks the "${hoisted.name}" method, but the module also declares a top-level "${hoisted.name}" binding. ` ++ `eve hoists that method to a top-level "async function ${hoisted.name}"; rename the existing binding.`,);}return {hasDirectives: true,hasWorkflowDirective,- source: hoistExecuteMethod(input.source, executeProperty, hoist.fn),+ source: hoistEntryPointMethod(input.source, hoisted),};}-function findDefaultExportExecuteProperty(body: readonly AstNode[]): AstNode | undefined {+function findDefaultExportEntryPoints(body: readonly AstNode[]): EntryPointMethod[] {const exported = body.find((statement) => statement.type === "ExportDefaultDeclaration");const declaration = exported?.declaration;const definition =declaration?.type === "CallExpression" ? declaration.arguments?.[0] : declaration;- if (definition?.type !== "ObjectExpression") return undefined;+ if (definition?.type !== "ObjectExpression") return [];- return definition.properties?.find(- (property) =>- property.type === "Property" &&- property.kind === "init" &&- property.computed !== true &&- readPropertyName(property.key) === HOISTED_EXECUTE_NAME,- );+ const methods: EntryPointMethod[] = [];+ for (const property of definition.properties ?? []) {+ if (property.type !== "Property" || property.kind !== "init" || property.computed === true) {+ continue;+ }+ const name = readPropertyName(property.key);+ const fn = property.value;+ if (name === undefined || !WORKFLOW_TOOL_ENTRY_POINTS.some((entry) => entry === name)) continue;+ if (!isAstNode(fn) || !isFunctionLike(fn)) continue;+ methods.push({ fn, name, property });+ }+ return methods;}-function hoistExecuteMethod(source: string, property: AstNode, fn: AstNode): string {+function hoistEntryPointMethod(source: string, method: EntryPointMethod): string {+ const { fn, name, property } = method;if (property.start === undefined ||property.end === undefined ||@@ -177,7 +192,7 @@ function hoistExecuteMethod(source: string, property: AstNode, fn: AstNode): strfn.body.start === undefined ||fn.body.end === undefined) {- throw new Error("Cannot hoist an execute method without source ranges.");+ throw new Error(`Cannot hoist a "${name}" method without source ranges.`);}const params = fn.params ?? [];@@ -191,9 +206,9 @@ function hoistExecuteMethod(source: string, property: AstNode, fn: AstNode): strconst returnTypeText = sliceNode(source, fn.returnType);const bodyText = source.slice(fn.body.start, fn.body.end);const star = fn.generator === true ? "*" : "";- const declaration = `async function${star} ${HOISTED_EXECUTE_NAME}${typeParametersText}(${paramsText})${returnTypeText} ${bodyText}`;+ const declaration = `async function${star} ${name}${typeParametersText}(${paramsText})${returnTypeText} ${bodyText}`;- return `${source.slice(0, property.start)}${HOISTED_EXECUTE_NAME}${source.slice(property.end)}\n${declaration}\n`;+ return `${source.slice(0, property.start)}${name}${source.slice(property.end)}\n${declaration}\n`;}function sliceNode(source: string, node: AstNode | null | undefined): string {diff --git a/packages/eve/src/internal/workflow-bundle/workflow-builders.test.ts b/packages/eve/src/internal/workflow-bundle/workflow-builders.test.tsindex aba9d2822..3c5fa1dc2 100644--- a/packages/eve/src/internal/workflow-bundle/workflow-builders.test.ts+++ b/packages/eve/src/internal/workflow-bundle/workflow-builders.test.ts@@ -96,7 +96,7 @@ describe("applyWorkflowTransform", () => {const transformed = await applyWorkflowTransform(filename,[- "export async function subagentToolExecuteWorkflow(): Promise<void> {",+ "export async function agentToolServeWorkflow(): Promise<void> {",' "use workflow";',"}","",@@ -106,13 +106,11 @@ describe("applyWorkflowTransform", () => {resolvePackageRoot(),);- expect(transformed.workflowManifest.workflows?.[filename]?.subagentToolExecuteWorkflow).toEqual(- {- workflowId: "workflow//eve//subagentToolExecuteWorkflow",- },- );+ expect(transformed.workflowManifest.workflows?.[filename]?.agentToolServeWorkflow).toEqual({+ workflowId: "workflow//eve//agentToolServeWorkflow",+ });expect(transformed.code).toContain(- 'globalThis.__private_workflows.set("workflow//eve//subagentToolExecuteWorkflow", subagentToolExecuteWorkflow);',+ 'globalThis.__private_workflows.set("workflow//eve//agentToolServeWorkflow", agentToolServeWorkflow);',);});diff --git a/packages/eve/src/internal/workflow-bundle/workflow-builders.ts b/packages/eve/src/internal/workflow-bundle/workflow-builders.tsindex f81367c03..e7174020b 100644--- a/packages/eve/src/internal/workflow-bundle/workflow-builders.ts+++ b/packages/eve/src/internal/workflow-bundle/workflow-builders.ts@@ -3,7 +3,7 @@ import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";import { STABLE_WORKFLOW_NAMES } from "#execution/stable-workflow-names.js";import { EVE_PACKAGE_NAME } from "#internal/package-name.js";-import { SUBAGENT_TOOL_EXECUTE_WORKFLOW_NAME } from "#runtime/subagents/workflow-reference.js";+import { AGENT_TOOL_SERVE_WORKFLOW_NAME } from "#runtime/subagents/workflow-reference.js";import { prepareAuthoredWorkflowDirectives } from "#internal/workflow-bundle/authored-workflow-directives.js";import {findWorkflowDirectiveFunctions,@@ -55,7 +55,7 @@ export async function applyWorkflowTransform(projectRoot?: string,stableWorkflowNames: ReadonlySet<string> = new Set([...STABLE_WORKFLOW_NAMES,- SUBAGENT_TOOL_EXECUTE_WORKFLOW_NAME,+ AGENT_TOOL_SERVE_WORKFLOW_NAME,]),): Promise<{code: string;diff --git a/packages/eve/src/protocol/agent-handle-error.ts b/packages/eve/src/protocol/agent-handle-error.tsdeleted file mode 100644index c79f2f4a1..000000000--- a/packages/eve/src/protocol/agent-handle-error.ts+++ /dev/null@@ -1,27 +0,0 @@-/** JSON error returned when an agent-handle operation cannot be completed. */-export interface AgentHandleErrorJson<TCode extends string = string> {- readonly code: TCode;- readonly error: string;- readonly ok: false;-}--function defineAgentHandleError<const TCode extends string>(- code: TCode,- message: string,-): {- readonly code: TCode;- readonly toJson: () => AgentHandleErrorJson<TCode>;-} {- return {- code,- toJson: () => ({ code, error: message, ok: false }),- };-}--/** Stable agent-handle errors shared by HTTP producers and consumers. */-export const AgentHandleError = {- SessionNotResumable: defineAgentHandleError(- "SESSION_NOT_RESUMABLE",- "Session is not active and cannot be resumed.",- ),-} as const;diff --git a/packages/eve/src/protocol/message.test.ts b/packages/eve/src/protocol/message.test.tsindex cc25d599f..00d01ae79 100644--- a/packages/eve/src/protocol/message.test.ts+++ b/packages/eve/src/protocol/message.test.ts@@ -17,7 +17,7 @@ import {createResultCompletedEvent,createSessionWaitingEvent,createStepStartedEvent,- createSubagentCalledEvent,+ createAgentStartedEvent,createTurnCancelledEvent,encodeMessageStreamEvent,stampMessageStreamEvent,@@ -283,25 +283,20 @@ describe("message stream protocol", () => {it("authors local and remote child stream paths", () => {const input = {callId: "call/1",- childSessionId: "child/1",name: "research",- sequence: 1,- sessionId: "parent/1",- toolName: "research",- turnId: "turn_1",- workflowId: "workflow_1",+ parentSessionId: "parent/1",+ sessionId: "child/1",+ turnId: "turn/1",};- expect(createSubagentCalledEvent(input).data.childStreamPath).toBe(- "/eve/v1/session/child%2F1/stream",- );+ expect(createAgentStartedEvent(input).data.streamPath).toBe("/eve/v1/session/child%2F1/stream");expect(- createSubagentCalledEvent({+ createAgentStartedEvent({...input,remote: { resolverId: "remote/research", url: "https://remote.example" },}).data,).toMatchObject({- childStreamPath: "/eve/v1/session/parent%2F1/subagents/call%2F1/child%2F1/stream",+ streamPath: "/eve/v1/session/parent%2F1/subagents/call%2F1/child%2F1/stream",remote: { resolverId: "remote/research", url: "https://remote.example" },});});diff --git a/packages/eve/src/protocol/message.ts b/packages/eve/src/protocol/message.tsindex 5d5e6b767..b92ed2651 100644--- a/packages/eve/src/protocol/message.ts+++ b/packages/eve/src/protocol/message.ts@@ -289,6 +289,8 @@ export interface InputRequestedStreamEvent {requests: readonly InputRequest[];sequence: number;stepIndex: number;+ /** The task that asks, when the request comes from a task's run. */+ taskId?: string;turnId: string;};type: "input.requested";@@ -357,58 +359,30 @@ export interface ActionPartialStreamEvent {type: "action.partial";}-/**- * Stream event emitted when the parent workflow starts a child subagent session.- */-export interface SubagentCalledStreamEvent {- data: {- agentId?: string;- callId: string;- childSessionId: string;- childStreamPath: string;- sessionId: string;- sequence: number;- name: string;- remote?: {- /**- * Key to the authored credential functions (`auth`/`headers`) for this- * remote child, resolved at stream-proxy time by- * `resolveRemoteAgentStreamHeaders`. Static subagent → the node id in- * `subagentRegistry.subagentsByNodeId`; dynamic subagent → its- * `credentialsStepId` in the step registry. The event stores this key —- * never resolved header values — because tokens expire and this event- * is persisted and streamed to clients. Absent when the remote child- * has no authored credentials.- */- resolverId?: string;- url: string;- };- toolName: string;- turnId: string;- workflowId: string;- };- type: "subagent.called";-}-/*** Stream event emitted when a workflow run opens a session with `ctx.agent`.* `callId` and `turnId` name the tool call whose run opened it; follow the- * session with `session.streamSubagent(event)`.+ * session with `session.agent(event).stream()`. For a task's run it comes+ * after that call's `task.started`.*/export interface AgentStartedStreamEvent {data: {callId: string;/** The turn of the call whose run opened the session. */turnId: string;+ /** The task whose run opened the session; absent when an `execute` call opened it. */+ taskId?: string;name: string;/** The opened session's id. */sessionId: string;/** A local session's stream route, or the parent-origin proxy for a remote one. */streamPath: string;/**- * Where a remote session runs, read by the parent's stream proxy. As on- * `subagent.called`, `resolverId` keys the authored credential functions,- * never resolved header values.+ * Where a remote session runs, read by the parent's stream proxy.+ * `resolverId` keys the authored credential functions (`auth` and+ * `headers`): a static agent's node id, or a dynamic agent's+ * `credentialsStepId`. The event is persisted and streamed to clients, so+ * it carries this key, never resolved header values.*/remote?: {resolverId?: string;@@ -419,40 +393,46 @@ export interface AgentStartedStreamEvent {}/**- * Stream event emitted when an inline subagent execution starts.- */-export interface SubagentStartedStreamEvent {- data: {- callId: string;- subagentName: string;- };- type: "subagent.started";-}--/**- * Stream event (`type: "subagent.event"`) wrapping one child stream event- * produced by an inline subagent, under `data.event`, tagged with the- * originating `data.callId` and `data.subagentName`.+ * Stream event emitted when a call starts a task. `(taskId, callId)`+ * identifies the call; `callId` is the tool call clients attach status to.+ * It comes before every event the task's run causes for the call, such as+ * `agent.started` and the call's `task.settled`.*/-export interface SubagentChildEventStreamEvent {+export interface TaskStartedStreamEvent {data: {callId: string;- event: UnstampedMessageStreamEvent;- subagentName: string;+ /**+ * `"agent"` for a subagent's generated tool, local or remote; `"tool"`+ * for an authored tool, including one that opens sessions with+ * `ctx.agent`. An agent call that fails before its session opens has no+ * `agent.started`, so this is how a client tells it is an agent call.+ */+ kind: "agent" | "tool";+ /** The tool whose call started the task. */+ name: string;+ taskId: string;+ turnId: string;};- type: "subagent.event";+ type: "task.started";}/**- * Stream event emitted after the parent accepts a successful subagent invocation result.+ * Stream event emitted once when a task's call settles: by the run's return+ * or failure, or by a cancel. `turnId` is the call's turn, the same as on its+ * `task.started`.*/-export interface SubagentCompletedStreamEvent {+export interface TaskSettledStreamEvent {data: {callId: string;- output: string;- subagentName: string;+ /** Why the call failed; present only when `status` is `"failed"`. */+ error?: { message: string };+ /** The call's result; present only when `status` is `"completed"`. */+ output?: JsonValue;+ status: "completed" | "failed" | "cancelled";+ taskId: string;+ turnId: string;};- type: "subagent.completed";+ type: "task.settled";}/**@@ -706,6 +686,8 @@ export interface AuthorizationRequiredStreamEvent {name: string;sequence: number;stepIndex: number;+ /** The task that needs the sign-in, when it comes from a task's run. */+ taskId?: string;turnId: string;webhookUrl?: string;};@@ -747,6 +729,8 @@ export interface AuthorizationCompletedStreamEvent {reason?: string;sequence: number;stepIndex: number;+ /** The task that needed the sign-in, when it comes from a task's run. */+ taskId?: string;turnId: string;};type: "authorization.completed";@@ -810,10 +794,8 @@ export type UnstampedMessageStreamEvent =| SessionStartedStreamEvent| SessionWaitingStreamEvent| ResultCompletedStreamEvent- | SubagentCalledStreamEvent- | SubagentChildEventStreamEvent- | SubagentCompletedStreamEvent- | SubagentStartedStreamEvent+ | TaskSettledStreamEvent+ | TaskStartedStreamEvent| ActionsRequestedStreamEvent| InputRequestedStreamEvent| InputResolvedStreamEvent@@ -1207,6 +1189,7 @@ export function createAuthorizationRequiredEvent(input: {readonly name: string;readonly sequence: number;readonly stepIndex: number;+ readonly taskId?: string;readonly turnId: string;readonly webhookUrl?: string;}): AuthorizationRequiredStreamEvent {@@ -1229,6 +1212,9 @@ export function createAuthorizationRequiredEvent(input: {if (input.webhookUrl !== undefined) {data.webhookUrl = input.webhookUrl;}+ if (input.taskId !== undefined) {+ data.taskId = input.taskId;+ }return {data,type: "authorization.required",@@ -1249,6 +1235,7 @@ export function createAuthorizationCompletedEvent(input: {readonly reason?: string;readonly sequence: number;readonly stepIndex: number;+ readonly taskId?: string;readonly turnId: string;}): AuthorizationCompletedStreamEvent {const data: AuthorizationCompletedStreamEvent["data"] = {@@ -1270,6 +1257,9 @@ export function createAuthorizationCompletedEvent(input: {if (input.reason !== undefined) {data.reason = input.reason;}+ if (input.taskId !== undefined) {+ data.taskId = input.taskId;+ }return {data,type: "authorization.completed",@@ -1297,17 +1287,17 @@ export function createInputRequestedEvent(input: {readonly requests: readonly InputRequest[];readonly sequence: number;readonly stepIndex: number;+ readonly taskId?: string;readonly turnId: string;}): InputRequestedStreamEvent {- return {- data: {- requests: input.requests,- sequence: input.sequence,- stepIndex: input.stepIndex,- turnId: input.turnId,- },- type: "input.requested",+ const data: InputRequestedStreamEvent["data"] = {+ requests: input.requests,+ sequence: input.sequence,+ stepIndex: input.stepIndex,+ turnId: input.turnId,};+ if (input.taskId !== undefined) data.taskId = input.taskId;+ return { data, type: "input.requested" };}/** Creates the authoritative `input.resolved` event for one pending HITL batch. */@@ -1382,47 +1372,35 @@ export function createActionPartialEvent(input: {};}-/**- * Creates the `subagent.called` event for one started child workflow session.- */-export function createSubagentCalledEvent(input: {- readonly agentId?: string;- readonly callId: string;- readonly childSessionId: string;- readonly sessionId: string;- readonly sequence: number;- readonly name: string;- readonly remote?: {- readonly resolverId?: string;- readonly url: string;- };- readonly toolName: string;- readonly turnId: string;- readonly workflowId: string;-}): SubagentCalledStreamEvent {+/** Creates the `task.started` event for one call that starts a task. */+export function createTaskStartedEvent(+ input: TaskStartedStreamEvent["data"],+): TaskStartedStreamEvent {return {data: {- agentId: input.agentId,callId: input.callId,- childSessionId: input.childSessionId,- childStreamPath:- input.remote === undefined- ? createEveSessionStreamRoutePath(input.childSessionId)- : createEveSubagentStreamRoutePath({- callId: input.callId,- childSessionId: input.childSessionId,- parentSessionId: input.sessionId,- }),- sessionId: input.sessionId,- sequence: input.sequence,+ kind: input.kind,name: input.name,- remote: input.remote,- toolName: input.toolName,+ taskId: input.taskId,turnId: input.turnId,- workflowId: input.workflowId,},- type: "subagent.called",+ type: "task.started",+ };+}++/** Creates the `task.settled` event for one settled task call. */+export function createTaskSettledEvent(+ input: TaskSettledStreamEvent["data"],+): TaskSettledStreamEvent {+ const data: TaskSettledStreamEvent["data"] = {+ callId: input.callId,+ status: input.status,+ taskId: input.taskId,+ turnId: input.turnId,};+ if (input.output !== undefined) data.output = input.output;+ if (input.error !== undefined) data.error = input.error;+ return { data, type: "task.settled" };}/**@@ -1437,6 +1415,7 @@ export function createAgentStartedEvent(input: {readonly url: string;};readonly sessionId: string;+ readonly taskId?: string;readonly turnId: string;}): AgentStartedStreamEvent {const data: AgentStartedStreamEvent["data"] = {@@ -1446,6 +1425,7 @@ export function createAgentStartedEvent(input: {sessionId: input.sessionId,streamPath: createEveSessionStreamRoutePath(input.sessionId),};+ if (input.taskId !== undefined) data.taskId = input.taskId;if (input.remote !== undefined) {data.remote = input.remote;data.streamPath = createEveSubagentStreamRoutePath({diff --git a/packages/eve/src/public/channels/eve-subagent-stream.test.ts b/packages/eve/src/public/channels/eve-subagent-stream.test.tsindex 5d93a2a91..05265e917 100644--- a/packages/eve/src/public/channels/eve-subagent-stream.test.ts+++ b/packages/eve/src/public/channels/eve-subagent-stream.test.ts@@ -8,7 +8,7 @@ import {} from "#internal/nitro/routes/channel-route-context.js";import { mockChannelContext } from "#internal/testing/mocks/mock-channel-operations.js";import { stampTestEvent } from "#internal/testing/events.js";-import { createSubagentCalledEvent, type MessageStreamEvent } from "#protocol/message.js";+import { createAgentStartedEvent, type MessageStreamEvent } from "#protocol/message.js";import { EVE_SUBAGENT_STREAM_ROUTE_PATTERN } from "#protocol/routes.js";import { none, type AuthFn } from "#public/channels/auth.js";import { eveChannel } from "#public/channels/eve.js";@@ -27,7 +27,7 @@ describe("eveChannel remote subagent stream", () => {it("authenticates before reading the parent or fetching upstream", async () => {const fetchMock = vi.fn();vi.stubGlobal("fetch", fetchMock);- const harness = createHarness({ auth: () => null, events: [remoteCalledEvent()] });+ const harness = createHarness({ auth: () => null, events: [remoteStartedEvent()] });const response = await harness.fetch(proxyRequest());@@ -40,9 +40,9 @@ describe("eveChannel remote subagent stream", () => {const fetchMock = vi.fn();vi.stubGlobal("fetch", fetchMock);const forged = createHarness({- events: [remoteCalledEvent({ callId: "different-call" })],+ events: [remoteStartedEvent({ callId: "different-call" })],});- const local = createHarness({ events: [localCalledEvent()] });+ const local = createHarness({ events: [localStartedEvent()] });expect((await forged.fetch(proxyRequest())).status).toBe(404);expect((await local.fetch(proxyRequest())).status).toBe(404);@@ -53,7 +53,7 @@ describe("eveChannel remote subagent stream", () => {const fetchMock = vi.fn();vi.stubGlobal("fetch", fetchMock);const harness = createHarness({- events: [remoteCalledEvent()],+ events: [remoteStartedEvent()],resolveHeaders: vi.fn().mockRejectedValue(new Error("remote URL mismatch")),});@@ -90,7 +90,7 @@ describe("eveChannel remote subagent stream", () => {const bindingCancelled = vi.fn();const harness = createHarness({bindingCancelled,- events: [remoteCalledEvent()],+ events: [remoteStartedEvent()],resolveHeaders,});const abort = new AbortController();@@ -148,7 +148,7 @@ describe("eveChannel remote subagent stream", () => {}),),);- const harness = createHarness({ events: [remoteCalledEvent()] });+ const harness = createHarness({ events: [remoteStartedEvent()] });const response = await harness.fetch(proxyRequest());@@ -158,38 +158,32 @@ describe("eveChannel remote subagent stream", () => {});});-function remoteCalledEvent(overrides: Partial<typeof coordinates> = {}): MessageStreamEvent {+function remoteStartedEvent(overrides: Partial<typeof coordinates> = {}): MessageStreamEvent {const values = { ...coordinates, ...overrides };return stampTestEvent(- createSubagentCalledEvent({+ createAgentStartedEvent({callId: values.callId,- childSessionId: values.childSessionId,name: "research",+ parentSessionId: values.parentSessionId,remote: {resolverId: "subagents/research",url: "https://remote.example/base",},- sequence: 1,- sessionId: values.parentSessionId,- toolName: "research",+ sessionId: values.childSessionId,turnId: "turn-1",- workflowId: "workflow-1",}),0,);}-function localCalledEvent(): MessageStreamEvent {+function localStartedEvent(): MessageStreamEvent {return stampTestEvent(- createSubagentCalledEvent({+ createAgentStartedEvent({callId: coordinates.callId,- childSessionId: coordinates.childSessionId,name: "research",- sequence: 1,- sessionId: coordinates.parentSessionId,- toolName: "research",+ parentSessionId: coordinates.parentSessionId,+ sessionId: coordinates.childSessionId,turnId: "turn-1",- workflowId: "workflow-1",}),0,);diff --git a/packages/eve/src/public/channels/slack/defaults.ts b/packages/eve/src/public/channels/slack/defaults.tsindex 663ea74b9..b3e27f674 100644--- a/packages/eve/src/public/channels/slack/defaults.ts+++ b/packages/eve/src/public/channels/slack/defaults.ts@@ -32,6 +32,7 @@ import type {SlackContext,SlackMentionResult,} from "#public/channels/slack/slackChannel.js";+import { stepNarration } from "#public/channels/slack/step-text.js";import type { InputRequest } from "#shared/input.js";const log = createLogger("slack.defaults");@@ -415,7 +416,6 @@ export const defaultEvents: SlackChannelInternalEvents = {},async "turn.started"(_event, channel, _ctx) {- channel.state.pendingToolCallMessage = null;channel.state.lastReasoningTypingAtMs = null;channel.state.lastReasoningTypingStatus = null;reasoningByState.delete(channel.state);@@ -467,23 +467,14 @@ export const defaultEvents: SlackChannelInternalEvents = {},async "actions.requested"(event, channel, _ctx) {- const buffered = channel.state.pendingToolCallMessage;- channel.state.pendingToolCallMessage = null;- if (buffered) {- await channel.thread.startTyping(truncateTypingStatus(buffered));- return;- }- await channel.thread.startTyping(truncateTypingStatus(describeActionRequests(event.actions)));+ const narration = stepNarration(channel.state, event.actions);+ const narrationLine = narration === null ? undefined : firstNonEmptyLine(narration);+ const status = narrationLine ?? describeActionRequests(event.actions);+ await channel.thread.startTyping(truncateTypingStatus(status));},async "message.completed"(event, channel, _ctx) {- if (event.finishReason === "tool-calls") {- channel.state.pendingToolCallMessage = event.message- ? (firstNonEmptyLine(event.message) ?? null)- : null;- return;- }- channel.state.pendingToolCallMessage = null;+ if (event.finishReason === "tool-calls") return;if (!event.message) {await channel.thread.startTyping();return;diff --git a/packages/eve/src/public/channels/slack/slackChannel.test.ts b/packages/eve/src/public/channels/slack/slackChannel.test.tsindex 9f65b94c0..ffbd6bff0 100644--- a/packages/eve/src/public/channels/slack/slackChannel.test.ts+++ b/packages/eve/src/public/channels/slack/slackChannel.test.ts@@ -765,9 +765,67 @@ describe("slackChannel() default event handlers", () => {expect(parseSlackRequestBody(init as RequestInit)).toMatchObject({status: "Checking the issue context first.",});- expect(ctx.state.pendingToolCallMessage).toBeNull();});+ it.each([+ ["the default handlers", {}],+ ["an overridden actions.requested", { events: { "actions.requested": async () => {} } }],+ ])(+ "posts a step's text only when its only tool call is task_wait, with %s",+ async (_, config) => {+ const adapter = withState(+ getAdapter(slackChannel({ credentials: { botToken: "xoxb-test" }, ...config })),+ THREAD_STATE,+ );+ const ctx = buildAdapterContext(adapter, stubAccessor());+ const runStep = async (+ stepIndex: number,+ toolNames: string[],+ textBefore: string,+ textAfter?: string,+ ) => {+ const coordinates = { sequence: 0, stepIndex, turnId: "t1" };+ const completeText = (message: string) =>+ callEvent(+ adapter,+ makeEvent("message.completed", { ...coordinates, finishReason: "tool-calls", message }),+ ctx,+ );+ await completeText(textBefore);+ for (const toolName of toolNames) {+ const action = {+ callId: `${stepIndex}-${toolName}`,+ input: {},+ kind: "tool-call",+ toolName,+ };+ await callEvent(+ adapter,+ makeEvent("actions.requested", { ...coordinates, actions: [action] }),+ ctx,+ );+ }+ if (textAfter !== undefined) await completeText(textAfter);+ await callEvent(+ adapter,+ makeEvent("step.completed", { ...coordinates, finishReason: "tool-calls" }),+ ctx,+ );+ };++ await runStep(0, ["task_wait"], "Checking revenue and incidents now.", "I'll report back.");+ await runStep(1, ["task_wait", "search"], "Searching while I wait.");++ const posts = fetchMock.mock.calls.filter(+ ([url]) => String(url) === "https://slack.com/api/chat.postMessage",+ );+ expect(posts).toHaveLength(1);+ expect(parseSlackRequestBody(posts[0]![1] as RequestInit)).toMatchObject({+ markdown_text: "Checking revenue and incidents now.\nI'll report back.",+ });+ },+ );+it("message.completed clears typing without posting for empty delivery", async () => {const adapter = withState(getAdapter(slackChannel({ credentials: { botToken: "xoxb-test" } })),diff --git a/packages/eve/src/public/channels/slack/slackChannel.ts b/packages/eve/src/public/channels/slack/slackChannel.tsindex 79c7f80a5..5b3965cbc 100644--- a/packages/eve/src/public/channels/slack/slackChannel.ts+++ b/packages/eve/src/public/channels/slack/slackChannel.ts@@ -48,6 +48,12 @@ import {defaultOnDirectMessage,postCompletedSlackReply,} from "#public/channels/slack/defaults.js";+import {+ bufferToolCallMessage,+ clearPendingStep,+ recordStepActions,+ takeTextBeforeTaskWait,+} from "#public/channels/slack/step-text.js";import {parseMessageEvent,type SlackEvent,@@ -240,13 +246,21 @@ export interface SlackChannelState {*/triggeringUserId?: string | null;/**- * Buffered text from a `message.completed` event whose `finishReason`- * was `"tool-calls"`. The default `actions.requested` handler uses the- * first non-empty line as the next typing indicator, surfacing the- * model's pre-tool narration instead of the action label. Cleared at- * `turn.started` and after use.+ * The step's text from `message.completed` events whose `finishReason`+ * was `"tool-calls"`, joined by newlines and kept until the step+ * completes. The default `actions.requested` handler shows its first+ * non-empty line as typing status for the step's first actions. At+ * `step.completed` the channel posts it when the step's only action was+ * `task_wait`, outside a schedule's turn, whichever `actions.requested`+ * and `message.completed` handlers are in use. Cleared at `turn.started`+ * and `step.completed`.*/pendingToolCallMessage?: string | null;+ /**+ * Names of the actions the current model step requested, collected across+ * its `actions.requested` events until `step.completed`.+ */+ stepActionNames?: string[] | null;/*** Last reasoning-derived typing indicator sent by the default* `reasoning.appended` handler. Used to surface substantial progressive@@ -587,7 +601,10 @@ export type SlackInboundResultOrPromise = SlackMentionResultOrPromise;* only that event's built-in default (see {@link defaultEvents}). Handlers* receive the event data, the {@link SlackEventContext}, and the session* {@link SessionContext}; `session.failed` receives only data and channel- * context and exposes the ID as `data.sessionId`.+ * context and exposes the ID as `data.sessionId`. Overriding+ * `actions.requested` or `message.completed` doesn't stop the channel from+ * posting a step's text at `step.completed` when the step's only action was+ * `task_wait`.*/export interface SlackChannelEvents {readonly "approval.candidate"?: SlackEventHandler<"approval.candidate">;@@ -627,7 +644,9 @@ export interface SlackChannelEvents {* handler keeps the full {@link SlackEventContext} because it owns the* public link-free status while user overrides remain private-only. The* factory adapts user overrides into this shape with- * {@link constrainAuthorizationRequired}.+ * {@link constrainAuthorizationRequired}. `step.completed` has no default+ * and can't be overridden: the factory handles it to post a step's text+ * before a `task_wait`.*/export interface SlackChannelInternalEvents extends Omit<SlackChannelEvents,@@ -635,6 +654,7 @@ export interface SlackChannelInternalEvents extends Omit<> {readonly "authorization.required"?: SlackEventHandler<"authorization.required">;readonly "input.requested"?: SlackEventHandler<"input.requested">;+ readonly "step.completed"?: SlackEventHandler<"step.completed">;}export type SlackApprovalChannel = "direct-message" | "thread";@@ -819,7 +839,6 @@ const activityOwnedMessageCompleted: NonNullable<SlackChannelEvents["message.comevent,channel,) => {- channel.state.pendingToolCallMessage = null;if (event.finishReason !== "tool-calls" && event.message) {await postCompletedSlackReply(channel, event.message);}@@ -829,7 +848,6 @@ const clearSlackTurnState: NonNullable<SlackChannelEvents["turn.started"]> = asy_data,channel,) => {- channel.state.pendingToolCallMessage = null;channel.state.lastReasoningTypingAtMs = null;channel.state.lastReasoningTypingStatus = null;};@@ -941,11 +959,26 @@ export function slackChannel(config: SlackChannelConfig = {}): SlackChannel {if (triggeringUserId !== undefined) {channel.state.triggeringUserId = triggeringUserId;}+ clearPendingStep(channel.state);await turnStartedHandler(data, channel, ctx);},"reasoning.appended": reasoningHandler,- "actions.requested": actionsHandler,- "message.completed": messageCompletedHandler,+ async "actions.requested"(data, channel, ctx) {+ recordStepActions(channel.state, data.actions);+ await actionsHandler(data, channel, ctx);+ },+ async "message.completed"(data, channel, ctx) {+ if (data.finishReason === "tool-calls") {+ bufferToolCallMessage(channel.state, data.message);+ } else {+ channel.state.pendingToolCallMessage = null;+ }+ await messageCompletedHandler(data, channel, ctx);+ },+ async "step.completed"(_data, channel) {+ const text = takeTextBeforeTaskWait(channel.state);+ if (text !== null) await postCompletedSlackReply(channel, text);+ },"input.requested": inputRequestedHandler,"authorization.required":authorizationRequiredOverride === undefineddiff --git a/packages/eve/src/public/channels/slack/step-text.ts b/packages/eve/src/public/channels/slack/step-text.tsnew file mode 100644index 000000000..abb93db88--- /dev/null+++ b/packages/eve/src/public/channels/slack/step-text.ts@@ -0,0 +1,75 @@+/**+ * Per-step bookkeeping for a model step's text and requested actions. Slack+ * shows the text as typing status while the step requests actions, and posts+ * it once the step completes if the step's only action was `task_wait`.+ */+import { contextStorage } from "#context/container.js";+import { ScheduleIdKey } from "#context/keys.js";+import { TASK_WAIT_TOOL_NAME } from "#execution/tasks/calls.js";+import type { SlackChannelState } from "#public/channels/slack/slackChannel.js";+import type { RuntimeActionRequest } from "#shared/action-types.js";++/**+ * Buffers a `"tool-calls"` step's text until the step completes. A step+ * flushes its text before each action and again at its end, so runs append.+ */+export function bufferToolCallMessage(state: SlackChannelState, message: string | null): void {+ if (message === null || message.trim().length === 0) return;+ const buffered = state.pendingToolCallMessage;+ state.pendingToolCallMessage = buffered ? `${buffered}\n${message}` : message;+}++/** Only a plain tool call can be `task_wait`, so other kinds record their kind. */+function requestedActionName(action: RuntimeActionRequest): string {+ if (action.kind === "tool-call") return action.toolName;+ return action.kind;+}++/** Collects the step's actions, which may arrive over several `actions.requested` events. */+export function recordStepActions(+ state: SlackChannelState,+ actions: readonly RuntimeActionRequest[],+): void {+ const names = actions.map(requestedActionName);+ state.stepActionNames = [...(state.stepActionNames ?? []), ...names];+}++/**+ * The step's text, offered as typing status only for the step's first actions.+ * The channel records each batch before its handler runs, so the first batch+ * is the one that makes up every recorded name.+ */+export function stepNarration(+ state: SlackChannelState,+ actions: readonly RuntimeActionRequest[],+): string | null {+ const isFirstBatch = (state.stepActionNames?.length ?? 0) === actions.length;+ if (!isFirstBatch) return null;+ return state.pendingToolCallMessage ?? null;+}++export function clearPendingStep(state: SlackChannelState): void {+ state.pendingToolCallMessage = null;+ state.stepActionNames = null;+}++function isOnlyTaskWait(actionNames: readonly string[]): boolean {+ return actionNames.length === 1 && actionNames[0] === TASK_WAIT_TOOL_NAME;+}++function isScheduleTurn(): boolean {+ return contextStorage.getStore()?.get(ScheduleIdKey) !== undefined;+}++/**+ * Ends the step and returns its text when its only action was `task_wait`, so+ * a person sees what is running while the turn waits. Returns `null` for any+ * other step and for a schedule's turn, whose reader gets only the final reply.+ */+export function takeTextBeforeTaskWait(state: SlackChannelState): string | null {+ const text = state.pendingToolCallMessage ?? null;+ const actionNames = state.stepActionNames ?? [];+ clearPendingStep(state);+ if (!isOnlyTaskWait(actionNames) || isScheduleTurn()) return null;+ return text;+}diff --git a/packages/eve/src/public/definitions/channel.ts b/packages/eve/src/public/definitions/channel.tsindex ad424b788..944e1ae93 100644--- a/packages/eve/src/public/definitions/channel.ts+++ b/packages/eve/src/public/definitions/channel.ts@@ -207,6 +207,7 @@ export interface ChannelEvents<TCtx = void> {readonly "message.appended"?: ChannelEventHandler<"message.appended", TCtx>;readonly "reasoning.appended"?: ChannelEventHandler<"reasoning.appended", TCtx>;readonly "reasoning.completed"?: ChannelEventHandler<"reasoning.completed", TCtx>;+ readonly "step.completed"?: ChannelEventHandler<"step.completed", TCtx>;readonly "input.requested"?: ChannelEventHandler<"input.requested", TCtx>;readonly "turn.failed"?: ChannelEventHandler<"turn.failed", TCtx>;readonly "turn.completed"?: ChannelEventHandler<"turn.completed", TCtx>;@@ -317,6 +318,7 @@ const channelEventTypes: Record<keyof ChannelEvents, null> = {"message.appended": null,"reasoning.appended": null,"reasoning.completed": null,+ "step.completed": null,"input.requested": null,"turn.failed": null,"turn.completed": null,diff --git a/packages/eve/src/public/definitions/hook.ts b/packages/eve/src/public/definitions/hook.tsindex 1c3f6fb49..a6738a14d 100644--- a/packages/eve/src/public/definitions/hook.ts+++ b/packages/eve/src/public/definitions/hook.ts@@ -42,10 +42,8 @@ export interface HookEventMap {readonly "step.completed": ProtocolEvent<"step.completed">;readonly "step.failed": ProtocolEvent<"step.failed">;readonly "step.started": ProtocolEvent<"step.started">;- readonly "subagent.called": ProtocolEvent<"subagent.called">;- readonly "subagent.completed": ProtocolEvent<"subagent.completed">;- readonly "subagent.event": ProtocolEvent<"subagent.event">;- readonly "subagent.started": ProtocolEvent<"subagent.started">;+ readonly "task.settled": ProtocolEvent<"task.settled">;+ readonly "task.started": ProtocolEvent<"task.started">;readonly "turn.cancelled": ProtocolEvent<"turn.cancelled">;readonly "turn.completed": ProtocolEvent<"turn.completed">;readonly "turn.failed": ProtocolEvent<"turn.failed">;diff --git a/packages/eve/src/public/tools/index.ts b/packages/eve/src/public/tools/index.tsindex 2f54d5ac5..ecafa6e60 100644--- a/packages/eve/src/public/tools/index.ts+++ b/packages/eve/src/public/tools/index.ts@@ -36,7 +36,13 @@ export {export {defineWorkflowTool,+ type WorkflowExecuteToolDefinition,+ type WorkflowServeCall,+ type WorkflowServeContext,+ type WorkflowServeReceive,+ type WorkflowServeToolDefinition,type WorkflowStepToolContext,+ type WorkflowTaskToolDefinition,type WorkflowToolContext,type WorkflowToolDefinition,type AgentMessageResult,diff --git a/packages/eve/src/runtime/agent/bootstrap-model-utils.ts b/packages/eve/src/runtime/agent/bootstrap-model-utils.tsindex ef547e443..00469718a 100644--- a/packages/eve/src/runtime/agent/bootstrap-model-utils.ts+++ b/packages/eve/src/runtime/agent/bootstrap-model-utils.ts@@ -1,6 +1,6 @@import type { MockLanguageModelV3 } from "ai/test";-import { AGENTS_SNIPPET_LABEL } from "#subagents/handles/prompt.js";+import { TASK_RESULT_TAG, TASKS_NOTE_LABEL } from "#execution/tasks/render.js";export type BootstrapGenerateOptions = Parameters<MockLanguageModelV3["doGenerate"]>[0];export type BootstrapPrompt = BootstrapGenerateOptions["prompt"];@@ -158,8 +158,8 @@ export function getPromptContentText(content: BootstrapPrompt[number]["content"]/*** Returns the text from the last user message in the prompt, or `null`.*- * Skips framework-injected `[Agents]` announcements: they ride the user- * role in conversation history, but they are not authored input and must+ * Skips framework-injected `[Tasks]` notes and task results: they ride the+ * user role in conversation history, but they are not authored input and must* not drive mock directive parsing.*/export function getLastUserPromptText(prompt: BootstrapPrompt): string | null {@@ -170,7 +170,7 @@ export function getLastUserPromptText(prompt: BootstrapPrompt): string | null {const text = getPromptContentText(message.content).trim();- if (isAgentsAnnouncementText(text)) {+ if (isFrameworkAnnouncementText(text)) {continue;}@@ -183,13 +183,12 @@ export function getLastUserPromptText(prompt: BootstrapPrompt): string | null {}/**- * True when the text is a framework-injected `[Agents]` announcement.- * Announcements are user-role scaffolding, not authored input: mock model- * heuristics must scan past them instead of treating them as the turn's- * message or as a turn boundary.+ * True when the text is a framework-injected `[Tasks]` note or task result:+ * user-role scaffolding, not authored input. Mock model heuristics must scan+ * past it instead of treating it as the turn's message or as a turn boundary.*/-export function isAgentsAnnouncementText(text: string): boolean {- return text.startsWith(AGENTS_SNIPPET_LABEL);+export function isFrameworkAnnouncementText(text: string): boolean {+ return text.startsWith(TASKS_NOTE_LABEL) || text.startsWith(TASK_RESULT_TAG);}/**diff --git a/packages/eve/src/runtime/agent/bootstrap.test.ts b/packages/eve/src/runtime/agent/bootstrap.test.tsindex f56baf855..72e1b0c13 100644--- a/packages/eve/src/runtime/agent/bootstrap.test.ts+++ b/packages/eve/src/runtime/agent/bootstrap.test.ts@@ -43,7 +43,7 @@ function createResolvedAgentForTest(overrides: Partial<ResolvedAgent> = {}): Resreturn agent as ResolvedAgent;}-describe("createResolvedRuntimeTurnAgent agent-messaging gating", () => {+describe("createResolvedRuntimeTurnAgent", () => {it("partitions static user instructions into initial messages", () => {const turnAgent = createResolvedRuntimeTurnAgent({agent: createResolvedAgentForTest({@@ -88,61 +88,4 @@ describe("createResolvedRuntimeTurnAgent agent-messaging gating", () => {"Instructions (instructions/system)\nSystem policy.",);});-- it("includes messaging instructions for the root framework agent tool", () => {- const turnAgent = createResolvedRuntimeTurnAgent({- agent: createResolvedAgentForTest(),- nodeId: ROOT_RUNTIME_AGENT_NODE_ID,- tools: [createFrameworkAgentTool()],- });-- expect(turnAgent.instructions).toContainEqual(expect.stringContaining("Agent messaging"));- expect(turnAgent.instructions).toContainEqual(expect.stringContaining("Tool execution"));- });-- it("omits the messaging instruction when an authored tool named agent shadows the framework tool", () => {- const turnAgent = createResolvedRuntimeTurnAgent({- agent: createResolvedAgentForTest({- config: { name: "test-agent" } as ResolvedAgent["config"],- }),- nodeId: ROOT_RUNTIME_AGENT_NODE_ID,- tools: [- {- description: "Authored replacement for the framework agent tool.",- inputSchema: null,- kind: "authored-tool",- logicalPath: `tools/${AGENT_TOOL_NAME}.ts`,- name: AGENT_TOOL_NAME,- owner: APPLICATION_OWNER,- sourceId: `tools/${AGENT_TOOL_NAME}.ts`,- },- ],- });-- expect(turnAgent.instructions).not.toContainEqual(expect.stringContaining("Agent messaging"));- });-- it("omits the messaging instruction when no agent tool was compiled", () => {- const turnAgent = createResolvedRuntimeTurnAgent({- agent: createResolvedAgentForTest({- config: { name: "test-agent" } as ResolvedAgent["config"],- }),- nodeId: ROOT_RUNTIME_AGENT_NODE_ID,- tools: [],- });-- expect(turnAgent.instructions).not.toContainEqual(expect.stringContaining("Agent messaging"));- });-- it("omits the messaging instruction for a non-root node without declared subagents", () => {- const turnAgent = createResolvedRuntimeTurnAgent({- agent: createResolvedAgentForTest({- config: { name: "test-agent" } as ResolvedAgent["config"],- }),- nodeId: "subagents/researcher",- tools: [],- });-- expect(turnAgent.instructions).not.toContainEqual(expect.stringContaining("Agent messaging"));- });});diff --git a/packages/eve/src/runtime/agent/bootstrap.ts b/packages/eve/src/runtime/agent/bootstrap.tsindex 4485c5882..b1a6a7b5d 100644--- a/packages/eve/src/runtime/agent/bootstrap.ts+++ b/packages/eve/src/runtime/agent/bootstrap.ts@@ -86,7 +86,6 @@ export const BOOTSTRAP_RUNTIME_SYSTEM_PROMPT =*/export function createResolvedRuntimeTurnAgent(input: {readonly agent: ResolvedAgent;- readonly dynamicSubagentsAvailable?: boolean;readonly id?: string;readonly nodeId?: string;readonly tools: readonly PreparedRuntimeTool[];@@ -97,14 +96,6 @@ export function createResolvedRuntimeTurnAgent(input: {if (id === undefined) {throw new Error("Expected a path-derived agent id while resolving agent resources.");}- const subagentDeclaredTool = input.tools.some(- (tool) => tool.kind === "subagent" || tool.kind === "remote",- );- const subagentFrameworkRootTool = input.tools.some(- (tool) =>- tool.behavior?.handling?.kind === "dispatch" &&- tool.behavior.handling.target.kind === "self-agent-call",- );const base: RuntimeTurnAgentBase = {availableSkills: agent.skills.map((skill) => ({description: skill.description,@@ -117,10 +108,6 @@ export function createResolvedRuntimeTurnAgent(input: {instructions: composeRuntimeBasePrompt({connections: agent.connections,instructions: agent.instructions,- subagentsAvailable:- input.dynamicSubagentsAvailable === true ||- subagentDeclaredTool ||- subagentFrameworkRootTool,toolsAvailable: input.tools.length > 0,workspaceSpec: agent.workspaceSpec,}),diff --git a/packages/eve/src/runtime/agent/mock-model-adapter.test.ts b/packages/eve/src/runtime/agent/mock-model-adapter.test.tsindex 74f95edcc..6a5dcf394 100644--- a/packages/eve/src/runtime/agent/mock-model-adapter.test.ts+++ b/packages/eve/src/runtime/agent/mock-model-adapter.test.ts@@ -698,12 +698,10 @@ describe("createMockAuthoredRuntimeModel", () => {]);});- // Regression: the [Agents] announcement is user-role scaffolding injected- // after a subagent settles. Treating it as a turn boundary masked the tool- // result, and the adapter re-issued the same deterministic tool call — a- // duplicate start operation that fatally failed the parent session in the- // mock world suites.- it("replies to a tool result behind a framework [Agents] announcement instead of re-calling", async () => {+ // Regression: the [Tasks] note is user-role scaffolding injected at a step+ // boundary. Treating it as a turn boundary masked the tool result, and the+ // adapter re-issued the same deterministic tool call.+ it("replies to a tool result behind a framework [Tasks] note instead of re-calling", async () => {const result = await generateWithPrompt([{@@ -734,7 +732,7 @@ describe("createMockAuthoredRuntimeModel", () => {},{content:- '[Agents]\n<agents>\n<agent id="ag_conditional-marker:5ae9bfd35776" name="conditional-marker">DYNAMIC_SUBAGENT_ENABLED</agent>\n</agents>',+ '[Tasks]\n<tasks>\n</tasks>\n<idle>\n<task id="conditional-marker-5ae9bf" tool="conditional-marker"/>\n</idle>',role: "user",},],diff --git a/packages/eve/src/runtime/agent/mock-model-adapter.ts b/packages/eve/src/runtime/agent/mock-model-adapter.tsindex 8aafaad6d..5b2516efe 100644--- a/packages/eve/src/runtime/agent/mock-model-adapter.ts+++ b/packages/eve/src/runtime/agent/mock-model-adapter.ts@@ -23,7 +23,7 @@ import {getLastUserPromptText,getPromptContentText,getPromptText,- isAgentsAnnouncementText,+ isFrameworkAnnouncementText,} from "#runtime/agent/bootstrap-model-utils.js";import {findRelevantSkill,@@ -32,6 +32,7 @@ import {} from "#runtime/agent/mock-model-skill-selection.js";import { createJsonSchemaSample } from "#runtime/agent/mock-structured-output.js";import { FINAL_OUTPUT_TOOL_NAME } from "#harness/final-output.js";+import { readTaskResults } from "#execution/tasks/render.js";import { LOAD_SKILL_TOOL_NAME } from "#runtime/skills/fragment-context.js";const MOCK_RUNTIME_MODEL_PROVIDER = "eve-runtime-mock";@@ -485,14 +486,16 @@ function getAvailableTools(options: BootstrapGenerateOptions): AvailableBootstrafunction getLastAuthoredToolResult(prompt: BootstrapPrompt): BootstrapToolResult | null {for (const message of [...prompt].reverse()) {if (message.role === "user") {- // A framework-injected [Agents] announcement is scaffolding, not a- // turn boundary. Treating it as one masks the tool result behind it,- // and the adapter then re-issues the same deterministic tool call —- // for subagent starts that collides on the derived operation id and- // fatally fails the parent session.- if (isAgentsAnnouncementText(getPromptContentText(message.content).trim())) {- continue;+ const text = getPromptContentText(message.content).trim();+ // A task's result arrives after its receipt, in a message of its own.+ const task = readTaskResults(text).at(-1);+ if (task !== undefined) {+ const { body: output, taskId: toolCallId, tool: toolName } = task;+ return { isError: task.status === "failed", output, toolCallId, toolName };}+ // The [Tasks] note is scaffolding, not a turn boundary: skipping it keeps+ // the tool result behind it, so the same call is not issued again.+ if (isFrameworkAnnouncementText(text)) continue;return null;}diff --git a/packages/eve/src/runtime/agent/mock-model-fixtures.ts b/packages/eve/src/runtime/agent/mock-model-fixtures.tsindex c6eb87961..a85d1c677 100644--- a/packages/eve/src/runtime/agent/mock-model-fixtures.ts+++ b/packages/eve/src/runtime/agent/mock-model-fixtures.ts@@ -1,8 +1,9 @@import type { BootstrapPrompt } from "#runtime/agent/bootstrap-model-utils.js";import {getPromptContentText,- isAgentsAnnouncementText,+ isFrameworkAnnouncementText,} from "#runtime/agent/bootstrap-model-utils.js";+import { TASK_ID_INPUT } from "#execution/tasks/task-id-input.js";import { createJsonSchemaSample } from "#runtime/agent/mock-structured-output.js";import { LOAD_SKILL_TOOL_NAME } from "#runtime/skills/fragment-context.js";@@ -14,10 +15,12 @@ export interface AvailableBootstrapTool {}export function createMockAuthoredToolInput(- tool: AvailableBootstrapTool,+ offered: AvailableBootstrapTool,message: string,city: string,): Record<string, unknown> {+ // The mock only starts tasks; it never names one to continue.+ const tool = { ...offered, inputSchema: withoutTaskIdInput(offered.inputSchema) };const inputPropertyNames = getToolInputPropertyNames(tool.inputSchema);if (inputPropertyNames.includes("question")) {return createQuestionInput(message);@@ -51,6 +54,12 @@ export function createMockAuthoredToolInput(return isRecord(sample) ? sample : {};}+function withoutTaskIdInput(schema: unknown): unknown {+ if (!isRecord(schema) || !isRecord(schema.properties)) return schema;+ const { [TASK_ID_INPUT]: _taskId, ...properties } = schema.properties;+ return { ...schema, properties };+}+/*** Extracts tool inputs anchored to schema property names in the message, e.g.* `with label "smoke-test"`, ``value `hello```, or `note: 'smoke'`. This lets@@ -142,9 +151,9 @@ function getTrailingUserText(prompt: BootstrapPrompt): string {if (message.role === "system") continue;if (message.role !== "user") break;const text = getPromptContentText(message.content);- // Framework-injected [Agents] announcements are scaffolding, not part- // of the turn's authored ask.- if (isAgentsAnnouncementText(text.trim())) continue;+ // Framework-injected [Tasks] notes are scaffolding, not part of the+ // turn's authored ask.+ if (isFrameworkAnnouncementText(text.trim())) continue;texts.unshift(text);}diff --git a/packages/eve/src/runtime/prompt/compose.test.ts b/packages/eve/src/runtime/prompt/compose.test.tsdeleted file mode 100644index fc08e487f..000000000--- a/packages/eve/src/runtime/prompt/compose.test.ts+++ /dev/null@@ -1,23 +0,0 @@-import { describe, expect, it } from "vitest";--import { composeRuntimeBasePrompt } from "#runtime/prompt/compose.js";--describe("composeRuntimeBasePrompt", () => {- it("includes agent messaging instructions when subagents are available", () => {- const prompt = composeRuntimeBasePrompt({- subagentsAvailable: true,- });-- expect(prompt).toContainEqual(expect.stringContaining("agentId"));- expect(prompt).toContainEqual(expect.stringContaining("<agents>"));- });-- it("omits agent messaging instructions when subagents are unavailable", () => {- const prompt = composeRuntimeBasePrompt({- subagentsAvailable: false,- });-- expect(prompt).not.toContainEqual(expect.stringContaining("Agent messaging"));- expect(prompt).not.toContainEqual(expect.stringContaining("<agents>"));- });-});diff --git a/packages/eve/src/runtime/prompt/compose.ts b/packages/eve/src/runtime/prompt/compose.tsindex 6e36edeb5..442d0bf3d 100644--- a/packages/eve/src/runtime/prompt/compose.ts+++ b/packages/eve/src/runtime/prompt/compose.ts@@ -11,9 +11,6 @@ import { formatConnectionsSection } from "#runtime/prompt/connections.js";const PARALLEL_ACTION_INSTRUCTION ="Tool execution\nA single tool or subagent call runs as one serial action. If you call multiple independent tools or subagents in one response, eve treats that batch as parallel work. Only batch work that is independent and does not rely on another call in the same response.";-const AGENT_MESSAGING_INSTRUCTION =- "Agent messaging\nA subagent call runs until the subagent replies, and its reply is the tool result. Agents you have already delegated to remain visible in the framework-authored `<agents>` conversation note. To continue an agent's conversation, call the original subagent tool again with that agentId. Calling a subagent without agentId starts a new agent session.";-/*** Input for composing the base authored instructions prompt for one* resolved agent.@@ -22,7 +19,6 @@ interface ComposeRuntimeBasePromptInput {connections?: readonly ResolvedConnectionDefinition[];instructions?: readonly ResolvedInstructionsDefinition[];skills?: readonly ResolvedSkillDefinition[];- subagentsAvailable?: boolean;toolsAvailable?: boolean;workspaceSpec?: WorkspaceRuntimeSpec;}@@ -36,7 +32,6 @@ export function composeRuntimeBasePrompt(input: ComposeRuntimeBasePromptInput):...createInstructionsPromptBlocks(input.instructions),...createWorkspacePromptBlocks(input.workspaceSpec),...(input.toolsAvailable ? [PARALLEL_ACTION_INSTRUCTION] : []),- ...(input.subagentsAvailable ? [AGENT_MESSAGING_INSTRUCTION] : []),...createConnectionsPromptBlocks(input.connections),...createSkillsPromptBlocks(input.skills),];diff --git a/packages/eve/src/runtime/resolve-agent-graph.ts b/packages/eve/src/runtime/resolve-agent-graph.tsindex 9cfeecd6e..3fe8e4b63 100644--- a/packages/eve/src/runtime/resolve-agent-graph.ts+++ b/packages/eve/src/runtime/resolve-agent-graph.ts@@ -174,7 +174,6 @@ async function resolveRuntimeAgentNode(toolRegistry,turnAgent: createResolvedRuntimeTurnAgent({agent,- dynamicSubagentsAvailable: subagentRegistry.dynamicResolvers.length > 0,id: input.agentId,nodeId,tools: [...toolRegistry.preparedTools, ...subagentRegistry.preparedTools],diff --git a/packages/eve/src/runtime/resolve-tool.ts b/packages/eve/src/runtime/resolve-tool.tsindex a244ca2ae..b3105fe44 100644--- a/packages/eve/src/runtime/resolve-tool.ts+++ b/packages/eve/src/runtime/resolve-tool.ts@@ -66,10 +66,14 @@ export async function resolveToolDefinition(registerDefinitionSource(sourceKey, sourceEntry);registerDefinitionSource(`tool:${resolvedRecord.description}`, sourceEntry);- const execute = expectFunction(- resolvedRecord.execute,- describe(definition, "to provide an execute function"),- ) as NonNullable<ResolvedToolDefinition["execute"]>;+ // A workflow tool's entry point runs from the workflow registry, never in process.+ const execute =+ definition.behavior?.handling?.kind === "workflow-tool"+ ? undefined+ : (expectFunction(+ resolvedRecord.execute,+ describe(definition, "to provide an execute function"),+ ) as NonNullable<ResolvedToolDefinition["execute"]>);const inputSchema = isToolSchema(resolvedRecord.inputSchema)? resolvedRecord.inputSchema: toInputSchema(definition.inputSchema);diff --git a/packages/eve/src/runtime/sessions/turn.ts b/packages/eve/src/runtime/sessions/turn.tsindex 9bc5b423e..7dc0430a9 100644--- a/packages/eve/src/runtime/sessions/turn.ts+++ b/packages/eve/src/runtime/sessions/turn.ts@@ -4,18 +4,6 @@ import type { InternalToolDefinition } from "#tools/definition.js";import type { AgentSourceOwner } from "#compiler/source-graph.js";import type { PreparedToolBehavior } from "#tools/behavior.js";-/** Grouped durable workflow metadata for one prepared harness tool. */-export interface PreparedRuntimeWorkflowTask {- /**- * Runtime graph ID of the agent definition this tool delegates to, including- * the root agent for the framework `agent` tool. Used for receipts and handle- * reservations; `agentId` identifies the resulting agent instance.- * Absent for authored workflow tools, even if their body calls `ctx.agent()`.- */- readonly nodeId?: string;- /** Registered workflow definition to execute. */- readonly workflowId: string;-}/*** Serializable authored tool descriptor prepared by the runtime for one* harness turn.@@ -27,7 +15,6 @@ export type PreparedRuntimeAuthoredTool = Readonly<kind: "authored-tool";owner: AgentSourceOwner;rootOnly?: boolean;- task?: PreparedRuntimeWorkflowTask;}>;@@ -38,7 +25,6 @@ type PreparedRuntimeDelegationToolBase<TKind extends "remote" | "subagent"> = Rebehavior: PreparedToolBehavior;kind: TKind;rootOnly?: boolean;- task: PreparedRuntimeWorkflowTask;}>;diff --git a/packages/eve/src/runtime/subagents/registry.ts b/packages/eve/src/runtime/subagents/registry.tsindex 7b73edd32..82f14a322 100644--- a/packages/eve/src/runtime/subagents/registry.ts+++ b/packages/eve/src/runtime/subagents/registry.ts@@ -7,7 +7,6 @@ import type {import type { JsonObject } from "#shared/json.js";import { serializeInputSchema } from "#tools/schema.js";import { SUBAGENT_TOOL_INPUT_SCHEMA } from "#tools/framework/agent-contract.js";-import { subagentToolExecuteWorkflowReference } from "#runtime/subagents/workflow-reference.js";/*** One runtime-owned subagent tracked by the prepared registry.@@ -159,9 +158,5 @@ export function createPreparedRuntimeSubagentTool(name: definition.name,nodeId: definition.nodeId,sourceId: definition.sourceId,- task: {- nodeId: definition.nodeId,- workflowId: subagentToolExecuteWorkflowReference.workflowId,- },};}diff --git a/packages/eve/src/runtime/subagents/workflow-reference.ts b/packages/eve/src/runtime/subagents/workflow-reference.tsindex 4f612b8d8..96907b485 100644--- a/packages/eve/src/runtime/subagents/workflow-reference.ts+++ b/packages/eve/src/runtime/subagents/workflow-reference.ts@@ -1,8 +1,24 @@import { EVE_PACKAGE_NAME } from "#internal/package-name.js";+import type { PreparedToolHandling } from "#tools/behavior.js";-export const SUBAGENT_TOOL_EXECUTE_WORKFLOW_NAME = "subagentToolExecuteWorkflow";+export const AGENT_TOOL_SERVE_WORKFLOW_NAME = "agentToolServeWorkflow";-/** Shared framework-owned execute body for local and remote subagent tools. */-export const subagentToolExecuteWorkflowReference = {- workflowId: `workflow//${EVE_PACKAGE_NAME}//${SUBAGENT_TOOL_EXECUTE_WORKFLOW_NAME}`,+/** The framework-owned `serve` body of every agent tool. */+export const agentToolServeWorkflowReference = {+ workflowId: `workflow//${EVE_PACKAGE_NAME}//${AGENT_TOOL_SERVE_WORKFLOW_NAME}`,};++/** Registered workflow that runs a tool with this handling; absent for tools without one. */+export function workflowIdForHandling(+ handling: PreparedToolHandling | undefined,+): string | undefined {+ if (handling?.kind !== "dispatch") return undefined;+ switch (handling.target.kind) {+ case "workflow-tool-call":+ return handling.target.workflowId;+ case "remote-agent-call":+ case "self-agent-call":+ case "subagent-call":+ return agentToolServeWorkflowReference.workflowId;+ }+}diff --git a/packages/eve/src/runtime/subagents/workflow.test.ts b/packages/eve/src/runtime/subagents/workflow.test.tsnew file mode 100644index 000000000..d963ebd73--- /dev/null+++ b/packages/eve/src/runtime/subagents/workflow.test.ts@@ -0,0 +1,213 @@+import { expect, it, vi } from "vitest";++import type { RuntimeActionResultHookPayload } from "#channel/types.js";+import type { SessionAuth } from "#context/session-context.js";+import type { AgentSessionContext } from "#execution/agent-sessions/context.js";+import type { WorkflowBodyInput } from "#execution/tools/workflow/body.js";+import type { WorkflowToolRunMessage } from "#execution/tools/workflow/messages.js";+import { startServeBody } from "#execution/tools/workflow/serve.js";+import type { AgentTurnResult } from "#shared/agent-turn-outcome.js";++/** The agent's side of the task: the messages it read and the turns it owes a reply. */+const agent = vi.hoisted(() => ({+ delivered: [] as WorkflowToolRunMessage[],+ read: [] as string[],+ turns: [] as Array<(payload: RuntimeActionResultHookPayload) => void>,+}));++vi.mock("#execution/workflow-registry.js", async () => {+ const { agentToolServeWorkflow } = await import("#runtime/subagents/workflow.js");+ return { readRegisteredWorkflow: () => agentToolServeWorkflow };+});+vi.mock("#execution/agent-sessions/steps.js", () => ({+ cancelAgentSessionTurnStep: async () => {},+ endAgentSessionsStep: async () => {},+ openAgentSessionStep: async ({ message }: { readonly message: string }) => {+ agent.read.push(message);+ return { kind: "local", name: "reviewer", nodeId: "reviewer", sessionId: "reviewer-session" };+ },+ sendAgentSessionMessageStep: async ({ message }: { readonly message: string }) => {+ agent.read.push(message);+ },+}));+vi.mock("#compiled/@workflow/core/index.js", () => ({+ // Each message's reply hook; the agent reports the turn that read it through it.+ createHook: () => {+ let report: (payload: RuntimeActionResultHookPayload) => void = () => {};+ const reported = new Promise<RuntimeActionResultHookPayload>((resolve) => {+ report = resolve;+ });+ agent.turns.push(report);+ return {+ [Symbol.asyncIterator]: () => ({+ next: async () => ({ done: false, value: await reported }),+ }),+ dispose: async () => {},+ token: `agent-turn-${String(agent.turns.length)}`,+ };+ },+}));++const agentContext = {+ agents: {},+ capabilities: { requestInput: false },+ parent: {+ callId: "call-1",+ rootSessionId: "session",+ sessionId: "session",+ turn: { id: "turn", sequence: 1 },+ },+} as AgentSessionContext;++const alice: SessionAuth = {+ current: { attributes: {}, authenticator: "test", principalId: "alice", principalType: "user" },+ initiator: null,+};++const input: WorkflowBodyInput = {+ agentContext,+ callId: "call-1",+ entry: { entryPoint: "serve", taskId: "reviewer-7k2m9q" },+ input: { message: "Review the release plan." },+ hookToken: "control",+ owner: {+ send: async (message) => {+ agent.delivered.push(message);+ },+ sent: 0,+ },+ runId: "run",+ session: { auth: alice, id: "session", turn: { id: "turn", sequence: 1 } },+ stepIndex: 0,+ toolName: "reviewer",+ workflowId: "workflow//eve//agentToolServeWorkflow",+};++function turnEnded(result: AgentTurnResult): RuntimeActionResultHookPayload {+ const usageDelta = { cacheReadTokens: 0, cacheWriteTokens: 0, inputTokens: 0, outputTokens: 0 };+ return {+ kind: "runtime-action-result",+ results: [+ {+ callId: "child-call",+ kind: "subagent-result",+ origin: "child",+ outcome: { kind: "parked", result, usageDelta },+ output: result.kind === "succeeded" ? result.output : "",+ subagentName: "reviewer",+ },+ ],+ };+}++/** Lets every pending step and hook delivery settle. */+function settle(): Promise<void> {+ return new Promise((resolve) => setImmediate(resolve));+}++function replies(): Array<{ readonly callId: string; readonly output: unknown }> {+ return agent.delivered.flatMap((message) =>+ message.kind === "reply"+ ? message.callIds.map((callId) => ({ callId, output: message.output }))+ : [],+ );+}++/** Alice asks the reviewer for a review; the reviewer has read her message. */+async function startReview(): Promise<ReturnType<typeof startServeBody>> {+ agent.delivered.length = 0;+ agent.read.length = 0;+ agent.turns.length = 0;+ const started = startServeBody(input);+ await settle();+ return started;+}++/**+ * Alice asks the reviewer for a review, and her next message reaches the task+ * `offset` microtasks after the reviewer's first turn ends. If `cancelled`,+ * she cancelled the review first, so the turn ends cancelled.+ */+async function sendAsTheTurnEnds(offset: number, { cancelled }: { readonly cancelled: boolean }) {+ const started = await startReview();+ if (cancelled) started.control.apply({ kind: "cancel", reason: "Alice cancelled the review." });+ agent.turns[0]?.(+ turnEnded(+ cancelled ? { kind: "cancelled" } : { kind: "succeeded", output: "The plan looks ready." },+ ),+ );+ for (let tick = 0; tick < offset; tick += 1) await Promise.resolve();+ const repliedFirst = replies().length > 0;+ started.control.apply({+ call: {+ agentContext,+ auth: alice,+ callId: "call-2",+ input: { message: "Check it against the Friday freeze." },+ sequence: 1,+ stepIndex: 1,+ turnId: "turn",+ },+ kind: "call",+ });+ await settle();+ agent.turns[1]?.(turnEnded({ kind: "succeeded", output: "The plan misses the Friday freeze." }));+ await settle();+ started.control.apply({ kind: "end", reason: "The session ended." });+ await started.outcome;+ return { read: [...agent.read], repliedFirst, replies: replies() };+}++it("forwards a message that reaches the task at any point as the agent's turn ends", async () => {+ // From joining the running turn to arriving after its reply, every arrival+ // point is covered: the sweep stops once the first reply precedes the+ // message. A cancelled turn ends through the same steps minus the reply, so+ // the same sweep covers it.+ for (let offset = 0; ; offset += 1) {+ const answered = await sendAsTheTurnEnds(offset, { cancelled: false });+ const cancelled = await sendAsTheTurnEnds(offset, { cancelled: true });++ for (const [firstTurn, run, firstCallReplies] of [+ ["answered", answered, 1],+ ["cancelled", cancelled, 0],+ ] as const) {+ const arrival = `${firstTurn} first turn, message ${String(offset)} microtasks after it ended`;+ expect(run.read, arrival).toEqual([+ "Review the release plan.",+ "Check it against the Friday freeze.",+ ]);+ // The turn that read the message answers it. The first call gets one+ // reply, unless cancelled: from its own turn or the one the message+ // joined or started.+ expect(+ run.replies.filter(({ callId }) => callId === "call-2"),+ arrival,+ ).toEqual([{ callId: "call-2", output: "The plan misses the Friday freeze." }]);+ expect(+ run.replies.filter(({ callId }) => callId === "call-1"),+ arrival,+ ).toHaveLength(firstCallReplies);+ }++ if (answered.repliedFirst) break;+ expect(offset, "the first reply never came before the message").toBeLessThan(100);+ }+});++it("fails the task with the reason the agent's turn failed", async () => {+ const started = await startReview();+ agent.turns[0]?.(+ turnEnded({+ error: {+ code: "SUBAGENT_EXECUTION_FAILED",+ message: "The model provider rejected the request.",+ },+ kind: "failed",+ }),+ );++ await expect(started.outcome).resolves.toMatchObject({+ error: { message: "The agent's turn failed: The model provider rejected the request." },+ status: "failed",+ });+});diff --git a/packages/eve/src/runtime/subagents/workflow.ts b/packages/eve/src/runtime/subagents/workflow.tsindex 653706741..759039853 100644--- a/packages/eve/src/runtime/subagents/workflow.ts+++ b/packages/eve/src/runtime/subagents/workflow.ts@@ -1,32 +1,107 @@-// Agent tools continue children by `agentId` through the owner's handle store,-// which `ctx.agent` sessions never touch. This is the only internal import rule-// 42 permits here.-import { invokeAgent } from "#execution/tools/subagent/invoke-agent.js";--type JsonValue = null | boolean | number | string | JsonValue[] | JsonObject;-interface JsonObject {- readonly [key: string]: JsonValue;-}+import type {+ AgentMessageResult,+ AgentSession,+ WorkflowServeCall,+ WorkflowServeContext,+ WorkflowServeReceive,+} from "#public/tools/index.js";-export interface SubagentWorkflowInput {- readonly agentId?: string | null;+/** The model's input to an agent tool; eve adds the optional `taskId`. */+export interface AgentToolInput {readonly message: string;- readonly outputSchema?: Record<string, unknown>;}-/** Shared execute body for local, remote, dynamic, and self-agent tools. */-export async function subagentToolExecuteWorkflow(- input: SubagentWorkflowInput,- ctx: Parameters<typeof invokeAgent>[0],-): Promise<unknown> {+type AgentToolCall = WorkflowServeCall<AgentToolInput>;++type AgentToolReceive = WorkflowServeReceive<AgentToolInput>;++/** One turn of the agent's session, and the signal of the calls it answers. */+interface AgentTurn {+ readonly result: Promise<AgentMessageResult>;+ /** Aborts when the task is cancelled, which cancels the turn. */+ readonly signal: AbortSignal;+}++type AgentTurnEvent =+ | { readonly kind: "call"; readonly call: AgentToolCall }+ | { readonly kind: "result"; readonly result: AgentMessageResult };++/**+ * The `serve` body of every agent tool: local, remote, dynamic, and the+ * `agent` copy of the root. Each task talks to one session with the agent. A+ * call that arrives while the agent works joins its turn, and the turn's final+ * response settles every call it answered.+ */+export async function agentToolServeWorkflow(+ receive: AgentToolReceive,+ ctx: WorkflowServeContext<string>,+): Promise<never> {"use workflow";- const invocation = {- ...(typeof input.agentId === "string" && input.agentId.trim() !== ""- ? { agentId: input.agentId }- : {}),- message: input.message,- outputSchema: input.outputSchema as JsonObject | undefined,- target: ctx.toolName,- };- return await invokeAgent(ctx, invocation, { invocationId: ctx.callId });++ const agent = ctx.agent(ctx.toolName);+ let turn = sendToAgent(agent, await receive());+ let next = receive();+ for (;;) {+ const event = await nextCallOrResult(next, turn);+ if (event.kind === "call") {+ turn = await forwardCall(agent, turn, event.call);+ next = receive();+ continue;+ }+ // A cancel already settled the turn's calls, and the task stays available.+ if (!turn.signal.aborted) {+ if (event.result.status === "failed") {+ throw new Error(+ `The agent's turn failed: ${event.result.error?.message ?? "no reason given"}`,+ );+ }+ // `next` can take a call after the result wins the race, and the reply+ // would settle that call unread. `receive()` returns `next` only while+ // it's pending, so another promise means the agent reads that call+ // first. Nothing may await between this check and the reply. The+ // session's end aborts the turn, so `following` can't reject here.+ const following = receive();+ if (following !== next) {+ turn = sendToAgent(agent, await next);+ next = following;+ continue;+ }+ ctx.reply(event.result.message ?? "");+ }+ turn = sendToAgent(agent, await next);+ next = receive();+ }+}++/** A cancel aborts the call's `abortSignal`, which cancels the agent's turn. */+function sendToAgent(agent: AgentSession, call: AgentToolCall): AgentTurn {+ const result = agent+ .send(call.input.message, { signal: call.abortSignal })+ .then((response) => response.result());+ return { result, signal: call.abortSignal };+}++/** `next` may take a call even when the turn's result wins, so the loop keeps it until it's read. */+async function nextCallOrResult(+ next: Promise<AgentToolCall>,+ turn: AgentTurn,+): Promise<AgentTurnEvent> {+ return await Promise.race([+ turn.result.then((result) => ({ kind: "result", result }) as const),+ next.then((call) => ({ call, kind: "call" }) as const),+ ]);+}++/**+ * The message joins the running turn, or starts the next one if it just+ * ended. A cancelled turn is left to end first, so the message starts a turn+ * that answers it instead of joining one whose calls were already settled.+ */+async function forwardCall(+ agent: AgentSession,+ turn: AgentTurn,+ call: AgentToolCall,+): Promise<AgentTurn> {+ if (turn.signal.aborted) await turn.result.catch(() => undefined);+ return sendToAgent(agent, call);}diff --git a/packages/eve/src/runtime/tools/registry.ts b/packages/eve/src/runtime/tools/registry.tsindex ad1abd815..d959ab6aa 100644--- a/packages/eve/src/runtime/tools/registry.ts+++ b/packages/eve/src/runtime/tools/registry.ts@@ -3,8 +3,6 @@ import type { PreparedRuntimeAuthoredTool } from "#runtime/sessions/turn.js";import type { ResolvedToolDefinition } from "#runtime/types.js";import { serializeInputSchema, serializeOutputSchema } from "#tools/schema.js";import { AGENT_TOOL_NAME } from "#tools/framework/agent-contract.js";-import { ROOT_RUNTIME_AGENT_NODE_ID } from "#runtime/graph.js";-import { subagentToolExecuteWorkflowReference } from "#runtime/subagents/workflow-reference.js";import type {CompiledToolBehavior,PreparedToolBehavior,@@ -86,18 +84,9 @@ async function createPreparedRuntimeTool(const isSelfAgent =definition.behavior?.handling?.kind === "dispatch" &&definition.behavior.handling.action === "self-agent";- const workflowId = isSelfAgent- ? subagentToolExecuteWorkflowReference.workflowId- : definition.behavior?.handling?.kind === "workflow-tool"- ? definition.behavior.handling.workflowId- : undefined;return {availableInSubagents: definition.availableInSubagents,- behavior: prepareToolBehavior(- definition.behavior,- nodeId,- isSelfAgent ? subagentToolExecuteWorkflowReference.workflowId : undefined,- ),+ behavior: prepareToolBehavior(definition.behavior, nodeId),description: definition.description,inputSchema: serializeInputSchema(definition.inputSchema),kind: "authored-tool",@@ -107,33 +96,17 @@ async function createPreparedRuntimeTool(outputSchema: serializeOutputSchema(definition.outputSchema),rootOnly: isSelfAgent || undefined,sourceId: definition.sourceId,- task:- workflowId === undefined- ? undefined- : isSelfAgent- ? {- nodeId: ROOT_RUNTIME_AGENT_NODE_ID,-- workflowId,- }- : { workflowId },};}function prepareToolBehavior(behavior: CompiledToolBehavior | undefined,nodeId: string | undefined,- workflowIdOverride?: string,): PreparedToolBehavior | undefined {if (behavior === undefined) return undefined;let handling: PreparedToolHandling | undefined;- if (workflowIdOverride !== undefined && nodeId !== undefined) {- handling = {- kind: "dispatch",- target: { kind: "self-agent-call", nodeId, subagentName: AGENT_TOOL_NAME },- };- } else if (behavior.handling?.kind === "dispatch") {+ if (behavior.handling?.kind === "dispatch") {if (nodeId === undefined) {throw new Error("The self-agent tool requires a concrete runtime node id.");}@@ -145,8 +118,9 @@ function prepareToolBehavior(handling = {kind: "dispatch",target: {+ entryPoint: behavior.handling.entryPoint,kind: "workflow-tool-call",- workflowId: workflowIdOverride ?? behavior.handling.workflowId,+ workflowId: behavior.handling.workflowId,},};} else {diff --git a/packages/eve/src/shared/action-types.ts b/packages/eve/src/shared/action-types.tsindex 112a24a7f..6514599e5 100644--- a/packages/eve/src/shared/action-types.ts+++ b/packages/eve/src/shared/action-types.ts@@ -113,9 +113,34 @@ export const runtimeRemoteAgentDispatchRequestSchema = z}).strict();+/**+ * The entry point a new run invokes: `execute`, which the turn waits on, or+ * `task` or `serve`, with the id of the task the call's model step committed.+ */+export type WorkflowToolRunEntry = Exclude<+ WorkflowToolCallEntry,+ { readonly entryPoint: "receive" }+>;++/**+ * How a deferred call enters its tool's workflow: through the entry point of+ * a new run, or, for a call with `taskId` to a `serve` tool, through the+ * `receive()` of the running task that id names.+ */+export type WorkflowToolCallEntry = z.infer<typeof workflowToolCallEntrySchema>;++const workflowToolCallEntrySchema = z.discriminatedUnion("entryPoint", [+ z.object({ entryPoint: z.literal("execute") }).strict(),+ z.object({ entryPoint: z.literal("task"), taskId: z.string() }).strict(),+ z.object({ entryPoint: z.literal("serve"), taskId: z.string() }).strict(),+ z.object({ entryPoint: z.literal("receive"), taskId: z.string() }).strict(),+]);+/*** One workflow task requested by the harness. The turn owner starts the- * durable run named by `workflowId` and waits for its result.+ * durable run named by `workflowId`, or sends the call to the running task it+ * names; the turn waits for an `execute` call's result, while a call to a task+ * is answered with its receipt.** Tasks are the coordination contract for authored workflow tools and* subagents. They are intentionally separate from `RuntimeActionRequest`.@@ -125,10 +150,10 @@ export type RuntimeWorkflowTaskRequest = z.infer<typeof runtimeWorkflowTaskRequeexport const runtimeWorkflowTaskRequestSchema = z.object({callId: z.string(),+ entry: workflowToolCallEntrySchema,executeInput: jsonValueSchema.optional(),input: jsonObjectSchema,kind: z.literal("workflow-task"),- nodeId: z.string().optional(),toolName: z.string(),workflowId: z.string(),})@@ -239,9 +264,8 @@ export interface RuntimeSubagentChildResult {/*** Subagent failure synthesized on the parent side when no child produced a- * result: dispatch rejections, start failures, and agentId-continuation- * delivery errors. Always an error. Enters the harness only through the- * trusted step-result path, never through the shared callback inbox.+ * result. Always an error. Enters the harness only through the trusted+ * step-result path, never through the shared callback inbox.*/export type RuntimeSubagentDispatchFailure = z.infer<typeof runtimeSubagentDispatchFailureSchema>;diff --git a/packages/eve/src/subagents/agent-handle-errors.test.ts b/packages/eve/src/subagents/agent-handle-errors.test.tsdeleted file mode 100644index a32957773..000000000--- a/packages/eve/src/subagents/agent-handle-errors.test.ts+++ /dev/null@@ -1,18 +0,0 @@-import { describe, expect, it } from "vitest";--import { formatAgentBusyMessage } from "#subagents/agent-handle-errors.js";--describe("formatAgentBusyMessage", () => {- it.each([- ["task_123", 'Agent "research" with id "agent-1" is still working on task "task_123".'],- [- "workflow-run-1",- 'Agent "research" with id "agent-1" is still working on another invocation.',- ],- [undefined, 'Agent "research" with id "agent-1" is still working on another task.'],- ])("describes owner %s", (ownerId, expected) => {- expect(formatAgentBusyMessage({ agentId: "agent-1", agentName: "research", ownerId })).toBe(- expected,- );- });-});diff --git a/packages/eve/src/subagents/agent-handle-errors.ts b/packages/eve/src/subagents/agent-handle-errors.tsdeleted file mode 100644index 475fd625a..000000000--- a/packages/eve/src/subagents/agent-handle-errors.ts+++ /dev/null@@ -1,38 +0,0 @@-/**- * Error codes carried by delegated agent (`subagent-result`) failures.- *- * Every producer that mints a code imports from this module, so the set- * stays closed. Codes are diagnostic only: child lifecycle is owned by the- * agent handle store and is never inferred from an error code.- */--/** Error code for an agent id invoked through the wrong subagent tool. */-export const AGENT_MISMATCH = "AGENT_MISMATCH";--/** Error code for a registered agent that cannot be reached. */-export const AGENT_UNREACHABLE = "AGENT_UNREACHABLE";--/** Error code for an agent that is starting or already running a turn. */-export const AGENT_BUSY = "AGENT_BUSY";--/** Describes the owner blocking a continuation without exposing workflow run ids. */-export function formatAgentBusyMessage(input: {- readonly agentId: string;- readonly agentName: string;- readonly ownerId?: string;-}): string {- const agent = `Agent "${input.agentName}" with id "${input.agentId}" is still working on`;- if (input.ownerId?.startsWith("task_")) {- return `${agent} task "${input.ownerId}".`;- }- return `${agent} ${input.ownerId === undefined ? "another task" : "another invocation"}.`;-}--/** Error code for a local subagent that failed to start. */-export const SUBAGENT_START_FAILED = "SUBAGENT_START_FAILED";--/** Error code for a delegated subagent whose execution threw. */-export const SUBAGENT_EXECUTION_FAILED = "SUBAGENT_EXECUTION_FAILED";--/** Error code for a remote agent session that failed to start. */-export const REMOTE_AGENT_START_FAILED = "REMOTE_AGENT_START_FAILED";diff --git a/packages/eve/src/subagents/continuation-bundle.ts b/packages/eve/src/subagents/continuation-bundle.tsdeleted file mode 100644index 76c72082b..000000000--- a/packages/eve/src/subagents/continuation-bundle.ts+++ /dev/null@@ -1,43 +0,0 @@-import type { RuntimeAgentHandleAction } from "#subagents/handle-dispatch.js";-import { resolveRemoteAgentForAction } from "#subagents/remote-dispatch.js";-import type { CompiledBundle } from "#runtime/sessions/runtime-context-keys.js";-import type { getDynamicSubagentSelection } from "#context/dynamic-subagent-lifecycle.js";--type DynamicRemoteAgentConfig = NonNullable<- Extract<- ReturnType<typeof getDynamicSubagentSelection>,- { readonly kind: "remote" }- >["remoteAgent"]->;--/** Overlays current dynamic credentials without replacing stored delivery coordinates. */-export function createAgentContinuationBundle(input: {- readonly action: RuntimeAgentHandleAction;- readonly bundle: CompiledBundle;- readonly dynamicRemoteAgent?: DynamicRemoteAgentConfig;-}): CompiledBundle {- const { action, dynamicRemoteAgent } = input;- if (action.kind !== "remote-agent-call" || dynamicRemoteAgent === undefined) {- return input.bundle;- }-- const registry = input.bundle.subagentRegistry.subagentsByNodeId;- const subagentsByNodeId = Object.assign(new Map(registry), {- get: (nodeId: string) =>- nodeId === action.nodeId- ? {- definition: resolveRemoteAgentForAction({- dynamicRemoteAgent,- nodeId,- registry,- remoteAgentName: action.remoteAgentName,- }),- }- : registry.get(nodeId),- });-- return {- ...input.bundle,- subagentRegistry: { ...input.bundle.subagentRegistry, subagentsByNodeId },- };-}diff --git a/packages/eve/src/subagents/handle-dispatch.test.ts b/packages/eve/src/subagents/handle-dispatch.test.tsdeleted file mode 100644index f9d359a42..000000000--- a/packages/eve/src/subagents/handle-dispatch.test.ts+++ /dev/null@@ -1,73 +0,0 @@-import { beforeEach, describe, expect, it, vi } from "vitest";-import { createWorkflowRuntime } from "#execution/workflow-runtime.js";-import { dispatchToClaimedAgentAddress } from "./handle-dispatch.js";-import { captureLogRecords } from "#internal/testing/log-records.js";--vi.mock("#execution/workflow-runtime.js", () => ({ createWorkflowRuntime: vi.fn() }));--describe("claimed child delivery", () => {- const dispatchSession = vi.fn();- const input = {- action: {- callId: "update-call",- description: "Research",- input: { message: "Use Alice's updated requirements" },- kind: "subagent-call",- name: "research",- nodeId: "subagents/research",- subagentName: "research",- },- auth: null,- bundle: { compiledArtifactsSource: {} } as never,- currentSession: {- agent: { dynamicModel: true, system: "", tools: [] },- compaction: { recentWindowSize: 5, threshold: 10_000 },- continuationToken: "parent-token",- history: [],- sessionId: "parent",- },- handle: {- address: { kind: "agent/local", sessionId: "child", continuationToken: "child-token" },- identity: { id: "agent", name: "research", nodeId: "subagents/research" },- operationId: "original-operation",- callId: "original-call",- ownerId: "original-task",- phase: "claimed",- },- parentToken: "reply-token",- } satisfies Parameters<typeof dispatchToClaimedAgentAddress>[0];-- beforeEach(() => {- vi.clearAllMocks();- dispatchSession.mockResolvedValue({ status: "accepted" });- vi.mocked(createWorkflowRuntime).mockReturnValue({ dispatchSession } as never);- });-- it("supplies a caller when continuing an idle child", async () => {- await dispatchToClaimedAgentAddress(input);- expect(dispatchSession).toHaveBeenCalledWith(- expect.objectContaining({- command: expect.objectContaining({- caller: {- callId: "update-call",- replyTo: { kind: "hook", token: "reply-token" },- subagentName: "research",- },- }),- }),- );- });-- it("reports a missing child without starting a replacement", async () => {- const logs = captureLogRecords();- dispatchSession.mockResolvedValueOnce({ status: "session_not_active" });- await expect(dispatchToClaimedAgentAddress(input)).resolves.toMatchObject({- kind: "error",- deliveryPermanent: true,- });- expect(dispatchSession).toHaveBeenCalledTimes(1);- expect(logs.records).toContainEqual(- expect.objectContaining({ level: "error", message: "task agent delivery failed" }),- );- });-});diff --git a/packages/eve/src/subagents/handle-dispatch.ts b/packages/eve/src/subagents/handle-dispatch.tsdeleted file mode 100644index 5255860cd..000000000--- a/packages/eve/src/subagents/handle-dispatch.ts+++ /dev/null@@ -1,256 +0,0 @@-/** Continuation delivery for agent sessions claimed by one owner. */--import type { ActivityObserverConfig, SessionAuthContext } from "#channel/types.js";-import { AGENT_UNREACHABLE } from "#subagents/agent-handle-errors.js";-import type { AgentAddress, AgentIdentity } from "#subagents/handles/store.js";-import type {- RuntimeAgentDispatchRequest,- RuntimeRemoteAgentDispatchRequest,- RuntimeSubagentDispatchRequest,- RuntimeSubagentDispatchFailure,-} from "#shared/action-types.js";-import type { CompiledBundle } from "#runtime/sessions/runtime-context-keys.js";-import {- continueRemoteAgentSession,- isAmbiguousRemoteAgentContinueError,- isRetryableRemoteAgentContinueError,- resolveRemoteAgentForAction,-} from "#subagents/remote-dispatch.js";-import { isRuntimeNoActiveSessionError } from "#execution/runtime-errors.js";-import type { hydrateDurableSession } from "#execution/session.js";-import { normalizeRequestedOutputSchema } from "#subagents/invocation.js";-import { createWorkflowRuntime } from "#execution/workflow-runtime.js";-import { createWorkflowCallbackUrl } from "#execution/workflow-callback-url.js";-import { createLogger, logError } from "#internal/logging.js";-import { createEveCallbackRoutePath } from "#protocol/routes.js";-import { err, ok, type Result } from "#shared/result.js";-import type { TaskOwnedAgentHandle } from "#subagents/handles/store.js";--const log = createLogger("execution.agent-handle-dispatch");--/** Agent-task requests that may address an agent handle via `agentId`. */-export type RuntimeAgentHandleAction =- | RuntimeRemoteAgentDispatchRequest- | RuntimeSubagentDispatchRequest;--/** Narrows an action to the kinds that may carry an `agentId` continuation. */-export function isAgentHandleAction(- action: RuntimeAgentDispatchRequest,-): action is RuntimeAgentHandleAction {- return action.kind === "subagent-call" || action.kind === "remote-agent-call";-}--/** Hydrated parent session snapshot threaded through dispatch. */-export type RuntimeSession = ReturnType<typeof hydrateDurableSession>;--/**- * Outcome of dispatching one planned agent task: an adopted child ready for- * the `subagent.called` emission tail, or a per-task error result.- * Either way the (possibly updated) session snapshot rides along.- *- * `address` is the same confirmed {@link AgentAddress} recorded on the- * child's running handle; consumers project it into wire shapes (e.g. the- * flat `childSessionId` / `remote` fields of `subagent.called`) at the- * emission site instead of this type re-encoding them.- */-export type DispatchOutcome =- | {- readonly address: AgentAddress;- readonly callId: string;- readonly kind: "called";- readonly name: string;- readonly session: RuntimeSession;- readonly toolName: string;- }- | {- readonly deliveryAmbiguous?: boolean;- readonly deliveryPermanent?: boolean;- readonly kind: "error";- readonly result: RuntimeSubagentDispatchFailure;- readonly session: RuntimeSession;- };--/** Delivers a continuation after the session handle store atomically claimed it for one owner. */-export async function dispatchToClaimedAgentAddress(input: {- readonly activityObserver?: ActivityObserverConfig;- readonly action: RuntimeAgentHandleAction;- readonly auth: SessionAuthContext | null;- readonly bundle: CompiledBundle;- readonly currentSession: RuntimeSession;- readonly handle: Extract<TaskOwnedAgentHandle, { phase: "claimed" }>;- /** Hook token the callee's turn result is delivered to. */- readonly parentToken: string;-}): Promise<DispatchOutcome> {- const { action, handle } = input;- const agentId = handle.identity.id;-- const delivery = await deliverToAgentAddress({- activityObserver: input.activityObserver,- action,- address: handle.address,- auth: input.auth,- bundle: input.bundle,- identity: handle.identity,- parentToken: input.parentToken,- });- if (!delivery.ok) {- const { cause, permanent } = delivery.error;- logError(log, "task agent delivery failed", cause, {- agentId,- callId: action.callId,- nodeId: handle.identity.nodeId,- permanent,- subagentName: handle.identity.name,- });- return {- deliveryAmbiguous: delivery.error.deliveryAmbiguous,- deliveryPermanent: permanent,- kind: "error",- result: createAgentErrorResult({- action,- code: AGENT_UNREACHABLE,- message: permanent- ? `Agent "${handle.identity.name}" with id "${agentId}" is no longer reachable.`- : `Agent "${handle.identity.name}" with id "${agentId}" is temporarily unreachable. Try again.`,- }),- session: input.currentSession,- };- }-- return {- address: handle.address,- callId: action.callId,- kind: "called",- name: action.name,- session: input.currentSession,- toolName: handle.identity.name,- };-}--/**- * Attempts the continuation delivery once and classifies the failure.- *- * Transient failures are never retried automatically: the callee may have- * accepted the message even though the response was lost, so a re-send could- * deliver the same turn twice. The caller surfaces a retryable- * AGENT_UNREACHABLE instead and the model decides whether to try again.- * Throwing is equally unsafe — a durable-step retry would re-dispatch- * already-started siblings.- */-async function deliverToAgentAddress(input: {- readonly activityObserver?: ActivityObserverConfig;- readonly action: RuntimeAgentHandleAction;- readonly address: AgentAddress;- readonly auth: SessionAuthContext | null;- readonly bundle: CompiledBundle;- readonly identity: AgentIdentity;- readonly parentToken: string;-}): Promise<- Result<- void,- { readonly cause: unknown; readonly deliveryAmbiguous: boolean; readonly permanent: boolean }- >-> {- const { action, address, bundle, identity, parentToken } = input;-- if (address.kind === "agent/remote") {- let resolvedRemote;- try {- resolvedRemote = resolveRemoteAgentForAction({- nodeId: identity.nodeId,- remoteAgentName: identity.name,- registry: bundle.subagentRegistry.subagentsByNodeId,- });- } catch (error) {- // The agent's node is gone from the compiled bundle; no retry can- // reach this handle again.- return err({ cause: error, deliveryAmbiguous: false, permanent: true });- }- try {- await continueRemoteAgentSession({- activityObserver: input.activityObserver,- auth: input.auth,- callback: {- callId: action.callId,- subagentName: identity.name,- token: parentToken,- url: createWorkflowCallbackUrl(- address.callbackBaseUrl,- createEveCallbackRoutePath(parentToken),- ),- },- message: readSubagentMessage(action),- outputSchema: normalizeRequestedOutputSchema(action.input.outputSchema),- remote: { ...resolvedRemote, url: address.url },- sessionId: address.sessionId,- });- } catch (error) {- return err({- cause: error,- deliveryAmbiguous: isAmbiguousRemoteAgentContinueError(error),- permanent: !isRetryableRemoteAgentContinueError(error),- });- }- return ok(undefined);- }-- const childRuntime = createWorkflowRuntime({- compiledArtifactsSource: bundle.compiledArtifactsSource,- nodeId: identity.nodeId,- });- try {- const result = await childRuntime.dispatchSession({- command: {- auth: input.auth,- caller: {- activityObserver: input.activityObserver,- callId: action.callId,- replyTo: { kind: "hook", token: parentToken },- subagentName: identity.name,- },- kind: "send",- payload: {- message: readSubagentMessage(action),- outputSchema: normalizeRequestedOutputSchema(action.input.outputSchema),- },- },- sessionId: address.sessionId,- });- if (result.status !== "accepted") {- return err({- cause: new Error(`Agent session "${address.sessionId}" is not available.`),- deliveryAmbiguous: false,- permanent: result.retryable !== true,- });- }- } catch (error) {- const permanent = isRuntimeNoActiveSessionError(error);- return err({ cause: error, deliveryAmbiguous: !permanent, permanent });- }- return ok(undefined);-}--export function createAgentErrorResult(input: {- readonly action: RuntimeAgentHandleAction;- readonly code: string;- readonly message: string;-}): RuntimeSubagentDispatchFailure {- return {- callId: input.action.callId,- isError: true,- kind: "subagent-result",- origin: "dispatch",- output: {- code: input.code,- message: input.message,- },- subagentName:- input.action.kind === "remote-agent-call"- ? input.action.remoteAgentName- : input.action.subagentName,- };-}--function readSubagentMessage(action: RuntimeAgentHandleAction): string {- return typeof action.input.message === "string" ? action.input.message : "";-}diff --git a/packages/eve/src/subagents/handles/operation-id.ts b/packages/eve/src/subagents/handles/operation-id.tsdeleted file mode 100644index 98f91119e..000000000--- a/packages/eve/src/subagents/handles/operation-id.ts+++ /dev/null@@ -1,21 +0,0 @@-import { createHash } from "node:crypto";--/**- * Derives the stable operation id for one dispatch. All three inputs are- * parent-controlled, so the id exists before any child does and replaying- * the same call produces the same operation.- *- * Lives apart from the handle store because it needs `node:crypto`: the- * store module is bundled into the session owner body (which rejects- * Node.js builtins), while operation ids are only ever minted inside- * dispatch steps.- */-export function deriveAgentOperationId(input: {- readonly callId: string;- readonly parentSessionId: string;- readonly parentTurnId: string;-}): string {- return createHash("sha256")- .update(`${input.parentSessionId}\0${input.parentTurnId}\0${input.callId}`)- .digest("hex");-}diff --git a/packages/eve/src/subagents/handles/prompt.test.ts b/packages/eve/src/subagents/handles/prompt.test.tsdeleted file mode 100644index c4134450c..000000000--- a/packages/eve/src/subagents/handles/prompt.test.ts+++ /dev/null@@ -1,130 +0,0 @@-import { describe, expect, it } from "vitest";--import {- projectParkedAgentHandles,- renderAgentsSnippet,- resolveAgentsAnnouncement,-} from "#subagents/handles/prompt.js";-import type { AgentHandle } from "#subagents/handles/store.js";--const identity = {- id: "ag_research:abcdef123456",- name: "research",- nodeId: "node_research",-} as const;--const runningHandle: AgentHandle = {- address: {- continuationToken: "CONTINUATION_TOKEN_SENTINEL",- kind: "agent/local",- sessionId: "SESSION_ID_SENTINEL_123456789",- },- identity,- operation: {- callId: "call_1",- id: "op_1",- kind: "start",- parentTurnId: "turn_1",- },- phase: "running",-};--const parkedRemoteHandle: AgentHandle = {- address: {- callbackBaseUrl: "https://CALLBACK_SENTINEL.invalid",- kind: "agent/remote",- sessionId: "SESSION_ID_SENTINEL_123456789",- url: "https://URL_SENTINEL.invalid",- },- identity,- lastStatus: "initial findings",- phase: "parked",-};--describe("projectParkedAgentHandles / renderAgentsSnippet", () => {- it("projects and renders only idle handles", () => {- const runningStore = { handles: [runningHandle] };- expect(projectParkedAgentHandles(runningStore)).toEqual([]);- expect(renderAgentsSnippet(runningStore)).toBe("[Agents]\n<agents>\n</agents>");-- const parkedStore = { handles: [parkedRemoteHandle] };- expect(projectParkedAgentHandles(parkedStore)).toEqual([parkedRemoteHandle]);- const snippet = renderAgentsSnippet(parkedStore);- expect(snippet.startsWith("[Agents]\n<agents>")).toBe(true);- expect(snippet).toContain(- `<agent id="${identity.id}" name="research">initial findings</agent>`,- );-- const availableHandle = {- address: runningHandle.address,- identity,- phase: "available" as const,- };- expect(renderAgentsSnippet({ handles: [availableHandle] })).toContain(- `<agent id="${identity.id}" name="research">(available)</agent>`,- );- });-- it("omits private delivery coordinates and renders a placeholder for empty statuses", () => {- const snippet = renderAgentsSnippet({- handles: [{ ...parkedRemoteHandle, lastStatus: "" }],- });-- expect(snippet).toContain("(no status)");- expect(snippet).not.toContain(parkedRemoteHandle.address.sessionId);- expect(snippet).not.toContain("URL_SENTINEL");- expect(snippet).not.toContain("CALLBACK_SENTINEL");- });-});--describe("resolveAgentsAnnouncement", () => {- it("announces a changed listing without replacing earlier conversation content", () => {- const messages = [{ content: "Earlier response", role: "assistant" as const }];- const content = resolveAgentsAnnouncement({- messages,- store: { handles: [parkedRemoteHandle] },- });-- expect(content).toContain(`<agent id="${identity.id}"`);- expect(messages).toEqual([{ content: "Earlier response", role: "assistant" }]);- });-- it("does not repeat an unchanged listing already announced as user content", () => {- const content = renderAgentsSnippet({ handles: [parkedRemoteHandle] });-- expect(- resolveAgentsAnnouncement({- messages: [{ content, role: "user" }],- store: { handles: [parkedRemoteHandle] },- }),- ).toBeUndefined();- });-- it("announces an empty listing after the last parked handle disappears", () => {- const previous = renderAgentsSnippet({ handles: [parkedRemoteHandle] });-- expect(- resolveAgentsAnnouncement({- messages: [{ content: previous, role: "user" }],- store: { handles: [runningHandle] },- }),- ).toBe("[Agents]\n<agents>\n</agents>");- });-- it("skips empty scaffolding when no listing was previously announced", () => {- expect(resolveAgentsAnnouncement({ messages: [], store: undefined })).toBeUndefined();- });-- it("ignores an assistant message that happens to start with the label", () => {- const content = renderAgentsSnippet({ handles: [parkedRemoteHandle] });-- // Only framework-injected user-role announcements gate re-announcement;- // model output echoing the label must not suppress a fresh listing.- expect(- resolveAgentsAnnouncement({- messages: [{ content, role: "assistant" }],- store: { handles: [parkedRemoteHandle] },- }),- ).toBe(content);- });-});diff --git a/packages/eve/src/subagents/handles/prompt.ts b/packages/eve/src/subagents/handles/prompt.tsdeleted file mode 100644index 9232d912f..000000000--- a/packages/eve/src/subagents/handles/prompt.ts+++ /dev/null@@ -1,78 +0,0 @@-import type { ModelMessage } from "ai";--import type { AgentHandle, AgentHandleStore } from "#subagents/handles/store.js";--/**- * Label prefixing every framework-injected agents announcement. Mock model- * adapters use it to treat announcements as transparent scaffolding rather- * than authored user input.- */-export const AGENTS_SNIPPET_LABEL = "[Agents]";--/** Returns the resumable handles: the only phases the model may continue. */-export function projectParkedAgentHandles(- store: AgentHandleStore,-): readonly Extract<AgentHandle, { phase: "available" | "parked" }>[] {- return store.handles.filter(- (handle): handle is Extract<AgentHandle, { phase: "available" | "parked" }> =>- handle.phase === "available" || handle.phase === "parked",- );-}--/**- * Renders the model-visible agent listing. Only idle handles appear:- * starting and running children cannot accept a continuation, and private- * delivery coordinates never render.- */-export function renderAgentsSnippet(store: AgentHandleStore): string {- const agents = projectParkedAgentHandles(store).map((handle) => {- const status = handle.phase === "parked" ? handle.lastStatus : "(available)";- return `<agent id="${escapeXml(handle.identity.id)}" name="${escapeXml(handle.identity.name)}">${escapeXml(status === "" ? "(no status)" : status)}</agent>`;- });- return [AGENTS_SNIPPET_LABEL, "<agents>", ...agents, "</agents>"].join("\n");-}--/**- * Returns an append-only announcement when the visible handle listing- * changed since the last one in history, or `undefined` when it is- * unchanged.- *- * The announcement is framework-injected `user`-role conversation content- * (the pattern system-reminder notes use in Claude Code and OpenCode), not- * an `assistant` or `system` entry:- *- * - `assistant` breaks providers that reject assistant-final requests- * (a settle resume carries no new user input, so the announcement would- * end the request) and invites the model to imitate the listing.- * - `system` busts the provider prompt cache for the entire conversation- * every time a child settles; append-only history preserves the prefix.- *- * The static agent-messaging prompt block declares the `[Agents]` label as- * eve-injected so the model does not attribute it to the user.- */-export function resolveAgentsAnnouncement(input: {- readonly messages: readonly ModelMessage[];- readonly store: AgentHandleStore | undefined;-}): string | undefined {- const latest = input.messages.findLast(- (message) =>- message.role === "user" &&- typeof message.content === "string" &&- message.content.startsWith(AGENTS_SNIPPET_LABEL),- );- const store = input.store ?? { handles: [] };- if (latest === undefined && projectParkedAgentHandles(store).length === 0) {- return undefined;- }-- const rendered = renderAgentsSnippet(store);- return latest?.content === rendered ? undefined : rendered;-}--function escapeXml(value: string): string {- return value- .replaceAll("&", "&")- .replaceAll('"', """)- .replaceAll("<", "<")- .replaceAll(">", ">");-}diff --git a/packages/eve/src/subagents/handles/query.ts b/packages/eve/src/subagents/handles/query.tsdeleted file mode 100644index 0c0726ebf..000000000--- a/packages/eve/src/subagents/handles/query.ts+++ /dev/null@@ -1,83 +0,0 @@-import type { RuntimeActionResult, RuntimeSubagentChildResult } from "#shared/action-types.js";-import { AGENT_HANDLES_STATE_KEY } from "#subagents/handles/state-key.js";-import type { AgentHandle, TurnOwnedAgentHandle } from "#subagents/handles/store.js";-import type { SessionStateMap } from "#harness/types.js";--/** A handle with one outstanding operation and a confirmed child address. */-export type RunningAgentHandle = Extract<TurnOwnedAgentHandle, { phase: "running" }>;--/**- * Schema-free read of the agent handles from session state.- *- * Trust boundary: every source store was validated by a handle transition.- * Owner-side reads trust that invariant instead of re-validating, so the- * session owner bundle stays free of compiled zod.- */-function readAgentHandles(state: SessionStateMap | undefined): readonly AgentHandle[] {- const raw = state?.[AGENT_HANDLES_STATE_KEY];- if (raw === undefined) {- return [];- }- const handles = (raw as { handles?: unknown }).handles;- return Array.isArray(handles) ? (handles as readonly AgentHandle[]) : [];-}--/**- * Finds the running agent handle a child-produced result must settle: the- * handle whose recorded operation carries the result's callId.- *- * Binding is by callId alone. Possession of the parent's callback token is- * the authorization to settle; the handle's recorded address is used for- * outbound delivery (continuation, cancellation), never as an inbound- * identity check. Under the accepted at-least-once dispatch window a- * replay-orphaned duplicate child holds the same token and callId and may- * settle the call in place of the owned child — an accepted trade-off,- * since both children computed the same input.- */-export function findRunningAgentHandle(- state: SessionStateMap | undefined,- input: { readonly callId: string },-): RunningAgentHandle | undefined {- const handles = readAgentHandles(state);- return handles.find(- (handle): handle is RunningAgentHandle =>- handle.phase === "running" && handle.operation.callId === input.callId,- );-}--/**- * A subagent result may settle a call only when a running handle records- * its callId: a late or duplicate result for an already-settled call finds- * no running handle and is dropped.- *- * `dispatch`-origin failures pass unconditionally: the parent synthesizes- * them for calls whose child never started, and they reach the harness only- * through the trusted step-result path. Untrusted channels must use- * {@link isInboxSubagentResultFromRunningHandle} instead.- */-export function isResultBoundToRunningHandle(- state: SessionStateMap | undefined,- result: RuntimeActionResult,-): boolean {- if (result.kind !== "subagent-result") {- return true;- }- if (result.origin === "dispatch") {- return true;- }- return findRunningAgentHandle(state, { callId: result.callId }) !== undefined;-}--/**- * Strict variant of {@link isResultBoundToRunningHandle} for results arriving- * over the shared turn inbox (child notifications and remote callbacks).- * An inbox result must bind to a running handle by callId; one with no- * matching running handle — including one for a callId whose dispatch- * already failed — must not overwrite the dispatch-produced error result.- */-export function isInboxSubagentResultFromRunningHandle(- state: SessionStateMap | undefined,- result: RuntimeSubagentChildResult,-): boolean {- return findRunningAgentHandle(state, { callId: result.callId }) !== undefined;-}diff --git a/packages/eve/src/subagents/handles/state-key.ts b/packages/eve/src/subagents/handles/state-key.tsdeleted file mode 100644index b769570a4..000000000--- a/packages/eve/src/subagents/handles/state-key.ts+++ /dev/null@@ -1,8 +0,0 @@-/**- * Session-state key for delegated agent handles.- *- * Lives apart from the store so schema-free readers (the session owner's- * handle query) can import the key without pulling the zod-backed store- * module into their bundle.- */-export const AGENT_HANDLES_STATE_KEY = "eve.agent.handles";diff --git a/packages/eve/src/subagents/handles/store.test.ts b/packages/eve/src/subagents/handles/store.test.tsdeleted file mode 100644index 450712350..000000000--- a/packages/eve/src/subagents/handles/store.test.ts+++ /dev/null@@ -1,147 +0,0 @@-import { describe, expect, it } from "vitest";--import { deriveAgentOperationId } from "#subagents/handles/operation-id.js";-import {- AGENT_HANDLES_STATE_KEY,- assertPersistableAgentHandleStore,- deriveAgentId,- formatAgentStatus,- getAgentHandleStore,- type AgentAddress,- type AgentHandle,- type AgentIdentity,- type StartOperation,-} from "#subagents/handles/store.js";--const startOperation: StartOperation = {- callId: "call_1",- id: deriveAgentOperationId({- callId: "call_1",- parentSessionId: "session_parent",- parentTurnId: "turn_1",- }),- kind: "start",- parentTurnId: "turn_1",-};--const identity: AgentIdentity = {- id: deriveAgentId("research", startOperation.id),- name: "research",- nodeId: "node_research",-};--const address: AgentAddress = {- continuationToken: "continuation_child",- kind: "agent/local",- sessionId: "session_child",-};--const parkedHandle: AgentHandle = {- address,- identity,- lastStatus: "initial findings",- phase: "parked",-};--describe("deriveAgentOperationId / deriveAgentId", () => {- it("is deterministic on parent-controlled inputs and independent of the child session", () => {- const again = deriveAgentOperationId({- callId: "call_1",- parentSessionId: "session_parent",- parentTurnId: "turn_1",- });- expect(again).toBe(startOperation.id);- expect(deriveAgentId("research", again)).toBe(identity.id);- expect(identity.id.startsWith("ag_research:")).toBe(true);- });-- it("changes when any input changes", () => {- const other = deriveAgentOperationId({- callId: "call_2",- parentSessionId: "session_parent",- parentTurnId: "turn_1",- });- expect(other).not.toBe(startOperation.id);- });-});--describe("getAgentHandleStore", () => {- it("returns undefined only when no store has been written", () => {- expect(getAgentHandleStore(undefined)).toBeUndefined();- expect(getAgentHandleStore({})).toBeUndefined();- });-- it("throws on a present but malformed store instead of treating it as absent", () => {- for (const malformed of [- null,- { handles: "not-an-array" },- { handles: [{ phase: "starting" }] },- {- handles: [- {- address,- identity,- lastStatus: "x".repeat(121),- phase: "parked",- },- ],- },- ]) {- expect(() => getAgentHandleStore({ [AGENT_HANDLES_STATE_KEY]: malformed })).toThrow(- AGENT_HANDLES_STATE_KEY,- );- }- });-- it("rejects duplicate handle ids", () => {- expect(() =>- getAgentHandleStore({- [AGENT_HANDLES_STATE_KEY]: { handles: [parkedHandle, parkedHandle] },- }),- ).toThrow("unique");- });-});--describe("assertPersistableAgentHandleStore", () => {- it("returns a valid store unchanged in shape", () => {- expect(assertPersistableAgentHandleStore({ handles: [parkedHandle] })).toEqual({- handles: [parkedHandle],- });- });-- it("preserves a remote child's creation-time credential resolver", () => {- const remoteHandle: AgentHandle = {- address: {- callbackBaseUrl: "https://parent.example.com",- credentialResolver: { resolverId: "dynamic-credentials-step" },- kind: "agent/remote",- sessionId: "remote-child",- url: "https://remote.example.com",- },- identity,- lastStatus: "waiting",- phase: "parked",- };-- expect(assertPersistableAgentHandleStore({ handles: [remoteHandle] })).toEqual({- handles: [remoteHandle],- });- });-- it("refuses to persist a malformed store", () => {- const corrupt = {- handles: [{ ...parkedHandle, lastStatus: "x".repeat(121) }],- };- expect(() => assertPersistableAgentHandleStore(corrupt)).toThrow(- "Refusing to persist a corrupt agent handle store",- );- });-});--describe("formatAgentStatus", () => {- it("collapses whitespace, truncates to 120, and stringifies objects", () => {- expect(formatAgentStatus(" a\n\tb ")).toBe("a b");- expect(formatAgentStatus({ ok: true })).toBe('{"ok":true}');- expect(formatAgentStatus("y".repeat(300)).length).toBe(120);- });-});diff --git a/packages/eve/src/subagents/handles/store.ts b/packages/eve/src/subagents/handles/store.tsdeleted file mode 100644index 75b2aab02..000000000--- a/packages/eve/src/subagents/handles/store.ts+++ /dev/null@@ -1,431 +0,0 @@-import { z } from "#compiled/zod/index.js";--import type { SessionStateMap } from "#harness/types.js";--import { AGENT_HANDLES_STATE_KEY } from "./state-key.js";--export { AGENT_HANDLES_STATE_KEY };--const MAX_STATUS_LENGTH = 120;--/**- * Stable identity of one delegated child, minted before its start side- * effect runs. The model-visible `id` derives from the first start- * operation, never from the child session id, so it exists before the- * child does and cannot collide on externally supplied session suffixes.- */-export interface AgentIdentity {- /** Model-visible identifier: `ag_<name>:<operation-hash>`. */- readonly id: string;- /** Subagent tool name. */- readonly name: string;- /** Agent-graph node used to re-resolve delivery configuration. */- readonly nodeId: string;-}--/**- * One dispatch the parent intends to perform or has performed. Repeating- * the same operation is a replay; a different operation against a- * starting/running handle is a busy conflict.- */-export interface StartOperation {- readonly kind: "start";- /** Derived via {@link deriveAgentOperationId}; stable across replays. */- readonly id: string;- readonly callId: string;- readonly parentTurnId: string;-}--/** A continuation delivery against a parked handle. */-export interface ContinueOperation {- readonly kind: "continue";- /** Derived via {@link deriveAgentOperationId}; stable across replays. */- readonly id: string;- readonly callId: string;- readonly parentTurnId: string;- /**- * Status the handle showed before this delivery, restored when the- * delivery is rejected as retryable so the handle returns to `parked`- * without optional state.- */- readonly previousStatus: string;-}--/** Where a fresh child will be started. No session exists yet. */-export type AgentStartTarget =- | {- readonly kind: "agent/local";- /** Deterministic child continuation token chosen at dispatch. */- readonly continuationToken: string;- }- | {- readonly kind: "agent/self";- readonly continuationToken: string;- }- | {- readonly kind: "agent/remote";- /** Deliver target base URL; never model-visible. */- readonly url: string;- /** Callback base URL stub captured at dispatch; never model-visible. */- readonly callbackBaseUrl: string;- /** Auth/header resolver selected when this child was created; `{}` means none. */- readonly credentialResolver?: { readonly resolverId?: string };- };--/** Confirmed delivery coordinates of a started child. */-export type AgentAddress =- | {- readonly kind: "agent/local";- readonly sessionId: string;- readonly continuationToken: string;- }- | {- readonly kind: "agent/self";- readonly sessionId: string;- readonly continuationToken: string;- }- | {- readonly kind: "agent/remote";- readonly sessionId: string;- readonly url: string;- readonly callbackBaseUrl: string;- /** Auth/header resolver selected when this child was created; `{}` means none. */- readonly credentialResolver?: { readonly resolverId?: string };- };--/**- * Parent-turn-owned lifecycle: `starting → running → parked ↔ running`.- *- * `starting` owns a start intent before the child has an address, `running`- * owns one outstanding child turn, and `parked` retains an idle, resumable- * child. A terminal child or dead dispatch leaves this union entirely.- */-export type TurnOwnedAgentHandle =- | {- readonly phase: "starting";- readonly identity: AgentIdentity;- readonly operation: StartOperation;- readonly target: AgentStartTarget;- }- | {- readonly phase: "running";- readonly identity: AgentIdentity;- readonly operation: StartOperation | ContinueOperation;- readonly address: AgentAddress;- }- | {- readonly phase: "parked";- readonly identity: AgentIdentity;- readonly address: AgentAddress;- readonly lastStatus: string;- };--/**- * Workflow-owner lifecycle: `reserved → claimed → available ↔ claimed`.- *- * `reserved` leases a fresh identity before start, `claimed` leases an- * addressed child turn to one task or workflow-tool run, and `available`- * retains the idle address between invocations. A terminal child leaves this- * union entirely.- */-export type TaskOwnedAgentHandle =- | {- /** Fresh identity leased to one owner before the child's address is confirmed. */- readonly phase: "reserved";- readonly identity: AgentIdentity;- readonly operationId: string;- readonly callId?: string;- readonly ownerId: string;- }- | {- /** Addressed child turn leased until its owner releases it. */- readonly phase: "claimed";- readonly identity: AgentIdentity;- readonly operationId: string;- readonly callId?: string;- readonly address: AgentAddress;- readonly ownerId: string;- }- | {- /** Idle addressed child with no owner lease, ready for a later invocation to claim. */- readonly phase: "available";- readonly identity: AgentIdentity;- readonly address: AgentAddress;- };--/**- * Durable ownership record for one delegated child.- *- * The two execution policies share an identity namespace and serialized store,- * but their lifecycle states and transitions are disjoint. A terminal child has- * no handle: settlement deletes it.- */-export type AgentHandle = TurnOwnedAgentHandle | TaskOwnedAgentHandle;--/** Lifecycle phase of a delegated agent handle. */-export type AgentHandlePhase = AgentHandle["phase"];--/** Session-state collection of delegated agent handles. */-export interface AgentHandleStore {- readonly handles: readonly AgentHandle[];-}--export const EMPTY_AGENT_HANDLE_STORE: AgentHandleStore = { handles: [] };--/** One serialized owner-lease mutation against the shared agent handle store. */-export type AgentHandleStoreCommand =- | { readonly kind: "read" }- | {- readonly identity: AgentIdentity;- readonly kind: "reserve";- readonly operationId: string;- readonly callId?: string;- readonly ownerId: string;- }- | {- readonly address: AgentAddress;- readonly kind: "confirm";- readonly operationId: string;- readonly ownerId: string;- }- | {- readonly agentId: string;- readonly expectedTarget: "local" | "remote";- readonly callId?: string;- readonly invokedName: string;- readonly kind: "claim";- readonly operationId: string;- readonly ownerId: string;- }- | { readonly agentId: string; readonly kind: "remove"; readonly ownerId: string }- | { readonly kind: "release-owner"; readonly ownerId: string };--export type AgentHandleStoreCommandResult =- | { readonly kind: "ready"; readonly handle?: TaskOwnedAgentHandle }- | { readonly kind: "busy"; readonly handle: AgentHandle }- | { readonly kind: "mismatch"; readonly handle: AgentHandle }- | { readonly kind: "unknown" };--const nonEmptyString = z.string().min(1);--const identitySchema = z.looseObject({- id: nonEmptyString,- name: nonEmptyString,- nodeId: nonEmptyString,-});--const startOperationSchema = z.looseObject({- callId: nonEmptyString,- id: nonEmptyString,- kind: z.literal("start"),- parentTurnId: nonEmptyString,-});--const continueOperationSchema = z.looseObject({- callId: nonEmptyString,- id: nonEmptyString,- kind: z.literal("continue"),- parentTurnId: nonEmptyString,- previousStatus: z.string().max(MAX_STATUS_LENGTH),-});--const startTargetSchema: z.ZodType<AgentStartTarget> = z.discriminatedUnion("kind", [- z.looseObject({ continuationToken: nonEmptyString, kind: z.literal("agent/local") }),- z.looseObject({ continuationToken: nonEmptyString, kind: z.literal("agent/self") }),- z.looseObject({- callbackBaseUrl: z.url(),- credentialResolver: z.looseObject({ resolverId: nonEmptyString.optional() }).optional(),- kind: z.literal("agent/remote"),- url: z.url(),- }),-]);--const addressSchema: z.ZodType<AgentAddress> = z.discriminatedUnion("kind", [- z.looseObject({- continuationToken: nonEmptyString,- kind: z.literal("agent/local"),- sessionId: nonEmptyString,- }),- z.looseObject({- continuationToken: nonEmptyString,- kind: z.literal("agent/self"),- sessionId: nonEmptyString,- }),- z.looseObject({- callbackBaseUrl: z.url(),- credentialResolver: z.looseObject({ resolverId: nonEmptyString.optional() }).optional(),- kind: z.literal("agent/remote"),- sessionId: nonEmptyString,- url: z.url(),- }),-]);--const agentHandleStoreCommandSchema: z.ZodType<AgentHandleStoreCommand> = z.discriminatedUnion(- "kind",- [- z.strictObject({ kind: z.literal("read") }),- z.strictObject({- identity: identitySchema,- callId: nonEmptyString.optional(),- kind: z.literal("reserve"),- operationId: nonEmptyString,- ownerId: nonEmptyString,- }),- z.strictObject({- address: addressSchema,- kind: z.literal("confirm"),- operationId: nonEmptyString,- ownerId: nonEmptyString,- }),- z.strictObject({- agentId: nonEmptyString,- callId: nonEmptyString.optional(),- expectedTarget: z.enum(["local", "remote"]),- invokedName: nonEmptyString,- kind: z.literal("claim"),- operationId: nonEmptyString,- ownerId: nonEmptyString,- }),- z.strictObject({- agentId: nonEmptyString,- kind: z.literal("remove"),- ownerId: nonEmptyString,- }),- z.strictObject({ kind: z.literal("release-owner"), ownerId: nonEmptyString }),- ],-);--const turnOwnedAgentHandleSchema: z.ZodType<TurnOwnedAgentHandle> = z.discriminatedUnion("phase", [- z.looseObject({- identity: identitySchema,- operation: startOperationSchema,- phase: z.literal("starting"),- target: startTargetSchema,- }),- z.looseObject({- address: addressSchema,- identity: identitySchema,- operation: z.discriminatedUnion("kind", [startOperationSchema, continueOperationSchema]),- phase: z.literal("running"),- }),- z.looseObject({- address: addressSchema,- identity: identitySchema,- lastStatus: z.string().max(MAX_STATUS_LENGTH),- phase: z.literal("parked"),- }),-]);--const taskOwnedAgentHandleSchema: z.ZodType<TaskOwnedAgentHandle> = z.discriminatedUnion("phase", [- z.looseObject({- callId: nonEmptyString.optional(),- identity: identitySchema,- operationId: nonEmptyString,- phase: z.literal("reserved"),- ownerId: nonEmptyString,- }),- z.looseObject({- address: addressSchema,- callId: nonEmptyString.optional(),- identity: identitySchema,- operationId: nonEmptyString,- phase: z.literal("claimed"),- ownerId: nonEmptyString,- }),- z.looseObject({- address: addressSchema,- identity: identitySchema,- phase: z.literal("available"),- }),-]);--const agentHandleSchema: z.ZodType<AgentHandle> = z.union([- turnOwnedAgentHandleSchema,- taskOwnedAgentHandleSchema,-]);--const agentHandleStoreSchema: z.ZodType<AgentHandleStore> = z- .looseObject({- handles: z.array(agentHandleSchema),- })- .refine(- (store) =>- new Set(store.handles.map((handle) => handle.identity.id)).size === store.handles.length,- { message: "Agent handle ids must be unique." },- );--/** Derives the model-visible agent id from the first start operation. */-export function deriveAgentId(name: string, startOperationId: string): string {- return `ag_${name}:${startOperationId.slice(0, 12)}`;-}--/** Collapses whitespace and truncates output into a handle status line. */-export function formatAgentStatus(output: unknown): string {- const text = typeof output === "string" ? output : (JSON.stringify(output) ?? "");- return text.replaceAll(/\s+/g, " ").trim().slice(0, MAX_STATUS_LENGTH);-}--/**- * Validates one agent handle store about to be persisted, returning the- * parsed value. Throws instead of writing an invalid store: transitions run- * this on every write, which is the invariant that lets the schema-free- * owner-side reader (`query.ts`) trust stored values without revalidating.- */-export function assertPersistableAgentHandleStore(store: AgentHandleStore): AgentHandleStore {- const parsed = agentHandleStoreSchema.safeParse(store);- if (!parsed.success) {- throw new Error(`Refusing to persist a corrupt agent handle store: ${parsed.error.message}`);- }- return parsed.data;-}--/** Parses one complete command before the session inbox routes it to the handle store. */-export function parseAgentHandleStoreCommand(value: unknown): AgentHandleStoreCommand | undefined {- const parsed = agentHandleStoreCommandSchema.safeParse(value);- return parsed.success ? parsed.data : undefined;-}--/**- * Reads and validates the agent handle store from session state.- *- * Returns `undefined` only when no store has been written. A present but- * invalid store throws: treating corruption as absence would let the next- * transition silently replace every delegated child's delivery coordinates.- */-export function getAgentHandleStore(- state: SessionStateMap | undefined,-): AgentHandleStore | undefined {- const raw = state?.[AGENT_HANDLES_STATE_KEY];- if (raw === undefined) {- return undefined;- }- const parsed = agentHandleStoreSchema.safeParse(raw);- if (!parsed.success) {- throw new Error(- `Corrupt agent handle store under session state key "${AGENT_HANDLES_STATE_KEY}": ${parsed.error.message}`,- );- }- return parsed.data;-}--/** Writes the validated agent handle store under its single session-state key. */-export function setAgentHandleStore(- state: SessionStateMap | undefined,- store: AgentHandleStore,-): SessionStateMap {- return {- ...state,- [AGENT_HANDLES_STATE_KEY]: assertPersistableAgentHandleStore(store),- };-}--/** Writes a validated handle list to a session-shaped value. */-export function writeHandles<Session extends { readonly state?: SessionStateMap }>(- session: Session,- handles: readonly AgentHandle[],-): Session {- return {- ...session,- state: setAgentHandleStore(session.state, { handles }),- };-}diff --git a/packages/eve/src/subagents/handles/transitions.test.ts b/packages/eve/src/subagents/handles/transitions.test.tsdeleted file mode 100644index a1381ca47..000000000--- a/packages/eve/src/subagents/handles/transitions.test.ts+++ /dev/null@@ -1,453 +0,0 @@-import { describe, expect, it } from "vitest";--import { deriveAgentOperationId } from "#subagents/handles/operation-id.js";-import {- EMPTY_AGENT_HANDLE_STORE,- deriveAgentId,- getAgentHandleStore,- writeHandles,- type AgentAddress,- type AgentHandle,- type AgentIdentity,- type StartOperation,- type TaskOwnedAgentHandle,-} from "#subagents/handles/store.js";-import {- abandonAgentInvocationOwners,- abandonRunningAgentTurns,- applyAgentHandleStoreCommand,- confirmAgentStarted,- prepareAgentStart,- rejectAgentEffect,- settleAgentTurn,-} from "#subagents/handles/transitions.js";-import type { HarnessSession } from "#harness/types.js";-import type { TokenUsage } from "#shared/token-usage.js";--const ZERO_USAGE: TokenUsage = {- cacheReadTokens: 0,- cacheWriteTokens: 0,- inputTokens: 0,- outputTokens: 0,-};--function createSession(state?: HarnessSession["state"]): HarnessSession {- return {- agent: {- modelReference: { id: "model_test" },- system: "",- tools: [],- },- compaction: { recentWindowSize: 4, threshold: 1_000_000 },- continuationToken: "continuation_test",- history: [],- sessionId: "session_parent",- state,- };-}--const startOperation: StartOperation = {- callId: "call_1",- id: deriveAgentOperationId({- callId: "call_1",- parentSessionId: "session_parent",- parentTurnId: "turn_1",- }),- kind: "start",- parentTurnId: "turn_1",-};--const identity: AgentIdentity = {- id: deriveAgentId("research", startOperation.id),- name: "research",- nodeId: "node_research",-};--const address: AgentAddress = {- continuationToken: "continuation_child",- kind: "agent/local",- sessionId: "session_child",-};--function preparedSession(): HarnessSession {- return prepareAgentStart(createSession(), {- identity,- operation: startOperation,- target: { continuationToken: "continuation_child", kind: "agent/local" },- });-}--function runningSession(): HarnessSession {- return confirmAgentStarted(preparedSession(), {- address,- operationId: startOperation.id,- });-}--function parkedSession(): HarnessSession {- const settled = settleAgentTurn(runningSession(), {- operationId: startOperation.id,- outcome: {- kind: "parked",- result: { kind: "succeeded", output: "initial findings" },- usageDelta: ZERO_USAGE,- },- });- if (settled.kind !== "settled") {- throw new Error("expected settled");- }- return settled.session;-}--function handlesOf(session: HarnessSession): readonly AgentHandle[] {- return getAgentHandleStore(session.state)?.handles ?? [];-}--describe("prepareAgentStart", () => {- it("records starting ownership before any side effect", () => {- const session = preparedSession();- expect(handlesOf(session)).toEqual([- {- identity,- operation: startOperation,- phase: "starting",- target: { continuationToken: "continuation_child", kind: "agent/local" },- },- ]);- });-- it("throws when the identity already exists", () => {- expect(() =>- prepareAgentStart(preparedSession(), {- identity,- operation: startOperation,- target: { continuationToken: "continuation_child", kind: "agent/local" },- }),- ).toThrow(identity.id);- });-});--describe("confirmAgentStarted", () => {- it("moves starting to running with the confirmed address", () => {- expect(handlesOf(runningSession())).toEqual([- { address, identity, operation: startOperation, phase: "running" },- ]);- });-- it("is a replay no-op when the handle is already running", () => {- const running = runningSession();- expect(confirmAgentStarted(running, { address, operationId: startOperation.id })).toBe(running);- });-- it("throws for an operation that was never prepared", () => {- expect(() =>- confirmAgentStarted(createSession(), { address, operationId: "op_unprepared" }),- ).toThrow("op_unprepared");- });-});--describe("rejectAgentEffect", () => {- it("deletes a dead start", () => {- const session = rejectAgentEffect(preparedSession(), {- disposition: "dead",- operationId: startOperation.id,- });- expect(handlesOf(session)).toEqual([]);- });-- it("restores parked with the previous status for a retryable continuation", () => {- const continueOperation = {- callId: "call_2",- id: "op_continue",- kind: "continue",- parentTurnId: "turn_2",- previousStatus: "initial findings",- } as const;- const prepared = {- session: writeHandles(parkedSession(), [- { address, identity, operation: continueOperation, phase: "running" },- ]),- };-- const restored = rejectAgentEffect(prepared.session, {- disposition: "retryable",- operationId: "op_continue",- });- expect(handlesOf(restored)).toEqual([- { address, identity, lastStatus: "initial findings", phase: "parked" },- ]);- });-- it("deletes a running start even when the failure is retryable", () => {- // A fresh start has no parked state to restore; the model retries by- // starting a new agent instead.- const session = rejectAgentEffect(runningSession(), {- disposition: "retryable",- operationId: startOperation.id,- });- expect(handlesOf(session)).toEqual([]);- });-- it("ignores unknown operations", () => {- const parked = parkedSession();- expect(rejectAgentEffect(parked, { disposition: "dead", operationId: "op_gone" })).toBe(parked);- });-});--describe("abandonRunningAgentTurns", () => {- it("parks a running handle as cancelled so it stays resumable", () => {- const abandoned = abandonRunningAgentTurns(runningSession());- expect(handlesOf(abandoned)).toEqual([- { address, identity, lastStatus: "(cancelled)", phase: "parked" },- ]);- });-- it("returns the session unchanged when nothing is running", () => {- const parked = parkedSession();- expect(abandonRunningAgentTurns(parked)).toBe(parked);-- const empty = createSession();- expect(abandonRunningAgentTurns(empty)).toBe(empty);- });-});--describe("owner-scoped handle claims", () => {- it("keeps a recorded workflow run's claim separate from a task claim", () => {- const available: TaskOwnedAgentHandle = { address, identity, phase: "available" };- const workflowClaim = applyAgentHandleStoreCommand(- { handles: [available] },- {- agentId: identity.id,- callId: "call-workflow",- expectedTarget: "local",- invokedName: identity.name,- kind: "claim",- operationId: "operation-workflow",- ownerId: "workflow-run-1",- },- );-- expect(workflowClaim.result).toMatchObject({- handle: { ownerId: "workflow-run-1", phase: "claimed" },- kind: "ready",- });- expect(- applyAgentHandleStoreCommand(workflowClaim.store, {- agentId: identity.id,- callId: "call-task",- expectedTarget: "local",- invokedName: identity.name,- kind: "claim",- operationId: "operation-task",- ownerId: "task_1",- }).result,- ).toMatchObject({ handle: { ownerId: "workflow-run-1" }, kind: "busy" });- });-});--describe("settleAgentTurn", () => {- it("parks the handle with a truncated status on a parked outcome", () => {- const settled = settleAgentTurn(runningSession(), {- operationId: startOperation.id,- outcome: {- kind: "parked",- result: { kind: "succeeded", output: ` padded\n${"x".repeat(200)} ` },- usageDelta: ZERO_USAGE,- },- });- expect(settled.kind).toBe("settled");- if (settled.kind !== "settled") {- return;- }- const [handle] = handlesOf(settled.session);- expect(handle?.phase).toBe("parked");- if (handle?.phase === "parked") {- expect(handle.lastStatus.length).toBeLessThanOrEqual(120);- expect(handle.lastStatus.startsWith("padded x")).toBe(true);- }- });-- it("deletes the handle on a terminal outcome, including failures", () => {- const settled = settleAgentTurn(runningSession(), {- operationId: startOperation.id,- outcome: {- kind: "terminal",- result: { error: { code: "BOOM" }, kind: "failed" },- usageDelta: ZERO_USAGE,- },- });- expect(settled.kind).toBe("settled");- if (settled.kind === "settled") {- expect(handlesOf(settled.session)).toEqual([]);- }- });-- it("keeps a failed-but-parked child resumable", () => {- const settled = settleAgentTurn(runningSession(), {- operationId: startOperation.id,- outcome: {- kind: "parked",- result: { error: "model overloaded", kind: "failed" },- usageDelta: ZERO_USAGE,- },- });- expect(settled.kind).toBe("settled");- if (settled.kind === "settled") {- expect(handlesOf(settled.session)[0]?.phase).toBe("parked");- }- });-- it("ignores stale operations", () => {- expect(- settleAgentTurn(runningSession(), {- operationId: "op_stale",- outcome: {- kind: "parked",- result: { kind: "succeeded", output: "" },- usageDelta: ZERO_USAGE,- },- }),- ).toEqual({ kind: "ignored", reason: "unknown-operation" });- });-});--describe("agent handle store task leases", () => {- it("reserves and confirms a task-owned start, then releases it for another task", () => {- const reserved = applyAgentHandleStoreCommand(EMPTY_AGENT_HANDLE_STORE, {- identity,- kind: "reserve",- operationId: "operation-1",- ownerId: "task-1",- });- expect(reserved.result).toMatchObject({ handle: { phase: "reserved" }, kind: "ready" });-- const confirmed = applyAgentHandleStoreCommand(reserved.store, {- address,- kind: "confirm",- operationId: "operation-1",- ownerId: "task-1",- });- expect(confirmed.result).toEqual({- kind: "ready",- handle: {- address,- identity,- operationId: "operation-1",- phase: "claimed",- ownerId: "task-1",- },- });-- const released = applyAgentHandleStoreCommand(confirmed.store, {- kind: "release-owner",- ownerId: "task-1",- });- expect(released.store.handles).toEqual([{ address, identity, phase: "available" }]);- });-- it("claims a parked child through the owner-scoped continuation path", () => {- const parked: AgentHandle = { address, identity, lastStatus: "(cancelled)", phase: "parked" };- const claimed = applyAgentHandleStoreCommand(- { handles: [parked] },- {- agentId: identity.id,- expectedTarget: "local",- invokedName: identity.name,- kind: "claim",- operationId: "operation-2",- ownerId: "workflow-run-2",- },- );-- expect(claimed.result).toMatchObject({- handle: { ownerId: "workflow-run-2", phase: "claimed" },- kind: "ready",- });- });-- it("parks claimed workflow owners as cancelled without changing available handles", () => {- const claimed: AgentHandle = {- address,- identity,- operationId: "operation-1",- ownerId: "workflow-run-1",- phase: "claimed",- };- const availableIdentity = { ...identity, id: "agent-2" };- const session = writeHandles(createSession(), [- claimed,- { address, identity: availableIdentity, phase: "available" },- ]);-- expect(handlesOf(abandonAgentInvocationOwners(session, new Set(["workflow-run-1"])))).toEqual([- { address, identity, lastStatus: "(cancelled)", phase: "parked" },- { address, identity: availableIdentity, phase: "available" },- ]);- });-- it("allows only one task to claim an available session agent", () => {- const available: TaskOwnedAgentHandle = { address, identity, phase: "available" };- const claimed = applyAgentHandleStoreCommand(- { handles: [available] },- {- agentId: identity.id,- expectedTarget: "local",- invokedName: identity.name,- kind: "claim",- operationId: "operation-2",- ownerId: "task-2",- },- );- expect(claimed.result).toMatchObject({ handle: { phase: "claimed" }, kind: "ready" });-- const competing = applyAgentHandleStoreCommand(claimed.store, {- agentId: identity.id,- expectedTarget: "local",- invokedName: identity.name,- kind: "claim",- operationId: "operation-3",- ownerId: "task-3",- });- expect(competing.result).toMatchObject({ handle: { ownerId: "task-2" }, kind: "busy" });- expect(competing.store).toBe(claimed.store);- });-- it("rejects a name or target mismatch without changing the store", () => {- const available: TaskOwnedAgentHandle = { address, identity, phase: "available" };-- for (const command of [- { expectedTarget: "local" as const, invokedName: "writer" },- { expectedTarget: "remote" as const, invokedName: identity.name },- ]) {- const result = applyAgentHandleStoreCommand(- { handles: [available] },- {- agentId: identity.id,- ...command,- kind: "claim",- operationId: "operation-2",- ownerId: "task-2",- },- );- expect(result.result).toMatchObject({ kind: "mismatch" });- expect(result.store.handles).toEqual([available]);- }- });-- it("does not let one task remove another task's claimed agent", () => {- const claimed: TaskOwnedAgentHandle = {- address,- identity,- operationId: "operation-1",- phase: "claimed",- ownerId: "task-1",- };- const result = applyAgentHandleStoreCommand(- { handles: [claimed] },- { agentId: identity.id, kind: "remove", ownerId: "task-2" },- );-- expect(result.result).toEqual({ handle: claimed, kind: "busy" });- expect(result.store.handles).toEqual([claimed]);- });-});diff --git a/packages/eve/src/subagents/handles/transitions.ts b/packages/eve/src/subagents/handles/transitions.tsdeleted file mode 100644index 0a611133d..000000000--- a/packages/eve/src/subagents/handles/transitions.ts+++ /dev/null@@ -1,420 +0,0 @@-import {- formatAgentStatus,- EMPTY_AGENT_HANDLE_STORE,- getAgentHandleStore,- writeHandles,- type AgentAddress,- type AgentHandle,- type AgentHandleStore,- type AgentHandleStoreCommand,- type AgentHandleStoreCommandResult,- type AgentIdentity,- type StartOperation,- type TaskOwnedAgentHandle,- type TurnOwnedAgentHandle,-} from "#subagents/handles/store.js";-import type { HarnessSession, SessionStateMap } from "#harness/types.js";-import type { AgentTurnOutcome } from "#shared/agent-turn-outcome.js";--/**- * Records intent to start a fresh child. Must be applied to the step's- * working snapshot before the start side effect runs, so the returned state- * owns any child the step may have created.- *- * The guarantee is intra-step, not exactly-once: the prepared handle- * durably commits only when the enclosing dispatch step's result commits.- * A crash between an accepted start and that commit replays the step from- * the pre-step snapshot and re-runs the side effect.- *- * Throws when the identity or operation already exists: fresh starts mint- * a new identity, so a collision means corrupted derivation, not a replay.- */-export function prepareAgentStart(- session: HarnessSession,- input: {- readonly identity: AgentIdentity;- readonly operation: StartOperation;- readonly target: AgentStartTargetInput;- },-): HarnessSession {- const handles = getAgentHandleStore(session.state)?.handles ?? [];- if (handles.some((handle) => handle.identity.id === input.identity.id)) {- throw new Error(`Agent handle "${input.identity.id}" already exists.`);- }- return writeHandles(session, [- ...handles,- {- identity: input.identity,- operation: input.operation,- phase: "starting",- target: input.target,- },- ]);-}--type AgentStartTargetInput = Extract<TurnOwnedAgentHandle, { phase: "starting" }>["target"];--type ActiveAgentHandle = Extract<TurnOwnedAgentHandle, { phase: "starting" | "running" }>;--function findActiveHandle(- handles: readonly AgentHandle[],- operationId: string,-): ActiveAgentHandle | undefined {- return handles.find(- (handle): handle is ActiveAgentHandle =>- (handle.phase === "starting" || handle.phase === "running") &&- handle.operation.id === operationId,- );-}--/**- * Confirms a started child: `starting` becomes `running` with the child's- * confirmed address. Throws when no starting handle carries the operation,- * because confirming an unprepared start means ownership was never- * committed. Re-confirming an already-running handle with the same- * operation and address is a replay no-op.- */-export function confirmAgentStarted(- session: HarnessSession,- input: {- readonly operationId: string;- readonly address: AgentAddress;- },-): HarnessSession {- const handles = getAgentHandleStore(session.state)?.handles ?? [];- const existing = findActiveHandle(handles, input.operationId);- if (existing === undefined) {- throw new Error(`No prepared agent handle for operation "${input.operationId}".`);- }- if (existing.phase === "running") {- return session;- }-- return writeHandles(- session,- handles.map((handle) =>- handle === existing- ? {- address: input.address,- identity: existing.identity,- operation: existing.operation,- phase: "running",- }- : handle,- ),- );-}--/**- * Resolves a dispatch that definitively failed.- *- * - A dead start or dead continuation deletes the handle: there is no- * child left to own.- * - A retryable continuation failure restores `parked` with the status the- * handle showed before the delivery, so the model may retry the same- * `agentId` later.- *- * Unknown operations are a no-op: the failure raced a settlement that- * already resolved the handle.- */-export function rejectAgentEffect(- session: HarnessSession,- input: {- readonly operationId: string;- readonly disposition: "dead" | "retryable";- },-): HarnessSession {- const handles = getAgentHandleStore(session.state)?.handles ?? [];- const existing = findActiveHandle(handles, input.operationId);- if (existing === undefined) {- return session;- }-- if (input.disposition === "retryable" && existing.phase === "running") {- const { operation } = existing;- if (operation.kind === "continue") {- return writeHandles(- session,- handles.map((handle) =>- handle === existing- ? {- address: existing.address,- identity: existing.identity,- lastStatus: operation.previousStatus,- phase: "parked",- }- : handle,- ),- );- }- }-- return writeHandles(- session,- handles.filter((handle) => handle !== existing),- );-}--/**- * Parks every running child when the parent abandons a cancelled turn.- *- * Cancellation requests each running descendant's cancellation and then- * tears down the turn inbox — the only hook a child settlement can- * resume — so no later settlement can move these handles. Without this- * transition they would stay `running` forever: invisible to the model,- * unresumable, and retried by every future cancellation.- *- * A cancelled child settles its own turn as a park, so `parked` with- * `"(cancelled)"` mirrors {@link settleAgentTurn}'s cancelled outcome. If- * the child instead died, a later continuation attempt discovers the dead- * session and {@link rejectAgentEffect} deletes the handle.- */-export function abandonRunningAgentTurns(session: HarnessSession): HarnessSession {- const handles = getAgentHandleStore(session.state)?.handles ?? [];- if (!handles.some((handle) => handle.phase === "running")) {- return session;- }- return writeHandles(- session,- handles.map((handle) =>- handle.phase === "running"- ? {- address: handle.address,- identity: handle.identity,- lastStatus: "(cancelled)",- phase: "parked",- }- : handle,- ),- );-}--/** Result of applying a settled child turn to the store. */-export type SettleAgentTurnResult =- | { readonly kind: "settled"; readonly session: HarnessSession }- | { readonly kind: "ignored"; readonly reason: "unknown-operation" };--/**- * Applies one settled child turn: `running` becomes `parked` for a parked- * outcome or is deleted for a terminal outcome.- *- * The settlement must carry the operation currently recorded on the- * running handle; anything else is ignored so a stale delivery can never- * move a newer turn.- */-export function settleAgentTurn(- session: HarnessSession,- input: {- readonly operationId: string;- readonly outcome: AgentTurnOutcome;- },-): SettleAgentTurnResult {- const handles = getAgentHandleStore(session.state)?.handles ?? [];- const existing = handles.find(- (handle) => handle.phase === "running" && handle.operation.id === input.operationId,- );- if (existing === undefined || existing.phase !== "running") {- return { kind: "ignored", reason: "unknown-operation" };- }-- if (input.outcome.kind === "terminal") {- return {- kind: "settled",- session: writeHandles(- session,- handles.filter((handle) => handle !== existing),- ),- };- }-- const { result } = input.outcome;- const lastStatus =- result.kind === "succeeded"- ? formatAgentStatus(result.output)- : result.kind === "failed"- ? formatAgentStatus(result.error)- : "(cancelled)";- return {- kind: "settled",- session: writeHandles(- session,- handles.map((handle) =>- handle === existing- ? {- address: existing.address,- identity: existing.identity,- lastStatus,- phase: "parked",- }- : handle,- ),- ),- };-}--/** Applies one atomic owner lease command to the shared agent handle store. */-export function applyAgentHandleStoreCommand(- store: AgentHandleStore,- command: AgentHandleStoreCommand,-): {- readonly result: AgentHandleStoreCommandResult;- readonly store: AgentHandleStore;-} {- switch (command.kind) {- case "read":- return { result: { kind: "ready" }, store };- case "reserve": {- const existing = store.handles.find((handle) => handle.identity.id === command.identity.id);- if (existing !== undefined) {- return (existing.phase === "reserved" || existing.phase === "claimed") &&- existing.operationId === command.operationId &&- existing.ownerId === command.ownerId- ? { result: { handle: existing, kind: "ready" }, store }- : { result: { handle: existing, kind: "busy" }, store };- }- const handle: TaskOwnedAgentHandle = {- callId: command.callId,- identity: command.identity,- operationId: command.operationId,- phase: "reserved",- ownerId: command.ownerId,- };- return {- result: { handle, kind: "ready" },- store: { handles: [...store.handles, handle] },- };- }- case "confirm": {- const existing = store.handles.find(- (- handle,- ): handle is Extract<TaskOwnedAgentHandle, { readonly phase: "claimed" | "reserved" }> =>- (handle.phase === "claimed" || handle.phase === "reserved") &&- handle.operationId === command.operationId &&- handle.ownerId === command.ownerId,- );- if (existing === undefined) return { result: { kind: "unknown" }, store };- if (existing.phase === "claimed") {- return { result: { handle: existing, kind: "ready" }, store };- }- const handle: TaskOwnedAgentHandle = {- address: command.address,- callId: existing.callId,- identity: existing.identity,- operationId: existing.operationId,- phase: "claimed",- ownerId: existing.ownerId,- };- return replaceHandle(store, existing, handle);- }- case "claim": {- const existing = store.handles.find((handle) => handle.identity.id === command.agentId);- if (existing === undefined) return { result: { kind: "unknown" }, store };- if (- existing.phase === "starting" ||- existing.phase === "running" ||- existing.identity.name !== command.invokedName ||- (existing.phase !== "reserved" &&- (existing.address.kind === "agent/remote") !== (command.expectedTarget === "remote"))- ) {- return { result: { handle: existing, kind: "mismatch" }, store };- }- if (existing.phase === "claimed") {- return existing.operationId === command.operationId && existing.ownerId === command.ownerId- ? { result: { handle: existing, kind: "ready" }, store }- : { result: { handle: existing, kind: "busy" }, store };- }- if (existing.phase === "reserved") {- return { result: { handle: existing, kind: "busy" }, store };- }- const handle: TaskOwnedAgentHandle = {- address: existing.address,- callId: command.callId,- identity: existing.identity,- operationId: command.operationId,- phase: "claimed",- ownerId: command.ownerId,- };- return replaceHandle(store, existing, handle);- }- case "remove": {- const existing = store.handles.find((handle) => handle.identity.id === command.agentId);- if (existing === undefined) return { result: { kind: "ready" }, store };- if (existing.phase === "claimed" && existing.ownerId !== command.ownerId) {- return { result: { handle: existing, kind: "busy" }, store };- }- return {- result: { kind: "ready" },- store: { handles: store.handles.filter((handle) => handle !== existing) },- };- }- case "release-owner": {- const handles = store.handles.flatMap((handle): readonly AgentHandle[] => {- if (handle.phase === "reserved" && handle.ownerId === command.ownerId) return [];- if (handle.phase !== "claimed" || handle.ownerId !== command.ownerId) return [handle];- return [{ address: handle.address, identity: handle.identity, phase: "available" }];- });- return {- result: { kind: "ready" },- store: handlesEqual(store.handles, handles) ? store : { handles },- };- }- }-}--/** Parks child turns still owned by workflow runs when their parent turn is cancelled. */-export function abandonAgentInvocationOwners<Session extends { readonly state?: SessionStateMap }>(- session: Session,- ownerIds: ReadonlySet<string>,-): Session {- const handles = getAgentHandleStore(session.state)?.handles ?? [];- const abandoned = handles.flatMap((handle): readonly AgentHandle[] => {- if (handle.phase === "reserved" && ownerIds.has(handle.ownerId)) return [];- if (handle.phase !== "claimed" || !ownerIds.has(handle.ownerId)) return [handle];- return [- {- address: handle.address,- identity: handle.identity,- lastStatus: "(cancelled)",- phase: "parked",- },- ];- });- return handlesEqual(handles, abandoned) ? session : writeHandles(session, abandoned);-}--/** Applies one owner-scoped handle transition to a harness session. */-export function applyTaskAgentHandleCommand<Session extends { readonly state?: SessionStateMap }>(- session: Session,- command: AgentHandleStoreCommand,-): {- readonly result: AgentHandleStoreCommandResult;- readonly session: Session;-} {- const store = getAgentHandleStore(session.state) ?? EMPTY_AGENT_HANDLE_STORE;- const applied = applyAgentHandleStoreCommand(store, command);- return {- result: applied.result,- session: applied.store === store ? session : writeHandles(session, applied.store.handles),- };-}--function replaceHandle(- store: AgentHandleStore,- existing: AgentHandle,- handle: TaskOwnedAgentHandle,-): {- readonly result: AgentHandleStoreCommandResult;- readonly store: AgentHandleStore;-} {- return {- result: { handle, kind: "ready" },- store: {- handles: store.handles.map((candidate) => (candidate === existing ? handle : candidate)),- },- };-}--function handlesEqual(left: readonly AgentHandle[], right: readonly AgentHandle[]): boolean {- return left.length === right.length && left.every((handle, index) => handle === right[index]);-}diff --git a/packages/eve/src/subagents/hitl-proxy.ts b/packages/eve/src/subagents/hitl-proxy.tsindex fab124966..c79af8fb9 100644--- a/packages/eve/src/subagents/hitl-proxy.ts+++ b/packages/eve/src/subagents/hitl-proxy.ts@@ -42,6 +42,7 @@ export async function emitProxiedInputRequest(input: {requests: input.hookPayload.event.requests,sequence: input.hookPayload.event.sequence,stepIndex: input.hookPayload.event.stepIndex,+ taskId: input.hookPayload.event.taskId,turnId: input.hookPayload.event.turnId,}),);diff --git a/packages/eve/src/subagents/invocation.ts b/packages/eve/src/subagents/invocation.tsindex e5084088e..43072d88d 100644--- a/packages/eve/src/subagents/invocation.ts+++ b/packages/eve/src/subagents/invocation.ts@@ -23,8 +23,7 @@ interface FormattedSubagentInvocation extends StepInput {* Reads the `outputSchema` a `ctx.agent()` call requested. An empty `{}`* constrains nothing, but honoring it would flip the child into* structured-output mode and discard its text reply, so only a non-empty- * object counts as a requested schema. Local and remote dispatch share this- * rule.+ * object counts as a requested schema.*/export function normalizeRequestedOutputSchema(outputSchema: JsonValue | undefined,diff --git a/packages/eve/src/subagents/parent-notification.ts b/packages/eve/src/subagents/parent-notification.tsindex 6a83ac779..106f31934 100644--- a/packages/eve/src/subagents/parent-notification.ts+++ b/packages/eve/src/subagents/parent-notification.ts@@ -12,7 +12,6 @@ import {type SubagentAdapterState,} from "#subagents/adapter-state.js";import { HookNotFoundError } from "#compiled/@workflow/errors/index.js";-import { SUBAGENT_EXECUTION_FAILED } from "#subagents/agent-handle-errors.js";import { createLogger } from "#internal/logging.js";import type { AgentTurnOutcome } from "#shared/agent-turn-outcome.js";import { toErrorMessage } from "#shared/errors.js";@@ -23,6 +22,9 @@ import { postSessionCallbackRequest } from "#execution/session-callback-request.const log = createLogger("execution.delegated-parent-notification");+/** Error code for a delegated agent whose execution threw. */+const SUBAGENT_EXECUTION_FAILED = "SUBAGENT_EXECUTION_FAILED";+/** Settled turn payload forwarded from the owner to the caller. */export interface SettledTurnNotification {readonly output: unknown;diff --git a/packages/eve/src/subagents/start-local.test.ts b/packages/eve/src/subagents/start-local.test.tsdeleted file mode 100644index ce74aebdd..000000000--- a/packages/eve/src/subagents/start-local.test.ts+++ /dev/null@@ -1,118 +0,0 @@-import { beforeEach, describe, expect, it, vi } from "vitest";--import { createWorkflowRuntime, waitForCommandHookOwner } from "#execution/workflow-runtime.js";-import { startLocalSubagent } from "#subagents/start-local.js";-import { buildSubagentRunInput } from "#subagents/tool.js";--const createSessionMock = vi.fn();--vi.mock("#execution/workflow-runtime.js", () => ({- createWorkflowRuntime: vi.fn(() => ({ createSession: createSessionMock })),- waitForCommandHookOwner: vi.fn(),-}));-vi.mock("#subagents/tool.js", () => ({- buildSubagentRunInput: vi.fn(),-}));--beforeEach(() => {- vi.clearAllMocks();- createSessionMock.mockResolvedValue({- events: new ReadableStream(),- sessionId: "candidate-session",- });- vi.mocked(buildSubagentRunInput).mockReturnValue({- childContinuationToken: "child-token",- runInput: {} as never,- });- vi.mocked(waitForCommandHookOwner).mockResolvedValue({ runId: "winning-session" });-});--describe("startLocalSubagent", () => {- it("uses the session that wins continuation ownership", async () => {- const outcome = await startLocalSubagent({- action: {- callId: "call-1",- name: "research",- nodeId: "subagents/research",- subagentName: "research",- } as never,- auth: null,- bundle: { compiledArtifactsSource: {} } as never,- capabilities: undefined,- channelMetadata: undefined,- currentSession: {} as never,- fanoutSize: 1,- initiatorAuth: null,- parent: {- continuationToken: "parent-token",- originAudience: "private",- lineage: {- callId: "call-1",- rootSessionId: "parent-session",- sessionId: "parent-session",- turn: { id: "turn-1", sequence: 0 },- },- },- sandboxSessionId: "parent-session",- session: {} as never,- source: { description: "Research", type: "local" },- });-- expect(createWorkflowRuntime).toHaveBeenCalledOnce();- expect(outcome).toMatchObject({- address: {- continuationToken: "child-token",- sessionId: "winning-session",- },- kind: "called",- });- });-- it("passes an inherited task activity observer through unchanged", async () => {- const activityObserver = {- sink: { url: "https://parent.example/activity", version: 1 as const },- workIdentity: {- id: "work:task",- kind: "subagent" as const,- name: "slack",- parentId: "work:root",- rootSessionId: "root-session",- rootTurnId: "root-turn",- },- };-- await startLocalSubagent({- action: {- callId: "call-1",- name: "slack",- nodeId: "subagents/slack",- subagentName: "slack",- } as never,- activityObserver,- auth: null,- bundle: { compiledArtifactsSource: {} } as never,- capabilities: undefined,- channelMetadata: undefined,- currentSession: {} as never,- fanoutSize: 1,- initiatorAuth: null,- parent: {- continuationToken: "parent-token",- lineage: {- callId: "call-1",- rootSessionId: "parent-session",- sessionId: "parent-session",- turn: { id: "turn-1", sequence: 0 },- },- },- sandboxSessionId: "parent-session",- session: {} as never,- source: { description: "Search Slack", type: "local" },- });-- expect(buildSubagentRunInput).toHaveBeenCalledWith(- expect.objectContaining({ activityObserver }),- );- expect(createSessionMock).toHaveBeenCalledOnce();- });-});diff --git a/packages/eve/src/subagents/start-local.ts b/packages/eve/src/subagents/start-local.tsdeleted file mode 100644index 8d55195e1..000000000--- a/packages/eve/src/subagents/start-local.ts+++ /dev/null@@ -1,110 +0,0 @@-import { sessionInboxHookToken } from "#execution/session-inbox/address.js";-import type { DispatchOutcome, RuntimeSession } from "#subagents/handle-dispatch.js";-import { ContextContainer, contextStorage } from "#context/container.js";-import type { LocalDevRequestProvenance } from "#context/keys.js";-import { buildSubagentRunInput, type SubagentInputSource } from "#subagents/tool.js";-import { resolveRemainingSessionTokenLimits } from "#subagents/token-budget.js";-import { createWorkflowRuntime, waitForCommandHookOwner } from "#execution/workflow-runtime.js";-import { SUBAGENT_START_FAILED } from "#subagents/agent-handle-errors.js";-import { createLogger, logError } from "#internal/logging.js";-import type { RuntimeSubagentDispatchRequest } from "#shared/action-types.js";-import type { CompiledBundle } from "#runtime/sessions/runtime-context-keys.js";-import { toErrorMessage } from "#shared/errors.js";-import type { SubagentParentContext } from "#subagents/invocation.js";--const log = createLogger("execution.subagent-start-local");--type DynamicSubagentAgentConfig = Parameters<- typeof createWorkflowRuntime->[0]["dynamicSubagentAgentConfig"];--/** Starts one local subagent after dispatch planning has selected its target. */-export async function startLocalSubagent(input: {- readonly action: RuntimeSubagentDispatchRequest;- readonly auth: Parameters<typeof buildSubagentRunInput>[0]["auth"];- readonly bundle: CompiledBundle;- readonly capabilities: Parameters<typeof buildSubagentRunInput>[0]["capabilities"];- readonly channelMetadata: Parameters<typeof buildSubagentRunInput>[0]["channelMetadata"];- readonly inheritedConversation?: Parameters<- typeof buildSubagentRunInput- >[0]["inheritedConversation"];- readonly currentSession: RuntimeSession;- readonly dynamicSubagentAgentConfig?: DynamicSubagentAgentConfig;- readonly fanoutSize: number;- readonly initiatorAuth: Parameters<typeof buildSubagentRunInput>[0]["initiatorAuth"];- readonly localDevRequest?: LocalDevRequestProvenance;- readonly parent: SubagentParentContext;- readonly activityObserver?: Parameters<typeof buildSubagentRunInput>[0]["activityObserver"];- readonly sandboxSessionId: string;- readonly session: RuntimeSession;- readonly source: SubagentInputSource;-}): Promise<DispatchOutcome> {- const { action, source } = input;- const childRuntime = createWorkflowRuntime({- compiledArtifactsSource: input.bundle.compiledArtifactsSource,- dynamicSubagentAgentConfig: input.dynamicSubagentAgentConfig,- nodeId: action.nodeId,- });- const { childContinuationToken, runInput } = buildSubagentRunInput({- action,- auth: input.auth,- capabilities: input.capabilities,- channelMetadata: input.channelMetadata,- continuationKey: `${input.session.sessionId}:${action.callId}`,- inheritedConversation: input.inheritedConversation,- initiatorAuth: input.initiatorAuth,- graph: input.bundle.graph,- limits: resolveRemainingSessionTokenLimits(input.session, input.fanoutSize),- parent: input.parent,- activityObserver: input.activityObserver,- sandboxSessionId: input.sandboxSessionId,- session: input.session,- selfAgent: source.type === "runtime",- source,- });-- const targetKind = source.type === "runtime" ? ("agent/self" as const) : ("agent/local" as const);- let childSessionId: string;- try {- await contextStorage.run(new ContextContainer({ localDevRequest: input.localDevRequest }), () =>- childRuntime.createSession(runInput),- );- childSessionId = (await waitForCommandHookOwner(sessionInboxHookToken(childContinuationToken)))- .runId;- } catch (error) {- logError(log, "local subagent start failed", error, {- callId: action.callId,- nodeId: action.nodeId,- subagentName: action.subagentName,- });- return {- kind: "error",- result: {- callId: action.callId,- isError: true,- kind: "subagent-result",- origin: "dispatch",- output: {- code: SUBAGENT_START_FAILED,- message: toErrorMessage(error),- },- subagentName: action.subagentName,- },- session: input.currentSession,- };- }-- const address = {- continuationToken: childContinuationToken,- kind: targetKind,- sessionId: childSessionId,- } as const;- return {- address,- callId: action.callId,- kind: "called",- name: action.name,- session: input.currentSession,- toolName: action.subagentName,- };-}diff --git a/packages/eve/src/subagents/start-remote.test.ts b/packages/eve/src/subagents/start-remote.test.tsdeleted file mode 100644index 4fef9932d..000000000--- a/packages/eve/src/subagents/start-remote.test.ts+++ /dev/null@@ -1,77 +0,0 @@-import { beforeEach, describe, expect, it, vi } from "vitest";--const { resolveRemoteAgentForAction, startRemoteAgentSession } = vi.hoisted(() => ({- resolveRemoteAgentForAction: vi.fn(() => ({ url: "https://remote.example/eve/v1" })),- startRemoteAgentSession: vi.fn(async () => ({ sessionId: "remote-session" })),-}));--vi.mock("#subagents/remote-dispatch.js", () => ({- resolveRemoteAgentForAction,- startRemoteAgentSession,-}));--import { startRemoteSubagent } from "#subagents/start-remote.js";--const parentObserver = {- sink: { url: "https://parent.example/activity", version: 1 as const },- workIdentity: {- id: "work:root",- kind: "root-turn" as const,- rootSessionId: "root-session",- rootTurnId: "root-turn",- },-};--describe("startRemoteSubagent", () => {- beforeEach(() => vi.clearAllMocks());-- it("derives a child identity beneath the parent observer", async () => {- await startRemoteSubagent({- action: {- callId: "call-remote",- description: "Research remotely",- input: { message: "Find it" },- kind: "remote-agent-call",- name: "remote_research",- nodeId: "remoteAgents/research",- remoteAgentName: "research",- },- activityObserver: parentObserver,- auth: null,- batchEvent: { sequence: 0, turnId: "parent-turn" },- bundle: { subagentRegistry: { subagentsByNodeId: new Map() } },- callbackBaseUrl: "https://parent.example",- currentSession: { sessionId: "parent-session" },- initiatorAuth: null,- parent: {- continuationToken: "parent-token",- conversationId: "root-session",- lineage: {- callId: "call-remote",- rootSessionId: "root-session",- sessionId: "parent-session",- turn: { id: "parent-turn", sequence: 0 },- },- originAudience: { kind: "unknown" },- traceContext: undefined,- },- session: { sessionId: "parent-session" },- } as never);-- expect(startRemoteAgentSession).toHaveBeenCalledWith(- expect.objectContaining({- activityObserver: {- sink: parentObserver.sink,- workIdentity: expect.objectContaining({- callId: "call-remote",- kind: "remote-agent",- name: "research",- parentId: parentObserver.workIdentity.id,- rootSessionId: "root-session",- rootTurnId: "root-turn",- }),- },- }),- );- });-});diff --git a/packages/eve/src/subagents/start-remote.ts b/packages/eve/src/subagents/start-remote.tsdeleted file mode 100644index 125ae1cde..000000000--- a/packages/eve/src/subagents/start-remote.ts+++ /dev/null@@ -1,122 +0,0 @@-import type { DispatchOutcome, RuntimeSession } from "#subagents/handle-dispatch.js";-import { deriveChildActivityObserverConfig } from "#execution/activity-work.js";-import { createRemoteAgentStartFailureResult } from "#execution/dispatch-action-failures.js";-import { mintStartOperation } from "#execution/dispatch-start-operation.js";-import {- resolveRemoteAgentForAction,- startRemoteAgentSession,-} from "#subagents/remote-dispatch.js";-import { createLogger, logError } from "#internal/logging.js";-import type { RuntimeRemoteAgentDispatchRequest } from "#shared/action-types.js";-import type { CompiledBundle } from "#runtime/sessions/runtime-context-keys.js";-import type { SubagentParentContext } from "#subagents/invocation.js";--const log = createLogger("execution.subagent-start-remote");--/** Starts one remote subagent after dispatch planning has selected its target. */-export async function startRemoteSubagent(input: {- readonly action: RuntimeRemoteAgentDispatchRequest;- readonly auth: Parameters<typeof startRemoteAgentSession>[0]["auth"];- readonly bundle: CompiledBundle;- readonly callbackBaseUrl: string | undefined;- readonly currentSession: RuntimeSession;- readonly dynamicRemoteAgent?: NonNullable<- Parameters<typeof resolveRemoteAgentForAction>[0]["dynamicRemoteAgent"]- >;- readonly initiatorAuth: Parameters<typeof startRemoteAgentSession>[0]["initiatorAuth"];- readonly parent: SubagentParentContext;- readonly activityObserver?: Parameters<typeof startRemoteAgentSession>[0]["activityObserver"];- readonly session: RuntimeSession;-}): Promise<DispatchOutcome> {- const { action } = input;- const activityObserver = deriveChildActivityObserverConfig({- activityObserver: input.activityObserver,- callId: action.callId,- kind: "remote-agent",- name: action.remoteAgentName,- parentSessionId: input.session.sessionId,- parentTurnId: input.parent.lineage.turn.id,- });-- // Preflight resolution failures happen before ownership exists, so they- // reject without touching the handle store.- let callbackBaseUrl: string;- let resolvedRemote: ReturnType<typeof resolveRemoteAgentForAction>;- try {- if (input.callbackBaseUrl === undefined) {- throw new Error("Cannot dispatch remote agent without a callback base URL.");- }- callbackBaseUrl = input.callbackBaseUrl;- resolvedRemote = resolveRemoteAgentForAction({- dynamicRemoteAgent: input.dynamicRemoteAgent,- nodeId: action.nodeId,- remoteAgentName: action.remoteAgentName,- registry: input.bundle.subagentRegistry.subagentsByNodeId,- });- } catch (error) {- logError(log, "remote agent start failed", error, {- remoteAgentName: action.remoteAgentName,- nodeId: action.nodeId,- callId: action.callId,- });- return {- kind: "error",- result: createRemoteAgentStartFailureResult({ action, error }),- session: input.currentSession,- };- }-- const { operation } = mintStartOperation({- callId: action.callId,- name: action.remoteAgentName,- nodeId: action.nodeId,- parentSessionId: input.session.sessionId,- parentTurnId: input.parent.lineage.turn.id,- });- const credentialResolver = {- resolverId:- input.dynamicRemoteAgent === undefined- ? action.nodeId- : input.dynamicRemoteAgent.credentialsStepId,- };- try {- const child = await startRemoteAgentSession({- action,- auth: input.auth,- callbackBaseUrl,- originAudience: input.parent.originAudience,- initiatorAuth: input.initiatorAuth,- operationId: operation.id,- parent: input.parent,- activityObserver,- remote: resolvedRemote,- session: input.session,- });- const address = {- callbackBaseUrl,- credentialResolver,- kind: "agent/remote",- sessionId: child.sessionId,- url: resolvedRemote.url,- } as const;- return {- address,- callId: action.callId,- kind: "called",- name: action.name,- session: input.currentSession,- toolName: action.remoteAgentName,- };- } catch (error) {- logError(log, "remote agent start failed", error, {- remoteAgentName: action.remoteAgentName,- nodeId: action.nodeId,- callId: action.callId,- });- return {- kind: "error",- result: createRemoteAgentStartFailureResult({ action, error }),- session: input.currentSession,- };- }-}diff --git a/packages/eve/src/subagents/token-budget.test.ts b/packages/eve/src/subagents/token-budget.test.tsindex 512d6554e..34c0f1358 100644--- a/packages/eve/src/subagents/token-budget.test.ts+++ b/packages/eve/src/subagents/token-budget.test.ts@@ -100,62 +100,6 @@ describe("resolveRemainingSessionTokenLimits", () => {});});- it("splits the remaining quota across the batch's delegated calls", () => {- const session = createSessionWithUsage({- limits: { maxInputTokensPerSession: 1_000_000, maxOutputTokensPerSession: 50_000 },- usedInputTokens: 100_000,- usedOutputTokens: 20_000,- });-- expect(resolveRemainingSessionTokenLimits(session, 3)).toEqual({- maxInputTokensPerSession: 300_000,- maxOutputTokensPerSession: 10_000,- });- });-- it("splits the remaining model token-cost budget across delegated calls", () => {- const session = createSessionWithUsage({- limits: { maxTokenCostUsdPerSession: 1.5 },- usedCostUsd: 0.3,- });-- const limits = resolveRemainingSessionTokenLimits(session, 3);- expect(limits).toMatchObject({- maxInputTokensPerSession: false,- maxOutputTokensPerSession: false,- });- expect(limits.maxTokenCostUsdPerSession).toBeCloseTo(0.4);- });-- it("floors uneven splits so a batch can never exceed the remainder", () => {- const session = createSessionWithUsage({- limits: { maxInputTokensPerSession: 100 },- });-- expect(resolveRemainingSessionTokenLimits(session, 3)).toEqual({- maxInputTokensPerSession: 33,- maxOutputTokensPerSession: false,- });- });-- it("treats a non-positive fan-out as a single delegation", () => {- const session = createSessionWithUsage({- limits: { maxInputTokensPerSession: 100 },- });-- expect(resolveRemainingSessionTokenLimits(session, 0)).toEqual({- maxInputTokensPerSession: 100,- maxOutputTokensPerSession: false,- });- });-- it("keeps uncapped parents uncapped regardless of fan-out", () => {- expect(resolveRemainingSessionTokenLimits(createSessionWithUsage({}), 5)).toEqual({- maxInputTokensPerSession: false,- maxOutputTokensPerSession: false,- });- });-it("marks uncapped axes as false", () => {const session = createSessionWithUsage({limits: { maxOutputTokensPerSession: 50_000 },diff --git a/packages/eve/src/subagents/token-budget.ts b/packages/eve/src/subagents/token-budget.tsindex 12783b598..67f0288e5 100644--- a/packages/eve/src/subagents/token-budget.ts+++ b/packages/eve/src/subagents/token-budget.ts@@ -4,45 +4,25 @@ import type { HarnessSession } from "#harness/types.js";/*** Computes the session token limits a delegated child inherits from its- * parent: the parent's remaining runtime-limit quota split evenly across the- * batch's delegated calls, per axis, at dispatch time. `false` marks an axis- * with no inherited cap.- *- * Splitting by `fanoutSize` makes one dispatch batch collectively- * bounded by the parent's remainder. N parallel children cannot each spend- * the full remainder. Sequential batches see the quota net of completed- * children because their usage folds back into the parent's session totals.- * A granted continuation bumps the parent's runtime limit, so children- * dispatched after a grant draw from the fresh window.+ * parent: the parent's remaining runtime-limit quota, per axis, when the+ * child opens. `false` marks an axis with no inherited cap. A granted+ * continuation bumps the parent's runtime limit, so children opened after a+ * grant draw from the fresh window.*/export function resolveRemainingSessionTokenLimits(session: Pick<HarnessSession, "limits" | "state">,- fanoutSize = 1,): RunSessionLimits {- const normalizedFanoutSize = Math.max(1, Math.floor(fanoutSize));const remaining = getSessionRemainingUsageQuota(session);-const limits: {maxInputTokensPerSession: number | false;maxOutputTokensPerSession: number | false;maxTokenCostUsdPerSession?: number;} = {- maxInputTokensPerSession: grantTokenShare(remaining.inputTokens, normalizedFanoutSize),- maxOutputTokensPerSession: grantTokenShare(remaining.outputTokens, normalizedFanoutSize),+ maxInputTokensPerSession: remaining.inputTokens,+ maxOutputTokensPerSession: remaining.outputTokens,};- const maxTokenCostUsdPerSession = grantCostShare(remaining.costUsd, normalizedFanoutSize);- if (maxTokenCostUsdPerSession !== false) {- limits.maxTokenCostUsdPerSession = maxTokenCostUsdPerSession;+ if (remaining.costUsd !== false) {+ limits.maxTokenCostUsdPerSession = remaining.costUsd;}return limits;}--function grantTokenShare(remaining: number | false, fanOut: number): number | false {- if (remaining === false) return false;- return Math.floor(remaining / fanOut);-}--function grantCostShare(remaining: number | false, fanOut: number): number | false {- if (remaining === false) return false;- return remaining / fanOut;-}diff --git a/packages/eve/src/subagents/tool.test.ts b/packages/eve/src/subagents/tool.test.tsindex 837676c67..cf423aeaa 100644--- a/packages/eve/src/subagents/tool.test.ts+++ b/packages/eve/src/subagents/tool.test.ts@@ -335,22 +335,6 @@ describe("buildSubagentRunInput", () => {expect(runInput.input.outputSchema).toBeUndefined();});- it("treats an empty outputSchema as absent", () => {- const action: RuntimeSubagentDispatchRequest = {- ...makeAction(),- input: { message: "do something", outputSchema: {} },- };- const { runInput } = buildRuntimeSubagentRunInput({- action,- auth: null,- initiatorAuth: null,- session: makeSession(),- parent: makeParent(makeSession(), { id: "turn-0", sequence: 0 }),- });-- expect(runInput.input.outputSchema).toBeUndefined();- });-it("includes parentSandboxState and sandboxSessionId for self-delegation", () => {const sandboxState = { initialized: true, session: null };const session = { ...makeSession(), sandboxState };diff --git a/packages/eve/src/subagents/tool.ts b/packages/eve/src/subagents/tool.tsindex c54a2fd92..66fa18558 100644--- a/packages/eve/src/subagents/tool.ts+++ b/packages/eve/src/subagents/tool.ts@@ -1,9 +1,6 @@import { SUBAGENT_ADAPTER_KIND } from "#subagents/adapter-state.js";-import {- formatSubagentInput,- normalizeRequestedOutputSchema,- type SubagentParentContext,-} from "#subagents/invocation.js";+import { formatSubagentInput, type SubagentParentContext } from "#subagents/invocation.js";+import type { JsonObject } from "#shared/json.js";import type {ActivityObserverConfig,ChannelInstrumentationProjection,@@ -100,7 +97,6 @@ export function buildSubagentRunInput(input: {} = input;const childContinuationToken = mintSubagentContinuationToken(input.continuationKey);- const requestedOutputSchema = normalizeRequestedOutputSchema(action.input.outputSchema);const adapterState: Record<string, unknown> = {callId: action.callId,parentContinuationToken: input.parent.continuationToken ?? session.continuationToken,@@ -135,7 +131,8 @@ export function buildSubagentRunInput(input: {action,source,}),- outputSchema: requestedOutputSchema,+ // `ctx.agent` already dropped an empty schema, so what arrives is one to honor.+ outputSchema: action.input.outputSchema as JsonObject | undefined,},limits: input.limits,conversationId: input.parent.conversationId,diff --git a/packages/eve/src/tools/behavior.ts b/packages/eve/src/tools/behavior.tsindex 7564b0f6e..1e704207d 100644--- a/packages/eve/src/tools/behavior.ts+++ b/packages/eve/src/tools/behavior.ts@@ -1,4 +1,5 @@import type { WebSearchProvider } from "#shared/web-search.js";+import type { WorkflowToolEntryPoint } from "#tools/workflow-entry-point.js";/** Session facts that can hide a selected tool without changing source composition. */export type ToolAvailabilityCondition = "root-session";@@ -7,7 +8,11 @@ export type ToolAvailabilityCondition = "root-session";export type CompiledToolHandling =| { readonly kind: "dispatch"; readonly action: "self-agent" }| { readonly kind: "provider-tool"; readonly provider: WebSearchProvider }- | { readonly kind: "workflow-tool"; readonly workflowId: string };+ | {+ readonly kind: "workflow-tool";+ readonly entryPoint: WorkflowToolEntryPoint;+ readonly workflowId: string;+ };/** Closed, serializable behavior carried by one selected compiled tool. */export interface ToolExecutionShape {@@ -38,7 +43,11 @@ export type PreparedDispatchTarget =readonly nodeId: string;readonly subagentName: string;}- | { readonly kind: "workflow-tool-call"; readonly workflowId: string };+ | {+ readonly kind: "workflow-tool-call";+ readonly entryPoint: WorkflowToolEntryPoint;+ readonly workflowId: string;+ };/** Runtime-prepared handling consumed by the harness and execution boundary. */export type PreparedToolHandling =diff --git a/packages/eve/src/tools/definition.ts b/packages/eve/src/tools/definition.tsindex 0cff930de..97eabbb75 100644--- a/packages/eve/src/tools/definition.ts+++ b/packages/eve/src/tools/definition.ts@@ -153,8 +153,8 @@ export interface ToolInputRequestOptions {/*** Withdraws the request when it aborts: the channel stops offering the* question and the ask resolves as `cancelled`, unless the session accepted- * an answer first, which the ask then resolves with. Pass- * `ctx.interruptSignal` to stop asking once a new message arrives.+ * an answer first, which the ask then resolves with. The call's+ * `abortSignal` withdraws the request the same way without being passed.*/readonly signal?: AbortSignal;}@@ -357,7 +357,7 @@ export function stampToolDefinition<readonly description: string;readonly inputSchema?: unknown;readonly outputSchema?: unknown;- readonly execute: (...args: never[]) => unknown;+ readonly execute?: (...args: never[]) => unknown;readonly label?: ToolLabelDefinition;readonly approval?: Approval<never>;readonly approvalKey?: (...args: never[]) => unknown;diff --git a/packages/eve/src/tools/durable-callbacks.ts b/packages/eve/src/tools/durable-callbacks.tsindex 6350d9ad6..4ac7fc336 100644--- a/packages/eve/src/tools/durable-callbacks.ts+++ b/packages/eve/src/tools/durable-callbacks.ts@@ -273,7 +273,7 @@ export function collectDurableDynamicToolCallbacks(input: {};readonly approval?: Approval<never>;readonly approvalKey?: (...args: never[]) => unknown;- readonly execute: (...args: never[]) => unknown;+ readonly execute?: (...args: never[]) => unknown;readonly toModelOutput?: (...args: never[]) => unknown;}): LiveDurableDynamicToolCallbacks {const labelComplete = readDurableDynamicCallback(input.label?.complete);diff --git a/packages/eve/src/tools/framework/agent-contract.ts b/packages/eve/src/tools/framework/agent-contract.tsindex 95275db64..6994127ad 100644--- a/packages/eve/src/tools/framework/agent-contract.ts+++ b/packages/eve/src/tools/framework/agent-contract.ts@@ -1,31 +1,21 @@+import type { AgentToolInput } from "#runtime/subagents/workflow.js";import { defineJsonSchema } from "#tools/schema.js";export const AGENT_TOOL_NAME = "agent";export const AGENT_TOOL_DESCRIPTION = [- "Delegate a focused subtask to a copy of yourself, or continue a previous delegation with `agentId`.",+ "Delegate a focused subtask to a copy of yourself.","Use it to isolate complex work or split a large task into independent pieces.","Issue multiple `agent` calls in one response to run a small fixed set in parallel.",- "A new child has fresh history and state but reuses your tools and sandbox, so include essential context in `message` and give parallel writers non-overlapping scopes.",+ "A new child has fresh history and state but reuses your tools and sandbox, so give parallel writers non-overlapping scopes.",].join(" ");-export interface SubagentToolInput {- agentId?: string | null;- message: string;-}--export const SUBAGENT_TOOL_INPUT_SCHEMA = defineJsonSchema<SubagentToolInput>({+export const SUBAGENT_TOOL_INPUT_SCHEMA = defineJsonSchema<AgentToolInput>({type: "object",properties: {- agentId: {- type: ["string", "null"],- description:- "The id of an existing agent from the <agents> list. Omit this field (or pass null or an empty string) to start a new agent.",- },message: {type: "string",- description:- "The message to send to the subagent. Provide all context the subagent needs to complete the task; the subagent does not see the parent's history.",+ description: "The message to send to the agent, with everything it needs to do the work.",},},required: ["message"],diff --git a/packages/eve/src/tools/provided/agent-router.test.ts b/packages/eve/src/tools/provided/agent-router.test.tsindex d912f502a..87bb8f9d2 100644--- a/packages/eve/src/tools/provided/agent-router.test.ts+++ b/packages/eve/src/tools/provided/agent-router.test.ts@@ -1,7 +1,7 @@import { beforeEach, describe, expect, it, vi } from "vitest";import { agentRouter } from "#tools/provided/agent-router.js";-import { executeAgentRouterTool } from "#execution/tools/agent-router.js";+import { runAgentRouterTask } from "#execution/tools/agent-router.js";import { evaluate } from "#ai/evaluate.js";import type { WorkflowToolContext } from "#tools/workflow-definition.js";@@ -10,12 +10,12 @@ vi.mock("#ai/evaluate.js", () => ({ evaluate: vi.fn() }));describe("agentRouter", () => {beforeEach(() => vi.clearAllMocks());- it("defines a workflow tool", () => {+ it("defines a task tool", () => {const definition = agentRouter();expect(definition.availableInSubagents).toBe(false);expect(definition.description).toContain("best available subagent");- expect(definition.execute).toBe(executeAgentRouterTool);+ expect(definition.task).toBe(runAgentRouterTask);});it("routes through all workflow agent descriptions", async () => {@@ -33,7 +33,7 @@ describe("agentRouter", () => {},});- await expect(executeAgentRouterTool({ message: "Deploy the service" }, ctx)).resolves.toBe(+ await expect(runAgentRouterTask({ message: "Deploy the service" }, ctx)).resolves.toBe("operated",);expect(evaluate).toHaveBeenCalledWith({@@ -64,9 +64,7 @@ describe("agentRouter", () => {},});- await expect(executeAgentRouterTool({ message: "Investigate" }, ctx)).resolves.toBe(- "researched",- );+ await expect(runAgentRouterTask({ message: "Investigate" }, ctx)).resolves.toBe("researched");expect(evaluate).not.toHaveBeenCalled();expect(agent).toHaveBeenCalledWith("researcher");expect(send).toHaveBeenCalledWith("Investigate", { signal: expect.any(AbortSignal) });@@ -79,9 +77,7 @@ describe("agentRouter", () => {agents: { researcher: { description: "Investigate and explain." } },});- await expect(executeAgentRouterTool({ message: "Investigate" }, ctx)).resolves.toBe(- "researched",- );+ await expect(runAgentRouterTask({ message: "Investigate" }, ctx)).resolves.toBe("researched");expect(evaluate).not.toHaveBeenCalled();expect(agent).toHaveBeenCalledWith("researcher");expect(send).toHaveBeenCalledWith("Investigate", { signal: expect.any(AbortSignal) });@@ -93,7 +89,7 @@ describe("agentRouter", () => {agents: { agent: { description: " " } },});- await expect(executeAgentRouterTool({ message: "Route me" }, ctx)).rejects.toThrow(+ await expect(runAgentRouterTask({ message: "Route me" }, ctx)).rejects.toThrow("agentRouter requires at least one available agent with a description.",);expect(evaluate).not.toHaveBeenCalled();diff --git a/packages/eve/src/tools/provided/agent-router.ts b/packages/eve/src/tools/provided/agent-router.tsindex 0716fe14c..ba6634c17 100644--- a/packages/eve/src/tools/provided/agent-router.ts+++ b/packages/eve/src/tools/provided/agent-router.ts@@ -2,21 +2,24 @@ import type { JsonValue } from "#shared/json.js";import {AGENT_ROUTER_INPUT_SCHEMA,AGENT_ROUTER_TOOL_DESCRIPTION,- executeAgentRouterTool,+ runAgentRouterTask,type AgentRouterInput,} from "#execution/tools/agent-router.js";-import { defineWorkflowTool, type WorkflowToolDefinition } from "#tools/workflow-definition.js";+import { defineWorkflowTool, type WorkflowTaskToolDefinition } from "#tools/workflow-definition.js";export type { AgentRouterInput };-export type AgentRouterTool = WorkflowToolDefinition<AgentRouterInput, JsonValue>;+export type AgentRouterTool = WorkflowTaskToolDefinition<AgentRouterInput, JsonValue>;-/** Defines a workflow tool that uses JEV to route a task across all available agent targets. */+/**+ * Defines a workflow tool that uses JEV to route a task across all available+ * agent targets. Each call runs as a task.+ */export function agentRouter(): AgentRouterTool {return defineWorkflowTool({availableInSubagents: false,description: AGENT_ROUTER_TOOL_DESCRIPTION,- execute: executeAgentRouterTool,inputSchema: AGENT_ROUTER_INPUT_SCHEMA,+ task: runAgentRouterTask,});}diff --git a/packages/eve/src/tools/provided/ask-question-workflow.ts b/packages/eve/src/tools/provided/ask-question-workflow.tsindex f351627de..95355698f 100644--- a/packages/eve/src/tools/provided/ask-question-workflow.ts+++ b/packages/eve/src/tools/provided/ask-question-workflow.ts@@ -12,7 +12,7 @@ export async function executeAskQuestionTool(): Promise<AskQuestionOutput> {"use workflow";- const answer = await ctx.ask(toAskQuestionRequest(input), { signal: ctx.interruptSignal });+ const answer = await ctx.ask(toAskQuestionRequest(input));return toAskQuestionOutput(answer);}diff --git a/packages/eve/src/tools/provided/ask-question.test.ts b/packages/eve/src/tools/provided/ask-question.test.tsindex d8bd7839f..e270f832a 100644--- a/packages/eve/src/tools/provided/ask-question.test.ts+++ b/packages/eve/src/tools/provided/ask-question.test.ts@@ -32,16 +32,11 @@ describe("askQuestion", () => {expect(isWorkflowToolDefinition(definition)).toBe(true);expect(definition.description).toBe(ASK_QUESTION_TOOL_DESCRIPTION);- const interruptSignal = new AbortController().signal;- await expect(- definition.execute(colorQuestion, { ask, interruptSignal } as never),- ).resolves.toEqual({+ await expect(definition.execute(colorQuestion, { ask } as never)).resolves.toEqual({answer: "Blue",status: "answered",});- expect(ask).toHaveBeenCalledExactlyOnceWith(toAskQuestionRequest(colorQuestion), {- signal: interruptSignal,- });+ expect(ask).toHaveBeenCalledExactlyOnceWith(toAskQuestionRequest(colorQuestion));});it("accepts one question with at most three label and description options", () => {diff --git a/packages/eve/src/tools/provided/ask-question.ts b/packages/eve/src/tools/provided/ask-question.tsindex 14cd2110c..1e8b6a30e 100644--- a/packages/eve/src/tools/provided/ask-question.ts+++ b/packages/eve/src/tools/provided/ask-question.ts@@ -1,4 +1,4 @@-import { defineWorkflowTool, type WorkflowToolDefinition } from "#public/tools/index.js";+import { defineWorkflowTool, type WorkflowExecuteToolDefinition } from "#public/tools/index.js";import { executeAskQuestionTool } from "#tools/provided/ask-question-workflow.js";import {INTERRUPTED_OUTPUT_SCHEMA,@@ -116,7 +116,7 @@ const ASK_QUESTION_OUTPUT_SCHEMA = defineJsonSchema<AskQuestionOutput>({* turn waits for the answer without holding an application runtime open. A new* message that does not answer the question withdraws it.*/-export function askQuestion(): WorkflowToolDefinition<AskQuestionInput, AskQuestionOutput> {+export function askQuestion(): WorkflowExecuteToolDefinition<AskQuestionInput, AskQuestionOutput> {return defineWorkflowTool({description: ASK_QUESTION_TOOL_DESCRIPTION,execute: executeAskQuestionTool,diff --git a/packages/eve/src/tools/provided/sleep-workflow.ts b/packages/eve/src/tools/provided/sleep-workflow.tsindex 1ca0e9d09..2e62344fe 100644--- a/packages/eve/src/tools/provided/sleep-workflow.ts+++ b/packages/eve/src/tools/provided/sleep-workflow.ts@@ -11,7 +11,7 @@ export async function executeSleepTool("use workflow";const interrupted = new Promise<"interrupted">((resolve) =>- ctx.interruptSignal.addEventListener("abort", () => resolve("interrupted"), { once: true }),+ ctx.abortSignal.addEventListener("abort", () => resolve("interrupted"), { once: true }),);const elapsed = sleep(Math.ceil(input.seconds * 1_000)).then(() => "elapsed" as const);const woke = await Promise.race([elapsed, interrupted]);diff --git a/packages/eve/src/tools/provided/sleep.test.ts b/packages/eve/src/tools/provided/sleep.test.tsindex 13e7bf7c9..b7ad79730 100644--- a/packages/eve/src/tools/provided/sleep.test.ts+++ b/packages/eve/src/tools/provided/sleep.test.ts@@ -30,8 +30,8 @@ describe("sleep", () => {}),);const definition = sleep();- const interruptSignal = new AbortController().signal;- const output = definition.execute({ seconds: 2.5001 }, { interruptSignal } as never);+ const abortSignal = new AbortController().signal;+ const output = definition.execute({ seconds: 2.5001 }, { abortSignal } as never);await vi.waitFor(() => {expect(workflowSleep).toHaveBeenCalledExactlyOnceWith(2_501);diff --git a/packages/eve/src/tools/provided/sleep.ts b/packages/eve/src/tools/provided/sleep.tsindex 2f467c801..2546eb906 100644--- a/packages/eve/src/tools/provided/sleep.ts+++ b/packages/eve/src/tools/provided/sleep.ts@@ -1,4 +1,4 @@-import { defineWorkflowTool, type WorkflowToolDefinition } from "#public/tools/index.js";+import { defineWorkflowTool, type WorkflowExecuteToolDefinition } from "#public/tools/index.js";import {INTERRUPTED_OUTPUT_SCHEMA,toInterruptibleModelOutput,@@ -58,7 +58,7 @@ const SLEEP_OUTPUT_SCHEMA = defineJsonSchema<SleepToolOutput>({* Each call runs as a durable workflow, so the wait does not hold an* application runtime open. A new message ends the wait early.*/-export function sleep(): WorkflowToolDefinition<SleepToolInput, SleepToolOutput> {+export function sleep(): WorkflowExecuteToolDefinition<SleepToolInput, SleepToolOutput> {return defineWorkflowTool({description: SLEEP_TOOL_DESCRIPTION,execute: executeSleepTool,diff --git a/packages/eve/src/tools/provided/task-cancel.ts b/packages/eve/src/tools/provided/task-cancel.tsnew file mode 100644index 000000000..b8e5815d5--- /dev/null+++ b/packages/eve/src/tools/provided/task-cancel.ts@@ -0,0 +1,26 @@+import { TASK_CANCEL_TOOL_NAME } from "#execution/tasks/calls.js";+import {+ TASK_CANCEL_DESCRIPTION,+ TASK_CANCEL_TASK_ID_DESCRIPTION,+} from "#execution/tasks/render.js";+import type { HarnessToolDefinition } from "#harness/execute-tool.js";+import { defineJsonSchema } from "#tools/schema.js";++export interface TaskCancelInput {+ readonly taskId: string;+}++/** `task_cancel`, offered to agents that can start tasks; the session answers each call. */+export const taskCancelTool: HarnessToolDefinition = {+ description: TASK_CANCEL_DESCRIPTION,+ frameworkAction: "task-cancel",+ inputSchema: defineJsonSchema<TaskCancelInput>({+ type: "object",+ properties: {+ taskId: { type: "string", minLength: 1, description: TASK_CANCEL_TASK_ID_DESCRIPTION },+ },+ required: ["taskId"],+ additionalProperties: false,+ }),+ name: TASK_CANCEL_TOOL_NAME,+};diff --git a/packages/eve/src/tools/provided/task-wait.ts b/packages/eve/src/tools/provided/task-wait.tsnew file mode 100644index 000000000..facf179cb--- /dev/null+++ b/packages/eve/src/tools/provided/task-wait.ts@@ -0,0 +1,25 @@+import { TASK_WAIT_TOOL_NAME } from "#execution/tasks/calls.js";+import { TASK_WAIT_DESCRIPTION, TASK_WAIT_TIMEOUT_DESCRIPTION } from "#execution/tasks/render.js";+import type { HarnessToolDefinition } from "#harness/execute-tool.js";+import { defineJsonSchema } from "#tools/schema.js";++export interface TaskWaitInput {+ readonly timeout?: number;+}++/**+ * `task_wait`, offered to agents that can start tasks. It is not a workflow tool: the+ * call defers out of the model step and the session parks the turn itself.+ */+export const taskWaitTool: HarnessToolDefinition = {+ description: TASK_WAIT_DESCRIPTION,+ frameworkAction: "task-wait",+ inputSchema: defineJsonSchema<TaskWaitInput>({+ type: "object",+ properties: {+ timeout: { type: "integer", minimum: 0, description: TASK_WAIT_TIMEOUT_DESCRIPTION },+ },+ additionalProperties: false,+ }),+ name: TASK_WAIT_TOOL_NAME,+};diff --git a/packages/eve/src/tools/provided/workflow.test.ts b/packages/eve/src/tools/provided/workflow.test.tsindex 4734ea2ed..4c4ae0a01 100644--- a/packages/eve/src/tools/provided/workflow.test.ts+++ b/packages/eve/src/tools/provided/workflow.test.ts@@ -6,7 +6,7 @@ vi.mock("#execution/dynamic-workflow/workflow.js", async (importOriginal) => ({runJsProgram: mocks.runJsProgram,}));-import { executeWorkflowProgram } from "#execution/dynamic-workflow/tool.js";+import { runWorkflowProgramTask } from "#execution/dynamic-workflow/tool.js";import { normalizeToolDefinition } from "#internal/authored-definition/schema-backed.js";import { workflow } from "#tools/provided/workflow.js";import { readWorkflowProgramOptions } from "#tools/workflow-program-input.js";@@ -32,7 +32,7 @@ describe("workflow", () => {);expect(definition.description).not.toContain("Available agents");expect(definition.description).toContain("at most 7 agents");- expect(definition.execute).toBe(executeWorkflowProgram);+ expect(definition.task).toBe(runWorkflowProgramTask);const inputSchema = serializeInputSchema(definition.inputSchema);expect(inputSchema).toMatchObject({@@ -59,8 +59,8 @@ describe("workflow", () => {});it("preserves the trusted budget in the compiled definition", () => {- const previousWorkflowId = Reflect.get(executeWorkflowProgram, "workflowId");- Reflect.set(executeWorkflowProgram, "workflowId", "workflow//test//executeWorkflowProgram");+ const previousWorkflowId = Reflect.get(runWorkflowProgramTask, "workflowId");+ Reflect.set(runWorkflowProgramTask, "workflowId", "workflow//test//runWorkflowProgramTask");try {const normalized = normalizeToolDefinition(workflow({ maxSubagents: 4 }),@@ -74,9 +74,9 @@ describe("workflow", () => {});} finally {if (previousWorkflowId === undefined) {- Reflect.deleteProperty(executeWorkflowProgram, "workflowId");+ Reflect.deleteProperty(runWorkflowProgramTask, "workflowId");} else {- Reflect.set(executeWorkflowProgram, "workflowId", previousWorkflowId);+ Reflect.set(runWorkflowProgramTask, "workflowId", previousWorkflowId);}}});@@ -91,7 +91,7 @@ describe("workflow", () => {mocks.runJsProgram.mockResolvedValue({ ok: true });const ctx = { callId: "call" } as never;- await expect(executeWorkflowProgram({ js: "return 1", maxSubagents: 3 }, ctx)).resolves.toEqual(+ await expect(runWorkflowProgramTask({ js: "return 1", maxSubagents: 3 }, ctx)).resolves.toEqual({ ok: true },);expect(mocks.runJsProgram).toHaveBeenCalledWith("return 1", ctx, {diff --git a/packages/eve/src/tools/provided/workflow.ts b/packages/eve/src/tools/provided/workflow.tsindex 00667f612..394d93371 100644--- a/packages/eve/src/tools/provided/workflow.ts+++ b/packages/eve/src/tools/provided/workflow.ts@@ -2,9 +2,9 @@ import {DEFAULT_WORKFLOW_PROGRAM_MAX_SUBAGENTS,parseWorkflowProgramOptions,} from "#execution/dynamic-workflow/schema.js";-import { executeWorkflowProgram } from "#execution/dynamic-workflow/tool.js";+import { runWorkflowProgramTask } from "#execution/dynamic-workflow/tool.js";import type { JsonValue } from "#shared/json.js";-import { defineWorkflowTool, type WorkflowToolDefinition } from "#tools/workflow-definition.js";+import { defineWorkflowTool, type WorkflowTaskToolDefinition } from "#tools/workflow-definition.js";import { attachWorkflowProgramOptions } from "#tools/workflow-program-input.js";import { defineJsonSchema } from "#tools/schema.js";@@ -17,7 +17,7 @@ export interface WorkflowToolInput {readonly js: string;}-export type WorkflowTool = WorkflowToolDefinition<WorkflowToolInput, JsonValue>;+export type WorkflowTool = WorkflowTaskToolDefinition<WorkflowToolInput, JsonValue>;const workflowProgramAgentContract ="Call ctx.agent(name, { message: string, outputSchema?: object }). Each call starts a new agent that does not see this conversation, so put everything it needs in message. It resolves directly to the agent's reply; when outputSchema is provided, the reply matches that schema. It does not return an agent metadata wrapper. The owning agent resolves the target and applies its existing availability and authorization checks.";@@ -46,8 +46,8 @@ export function workflow(options: WorkflowToolOptions = {}): WorkflowTool {return attachWorkflowProgramOptions(defineWorkflowTool({description,- execute: executeWorkflowProgram,inputSchema: workflowInputSchema,+ task: runWorkflowProgramTask,}),normalized,);diff --git a/packages/eve/src/tools/schema.ts b/packages/eve/src/tools/schema.tsindex bbcec56eb..b712acae0 100644--- a/packages/eve/src/tools/schema.ts+++ b/packages/eve/src/tools/schema.ts@@ -132,6 +132,66 @@ export function defineJsonSchema<T = unknown>(/** Schemas built by {@link defineJsonSchema}, which reach the model exactly as written. */const plainJsonSchemas = new WeakSet<object>();+/** An optional string property added to an input schema. */+export interface OptionalStringProperty {+ readonly description: string;+ readonly name: string;+}++/**+ * Extends an object input schema with an optional string property that the+ * schema itself never sees: validation splits the property off, validates the+ * rest with `schema`, and returns the property alongside the result. A plain+ * JSON Schema stays advertised as written.+ */+export function withOptionalStringProperty(+ schema: ToolSchema,+ property: OptionalStringProperty,+): ToolSchema {+ const emit = (): Record<string, unknown> =>+ addOptionalStringProperty(serializeInputSchema(schema), property);+ const extended = {+ "~standard": {+ version: 1,+ vendor: "eve",+ validate: (value: unknown) => validateWithProperty(schema, property.name, value),+ jsonSchema: { input: emit, output: emit },+ },+ } as ToolSchema;+ if (plainJsonSchemas.has(schema)) plainJsonSchemas.add(extended);+ return extended;+}++function addOptionalStringProperty(+ schema: JsonObject,+ property: OptionalStringProperty,+): Record<string, unknown> {+ const properties = isObject(schema.properties) ? schema.properties : {};+ return {+ ...schema,+ type: schema.type ?? "object",+ properties: {+ ...properties,+ [property.name]: { description: property.description, type: "string" },+ },+ };+}++async function validateWithProperty(+ schema: ToolSchema,+ name: string,+ value: unknown,+): Promise<StandardSchemaV1.Result<unknown>> {+ if (!isObject(value) || !(name in value)) return await schema["~standard"].validate(value);+ const { [name]: propertyValue, ...rest } = value;+ if (typeof propertyValue !== "string") {+ return { issues: [{ message: `Expected "${name}" to be a string.`, path: [name] }] };+ }+ const result = await schema["~standard"].validate(rest);+ if (result.issues !== undefined || !isObject(result.value)) return result;+ return { value: { ...result.value, [name]: propertyValue } };+}+/*** Permissive schema lowered onto model-visible tools whose definitions* declare no input schema. Accepts any input — an absent schema declares nodiff --git a/packages/eve/src/tools/workflow-definition.test.ts b/packages/eve/src/tools/workflow-definition.test.tsindex 6b57b8cb1..0dab1f448 100644--- a/packages/eve/src/tools/workflow-definition.test.ts+++ b/packages/eve/src/tools/workflow-definition.test.ts@@ -7,6 +7,8 @@ import {isWorkflowToolDefinition,type AgentMessageResult,type WorkflowAgentMetadata,+ type WorkflowServeCall,+ type WorkflowServeContext,type WorkflowStepToolContext,type WorkflowToolContext,} from "#tools/workflow-definition.js";@@ -48,6 +50,51 @@ describe("defineWorkflowTool", () => {expectTypeOf(definition.execute).parameter(0).toEqualTypeOf<{ service: string }>();});+ it("infers a task's input and gives it the context of an execute call", () => {+ const definition = defineWorkflowTool({+ description: "Deploy",+ inputSchema: z.object({ service: z.string() }),+ async task(input, ctx) {+ expectTypeOf(input).toEqualTypeOf<{ service: string }>();+ expectTypeOf(ctx).toEqualTypeOf<WorkflowToolContext>();+ return { deployed: input.service };+ },+ });+ expectTypeOf(definition.task).parameter(0).toEqualTypeOf<{ service: string }>();+ });++ it("types a serve body's calls by inputSchema and its replies by outputSchema", () => {+ const definition = defineWorkflowTool({+ description: "Draft a release plan and revise it on request.",+ inputSchema: z.object({ request: z.string() }),+ outputSchema: z.object({ steps: z.array(z.string()) }),+ async serve(receive, ctx) {+ const call = await receive();+ expectTypeOf(call).toEqualTypeOf<WorkflowServeCall<{ request: string }>>();+ expectTypeOf(ctx).toEqualTypeOf<WorkflowServeContext<{ steps: string[] }>>();+ // @ts-expect-error Each call carries its own abortSignal.+ void ctx.abortSignal;+ ctx.reply({ steps: [call.input.request] });+ // @ts-expect-error A reply matches outputSchema.+ ctx.reply({ steps: "freeze" });+ return { steps: [] };+ },+ });+ expectTypeOf(definition.serve)+ .parameter(0)+ .returns.resolves.toEqualTypeOf<WorkflowServeCall<{ request: string }>>();+ });++ it.each([+ ["none", {}],+ ["execute and task", { execute: async () => null, task: async () => null }],+ ])("requires exactly one entry point (%s)", (found, entryPoints) => {+ const definition = { description: "Deploy", inputSchema: {}, ...entryPoints };+ expect(() => defineWorkflowTool(definition as never)).toThrow(+ `Define exactly one of execute(input, ctx), task(input, ctx), or serve(receive, ctx); this tool defines ${found}.`,+ );+ });+it("exposes only step-safe capabilities on WorkflowStepToolContext", () => {const useStepContext = (ctx: WorkflowStepToolContext) => {void ctx.getToken;@@ -64,7 +111,7 @@ describe("defineWorkflowTool", () => {expectTypeOf(useStepContext).parameter(0).toEqualTypeOf<WorkflowStepToolContext>();});- it("rejects the removed execution option", () => {+ it("rejects the replaced execution option", () => {const definition = {description: "Report a deployment",execution: "background",@@ -74,7 +121,7 @@ describe("defineWorkflowTool", () => {},};expect(() => defineWorkflowTool(definition)).toThrow(- '"execution" was removed; workflow tool calls now block until they settle.',+ '"execution" was replaced by task(). Define task(input, ctx) to run each call as a task.',);});diff --git a/packages/eve/src/tools/workflow-definition.ts b/packages/eve/src/tools/workflow-definition.tsindex 181efd5a8..1068f4414 100644--- a/packages/eve/src/tools/workflow-definition.ts+++ b/packages/eve/src/tools/workflow-definition.ts@@ -14,6 +14,12 @@ import {type ToolInputResponse,} from "#tools/definition.js";import type { ToolModelOutput } from "#tools/model-output.js";+import {+ WORKFLOW_TOOL_ENTRY_POINTS,+ type WorkflowToolEntryPoint,+} from "#tools/workflow-entry-point.js";++export type { WorkflowToolEntryPoint };export interface WorkflowAgentMetadata {readonly description: string;@@ -37,12 +43,16 @@ export interface AgentSendOptions<TOutput = unknown> {* How one agent turn ended, as the client's `MessageResult` reports it:* `"waiting"` when the session waits for its next message, including after a* cancelled turn, which carries neither `data` nor `message`; `"completed"`- * when the session ended with the turn; and `"failed"` when the turn failed.+ * when the session ended with the turn; and `"failed"` when the turn failed,+ * with the reason in `error`.*/export type AgentMessageResult<TOutput = unknown> = Pick<MessageResult<TOutput>,"data" | "message" | "status"->;+> & {+ /** Why the turn failed, present only when `status` is `"failed"`. */+ readonly error?: { readonly message: string };+};/** The response to one message sent to a `ctx.agent` session. */export interface AgentResponse<TOutput = unknown> {@@ -57,7 +67,8 @@ export interface AgentResponse<TOutput = unknown> {export interface AgentSession {/*** Delivers a message. It joins the session's running turn, whose result the- * response resolves, or starts the next turn when the session is idle.+ * response resolves, or starts the next turn when the session is idle or the+ * running turn ends before the agent reads it.*/send<TOutput = unknown>(message: string,@@ -65,13 +76,10 @@ export interface AgentSession {): Promise<AgentResponse<TOutput>>;}-/**- * Context supplied to a workflow tool body. When passed directly to a step,- * eve replaces it with {@link WorkflowStepToolContext}.- */-export type WorkflowToolContext = Pick<+/** Members the context of every workflow tool entry point shares. */+export type WorkflowSharedContext = Pick<ToolContext,- "abortSignal" | "callId" | "session" | "toolName" | "getToken" | "requireAuth"+ "session" | "toolName" | "getToken" | "requireAuth"> & {/*** Returns a new session with the agent of this invocation name. Nothing@@ -86,74 +94,259 @@ export type WorkflowToolContext = Pick<* `options.signal` or the call's `abortSignal` aborts.*/ask(request: ToolInputRequest, options?: ToolInputRequestOptions): PromiseLike<ToolInputResponse>;+};++/**+ * Context of an `execute(input, ctx)` or `task(input, ctx)` call. When passed+ * directly to a step, eve replaces it with {@link WorkflowStepToolContext}.+ */+export type WorkflowToolContext = WorkflowSharedContext &+ Pick<ToolContext, "callId"> & {+ /**+ * Aborts when the call's work should stop: the call is cancelled, by+ * `task_cancel`, `session.cancel()`, a failed turn, or the end of the+ * session, or, for an `execute` call, a steering message arrives while the+ * turn waits on it. Stop and return what you have. After a steering+ * message the call settles with what the body returns, or with+ * `{ interrupted: true }` if it rejects; a cancelled call's result is+ * discarded. A task never sees a steering message.+ */+ readonly abortSignal: AbortSignal;+ };++/**+ * One call a `serve` body receives: the call that started the task, or a+ * later call the model made with the task's `taskId`.+ */+export interface WorkflowServeCall<TInput = unknown> {+ readonly callId: string;+ /** The call's input, validated by the tool's `inputSchema`. */+ readonly input: TInput;+ /**+ * Aborts when the task's current stretch of work is cancelled or the+ * session ends. A stretch starts when a call reaches an idle task and ends+ * when a reply or a cancel settles its calls; calls that arrive during it+ * share its signal, and the next stretch gets a new one.+ */+ readonly abortSignal: AbortSignal;+}++/**+ * Resolves with the task's next call. The first `receive()` resolves at once+ * with the call that started the task; each later one with the next call made+ * with the task's `taskId`, in arrival order. A pending `receive()` is shared:+ * calling it again returns the same promise. A call counts as received once its+ * promise resolves, even if that promise lost a `Promise.race`, and the next+ * `ctx.reply()` settles it, so keep a raced promise until you read its call.+ * It rejects when the session ends.+ */+export type WorkflowServeReceive<TInput = unknown> = () => Promise<WorkflowServeCall<TInput>>;++/**+ * Context of a `serve(receive, ctx)` task. Each call brings its own `callId`+ * and `abortSignal` from `receive()`, and steering never interrupts a task, so+ * the context has neither. `session` (its turn and auth) and `agents`+ * describe the latest call received, the call the body serves now. A session+ * opened with `agent()` is the child of the call served when it opens, and+ * each message sent to it carries the auth of the call served when it is sent.+ * `ctx.ask` throws while no call is+ * waiting for a result. When passed directly to a step, eve replaces it with+ * {@link WorkflowStepToolContext} for the latest call waiting for a result.+ */+export type WorkflowServeContext<TOutput = unknown> = WorkflowSharedContext & {/**- * Aborts once, on the first steering message that arrives while the turn- * waits on this call. What it means is the tool's choice: a body that- * ignores it keeps going, and one that should stop early races or passes it.+ * Settles every call received so far with `output`, and the task goes idle+ * until its next call. A reply with no call left to settle, including one+ * after a cancel, is dropped.*/- readonly interruptSignal: AbortSignal;+ reply(output: TOutput): void;};const WORKFLOW_TOOL_BRAND = Symbol.for("eve:workflow-tool-brand");-/** A static tool whose executor runs as a durable workflow. Its executor must start with "use workflow". */-export interface WorkflowToolDefinition<- TInput = unknown,- TOutput = unknown,-> extends PublicToolDefinition<TInput, TOutput> {+interface WorkflowToolDefinitionBase<TInput, TOutput> extends PublicToolDefinition<+ TInput,+ TOutput+> {readonly [WORKFLOW_TOOL_BRAND]: true;- execute(input: TInput, ctx: WorkflowToolContext): Promise<TOutput> | AsyncIterable<TOutput>;approval?: Approval<unknown extends TInput ? Record<string, unknown> : TInput>;toModelOutput?: (output: TOutput) => ToolModelOutput | Promise<ToolModelOutput>;}+/** A workflow tool whose calls are ordinary tool calls: the turn waits until each settles. */+export interface WorkflowExecuteToolDefinition<+ TInput = unknown,+ TOutput = unknown,+> extends WorkflowToolDefinitionBase<TInput, TOutput> {+ execute(input: TInput, ctx: WorkflowToolContext): Promise<TOutput> | AsyncIterable<TOutput>;+ task?: never;+ serve?: never;+}++/**+ * A workflow tool whose every call runs as a task: the model gets a receipt at+ * once and the conversation continues, and the result arrives later in a+ * `task.result` message.+ */+export interface WorkflowTaskToolDefinition<+ TInput = unknown,+ TOutput = unknown,+> extends WorkflowToolDefinitionBase<TInput, TOutput> {+ task(input: TInput, ctx: WorkflowToolContext): Promise<TOutput> | AsyncIterable<TOutput>;+ execute?: never;+ serve?: never;+}++/**+ * A workflow tool whose calls reach resumable tasks. A call without `taskId`+ * starts a task, whose body runs once and gets that call and every later call+ * made with its `taskId` from `receive()`; each `ctx.reply()` delivers a+ * result. eve adds the optional `taskId` to the tool's model input, so+ * `inputSchema` must not declare its own. Returning settles the calls still+ * waiting and ends the task; throwing fails them.+ */+export interface WorkflowServeToolDefinition<+ TInput = unknown,+ TOutput = unknown,+> extends WorkflowToolDefinitionBase<TInput, TOutput> {+ serve(+ receive: WorkflowServeReceive<TInput>,+ ctx: WorkflowServeContext<TOutput>,+ ): Promise<TOutput>;+ execute?: never;+ task?: never;+}++/**+ * A static tool whose entry point runs as a durable workflow and must start+ * with "use workflow". It defines exactly one entry point.+ */+export type WorkflowToolDefinition<TInput = unknown, TOutput = unknown> =+ | WorkflowExecuteToolDefinition<TInput, TOutput>+ | WorkflowTaskToolDefinition<TInput, TOutput>+ | WorkflowServeToolDefinition<TInput, TOutput>;++type Unbranded<T> = T extends unknown ? Omit<T, typeof WORKFLOW_TOOL_BRAND> : never;type WorkflowReturn<T> = T extends AsyncIterable<infer Output> ? Output : Awaited<T>;type Schema = StandardSchemaV1<unknown, unknown> | StandardJSONSchemaV1<unknown, unknown>;-type Definition<TInput, TReturn> = Omit<- WorkflowToolDefinition<TInput, WorkflowReturn<TReturn>>,- typeof WORKFLOW_TOOL_BRAND | "execute"-> & {+type EntryPointReturn<TOutput> = Promise<TOutput> | AsyncIterable<TOutput>;+type InferOutput<TSchema extends StandardJSONSchemaV1<unknown, unknown>> =+ StandardJSONSchemaV1.InferOutput<TSchema>;+type InferInput<TSchema extends Schema> = StandardSchemaV1.InferOutput<TSchema>;++type DefinitionFields<TInput, TOutput> = Omit<+ WorkflowToolDefinitionBase<TInput, TOutput>,+ typeof WORKFLOW_TOOL_BRAND+>;+type ExecuteDefinition<TInput, TReturn> = DefinitionFields<TInput, WorkflowReturn<TReturn>> & {execute(input: TInput, ctx: WorkflowToolContext): TReturn;+ task?: never;+ serve?: never;+};+type TaskDefinition<TInput, TReturn> = DefinitionFields<TInput, WorkflowReturn<TReturn>> & {+ task(input: TInput, ctx: WorkflowToolContext): TReturn;+ execute?: never;+ serve?: never;+};+// `ctx.reply()` needs the output type before the body is checked, so a serve+// tool's output comes from its `outputSchema`, not from what `serve` returns.+type ServeDefinition<TInput, TOutput> = DefinitionFields<TInput, TOutput> & {+ serve(+ receive: WorkflowServeReceive<TInput>,+ ctx: WorkflowServeContext<TOutput>,+ ): Promise<TOutput>;+ execute?: never;+ task?: never;+};+type WithSchemas<TDefinition, TInputSchema, TOutputSchema> = Omit<+ TDefinition,+ "inputSchema" | "outputSchema"+> & {+ inputSchema: TInputSchema;+ outputSchema: TOutputSchema;+};+type WithInputSchema<TDefinition, TSchema> = Omit<TDefinition, "inputSchema"> & {+ inputSchema: TSchema;};+// One overload per entry point and schema form. A single overload per form+// can't tell which entry point a definition uses: TypeScript neither infers it+// from the method a definition defines nor contextually types `toModelOutput`+// through a union of the three shapes.export function defineWorkflowTool<TInputSchema extends Schema,TOutputSchema extends StandardJSONSchemaV1<unknown, unknown>,- TReturn extends- | Promise<StandardJSONSchemaV1.InferOutput<TOutputSchema>>- | AsyncIterable<StandardJSONSchemaV1.InferOutput<TOutputSchema>>,+ TReturn extends EntryPointReturn<InferOutput<TOutputSchema>>,>(- definition: Omit<- Definition<StandardSchemaV1.InferOutput<TInputSchema>, TReturn>,- "inputSchema" | "outputSchema"- > & {- inputSchema: TInputSchema;- outputSchema: TOutputSchema;- },-): WorkflowToolDefinition<- StandardSchemaV1.InferOutput<TInputSchema>,- StandardJSONSchemaV1.InferOutput<TOutputSchema>->;+ definition: WithSchemas<+ ExecuteDefinition<InferInput<TInputSchema>, TReturn>,+ TInputSchema,+ TOutputSchema+ >,+): WorkflowExecuteToolDefinition<InferInput<TInputSchema>, InferOutput<TOutputSchema>>;+export function defineWorkflowTool<+ TInputSchema extends Schema,+ TOutputSchema extends StandardJSONSchemaV1<unknown, unknown>,+ TReturn extends EntryPointReturn<InferOutput<TOutputSchema>>,+>(+ definition: WithSchemas<+ TaskDefinition<InferInput<TInputSchema>, TReturn>,+ TInputSchema,+ TOutputSchema+ >,+): WorkflowTaskToolDefinition<InferInput<TInputSchema>, InferOutput<TOutputSchema>>;+export function defineWorkflowTool<+ TInputSchema extends Schema,+ TOutputSchema extends StandardJSONSchemaV1<unknown, unknown>,+>(+ definition: WithSchemas<+ ServeDefinition<InferInput<TInputSchema>, InferOutput<TOutputSchema>>,+ TInputSchema,+ TOutputSchema+ >,+): WorkflowServeToolDefinition<InferInput<TInputSchema>, InferOutput<TOutputSchema>>;+export function defineWorkflowTool<+ TSchema extends Schema,+ TReturn extends EntryPointReturn<unknown>,+>(+ definition: WithInputSchema<ExecuteDefinition<InferInput<TSchema>, TReturn>, TSchema>,+): WorkflowExecuteToolDefinition<InferInput<TSchema>, WorkflowReturn<TReturn>>;export function defineWorkflowTool<TSchema extends Schema,- TReturn extends Promise<unknown> | AsyncIterable<unknown>,+ TReturn extends EntryPointReturn<unknown>,>(- definition: Omit<Definition<StandardSchemaV1.InferOutput<TSchema>, TReturn>, "inputSchema"> & {- inputSchema: TSchema;- },-): WorkflowToolDefinition<StandardSchemaV1.InferOutput<TSchema>, WorkflowReturn<TReturn>>;-export function defineWorkflowTool<TReturn extends Promise<unknown> | AsyncIterable<unknown>>(- definition: Definition<Record<string, unknown>, TReturn> & { inputSchema: JsonObject },-): WorkflowToolDefinition<Record<string, unknown>, WorkflowReturn<TReturn>>;+ definition: WithInputSchema<TaskDefinition<InferInput<TSchema>, TReturn>, TSchema>,+): WorkflowTaskToolDefinition<InferInput<TSchema>, WorkflowReturn<TReturn>>;+export function defineWorkflowTool<TSchema extends Schema>(+ definition: WithInputSchema<ServeDefinition<InferInput<TSchema>, unknown>, TSchema>,+): WorkflowServeToolDefinition<InferInput<TSchema>>;+export function defineWorkflowTool<TReturn extends EntryPointReturn<unknown>>(+ definition: ExecuteDefinition<Record<string, unknown>, TReturn> & { inputSchema: JsonObject },+): WorkflowExecuteToolDefinition<Record<string, unknown>, WorkflowReturn<TReturn>>;+export function defineWorkflowTool<TReturn extends EntryPointReturn<unknown>>(+ definition: TaskDefinition<Record<string, unknown>, TReturn> & { inputSchema: JsonObject },+): WorkflowTaskToolDefinition<Record<string, unknown>, WorkflowReturn<TReturn>>;+export function defineWorkflowTool(+ definition: ServeDefinition<Record<string, unknown>, unknown> & { inputSchema: JsonObject },+): WorkflowServeToolDefinition<Record<string, unknown>>;export function defineWorkflowTool<TInput = unknown, TOutput = unknown>(- definition: Omit<WorkflowToolDefinition<TInput, TOutput>, typeof WORKFLOW_TOOL_BRAND>,-): WorkflowToolDefinition<TInput, TOutput>;-export function defineWorkflowTool<TInput, TOutput>(- definition: Omit<WorkflowToolDefinition<TInput, TOutput>, typeof WORKFLOW_TOOL_BRAND>,-): WorkflowToolDefinition<TInput, TOutput> {+ definition: Unbranded<WorkflowExecuteToolDefinition<TInput, TOutput>>,+): WorkflowExecuteToolDefinition<TInput, TOutput>;+export function defineWorkflowTool<TInput = unknown, TOutput = unknown>(+ definition: Unbranded<WorkflowTaskToolDefinition<TInput, TOutput>>,+): WorkflowTaskToolDefinition<TInput, TOutput>;+export function defineWorkflowTool<TInput = unknown, TOutput = unknown>(+ definition: Unbranded<WorkflowServeToolDefinition<TInput, TOutput>>,+): WorkflowServeToolDefinition<TInput, TOutput>;+export function defineWorkflowTool(+ definition: Unbranded<WorkflowToolDefinition>,+): WorkflowToolDefinition {if ("execution" in definition) {- throw new Error('"execution" was removed; workflow tool calls now block until they settle.');+ throw new Error(+ '"execution" was replaced by task(). Define task(input, ctx) to run each call as a task.',+ );}+ assertOneEntryPoint(definition);stampToolDefinition(definition, "defineWorkflowTool");return Object.assign(definition, { [WORKFLOW_TOOL_BRAND]: true as const });}@@ -163,3 +356,21 @@ export function isWorkflowToolDefinition(value: unknown): boolean {typeof value === "object" && value !== null && Reflect.get(value, WORKFLOW_TOOL_BRAND) === true);}++/** The entry points a definition defines; a workflow tool defines exactly one. */+export function readWorkflowToolEntryPoints(definition: object): WorkflowToolEntryPoint[] {+ return WORKFLOW_TOOL_ENTRY_POINTS.filter(+ (entryPoint) => Reflect.get(definition, entryPoint) !== undefined,+ );+}++const ENTRY_POINT_LIST = new Intl.ListFormat("en", { type: "conjunction" });++function assertOneEntryPoint(definition: object): void {+ const defined = readWorkflowToolEntryPoints(definition);+ if (defined.length === 1) return;+ const found = defined.length === 0 ? "none" : ENTRY_POINT_LIST.format(defined);+ throw new Error(+ `Define exactly one of execute(input, ctx), task(input, ctx), or serve(receive, ctx); this tool defines ${found}.`,+ );+}diff --git a/packages/eve/src/tools/workflow-entry-point.ts b/packages/eve/src/tools/workflow-entry-point.tsnew file mode 100644index 000000000..dab9f9a25--- /dev/null+++ b/packages/eve/src/tools/workflow-entry-point.ts@@ -0,0 +1,9 @@+/** The method a workflow tool defines, which decides how its calls run. */+export type WorkflowToolEntryPoint = "execute" | "task" | "serve";++// Dependency-free so the build's directive transform can read it too.+export const WORKFLOW_TOOL_ENTRY_POINTS: readonly WorkflowToolEntryPoint[] = [+ "execute",+ "task",+ "serve",+];diff --git a/packages/eve/src/tracing/agent-invocation-coordinator.ts b/packages/eve/src/tracing/agent-invocation-coordinator.tsindex 6c446134a..65d8e36b2 100644--- a/packages/eve/src/tracing/agent-invocation-coordinator.ts+++ b/packages/eve/src/tracing/agent-invocation-coordinator.ts@@ -125,8 +125,9 @@ export function prepareAgentInvocationTrace(input: {}/**- * The trace dispatch for sessions a workflow tool call's run opens with- * `ctx.agent`, read from the calling session when the run starts.+ * The trace dispatch for sessions opened with `ctx.agent` while a run serves+ * one workflow tool call: the call's tool span in the calling turn, read from+ * the calling session when it admits the call.*/export function resolveToolCallAgentTrace(input: {readonly callId: string;diff --git a/packages/eve/test/runtime-subagent-registry.test.ts b/packages/eve/test/runtime-subagent-registry.test.tsindex a4a92b1a7..f73917977 100644--- a/packages/eve/test/runtime-subagent-registry.test.ts+++ b/packages/eve/test/runtime-subagent-registry.test.ts@@ -1,25 +1,15 @@import { describe, expect, it } from "vitest";import { RuntimeRegistryError } from "../src/internal/runtime-registry.js";-import {- createPreparedRuntimeSubagentTool,- createRuntimeSubagentRegistry,-} from "../src/runtime/subagents/registry.js";-import { SUBAGENT_TOOL_INPUT_SCHEMA as subagentToolInputSchema } from "../src/tools/framework/agent-contract.js";+import { createRuntimeSubagentRegistry } from "../src/runtime/subagents/registry.js";import type { ResolvedRuntimeSubagentNode } from "../src/runtime/types.js";const SUBAGENT_TOOL_INPUT_SCHEMA = {type: "object",properties: {- agentId: {- type: ["string", "null"],- description:- "The id of an existing agent from the <agents> list. Omit this field (or pass null or an empty string) to start a new agent.",- },message: {type: "string",- description:- "The message to send to the subagent. Provide all context the subagent needs to complete the task; the subagent does not see the parent's history.",+ description: "The message to send to the agent, with everything it needs to do the work.",},},required: ["message"],@@ -27,15 +17,6 @@ const SUBAGENT_TOOL_INPUT_SCHEMA = {} as const;describe("createRuntimeSubagentRegistry", () => {- it("accepts null as an omitted agentId", () => {- expect(- subagentToolInputSchema["~standard"].validate({- agentId: null,- message: "Investigate this",- }),- ).toEqual({ value: { agentId: null, message: "Investigate this" } });- });-it("lowers local subagent inputs into serializable model-visible tools with a uniform messaging schema", () => {const registry = createRuntimeSubagentRegistry({subagents: [@@ -94,23 +75,6 @@ describe("createRuntimeSubagentRegistry", () => {}),).toThrowError(RuntimeRegistryError);});-- it("prepares subagent tools as workflow tools", () => {- const definition = createResolvedRuntimeSubagentNode({- description: "Investigate one task in depth.",- logicalPath: "subagents/researcher",- name: "researcher",- nodeId: "subagents/researcher",- sourceId: "subagents/researcher",- });-- const prepared = createPreparedRuntimeSubagentTool(definition);-- expect(prepared.task).toEqual({- nodeId: definition.nodeId,- workflowId: expect.stringContaining("subagentToolExecuteWorkflow"),- });- });});function createResolvedRuntimeSubagentNode(input: {diff --git a/packages/eve/test/runtime-tool-registry.test.ts b/packages/eve/test/runtime-tool-registry.test.tsindex a79977188..4549ef057 100644--- a/packages/eve/test/runtime-tool-registry.test.ts+++ b/packages/eve/test/runtime-tool-registry.test.ts@@ -1,7 +1,6 @@import { describe, expect, it } from "vitest";import { RuntimeRegistryError } from "../src/internal/runtime-registry.js";-import { subagentToolExecuteWorkflowReference } from "../src/runtime/subagents/workflow-reference.js";import { createRuntimeToolRegistry } from "../src/runtime/tools/registry.js";import type { ResolvedToolDefinition } from "../src/runtime/types.js";import { toInputSchema } from "../src/tools/schema.js";@@ -74,7 +73,7 @@ describe("createRuntimeToolRegistry", () => {createResolvedToolDefinition({behavior: {availability: [],- handling: { kind: "workflow-tool", workflowId },+ handling: { entryPoint: "execute", kind: "workflow-tool", workflowId },},logicalPath: "tools/deploy.ts",name: "deploy",@@ -88,7 +87,6 @@ describe("createRuntimeToolRegistry", () => {handling: { kind: "dispatch", target: { kind: "workflow-tool-call", workflowId } },},});- expect(registry.preparedTools[0]?.task).toEqual({ workflowId });expect(registry.preparedTools[0]).not.toHaveProperty("workflowId");expect(registry.preparedTools[0]).not.toHaveProperty("nodeId");expect(registry.preparedTools[0]).not.toHaveProperty("resultKind");@@ -101,7 +99,7 @@ describe("createRuntimeToolRegistry", () => {createResolvedToolDefinition({behavior: {availability: [],- handling: { kind: "workflow-tool", workflowId },+ handling: { entryPoint: "execute", kind: "workflow-tool", workflowId },},logicalPath: "tools/agent.ts",name: "agent",@@ -111,14 +109,13 @@ describe("createRuntimeToolRegistry", () => {});const prepared = registry.preparedTools[0];- expect(prepared?.task).toEqual({ workflowId });expect(prepared?.behavior?.handling).toEqual({kind: "dispatch",- target: { kind: "workflow-tool-call", workflowId },+ target: { entryPoint: "execute", kind: "workflow-tool-call", workflowId },});});- it("uses the shared stable workflow for a restored application-owned agent tool", async () => {+ it("prepares a restored application-owned agent tool as self-delegation", async () => {const registry = await createRuntimeToolRegistry({tools: [@@ -137,10 +134,6 @@ describe("createRuntimeToolRegistry", () => {);const prepared = registry.preparedTools[0];- expect(prepared?.task).toEqual({- nodeId: "__root__",- workflowId: subagentToolExecuteWorkflowReference.workflowId,- });expect(prepared?.behavior?.handling).toEqual({kind: "dispatch",target: {diff --git a/packages/eve/test/scenarios/compile-agent.scenario.test.ts b/packages/eve/test/scenarios/compile-agent.scenario.test.tsindex 613872e01..b745b0573 100644--- a/packages/eve/test/scenarios/compile-agent.scenario.test.ts+++ b/packages/eve/test/scenarios/compile-agent.scenario.test.ts@@ -176,6 +176,7 @@ describe("compiler artifacts", () => {behavior: {availability: [],handling: {+ entryPoint: "execute",kind: "workflow-tool",workflowId: `workflow//${packageInfo.name}@${packageInfo.version}//executeSleepTool`,},diff --git a/packages/eve/test/scenarios/remote-agent-principal-forwarding.scenario.test.ts b/packages/eve/test/scenarios/remote-agent-principal-forwarding.scenario.test.tsindex f11b77f09..54cd6660d 100644--- a/packages/eve/test/scenarios/remote-agent-principal-forwarding.scenario.test.ts+++ b/packages/eve/test/scenarios/remote-agent-principal-forwarding.scenario.test.ts@@ -1,7 +1,7 @@import { describe, expect, it } from "vitest";import type { SessionAuthContext } from "../../src/channel/types.js";-import { startRemoteAgentSession } from "../../src/subagents/remote-dispatch.js";+import { startRemoteAgentSession } from "../../src/execution/agent-sessions/remote.js";import type { RuntimeRemoteAgentDispatchRequest } from "../../src/shared/action-types.js";import type { ResolvedRuntimeRemoteAgentNode } from "../../src/runtime/types.js";import {diff --git a/packages/eve/test/scenarios/steering.scenario.test.ts b/packages/eve/test/scenarios/steering.scenario.test.tsindex 17d187290..7a3fe70a5 100644--- a/packages/eve/test/scenarios/steering.scenario.test.ts+++ b/packages/eve/test/scenarios/steering.scenario.test.ts@@ -55,8 +55,15 @@ export default defineAgent({const steps = events.filter((event) => event.type === "step.started").map((event) => `${event.data.turnId}:${event.data.stepIndex}`);- expect(steps).toHaveLength(2);+ // The first step starts five worker tasks; later steps read their+ // results as they arrive. No step may run twice.+ expect(steps.length).toBeGreaterThan(2);expect(new Set(steps).size).toBe(steps.length);+ expect(+ events.filter(+ (event) => event.type === "task.settled" && event.data.status === "completed",+ ),+ ).toHaveLength(5);expect(events.filter((event) => event.type === "turn.completed")).toHaveLength(1);expect(server.stderr()).toContain("Step execution already in flight in this process");} finally {diff --git a/packages/eve/test/scenarios/turn-cancellation.scenario.test.ts b/packages/eve/test/scenarios/turn-cancellation.scenario.test.tsindex 24b5d8f38..096863979 100644--- a/packages/eve/test/scenarios/turn-cancellation.scenario.test.ts+++ b/packages/eve/test/scenarios/turn-cancellation.scenario.test.ts@@ -77,6 +77,10 @@ import { mockModel } from "eve/evals";const model = mockModel((request) => {const message = request.lastUserMessage ?? "";if (message.includes("Use workflow exactly once")) {+ // The workflow tool runs as a task: after its receipt, wait on it.+ if (request.toolResults.some((entry) => entry.name === "workflow")) {+ return { toolCalls: [{ name: "task_wait", input: {} }] };+ }const localOnly = message.includes("local-sleeper only");return {toolCalls: [@@ -289,11 +293,13 @@ describe("turn cancellation descendant cascade", () => {iterator: response[Symbol.asyncIterator](),label: "root session-limit prompt",});- const calls = events.filter((event) => event.type === "agent.started");+ // The workflow program runs as a task, so the root reaches its limit+ // prompt while the task keeps working.+ const tasks = events.filter((event) => event.type === "task.started");const requests = events.flatMap((event) =>event.type === "input.requested" ? event.data.requests : [],);- expect(calls).toHaveLength(1);+ expect(tasks).toHaveLength(1);expect(requests).toHaveLength(1);expect(requests[0]?.requestId.startsWith(`${response.sessionId}:limit:`)).toBe(true);@@ -302,7 +308,13 @@ describe("turn cancellation descendant cascade", () => {const declined = await (await session.respond([{ optionId: "stop", requestId }])).result();expect(declined.status).toBe("waiting");expectCancellationBoundary(declined.events);- expect(declined.events.some((event) => event.type === "agent.started")).toBe(false);+ expect(declined.events).toContainEqual(+ expect.objectContaining({+ data: expect.objectContaining({ status: "cancelled" }),+ type: "task.settled",+ }),+ );+ expect(declined.events.some((event) => event.type === "step.started")).toBe(false);} catch (error) {throw new Error([diff --git a/packages/eve/test/tui-client/tui-subagents.ts b/packages/eve/test/tui-client/tui-subagents.tsindex f1f354350..38c0b0e01 100644--- a/packages/eve/test/tui-client/tui-subagents.ts+++ b/packages/eve/test/tui-client/tui-subagents.ts@@ -5,20 +5,16 @@ import { EveTUIRunner, MockScreen, MockUserInput } from "./lib/tui.ts";// Note: the apps/fixtures/agent-tui-client's echo-marker subagent is the source of every child// stream event the TUI observes here. The smoke validates the full pipeline:-// parent subagent.called → child session subscription → nested `│` region-// populated from the child's message.completed → parent subagent.completed.+// parent task.started + agent.started → child session subscription → nested `│` region+// populated from the child's message.completed → parent task.settled.import { run } from "./lib/run.ts";import { theme } from "./lib/theme.ts";/**- * End-to-end proof that the TUI surfaces subagent stream events as a- * persistent body section.- *- * Previously, `subagent.called`/`.started`/`.event`/`.completed` events- * fell into the translator's `default:` arm and were dropped, the user- * just saw a long pause. This smoke test drives the new subagent- * section path against the `echo-marker` fixture:+ * End-to-end proof that the TUI surfaces an agent task's child stream as a+ * persistent body section. This smoke test drives the subagent section path+ * against the `echo-marker` fixture:** 1. Start the apps/fixtures/agent-tui-client server.* 2. Boot an `EveTUIRunner` with a mock terminal.diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex b066dfcbd..317d07432 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -1267,6 +1267,28 @@ importers:specifier: 'catalog:'version: 7.0.2+ e2e/fixtures/agent-tasks:+ dependencies:+ '@eve-e2e/config':+ specifier: workspace:*+ version: link:../e2e-config+ '@workflow/world-postgres':+ specifier: 'catalog:'+ version: 5.0.0-beta.47(@opentelemetry/[email protected])(@types/[email protected])(@upstash/[email protected])([email protected])([email protected])([email protected])+ eve:+ specifier: workspace:*+ version: link:../../../packages/eve+ zod:+ specifier: 'catalog:'+ version: 4.5.4+ devDependencies:+ '@types/node':+ specifier: 'catalog:'+ version: 24.13.3+ typescript:+ specifier: 'catalog:'+ version: 7.0.2+e2e/fixtures/agent-tools:dependencies:'@eve-e2e/config':diff --git a/research/eve-tasks.md b/research/eve-tasks.mdindex 2ee23982d..39ccba791 100644--- a/research/eve-tasks.md+++ b/research/eve-tasks.md@@ -1,7 +1,7 @@---issue: https://github.com/vercel/eve/issues/1084status: draft-last_updated: "2026-09-26"+last_updated: "2026-09-28"---# eve tasks@@ -20,8 +20,8 @@ stack of pull requests that lands it in pieces. Paths are relative to `packages/3. **`serve(receive, ctx)` runs a resumable task.** It gets each call from `receive()`,including later calls the model sends by `taskId`, and settles them with `ctx.reply()`. Everyagent tool is a `serve` tool built on `ctx.agent`.-4. **Steering never cancels a task.** A new message ends the model's waits, and an `execute` call- the turn is waiting on learns about it through `ctx.interruptSignal`. Tasks stop only for+4. **Steering never cancels a task.** A new message ends the model's waits and aborts the+ `abortSignal` of each `execute` call the turn is waiting on. Tasks stop only for`task_cancel`, `session.cancel()`, or session end.5. **Results arrive one way:** a `task.result` message at a step boundary. The model gets`task_wait`, which parks the turn until a task settles, and `task_cancel`.@@ -73,14 +73,13 @@ defineWorkflowTool({- **`execute(input, ctx)`** is an ordinary tool call, exactly as on `main` and like`defineTool`'s `execute`: the turn parks durably until the call settles, and its result is the- tool result. Its context, `WorkflowToolContext`, has `callId`, `abortSignal`, and- `interruptSignal` (§2).+ tool result. Its context, `WorkflowToolContext`, has `callId` and `abortSignal`, which a+ steering message also aborts (§2).- **`task(input, ctx)`** runs the call as a task: a receipt now, the result later as a- `task.result` message. Its context, `WorkflowTaskContext`, has `callId` and `abortSignal`, and- no `interruptSignal`, because tasks are never interrupted.+ `task.result` message. Its context is the same `WorkflowToolContext`, and steering never aborts+ its `abortSignal`.- **`serve(receive, ctx)`** runs a resumable task (§3). `receive()` resolves each call with its- own `callId` and `abortSignal`, and the context, `WorkflowServeContext`, has `reply(output)`- and no `interruptSignal`.+ own `callId` and `abortSignal`, and the context, `WorkflowServeContext`, has `reply(output)`.- All three contexts share `ask`, `agent`, `agents`, `getToken`, `requireAuth`, and `session`.- In `execute` and `task`, `return output` settles the call and a throw fails it. `async *execute`and `async *task` still yield progress as `action.partial`.@@ -95,17 +94,18 @@ defines {found}.**Tool calls and tasks.** The entry point answers whether the conversation should continue whilethe call runs. Parking alone doesn't need a task: a question, a sleep, or an approval parks-durably inside an `execute` call and holds no compute. A twenty-minute deploy, or research the-model may not need right away, is a task. A long `execute` tool holds the conversation until it+durably inside an `execute` call and holds no compute, until a new message stops it. A+twenty-minute deploy, research the model may not need right away, or a question that should+outlast new messages is a task. A long `execute` tool holds the conversation until itsettles; the docs say so where `task()` is introduced.-| Call | Runs as | Result | Steering during the call |-| ------------------------------------------------------------------------ | ------------------------- | ------------------------------------------------- | --------------------------------------------- |-| `execute()` tool, including `sleep` and `ask_question` | Tool call; the turn parks | The tool result | Its `interruptSignal` fires; the call decides |-| `task()` tool, including `agentRouter()` and the `workflow` program tool | Task | A receipt, then a `task.result` message | Nothing |-| `serve()` tool, including every agent tool | Resumable task | A receipt, then a `task.result` message per reply | Nothing |-| `task_wait` | Kernel wait | Which tasks settled | Returns `interrupt` |-| Plain and MCP tools | Inside the model step | The tool result | Applied at the next step boundary |+| Call | Runs as | Result | Steering during the call |+| ------------------------------------------------------------------------ | ------------------------- | ------------------------------------------------- | ------------------------------------------- |+| `execute()` tool, including `sleep` and `ask_question` | Tool call; the turn parks | The tool result | Its `abortSignal` aborts; the body's result |+| `task()` tool, including `agentRouter()` and the `workflow` program tool | Task | A receipt, then a `task.result` message | Nothing |+| `serve()` tool, including every agent tool | Resumable task | A receipt, then a `task.result` message per reply | Nothing |+| `task_wait` | Session wait | Which tasks settled | Returns `interrupt` |+| Plain and MCP tools | Inside the model step | The tool result | Applied at the next step boundary |**Agents are always `serve` tasks.** Whether an agent's result is needed now depends on theconversation, which only the model sees, and the turn rule (§6) guarantees the result reaches it.@@ -120,29 +120,31 @@ Steering is applied in this order:1. If the message answers a pending request, it answers it and doesn't steer. Only a person'smessage to the session they're talking to can answer, as on `main` after #3700; a caller'smessage, such as an agent tool's message to its child, never does.-2. Otherwise, the `interruptSignal` of every `execute` call the turn is waiting on fires, and+2. Otherwise, the `abortSignal` of every `execute` call the turn is waiting on aborts, and`task_wait` returns `interrupt`. Tasks are untouched. The model sees the message once thestep's `execute` calls settle, and decides whether to keep, correct, or cancel each task.Steering never ends the turn. A `"queue"` message waits for the turn to end.-**`ctx.interruptSignal`** fires once, on the first steering message while the turn waits on the-call; later messages are applied after the call settles anyway. What it means is the author's-choice. A body that ignores it keeps going: a deploy waiting on an approval survives unrelated-messages. A body that wants to stop races or passes the signal. Tasks are never interrupted, so-`task` and `serve` have no `interruptSignal`.+**One signal, two triggers.** A call's `abortSignal` aborts when its work should stop: a cancel+stops any call, and a steering message stops the `execute` calls the turn waits on. The body+doesn't tell them apart; it stops and returns what it has. The run does. After a steering message+the call settles with the body's result, or `{ interrupted: true }` if the body rejects, with no+cleanup deadline. After a cancel the result is discarded and the run ends 30 s later. Work that+should outlast new messages, such as an approval that must stay open, is a task.**Anything that waits takes a `signal`.** `ctx.ask(request, { signal })` withdraws the requestwhen the signal aborts: it resolves `{ status: "cancelled" }`, and `input.resolved` reports`outcome: "cancelled"` so channels update the question. Cancellation withdraws a pending ask the-same way. An ask that should end when the conversation moves on passes `ctx.interruptSignal`,-which replaces `dismissible`. The built-in tools do exactly this:+same way. The session decides between an answer and a withdrawal (§7), so an answer it accepted+first still resolves the ask as `answered` after the signal aborts. Steering aborts a waited `execute` call's `abortSignal`, so its asks end when the conversation+moves on, which replaces `dismissible`. The built-in tools rely on that:```ts// ask_question, as eve ships itasync execute(input, ctx) {"use workflow";- const answer = await ctx.ask(toQuestion(input), { signal: ctx.interruptSignal });+ const answer = await ctx.ask(toQuestion(input));return answer.status === "cancelled" ? { interrupted: true } : answer;}@@ -150,7 +152,7 @@ async execute(input, ctx) {async execute(input, ctx) {"use workflow";const interrupted = new Promise<"interrupted">((resolve) =>- ctx.interruptSignal.addEventListener("abort", () => resolve("interrupted"), { once: true }),+ ctx.abortSignal.addEventListener("abort", () => resolve("interrupted"), { once: true }),);const elapsed = sleep(input.seconds * 1_000).then(() => "elapsed" as const);const woke = await Promise.race([elapsed, interrupted]);@@ -201,31 +203,33 @@ A `serve` body runs once per task and gets its calls from `receive()` instead ofvalidated by `inputSchema`. The first `receive()` resolves in memory from the call that startedthe task, with no step or hook. After that, it resolves with each call made with the task's`taskId`, in arrival order. Calls that arrive while the body isn't waiting are kept. A pending- `receive()` is shared: calling it again returns the same promise, so a `Promise.race` it loses- never drops a call.+ `receive()` is shared: calling it again returns the same promise. A call counts as received once+ its promise resolves, even if that promise lost a `Promise.race`, and the next `ctx.reply()`+ settles it, so a body that races `receive()` keeps the promise until it reads the call.- **`ctx.reply(output)`** settles the calls received so far with `output`, and the task goes idleuntil the next call. A reply with no call left to settle is dropped, and `ctx.ask` throws whileno call is waiting for a result.- **`return output`** settles the calls still waiting and ends the task; throwing fails them.`serve` is not a generator, so it can't yield progress for now.-- **`taskId` on the model input.** eve adds an optional `taskId` to the tool's model input.- Without it, a call starts a new task; with it, the call goes to that task. The build fails if- `inputSchema` declares its own `taskId`. The ID must name an unfinished task this tool started- for the caller's principal, or the call fails `UNKNOWN_TASK`.+- **`taskId` on the model input.** eve adds an optional `taskId` to the tool's model input. Without+ it, a call starts a new task; with it, the call goes to that task. The build fails if+ `inputSchema` declares its own `taskId`. The ID must name an unfinished task this tool started, or+ the call fails `UNKNOWN_TASK`.- **One `abortSignal` per stretch of work.** A stretch starts when a call reaches an idle task andends when a reply or a cancel settles its calls; calls that arrive during it carry the samesignal. Each signal aborts at most once and the next stretch gets a new one, so a task can becancelled any number of times. A body stays available only if it catches its stretch's abort- and returns to `receive()`; an abort that escapes the body finishes the task. A body that ignores- the signal keeps working, and its reply is dropped.+ and returns to `receive()`; an abort that escapes the body finishes the task, and so does a body+ that hasn't returned to `receive()` 30 s after the cancel.- **The context follows the call.** `ctx.session` (its turn and auth) and `ctx.agents` describethe call being served, from the moment `receive()` resolves it. An agent session the body opensbelongs to the call that opened it: its parent, turn, and trace come from that call. Eachmessage the body sends it carries the auth of the call being served when it is sent.- **Working and idle.** A resumable task is working while one of its calls has no result, andidle otherwise. An idle task holds no turn and doesn't count toward the cap.-- **Finishing.** The task finishes when its body returns or throws, or when the session ends,- which aborts the current stretch's signal and rejects a pending `receive()`.+- **Finishing.** The task finishes when its body returns or throws, when it hasn't returned to+ `receive()` 30 s after a cancel, or when the session ends, which aborts the current stretch's+ signal and rejects a pending `receive()`.- eve appends this sentence to the tool's description:```text@@ -265,23 +269,36 @@ async serve(receive, ctx) {"use workflow";const agent = ctx.agent(name);// A cancel aborts the call's abortSignal, which ends the agent's turn.- const send = ({ input, abortSignal }: Awaited<ReturnType<typeof receive>>) =>- agent- .send(input.message, { signal: abortSignal })- .then((response) => response.result());- let latest = send(await receive());+ const send = ({ input, abortSignal }: Awaited<ReturnType<typeof receive>>) => ({+ result: agent.send(input.message, { signal: abortSignal }).then((r) => r.result()),+ signal: abortSignal,+ });+ let turn = send(await receive());+ let next = receive(); // kept until its call is read, even after it loses the racefor (;;) {const event = await Promise.race([- latest.then((result) => ({ result })),- receive().then((next) => ({ next })),+ turn.result.then((result) => ({ result })),+ next.then((call) => ({ call })),]);- if ("next" in event) {- latest = send(event.next); // joins the running turn, or starts the next if it just ended+ if ("call" in event) {+ if (turn.signal.aborted) await turn.result.catch(() => {}); // a cancelled turn ends first+ turn = send(event.call); // joins the running turn, or starts the next if it just ended+ next = receive();continue;}- if (event.result.status === "failed") throw new Error("The agent's session ended.");- ctx.reply(toOutput(event.result)); // settles the calls received so far; dropped after a cancel- latest = send(await receive());+ // After a cancel, the turn's calls are already settled.+ if (!turn.signal.aborted) {+ if (event.result.status === "failed") throw new Error("The agent's session ended.");+ const following = receive();+ if (following !== next) {+ turn = send(await next); // `next` took a call as the turn ended: the agent reads it first+ next = following;+ continue;+ }+ ctx.reply(toOutput(event.result)); // settles the calls received so far+ }+ turn = send(await next);+ next = receive();}}```@@ -309,10 +326,10 @@ Both are offered, with the system block below, when the agent has an agent or a`serve()` tool.All model text is a draft, tuned with real-model evals.-**`task_wait`** returns when any task the turn's principal started settles, when `timeout`-passes, or when steering arrives, and at once if a result is already waiting. It never returns-content; the settled results follow as the `task.result` message in the same step. Waiting never-stops a task, and a task waiting on a person keeps the wait going.+**`task_wait`** returns when any task in the turn settles, when `timeout` passes, or when steering+arrives, and at once if a result is already waiting. It never returns content; the settled results+follow as the `task.result` message in the same step. Waiting never stops a task, and a task waiting+on a person keeps the wait going.```textWait until one of your tasks has a result, a new message arrives, or timeout (in milliseconds)@@ -375,8 +392,8 @@ Sent to task researcher-7k2m9q.**`[Tasks]` note.** A `context.state` message appended at a model-step boundary when the listingchanges, and after compaction, so task IDs survive it. It is derived only from the session's task-table in process, never from child streams: the turn principal's working tasks with tool and-status, then its 10 most recent idle resumable tasks.+table in process, never from child streams: the working tasks with tool and status, then the 10 most+recent idle resumable tasks.```text[Tasks]@@ -404,18 +421,18 @@ task_cancel. Never use sleep to wait for a task.**Errors.** These are the only task error codes.-| Code | Where | Message |-| ---------------- | ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |-| `UNKNOWN_TASK` | Call with `taskId`, `task_cancel` | `No task "{id}" is available to {tool}: it may have ended or belong to another tool or caller. Start a new one by calling {tool} without taskId.` |-| `TOO_MANY_TASKS` | Start, call to an idle resumable task | `32 tasks are already working ({ids}). Wait with task_wait or stop one with task_cancel, then try again.` |+| Code | Where | Message |+| ---------------- | ------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |+| `UNKNOWN_TASK` | Call with `taskId`, `task_cancel` | `No task "{id}" is available to {tool}: it may have ended or belong to another tool. Start a new one by calling {tool} without taskId.` |+| `TOO_MANY_TASKS` | Start, call to an idle resumable task | `32 tasks are already working ({ids}). Wait with task_wait or stop one with task_cancel, then try again.` |## 6. Turns, principals, and limits-**The turn rule.** No turn ends while tasks its principal started are working, in any session.-When the model ends such a turn, eve does what `task_wait` does: it parks until one of those tasks-settles or the same principal steers, appends the settled results, and calls the model again. A-`final_output` call while tasks work returns an error naming them. No result ever starts a turn.-Session expiry and turn failures cancel the turn's tasks, as `session.cancel()` does.+**The turn rule.** No turn ends while any task is working, in any session. When the model ends such+a turn, eve does what `task_wait` does: it parks until one of those tasks settles or the turn's+principal steers, appends the settled results, and calls the model again. A `final_output` call+while tasks work returns an error naming them. No result ever starts a turn. Session expiry and turn+failures cancel the turn's tasks, as `session.cancel()` does.**Presentation of a held turn.** A held turn stays open. Each time an open turn parks, the streamemits `turn.waiting` with the turn's ID: when eve holds a turn the model tried to end, in every@@ -452,11 +469,11 @@ call's receipt doesn't show as finished: Slack's activity keeps the call runninguntil `task.settled` for that `callId`, then settles it with the real status. There is no optionyet, and other channels are unchanged.-**Principals.** Only the turn's own principal steers it; another principal's message waits for-the turn to end, then starts that principal's turn. Calls with `taskId` and `task_cancel` accept-only the task's creator principal, and `task_wait` and `[Tasks]` cover only the turn principal's-tasks. Anonymous callers share one principal. Queued messages from one principal share a turn-even when their claims differ, and the turn runs with the latest claims.+**Principals.** Only the turn's own principal steers it; another principal's message waits for the+turn to end, then starts that principal's turn. Tasks belong to the session's open turn, and any+turn can continue an idle task by `taskId` with its own caller's auth. Anonymous callers share one+principal. Queued messages from one principal share a turn even when their claims differ, and the+turn runs with the latest claims.**No task time limits.** `defineAgent`'s `limits.sessionTimeoutMs` keeps its meaning, thesession lifetime (default 30 days), and bounds all work in the session; with `false`, tasks are@@ -470,7 +487,7 @@ shouldn't reach. Idle resumable tasks don't count.```ts{ type: "turn.waiting"; data: { turnId, sequence } }-{ type: "task.started"; data: { taskId, callId, turnId, name } }+{ type: "task.started"; data: { taskId, callId, turnId, name, kind: "agent" | "tool" } }{ type: "task.settled"; data: { taskId, callId, turnId,status: "completed" | "failed" | "cancelled",output?: JsonValue, error?: { message: string } } }@@ -483,7 +500,9 @@ shouldn't reach. Idle resumable tasks don't count.a task or reaches one by `taskId`, and when a reply, return, failure, or cancel settles it.`(taskId, callId)` identifies the call; `callId` is the tool call clients attach status to, andboth events carry that call's `turnId`. For each invocation, `task.started` comes before the- sessions it announces and the calls it settles.+ sessions it announces and the calls it settles. `kind` is `"agent"` for an agent tool's call and+ `"tool"` for any authored tool, so clients tell agent calls apart without `agent.started`, which+ only adds the child session.- **`agent.started`** comes once per session a workflow run opens with `ctx.agent`, including anagent tool's, with the `callId` and `turnId` of the call whose invocation opened it; for a`serve` task that is the current call, not the first. `taskId` is present when that invocation@@ -492,8 +511,9 @@ shouldn't reach. Idle resumable tasks don't count.- **`output`** is a completed call's typed result; **`error.message`** explains a failed one.There are no error codes and no usage; either can be added later without breaking anyone.-`session.streamSubagent(started)` takes an `agent.started` event and no longer checks the parent-session ID; the proxy validates the parent and call. Hooks subscribe to the new events in place+`session.agent(started)` takes an `agent.started` event and returns the child's handle, whose+`stream()` follows it; the proxy validates the parent and call. It replaces+`session.streamSubagent()`, and the handle leaves room for more child operations. Hooks subscribe to the new events in placeof `subagent.*`. `input.requested` and `authorization.*` gain `taskId` when a task asks. A`task.result` message is not published as `message.received`: it stays a user-role message inthe model's history, and clients see outcomes through `task.settled`. The eval assertion@@ -502,12 +522,11 @@ the model's history, and clients see outcomes through `task.settled`. The eval a## 7. Runtime invariants- **One owner per task.** The session owns every task; a workflow run owns only the sessions it- opens with `ctx.agent`, which are not tasks. One small versioned record per task, written only- by applying the session's inbox messages (`execution/tasks/table.ts`): `id`, `name`,- `resumable`, `status` (`working`, `idle`, or finished), the calls without a result, each with- its `turnId`, `delivered`, `creator` (auth captured at start), and the cancel timestamp. A- record that fails to decode fails its task ("its state could not be read"), never the session.- Sessions aren't migrated.+ opens with `ctx.agent`, which are not tasks. One small versioned record per task, written only by+ applying the session's inbox messages (`execution/tasks/table.ts`): `id`, `name`, `resumable`,+ `status` (`working`, `idle`, or finished), the calls without a result, each with its `turnId`,+ `delivered`, and the cancel timestamp. A record that fails to decode fails its task ("its state+ could not be read"), never the session. Sessions aren't migrated.- **Every wait suspends.** The session is a durable workflow (`execution/session/entry.ts`) whoseinbox is built on Workflow SDK hooks. `execute` calls keep today's path: the call defers outof the model step and the turn loop parks until it settles (`execution/session/turn.ts`,@@ -519,28 +538,40 @@ the model's history, and clients see outcomes through `task.settled`. The eval aOnly later calls to a `serve` task use the run's private hook, created with a token derivedfrom `taskId` before the body starts, because a Workflow SDK hook registers only when the runsuspends.-- **One inbox per run.** A run's signals and ask results are views over one ordered inbox, so- when an answer and an interrupt race, they resolve in inbox order: `ask_question` gets the- answer or `cancelled`, whichever its run's inbox received first.+- **One inbox per run.** Everything the run receives (calls, answers, interrupt, cancel) is+ delivered through one ordered inbox in the order the session accepted it. The inbox is the run's+ control hook; only the session writes to it, and ask results and signals are views over it.+ The session is the one authority on a question: it accepts an answer or a withdrawal at the+ step that retires the question's route, emits `input.resolved` from that step, and sends its+ decision (`answer` or `withdrawn`) on the control hook. An aborted signal only asks the session+ to withdraw. `cancel` of an `execute` or `task()` call and `end` settle its pending asks as+ `cancelled`, because the session retires their routes when it sends them.- **Start once.** The model step commits the task record, with an ID assigned by the session,alongside the tool call; the session then starts the task's run in one step keyed on `taskId`.Commands issued before the run reports started are held on the record.- **Settle once.** Runs send the session `task.input` and `task.settled`, keyed- `(taskId, callId, kind)`; a reply sends one `task.settled` per call it settles. The first- outcome per call wins, owner-cancelled results are dropped, and every other result is appended- once to the next `task.result` message and marked `delivered`.-- **Calls with `taskId`.** The session checks the task is resumable, unfinished, this tool's, and- the caller's principal's (else `UNKNOWN_TASK`), records the call, marks the task `working`,- emits `task.started`, and resumes the task's hook with the validated input.+ `(taskId, callId, kind)`. A reply settles every call it answers in one step, with one+ `task.settled` per call, so no wait wakes while some of them look unanswered. The first outcome+ per call wins, owner-cancelled results are dropped, and every other result is appended once to+ the next `task.result` message and marked `delivered`; calls one reply or return settles share+ one result.+- **Calls with `taskId`.** The session checks the task is resumable, unfinished, and this tool's+ (else `UNKNOWN_TASK`), records the call, marks the task `working`, emits `task.started`, and+ resumes the task's hook with the validated input.- **Cancel.** The session settles the waiting calls as `cancelled`, sends the run `cancel`, and- returns at once. A `task()` run aborts its call's `abortSignal`, and one sleeper run per- session, armed only for the earliest pending confirmation, hard-stops it after 30 s. A `serve()`- run aborts the current stretch's signal and stays parked on its hook, so it needs no hard stop.-- **Agent sessions.** A workflow run's start input carries the caller's principal, capabilities,- dynamic agent selections, and sandbox reference. `ctx.agent` opens its child, local or remote,- in a step keyed on the run and the handle's position; `send` uses the child's existing deliver- path with the run's `callId` as `caller.callId`; `result()` waits through a hook. The run- publishes `agent.started` on the session's stream, as it publishes `action.partial`.+ returns at once. A `task()` run aborts its call's `abortSignal`; a `serve()` run aborts the+ current stretch's signal. The run bounds its own cleanup: a `task()` body still running, or a+ `serve()` body not back at `receive()`, 30 s after the cancel ends the run as `cancelled`. The+ session never waits on it, so it keeps no timer.+- **Agent sessions.** A workflow run's start input carries the caller's capabilities, dynamic agent+ selections, and sandbox reference, and each message to a session carries the auth of the call that+ sends it. `ctx.agent` opens its child, local or remote, in a step keyed on the run and the+ handle's position; `send` uses the child's existing deliver path with the run's `callId` as+ `caller.callId`; `result()` waits through a hook. The run sends `agent.started` to the session,+ which publishes it as it arrives, even while a model step runs, so clients follow a child while it+ works. Publishing it changes no session state, so the step's result, which replaces that state at+ the boundary, loses nothing. `action.partial` reaches channel handlers, which can change state, so+ it waits for the step boundary.- **Questions go up, answers come down.** A child's `input.requested` and `authorization.*` travelup the owner chain to the root, where a person answers, and answers route down by request ID.The root emits `input.resolved` for each answer it routes, during a hold too. This is the only@@ -548,13 +579,13 @@ the model's history, and clients see outcomes through `task.settled`. The eval awith idempotent callbacks and a version check that fails the call at start with a messagenaming both versions.- **Turn end.** The harness's terminate branch (`harness/tool-loop.ts`) returns `held` with the- working task IDs, the turn loop waits, and the program (`execution/session/program.ts`) sends- the caller's reply from one guarded site. The hold is keyed by principal, so a turn resumed- after an approval or sign-in still holds on the parked turn's work.+ working task IDs, the turn loop waits, and the program (`execution/session/program.ts`) sends the+ caller's reply from one guarded site. The open turn holds on every working task, so a turn resumed+ after an approval or sign-in still holds on the earlier turn's work.- **A turn completes once.** `turn.completed` comes only at a turn's real end. A question orsign-in inside a running call parks the turn with `turn.waiting` and never ends it.- **Guards** (`pnpm guard:invariants`): `tools/provided/**` and generated agent tools import only- public entry points, except the kernel's `task_wait` and `task_cancel`; only+ public entry points, except the session's own `task_wait` and `task_cancel`; only`execution/tasks/table*.ts` writes records; model text lives only in`execution/tasks/render.ts`; one caller-reply site.@@ -572,7 +603,8 @@ These are the upgrade notes; everything is breaking and allowed pre-1.0.- **`ctx.agent`:** `ctx.agent(name, { message, agentId })` returning output becomes`ctx.agent(name)` returning a session handle. `agentId` is removed; each handle is a new child.-- **`ctx.ask`:** `dismissible` is removed; pass `ctx.interruptSignal` as `signal`. The+- **`ctx.ask`:** `dismissible` is removed; a steering message withdraws a waited `execute` call's+ questions, and a task's stay open. The`input.resolved` outcome `"dismissed"` becomes `"cancelled"`.- **Agent tools:** `agentId` becomes `taskId`, and every agent call is a task.- **`agentRouter()` and the `workflow` program tool** become `task()` tools instead of blocking@@ -621,23 +653,23 @@ replacement.- Extract a helper function wherever a step has a name, and define explicit interfaces andtypes at module boundaries: task records, inbox commands, the received call, and agentsession handles.- - Keep related code together: the task kernel under `execution/tasks/`, its model text in one+ - Keep related code together: tasks under `execution/tasks/`, their model text in onerenderer, and public types beside the definitions they describe.- Follow `AGENTS.md`: keep it simple, comment why rather than what, add no legacy fallbacks,and wrap third-party APIs.-| # | PR | Main after it lands |-| --- | ----------------------------- | --------------------------------------------------------------- |-| 1 | Remove background tasks | Every workflow tool and agent call blocks |-| 2 | Workflow tool body (dropped) | Nothing: `execute(input, ctx)` keeps its signature |-| 3 | Steering signals | `ctx.interruptSignal`; `sleep` and `ask_question` on public API |-| 4 | Agent sessions | `ctx.agent(name)` handles; `agent.started`; `turn.waiting` |-| 5 | Task kernel and the turn rule | `task(input, ctx)`, `task_wait`, `task_cancel`, held turns |-| 6 | Held-turn presentation | `turn.waiting` for every held turn; root text steps as `"stop"` |-| 7 | Resumable tasks | `serve(receive, ctx)`, `ctx.reply()`, `taskId` |-| 8 | Agents as tasks | Agent tools as `serve` tools; `subagent.*` removed |-| 9 | Slack post before a wait | The text of a `task_wait` step is posted; receipts stay running |-| 10 | Tests and release readiness | E2E suites, real-model evals, Tasks and upgrade guides |+| # | PR | Main after it lands |+| --- | ---------------------------- | --------------------------------------------------------------- |+| 1 | Remove background tasks | Every workflow tool and agent call blocks |+| 2 | Workflow tool body (dropped) | Nothing: `execute(input, ctx)` keeps its signature |+| 3 | Steering signals | `ctx.interruptSignal`; `sleep` and `ask_question` on public API |+| 4 | Agent sessions | `ctx.agent(name)` handles; `agent.started`; `turn.waiting` |+| 5 | Tasks and the turn rule | `task(input, ctx)`, `task_wait`, `task_cancel`, held turns |+| 6 | Held-turn presentation | `turn.waiting` for every held turn; root text steps as `"stop"` |+| 7 | Resumable tasks | `serve(receive, ctx)`, `ctx.reply()`, `taskId` |+| 8 | Agents as tasks | Agent tools as `serve` tools; `subagent.*` removed |+| 9 | Slack post before a wait | The text of a `task_wait` step is posted; receipts stay running |+| 10 | Tests and release readiness | E2E suites, real-model evals, guides; one `abortSignal` |**1. Remove background tasks.** Delete `execution: "background"` (rejected at definition),`taskDeliveryPolicy`, cohorts, the `[Task state]` and `[Agents]` notes, prose notifications,@@ -659,7 +691,7 @@ calls, `ctx.ask(..., { signal })` withdrawal with `outcome: "cancelled"`, removi`sleep` and `ask_question` rebuilt as `execute(input, ctx)` on public API, and the`tools/provided/**` guard.-**4. Agent sessions.** `ctx.agent(name)` handles opened from the run with the caller's principal,+**4. Agent sessions.** `ctx.agent(name)` handles opened from the run with the caller's auth,capabilities, dynamic selections, and sandbox reference in the start input; `agent.started` withthe opening call's `turnId`; `streamSubagent()` accepting `agent.started`; questions and sign-insup the owner chain from run-owned sessions; the remote protocol change and version check.@@ -675,17 +707,15 @@ scanning for `subagent.called` (`eve-channel/support.ts`); resolve it from the a`agent.started.name`, and if dynamic remote agents can't be resolved that way, record the bindingon the run's `agent.started` step instead.-**5. Task kernel and the turn rule.** Task records, `task(input, ctx)` with-`WorkflowTaskContext` and the one-entry-point definition error, receipts, `task.started` and-`task.settled` with each call's `turnId`, `task_wait` with `turn.waiting` when it parks,-`task_cancel`, the `task.result` message (not published as `message.received`), `[Tasks]`, the-system block, `UNKNOWN_TASK`, `TOO_MANY_TASKS`, principals, `session.cancel()` cancelling working-tasks, the hard-stop timer, and the turn rule with `final_output`'s error. `agent.started` gains-`taskId` for `task()` runs, and proxied answers emit `input.resolved` during a hold. A held turn-emits no `turn.waiting` yet: every held text step reports `"tool-calls"`, as child turns do.-`agentRouter()` and-the `workflow` program tool become `task()` tools; the `execution` error gains its final-wording.+**5. Tasks and the turn rule.** Task records, `task(input, ctx)` with `WorkflowTaskContext` and the+one-entry-point definition error, receipts, `task.started` and `task.settled` with each call's+`turnId`, `task_wait` with `turn.waiting` when it parks, `task_cancel`, the `task.result` message+(not published as `message.received`), `[Tasks]`, the system block, `UNKNOWN_TASK`,+`TOO_MANY_TASKS`, principal steering and queuing, `session.cancel()` cancelling working tasks, and+the turn rule with `final_output`'s error. `agent.started` gains `taskId` for `task()` runs, and+proxied answers emit `input.resolved` during a hold. A held turn emits no `turn.waiting` yet: every+held text step reports `"tool-calls"`, as child turns do. `agentRouter()` and the `workflow` program+tool become `task()` tools; the `execution` error gains its final wording.**6. Held-turn presentation.** `turn.waiting` whenever eve holds a turn, in every session kind; aroot turn's held text step completes as `"stop"`, and `"tool-calls"` remains only for child and@@ -695,7 +725,7 @@ schedule turns.first call from the start input and later calls through the run's hook, `ctx.reply()`, returnand throw settlement, `ctx.ask` throwing while no call waits, `taskId` on the model input and itsbuild check, per-stretch `abortSignal`, idle tasks in the turn rule and `[Tasks]`, and cancel-keeping the task. Each call carries its own turn, auth, and agent context, so `ctx.session`,+keeping the task when the body returns to `receive()` within 30 s. Each call carries its own turn, auth, and agent context, so `ctx.session`,`ctx.agents`, `agent.started`, and `task.settled` describe the current call, and a session thebody opens belongs to the call that opened it.@@ -710,7 +740,9 @@ and hook event map to task events. #3700's delegated-session regressions and itsTask receipts stay running in Slack's activity until their `task.settled`.**10. Tests and release readiness.** The test pass in §10, a Tasks guide in `docs/` (choosing-`execute`, `task()`, or `serve()`, the ordering pattern, signals), and the upgrade guide from §8. Then release, and migrate+`execute`, `task()`, or `serve()`, the ordering pattern, signals), and the upgrade guide from §8.+It folds `ctx.interruptSignal` into `abortSignal` and `WorkflowTaskContext` into+`WorkflowToolContext` (§2). Then release, and migrateinternal-agents.## 10. Tests after the stack@@ -721,8 +753,8 @@ suites under the fixtures they exercise.**E2E (mock model):**- An `execute` tool's result arrives as its tool result.-- Steering ends `sleep` but not an approval-gated tool, and a withdrawn ask reports- `outcome: "cancelled"`.+- Steering ends `sleep` and a waited body that rejects on abort, which settles as+ `{ interrupted: true }`, and a withdrawn ask reports `outcome: "cancelled"`.- A `task()` tool starts, is waited on, and delivers its result; `task_cancel` stops one.- The turn rule in each session kind: `turn.waiting` in a root session, a child turn, and aschedule's turn; a held root turn's `send().result()` and MCP `agent_start` with a delegating@@ -730,6 +762,8 @@ suites under the fixtures they exercise.- A task's question during a hold emits `input.requested`, then `turn.waiting`, and the answeredturn completes once.- A user-defined `serve()` tool is continued by `taskId`, cancelled, and continued again.+- Cancelling a `serve()` task withdraws its pending question as `cancelled`, and the task serves+ its next call.- An agent, local and remote, is continued by `taskId` across turns and after `task_cancel` withits conversation intact; a child's question is answered at the root.- Slack posts the text of a step whose only tool call is `task_wait`.@@ -741,21 +775,23 @@ told there's no rush; doesn't use a side-effect tool before the result it depend**Candidates beyond e2e,** decided in this pass because e2e can't hit them deterministically:duplicate settlement; a result before the run reports started; a cancel before it starts; a crash-between the record and the start; a hard stop racing a result; a result settling as `task_wait`+between the record and the start; a cancel's cleanup deadline racing a result; a result settling as `task_wait`starts or ends; an agent message racing the end of its turn; a call arriving before a `serve`-body's first `receive()`.+body's first `receive()`; a person's answer the session accepts after the run asked to withdraw+the question but before the session handled the request.## 11. Risks and accepted costs1. **One more model step per needed result** (start, then wait), and one wake per result when themodel needs several.2. **Long `execute` tools** hold the conversation until they settle.-3. **`interruptSignal` is unproven** until PR 3's spike.+3. **A body that ignores `abortSignal` holds the turn after a steering message.** The call isn't+ cancelled, so there is no cleanup deadline.4. **Shared-thread wait.** Another person's message waits for a held turn, tasks included. Oneopen turn per principal is the first follow-up.5. **`serve` bodies own their correctness.** A body must catch its stretch's abort to stayavailable, one that never replies holds the turn until its call is cancelled, and one that- ignores `abortSignal` keeps working after a cancel.+ ignores `abortSignal` ends 30 s after a cancel instead of staying available.6. **Every agent task costs a workflow run** around its child session.7. **A lost remote completion** leaves its task working until the session ends; remote callbackretries and an `agent_state` tool are follow-ups.diff --git a/scripts/guard-invariants.mjs b/scripts/guard-invariants.mjsindex b599f3d36..5ee838d4d 100644--- a/scripts/guard-invariants.mjs+++ b/scripts/guard-invariants.mjs@@ -96,11 +96,6 @@* `pnpm --filter eve build`. Turbo owns workspace dependency* ordering; nested builds race on eve's clean-and-publish dist* directory and let consumers observe a partial package.- * rule 42 — The shared subagent workflow body is framework-authored- * userspace. It must not import task, harness, or context- * internals or recover private state through `Symbol.for`.- * Privileged dispatch belongs in ordinary step-backed APIs that- * the workflow body consumes through a public contract.* rule 43 — Reusable session plumbing stays independent of the subagent* executor. The generic inbox and state cursor must not* import subagent modules; session/turn composition roots may@@ -109,13 +104,24 @@* `defineSandboxProvider()` and does not import sandbox runtime* orchestration, registries, key derivation, or session state.* Built-ins and authored providers must share one contract.- * rule 45 — Provided tools under `packages/eve/src/tools/provided/**` import- * only public eve entry points (the `#` specifiers of the- * package's `exports`), the vendored Workflow SDK that authored- * bodies import as `workflow`, and each other. eve is built on- * eve: a provided tool that needs a private hook means authors- * cannot build the same tool. Files that predate the rule are- * baselined and may only leave the baseline.+ * rule 45 — Provided tools under `packages/eve/src/tools/provided/**` and+ * the body of every agent tool import only public eve entry+ * points (the `#` specifiers of the package's `exports`), the+ * vendored Workflow SDK that authored bodies import as+ * `workflow`, and each other. eve is built on eve: a provided+ * tool that needs a private hook means authors cannot build the+ * same tool. Files that predate the rule are baselined and may+ * only leave the baseline.+ * rule 46 — Tasks own their records and their words. Only+ * `execution/tasks/table*.ts` names the session's task table, so+ * every record write goes through it, and the model-facing task+ * markers appear only in `execution/tasks/render.ts`, which holds+ * all of the tasks' model text.+ * rule 47 — A caller hears from its session only at a turn's real end.+ * Only `execution/session/program.ts` sends the caller's reply,+ * after the turn loop returns, and `execution/session/finalization.ts`+ * when the session ends. A held turn is still open, so nothing+ * inside the turn loop or the harness may reply.** Baselines for rules with pre-existing violations live in* `guard-invariants-baseline.json`. Counts and allowlists in that file@@ -210,10 +216,11 @@ function isTsLike(relPath) {* rule33: Violation[];* rule35: Violation[];* rule37: Violation[];- * rule42: Violation[];* rule43: Violation[];* rule44: Violation[];* rule45: { allowlist: Set<string>; violations: Violation[] };+ * rule46: Violation[];+ * rule47: Violation[];* symlinks: string[];* }} state*/@@ -242,48 +249,18 @@ async function scanRepo(state) {checkRule33(posix, lines, state.rule33);checkRule35(posix, lines, state.rule35);checkRule37(posix, content, state.rule37);- checkRule42(posix, lines, state.rule42);checkRule43(posix, lines, state.rule43);checkRule44(posix, lines, state.rule44);checkRule45(posix, lines, state.rule45);+ checkRule46(posix, lines, state.rule46);+ checkRule47(posix, lines, state.rule47);}}-// ---------- Rule 42: userspace subagent workflow ------------const SUBAGENT_WORKFLOW_PATH = "packages/eve/src/runtime/subagents/workflow.ts";-const SUBAGENT_WORKFLOW_PRIVATE_IMPORT_RE =- /["']#(?:tasks|execution|harness|context|shared)(?:\/|\.js)/;-// The shared body owns its invocation id, so it consumes the framework-internal-// entry rather than the public `agent()`; that import is the one exception.-const SUBAGENT_WORKFLOW_ALLOWED_IMPORT = '"#execution/tools/subagent/invoke-agent.js"';--/**- * @param {string} posix- * @param {string[]} lines- * @param {Violation[]} violations- */-function checkRule42(posix, lines, violations) {- if (posix !== SUBAGENT_WORKFLOW_PATH) return;-- lines.forEach((line, idx) => {- if (line.includes(SUBAGENT_WORKFLOW_ALLOWED_IMPORT)) return;- if (!SUBAGENT_WORKFLOW_PRIVATE_IMPORT_RE.test(line) && !line.includes("Symbol.for(")) return;- violations.push({- rule: 42,- file: posix,- line: idx + 1,- message:- "the shared subagent workflow reaches into task, harness, or context internals. Keep the body userspace-shaped and call a public workflow-safe agent API instead.",- });- });-}-// ---------- Rule 43: executor-neutral session plumbing ----------// Matches both `#` alias specifiers and relative paths into the executor trees.-const SUBAGENT_IMPORT_RE =- /from ["'](?:#|(?:\.\.?\/)+(?:[\w-]+\/)*)(?:subagents|execution\/tools\/subagent|tools\/subagent)(?:\/|\.js|["'])/;+const SUBAGENT_IMPORT_RE = /from ["'](?:#|(?:\.\.?\/)+(?:[\w-]+\/)*)subagents(?:\/|\.js|["'])/;const RULE43_GENERIC_SESSION_FILES = new Set(["packages/eve/src/execution/session-hook-claims.ts",@@ -345,6 +322,8 @@ function checkRule44(posix, lines, violations) {// ---------- Rule 45: provided tools use only public entry points ----------const PROVIDED_TOOLS_DIR = "packages/eve/src/tools/provided/";+// Every agent tool is a `serve` workflow tool eve generates around this body.+const AGENT_TOOL_BODY_PATH = "packages/eve/src/runtime/subagents/workflow.ts";const EVE_PACKAGE_EXPORTS = require(join(REPO_ROOT, "packages/eve/package.json")).exports;const EXPORTED_TYPES_PATH_RE = /^\.\/dist\/src\/(.+)\.d\.ts$/;@@ -376,9 +355,12 @@ const PROVIDED_TOOL_EXTRA_IMPORTS = new Set(["#tools/schema.js",]);-// The task kernel's `task_wait` and `task_cancel` read the session's task table-// directly. When they land, list their files here rather than in the baseline.-const PROVIDED_KERNEL_TOOL_FILES = new Set();+// `task_wait` and `task_cancel` belong to the session, not to authors: they+// take their model text from execution/tasks/render.ts directly.+const PROVIDED_TASK_TOOL_FILES = new Set([+ "packages/eve/src/tools/provided/task-cancel.ts",+ "packages/eve/src/tools/provided/task-wait.ts",+]);const IMPORT_SPECIFIER_RE = /(?:\bfrom\s+|\bimport\s*\(\s*|^\s*import\s+)["']([^"']+)["']/;@@ -395,8 +377,9 @@ function isProvidedToolImportAllowed(specifier) {* @param {{ allowlist: Set<string>; violations: Violation[] }} state*/function checkRule45(posix, lines, state) {- if (!posix.startsWith(PROVIDED_TOOLS_DIR) || posix.endsWith(".test.ts")) return;- if (state.allowlist.has(posix) || PROVIDED_KERNEL_TOOL_FILES.has(posix)) return;+ const provided = posix.startsWith(PROVIDED_TOOLS_DIR) && !posix.endsWith(".test.ts");+ if (!provided && posix !== AGENT_TOOL_BODY_PATH) return;+ if (state.allowlist.has(posix) || PROVIDED_TASK_TOOL_FILES.has(posix)) return;lines.forEach((line, idx) => {// Doc comments show authors how to import the tool from its public entry.if (/^\s*(?:\*|\/\/)/.test(line)) return;@@ -411,6 +394,72 @@ function checkRule45(posix, lines, state) {});}+// ---------- Rule 46: tasks own their records and model text ----------++const TASKS_DIR = "packages/eve/src/execution/tasks/";+const TASK_TABLE_FILE_RE = /^packages\/eve\/src\/execution\/tasks\/table[\w-]*\.ts$/;+const TASK_RENDER_FILE = `${TASKS_DIR}render.ts`;+const TASK_TABLE_KEY = '"eve.taskTable"';+const TASK_MODEL_MARKERS = ["<task_result", "[Tasks]", "Started task ", "Sent to task "];++/**+ * @param {string} posix+ * @param {string[]} lines+ * @param {Violation[]} violations+ */+function checkRule46(posix, lines, violations) {+ if (!posix.startsWith("packages/eve/src/") || posix.endsWith(".test.ts")) return;+ lines.forEach((line, idx) => {+ if (line.includes(TASK_TABLE_KEY) && !TASK_TABLE_FILE_RE.test(posix)) {+ violations.push({+ rule: 46,+ file: posix,+ line: idx + 1,+ message:+ "names the session's task table outside execution/tasks/table*.ts. Read and write task records through the table module's helpers.",+ });+ }+ if (posix === TASK_RENDER_FILE || /^\s*(?:\/?\*|\/\/)/.test(line)) return;+ const marker = TASK_MODEL_MARKERS.find((candidate) => line.includes(candidate));+ if (marker === undefined) return;+ violations.push({+ rule: 46,+ file: posix,+ line: idx + 1,+ message: `writes the model-facing task text "${marker}" outside execution/tasks/render.ts. Keep every string the model reads about tasks in the renderer and import it from there.`,+ });+ });+}++// ---------- Rule 47: one caller-reply site ----------++const CALLER_REPLY_DEFINITION_FILE = "packages/eve/src/subagents/parent-notification.ts";+const CALLER_REPLY_FILES = new Set([+ "packages/eve/src/execution/session/program.ts",+ "packages/eve/src/execution/session/finalization.ts",+]);+const CALLER_REPLY_CALL_RE = /\b(?:notifyTurnCallerStep|notifyCancelledTaskCallerStep)\(/;++/**+ * @param {string} posix+ * @param {string[]} lines+ * @param {Violation[]} violations+ */+function checkRule47(posix, lines, violations) {+ if (!posix.startsWith("packages/eve/src/") || posix.endsWith(".test.ts")) return;+ if (posix === CALLER_REPLY_DEFINITION_FILE || CALLER_REPLY_FILES.has(posix)) return;+ lines.forEach((line, idx) => {+ if (!CALLER_REPLY_CALL_RE.test(line)) return;+ violations.push({+ rule: 47,+ file: posix,+ line: idx + 1,+ message:+ "sends a caller's reply outside execution/session/program.ts and execution/session/finalization.ts. A turn replies to its caller only at its real end, which the session program owns; finalization replies when the session ends.",+ });+ });+}+// ---------- Rule 13: spread-ternary object composition ----------/** Matches `...(<expr> ? {} : { ... })` or the mirrored form. */@@ -1459,13 +1508,14 @@ async function main() {rule33: /** @type {Violation[]} */ ([]),rule35: /** @type {Violation[]} */ ([]),rule37: /** @type {Violation[]} */ ([]),- rule42: /** @type {Violation[]} */ ([]),rule43: /** @type {Violation[]} */ ([]),rule44: /** @type {Violation[]} */ ([]),rule45: {allowlist: new Set(baseline.rule45_providedToolPrivateImportAllowlist),violations: /** @type {Violation[]} */ ([]),},+ rule46: /** @type {Violation[]} */ ([]),+ rule47: /** @type {Violation[]} */ ([]),symlinks: /** @type {string[]} */ ([]),};@@ -1565,9 +1615,6 @@ async function main() {// Rule 38violations.push(...(await checkRule38NoNestedEveBuild()));- // Rule 42- violations.push(...state.rule42);-// Rule 43violations.push(...state.rule43);violations.push(...state.rule44);@@ -1580,6 +1627,12 @@ async function main() {// Rule 45violations.push(...state.rule45.violations);+ // Rule 46+ violations.push(...state.rule46);++ // Rule 47+ violations.push(...state.rule47);+if (violations.length === 0) {process.stdout.write("[eve:guard:invariants] ok — all mechanical lints passed.\n");return;