The Open Framework for Building Agents
feat(eve): harden task tool guidance for models (#3948)
Andrew Barbace14b1eec04b
diff --git a/.changeset/channel-step-completed.md b/.changeset/channel-step-completed.mdnew file mode 100644index 000000000..a75ef712d--- /dev/null+++ b/.changeset/channel-step-completed.md@@ -0,0 +1,5 @@+---+"eve": patch+---++`defineChannel` event handlers can now subscribe to `step.completed`, the same event hooks receive when a model step finishes.diff --git a/.changeset/slack-post-before-task-wait.md b/.changeset/slack-post-before-task-wait.mddeleted file mode 100644index c6edd73ea..000000000--- a/.changeset/slack-post-before-task-wait.md+++ /dev/null@@ -1,5 +0,0 @@-----"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/task-tool-guidance.md b/.changeset/task-tool-guidance.mdnew file mode 100644index 000000000..f7cbf21d9--- /dev/null+++ b/.changeset/task-tool-guidance.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Models now get clearer task guidance: call `task_wait` when there's nothing to say until a result arrives, reply when the person should hear something first, and in child and schedule sessions wait instead of replying. `task_wait` takes `timeoutSeconds` instead of `timeout` in milliseconds, `task_cancel` answers in plain text, and receipts and failed agent results tell the model what happens next.diff --git a/docs/channels/slack.mdx b/docs/channels/slack.mdxindex 82963ea0c..b63905c91 100644--- a/docs/channels/slack.mdx+++ b/docs/channels/slack.mdx@@ -450,10 +450,12 @@ 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. 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 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 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.+When the model replies while its [tasks](/docs/tools/tasks) keep working, that reply posts like any other, and the reply after the results posts as another message. A schedule's session posts only the final reply.+Outbound text preserves bare `@` tokens as literal text. To mention a user, embed Slack's `<@USER_ID>` syntax directly or use `channel.thread.mentionUser(userId)`.When a session starts without a `threadTs` (say, from a schedule's `to(slack, target).send(...)`), eve gives it a unique temporary continuation token. The first agent post anchors the session to the Slack message timestamp, and later posts and mentions resume that same session. Pass `initialMessage` with a `Card` to land a structured anchor first instead. `threadTs` and `initialMessage` are mutually exclusive.diff --git a/docs/concepts/built-in-tools.md b/docs/concepts/built-in-tools.mdindex d3e4b0fc9..e6d04b293 100644--- a/docs/concepts/built-in-tools.md+++ b/docs/concepts/built-in-tools.md@@ -275,8 +275,8 @@ An authored `agent/tools/connection_search.ts` replaces the framework behavior.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.+- `task_wait({ timeoutSeconds? })` parks the turn until any task has a result, a new message arrives, or `timeoutSeconds` 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 says so, or says the task had no work to stop when it 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.diff --git a/docs/subagents/index.mdx b/docs/subagents/index.mdxindex c51281946..fca0f5560 100644--- a/docs/subagents/index.mdx+++ b/docs/subagents/index.mdx@@ -28,7 +28,7 @@ The root session receives `agent` by default. The model calls it to delegate a t}```-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.+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, so several children can work at once, whether the model starts them in one response or across several. 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.diff --git a/docs/tools/tasks.md b/docs/tools/tasks.mdindex a588e3975..8f310f3c3 100644--- a/docs/tools/tasks.md+++ b/docs/tools/tasks.md@@ -134,16 +134,20 @@ provided `sleep` tool races its timer against the signal.## What the model seeseve 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.+the agent has an agent tool or a `task` or `serve` workflow tool. The block tells the model to call+`task_wait` when it has nothing to say until a result arrives, and to reply when the person should+hear from it first, such as a confirmation that work is underway. In a child session or a+schedule's session, where only the final reply reaches the caller, it tells the model to call+`task_wait` instead of replying while tasks work.**Receipts.** A call that starts a task returns a receipt as its tool result. Task ids are the toolname and six characters. A resumable task's receipt tells the model how to reach it again, and acall 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.+Started task deploy-4hd8sa. Its result will arrive in a <task_result> message.+Started task researcher-7k2m9q. Its result will arrive in a <task_result> message. To send it another message, call researcher again with taskId researcher-7k2m9q.+Sent to task researcher-7k2m9q. Its reply will arrive in a <task_result> message.```**Results.** Each result arrives once, as a `<task_result>` block in a `task.result` message that@@ -156,18 +160,24 @@ text is cut and marked `[truncated]`.<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:+**`task_wait({ timeoutSeconds? })`** parks the turn until any task has a result, a new message+arrives, or `timeoutSeconds` pass. `timeoutSeconds` is a whole number of at least 1, in seconds+like `sleep`. It returns at once when a result is already waiting. Waiting never stops a task. The+model reads which tasks settled and which are still working, for example:```textdeploy-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" }`.+**`task_cancel({ taskId })`** stops a task's current work and says so. A resumable task's answer+also tells the model how to give it new work. When the task has no work to stop, because it already+finished or is an idle resumable task, `task_cancel` says that instead:++```text+Stopped deploy-4hd8sa; it won't report back.+Stopped researcher-7k2m9q's current work; it won't report back. To give it new work, call researcher again with taskId researcher-7k2m9q.+researcher-7k2m9q had no work to stop.+```**`[Tasks]` note.** When the session's tasks change, eve adds a note at the next step boundary thatlists the working tasks and the 10 most recently used idle resumable tasks. The note returns after@@ -185,11 +195,11 @@ lists the working tasks and the 10 most recently used idle resumable tasks. The**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 |+| 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 has no work to stop |+| `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.@@ -218,9 +228,9 @@ In every session, `turn.completed` comes only when the turn really ends. The Typ`send(...).result()` and the MCP channel's `agent_get` read past `turn.waiting` and report thefinal reply rather than the text written before the wait. `result()` stops at `turn.waiting` onlywhile 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.+same turn to its end. See [Aggregate a turn](/docs/guides/client/streaming#aggregate-a-turn).+Channels such as [Slack](/docs/channels/slack) post a root session's text before the wait as an+ordinary reply, then post the reply after the results as another message.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 itdiff --git a/docs/tools/workflows.mdx b/docs/tools/workflows.mdxindex 1cad77fad..cd9d76f24 100644--- a/docs/tools/workflows.mdx+++ b/docs/tools/workflows.mdx@@ -264,8 +264,9 @@ 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.+- **Receipt:** the call's tool result is a receipt, such as+ `Started task deploy-4hd8sa. Its result will arrive in a <task_result> message.`, 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 theresult, not the receipt.@@ -320,9 +321,10 @@ described in [Tasks](/docs/tools/tasks). What differs: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 andappends 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+ whose receipt names it and ends with+ `To send it another message, call release-plan again with taskId release-plan-7k2m9q.` A call+ with `taskId` goes to that task and returns a receipt that starts+ `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 callfails with `UNKNOWN_TASK`. The call can come from any caller in the session.@@ -355,8 +357,8 @@ release-plan-7k2m9q to send it another message.` A call with `taskId` goes to thsignal, 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 waitingcalls 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+ so the task becomes idle and stays available. `task_cancel` on an idle task says the task had no+ work to stop. To stay available, a body must catch its stretch's abort andreturn to `receive()`, as the example does; an abort that escapes the body finishes the task. Abody that ignores the signal keeps working and its reply is dropped, but a body that doesn'treturn to `receive()` within 30 seconds of a cancel ends, and the task finishes.diff --git a/e2e/fixtures/agent-cancellation/agent/agent.ts b/e2e/fixtures/agent-cancellation/agent/agent.tsindex 1bdf06522..347546dff 100644--- a/e2e/fixtures/agent-cancellation/agent/agent.ts+++ b/e2e/fixtures/agent-cancellation/agent/agent.ts@@ -109,7 +109,7 @@ function cancelAndContinueSleeper(request: MockModelRequest): MockModelResponseconst 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" }] };+ return { toolCalls: [{ input: { timeoutSeconds: 2 }, name: "task_wait" }] };}if (calls("task_cancel").length === 0) {return { toolCalls: [{ input: { taskId }, name: "task_cancel" }] };diff --git a/e2e/fixtures/agent-subagents/agent/lib/notebook.ts b/e2e/fixtures/agent-subagents/agent/lib/notebook.tsindex 2236e2b98..f6e415e87 100644--- a/e2e/fixtures/agent-subagents/agent/lib/notebook.ts+++ b/e2e/fixtures/agent-subagents/agent/lib/notebook.ts@@ -79,7 +79,7 @@ function parentTurn(input: (request) => ({ message: REVIEW_ENTRY, taskId: keeperTask(request) }),name: tool,},- { id: "notebook-review-wait", input: () => ({ timeout: 2_000 }), name: "task_wait" },+ { id: "notebook-review-wait", input: () => ({ timeoutSeconds: 2 }), name: "task_wait" },{id: "notebook-cancel",input: (request) => ({ taskId: keeperTask(request) }),diff --git a/e2e/fixtures/agent-subagents/evals/agent-continuation.shared.ts b/e2e/fixtures/agent-subagents/evals/agent-continuation.shared.tsindex cc92ad777..de7ac4c60 100644--- a/e2e/fixtures/agent-subagents/evals/agent-continuation.shared.ts+++ b/e2e/fixtures/agent-subagents/evals/agent-continuation.shared.ts@@ -20,7 +20,7 @@ export async function continueKeeperAcrossTurns(t: EveEvalContext, tool: string)`NOTEBOOK-REVIEW ${tool} Alice asks for a review, then changes her mind.`,);reviewed.expectOk();- reviewed.calledTool("task_cancel", { count: 1, output: { status: "cancelled" } });+ reviewed.calledTool("task_cancel", { count: 1, output: /^Stopped \S+'s current work;/u });reviewed.event("task.settled", {count: 1,data: { callId: "notebook-review", status: "cancelled" },diff --git a/e2e/fixtures/agent-tasks/evals/no-rush.eval.ts b/e2e/fixtures/agent-tasks/evals/no-rush.eval.tsindex 21355cb20..ff7437d91 100644--- a/e2e/fixtures/agent-tasks/evals/no-rush.eval.ts+++ b/e2e/fixtures/agent-tasks/evals/no-rush.eval.ts@@ -1,12 +1,13 @@import { defineEval } from "eve/evals";-import { firstSettlementOf, heldTurn, taskStarts } from "./task-events";+import { firstSettlementOf, heldTurn, reportIdOf, settlementsOf, 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.+ * turn. The confirmation doesn't guess a report id, and the reply after the+ * result reports the real one.*/export default defineEval({description: "The model doesn't wait on a task when told there's no rush.",@@ -27,7 +28,20 @@ export default defineEval({);return callIds.length === 1 && replied >= 0 && replied < settled;});+ turn.eventsSatisfy("the confirmation doesn't guess a report id", (events) => {+ const confirmation = events.find(+ (event) => event.type === "message.completed" && event.data.finishReason === "stop",+ );+ return confirmation?.type === "message.completed" && !/RPT-/u.test(confirmation.data.message);+ });turn.event("task.settled", { count: 1, data: { status: "completed" } });+ turn.eventsSatisfy("the reply after the result reports the report id", (events) => {+ const callIds = taskStarts(events, "compile_report").map((call) => call.callId);+ const reportId = settlementsOf(events, callIds).flatMap(+ (settled) => reportIdOf(settled) ?? [],+ )[0];+ return reportId !== undefined && (turn.message ?? "").includes(reportId);+ });t.noFailedActions();},});diff --git a/e2e/fixtures/agent-workflow-tools/agent/lib/task-scenarios.ts b/e2e/fixtures/agent-workflow-tools/agent/lib/task-scenarios.tsindex bbeb5ef9d..f1fe861fb 100644--- a/e2e/fixtures/agent-workflow-tools/agent/lib/task-scenarios.ts+++ b/e2e/fixtures/agent-workflow-tools/agent/lib/task-scenarios.ts@@ -74,7 +74,7 @@ const SCENARIOS: Readonly<Record<string, Scenario>> = {request,[{ id: "plan-hold", input: revisionOf(HOLD_REQUEST), name: "revise_plan" },- { id: "plan-hold-wait", input: () => ({ timeout: 1_000 }), name: "task_wait" },+ { id: "plan-hold-wait", input: () => ({ timeoutSeconds: 1 }), 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" },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.tsindex d9852abd8..e13eb069d 100644--- a/e2e/fixtures/agent-workflow-tools/evals/canary-deploy.cancel.eval.ts+++ b/e2e/fixtures/agent-workflow-tools/evals/canary-deploy.cancel.eval.ts@@ -12,11 +12,13 @@ export default defineEval({turn.expectOk();turn.event("task.started", { count: 1, data: { callId: "canary", name: "canary_deploy" } });- turn.calledTool("task_cancel", { count: 1, output: { status: "cancelled" } });+ turn.calledTool("task_cancel", { count: 1, output: /^Stopped \S+; it won't report back\.$/u });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"}');+ turn.messageIncludes(+ /WORKFLOW-CANARY-RESULT Stopped canary_deploy-\w{6}; it won't report back\./u,+ );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.tsindex 328c65d4a..3e72128a7 100644--- a/e2e/fixtures/agent-workflow-tools/evals/revise-plan.serve.eval.ts+++ b/e2e/fixtures/agent-workflow-tools/evals/revise-plan.serve.eval.ts@@ -16,15 +16,18 @@ export default defineEval({drafted.expectOk();drafted.calledTool("revise_plan", {count: 1,- output: /^Started task revise_plan-\w{6}\. Call revise_plan again with taskId/u,+ 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("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.calledTool("task_cancel", {+ count: 1,+ output: /^Stopped revise_plan-\w{6}'s current work;/u,+ });revised.event("task.settled", { count: 1, data: { callId: "plan-hold", status: "cancelled" } });revised.event("task.settled", {count: 1,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.tsindex 3c50d71f4..6a23073d1 100644--- 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.ts@@ -23,7 +23,10 @@ export default defineEval({const reworked = await parked.session.send(ALICE_REWORK, { turnPolicy: "steer" });reworked.expectOk();- reworked.calledTool("task_cancel", { count: 1, output: { status: "cancelled" } });+ reworked.calledTool("task_cancel", {+ count: 1,+ output: /^Stopped sign_off_plan-\w{6}'s current work;/u,+ });reworked.messageIncludes('WORKFLOW-SIGNOFF-RESULT {"notes":["rework the plan first"]}');// Follow the stream as a channel does: the question resolves once, as withdrawn.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.tsindex a44e3afbf..b3caea782 100644--- a/e2e/fixtures/agent-workflow-tools/evals/stage-deploy.task.eval.ts+++ b/e2e/fixtures/agent-workflow-tools/evals/stage-deploy.task.eval.ts@@ -12,7 +12,10 @@ export default defineEval({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.calledTool("stage_deploy", {+ count: 1,+ output: /^Started task stage_deploy-\w{6}\. Its result will arrive/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", {diff --git a/packages/eve/src/execution/node-step.test.ts b/packages/eve/src/execution/node-step.test.tsindex 6a516e043..0503c9a12 100644--- a/packages/eve/src/execution/node-step.test.ts+++ b/packages/eve/src/execution/node-step.test.ts@@ -264,8 +264,8 @@ describe("createNodeHarnessTools", () => {const agentTool = createNodeHarnessTools({ node }).get("agent");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("several agents can work at once");+ expect(agentTool?.description).toContain("state the goal, what to return");expect(agentTool?.description).toContain("put everything it needs in message");expect(agentTool?.description).toContain("non-overlapping scopes");expect(agentTool?.description).not.toMatch(/\beve\b/);diff --git a/packages/eve/src/execution/session/turn.ts b/packages/eve/src/execution/session/turn.tsindex 39abcdcb7..e33fd200e 100644--- a/packages/eve/src/execution/session/turn.ts+++ b/packages/eve/src/execution/session/turn.ts@@ -417,15 +417,13 @@ interface TaskWait {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 };+ const timer = timeoutMs === undefined ? undefined : sleep(timeoutMs).then(() => callId);+ return { callId, startedAtMs: Date.now(), timedOut: false, timer };}type RuntimeEvent =diff --git a/packages/eve/src/execution/tasks/calls.test.ts b/packages/eve/src/execution/tasks/calls.test.tsnew file mode 100644index 000000000..c344a53e5--- /dev/null+++ b/packages/eve/src/execution/tasks/calls.test.ts@@ -0,0 +1,21 @@+import { expect, it } from "vitest";++import { pendingTaskToolCalls } from "#execution/tasks/calls.js";++it("reads task_wait's timeoutSeconds as the milliseconds the turn waits", () => {+ const calls = pendingTaskToolCalls([+ {+ content: [+ {+ input: { timeoutSeconds: 90 },+ toolCallId: "wait-1",+ toolName: "task_wait",+ type: "tool-call",+ },+ ],+ role: "assistant",+ },+ ]);++ expect(calls).toEqual([{ callId: "wait-1", kind: "task_wait", timeoutMs: 90_000 }]);+});diff --git a/packages/eve/src/execution/tasks/calls.ts b/packages/eve/src/execution/tasks/calls.tsindex ff81d84f2..a6d5054ce 100644--- a/packages/eve/src/execution/tasks/calls.ts+++ b/packages/eve/src/execution/tasks/calls.ts@@ -41,10 +41,11 @@ export function pendingTaskToolCalls(messages: readonly ModelMessage[]): TaskTooconst 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");+ // Seconds, to match `sleep`.+ const timeoutSeconds: unknown = Reflect.get(input, "timeoutSeconds");calls.push(- typeof timeout === "number"- ? { callId: part.toolCallId, kind: "task_wait", timeoutMs: timeout }+ typeof timeoutSeconds === "number"+ ? { callId: part.toolCallId, kind: "task_wait", timeoutMs: timeoutSeconds * 1_000 }: { callId: part.toolCallId, kind: "task_wait" },);}@@ -66,7 +67,11 @@ export type TaskWaitResult =}| { readonly status: "timeout" | "interrupt"; readonly working: readonly string[] };-export type TaskCancelResult = { readonly status: "cancelled" | "already_finished" };+export interface TaskCancelResult {+ readonly resumable: boolean;+ readonly status: "cancelled" | "already_finished";+ readonly tool: string;+}// Built directly: the workflow body can't import the harness's result helpers.export function taskToolResult(diff --git a/packages/eve/src/execution/tasks/model-step.ts b/packages/eve/src/execution/tasks/model-step.tsindex 7fda6faaf..e5b869399 100644--- a/packages/eve/src/execution/tasks/model-step.ts+++ b/packages/eve/src/execution/tasks/model-step.ts@@ -2,6 +2,7 @@ import type { ModelMessage, SystemModelMessage } from "ai";import { TASK_CANCEL_TOOL_NAME, TASK_WAIT_TOOL_NAME } from "#execution/tasks/calls.js";import {+ FINAL_REPLY_TASK_SYSTEM_BLOCK,renderModelOutputText,renderTaskResults,renderTasksNote,@@ -58,8 +59,18 @@ export function withTaskTools(tools: HarnessToolMap): HarnessToolMap {]);}-export function taskSystemMessages(tools: HarnessToolMap): SystemModelMessage[] {- return offersTasks(tools) ? [{ content: TASK_SYSTEM_BLOCK, role: "system" }] : [];+/**+ * The task block, when the agent can start tasks. `finalReplyOnly` is set for a+ * child or schedule session, which hides a held turn's text, so a reply before+ * a result would reach no one.+ */+export function taskSystemMessages(+ tools: HarnessToolMap,+ options: { readonly finalReplyOnly: boolean },+): SystemModelMessage[] {+ if (!offersTasks(tools)) return [];+ const content = options.finalReplyOnly ? FINAL_REPLY_TASK_SYSTEM_BLOCK : TASK_SYSTEM_BLOCK;+ return [{ content, role: "system" }];}/** A deferred call as the model made it, before the session knows what it enters. */diff --git a/packages/eve/src/execution/tasks/render.ts b/packages/eve/src/execution/tasks/render.tsindex a959707b9..fb3e49b33 100644--- a/packages/eve/src/execution/tasks/render.ts+++ b/packages/eve/src/execution/tasks/render.ts@@ -1,19 +1,46 @@-import type { TaskWaitResult } from "#execution/tasks/calls.js";+import type { TaskCancelResult, 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.";+ "Wait silently until any of your tasks has a result, a new message arrives, or timeoutSeconds pass. Call it when you have nothing to say until a result arrives. It returns after the first result, which follows in a <task_result> message; call it again to wait for the rest. Waiting never stops a task.";-export const TASK_WAIT_TIMEOUT_DESCRIPTION = "How long to wait, in milliseconds.";+export const TASK_WAIT_TIMEOUT_DESCRIPTION =+ "Optional. Seconds to wait before returning without a result. Omit it to wait for a result or a new message, which is almost always right. Don't use short timeouts to check on tasks: results reach you without checking.";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.";+const TASK_ID_SOURCE = 'copied from its "Started task" receipt or the [Tasks] note';++export const TASK_CANCEL_TASK_ID_DESCRIPTION = `The id of the task to stop, ${TASK_ID_SOURCE}.`;++const TASK_SYSTEM_BLOCK_OPENING = [+ "Tasks",+ '- A call that returns "Started task <id>" is a task: it keeps working while you continue. Every agent call is a task.',+ "- Each result arrives once, in a <task_result> message. Until then you know nothing about it, so don't guess or report its result.",+ "- Ending your reply doesn't end your turn. While tasks work, eve holds your turn and calls you again with each result.",+];++const TASK_SYSTEM_BLOCK_CLOSING = [+ "- Don't redo work you delegated. Never use sleep or shell commands to wait for a task.",+ "- To correct or continue an agent, or any task that accepts more input, call its tool again with its taskId. A new message never stops your tasks: answer it if it asks you something, decide whether it changes the work, then keep each task, correct an agent by taskId, or stop a task with task_cancel.",+];++/** The task block for a session a person reads, where a reply before a result is posted. */+export const TASK_SYSTEM_BLOCK = [+ ...TASK_SYSTEM_BLOCK_OPENING,+ "- If you have nothing to tell the person until a result arrives, call task_wait. Start every independent task first, then wait.",+ "- If the person should hear from you now, for example to confirm work is underway when they don't need the result yet, reply. When results arrive, report them without repeating yourself.",+ ...TASK_SYSTEM_BLOCK_CLOSING,+].join("\n");++/** The task block for a child or schedule session, whose caller reads only the final reply. */+export const FINAL_REPLY_TASK_SYSTEM_BLOCK = [+ ...TASK_SYSTEM_BLOCK_OPENING,+ "- Only your final reply reaches your caller. While tasks work, call task_wait instead of replying. Start every independent task first, then wait.",+ ...TASK_SYSTEM_BLOCK_CLOSING,+].join("\n");/** Appended to a `serve` tool's description. */export const SERVE_TOOL_DESCRIPTION =@@ -24,8 +51,7 @@ 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.";+export const TASK_ID_INPUT_DESCRIPTION = `The id of a task this tool started, ${TASK_ID_SOURCE}, 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]";@@ -46,19 +72,31 @@ export function renderTaskReceipt(task: {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.`;+ const started = `Started task ${task.id}. Its result will arrive in a <task_result> message.`;+ if (!task.resumable) return started;+ return `${started} To send it another message, call ${task.tool} again with taskId ${task.id}.`;}/** The receipt for a call that reaches a resumable task by its `taskId`. */export function renderTaskSentReceipt(taskId: string): string {- return `Sent to task ${taskId}.`;+ return `Sent to task ${taskId}. Its reply will arrive in a <task_result> message.`;}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 renderUnknownCancelTaskError(taskId: string): string {+ return `No task "${taskId}" is in this session. Copy an id from a "Started task" receipt or the [Tasks] note.`;+}++/** What the model reads when `task_cancel` answers. */+export function renderTaskCancelResult(taskId: string, result: TaskCancelResult): string {+ if (result.status === "already_finished") return `${taskId} had no work to stop.`;+ if (!result.resumable) return `Stopped ${taskId}; it won't report back.`;+ return `Stopped ${taskId}'s current work; it won't report back. To give it new work, call ${result.tool} again with taskId ${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.`;}diff --git a/packages/eve/src/execution/tasks/session.ts b/packages/eve/src/execution/tasks/session.tsindex b29a2b0d8..43a448fd0 100644--- a/packages/eve/src/execution/tasks/session.ts+++ b/packages/eve/src/execution/tasks/session.ts@@ -4,12 +4,11 @@ import {taskToolResult,type TaskToolCall,} from "#execution/tasks/calls.js";-import { renderUnknownTaskError } from "#execution/tasks/render.js";+import { renderTaskCancelResult, renderUnknownCancelTaskError } 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";@@ -49,12 +48,16 @@ export async function answerTaskCancel(if (result === undefined) {const error = {code: "UNKNOWN_TASK",- message: renderUnknownTaskError(call.taskId, taskToolName(call.taskId)),+ message: renderUnknownCancelTaskError(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);+ return taskToolResult(+ call.callId,+ TASK_CANCEL_TOOL_NAME,+ renderTaskCancelResult(call.taskId, result),+ );}diff --git a/packages/eve/src/execution/tasks/table.ts b/packages/eve/src/execution/tasks/table.tsindex 8521f72ab..ddb950d0c 100644--- a/packages/eve/src/execution/tasks/table.ts+++ b/packages/eve/src/execution/tasks/table.ts@@ -129,12 +129,6 @@ 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);}@@ -192,7 +186,11 @@ export function taskWaitResult(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" };+ return {+ resumable: record.resumable,+ status: isTaskWorking(record) ? "cancelled" : "already_finished",+ tool: record.name,+ };}/** Runs that may still be doing work, including cancelled runs that haven't confirmed yet. */diff --git a/packages/eve/src/harness/tool-loop.test.ts b/packages/eve/src/harness/tool-loop.test.tsindex 7edf6df2d..23326d443 100644--- a/packages/eve/src/harness/tool-loop.test.ts+++ b/packages/eve/src/harness/tool-loop.test.ts@@ -329,6 +329,29 @@ function createDelegationToolMap(): ToolLoopHarnessConfig["tools"] {]);}+/** A `task` workflow tool, so the agent can start tasks and gets the task tools. */+function createTaskToolMap(): ToolLoopHarnessConfig["tools"] {+ const workflowId = "workflow//./agent/tools/research//task";+ return new Map([+ [+ "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,+ },+ ],+ ]);+}+function setDelegatedParent(ctx: ContextContainer): void {ctx.set(ParentSessionKey, {callId: "call-parent",@@ -1570,25 +1593,9 @@ describe("createToolLoopHarness", () => {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,- },- ],+ ...createTaskToolMap(),]);const { emit } = createEventCollector();@@ -4460,6 +4467,48 @@ describe("createToolLoopHarness", () => {expect(events.map((event) => event.type)).not.toContain("session.waiting");});+ const REPLY_BEFORE_RESULT = "If the person should hear from you now";+ const WAIT_INSTEAD_OF_REPLYING = "Only your final reply reaches your caller.";++ it.each([+ {+ absent: WAIT_INSTEAD_OF_REPLYING,+ delegated: false,+ guidance: REPLY_BEFORE_RESULT,+ session: "a root session, where a person reads each reply",+ },+ {+ absent: REPLY_BEFORE_RESULT,+ delegated: true,+ guidance: WAIT_INSTEAD_OF_REPLYING,+ session: "a delegated session, whose caller reads only the final reply",+ },+ ])(+ "tells the model how to wait on tasks in $session",+ async ({ absent, delegated, guidance }) => {+ setupMockAgent({+ finishReason: "stop",+ response: { messages: [{ content: "Done.", role: "assistant" }] },+ text: "Done.",+ toolCalls: [],+ toolResults: [],+ });+ const runStep = createToolLoopHarness(+ createTestConfig(undefined, { tools: createTaskToolMap() }),+ );+ const ctx = new ContextContainer();+ if (delegated) setDelegatedParent(ctx);++ await contextStorage.run(ctx, () =>+ runStep(createTestSession(), { message: "Research this." }),+ );++ const instructions = JSON.stringify(vi.mocked(ToolLoopAgent).mock.calls[0]?.[0].instructions);+ expect(instructions).toContain(guidance);+ expect(instructions).not.toContain(absent);+ },+ );+it("emits the full terminal failure cascade on an explicit Gateway invalid-request error", async () => {const logs = captureLogRecords();setupMockAgentError(diff --git a/packages/eve/src/harness/tool-loop.ts b/packages/eve/src/harness/tool-loop.tsindex 9f5b0151d..aae3880fd 100644--- a/packages/eve/src/harness/tool-loop.ts+++ b/packages/eve/src/harness/tool-loop.ts@@ -1266,7 +1266,9 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {if (ctx !== undefined) {currentMessages.addSystem(buildDynamicInstructionMessages(ctx));}- currentMessages.addSystem(taskSystemMessages(modelCallCoordinationTools));+ currentMessages.addSystem(+ taskSystemMessages(modelCallCoordinationTools, { finalReplyOnly: hidesHeldText }),+ );currentMessages.addAnnouncements({availableSkills: ctx?.get(PendingSkillAnnouncementKey),});diff --git a/packages/eve/src/public/channels/slack/defaults.ts b/packages/eve/src/public/channels/slack/defaults.tsindex b3e27f674..663ea74b9 100644--- a/packages/eve/src/public/channels/slack/defaults.ts+++ b/packages/eve/src/public/channels/slack/defaults.ts@@ -32,7 +32,6 @@ 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");@@ -416,6 +415,7 @@ 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,14 +467,23 @@ export const defaultEvents: SlackChannelInternalEvents = {},async "actions.requested"(event, channel, _ctx) {- 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));+ 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)));},async "message.completed"(event, channel, _ctx) {- if (event.finishReason === "tool-calls") return;+ if (event.finishReason === "tool-calls") {+ channel.state.pendingToolCallMessage = event.message+ ? (firstNonEmptyLine(event.message) ?? null)+ : null;+ return;+ }+ channel.state.pendingToolCallMessage = null;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 ffbd6bff0..9f65b94c0 100644--- a/packages/eve/src/public/channels/slack/slackChannel.test.ts+++ b/packages/eve/src/public/channels/slack/slackChannel.test.ts@@ -765,67 +765,9 @@ 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 5b3965cbc..79c7f80a5 100644--- a/packages/eve/src/public/channels/slack/slackChannel.ts+++ b/packages/eve/src/public/channels/slack/slackChannel.ts@@ -48,12 +48,6 @@ 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,@@ -246,21 +240,13 @@ export interface SlackChannelState {*/triggeringUserId?: string | null;/**- * 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`.+ * 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.*/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@@ -601,10 +587,7 @@ 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`. 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`.+ * context and exposes the ID as `data.sessionId`.*/export interface SlackChannelEvents {readonly "approval.candidate"?: SlackEventHandler<"approval.candidate">;@@ -644,9 +627,7 @@ 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}. `step.completed` has no default- * and can't be overridden: the factory handles it to post a step's text- * before a `task_wait`.+ * {@link constrainAuthorizationRequired}.*/export interface SlackChannelInternalEvents extends Omit<SlackChannelEvents,@@ -654,7 +635,6 @@ 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";@@ -839,6 +819,7 @@ const activityOwnedMessageCompleted: NonNullable<SlackChannelEvents["message.comevent,channel,) => {+ channel.state.pendingToolCallMessage = null;if (event.finishReason !== "tool-calls" && event.message) {await postCompletedSlackReply(channel, event.message);}@@ -848,6 +829,7 @@ const clearSlackTurnState: NonNullable<SlackChannelEvents["turn.started"]> = asy_data,channel,) => {+ channel.state.pendingToolCallMessage = null;channel.state.lastReasoningTypingAtMs = null;channel.state.lastReasoningTypingStatus = null;};@@ -959,26 +941,11 @@ export function slackChannel(config: SlackChannelConfig = {}): SlackChannel {if (triggeringUserId !== undefined) {channel.state.triggeringUserId = triggeringUserId;}- clearPendingStep(channel.state);await turnStartedHandler(data, channel, ctx);},"reasoning.appended": reasoningHandler,- 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);- },+ "actions.requested": actionsHandler,+ "message.completed": messageCompletedHandler,"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.tsdeleted file mode 100644index abb93db88..000000000--- a/packages/eve/src/public/channels/slack/step-text.ts+++ /dev/null@@ -1,75 +0,0 @@-/**- * 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/runtime/prompt/compose.ts b/packages/eve/src/runtime/prompt/compose.tsindex 442d0bf3d..82fb3156c 100644--- a/packages/eve/src/runtime/prompt/compose.ts+++ b/packages/eve/src/runtime/prompt/compose.ts@@ -9,7 +9,7 @@ import type { WorkspaceRuntimeSpec } from "#runtime/workspace/types.js";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.";+ "Tool execution\nTool calls in one response run in parallel, so batch only calls that don't depend on each other.";/*** Input for composing the base authored instructions prompt for onediff --git a/packages/eve/src/runtime/subagents/workflow.test.ts b/packages/eve/src/runtime/subagents/workflow.test.tsindex d963ebd73..f21e44e40 100644--- a/packages/eve/src/runtime/subagents/workflow.test.ts+++ b/packages/eve/src/runtime/subagents/workflow.test.ts@@ -194,7 +194,7 @@ it("forwards a message that reaches the task at any point as the agent's turn en}});-it("fails the task with the reason the agent's turn failed", async () => {+it("fails the task with the reason the agent's turn failed and how to retry", async () => {const started = await startReview();agent.turns[0]?.(turnEnded({@@ -207,7 +207,10 @@ it("fails the task with the reason the agent's turn failed", async () => {);await expect(started.outcome).resolves.toMatchObject({- error: { message: "The agent's turn failed: The model provider rejected the request." },+ error: {+ message:+ "The agent's turn failed: The model provider rejected the request.\nThis task has ended; to retry, call reviewer without taskId.",+ },status: "failed",});});diff --git a/packages/eve/src/runtime/subagents/workflow.ts b/packages/eve/src/runtime/subagents/workflow.tsindex 759039853..febd1fd7e 100644--- a/packages/eve/src/runtime/subagents/workflow.ts+++ b/packages/eve/src/runtime/subagents/workflow.ts@@ -51,8 +51,9 @@ export async function agentToolServeWorkflow(// A cancel already settled the turn's calls, and the task stays available.if (!turn.signal.aborted) {if (event.result.status === "failed") {+ // The throw ends this task, so the model can only retry with a new one.throw new Error(- `The agent's turn failed: ${event.result.error?.message ?? "no reason given"}`,+ `The agent's turn failed: ${event.result.error?.message ?? "no reason given"}\nThis task has ended; to retry, call ${ctx.toolName} without taskId.`,);}// `next` can take a call after the result wins the race, and the replydiff --git a/packages/eve/src/tools/framework/agent-contract.ts b/packages/eve/src/tools/framework/agent-contract.tsindex 6994127ad..9a8df2bff 100644--- a/packages/eve/src/tools/framework/agent-contract.ts+++ b/packages/eve/src/tools/framework/agent-contract.ts@@ -6,8 +6,9 @@ export const AGENT_TOOL_NAME = "agent";export const AGENT_TOOL_DESCRIPTION = ["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.",+ "Each call starts a task, so several agents can work at once: start every independent one before you wait.","A new child has fresh history and state but reuses your tools and sandbox, so give parallel writers non-overlapping scopes.",+ "In message, state the goal, what to return, and whether it may change files.",].join(" ");export const SUBAGENT_TOOL_INPUT_SCHEMA = defineJsonSchema<AgentToolInput>({diff --git a/packages/eve/src/tools/provided/task-wait.ts b/packages/eve/src/tools/provided/task-wait.tsindex facf179cb..e7f8f5527 100644--- a/packages/eve/src/tools/provided/task-wait.ts+++ b/packages/eve/src/tools/provided/task-wait.ts@@ -4,7 +4,7 @@ import type { HarnessToolDefinition } from "#harness/execute-tool.js";import { defineJsonSchema } from "#tools/schema.js";export interface TaskWaitInput {- readonly timeout?: number;+ readonly timeoutSeconds?: number;}/**@@ -17,7 +17,11 @@ export const taskWaitTool: HarnessToolDefinition = {inputSchema: defineJsonSchema<TaskWaitInput>({type: "object",properties: {- timeout: { type: "integer", minimum: 0, description: TASK_WAIT_TIMEOUT_DESCRIPTION },+ timeoutSeconds: {+ type: "integer",+ minimum: 1,+ description: TASK_WAIT_TIMEOUT_DESCRIPTION,+ },},additionalProperties: false,}),diff --git a/packages/eve/test/runtime-prompt-compose.test.ts b/packages/eve/test/runtime-prompt-compose.test.tsindex 5823be9dc..c88ffcfdf 100644--- a/packages/eve/test/runtime-prompt-compose.test.ts+++ b/packages/eve/test/runtime-prompt-compose.test.ts@@ -28,7 +28,7 @@ describe("composeRuntimeBasePrompt", () => {).toEqual([["Tool execution",- "A 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.",+ "Tool calls in one response run in parallel, so batch only calls that don't depend on each other.",].join("\n"),]);});@@ -162,7 +162,7 @@ describe("composeRuntimeBasePrompt", () => {].join("\n"),["Tool execution",- "A 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.",+ "Tool calls in one response run in parallel, so batch only calls that don't depend on each other.",].join("\n"),]);});