Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat(eve): yield progress and messages from background tools (#2997)

Ruib736b406b571
diff --git a/.changeset/tool-task-yields.md b/.changeset/tool-task-yields.md
new file mode 100644
index 000000000..e5d365e85
--- /dev/null
+++ b/.changeset/tool-task-yields.md
@@ -0,0 +1,5 @@
+---
+"eve": minor
+---
+
+Remove `task.delegated()` and replace authored background-tool delegation callbacks with durable generator yields; extensions using the removed API must migrate and rebuild. Background tools now use `task.postMessage()` for explicit parent wakes; ordinary yields are stream-only progress, and returning or throwing settles the task.
diff --git a/docs/tools/overview.mdx b/docs/tools/overview.mdx
index 6dc4ee578..edfd68142 100644
--- a/docs/tools/overview.mdx
+++ b/docs/tools/overview.mdx
@@ -58,18 +58,27 @@ can retry a step and replay overlapping snapshots.
### Background execution
-`defineTool({ execution: "background" })` receives a third `task` argument. Returning a normal
-value completes the durable task with that value. Returning `task.delegated({ executor, receipt })`
-returns a `working` receipt immediately while an external executor continues the task. Background
-tools are a normal execution mode and need no root-agent flag.
-
-Built-in, declared local, and remote subagents use this background task lifecycle automatically.
-After delegating, an
-in-process executor reports
-progress with `task.send({ kind: "update", message })` and the terminal result with
-`task.send({ kind: "complete", data })` (or `fail` / `cancel`). `send` is not restart-safe — an
-in-memory callback dies with the process — so the cross-process executor wire remains
-framework-owned and is not yet a stable authored-tool API.
+`defineTool({ execution: "background" })` receives a third `task` argument and returns
+`{ status: "working", taskId }` to the model. Add `"use workflow"` to let the body outlive the
+initiating step; without it, the step waits for the body to finish. Return completes the durable task; throw fails it. An
+async generator may additionally yield:
+
+```ts
+yield { progress: 0.5 }; // stream-only progress; does not wake the agent
+yield task.postMessage("The export needs review."); // one new parent turn
+```
+
+For background tools, `outputSchema` and `toModelOutput` describe the fixed receipt. The body's
+return value is available through the completed task's output.
+
+`task.delegated()` has been removed. Move external work into a `"use workflow"` body and
+return its result when it finishes. Rebuild extensions using the removed API after migrating.
+
+`postMessage` is the only yield that wakes the parent agent. Keep values needed by the body
+in local variables; workflow replay reconstructs them across durable waits.
+Use [`ask`](/docs/tools/workflows#ask-a-human-ask) when the body needs an answer from the human.
+Background tools are a normal execution mode and need no root-agent flag. Built-in, declared local,
+and remote subagents use this task lifecycle automatically.
After the initiating turn accepts background tasks, eve supplies runtime-authored state for that
cohort and instructs the model to acknowledge that the work started without waiting for results.
diff --git a/docs/tools/workflows.mdx b/docs/tools/workflows.mdx
index 728e43852..10a6a2f4e 100644
--- a/docs/tools/workflows.mdx
+++ b/docs/tools/workflows.mdx
@@ -15,8 +15,10 @@ ends.
Workflow tools use the [Workflow SDK](https://workflow-sdk.dev): `"use workflow"`, `"use step"`,
`createHook`, `createWebhook`, `sleep`, retries, and replay. eve adds `ask` from `eve/workflow` for
-questions answered through the session's channel and `agent` for durable subagent delegation. Each
-`yield` becomes a durable progress report.
+questions answered through the session's channel and `agent` for durable subagent delegation. A
+waiting workflow's `yield` is turn progress. A background workflow also receives `task`: yield an
+ordinary value for stream-only progress or `task.postMessage(...)` to wake the parent agent
+with one message. Values needed after a durable wait stay in local variables in the workflow body.
A workflow tool runs code you wrote and appears to the model under its path-derived tool name, such
as `deploy`.
@@ -77,7 +79,8 @@ or days later, the run resumes, deploys, and returns. The model sees one tool re
`start`, `getRun`, and `resumeHook` from `workflow/api` belong in steps. Your app does not install
the SDK; for types, new projects list `eve/workflow-modules` in the tsconfig `types`.
- In the body, `ctx` has `session`, `callId`, `toolName`, and `abortSignal`. `getSandbox`,
- `getSkill`, `getToken`, and `requireAuth` throw there; read credentials in a step instead.
+ `getSkill`, `getToken`, and `requireAuth` throw there. Read credentials from `process.env` in a
+ step; session-scoped workflow authorization is not yet available.
- The tool's input must be a JSON object. Workflow bodies are for static tools under `agent/tools/`,
not tools returned from `defineDynamic` resolvers.
@@ -88,7 +91,8 @@ or days later, the run resumes, deploys, and returns. The model sees one tool re
| tool result | the run's return value | `{ status: "working", taskId }` |
| turn while the run lives | parked | continues |
| when the run ends | result lands in the tool call | agent is woken with the result or the error |
-| progress (`yield`) | `action.partial` on the turn | wakes the agent with a note |
+| progress (`yield`) | `action.partial` on the turn | stream-only; does not wake the agent |
+| parent message | not applicable | `yield task.postMessage(...)` |
| cancel | cancelling the turn cancels the run | `task_cancel`, or the session ending |
Wait when the model needs the answer to continue. Go background when the wait may outlive the
@@ -151,8 +155,9 @@ keys. `target` is the model-visible subagent name; pass `agentId` to continue an
## Report progress: `yield`
-A workflow body may be an async generator. Each `yield` is a durable progress snapshot; the return
-value is the result, or the last `yield` when the body returns nothing.
+A workflow body may be an async generator. Each ordinary `yield` reports progress; the return
+value is the result. If the body returns nothing, a waiting tool uses its last yield and a
+background tool completes with `null`.
```ts
async *execute({ service }, ctx) {
@@ -166,8 +171,8 @@ async *execute({ service }, ctx) {
For a waiting tool each `yield` streams as an `action.partial` event, last-write-wins by tool call
id, and never enters model history — the same contract as an in-process generator tool. For a
-background tool each `yield` wakes the owning agent with a note. Returning ends the run with the
-result; throwing ends it with the failure.
+background tool ordinary yields are stream-only; `yield task.postMessage(message)` wakes the
+owning agent. Returning ends the run with the result; throwing ends it with the failure.
## Cancel and clean up: `ctx.abortSignal`
diff --git a/e2e/fixtures/agent-background-tools/agent/agent.ts b/e2e/fixtures/agent-background-tools/agent/agent.ts
index a14bdd39b..ef0641fce 100644
--- a/e2e/fixtures/agent-background-tools/agent/agent.ts
+++ b/e2e/fixtures/agent-background-tools/agent/agent.ts
@@ -29,7 +29,7 @@ function respond(request: MockModelRequest): MockModelResponse | string {
return "BACKGROUND-EXPORT-STARTED";
}
- if (message.includes(`update: ${PROGRESS}`)) {
+ if (message.includes(PROGRESS)) {
return "BACKGROUND-EXPORT-UPDATE-RECEIVED";
}
@@ -50,7 +50,7 @@ function respond(request: MockModelRequest): MockModelResponse | string {
function respondScheduled(request: MockModelRequest): MockModelResponse | string {
const taskNotification = [...request.userMessages]
.reverse()
- .find((entry) => /^Background task task_[a-z0-9]+/iu.test(entry));
+ .find((entry) => /^(?:Background task|Export) task_[a-z0-9]+/iu.test(entry));
if (taskNotification?.includes("is completed") && taskNotification.includes(RESULT)) {
return "SCHEDULED-EXPORT-DONE";
}
diff --git a/e2e/fixtures/agent-background-tools/agent/tools/export.ts b/e2e/fixtures/agent-background-tools/agent/tools/export.ts
index 874227288..75d8a1154 100644
--- a/e2e/fixtures/agent-background-tools/agent/tools/export.ts
+++ b/e2e/fixtures/agent-background-tools/agent/tools/export.ts
@@ -1,66 +1,17 @@
-import { defineTool, type TaskExec } from "eve/tools";
+import { defineTool } from "eve/tools";
+import { sleep } from "workflow";
import { z } from "zod";
-const PROGRESS = "EXPORT-PROGRESS";
-const RESULT = "EXPORT-COMPLETE";
-
-/**
- * Authored background tool with an in-process executor.
- *
- * Delegates immediately, then reports one progress update and a terminal
- * result through the task capability so the parent sees both.
- */
export default defineTool({
description: "Start a durable background export.",
execution: "background",
- inputSchema: z.strictObject({
- query: z.string(),
- }),
- outputSchema: z.strictObject({
- status: z.literal("working"),
- taskId: z.string(),
- }),
- async execute(input, _ctx, task) {
- const executor = {
- data: { query: input.query },
- kind: "export",
- };
-
- // Start a deterministic in-process executor before the tool returns so
- // completion is independent of the parent turn.
- void runExportExecutor({
- query: input.query,
- send: task.send,
- });
-
- return task.delegated({
- executor,
- receipt: {},
- });
+ inputSchema: z.strictObject({ query: z.string() }),
+ async *execute({ query }, _ctx, task) {
+ "use workflow";
+
+ yield { progress: 0.5 };
+ yield task.postMessage(`Export ${task.taskId}: EXPORT-PROGRESS`);
+ await sleep("250ms");
+ return { query, result: "EXPORT-COMPLETE" };
},
});
-
-async function runExportExecutor(input: {
- readonly query: string;
- readonly send: TaskExec["send"];
-}): Promise<void> {
- // Give the parent turn a moment to acknowledge the delegated task so
- // the update is not buffered past completion.
- await delay(250);
-
- await input.send({
- kind: "update",
- message: PROGRESS,
- });
-
- await delay(250);
-
- await input.send({
- data: { query: input.query, result: RESULT },
- kind: "complete",
- });
-}
-
-function delay(ms: number): Promise<void> {
- return new Promise((resolve) => setTimeout(resolve, ms));
-}
diff --git a/e2e/fixtures/agent-background-tools/evals/background-export.update-and-complete.eval.ts b/e2e/fixtures/agent-background-tools/evals/background-export.update-and-complete.eval.ts
index a2809bb72..52ae8d6c4 100644
--- a/e2e/fixtures/agent-background-tools/evals/background-export.update-and-complete.eval.ts
+++ b/e2e/fixtures/agent-background-tools/evals/background-export.update-and-complete.eval.ts
@@ -6,7 +6,7 @@ const RESULT = "EXPORT-COMPLETE";
export default defineEval({
description:
- "An authored background defineTool posts one task update then completes; the parent sees both.",
+ "An authored background defineTool yields state and progress, explicitly posts a message, then completes; the parent sees both.",
async test(t) {
const started = await t.send("BACKGROUND-EXPORT-START");
started.expectOk();
@@ -32,11 +32,9 @@ export default defineEval({
events.some(
(event) =>
event.type === "message.received" &&
- messageText(event.data.message).includes(
- `Background task ${taskId} (export) update: ${PROGRESS}`,
- ),
+ messageText(event.data.message).includes(`Export ${taskId}: ${PROGRESS}`),
),
- "parent receives the executor update with task identity",
+ "parent receives the authored message with task identity",
),
);
diff --git a/e2e/fixtures/agent-background-tools/evals/scheduled-export.quiet-launch.eval.ts b/e2e/fixtures/agent-background-tools/evals/scheduled-export.quiet-launch.eval.ts
index ff5d5cb99..5979802df 100644
--- a/e2e/fixtures/agent-background-tools/evals/scheduled-export.quiet-launch.eval.ts
+++ b/e2e/fixtures/agent-background-tools/evals/scheduled-export.quiet-launch.eval.ts
@@ -7,7 +7,7 @@ const RESULT = "EXPORT-COMPLETE";
* A schedule-launched turn that dispatches a background task sends no launch
* acknowledgement even when it runs with a user principal: durable schedule
* provenance keeps conditional delivery, so the
- * launching turn and the pending update wake both complete with a null
+ * launching turn and the pending message wake both complete with a null
* message, and only the settled wake delivers a report.
*/
export default defineEval({
@@ -44,7 +44,7 @@ export default defineEval({
data: (data) => data.finishReason !== "tool-calls" && data.message !== null,
});
- // The executor's progress update wakes the parent while the cohort is
+ // The executor's explicit message wakes the parent while the cohort is
// still pending; that wake stays silent too.
const updateLive = t.target.watchTurn(sessionId, {
startIndex: requireStreamIndex(session, "update wait"),
@@ -60,7 +60,7 @@ export default defineEval({
});
await t.require(
updateTurn.message,
- satisfies((message) => message === undefined, "the pending update wake is silent"),
+ satisfies((message) => message === undefined, "the pending message wake is silent"),
);
// Only the settled wake produces a user-facing report.
diff --git a/e2e/fixtures/agent-background-tools/tsconfig.json b/e2e/fixtures/agent-background-tools/tsconfig.json
index 7e570d043..1b9a6162e 100644
--- a/e2e/fixtures/agent-background-tools/tsconfig.json
+++ b/e2e/fixtures/agent-background-tools/tsconfig.json
@@ -11,7 +11,7 @@
"forceConsistentCasingInFileNames": true,
"declaration": false,
"noEmit": true,
- "types": ["node"]
+ "types": ["node", "eve/workflow-modules"]
},
"include": ["agent/**/*.ts", "evals/**/*.ts"]
}
diff --git a/e2e/fixtures/agent-workflow-tools/agent/agent.ts b/e2e/fixtures/agent-workflow-tools/agent/agent.ts
index d84b2dbb6..28d18f582 100644
--- a/e2e/fixtures/agent-workflow-tools/agent/agent.ts
+++ b/e2e/fixtures/agent-workflow-tools/agent/agent.ts
@@ -53,7 +53,7 @@ function respond(request: MockModelRequest): MockModelResponse | string {
}`;
}
- if (message.includes("update: WORKFLOW-REPORT-PROGRESS")) {
+ if (message.includes("WORKFLOW-REPORT-PROGRESS")) {
return "WORKFLOW-REPORT-UPDATE-RECEIVED";
}
if (message.includes("is completed") && message.includes("WORKFLOW-REPORT-COMPLETE")) {
diff --git a/e2e/fixtures/agent-workflow-tools/agent/tools/report_deploy.ts b/e2e/fixtures/agent-workflow-tools/agent/tools/report_deploy.ts
index 325c7ec63..bb567fb9a 100644
--- a/e2e/fixtures/agent-workflow-tools/agent/tools/report_deploy.ts
+++ b/e2e/fixtures/agent-workflow-tools/agent/tools/report_deploy.ts
@@ -4,18 +4,19 @@ import { z } from "zod";
import { describePlan, hashPlan } from "../lib/plan.ts";
/**
- * Background workflow tool: the model gets a receipt, each `yield` is a
- * durable progress note, and the agent is woken with the return value.
+ * Background workflow tool: the model gets a receipt, `postMessage` delivers a
+ * progress note, and the agent is woken with the return value.
*/
export default defineTool({
description: "Plan a deploy in the background and report when it is ready.",
execution: "background",
inputSchema: z.strictObject({ service: z.string() }),
- async *execute({ service }) {
+ async *execute({ service }, _ctx, task) {
"use workflow";
const plan = describePlan(service);
- yield `WORKFLOW-REPORT-PROGRESS ${plan}`;
+ yield { plan };
+ yield task.postMessage(`Deploy ${task.taskId}: WORKFLOW-REPORT-PROGRESS ${plan}`);
const digest = await hashPlan(plan);
return { digest, plan, result: "WORKFLOW-REPORT-COMPLETE" };
},
diff --git a/e2e/fixtures/agent-workflow-tools/evals/report-deploy.background.eval.ts b/e2e/fixtures/agent-workflow-tools/evals/report-deploy.background.eval.ts
index 08f3178ef..6c634acab 100644
--- a/e2e/fixtures/agent-workflow-tools/evals/report-deploy.background.eval.ts
+++ b/e2e/fixtures/agent-workflow-tools/evals/report-deploy.background.eval.ts
@@ -30,7 +30,7 @@ export default defineEval({
(event) =>
event.type === "message.received" &&
messageText(event.data.message).includes(
- `Background task ${taskId} (report_deploy) update: WORKFLOW-REPORT-PROGRESS deploy api`,
+ `Deploy ${taskId}: WORKFLOW-REPORT-PROGRESS deploy api`,
),
),
"parent receives the run's progress note with task identity",
diff --git a/packages/eve/extension-contracts/compatibility/dynamicTool/v28.ts b/packages/eve/extension-contracts/compatibility/dynamicTool/v28.ts
new file mode 100644
index 000000000..84cdfafc3
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/dynamicTool/v28.ts
@@ -0,0 +1,18 @@
+import { z } from "zod";
+
+import { defineDynamic, defineTool } from "#public/tools/index.js";
+
+export default defineDynamic({
+ events: {
+ "session.started": () =>
+ defineTool({
+ description: "Delegate a background report.",
+ execution: "background",
+ inputSchema: z.object({ reportId: z.string() }),
+ async *execute({ reportId }) {
+ yield { reportId };
+ return { reportId };
+ },
+ }),
+ },
+});
diff --git a/packages/eve/extension-contracts/compatibility/tool/v28.ts b/packages/eve/extension-contracts/compatibility/tool/v28.ts
new file mode 100644
index 000000000..6e37f463d
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/tool/v28.ts
@@ -0,0 +1,13 @@
+import { z } from "zod";
+
+import { defineTool } from "#public/tools/index.js";
+
+export default defineTool({
+ description: "Start a durable report task.",
+ execution: "background",
+ inputSchema: z.object({ reportId: z.string() }),
+ async *execute(input) {
+ yield { reportId: input.reportId };
+ return { reportId: input.reportId };
+ },
+});
diff --git a/packages/eve/extension-contracts/reports/dynamicTool/v28.json b/packages/eve/extension-contracts/reports/dynamicTool/v28.json
new file mode 100644
index 000000000..fc911f89b
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/dynamicTool/v28.json
@@ -0,0 +1,13 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "dynamicTool",
+ "epoch": 28,
+ "sha256": "8aac382af87c38d0ef3a09b6d323ab5437fab7e780702dcd468fbafc96ea2fae",
+ "exports": [
+ "DynamicToolEntry",
+ "DynamicToolEvents",
+ "DynamicToolResult",
+ "DynamicToolSet",
+ "defineDynamic"
+ ]
+}
diff --git a/packages/eve/extension-contracts/reports/tool/v28.json b/packages/eve/extension-contracts/reports/tool/v28.json
new file mode 100644
index 000000000..6f278a18a
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/tool/v28.json
@@ -0,0 +1,19 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "tool",
+ "epoch": 28,
+ "sha256": "0b7e7e4e61cac5fd6e2a41b3b7ec639923d04efa7eb7f250f1467236b2878c6b",
+ "exports": [
+ "defaultWebSearch",
+ "defineTool",
+ "disableTool",
+ "experimental_workflow",
+ "isDisabledToolSentinel",
+ "isExperimentalWorkflowToolDefinition",
+ "isWebSearchToolDefinition",
+ "toolOutput",
+ "toolOutputPart",
+ "toolResultFrom",
+ "webSearch"
+ ]
+}
diff --git a/packages/eve/src/compiler/extension-compatibility.test.ts b/packages/eve/src/compiler/extension-compatibility.test.ts
index ccec98d5f..46950f5ab 100644
--- a/packages/eve/src/compiler/extension-compatibility.test.ts
+++ b/packages/eve/src/compiler/extension-compatibility.test.ts
@@ -104,6 +104,31 @@ describe("extension compatibility manifest", () => {
]);
});
+ it.each([
+ { capability: "tool", firstDelegatedEpoch: 14 },
+ { capability: "dynamicTool", firstDelegatedEpoch: 23 },
+ ])(
+ "rejects $capability extensions requiring task.delegated",
+ ({ capability, firstDelegatedEpoch }) => {
+ for (let requiredVersion = firstDelegatedEpoch; requiredVersion <= 27; requiredVersion++) {
+ expect(
+ findUnsupportedExtensionCapabilities({
+ kind: EXTENSION_COMPATIBILITY_MANIFEST_KIND,
+ formatVersion: EXTENSION_COMPATIBILITY_MANIFEST_FORMAT_VERSION,
+ builtWithEve: "0.40.0",
+ requires: { [capability]: requiredVersion },
+ }),
+ ).toEqual([
+ {
+ capability,
+ requiredVersion,
+ supportedVersions: EXTENSION_CAPABILITY_SUPPORT[capability as ExtensionCapability],
+ },
+ ]);
+ }
+ },
+ );
+
it("publishes valid support history for every capability version it stamps", () => {
for (const [capability, version] of Object.entries(EXTENSION_CAPABILITY_VERSIONS)) {
const supportedVersions = EXTENSION_CAPABILITY_SUPPORT[capability as ExtensionCapability];
diff --git a/packages/eve/src/compiler/extension-compatibility.ts b/packages/eve/src/compiler/extension-compatibility.ts
index 50593c4d0..72e4e8fed 100644
--- a/packages/eve/src/compiler/extension-compatibility.ts
+++ b/packages/eve/src/compiler/extension-compatibility.ts
@@ -22,19 +22,35 @@ interface ExtensionCapabilityContract {
const EXTENSION_CAPABILITY_CONTRACTS = {
extension: { current: 1, supported: [1], dropped: {} },
tool: {
- current: 27,
- supported: [
- 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27,
- ],
- dropped: { 15: "TaskExec replaces stageEffect with send" },
+ current: 28,
+ supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 28],
+ dropped: {
+ 14: "TaskExec.delegated was removed; migrate to workflow-backed background tools",
+ 15: "TaskExec replaces stageEffect with send",
+ 16: "TaskExec.delegated was removed; migrate to workflow-backed background tools",
+ 17: "TaskExec.delegated was removed; migrate to workflow-backed background tools",
+ 18: "TaskExec.delegated was removed; migrate to workflow-backed background tools",
+ 19: "TaskExec.delegated was removed; migrate to workflow-backed background tools",
+ 20: "TaskExec.delegated was removed; migrate to workflow-backed background tools",
+ 21: "TaskExec.delegated was removed; migrate to workflow-backed background tools",
+ 22: "TaskExec.delegated was removed; migrate to workflow-backed background tools",
+ 23: "TaskExec.delegated was removed; migrate to workflow-backed background tools",
+ 24: "TaskExec.delegated was removed; migrate to workflow-backed background tools",
+ 25: "TaskExec.delegated was removed; migrate to workflow-backed background tools",
+ 26: "Background tools now use task yield descriptors",
+ 27: "TaskExec.delegated was removed; migrate to workflow-backed background tools",
+ },
},
dynamicTool: {
- current: 27,
- supported: [
- 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 22, 23, 24, 25, 26, 27,
- ],
+ current: 28,
+ supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 22, 28],
dropped: {
21: "Message and reasoning append events now expose deltas instead of cumulative snapshots.",
+ 23: "TaskExec.delegated was removed; migrate to workflow-backed background tools",
+ 24: "TaskExec.delegated was removed; migrate to workflow-backed background tools",
+ 25: "TaskExec.delegated was removed; migrate to workflow-backed background tools",
+ 26: "Background tools now use task yield descriptors",
+ 27: "TaskExec.delegated was removed; migrate to workflow-backed background tools",
},
},
channel: {
diff --git a/packages/eve/src/compiler/manifest.ts b/packages/eve/src/compiler/manifest.ts
index f989e26f2..00bc9beea 100644
--- a/packages/eve/src/compiler/manifest.ts
+++ b/packages/eve/src/compiler/manifest.ts
@@ -854,6 +854,13 @@ const compiledToolBehaviorSchema: z.ZodType<CompiledToolBehavior> = z
])
.optional(),
presentation: z.literal("load-skill").optional(),
+ shape: z
+ .object({
+ lifetime: z.enum(["step", "task"]),
+ suspend: z.enum(["none", "workflow"]),
+ })
+ .strict()
+ .optional(),
})
.strict();
diff --git a/packages/eve/src/compiler/normalize-manifest.test.ts b/packages/eve/src/compiler/normalize-manifest.test.ts
index 1bbca6f0c..224c1882b 100644
--- a/packages/eve/src/compiler/normalize-manifest.test.ts
+++ b/packages/eve/src/compiler/normalize-manifest.test.ts
@@ -140,6 +140,7 @@ describe("compileAgentManifest source graph", () => {
kind: "workflow-tool",
workflowId: "workflow//example/tool//execute",
},
+ shape: { lifetime: "step", suspend: "workflow" },
});
});
@@ -207,7 +208,10 @@ describe("compileAgentManifest source graph", () => {
});
const selected = compiled.tools.find((tool) => tool.name === "agent");
expect(selected).toMatchObject({ hasExecute: true, logicalPath: "tools/agent.ts" });
- expect(selected?.behavior).toBeUndefined();
+ expect(selected?.behavior).toEqual({
+ availability: [],
+ shape: { lifetime: "step", suspend: "none" },
+ });
const moduleMap = await createProgrammaticCompiledModuleMap(compiled, [
frameworkAgentSourceRegistry,
@@ -215,7 +219,10 @@ describe("compileAgentManifest source graph", () => {
]);
const graph = await resolveRuntimeAgentGraph({ manifest: compiled, moduleMap });
const resolved = graph.root.toolRegistry.toolsByName.get("agent")?.definition;
- expect(resolved?.behavior).toBeUndefined();
+ expect(resolved?.behavior).toEqual({
+ availability: [],
+ shape: { lifetime: "step", suspend: "none" },
+ });
expect(await resolved?.execute?.({}, {} as never)).toEqual({ ordinary: true });
expect(execute).toHaveBeenCalledOnce();
});
diff --git a/packages/eve/src/compiler/normalize-tool.ts b/packages/eve/src/compiler/normalize-tool.ts
index 4f6756e71..25ebc3b7a 100644
--- a/packages/eve/src/compiler/normalize-tool.ts
+++ b/packages/eve/src/compiler/normalize-tool.ts
@@ -107,13 +107,19 @@ export async function compileToolEntry(
}
const workflowId = readWorkflowFunctionId(entry.definition.execute);
+ const shape = {
+ lifetime: entry.definition.execution === "background" ? ("task" as const) : ("step" as const),
+ suspend: workflowId === undefined ? ("none" as const) : ("workflow" as const),
+ };
return {
kind: "tool",
definition: {
behavior:
workflowId === undefined
- ? entry.definition.behavior
- : { availability: [], handling: { kind: "workflow-tool", workflowId } },
+ ? entry.definition.behavior === undefined
+ ? { availability: [], shape }
+ : { ...entry.definition.behavior, shape }
+ : { availability: [], handling: { kind: "workflow-tool", workflowId }, shape },
description: entry.definition.description,
execution: entry.definition.execution,
exportName: source.exportName,
diff --git a/packages/eve/src/context/dynamic-tool-lifecycle.test.ts b/packages/eve/src/context/dynamic-tool-lifecycle.test.ts
index 51904e8ff..6ba1d02f8 100644
--- a/packages/eve/src/context/dynamic-tool-lifecycle.test.ts
+++ b/packages/eve/src/context/dynamic-tool-lifecycle.test.ts
@@ -1059,19 +1059,24 @@ describe("dispatchDynamicToolEvent", () => {
it("persists background execution and forwards TaskExec when replaying", async () => {
const ctx = createCtx();
- const stepFn = vi.fn((_closure: unknown, _input: unknown, _toolCtx: unknown, task: TaskExec) =>
- task.delegated({
- executor: { data: {}, kind: "test" },
- receipt: {},
- }),
- );
+ const stepFn = vi.fn(async function* (
+ _closure: unknown,
+ _input: unknown,
+ _toolCtx: unknown,
+ task: TaskExec,
+ ) {
+ yield task.postMessage("replayed");
+ return { done: true };
+ });
const resolver = createResolver("background", ["session.started"], () => {
const entry = defineTool({
description: "delegate background work",
execution: "background",
inputSchema: z.strictObject({}),
- execute: (_input, _toolCtx, task) =>
- task.delegated({ executor: { data: {}, kind: "test" }, receipt: {} }),
+ async *execute(_input, _toolCtx, task) {
+ yield task.postMessage("replayed");
+ return { done: true };
+ },
});
stampDurableDynamicToolCallbacks(entry, {
execute: { callback: stepFn as never, closure: {} },
@@ -1091,23 +1096,18 @@ describe("dispatchDynamicToolEvent", () => {
const [tool] = buildDynamicTools(restored);
expect(tool?.execution).toBe("background");
- const binding = { taskId: "task-1", token: "token-1" };
const task: TaskExec = {
- batch: [],
- binding,
- delegated: ({ executor, receipt }) => ({
- executor,
- kind: "eve:task-delegated",
- receipt: { ...receipt, status: "working", taskId: binding.taskId },
- }),
+ binding: { taskId: "task-1", token: "token-1" },
+ postMessage: (message) => ({ kind: "eve:task-message", message }),
send: vi.fn(),
session: {} as TaskExec["session"],
task: {} as TaskExec["task"],
+ taskId: "task-1",
};
- await expect(tool!.execute!({}, executeOptions, task)).resolves.toMatchObject({
- kind: "eve:task-delegated",
- receipt: { status: "working", taskId: "task-1" },
- });
+ const output = tool!.execute!({}, executeOptions, task) as AsyncIterable<unknown>;
+ const updates = [];
+ for await (const update of output) updates.push(update);
+ expect(updates).toEqual([{ kind: "eve:task-message", message: "replayed" }]);
expect(stepFn).toHaveBeenCalledWith({}, {}, expect.anything(), task);
});
diff --git a/packages/eve/src/execution/tasks/child/steps.ts b/packages/eve/src/execution/tasks/child/steps.ts
index ede079728..6d506b709 100644
--- a/packages/eve/src/execution/tasks/child/steps.ts
+++ b/packages/eve/src/execution/tasks/child/steps.ts
@@ -1,9 +1,5 @@
import { getWritable } from "#compiled/@workflow/core/index.js";
-import type {
- ActivityObserverConfig,
- SessionAuthContext,
- SessionCommand,
-} from "#channel/types.js";
+import type { ActivityObserverConfig, SessionAuthContext, SessionCommand } from "#channel/types.js";
import type {
WorkflowToolAuthorizationRequest,
WorkflowToolRunRequestMessage,
@@ -19,13 +15,16 @@ import type { ActivityEventV1 } from "#protocol/activity.js";
import type { JsonValue } from "#shared/json.js";
import {
isTerminalTaskStatus,
+ TASK_PROGRESS_STREAM_NAMESPACE,
TASK_VIEW_STREAM_NAMESPACE,
taskAuthorizationRequestId,
type TaskAgentRequestDelivery,
type TaskAuthorizationEventDelivery,
type TaskInboundAnswerInput,
+ type TaskInboundMessage,
type TaskInboundUpdate,
type TaskInputRequestDelivery,
+ type TaskProgress,
type TaskView,
} from "#tasks/types.js";
@@ -88,6 +87,21 @@ export function projectTaskActivity(input: {
];
}
+/** Appends task progress without starting a parent turn. */
+export async function appendTaskProgressStep(input: {
+ readonly progress: TaskProgress;
+}): Promise<void> {
+ "use step";
+
+ const writable = getWritable<TaskProgress>({ namespace: TASK_PROGRESS_STREAM_NAMESPACE });
+ const writer = writable.getWriter();
+ try {
+ await writer.write(input.progress);
+ } finally {
+ writer.releaseLock();
+ }
+}
+
/**
* Wakes the parent session with a framework task notification.
*
@@ -148,6 +162,27 @@ export async function wakeTaskUpdateParentStep(input: {
}
}
+/** Delivers one task-authored message to the parent as a new turn. */
+export async function wakeTaskMessageParentStep(input: {
+ readonly message: TaskInboundMessage;
+ readonly taskId: string;
+ readonly token: string;
+}): Promise<void> {
+ "use step";
+
+ const command: SessionCommand = {
+ kind: "send",
+ payload: { message: input.message.message },
+ taskDeliveryId: `${input.taskId}:message:${input.message.messageEpoch}:${input.message.messageIndex}:${input.message.callId}`,
+ };
+ try {
+ await resumeSessionInbox(input.token, command);
+ } catch (error) {
+ if (isTaskWorkflowTargetGone(error)) return;
+ throw error;
+ }
+}
+
/** Forwards one agent spawn or settlement request to the parent session. */
export async function wakeTaskAgentRequestParentStep(input: {
readonly request: WorkflowToolRunRequestMessage;
diff --git a/packages/eve/src/execution/tasks/child/workflow.test.ts b/packages/eve/src/execution/tasks/child/workflow.test.ts
index 7a7574192..32951aca6 100644
--- a/packages/eve/src/execution/tasks/child/workflow.test.ts
+++ b/packages/eve/src/execution/tasks/child/workflow.test.ts
@@ -5,6 +5,7 @@ import { taskRunWorkflow } from "#execution/tasks/child/workflow.js";
import type { TaskView } from "#tasks/types.js";
const mocks = vi.hoisted(() => ({
+ appendTaskProgressStep: vi.fn(),
appendTaskViewStep: vi.fn(),
cancelWorkflowToolRunStep: vi.fn(),
claimHookOwnership: vi.fn(),
@@ -16,6 +17,7 @@ const mocks = vi.hoisted(() => ({
raceChannelReads: vi.fn(),
resumeHookStep: vi.fn(),
wakeTaskAgentRequestParentStep: vi.fn(),
+ wakeTaskMessageParentStep: vi.fn(),
wakeTaskParentStep: vi.fn(),
wakeTaskUpdateParentStep: vi.fn(),
wakeWorkflowTaskInputRequestParentStep: vi.fn(),
@@ -42,9 +44,11 @@ vi.mock("#execution/hook-ownership.js", () => ({
isHookConflictError: () => false,
}));
vi.mock("#execution/tasks/child/steps.js", () => ({
+ appendTaskProgressStep: mocks.appendTaskProgressStep,
appendTaskViewStep: mocks.appendTaskViewStep,
deliverTaskInputResponsesStep: mocks.deliverTaskInputResponsesStep,
wakeTaskAgentRequestParentStep: mocks.wakeTaskAgentRequestParentStep,
+ wakeTaskMessageParentStep: mocks.wakeTaskMessageParentStep,
wakeTaskAuthorizationParentStep: vi.fn(),
wakeTaskParentStep: mocks.wakeTaskParentStep,
wakeTaskUpdateParentStep: mocks.wakeTaskUpdateParentStep,
@@ -107,7 +111,43 @@ describe("taskRunWorkflow", () => {
vi.resetAllMocks();
mocks.createHook.mockReturnValue({ token: "task-token" });
mocks.openWorkflowToolRunOwnerChannels.mockReturnValue({ dispose: vi.fn(), readers: [] });
- mocks.executeWorkflowBody.mockResolvedValue({ output: "done", status: "completed" });
+ mocks.executeWorkflowBody.mockResolvedValue({
+ outcome: { output: "done", status: "completed" },
+ reportCount: 0,
+ });
+ });
+
+ it("delivers an authored message queued before completion and dispatch acknowledgement", async () => {
+ const message = {
+ callId: "call-1",
+ kind: "task-message" as const,
+ message: "Review the export",
+ messageEpoch: "task-1",
+ messageIndex: 0,
+ };
+ for (const value of [
+ message,
+ { kind: "task-command", command: { kind: "complete", data: "done" } },
+ { kind: "task-command", command: { kind: "ready" } },
+ ]) {
+ mocks.raceChannelReads.mockResolvedValueOnce({
+ channel: "commands",
+ next: { done: false, value },
+ });
+ }
+ await taskRunWorkflow({
+ initialView,
+ parentContinuationToken: "parent-token",
+ taskInboxToken: "task-token",
+ });
+ expect(mocks.wakeTaskMessageParentStep).toHaveBeenCalledWith({
+ message,
+ taskId: "task-1",
+ token: "parent-token",
+ });
+ expect(mocks.wakeTaskMessageParentStep.mock.invocationCallOrder[0]).toBeLessThan(
+ mocks.wakeTaskParentStep.mock.invocationCallOrder[0]!,
+ );
});
it("buffers agent requests until task dispatch is acknowledged", async () => {
@@ -219,46 +259,63 @@ describe("taskRunWorkflow", () => {
expect(mocks.executeWorkflowBody).toHaveBeenCalledOnce();
});
- it("flushes an update queued before readiness ahead of terminal completion", async () => {
- const update = {
- callId: "call-1",
- kind: "task-update" as const,
- message: "progress",
- updateEpoch: "task-1",
- updateIndex: 0,
- };
- mocks.raceChannelReads
- .mockResolvedValueOnce({ channel: "commands", next: { done: false, value: update } })
- .mockResolvedValueOnce({
- channel: "commands",
- next: {
- done: false,
- value: {
- command: { data: "done", kind: "complete" },
- kind: "task-command",
+ it.each(["tool", "subagent"])(
+ "routes %s progress without changing subagent delivery",
+ async (kind) => {
+ const update = {
+ callId: "call-1",
+ kind: "task-update" as const,
+ message: "progress",
+ updateEpoch: "task-1",
+ updateIndex: 0,
+ };
+ mocks.raceChannelReads
+ .mockResolvedValueOnce({ channel: "commands", next: { done: false, value: update } })
+ .mockResolvedValueOnce({
+ channel: "commands",
+ next: {
+ done: false,
+ value: {
+ command: { data: "done", kind: "complete" },
+ kind: "task-command",
+ },
},
- },
- })
- .mockResolvedValueOnce({
- channel: "commands",
- next: { done: false, value: { command: { kind: "ready" }, kind: "task-command" } },
- });
+ })
+ .mockResolvedValueOnce({
+ channel: "commands",
+ next: { done: false, value: { command: { kind: "ready" }, kind: "task-command" } },
+ });
- await taskRunWorkflow({
- initialView,
- parentContinuationToken: "parent-token",
- taskInboxToken: "task-token",
- });
+ await taskRunWorkflow({
+ initialView: { ...initialView, metadata: { ...initialView.metadata, kind } },
+ parentContinuationToken: "parent-token",
+ taskInboxToken: "task-token",
+ });
- expect(mocks.wakeTaskUpdateParentStep).toHaveBeenCalledWith({
- token: "parent-token",
- update,
- view: expect.objectContaining({ status: "completed" }),
- });
- expect(mocks.wakeTaskUpdateParentStep.mock.invocationCallOrder[0]).toBeLessThan(
- mocks.wakeTaskParentStep.mock.invocationCallOrder[0]!,
- );
- });
+ if (kind === "subagent") {
+ expect(mocks.appendTaskProgressStep).not.toHaveBeenCalled();
+ expect(mocks.wakeTaskUpdateParentStep).toHaveBeenCalledWith({
+ token: "parent-token",
+ update,
+ view: expect.objectContaining({ status: "completed" }),
+ });
+ expect(mocks.wakeTaskUpdateParentStep.mock.invocationCallOrder[0]).toBeLessThan(
+ mocks.wakeTaskParentStep.mock.invocationCallOrder[0]!,
+ );
+ return;
+ }
+ expect(mocks.appendTaskProgressStep).toHaveBeenCalledWith({
+ progress: {
+ callId: "call-1",
+ kind: "task-progress",
+ taskId: "task-1",
+ update: "progress",
+ updateIndex: 0,
+ },
+ });
+ expect(mocks.wakeTaskUpdateParentStep).not.toHaveBeenCalled();
+ },
+ );
it("publishes cancellation after the workflow body observes its abort", async () => {
mocks.raceChannelReads
@@ -272,14 +329,18 @@ describe("taskRunWorkflow", () => {
})
.mockResolvedValueOnce({
channel: "body",
- next: { done: false, value: { reason: "cancelled", status: "cancelled" } },
+ next: {
+ done: false,
+ value: { outcome: { reason: "cancelled", status: "cancelled" }, reportCount: 0 },
+ },
});
mocks.executeWorkflowBody.mockImplementation(
async (_input, signal: AbortSignal) =>
await new Promise((resolve) => {
signal.addEventListener(
"abort",
- () => resolve({ reason: "cancelled", status: "cancelled" }),
+ () =>
+ resolve({ outcome: { reason: "cancelled", status: "cancelled" }, reportCount: 0 }),
{ once: true },
);
}),
@@ -308,4 +369,54 @@ describe("taskRunWorkflow", () => {
view: expect.objectContaining({ status: "cancelled" }),
});
});
+
+ it("consumes every persisted report before accepting a body's completion", async () => {
+ mocks.raceChannelReads
+ .mockResolvedValueOnce({
+ channel: "commands",
+ next: { done: false, value: { command: { kind: "ready" }, kind: "task-command" } },
+ })
+ .mockResolvedValueOnce({
+ channel: "body",
+ next: {
+ done: false,
+ value: { outcome: { output: "done", status: "completed" }, reportCount: 1 },
+ },
+ })
+ .mockResolvedValueOnce({
+ channel: "report",
+ next: {
+ done: false,
+ value: {
+ from: bufferedAgentRequest.from,
+ update: { kind: "eve:task-message", message: "Review the export" },
+ },
+ },
+ });
+ await taskRunWorkflow({
+ initialView,
+ parentContinuationToken: "parent-token",
+ taskInboxToken: "task-token",
+ workflow: {
+ callId: "call-1",
+ input: {},
+ session: {
+ auth: { current: null, initiator: null },
+ id: "session-1",
+ turn: { id: "turn-1", sequence: 0 },
+ },
+ stepIndex: 0,
+ toolName: "worker",
+ workflowId: "workflow//eve//worker",
+ },
+ });
+ expect(mocks.wakeTaskMessageParentStep).toHaveBeenCalledWith({
+ message: expect.objectContaining({ message: "Review the export" }),
+ taskId: "task-1",
+ token: "parent-token",
+ });
+ expect(mocks.wakeTaskMessageParentStep.mock.invocationCallOrder[0]).toBeLessThan(
+ mocks.wakeTaskParentStep.mock.invocationCallOrder[0]!,
+ );
+ });
});
diff --git a/packages/eve/src/execution/tasks/child/workflow.ts b/packages/eve/src/execution/tasks/child/workflow.ts
index 57c70f987..fb151d361 100644
--- a/packages/eve/src/execution/tasks/child/workflow.ts
+++ b/packages/eve/src/execution/tasks/child/workflow.ts
@@ -3,10 +3,12 @@ import { createHook } from "#compiled/@workflow/core/index.js";
import type { ActivityObserverConfig } from "#channel/types.js";
import { claimHookOwnership, disposeHook, isHookConflictError } from "#execution/hook-ownership.js";
import {
+ appendTaskProgressStep,
appendTaskViewStep,
deliverTaskInputResponsesStep,
wakeTaskAgentRequestParentStep,
wakeTaskAuthorizationParentStep,
+ wakeTaskMessageParentStep,
wakeTaskParentStep,
wakeTaskUpdateParentStep,
wakeWorkflowTaskInputRequestParentStep,
@@ -15,6 +17,7 @@ import {
createWorkflowBodyRef,
executeWorkflowBody,
type WorkflowBodyDefinition,
+ type WorkflowBodyResult,
} from "#execution/tools/workflow/body.js";
import {
deriveWorkflowToolRunOwner,
@@ -24,7 +27,7 @@ import { createChannelReader, raceChannelReads } from "#execution/tools/workflow
import { openWorkflowToolRunOwnerChannels } from "#execution/tools/workflow/owner.js";
import {
workflowToolRunOutcomeToTaskCommand,
- workflowToolRunReportToTaskUpdate,
+ workflowToolRunReportToTaskPayload,
workflowToolRunRequestToTaskInputRequest,
} from "#execution/tools/workflow/owner-inbox.js";
import type { AnswerHookRoute } from "#harness/proxy-input-requests.js";
@@ -35,6 +38,7 @@ import {
readTaskInputRequestId,
type TaskCommand,
type TaskInboundAnswerInput,
+ type TaskInboundMessage,
type TaskInputRequest,
type TaskInboundUpdate,
type TaskRunInboundPayload,
@@ -65,6 +69,7 @@ export type WorkflowToolRunTaskInputRequest = WorkflowToolRunTaskInputRequestBas
);
interface PendingWorkflowToolTraffic {
+ readonly messages: TaskInboundMessage[];
readonly ownerRequests: WorkflowToolRunRequestMessage[];
}
@@ -85,16 +90,17 @@ export async function taskRunWorkflow(input: TaskRunWorkflowInput): Promise<void
let pendingInputRequest: WorkflowToolRunTaskInputRequest | undefined;
let pendingUpdates: TaskInboundUpdate[] = [];
let updateIndex = 0;
- const pendingTraffic: PendingWorkflowToolTraffic = { ownerRequests: [] };
+ const pendingTraffic: PendingWorkflowToolTraffic = { messages: [], ownerRequests: [] };
const answerHooks = new Map<string, AnswerHookRoute>();
const bodyController = new AbortController();
let bodyReader:
| import("#execution/tools/workflow/owner-channels.js").ChannelReader<
"body",
- import("#execution/tools/workflow/messages.js").WorkflowToolRunOutcome
+ WorkflowBodyResult
>
| undefined;
let executorSettled = input.workflow === undefined;
+ let pendingBodyResult: WorkflowBodyResult | undefined;
try {
try {
@@ -106,31 +112,37 @@ export async function taskRunWorkflow(input: TaskRunWorkflowInput): Promise<void
}
await appendTaskViewStep({ activityObserver: input.activityObserver, view });
- while (!isFinished()) {
- const read = await raceChannelReads(
- bodyReader === undefined ? readers : [...readers, bodyReader],
- );
- if (read.channel === "body") {
+ while (true) {
+ // Hook persistence does not mean the owner has consumed every report yet.
+ if (pendingBodyResult !== undefined && updateIndex >= pendingBodyResult.reportCount) {
executorSettled = true;
- bodyReader = undefined;
- if (read.next.done) continue;
await applyPayload({
command: workflowToolRunOutcomeToTaskCommand({
from: createWorkflowBodyRef({ ...input.workflow!, execution: "background" }),
- result: read.next.value,
+ result: pendingBodyResult.outcome,
}),
kind: "task-command",
});
+ pendingBodyResult = undefined;
if (view.status === "cancelled" && dispatchAcknowledged && !dispatchRejected) {
await wakeTaskParentStep({ token: input.parentContinuationToken, view });
}
+ }
+ if (isFinished()) break;
+ const read = await raceChannelReads(
+ bodyReader === undefined ? readers : [...readers, bodyReader],
+ );
+ if (read.channel === "body") {
+ bodyReader = undefined;
+ if (read.next.done) continue;
+ pendingBodyResult = read.next.value;
continue;
}
if (read.next.done) return;
if (read.channel === "report") {
await applyPayload(
- workflowToolRunReportToTaskUpdate(read.next.value, view.taskId, updateIndex++),
+ workflowToolRunReportToTaskPayload(read.next.value, view.taskId, updateIndex++),
);
continue;
}
@@ -173,11 +185,37 @@ export async function taskRunWorkflow(input: TaskRunWorkflowInput): Promise<void
}
async function handleUpdate(update: TaskInboundUpdate): Promise<void> {
- if (dispatchAcknowledged && !isTerminalTaskStatus(view.status)) {
- await wakeTaskUpdateParentStep({ token: input.parentContinuationToken, update, view });
- } else {
- pendingUpdates.push(update);
+ if (view.metadata.kind === "subagent") {
+ if (dispatchRejected) return;
+ if (dispatchAcknowledged && !isTerminalTaskStatus(view.status)) {
+ await wakeTaskUpdateParentStep({ token: input.parentContinuationToken, update, view });
+ } else {
+ pendingUpdates.push(update);
+ }
+ return;
+ }
+ await appendTaskProgressStep({
+ progress: {
+ callId: update.callId,
+ kind: "task-progress",
+ taskId: view.taskId,
+ update: update.message,
+ updateIndex: update.updateIndex,
+ },
+ });
+ }
+
+ async function handleMessage(message: TaskInboundMessage): Promise<void> {
+ if (dispatchRejected || isTerminalTaskStatus(view.status)) return;
+ if (!dispatchAcknowledged) {
+ pendingTraffic.messages.push(message);
+ return;
}
+ await wakeTaskMessageParentStep({
+ message,
+ taskId: view.taskId,
+ token: input.parentContinuationToken,
+ });
}
async function applyPayload(
@@ -191,7 +229,12 @@ export async function taskRunWorkflow(input: TaskRunWorkflowInput): Promise<void
if (isReady || isRejected) {
if (isRejected || isTerminalTaskStatus(view.status)) {
executorSettled = true;
- } else if (input.workflow !== undefined && bodyReader === undefined && !executorSettled) {
+ } else if (
+ input.workflow !== undefined &&
+ bodyReader === undefined &&
+ pendingBodyResult === undefined &&
+ !executorSettled
+ ) {
bodyReader = createChannelReader(
"body",
awaitBodyResult(
@@ -210,6 +253,10 @@ export async function taskRunWorkflow(input: TaskRunWorkflowInput): Promise<void
}
if (payload.kind === "task-input-request") pendingInputRequest = payload;
+ if (payload.kind === "task-message") {
+ await handleMessage(payload);
+ return;
+ }
if (payload.kind === "task-update") {
await handleUpdate(payload);
return;
@@ -298,8 +345,16 @@ export async function taskRunWorkflow(input: TaskRunWorkflowInput): Promise<void
async function flushPendingTraffic(): Promise<void> {
if (!dispatchRejected) {
+ for (const message of pendingTraffic.messages) {
+ await wakeTaskMessageParentStep({
+ message,
+ taskId: view.taskId,
+ token: input.parentContinuationToken,
+ });
+ }
for (const request of pendingTraffic.ownerRequests) await wakeTaskOwnerRequestParent(request);
}
+ pendingTraffic.messages.length = 0;
pendingTraffic.ownerRequests.length = 0;
}
@@ -321,8 +376,8 @@ export async function taskRunWorkflow(input: TaskRunWorkflowInput): Promise<void
}
async function* awaitBodyResult(
- result: Promise<import("#execution/tools/workflow/messages.js").WorkflowToolRunOutcome>,
-): AsyncGenerator<import("#execution/tools/workflow/messages.js").WorkflowToolRunOutcome> {
+ result: Promise<WorkflowBodyResult>,
+): AsyncGenerator<WorkflowBodyResult> {
yield await result;
}
diff --git a/packages/eve/src/execution/tasks/parent/tool-execution.test.ts b/packages/eve/src/execution/tasks/parent/tool-execution.test.ts
new file mode 100644
index 000000000..51c7357fa
--- /dev/null
+++ b/packages/eve/src/execution/tasks/parent/tool-execution.test.ts
@@ -0,0 +1,82 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { ContextContainer, contextStorage } from "#context/container.js";
+import { backgroundToolExecutionProvider } from "#execution/tasks/parent/tool-execution.js";
+import { beginBackgroundTask } from "#execution/tasks/parent/delegate.js";
+import { sendTaskCommand, sendTaskInboundPayload } from "#execution/tasks/parent/run-parent.js";
+import { setHarnessEmissionState } from "#harness/emission.js";
+import {
+ createBackgroundToolCallBatch,
+ type BackgroundExecutableTool,
+} from "#harness/background-tools.js";
+import type { HarnessSession } from "#harness/types.js";
+
+vi.mock("#execution/tasks/parent/delegate.js", () => ({ beginBackgroundTask: vi.fn() }));
+vi.mock("#execution/tasks/parent/run-parent.js", () => ({
+ sendTaskCommand: vi.fn(),
+ sendTaskInboundPayload: vi.fn(),
+}));
+
+describe("ordinary background tool execution", () => {
+ beforeEach(() => {
+ vi.resetAllMocks();
+ vi.mocked(sendTaskCommand).mockResolvedValue("delivered");
+ vi.mocked(sendTaskInboundPayload).mockResolvedValue("delivered");
+ vi.mocked(beginBackgroundTask).mockResolvedValue({
+ createdByTurnId: "turn-1",
+ metadata: { kind: "tool", name: "export" },
+ taskId: "task-1",
+ taskInboxToken: "inbox-1",
+ taskRunId: "run-1",
+ });
+ });
+
+ it("returns the fixed receipt while routing yields and the final return separately", async () => {
+ const ctx = new ContextContainer();
+ const session: HarnessSession = setHarnessEmissionState(
+ {
+ agent: { modelReference: { id: "openai/gpt-5.4" }, system: "", tools: [] },
+ compaction: { recentWindowSize: 10, threshold: 100_000 },
+ continuationToken: "parent-token",
+ history: [],
+ sessionId: "session-1",
+ },
+ { sequence: 0, sessionStarted: true, stepIndex: 0, turnId: "turn-1" },
+ );
+ const provider = await backgroundToolExecutionProvider.create(ctx, session);
+ if (provider === undefined) throw new Error("Background executor was not created.");
+ const executor = provider.value;
+ const definition: BackgroundExecutableTool = {
+ name: "export",
+ async *execute(_input, _options, task) {
+ yield "progress";
+ yield task.postMessage("Review the export");
+ return { result: "done" };
+ },
+ };
+ const batch = createBackgroundToolCallBatch();
+ batch.setTool("export", definition);
+ batch.register({ callId: "call-1", input: {}, toolName: "export" });
+ const result = await contextStorage.run(ctx, () =>
+ executor.execute({
+ batch,
+ definition,
+ options: { toolCallId: "call-1", messages: [] },
+ toolInput: {},
+ }),
+ );
+ expect(result).toEqual({ status: "working", taskId: "task-1" });
+ expect(sendTaskCommand).toHaveBeenCalledWith({
+ command: { kind: "complete", data: { result: "done" } },
+ taskInboxToken: "inbox-1",
+ });
+ expect(sendTaskInboundPayload).toHaveBeenCalledWith({
+ payload: expect.objectContaining({ kind: "task-update", message: "progress" }),
+ taskInboxToken: "inbox-1",
+ });
+ expect(sendTaskInboundPayload).toHaveBeenCalledWith({
+ payload: expect.objectContaining({ kind: "task-message", message: "Review the export" }),
+ taskInboxToken: "inbox-1",
+ });
+ });
+});
diff --git a/packages/eve/src/execution/tasks/parent/tool-execution.ts b/packages/eve/src/execution/tasks/parent/tool-execution.ts
index b78c936a9..6b069506a 100644
--- a/packages/eve/src/execution/tasks/parent/tool-execution.ts
+++ b/packages/eve/src/execution/tasks/parent/tool-execution.ts
@@ -4,7 +4,6 @@ import { ActivityObserverKey } from "#context/keys.js";
import type { FrameworkContextProvider } from "#context/provider.js";
import { runStep } from "#context/run-step.js";
import { buildCallbackContext } from "#context/build-callback-context.js";
-import { CallbackBaseUrlKey } from "#harness/authorization.js";
import { isAuthorizationSignal } from "#harness/authorization.js";
import { activeTurnId } from "#harness/active-turn-id.js";
import { getHarnessEmissionState } from "#harness/emission.js";
@@ -17,20 +16,12 @@ import {
type BackgroundToolExecutor,
} from "#harness/background-tools.js";
import { deriveBackgroundTaskActivityObserver } from "#execution/activity-work.js";
-import { createEveCallbackRoutePath } from "#protocol/routes.js";
import { isAsyncIterable } from "#shared/async-iterable.js";
import { parseJsonValue } from "#shared/json.js";
import type { ToolExecuteOptions } from "#tools/definition.js";
-import {
- createTaskDelegated,
- isTaskDelegated,
- type TaskExec,
- type TaskSendCommand,
-} from "#tools/task.js";
+import { createTaskMessage, isTaskMessage, type TaskExec } from "#tools/task.js";
import { recordSessionTask } from "#tasks/session-index.js";
-import type { TaskInboundUpdate } from "#tasks/types.js";
import type { AgentView } from "#subagents/handles/prompt.js";
-import { createWorkflowCallbackUrl } from "#execution/workflow-callback-url.js";
import {
beginBackgroundTask,
prepareBackgroundTask,
@@ -276,26 +267,15 @@ class BackgroundToolExecutionScope implements BackgroundToolExecutor {
const task = started.task;
record.task = task;
- const callbackBaseUrl = ctx.get(CallbackBaseUrlKey);
- const binding = {
- taskId: task.taskId,
- token: task.taskInboxToken,
- ...(callbackBaseUrl === undefined
- ? {}
- : {
- url: createWorkflowCallbackUrl(
- callbackBaseUrl,
- createEveCallbackRoutePath(task.taskInboxToken),
- ),
- }),
- };
const taskExec: TaskExec = {
- batch: input.batch.calls,
- binding,
- delegated: ({ executor, receipt }) => createTaskDelegated({ binding, executor, receipt }),
- send: createTaskSender(task, input.options.toolCallId),
+ binding: { taskId: task.taskId, token: task.taskInboxToken },
+ postMessage: createTaskMessage,
+ send() {
+ throw new Error("task.send() was replaced by yielded task descriptors.");
+ },
session: this.initialSession,
task,
+ taskId: task.taskId,
};
if (input.definition.workflowId !== undefined) {
record.settled = true;
@@ -306,28 +286,18 @@ class BackgroundToolExecutionScope implements BackgroundToolExecutor {
};
}
const output = input.definition.execute(input.toolInput, input.options, taskExec);
- if (isAsyncIterable(output)) {
- throw new Error("Background tools cannot return AsyncIterable output.");
- }
- const settled = await output;
+ const settled = isAsyncIterable(output)
+ ? await executeBackgroundIterable({
+ callId: input.options.toolCallId,
+ output,
+ task,
+ })
+ : await output;
if (isAuthorizationSignal(settled)) return settled;
- if (isTaskDelegated(settled)) {
- if (settled.executor !== undefined) {
- await deliverTaskCommand(task, {
- executor: settled.executor,
- kind: "bind",
- });
- record.task = { ...task, executor: settled.executor };
- }
- record.settled = true;
- return started.receipt === undefined
- ? settled.receipt
- : { ...settled.receipt, ...started.receipt };
- }
await deliverTaskCommand(task, { data: parseJsonValue(settled), kind: "complete" });
record.settled = true;
- return settled;
+ return { status: "working", taskId: task.taskId };
}
private async startTask(input: {
@@ -486,6 +456,7 @@ class BackgroundToolExecutionScope implements BackgroundToolExecutor {
session: buildCallbackContext().session,
stepIndex: input.emission.stepIndex,
toolName: input.input.definition.name,
+ taskId: task.taskId,
workflowId: workflow.workflowId,
},
});
@@ -558,6 +529,42 @@ class BackgroundToolExecutionScope implements BackgroundToolExecutor {
}
}
+async function executeBackgroundIterable(input: {
+ readonly callId: string;
+ readonly output: AsyncIterable<unknown>;
+ readonly task: BackgroundTask;
+}): Promise<unknown> {
+ const iterator = input.output[Symbol.asyncIterator]();
+ let updateIndex = 0;
+ let next = await iterator.next();
+ while (!next.done) {
+ const payload = isTaskMessage(next.value)
+ ? {
+ callId: input.callId,
+ kind: "task-message" as const,
+ message: next.value.message,
+ messageEpoch: input.task.taskId,
+ messageIndex: updateIndex++,
+ }
+ : {
+ callId: input.callId,
+ kind: "task-update" as const,
+ message: typeof next.value === "string" ? next.value : JSON.stringify(next.value),
+ updateEpoch: input.task.taskId,
+ updateIndex: updateIndex++,
+ };
+ const outcome = await sendTaskInboundPayload({
+ payload,
+ taskInboxToken: input.task.taskInboxToken,
+ });
+ if (outcome !== "delivered") {
+ throw new Error(`Task run "${input.task.taskId}" did not accept "${payload.kind}".`);
+ }
+ next = await iterator.next();
+ }
+ return next.value ?? null;
+}
+
function hasAgentHandle(session: HarnessSession, agentId: string): boolean {
return (
getAgentHandleStore(session.state)?.handles.some((handle) => handle.identity.id === agentId) ===
@@ -582,34 +589,6 @@ async function deliverTaskCommand(
}
}
-function createTaskSender(
- task: BackgroundTask,
- callId: string,
-): (command: TaskSendCommand) => Promise<void> {
- let nextUpdateIndex = 0;
- return async (command) => {
- if (command.kind !== "update") {
- await deliverTaskCommand(task, command);
- return;
- }
-
- const payload: TaskInboundUpdate = {
- callId,
- kind: "task-update",
- message: command.message,
- updateEpoch: task.taskId,
- updateIndex: nextUpdateIndex++,
- };
- const outcome = await sendTaskInboundPayload({
- payload,
- taskInboxToken: task.taskInboxToken,
- });
- if (outcome !== "delivered") {
- throw new Error(`Task run "${task.taskId}" did not accept "${command.kind}".`);
- }
- };
-}
-
function readClaimedHandle(result: AgentHandleStoreCommandResult): boolean {
return result.kind === "ready" && result.handle?.phase === "claimed";
}
diff --git a/packages/eve/src/execution/tools/workflow/body.ts b/packages/eve/src/execution/tools/workflow/body.ts
index 52810eb1b..d5290c30f 100644
--- a/packages/eve/src/execution/tools/workflow/body.ts
+++ b/packages/eve/src/execution/tools/workflow/body.ts
@@ -13,6 +13,7 @@ import { normalizeSerializableError } from "#execution/workflow-errors.js";
import { readRegisteredWorkflow } from "#execution/workflow-registry.js";
import type { JsonObject, JsonValue } from "#shared/json.js";
import type { ToolContext } from "#tools/definition.js";
+import { createTaskMessage, type TaskExec } from "#tools/task.js";
export interface WorkflowBodyDefinition {
readonly callId: string;
@@ -21,6 +22,7 @@ export interface WorkflowBodyDefinition {
readonly resultKind?: "subagent" | "tool";
readonly session: SessionContext["session"];
readonly stepIndex: number;
+ readonly taskId?: string;
readonly toolName: string;
readonly workflowId: string;
}
@@ -29,9 +31,15 @@ export interface WorkflowBodyInput extends WorkflowBodyDefinition {
readonly owner: WorkflowToolRunOwner;
}
+export interface WorkflowBodyResult {
+ readonly outcome: WorkflowToolRunOutcome;
+ readonly reportCount: number;
+}
+
type WorkflowToolExecute = (
input: unknown,
ctx: ToolContext,
+ task?: TaskExec,
) => Promise<JsonValue> | AsyncIterable<JsonValue>;
/** Executes one registered workflow body and reports progress to its owner. */
@@ -41,14 +49,16 @@ export async function executeWorkflowBody(
readonly runId?: string;
},
signal: AbortSignal,
-): Promise<WorkflowToolRunOutcome> {
+): Promise<WorkflowBodyResult> {
const from = createWorkflowBodyRef(input);
const ctx = createWorkflowBodyContext(input, signal);
attachWorkflowToolRunContext(ctx, { from, owner: input.owner });
+ let reportCount = 0;
try {
const execute = resolveWorkflowToolExecute(input);
- const result = execute(input.executeInput ?? input.input, ctx);
+ const task = input.execution === "background" ? createWorkflowTaskExec(input) : undefined;
+ const result = execute(input.executeInput ?? input.input, ctx, task);
let output: JsonValue;
if (!isAsyncIterable(result)) {
output = await result;
@@ -60,20 +70,27 @@ export async function executeWorkflowBody(
last = next.value;
const report: WorkflowToolRunReport = { from, update: next.value };
await resumeHookStep(input.owner.report, report);
+ reportCount += 1;
next = await iterator.next();
}
- output = (next.value as JsonValue | undefined) ?? last ?? null;
+ output =
+ (next.value as JsonValue | undefined) ??
+ (input.execution === "blocking" ? last : undefined) ??
+ null;
}
- return { output, status: "completed" };
+ return { outcome: { output, status: "completed" }, reportCount };
} catch (error) {
if (signal.aborted) {
return {
- reason:
- signal.reason instanceof Error ? signal.reason.message : String(signal.reason ?? ""),
- status: "cancelled",
+ outcome: {
+ reason:
+ signal.reason instanceof Error ? signal.reason.message : String(signal.reason ?? ""),
+ status: "cancelled",
+ },
+ reportCount,
};
}
- return { error: normalizeSerializableError(error), status: "failed" };
+ return { outcome: { error: normalizeSerializableError(error), status: "failed" }, reportCount };
}
}
@@ -125,6 +142,22 @@ function createWorkflowBodyContext(input: WorkflowBodyInput, signal: AbortSignal
};
}
+function createWorkflowTaskExec(input: WorkflowBodyInput): TaskExec {
+ if (input.taskId === undefined) {
+ throw new Error(`Background workflow tool "${input.toolName}" has no task id.`);
+ }
+ return {
+ binding: { taskId: input.taskId, token: input.taskId },
+ postMessage: createTaskMessage,
+ send() {
+ throw new Error("task.send() was replaced by yielded task descriptors.");
+ },
+ session: undefined as never,
+ task: undefined as never,
+ taskId: input.taskId,
+ };
+}
+
function isAsyncIterable(value: unknown): value is AsyncIterable<JsonValue> {
return (
typeof value === "object" &&
diff --git a/packages/eve/src/execution/tools/workflow/owner-inbox.test.ts b/packages/eve/src/execution/tools/workflow/owner-inbox.test.ts
index 365623d0e..162f74f2e 100644
--- a/packages/eve/src/execution/tools/workflow/owner-inbox.test.ts
+++ b/packages/eve/src/execution/tools/workflow/owner-inbox.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest";
import {
workflowToolRunOutcomeToTaskCommand,
+ workflowToolRunReportToTaskPayload,
workflowToolRunRequestToTaskInputRequest,
} from "#execution/tools/workflow/owner-inbox.js";
@@ -91,6 +92,36 @@ describe("workflow-tool task input", () => {
});
});
+describe("workflow-tool task reports", () => {
+ it("maps postMessage to a distinct parent delivery", () => {
+ expect(
+ workflowToolRunReportToTaskPayload(
+ { from, update: { kind: "eve:task-message", message: "Review this output." } },
+ "task-1",
+ 2,
+ ),
+ ).toEqual({
+ callId: "call-1",
+ kind: "task-message",
+ message: "Review this output.",
+ messageEpoch: "task-1",
+ messageIndex: 2,
+ });
+ });
+
+ it("keeps untagged yields as progress", () => {
+ expect(
+ workflowToolRunReportToTaskPayload({ from, update: { progress: 0.5 } }, "task-1", 1),
+ ).toEqual({
+ callId: "call-1",
+ kind: "task-update",
+ message: '{"progress":0.5}',
+ updateEpoch: "task-1",
+ updateIndex: 1,
+ });
+ });
+});
+
describe("workflow-tool task outcomes", () => {
it("keeps a subagent failure object as task failure data", () => {
expect(
diff --git a/packages/eve/src/execution/tools/workflow/owner-inbox.ts b/packages/eve/src/execution/tools/workflow/owner-inbox.ts
index 3ea4465fd..57644b6d6 100644
--- a/packages/eve/src/execution/tools/workflow/owner-inbox.ts
+++ b/packages/eve/src/execution/tools/workflow/owner-inbox.ts
@@ -12,7 +12,8 @@ import type { RuntimeSubagentResult } from "#shared/action-types.js";
import type { InputRequest } from "#shared/input.js";
import type { ToolInputRequest } from "#tools/definition.js";
import type { WorkflowToolRunTaskInputRequest } from "#execution/tasks/child/workflow.js";
-import type { TaskCommand, TaskInboundUpdate } from "#tasks/types.js";
+import type { TaskCommand, TaskInboundMessage, TaskInboundUpdate } from "#tasks/types.js";
+import { isTaskMessage } from "#tools/task.js";
import { SUBAGENT_EXECUTION_FAILED } from "#subagents/agent-handle-errors.js";
import { parseJsonValue, type JsonValue } from "#shared/json.js";
@@ -98,11 +99,20 @@ function subagentFailureOutput(error: unknown): JsonValue {
};
}
-export function workflowToolRunReportToTaskUpdate(
+export function workflowToolRunReportToTaskPayload(
report: WorkflowToolRunReport,
taskId: string,
updateIndex: number,
-): TaskInboundUpdate {
+): TaskInboundMessage | TaskInboundUpdate {
+ if (isTaskMessage(report.update)) {
+ return {
+ callId: report.from.callId,
+ kind: "task-message",
+ message: report.update.message,
+ messageEpoch: taskId,
+ messageIndex: updateIndex,
+ };
+ }
return {
callId: report.from.callId,
kind: "task-update",
diff --git a/packages/eve/src/execution/tools/workflow/workflow-tool-run.integration.test.ts b/packages/eve/src/execution/tools/workflow/workflow-tool-run.integration.test.ts
index ec8cd8793..599f2bc87 100644
--- a/packages/eve/src/execution/tools/workflow/workflow-tool-run.integration.test.ts
+++ b/packages/eve/src/execution/tools/workflow/workflow-tool-run.integration.test.ts
@@ -9,6 +9,7 @@ import { createTestRuntime, type TestRuntime } from "#internal/testing/app-harne
import { captureTurnEvents, filterEventsByType } from "#internal/testing/events.js";
import {
askThenRaceWorkflow,
+ backgroundDeployWorkflow,
confirmDeployWorkflow,
deployServiceWorkflow,
failingDeployWorkflow,
@@ -377,7 +378,7 @@ describe("workflow tools", () => {
it("runs a background workflow tool as its task's executor", async () => {
const runtime = await createWorkflowToolRuntime({
agentName: "workflow-tool-background",
- execute: reportingDeployWorkflow,
+ execute: backgroundDeployWorkflow,
toolName: "report_deploy",
});
@@ -414,7 +415,8 @@ describe("workflow tools", () => {
notifications.push(eventsText(filterEventsByType(woken, "message.received")));
}
const text = notifications.join("\n");
- expect(text).toContain("update: planned api");
+ expect(text).toContain("Review plan:api");
+ expect(text).not.toContain("update: planned api");
expect(text).toContain("is completed");
expect(text).toContain("plan:api");
} finally {
diff --git a/packages/eve/src/execution/tools/workflow/workflow.ts b/packages/eve/src/execution/tools/workflow/workflow.ts
index 7befeb48a..f322b895a 100644
--- a/packages/eve/src/execution/tools/workflow/workflow.ts
+++ b/packages/eve/src/execution/tools/workflow/workflow.ts
@@ -30,7 +30,7 @@ export async function workflowToolRunWorkflow(input: WorkflowToolRunInput): Prom
const bodyInput = { ...input, execution: input.execution ?? "blocking" } as const;
const from = createWorkflowBodyRef(bodyInput);
- const body = executeWorkflowBody(bodyInput, control.signal).then((outcome) => {
+ const body = executeWorkflowBody(bodyInput, control.signal).then(({ outcome }) => {
if (outcome.status === "completed") return outcome.output;
if (outcome.status === "failed") throw outcome.error;
throw control.signal.reason ?? new Error(outcome.reason ?? "Workflow tool run cancelled.");
diff --git a/packages/eve/src/internal/authored-definition/schema-backed.test.ts b/packages/eve/src/internal/authored-definition/schema-backed.test.ts
index 7dd8eabf6..26b60f422 100644
--- a/packages/eve/src/internal/authored-definition/schema-backed.test.ts
+++ b/packages/eve/src/internal/authored-definition/schema-backed.test.ts
@@ -36,11 +36,9 @@ describe("normalizeToolDefinition", () => {
description: "Starts an export.",
execution: "background",
inputSchema: z.object({ exportId: z.string() }),
- execute(input, _ctx, task) {
- return task.delegated({
- executor: { data: { exportId: input.exportId }, kind: "export" },
- receipt: { exportId: input.exportId },
- });
+ async *execute(input) {
+ yield { exportId: input.exportId };
+ return { exportId: input.exportId };
},
});
diff --git a/packages/eve/src/internal/testing/workflow-tool-fixtures.ts b/packages/eve/src/internal/testing/workflow-tool-fixtures.ts
index e8470d75e..2955f705d 100644
--- a/packages/eve/src/internal/testing/workflow-tool-fixtures.ts
+++ b/packages/eve/src/internal/testing/workflow-tool-fixtures.ts
@@ -10,6 +10,7 @@ import { createHook, sleep as workflowSleep } from "#compiled/@workflow/core/ind
import { ask } from "#execution/tools/workflow/ask.js";
import type { ToolContext } from "#tools/definition.js";
+import type { TaskExec, TaskMessage } from "#tools/task.js";
export interface DeployInput {
readonly service: string;
@@ -80,6 +81,19 @@ export async function* reportingDeployWorkflow(
return { plan };
}
+export async function* backgroundDeployWorkflow(
+ input: DeployInput,
+ _ctx: ToolContext,
+ task: TaskExec,
+): AsyncGenerator<string | TaskMessage, { readonly plan: string }> {
+ "use workflow";
+
+ const plan = await planDeployStep(input.service);
+ yield `planned ${input.service}`;
+ yield task.postMessage(`Review ${plan}`);
+ return { plan };
+}
+
async function planDeployStep(service: string): Promise<string> {
"use step";
diff --git a/packages/eve/src/public/definitions/exact.test.ts b/packages/eve/src/public/definitions/exact.test.ts
index 828025ba1..d0fa1d8ef 100644
--- a/packages/eve/src/public/definitions/exact.test.ts
+++ b/packages/eve/src/public/definitions/exact.test.ts
@@ -27,8 +27,8 @@ import { defineSchedule } from "#public/definitions/schedule.js";
import { defineSkill } from "#public/definitions/skill.js";
import {
defineTool,
- type TaskReceipt,
type TaskExec,
+ type TaskReceipt,
type ToolDefinition,
} from "#public/tools/index.js";
import { experimental_workflow } from "#public/tools/workflow.js";
@@ -97,20 +97,19 @@ describe("definition helper exact inputs", () => {
description: "Start a durable export.",
execution: "background",
inputSchema: z.object({ jobId: z.string() }),
- execute(input, _ctx, task) {
+ async *execute(input, _ctx, task) {
expectTypeOf(task).toEqualTypeOf<TaskExec>();
- expectTypeOf(task.binding.taskId).toEqualTypeOf<string>();
- return task.delegated({
- executor: { data: { jobId: input.jobId }, kind: "export" },
- receipt: { jobId: input.jobId },
- });
+ expectTypeOf(task.taskId).toEqualTypeOf<string>();
+ expectTypeOf(task).not.toHaveProperty("delegated");
+ yield { jobId: input.jobId };
+ return { jobId: input.jobId };
},
});
expectTypeOf(backgroundTool.execution).toEqualTypeOf<"background">();
- expectTypeOf<Parameters<NonNullable<typeof backgroundTool.toModelOutput>>[0]>().toEqualTypeOf<
- TaskReceipt<{ jobId: string }>
- >();
+ expectTypeOf<
+ Parameters<NonNullable<typeof backgroundTool.toModelOutput>>[0]
+ >().toEqualTypeOf<TaskReceipt>();
expect(backgroundTool.execution).toBe("background");
});
@@ -133,16 +132,6 @@ describe("definition helper exact inputs", () => {
});
function typeOnlyFixtures(): void {
- defineTool({
- description: "Invalid streaming background tool.",
- // @ts-expect-error Background executors settle once; streamed output is unsupported.
- execution: "background",
- inputSchema: { type: "object" },
- async *execute() {
- yield { status: "working" };
- },
- });
-
defineDynamic({
// @ts-expect-error defineDynamic is resolver-only.
fallback: "anthropic/claude-sonnet-5",
diff --git a/packages/eve/src/public/tools/index.ts b/packages/eve/src/public/tools/index.ts
index fcd6367d0..b11a949b8 100644
--- a/packages/eve/src/public/tools/index.ts
+++ b/packages/eve/src/public/tools/index.ts
@@ -8,10 +8,7 @@ export {
defineTool,
disableTool,
isDisabledToolSentinel,
- type TaskBinding,
- type TaskDelegated,
type TaskExec,
- type TaskExecutorBinding,
type TaskReceipt,
type ToolAuthOptions,
type ToolAuthProvider,
diff --git a/packages/eve/src/tasks/types.ts b/packages/eve/src/tasks/types.ts
index 33b609c7d..17175b596 100644
--- a/packages/eve/src/tasks/types.ts
+++ b/packages/eve/src/tasks/types.ts
@@ -139,6 +139,15 @@ export interface TaskCommandHookPayload {
readonly command: TaskCommand;
}
+/** One authored message delivered to the parent as a new turn. */
+export interface TaskInboundMessage {
+ readonly callId: string;
+ readonly kind: "task-message";
+ readonly message: string;
+ readonly messageIndex: number;
+ readonly messageEpoch: string;
+}
+
/** Intermediate progress reported by an executor. */
export interface TaskInboundUpdate {
readonly callId: string;
@@ -175,6 +184,7 @@ export interface TaskInboundAnswerInput {
export type TaskRunInboundPayload =
| TaskCommandHookPayload
| TaskInboundAnswerInput
+ | TaskInboundMessage
| TaskInboundUpdate;
/** Generic task-owned request sent through the parent session payload. */
@@ -221,6 +231,15 @@ export interface TaskAgentRequestDelivery {
readonly taskId: string;
}
+export interface TaskProgress {
+ readonly callId: string;
+ readonly kind: "task-progress";
+ readonly taskId: string;
+ readonly update: JsonValue;
+ readonly updateIndex: number;
+}
+
+export const TASK_PROGRESS_STREAM_NAMESPACE = "eve.task.progress";
export const TASK_VIEW_STREAM_NAMESPACE = "eve.task";
export function isTerminalTaskStatus(status: TaskStatus): boolean {
diff --git a/packages/eve/src/tools/behavior.ts b/packages/eve/src/tools/behavior.ts
index 3191b28b2..dbd64ca18 100644
--- a/packages/eve/src/tools/behavior.ts
+++ b/packages/eve/src/tools/behavior.ts
@@ -14,10 +14,16 @@ export type CompiledToolHandling =
| { readonly kind: "workflow-tool"; readonly workflowId: string };
/** Closed, serializable behavior carried by one selected compiled tool. */
+export interface ToolExecutionShape {
+ readonly lifetime: "step" | "task";
+ readonly suspend: "none" | "workflow";
+}
+
export interface CompiledToolBehavior {
readonly availability: readonly ToolAvailabilityCondition[];
readonly handling?: CompiledToolHandling;
readonly presentation?: "load-skill";
+ readonly shape?: ToolExecutionShape;
}
/** Concrete dispatch identity prepared before a tool reaches the harness. */
diff --git a/packages/eve/src/tools/definition.ts b/packages/eve/src/tools/definition.ts
index a64829312..6f057f777 100644
--- a/packages/eve/src/tools/definition.ts
+++ b/packages/eve/src/tools/definition.ts
@@ -17,20 +17,13 @@ import {
} from "#tools/durable-callbacks.js";
import { TOOL_BRAND } from "#tools/dynamic.js";
import type { ToolModelOutput } from "#tools/model-output.js";
-import type { TaskDelegated, TaskExec, TaskReceipt } from "#tools/task.js";
+import type { TaskExec, TaskReceipt } from "#tools/task.js";
type ApprovalContextInput<TInput> = unknown extends TInput ? Record<string, unknown> : TInput;
export type { ToolAuthDefinition, ToolAuthOptions, ToolAuthProvider } from "#tools/auth.js";
export type { ToolModelOutput, ToolModelOutputPart } from "#tools/model-output.js";
-export type {
- TaskBinding,
- TaskDelegated,
- TaskExec,
- TaskExecutorBinding,
- TaskReceipt,
- TaskSendCommand,
-} from "#tools/task.js";
+export type { TaskExec, TaskExecutorBinding, TaskReceipt } from "#tools/task.js";
export type ToolExecuteOptions = Omit<ToolExecutionOptions<unknown>, "context">;
@@ -210,15 +203,15 @@ export interface ToolDefinition<TInput = unknown, TOutput = unknown> extends Pub
export interface BackgroundToolDefinition<
TInput = unknown,
TOutput = unknown,
-> extends PublicToolDefinition<TInput, TOutput> {
+> extends PublicToolDefinition<TInput, TaskReceipt> {
readonly execution: "background";
execute(
input: TInput,
ctx: ToolContext,
task: TaskExec,
- ): Promise<TaskDelegated | TOutput> | TaskDelegated | TOutput | AsyncIterable<TOutput>;
+ ): Promise<TOutput> | TOutput | AsyncIterable<unknown>;
approval?: Approval<ApprovalContextInput<TInput>>;
- toModelOutput?: (output: TOutput) => ToolModelOutput | Promise<ToolModelOutput>;
+ toModelOutput?: (output: TaskReceipt) => ToolModelOutput | Promise<ToolModelOutput>;
}
type ToolOutputFromExecuteReturn<TReturn> =
@@ -229,11 +222,11 @@ type ToolOutputFromExecuteReturn<TReturn> =
: TReturn;
type BackgroundToolOutputFromExecuteReturn<TReturn> =
- ToolOutputFromExecuteReturn<TReturn> extends infer TOutput
- ? TOutput extends TaskDelegated<infer TData>
- ? TaskReceipt<TData>
- : TOutput
- : never;
+ TReturn extends AsyncGenerator<unknown, infer TOutput>
+ ? TOutput
+ : TReturn extends AsyncIterable<unknown>
+ ? null
+ : Awaited<TReturn>;
type ToolDefinitionWithExecuteReturn<TInput, TOutput, TReturn> = ToolDefinition<TInput, TOutput> & {
execute(input: TInput, ctx: ToolContext): TReturn;
@@ -261,10 +254,7 @@ export function defineTool<
description: BackgroundToolDefinition<unknown, unknown>["description"];
execution: "background";
inputSchema: TSchema;
- outputSchema?: PublicToolDefinition<
- unknown,
- BackgroundToolOutputFromExecuteReturn<TReturn>
- >["outputSchema"];
+ outputSchema?: PublicToolDefinition<unknown, TaskReceipt>["outputSchema"];
execute(input: StandardSchemaV1.InferOutput<TSchema>, ctx: ToolContext, task: TaskExec): TReturn;
approval?: BackgroundToolDefinition<StandardSchemaV1.InferOutput<TSchema>, unknown>["approval"];
toModelOutput?: BackgroundToolDefinition<
diff --git a/packages/eve/src/tools/dynamic.ts b/packages/eve/src/tools/dynamic.ts
index 6762757a3..385ef36b4 100644
--- a/packages/eve/src/tools/dynamic.ts
+++ b/packages/eve/src/tools/dynamic.ts
@@ -5,7 +5,7 @@ import type {
PublicToolOutputSchema,
ToolContext,
} from "#tools/definition.js";
-import type { TaskDelegated, TaskExec } from "#tools/task.js";
+import type { TaskExec } from "#tools/task.js";
import type { ToolModelOutput } from "#tools/model-output.js";
/**
@@ -26,11 +26,7 @@ export interface DynamicToolEntry<TInput = Record<string, unknown>, TOutput = an
readonly inputSchema: PublicToolInputSchema<TInput>;
readonly outputSchema?: PublicToolOutputSchema<TOutput>;
readonly execution?: "background";
- execute(
- input: TInput,
- ctx: ToolContext,
- task?: TaskExec,
- ): TOutput | TaskDelegated | Promise<TOutput | TaskDelegated>;
+ execute(input: TInput, ctx: ToolContext, task?: TaskExec): TOutput | Promise<TOutput>;
readonly toModelOutput?: (output: TOutput) => ToolModelOutput | Promise<ToolModelOutput>;
/**
* Optional per-call approval gate, mirroring the authored-tool
diff --git a/packages/eve/src/tools/task.test.ts b/packages/eve/src/tools/task.test.ts
new file mode 100644
index 000000000..91e957cf1
--- /dev/null
+++ b/packages/eve/src/tools/task.test.ts
@@ -0,0 +1,13 @@
+import { describe, expect, it } from "vitest";
+
+import { createTaskMessage } from "#tools/task.js";
+
+describe("TaskExec descriptors", () => {
+ it("builds non-empty parent messages", () => {
+ expect(createTaskMessage("Review the export.")).toEqual({
+ kind: "eve:task-message",
+ message: "Review the export.",
+ });
+ expect(() => createTaskMessage(" ")).toThrow("Task messages must not be empty.");
+ });
+});
diff --git a/packages/eve/src/tools/task.ts b/packages/eve/src/tools/task.ts
index edfd558c3..0fad91591 100644
--- a/packages/eve/src/tools/task.ts
+++ b/packages/eve/src/tools/task.ts
@@ -1,125 +1,63 @@
import type { BackgroundTask } from "#execution/tasks/parent/delegate.js";
-import type { BackgroundToolCall } from "#harness/background-tools.js";
import type { HarnessSession } from "#harness/types.js";
import type { JsonObject, JsonValue } from "#shared/json.js";
-const TASK_DELEGATED_KIND = "eve:task-delegated";
+const TASK_MESSAGE_KIND = "eve:task-message" as const;
-/** Private address an executor uses to report lifecycle changes to its owning task. */
-export interface TaskBinding {
- readonly taskId: string;
- readonly token: string;
- readonly url?: string;
+export type TaskMessage = JsonObject & {
+ readonly kind: typeof TASK_MESSAGE_KIND;
+ readonly message: string;
+};
+
+export function createTaskMessage(message: string): TaskMessage {
+ if (message.trim() === "") throw new TypeError("Task messages must not be empty.");
+ return { kind: TASK_MESSAGE_KIND, message };
+}
+
+export function isTaskMessage(value: unknown): value is TaskMessage {
+ return (
+ typeof value === "object" && value !== null && Reflect.get(value, "kind") === TASK_MESSAGE_KIND
+ );
}
-/**
- * Opaque, task-private address used to control an external executor. `data`
- * means nothing to the task layer beyond deep equality (replay idempotency);
- * only the executor `kind` that wrote it may parse it (e.g. cancel routing).
- */
+/** Opaque, framework-private address used to control a task executor. */
export interface TaskExecutorBinding {
readonly kind: string;
readonly data: JsonObject;
}
-/**
- * What the model sees as this call's tool output when work is delegated: the
- * author-supplied data plus `status: "working"` and the `taskId` it can poll
- * or cancel. It acknowledges delegation — it is not the task's result, which
- * arrives later through task completion.
- */
-export type TaskReceipt<TData extends JsonObject = JsonObject> = TData & {
- readonly status: "working";
+/** @deprecated Use workflow-backed background tools with yield descriptors. */
+export interface TaskBinding {
readonly taskId: string;
-};
-
-/**
- * Sentinel returned by a background tool after an external executor accepts
- * responsibility for the task. Returning it ends `execute`; it does not
- * complete the durable task.
- */
-export interface TaskDelegated<TData extends JsonObject = JsonObject> {
- readonly kind: typeof TASK_DELEGATED_KIND;
- readonly executor: TaskExecutorBinding;
- readonly receipt: TaskReceipt<TData>;
+ readonly token: string;
+ readonly url?: string;
}
-/**
- * Commands an in-process executor may report to its task via
- * {@link TaskExec.send}. Deliberately narrower than the task run's full
- * command surface — bind, ready, and input routing stay runtime-owned.
- */
+/** @deprecated Use workflow-backed background tools with yield descriptors. */
export type TaskSendCommand =
- | {
- readonly kind: "update";
- readonly message: string;
- }
+ | { readonly kind: "update"; readonly message: string }
| { readonly kind: "complete"; readonly data: JsonValue }
| { readonly kind: "fail"; readonly data: JsonValue }
| { readonly kind: "cancel" };
-/** Task capability passed only to tools declared with `execution: "background"`. */
+/** Fixed acknowledgement returned when a background task is admitted. */
+export interface TaskReceipt {
+ readonly status: "working";
+ readonly taskId: string;
+}
+
+/** Capability passed only to tools declared with `execution: "background"`. */
export interface TaskExec {
- /**
- * The sibling background calls admitted in the same step. The only view a
- * tool has of what launched alongside it, for enforcing batch-wide
- * invariants before delegating.
- */
- readonly batch: readonly BackgroundToolCall[];
- /**
- * The task-private address for reporting lifecycle changes back to this
- * task. Hand it to the external executor so completion routes to the task
- * directly instead of through the (already finished) tool call.
- */
+ /** Model-facing durable task identity. */
+ readonly taskId: string;
+ /** Returns a descriptor which sends one message to the parent when yielded. */
+ postMessage(message: string): TaskMessage;
+ /** @deprecated Use yields from a workflow-backed background tool. */
readonly binding: TaskBinding;
- /**
- * Snapshot of the harness session at step start, for reading context.
- * Mutating it changes nothing durable: session writes belong to the
- * runtime, keyed off the executor binding at step commit.
- */
- readonly session: HarnessSession;
- /**
- * Delivers progress or a terminal command to this task's inbox from the same
- * process, for executors that outlive `execute` in-memory (e.g. a callback firing
- * after delegation). Call it only after `execute` returned `delegated(...)`
- * — the runtime settles non-delegated returns itself, and a second terminal
- * command is refused. Not restart-safe: an in-process callback dies with
- * the process; the persisted executor binding remains the durable
- * cancellation path. Throws when the task no longer accepts commands
- * (already terminal).
- */
+ /** @deprecated Use yields from a workflow-backed background tool. */
readonly send: (command: TaskSendCommand) => Promise<void>;
- /** The durable task backing this call; its identity outlives `execute`. */
+ /** @deprecated Use ctx.session. */
+ readonly session: HarnessSession;
+ /** @deprecated Framework-owned task internals are not part of the authoring API. */
readonly task: BackgroundTask;
-
- /**
- * Builds the `TaskDelegated` sentinel to return from `execute`. Centralizes
- * receipt stamping so every receipt carries this task's `taskId` and
- * `status: "working"` — tools cannot mint receipts for tasks they don't own.
- */
- delegated<TData extends JsonObject>(input: {
- readonly executor: TaskExecutorBinding;
- readonly receipt: TData;
- }): TaskDelegated<TData>;
-}
-
-export function createTaskDelegated<TData extends JsonObject>(input: {
- readonly binding: TaskBinding;
- readonly executor: TaskExecutorBinding;
- readonly receipt: TData;
-}): TaskDelegated<TData> {
- return {
- executor: input.executor,
- kind: TASK_DELEGATED_KIND,
- receipt: { ...input.receipt, status: "working", taskId: input.binding.taskId },
- };
-}
-
-export function isTaskDelegated(value: unknown): value is TaskDelegated {
- return (
- typeof value === "object" &&
- value !== null &&
- "kind" in value &&
- value.kind === TASK_DELEGATED_KIND
- );
}
diff --git a/packages/eve/test/scenarios/compile-agent.scenario.test.ts b/packages/eve/test/scenarios/compile-agent.scenario.test.ts
index a666c17f3..92f7369b0 100644
--- a/packages/eve/test/scenarios/compile-agent.scenario.test.ts
+++ b/packages/eve/test/scenarios/compile-agent.scenario.test.ts
@@ -179,6 +179,7 @@ describe("compiler artifacts", () => {
kind: "workflow-tool",
workflowId: `workflow//${packageInfo.name}@${packageInfo.version}//executeSleepTool`,
},
+ shape: { lifetime: "step", suspend: "workflow" },
},
logicalPath: "tools/sleep.mjs",
name: "sleep",
diff --git a/research/tool-suspendability-and-lifetime.md b/research/tool-suspendability-and-lifetime.md
new file mode 100644
index 000000000..ca29f1989
--- /dev/null
+++ b/research/tool-suspendability-and-lifetime.md
@@ -0,0 +1,367 @@
+---
+issue: TBD
+status: draft
+last_updated: "2026-09-03"
+---
+
+# Tools: suspendability and lifetime as two explicit axes
+
+## 1. Summary
+
+The proposal uses workflow-local bindings for execution data, ordinary yields
+for silent progress, and `yield task.postMessage(...)` for parent messages.
+There is no `task.setState()` or authored `TaskView.state`.
+
+An authored tool has two independent properties that eve encodes as two
+unrelated flags and re-derives with `if` chains at every consumer:
+
+- **Suspendability** — can the body park without holding compute? Implied by
+ the `"use workflow"` directive; surfaces as `handling.kind === "workflow-tool"`.
+- **Lifetime** — does the call end with the harness step, or outlive it as a
+ durable task? Declared by `execution: "background"`.
+
+This document makes the pair explicit in the compiled tool shape and gives
+each of the four cells one `execute` contract. The authoring surface keeps
+`execution: "background"` and the third `task` argument, but `task` loses
+`delegated`, `send`, `binding`, and the non-serializable `batch`. In their place a background body has one
+one-way channel to its task (`yield`) and two round-trip primitives that
+already exist for waiting workflow tools: `ask` for the human, and
+`ctx.getToken`/`ctx.requireAuth` inside a step for the provider. The latter is
+a blocker today for any Connect-backed workflow tool and is in scope.
+
+[Implementation PR #2997](https://github.com/vercel/eve/pull/2997) implements
+the compiled shape, fixed receipt, progress and message yields, and removal of
+`task.delegated()`. Step-scoped provider authorization (§3.2), cancellation of
+parked bodies (§7), consolidation of inbound messages (§4.1), and removal of
+the remaining deprecated `TaskExec` fields (§6) are still proposed work. The
+Devbox example below depends on the authorization and cancellation work.
+
+Motivating case: [vercel/internal-agents#2173](https://github.com/vercel/internal-agents/pull/2173)
+runs Devbox as a background tool and had to build a relay workflow, a webhook
+route, and a `session.completed` adapter because a background `execute()`
+cannot park on an external webhook or resolve the requester's token.
+
+## 2. The four cells
+
+| | `lifetime: "step"` | `lifetime: "task"` |
+| --------------------- | ------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- |
+| `suspend: "none"` | `execute(input, ctx)`. Runs in the step; generator yields are `action.partial`. | `execute(input, ctx, task)`. Runs in the step; yields report progress or parent messages, and `return` completes. No `ask`. |
+| `suspend: "workflow"` | `execute(input, ctx)` with `"use workflow"`. Turn parks on the run. | `execute(input, ctx, task)` with `"use workflow"`. Receipt to the model; run outlives the step; all of §3. |
+
+Every cell exists today. What changes: the pair is data the compiler writes
+once (§5), the same `task` capability means the same thing in both task cells,
+and a background workflow body receives `task` at all — today it is silently
+absent. `execution: "background"` selects the task column; the directive selects
+the workflow row; there is no combined enum.
+
+## 3. Authoring API
+
+### 3.1 The `task` argument and `yield`
+
+`TaskExec` shrinks to identity plus one message constructor. It returns tagged
+JSON and does no I/O, so it is replay-safe in a workflow body.
+
+```ts
+interface TaskExec {
+ readonly taskId: string;
+ postMessage(message: string): TaskMessage;
+}
+```
+
+A background body may `yield` two kinds of value:
+
+| form | parent | use |
+| ----------------------------- | ------------------------------------ | -------------------------------------- |
+| `yield value` (untagged) | not woken; streamed as progress | transient progress |
+| `yield task.postMessage(msg)` | woken with `msg` as the turn's input | something the parent should act on now |
+
+Ordinary yields from authored background tools become stream-only progress.
+Subagent update delivery stays unchanged. `postMessage` sends one message
+attributed to the task under the existing task-delivery policy.
+
+The model receives `{ status: "working", taskId }` after task admission.
+Workflow-local bindings carry the data needed after a durable wait; replay
+reconstructs them from recorded steps and events. No separate authored task
+snapshot is needed to resume the body.
+
+### 3.2 Replies: `ask` and provider authorization
+
+`yield` never asks. Anything that needs a reply is a suspension point with a
+typed reply, disjoint from `yield`:
+
+| direction | primitive | reply |
+| ------------------------ | -------------------------------------------- | ----------------------------- |
+| body ↔ human | `ask(ctx, request)` from `eve/workflow` | `{ optionId?, text? }` |
+| body ↔ identity provider | `ctx.getToken` / `ctx.requireAuth` in a step | a token, or a park on sign-in |
+
+The parent reaches the body only through `ctx.abortSignal`.
+
+**`ask`** is unchanged from the waiting-tool contract in
+`docs/tools/workflows.mdx`: the request travels over the run's `request`
+channel, the task moves to `input_required`, the channel renders it like
+`ask_question`, the answer resumes the hook. Richer response schemas are
+deferred. `postMessage` tells the agent something; `ask` asks the human
+something. A body never posts a question for the parent to relay.
+
+**Provider authorization** is the change. Today `getToken`/`requireAuth`
+throw in a workflow body and a step sees only `process.env`, so no
+Connect-backed tool can be a workflow. Contract:
+
+- Both are callable inside a `"use step"` that received `ctx`. They resolve
+ under the session identity in the run's serialized context, through the
+ scoped-authorization path a step tool uses (`execution/tool-auth.ts`). The
+ gate is the Workflow SDK's ambient step context: the same `ctx` method
+ succeeds when that context is present and throws when it is not.
+- A token is returned to the step and never enters the body's replay log.
+- Interactive authorization does not return an `AuthorizationSignal` to the
+ model. The run parks the way `ask` parks: the challenge is a `RunRequestMessage`
+ with a new `authorization` variant next to `question`; the task moves to
+ `input_required`; the parent channel renders it like a subagent's
+ `authorization.required` today (`tasks/child/steps.ts`); the callback resumes
+ the step's hook and it re-resolves. To the body this is one `await`.
+- The loop guard is unchanged: a token rejected immediately after
+ authorization fails the run.
+- In the body itself both methods keep throwing.
+
+### 3.3 Example: Devbox as a background durable tool
+
+Against the api-devbox contract the v PR already codes to: one webhook URL at
+`createTask`; `taskStateChange` posts with
+`state ∈ { pending, running, attention-required, complete, errored }`; a
+`prompt` endpoint for follow-ups; a result `{ summary, exitStatus, error?, prs? }`
+from `getTask`. `Hook` is an `AsyncIterable`, so one webhook receives every
+state change for the task's lifetime.
+
+One run owns the whole api-devbox task. Every follow-up — an
+attention-required answer, or "now fix the review findings" — goes through
+`ask`, so there is no continuation argument and no second tool.
+
+```ts
+export default defineTool({
+ execution: "background",
+ description: "Start repository work in api-devbox and see it through. Use once per task.",
+ inputSchema: devboxInputSchema, // repos, prompt, title?, assistant?, model?, pr?
+ async execute(input, ctx) {
+ "use workflow";
+
+ const events = createWebhook(); // registered before the task exists
+ const devbox = await createDevboxTask(input, events.url, ctx); // step
+
+ try {
+ for await (const request of events) {
+ const change = parseTaskStateChange(await request.json());
+ if (change === null || change.taskId !== devbox.taskId) continue;
+
+ switch (change.state) {
+ case "pending":
+ case "running":
+ continue;
+
+ case "attention-required": {
+ // api-devbox does not carry the question in the webhook; the task page does.
+ const answer = await ask(ctx, {
+ prompt:
+ `Devbox needs your input to continue "${devbox.title}".\n` +
+ `Open ${devbox.taskUrl} to see what it is asking, then reply here.`,
+ display: "text",
+ allowFreeform: true,
+ });
+ await promptDevbox(devbox.taskId, answer.text ?? "", ctx); // step
+ continue;
+ }
+
+ case "complete": {
+ const result = await readDevboxTask(devbox.taskId, ctx); // step: authoritative
+ if (input.pr === false) {
+ const next = await ask(ctx, {
+ prompt: `Review finished:\n\n${result.summary}\n\nApply these findings?`,
+ display: "confirmation",
+ options: [
+ { id: "apply", label: "Apply the findings", style: "primary" },
+ { id: "done", label: "Done" },
+ ],
+ });
+ if (next.optionId === "apply") {
+ await promptDevbox(devbox.taskId, "Apply the review findings and open a PR.", ctx);
+ continue;
+ }
+ }
+ return { summary: result.summary, prs: result.prs ?? [], taskUrl: devbox.taskUrl };
+ }
+
+ case "errored": {
+ const result = await readDevboxTask(devbox.taskId, ctx);
+ throw new FatalError(result.error ?? `Devbox task ${devbox.taskId} errored`);
+ }
+ }
+ }
+ throw new FatalError(
+ `Webhook for Devbox task ${devbox.taskId} closed before a terminal state`,
+ );
+ } finally {
+ if (ctx.abortSignal.aborted) await stopDevbox(devbox.devboxId, ctx); // step
+ }
+ },
+});
+
+async function createDevboxTask(input: DevboxInput, webhookUrl: string, ctx: ToolContext) {
+ "use step";
+ const { token } = await ctx.getToken(devboxUserAuth); // parks the run on sign-in (§3.2)
+ const client = createDevboxClient({
+ token,
+ onUnauthorized: () => ctx.requireAuth(devboxUserAuth),
+ });
+ const snapshot = await selectSnapshot(client, input.repos);
+ const set = await client.createTaskSet(input.title ?? deriveTitle(input.prompt));
+ const created = await client.createTask({
+ setId: set.set_id,
+ snapshotId: snapshot.id,
+ prompt: promptWithDeliverable(input),
+ assistant: input.assistant,
+ model: input.model,
+ webhookUrl,
+ });
+ return {
+ taskId: created.task_id,
+ devboxId: created.devbox_id,
+ title: input.title ?? deriveTitle(input.prompt),
+ taskUrl: devboxTaskUrl(created.task_id),
+ };
+}
+```
+
+`promptDevbox`, `readDevboxTask`, and `stopDevbox` are one-call steps over the
+same client; snapshot selection and prompt construction are the PR's helpers.
+
+What this buys over the bridge:
+
+- attention-required is not terminal. The run parks on `ask`, the requester
+ answers on v's channel (only the requester — `ask` already enforces that on
+ Slack), and the answer is posted from the same run.
+- A review can be followed by a fix without a second launch.
+- Sign-in is not a state the tool returns; `getToken` parks the run under the
+ requester's identity.
+- Cancellation stops the sandbox from `finally` (§7).
+- Duplicate or out-of-order webhooks are harmless: other tasks' posts are
+ skipped, a repeated `attention-required` re-asks, and a post after `return`
+ hits a hook nobody reads.
+
+Deleted: the relay workflow and route, the `session.completed`/`subagentName`
+adapter, the launch and follow-up fingerprint guards (replay is the idempotency
+mechanism), the `task` continuation argument, and `stop_devbox_task`.
+
+## 4. Task messages
+
+### 4.1 Delivery
+
+`postMessage` is not a task command and does not touch the view. It is the
+parent-session `send` the child workflow already issues for updates
+(`wakeTaskUpdateParentStep`), carrying the author's message attributed to the
+task instead of the framework's `Background task … update:` prose, deduplicated
+by the same delivery id. The receiving turn runs under the existing
+task-delivery policy.
+
+Use one `TaskInboundMessage` contract for parent-bound traffic, subsuming
+`TaskInboundUpdate` rather than keeping separate message and update queues.
+Subagent updates retain their formatting and delivery policy. `TaskProgress`
+remains the stream-only contract. The shared delivery path must preserve
+deduplication ids, buffer messages until dispatch acknowledgement, and drain
+persisted reports before task completion.
+
+### 4.2 Wiring
+
+- `runBody` already sends each yield as a `RunReport`. The owner maps
+ `TaskMessage` → parent `send`, untagged → progress on the stream. Subagent
+ reports retain their parent wakes through the shared message path.
+- `createWorkflowToolBackgroundExecute` returns `{ status: "working", taskId }` after task admission. It never waits for a body yield.
+- The `"Background tools cannot return AsyncIterable"` guard goes; the
+ ordinary background executor iterates the body, routes progress and messages,
+ and completes with the return value.
+- Step-scoped auth: `createWorkflowToolContext` builds `getToken`/`requireAuth`
+ that work under ambient step context and throw otherwise;
+ `runRequestToInputRequestPayload` maps the `authorization` request variant to
+ the `authorization.required` task event the child workflow already forwards.
+- Subagents and the tool-run keep binding executors through the internal
+ `delegated` seam. No public surface.
+
+## 5. Compiled shape
+
+`CompiledToolBehavior` carries the pair as data:
+
+```ts
+readonly shape: {
+ readonly lifetime: "step" | "task";
+ readonly suspend: "none" | "workflow";
+};
+```
+
+`handling.kind === "workflow-tool"` collapses into `suspend: "workflow"` plus
+its `workflowId`. `prepareToolBehavior`, the background-call filter in
+`tool-loop.ts`, `dispatchTaskStep`, and `createWorkflowToolBackgroundExecute`
+switch on `shape` instead of re-deriving it. `defineTool` overloads gate the
+capabilities by cell: `task` is available only for background execution, and
+`ask` requires a workflow body.
+
+## 6. Removed
+
+From the public `TaskExec`: `delegated()` and `TaskExecutorBinding` (a tool
+parks on the external system from a workflow body instead of handing off by
+sentinel; the seam stays internal), `send()` (not restart-safe by its own
+contract; dominated by `yield`), `binding` (the framework callback wire stops
+being reachable from authored code), `session` (use `ctx.session`), and `task`
+(the durable task internals remain framework-owned).
+
+Pre-1.0: no shim. The only known external consumer is the Devbox bridge; §3.3
+is its replacement. The `agent-background-tools/export.ts` fixture is rewritten
+as a workflow body.
+
+Extension manifests requiring removed delegation contracts are rejected before
+their code runs. Keep the historical contract fixtures immutable, but compile
+only the versions still declared supported.
+
+## 7. Cancellation
+
+`task_cancel` aborts `ctx.abortSignal` in the run and waits the existing grace
+period — unchanged. What changes: a body parked on a hook, webhook, `ask`, or
+authorization does not observe the signal today and is abandoned after the
+grace period without running `finally`. The tool-run must race the parked
+await against its control inbox so `finally` runs before the run ends;
+otherwise external cleanup has no home and authors reach for a second tool.
+
+With §3.2's auth change, this is one of two `execution/` changes beyond wiring.
+Both are required for the Devbox migration.
+
+## 8. Invariants
+
+- A tool's cell is fixed at compile time and visible in the manifest; `task`
+ exists iff `execution === "background"`.
+- `yield` is the only one-way channel from a body to its task, and it never
+ asks. There is no post-return path.
+- Workflow-local values survive durable waits through replay; there is no
+ authored `TaskView.state` snapshot.
+- A fixed `{ status: "working", taskId }` receipt is observed exactly once and
+ never depends on a body yield.
+- A token never enters a workflow body's replay log.
+- Subagent task behaviour is unchanged.
+
+## 9. Deferred
+
+- Structured `ask` responses (a response schema instead of
+ `{ optionId?, text? }`).
+- Externally readable authored task snapshots, pending a concrete consumer.
+
+## 10. Testing
+
+- Unit: message descriptor tagging; `defineTool` overload typing via
+ `expectTypeOf`.
+- Integration: ordinary yields remain silent; `postMessage` → parent `send`;
+ receipt independent of body yields; local values remain usable after a
+ durable wait; `getToken` in a
+ step of a background run resolves under the session identity; a step-raised
+ authorization requirement parks the task `input_required` and resumes on
+ callback; `getToken` in the body still throws.
+- Scenario: compiled `shape` for each cell.
+- E2E: rewrite `agent-background-tools/export.ts` as a workflow body that
+ parks on `createWebhook`, posts a message on callback, and
+ completes. Add a body that parks on `ask` from a background run. Sign-in
+ cannot be driven in e2e; it stays at integration tier.
diff --git a/scripts/extension-contracts/reports.mjs b/scripts/extension-contracts/reports.mjs
index 88b224d1d..69cae3496 100644
--- a/scripts/extension-contracts/reports.mjs
+++ b/scripts/extension-contracts/reports.mjs
@@ -61,9 +61,24 @@ async function rewriteDeclarationSpecifiers(declarationRoot) {
}
}
-async function emitDeclarations(tempRoot, { contractRoot, eveRoot }) {
+async function emitDeclarations(tempRoot, configuration, { contractRoot, eveRoot }) {
const declarationRoot = join(tempRoot, "declarations");
await mkdir(declarationRoot, { recursive: true });
+ const tsconfigPath = join(tempRoot, "tsconfig.json");
+ await writeFile(
+ tsconfigPath,
+ JSON.stringify({
+ extends: join(contractRoot, "tsconfig.json"),
+ include: [
+ join(contractRoot, "entrypoints/**/*.ts"),
+ ...Object.entries(configuration.contracts ?? {}).flatMap(([capability, contract]) =>
+ contract.supported
+ .filter((version) => version < contract.current)
+ .map((version) => join(contractRoot, "compatibility", capability, `v${version}.ts`)),
+ ),
+ ],
+ }),
+ );
execFileSync(process.execPath, [join(eveRoot, "scripts/vendor-compiled.mjs")], {
cwd: eveRoot,
stdio: ["ignore", "pipe", "pipe"],
@@ -76,7 +91,7 @@ async function emitDeclarations(tempRoot, { contractRoot, eveRoot }) {
[
tsc,
"-p",
- join(contractRoot, "tsconfig.json"),
+ tsconfigPath,
"--outDir",
declarationRoot,
"--declarationMap",
@@ -172,7 +187,10 @@ export async function generateCapabilityReports(
await mkdir(cacheRoot, { recursive: true });
const tempRoot = await mkdtemp(join(cacheRoot, "extension-contracts-"));
try {
- const declarationRoot = await emitDeclarations(tempRoot, { contractRoot, eveRoot });
+ const declarationRoot = await emitDeclarations(tempRoot, configuration, {
+ contractRoot,
+ eveRoot,
+ });
const capabilities = Object.keys(configuration.current);
const configs = [];
for (const [capability, version] of Object.entries(configuration.current)) {