Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

fix(eve): diagnose unsupported workflow helper contexts (#3017)

Rui3dd8300b4345
diff --git a/.changeset/friendly-workflow-context-errors.md b/.changeset/friendly-workflow-context-errors.md
new file mode 100644
index 000000000..146eae3ac
--- /dev/null
+++ b/.changeset/friendly-workflow-context-errors.md
@@ -0,0 +1,5 @@
+---
+"eve": minor
+---
+
+Define durable tools with `defineWorkflowTool` from `eve/tools`; its inline or referenced executor must start with `"use workflow"` and receives `ctx.agent` and `ctx.ask`. Replace workflow-backed `defineTool` calls with this API and remove imports from the deleted `eve/workflow` entry point.
diff --git a/docs/concepts/execution-model-and-durability.mdx b/docs/concepts/execution-model-and-durability.mdx
index 5719d508a..c64b860a3 100644
--- a/docs/concepts/execution-model-and-durability.mdx
+++ b/docs/concepts/execution-model-and-durability.mdx
@@ -60,11 +60,22 @@ Crash the process, hit a timeout, or redeploy mid-turn, and the run picks up fro
There's nothing to configure. eve owns the workflow lifecycle, and sessions are durable by default.
-You don't write workflow code directly. Workflow primitives (`start()`, `resumeHook()`, etc.) are an implementation detail of eve's runtime layer; channels, tools, and hooks never touch them. Two surfaces give your own code session data: tools read the current session's metadata (id, turn, auth, parent lineage) via `ctx.session`, and [`defineState`](./state) reads or writes session-scoped durable state. See [State](./state) for the read/write model.
+For ordinary tools, eve manages the workflow around your executor. Use [`defineWorkflowTool`](../tools/workflows) when your own tool body needs durable waits, such as a timer, webhook, or human answer. Two surfaces give your own code session data: tools read the current session's metadata (id, turn, auth, parent lineage) via `ctx.session`, and [`defineState`](./state) reads or writes session-scoped durable state. See [State](./state) for the read/write model.
## Parked work
-Some work has to wait, including a human approving a [tool](../tools) or an interactive OAuth sign-in for a [connection](../connections). At those points the turn parks durably. The workflow suspends and holds no compute until the input it's waiting on arrives, even if that's much later. When it does, the conversation picks up exactly where it left off. Background tools and subagents return a task receipt instead, so the turn continues and later task notifications deliver progress or the outcome.
+Some work has to wait, including a human approving a [tool](../tools) or an interactive OAuth sign-in for a [connection](../connections). At those points the turn parks durably. The workflow suspends and holds no compute until the input it's waiting on arrives, even if that's much later. When it does, the conversation picks up exactly where it left off.
+
+Background execution is a separate choice about result delivery. A background workflow tool
+returns a task receipt so the parent turn can continue; the tool's workflow may then run or
+suspend independently. A default workflow tool can suspend too, with its original tool call
+still pending. Ordinary background tools run their executor inside the initiating step and do
+not gain durable waits by setting `execution: "background"`.
+
+A generator's `yield` reports progress; an awaited workflow operation provides the durable wait.
+For background tools, ordinary yields are stream-only, while `yield task.postMessage(...)`
+requests a parent-agent turn. See [background execution](../tools#background-execution) and
+[workflow suspension](../tools/workflows#how-suspension-works) for the execution and result rules.
## Message delivery and steering
diff --git a/docs/reference/typescript-api.md b/docs/reference/typescript-api.md
index b24d2d8c6..749be9352 100644
--- a/docs/reference/typescript-api.md
+++ b/docs/reference/typescript-api.md
@@ -34,6 +34,7 @@ export default defineTool({
| ----------------------------------------------------- | ----------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | ------------------------------------------------------ |
| `defineAgent` | `eve` | `agent/agent.ts` | [agent.ts](../agent-config) |
| `defineTool` | `eve/tools` | `agent/tools/<name>.ts` | [Tools](../tools) |
+| `defineWorkflowTool` | `eve/tools` | `agent/tools/<name>.ts` | [Workflow tools](../tools/workflows) |
| `defineDynamic` | `eve`, `eve/tools`, `eve/skills`, `eve/instructions`, `eve/connections` | dynamic model or subagent `agent.ts`; `agent/{tools,skills,instructions,connections}/` | [Dynamic capabilities](../guides/dynamic-capabilities) |
| `defineMcpClientConnection` | `eve/connections` | `agent/connections/<name>.ts` | [MCP connections](../connections/mcp) |
| `defineOpenAPIConnection` | `eve/connections` | `agent/connections/<name>.ts` | [OpenAPI connections](../connections/openapi) |
@@ -53,7 +54,7 @@ export default defineTool({
| `mockModel` | `eve/evals` | Deterministic fixture agent models | [Evals](../evals/overview) |
| `useEveAgent` | `eve/react`, `eve/vue`, `eve/svelte` | frontend | [Frontend](../guides/frontend/overview) |
-Tool-wide authoring helpers such as `defineTool`, `defineDynamic`, and `disableTool` come from `eve/tools`. Capability-specific definitions and helpers use their own subpaths (see [Built-in tools](../concepts/built-in-tools)): reusable definitions such as `bash` and `glob` come from `eve/tools/<name>`, `webSearch` comes from `eve/tools/web_search`, `experimental_workflow` comes from `eve/tools/workflow`, `sleep` comes from `eve/tools/sleep`, and approval policies and types come from `eve/tools/approval`. The route verbs `GET`/`HEAD`/`POST`/`PUT`/`PATCH`/`DELETE`/`OPTIONS`/`WS` plus `disableRoute` come from `eve/channels`, and the channel auth helpers `localDev`/`vercelOidc`/`placeholderAuth` come from `eve/channels/auth`.
+Tool-wide authoring helpers such as `defineTool`, `defineWorkflowTool`, `defineDynamic`, and `disableTool` come from `eve/tools`. Capability-specific definitions and helpers use their own subpaths (see [Built-in tools](../concepts/built-in-tools)): reusable definitions such as `bash` and `glob` come from `eve/tools/<name>`, `webSearch` comes from `eve/tools/web_search`, `experimental_workflow` comes from `eve/tools/workflow`, `sleep` comes from `eve/tools/sleep`, and approval policies and types come from `eve/tools/approval`. The route verbs `GET`/`HEAD`/`POST`/`PUT`/`PATCH`/`DELETE`/`OPTIONS`/`WS` plus `disableRoute` come from `eve/channels`, and the channel auth helpers `localDev`/`vercelOidc`/`placeholderAuth` come from `eve/channels/auth`.
`AgentReasoningDefinition` is exported from `eve` for the top-level `defineAgent({ reasoning })` setting. `AgentLimitsDefinition` is exported for `defineAgent({ limits })`. `AgentWorkflowDefinition` and `AgentWorkflowWorldDefinition` are exported from `eve` for the `defineAgent({ experimental: { workflow } })` config shape. `ExperimentalWorkflowToolInput` is exported from `eve/tools/workflow`; `WebSearchToolInput` and `WebSearchProvider` are exported from `eve/tools/web_search`.
@@ -107,40 +108,40 @@ import template from "../../prompts/template.txt?raw";
## Imports at a glance
-| Import | Holds |
-| --------------------------------------------------------------------------- | ------------------------------------------------------------------------- |
-| `eve` | `defineAgent`, `defineRemoteAgent`, `defineDynamic`, agent config types |
-| `eve/tools` | `defineTool`, `defineDynamic`, `disableTool`, generic tool types |
-| `eve/tools/{bash,read_file,write_file,todo,web_fetch,load_skill,glob,grep}` | Individual reusable tool definitions |
-| `eve/tools/approval` | Approval types and `always`, `once`, `never` |
-| `eve/tools/web_search` | Provider-managed `webSearch` configuration |
-| `eve/tools/workflow` | Experimental `Workflow` tool definition |
-| `eve/tools/sleep` | Opt-in durable `sleep` tool |
-| `eve/connections` | `defineMcpClientConnection`, `defineOpenAPIConnection`, `defineDynamic` |
-| `eve/channels` | `defineChannel`, `disableRoute`, route verbs |
-| `eve/channels/eve` | `eveChannel` |
-| `eve/channels/auth` | `localDev`, `vercelOidc`, `placeholderAuth` |
-| `eve/channels/{slack,discord,teams,telegram,twilio,github}` | platform channel factories |
-| `eve/hooks` | `defineHook` |
-| `eve/schedules` | `defineSchedule` |
-| `eve/skills` | `defineSkill`, `defineDynamic` |
-| `eve/instructions` | `defineInstructions`, `defineDynamic` |
-| `eve/memory` | `defineMemory`, `defineMemoryProvider`, provider and lifecycle types |
-| `eve/memory/scope` | `byPrincipal` and memory scope helpers |
-| `eve/memory/file` | `fileMemory`, `inMemory`, and the conditional document backend contract |
-| `eve/memory/file/vercel` | `vercelBlob` and Vercel Blob backend options |
-| `eve/context` | `defineState`, session and state types |
-| `eve/sandbox` | `defineSandbox`, backends |
-| `eve/instrumentation` | `defineInstrumentation`, `isChannel` |
-| `eve/local-dev` | `getLocalDevCapability`, `LocalDevCapability` |
-| `eve/models/openai` | `chatgpt`, deprecated `experimental_chatgpt` |
-| `eve/evals` | `defineEval`, `defineEvalConfig`, `mockModel`, eval types |
-| `eve/evals/expect` | `includes`, `equals`, `matches`, `similarity` |
-| `eve/evals/reporters` | `Braintrust`, `JUnit`, `EvalReporter` |
-| `eve/evals/loaders` | `loadJson`, `loadYaml` |
-| `eve/react`, `eve/vue`, `eve/svelte` | `useEveAgent` |
-| `eve/next`, `eve/nuxt`, `eve/sveltekit` | framework bundler plugins |
-| [`eve/client`](../guides/client/overview) | `Client`, `ClientSession`, health and agent-info schemas, response errors |
+| Import | Holds |
+| --------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- |
+| `eve` | `defineAgent`, `defineRemoteAgent`, `defineDynamic`, agent config types |
+| `eve/tools` | `defineTool`, `defineWorkflowTool`, `defineDynamic`, `disableTool`, generic tool types |
+| `eve/tools/{bash,read_file,write_file,todo,web_fetch,load_skill,glob,grep}` | Individual reusable tool definitions |
+| `eve/tools/approval` | Approval types and `always`, `once`, `never` |
+| `eve/tools/web_search` | Provider-managed `webSearch` configuration |
+| `eve/tools/workflow` | Experimental `Workflow` tool definition |
+| `eve/tools/sleep` | Opt-in durable `sleep` tool |
+| `eve/connections` | `defineMcpClientConnection`, `defineOpenAPIConnection`, `defineDynamic` |
+| `eve/channels` | `defineChannel`, `disableRoute`, route verbs |
+| `eve/channels/eve` | `eveChannel` |
+| `eve/channels/auth` | `localDev`, `vercelOidc`, `placeholderAuth` |
+| `eve/channels/{slack,discord,teams,telegram,twilio,github}` | platform channel factories |
+| `eve/hooks` | `defineHook` |
+| `eve/schedules` | `defineSchedule` |
+| `eve/skills` | `defineSkill`, `defineDynamic` |
+| `eve/instructions` | `defineInstructions`, `defineDynamic` |
+| `eve/memory` | `defineMemory`, `defineMemoryProvider`, provider and lifecycle types |
+| `eve/memory/scope` | `byPrincipal` and memory scope helpers |
+| `eve/memory/file` | `fileMemory`, `inMemory`, and the conditional document backend contract |
+| `eve/memory/file/vercel` | `vercelBlob` and Vercel Blob backend options |
+| `eve/context` | `defineState`, session and state types |
+| `eve/sandbox` | `defineSandbox`, backends |
+| `eve/instrumentation` | `defineInstrumentation`, `isChannel` |
+| `eve/local-dev` | `getLocalDevCapability`, `LocalDevCapability` |
+| `eve/models/openai` | `chatgpt`, deprecated `experimental_chatgpt` |
+| `eve/evals` | `defineEval`, `defineEvalConfig`, `mockModel`, eval types |
+| `eve/evals/expect` | `includes`, `equals`, `matches`, `similarity` |
+| `eve/evals/reporters` | `Braintrust`, `JUnit`, `EvalReporter` |
+| `eve/evals/loaders` | `loadJson`, `loadYaml` |
+| `eve/react`, `eve/vue`, `eve/svelte` | `useEveAgent` |
+| `eve/next`, `eve/nuxt`, `eve/sveltekit` | framework bundler plugins |
+| [`eve/client`](../guides/client/overview) | `Client`, `ClientSession`, health and agent-info schemas, response errors |
Exported types ship from the same entrypoint as the helper they describe (for example `ToolDefinition` and `ToolContext` from `eve/tools`). The `exports` field in `packages/eve/package.json` lists every public entrypoint.
diff --git a/docs/tools/overview.mdx b/docs/tools/overview.mdx
index edfd68142..4ed24245b 100644
--- a/docs/tools/overview.mdx
+++ b/docs/tools/overview.mdx
@@ -34,8 +34,8 @@ When a tool returns structured data, add an optional `outputSchema`. With Zod or
### Stream preliminary tool results
-An async generator lets a long-running tool stream complete output snapshots
-before it finishes. Each `yield` replaces the previous snapshot; the final
+For a `defineTool` executor with the default execution mode, an async generator streams complete
+output snapshots before it finishes. Each `yield` replaces the previous snapshot; the final
yield is the normal tool result the model receives:
```ts title="agent/tools/build_report.ts"
@@ -54,29 +54,41 @@ eve publishes every earlier yield as an `action.partial` stream event. The
snapshot is visible to channels, hooks, and clients but never enters model
history or `toModelOutput`; only the final yield does. Treat snapshots as
last-write-wins by tool call id, not append-only progress. The durable runtime
-can retry a step and replay overlapping snapshots.
+can retry a step and replay overlapping snapshots. A generator `return` value is not used as
+the result in this mode; yield the final output. Workflow and background generators have
+different result rules, described under [yield and return](#yield-and-return).
### Background execution
-`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:
+Background execution controls how a tool delivers its result to the parent agent. Durable
+suspension controls whether the executor can pause at a workflow wait and release compute.
+These are independent choices: `execution: "background"` selects the task lifecycle;
+`defineWorkflowTool` with a leading `"use workflow"` directive enables durable suspension.
-```ts
-yield { progress: 0.5 }; // stream-only progress; does not wake the agent
-yield task.postMessage("The export needs review."); // one new parent turn
-```
+| Definition | Durable waits inside `execute` | Result delivered to the model |
+| ------------------------------------------------ | --------------------------------------------------------------- | ---------------------------------------------------------------------- |
+| `defineTool` | No; the executor runs inside the initiating step. | Executor output after it finishes. |
+| `defineTool` + `execution: "background"` | No; the initiating step still waits for the executor to finish. | Task receipt, followed by task notifications. |
+| `defineWorkflowTool` | Yes; the tool call waits while the workflow can suspend. | Workflow output after it finishes. |
+| `defineWorkflowTool` + `execution: "background"` | Yes; the workflow body can outlive the initiating step. | Task receipt before the body finishes, followed by task notifications. |
+
+A background tool receives a third `task` argument. Its tool result is the receipt
+`{ status: "working", taskId }`; its eventual output belongs to the task. Use a background
+workflow tool when the conversation should continue while the body waits for a person,
+webhook, or timer. Setting `execution: "background"` on an ordinary tool does not move its
+executor into a separate workflow or make an ordinary Promise a durable wait.
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
+`task.delegated()` has been removed. Move external work into a `defineWorkflowTool` executor 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.
+`yield task.postMessage(message)` is the only yield that requests a parent-agent turn. Calling
+`task.postMessage` only constructs the message descriptor; you must yield it to send it.
+In a workflow body, keep values needed after a wait in local variables; workflow replay
+reconstructs them across durable waits.
+Use [`ctx.ask`](/docs/tools/workflows#ask-a-human-ctxask) 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.
@@ -88,11 +100,31 @@ Later task-triggered parent turns receive fresh state for the same cohort. The m
to keep related intermediate results silent while any task remains pending. Once every related
task is terminal, the state includes their outputs so the model can combine the useful results.
+### Yield and return
+
+`yield` hands a value to eve's generator consumer, which processes it and advances the generator.
+It does not by itself create a durable wait for a person, timer, or external event. The value's
+meaning depends on the tool's execution mode:
+
+| Executor | Ordinary `yield value` | Final output |
+| ------------------------------------------------ | --------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- |
+| `defineTool`, default execution | Earlier values are `action.partial` snapshots; the final yield becomes the tool result. | Last yielded value; a generator `return` value is ignored. |
+| `defineWorkflowTool`, default execution | Every yield is an `action.partial` snapshot. | Explicit return value; falls back to the last yield if the return is `null` or `undefined`, then to `null`. |
+| Either definition with `execution: "background"` | Stream-only task progress; does not request a parent-agent turn. | Explicit return value becomes the task output; no return completes with `null`. The last yield is not a fallback. |
+
+For either kind of background tool, `yield task.postMessage(message)` sends a message to the
+parent agent while the task remains open. Return completes the task; throw fails it. These
+notifications are separate from the original tool call's receipt.
+
+Progress snapshots do not enter model history as intermediate tool results. For a default
+executor, the final output selected by the rules above becomes the tool result. For a background
+executor, task messages and completion notifications provide input to later parent-agent turns.
+
### Workflows as tools
-Put `"use workflow"` at the start of a tool's `execute` function to run each call as a durable
-Workflow run. The tool can wait for a person, webhook, or timer without holding compute, then return
-its result to the model. See [Workflows as tools](/docs/tools/workflows) for the authoring rules and
+Use `defineWorkflowTool` from `eve/tools` to run each call as a durable Workflow run. Its
+executor must start with `"use workflow"` and receives `ctx.agent` and `ctx.ask`. The tool can
+wait for a person, webhook, or timer without holding compute, then return its result to the model. See [Workflows as tools](/docs/tools/workflows) for the authoring rules and
examples.
### The `ctx` parameter
diff --git a/docs/tools/workflows.mdx b/docs/tools/workflows.mdx
index 10a6a2f4e..cc4f06b29 100644
--- a/docs/tools/workflows.mdx
+++ b/docs/tools/workflows.mdx
@@ -4,21 +4,20 @@ description: "Define durable workflow tools that wait for people, webhooks, or t
url: /tools/workflows
---
-A workflow tool is an authored tool whose `execute` function starts with `"use workflow"`. Each
-call starts a durable Workflow run. Use one when a tool must wait for a person, webhook, or timer,
+A workflow tool is a static tool defined with `defineWorkflowTool` from `eve/tools`, with
+`"use workflow"` as the first statement of its executor. Each call starts a durable Workflow run. Use one when a tool must wait for a person, webhook, or timer,
delegate work to subagents, or coordinate retryable steps over a long period.
-By default, the model's tool call waits for the run's return value. While the run is suspended, the
-turn is parked and holds no compute. Set `execution: "background"` when the conversation should
-continue; the model receives a task receipt, and eve wakes the agent with the result when the run
-ends.
+Durable suspension and background execution are independent. `defineWorkflowTool` lets the body
+suspend at durable waits without holding compute. `execution: "background"` determines whether
+the parent agent receives a task receipt and continues before the body finishes. A workflow can
+suspend in either execution mode; running in the background does not require a suspension.
-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. 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.
+Workflow tools use the [Workflow SDK](https://workflow-sdk.dev): `"use workflow"`, `"use step"`, `createHook`,
+`createWebhook`, `sleep`, retries, and replay. eve provides `ctx.ask` for questions answered through
+the session's channel and `ctx.agent` for durable subagent delegation. Use `yield` to report
+progress and `await` on a workflow operation to wait durably. 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`.
@@ -26,19 +25,17 @@ as `deploy`.
## Define a workflow tool
```ts title="agent/tools/deploy.ts"
-import { defineTool } from "eve/tools";
-import { ask } from "eve/workflow";
+import { defineWorkflowTool } from "eve/tools";
import { z } from "zod";
import { computePlan, runDeploy, type DeployPlan } from "../lib/deploy";
-export default defineTool({
+export default defineWorkflowTool({
description: "Deploy a service to production. Pauses for a human to approve the plan.",
inputSchema: z.object({ service: z.string() }),
async execute({ service }, ctx) {
"use workflow";
-
const plan = await planDeploy(service);
- const answer = await ask(ctx, {
+ const answer = await ctx.ask({
prompt: `Deploy ${service}?\n\n${plan.summary}`,
display: "confirmation",
options: [
@@ -70,41 +67,91 @@ or days later, the run resumes, deploys, and returns. The model sees one tool re
### Rules
-- `"use workflow"` goes on its own line as the first statement of `execute`, or of a top-level
- `async function` you reference as `execute: deploy`.
+- Export `defineWorkflowTool({ ... })` as the default export. Its `execute` must be an async
+ function or async generator, written inline or referenced as a top-level `async function` in
+ the same module or an imported application module. Start the executor with `"use workflow"`
+ as its first statement. A missing
+ directive is a build error, even if another function in the module has one.
- `"use step"` marks a top-level `async function` in the tool module, or any module it imports, as a
step. Side effects, clocks, randomness, `process.env`, and Node.js APIs belong in steps; the body
is replayed and must stay deterministic.
- Import `createHook`, `createWebhook`, `sleep`, and `FatalError` from `workflow` in the body.
`start`, `getRun`, and `resumeHook` from `workflow/api` belong in steps. Your app does not 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 from `process.env` in a
- step; session-scoped workflow authorization is not yet available.
+- In the body, `ctx` has `session`, `callId`, `toolName`, `abortSignal`, `agent`, and `ask`.
+ `getSandbox`, `getSkill`, `getToken`, and `requireAuth` are not part of `WorkflowToolContext`.
+ 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.
+`ctx.agent` and `ctx.ask` are available only on `WorkflowToolContext`. Ordinary tools, channel
+handlers, and schedule handlers do not receive these methods. A shared helper may accept
+`WorkflowToolContext` from `eve/tools` and use the context supplied by a workflow tool body.
+
+Workflow executors require `defineWorkflowTool`. Adding `"use workflow"` to `defineTool`, a bare
+tool object, a channel handler, or a schedule handler fails the build. To start a session from a
+channel or schedule, use the [channel operations](/docs/channels/custom#channel-operations-and-session-handles)
+or [schedule handler](/docs/schedules#handler-form-run) APIs.
+
+### Migrate an existing workflow tool
+
+Replace `defineTool` with `defineWorkflowTool`, keep the executor's `"use workflow"` directive,
+and replace `agent(ctx, input)` and `ask(ctx, request)` with `ctx.agent(input)` and `ctx.ask(request)`.
+The `eve/workflow` entry point has been removed. Import `WorkflowToolContext`, `AgentInput`,
+`ToolInputRequest`, and `ToolInputResponse` from `eve/tools` when you need explicit types.
+
## Wait or run in the background
-| | default | `execution: "background"` |
-| ------------------------ | ----------------------------------- | ------------------------------------------- |
-| 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 | 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 |
+Both modes support the same durable waits. Choose the execution mode based on when the parent
+agent should receive a tool result:
-Wait when the model needs the answer to continue. Go background when the wait may outlive the
-conversation or the user should keep talking in the meantime. Background tools need no root-agent
-flag.
+| | Default execution | `execution: "background"` |
+| ---------------------------- | --------------------------------------------------- | -------------------------------------------------------------------- |
+| Tool result | The workflow's output after it finishes. | `{ status: "working", taskId }` before the body finishes. |
+| Parent turn | Waits for this tool call to finish. | Continues after receiving the receipt. |
+| Durable wait inside the body | Suspends the workflow; the tool call stays pending. | Suspends the workflow; the parent can continue independently. |
+| When the run ends | Settles the pending tool call. | Sends a task completion or failure notification to the parent agent. |
+| Cancel | Cancelling the turn cancels the run. | `task_cancel`, or the session ending. |
-## Ask a human: `ask`
+Use default execution when the model needs the answer to continue. Use background execution when
+the conversation should continue while the task is pending. Background tools need no root-agent
+flag. Ordinary `defineTool` also accepts `execution: "background"`, but its executor still runs
+inside the initiating step and cannot suspend at workflow waits. See the
+[tool execution comparison](/docs/tools#background-execution).
+
+### How suspension works
+
+Suspension happens when a workflow must wait for an unresolved durable operation, such as
+`ctx.ask`, an awaited hook or webhook, or `sleep`. The runtime persists the wait and releases the
+workflow's compute. When the answer, event, or timer arrives, the runtime replays the workflow,
+reuses recorded step results, and continues past the wait. Put side effects in `"use step"`
+functions so replay does not repeat completed effects.
+
+Consider a body that reports progress and then asks for approval:
```ts
-import { ask } from "eve/workflow";
+async *execute(input, ctx) {
+ "use workflow";
+ yield { status: "awaiting approval" };
+ const answer = await ctx.ask({ prompt: "Continue?", display: "confirmation" });
+ return { answer };
+}
+```
+
+The yield reports a snapshot, and eve advances the generator to `ctx.ask`. Awaiting the unanswered
+request is the durable wait. In default execution, the original tool call remains pending until
+the answer arrives and the body returns. With `execution: "background"`, the original call has
+already returned a task receipt, and the workflow can suspend while the conversation continues.
+Answering resumes the body in either mode.
+
+`yield` itself does not wait for approval or switch a tool into background execution. An ordinary
+Promise or Node.js timer inside a step also does not create a durable workflow suspension; use
+the workflow operations for waits that must survive a restart.
+
+## Ask a human: `ctx.ask`
-const answer = await ask(ctx, {
+```ts
+const answer = await ctx.ask({
prompt: string,
display?: "confirmation" | "select" | "text",
options?: { id: string; label: string; description?: string; style?: "primary" | "danger" | "default" }[],
@@ -112,13 +159,12 @@ const answer = await ask(ctx, {
}); // { optionId?: string; text?: string }
```
-`ask` publishes an `input.requested` event on the session — rendered the way channels render
-`ask_question` and tool approvals — and returns the hook the answer resumes, the way `createHook`
-returns one. Awaiting it suspends the run until a response arrives. Because it is a hook, it composes
-with the SDK's own constructs; race it against a deadline:
+`ctx.ask` publishes an `input.requested` event on the session — rendered the way channels render
+`ask_question` and tool approvals — and returns an awaitable answer. Awaiting it suspends the run until a response arrives.
+It composes with the SDK's own constructs; race it against a deadline:
```ts
-const pending = ask(ctx, { prompt: `Deploy ${service}?`, options: APPROVE_OR_CANCEL });
+const pending = ctx.ask({ prompt: `Deploy ${service}?`, options: APPROVE_OR_CANCEL });
const answer = await Promise.race([pending, sleep("4h")]);
if (answer === undefined) return { deployed: false, reason: "timed out" };
```
@@ -132,16 +178,14 @@ if (answer === undefined) return { deployed: false, reason: "timed out" };
normal `turnPolicy`.
Compare the [`approval`](/docs/human-in-the-loop) policy, which gates the call before `execute` runs
-and can only show the model's input. Both compose: `approval` before the run, `ask` inside it.
+and can only show the model's input. Both compose: `approval` before the run, `ctx.ask` inside it.
-## Delegate work: `agent`
+## Delegate work: `ctx.agent`
Workflow tools can call a visible subagent and wait for its result:
```ts
-import { agent } from "eve/workflow";
-
-const result = await agent(ctx, {
+const result = await ctx.agent({
key: "security-review",
target: "reviewer",
message: "Review the deployment plan for security risks.",
@@ -155,24 +199,49 @@ 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 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`.
+A workflow body may be an async generator. Ordinary yields report progress in both execution
+modes. After processing a yield, eve advances the generator; use an awaited workflow operation
+when the body needs to suspend.
-```ts
-async *execute({ service }, ctx) {
- "use workflow";
- yield { status: "planning" };
- const plan = await planDeploy(service);
- yield { status: "deploying" };
- return { deployed: true, url: await applyDeploy(plan) };
-}
+| Operation | Default execution | `execution: "background"` |
+| --------------------------------- | ----------------------------------------------------------------- | ---------------------------------------------------------------------- |
+| `yield value` | Emits an `action.partial` snapshot for the pending tool call. | Emits stream-only task progress; does not request a parent-agent turn. |
+| `yield task.postMessage(message)` | Unavailable; there is no `task` argument. | Sends a message requesting a parent-agent turn; the task stays open. |
+| `return value` | Settles the tool call with its output. | Completes the task and delivers its output in a later notification. |
+| No return value | Uses the last yield as output, or `null` if there were no yields. | Completes with `null`; yielded progress is not the task output. |
+
+For default execution, an explicit `return null` also falls back to the last yield. Prefer an
+explicit object return when progress snapshots and the final result have different shapes.
+Progress snapshots are last-write-wins by tool call id and do not enter model history as
+intermediate tool results. A snapshot used as the final output does enter history as the tool result.
+
+This background workflow reports progress, sends the parent one message, and then suspends:
+
+```ts title="agent/tools/remind_with_progress.ts"
+import { defineWorkflowTool } from "eve/tools";
+import { sleep } from "workflow";
+import { z } from "zod";
+
+export default defineWorkflowTool({
+ description: "Schedule a reminder and report progress before waiting.",
+ inputSchema: z.object({ note: z.string(), delay: z.string() }),
+ execution: "background",
+ async *execute({ note, delay }, ctx, task) {
+ "use workflow";
+ yield { status: "preparing reminder" }; // Stream-only progress.
+ yield task.postMessage(`Reminder scheduled for ${delay}.`); // Parent-agent message.
+ await sleep(delay); // Durable suspension while the timer is pending.
+ return { reminder: note }; // Task completion notification.
+ },
+});
```
-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 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.
+Calling `task.postMessage` constructs a descriptor; yielding it sends the message. It does not
+wait for a reply. Use [`ctx.ask`](#ask-a-human-ctxask) when the workflow needs a human answer.
+Removing `execution: "background"` requires removing the `task` argument and message yield; the
+ordinary progress yield and `await sleep(delay)` still work, but the model waits for the final
+reminder as the tool result. See [yield and return](/docs/tools#yield-and-return) for the different
+final-output rules of ordinary `defineTool` generators.
## Cancel and clean up: `ctx.abortSignal`
@@ -205,9 +274,8 @@ first.
```ts
async execute({ service }, ctx) {
"use workflow";
-
const plan = await planDeploy(service);
- const pending = ask(ctx, { prompt: `Deploy ${service}?`, display: "confirmation", options: APPROVE_OR_CANCEL });
+ const pending = ctx.ask({ prompt: `Deploy ${service}?`, display: "confirmation", options: APPROVE_OR_CANCEL });
let answer = await Promise.race([pending, sleep("4h")]);
if (answer === undefined) {
@@ -227,17 +295,16 @@ and returning withdraws the request.
### Wait for an external system to call back
```ts title="agent/tools/render_video.ts"
-import { defineTool } from "eve/tools";
+import { defineWorkflowTool } from "eve/tools";
import { createWebhook, FatalError } from "workflow";
import { z } from "zod";
import { submitRender } from "../lib/render";
-export default defineTool({
+export default defineWorkflowTool({
description: "Render a video. Returns the URL once the render farm finishes.",
inputSchema: z.object({ projectId: z.string() }),
async execute({ projectId }) {
"use workflow";
-
const done = createWebhook();
const jobId = await submitRender(projectId, done.url);
const callback = await done;
@@ -255,19 +322,17 @@ system posts to it when it is done. Nothing runs in between.
### Ask now, act when answered
```ts title="agent/tools/refund_order.ts"
-import { defineTool } from "eve/tools";
-import { ask } from "eve/workflow";
+import { defineWorkflowTool } from "eve/tools";
import { z } from "zod";
import { issueRefund } from "../lib/refunds";
-export default defineTool({
+export default defineWorkflowTool({
description: "Request approval to refund an order, then issue the refund once approved.",
inputSchema: z.object({ orderId: z.string(), amount: z.number() }),
execution: "background",
async execute({ orderId, amount }, ctx) {
"use workflow";
-
- const decision = await ask(ctx, {
+ const decision = await ctx.ask({
prompt: `Refund $${amount} on order ${orderId}?`,
display: "confirmation",
options: [
@@ -288,11 +353,11 @@ on the channel. When it is answered, the refund runs and the agent is woken with
### Remind me later
```ts title="agent/tools/remind.ts"
-import { defineTool } from "eve/tools";
+import { defineWorkflowTool } from "eve/tools";
import { sleep } from "workflow";
import { z } from "zod";
-export default defineTool({
+export default defineWorkflowTool({
description: "Remind the user about something after a delay.",
inputSchema: z.object({ note: z.string(), delay: z.string() }),
execution: "background",
@@ -322,6 +387,7 @@ session's task index, can be cancelled with `task_cancel`, and are cancelled whe
Errors follow the SDK. A thrown error in a step retries per the step's policy; `FatalError` does
not. An error that escapes the body fails the run.
-Identity follows the tool. The workflow id derives from the tool's path, so renaming or moving the
-file creates a new workflow. Runs in flight finish on the deployment that started them; a run that
+The workflow id derives from the executor's module path and function name. Inline executors use
+the tool module and the name `execute`; imported executors use their declaring module and name.
+Renaming or moving that function creates a new workflow. Runs in flight finish on the deployment that started them; a run that
resumes on a deployment without its tool fails with an error naming the missing workflow.
diff --git a/e2e/fixtures/agent-background-tools/agent/tools/export.ts b/e2e/fixtures/agent-background-tools/agent/tools/export.ts
index 75d8a1154..ebbe9ee4b 100644
--- a/e2e/fixtures/agent-background-tools/agent/tools/export.ts
+++ b/e2e/fixtures/agent-background-tools/agent/tools/export.ts
@@ -1,8 +1,8 @@
-import { defineTool } from "eve/tools";
+import { defineWorkflowTool } from "eve/tools";
import { sleep } from "workflow";
import { z } from "zod";
-export default defineTool({
+export default defineWorkflowTool({
description: "Start a durable background export.",
execution: "background",
inputSchema: z.strictObject({ query: z.string() }),
diff --git a/e2e/fixtures/agent-workflow-tools/agent/lib/deploy.ts b/e2e/fixtures/agent-workflow-tools/agent/lib/deploy.ts
new file mode 100644
index 000000000..0e2debf3e
--- /dev/null
+++ b/e2e/fixtures/agent-workflow-tools/agent/lib/deploy.ts
@@ -0,0 +1,13 @@
+import type { WorkflowToolContext } from "eve/tools";
+import { sleep } from "workflow";
+
+import { describePlan, hashPlan } from "./plan.ts";
+
+export async function deployService({ service }: { service: string }, ctx: WorkflowToolContext) {
+ "use workflow";
+
+ const plan = describePlan(service);
+ const digest = await hashPlan(plan);
+ await sleep("50ms");
+ return { digest, plan, tool: ctx.toolName };
+}
diff --git a/e2e/fixtures/agent-workflow-tools/agent/lib/workflow-agent-probe.ts b/e2e/fixtures/agent-workflow-tools/agent/lib/workflow-agent-probe.ts
index 845494f1c..a8c5c4def 100644
--- a/e2e/fixtures/agent-workflow-tools/agent/lib/workflow-agent-probe.ts
+++ b/e2e/fixtures/agent-workflow-tools/agent/lib/workflow-agent-probe.ts
@@ -1,4 +1,4 @@
-import { agent } from "eve/workflow";
+import type { WorkflowToolContext } from "eve/tools";
import { z } from "zod";
export const workflowAgentProbeInputSchema = z.strictObject({
@@ -7,9 +7,9 @@ export const workflowAgentProbeInputSchema = z.strictObject({
export async function executeWorkflowAgentProbe(
input: z.infer<typeof workflowAgentProbeInputSchema>,
- ctx: Parameters<typeof agent>[0],
+ ctx: WorkflowToolContext,
): Promise<unknown> {
- return await agent(ctx, {
+ return await ctx.agent({
key: `local-${input.kind}`,
message: `Run the ${input.kind} probe.`,
target: input.kind === "hitl" ? "workflow-hitl" : "workflow-auth",
diff --git a/e2e/fixtures/agent-workflow-tools/agent/tools/background_agent.ts b/e2e/fixtures/agent-workflow-tools/agent/tools/background_agent.ts
index 91ffac8ac..1b51fd807 100644
--- a/e2e/fixtures/agent-workflow-tools/agent/tools/background_agent.ts
+++ b/e2e/fixtures/agent-workflow-tools/agent/tools/background_agent.ts
@@ -1,15 +1,14 @@
-import { defineTool } from "eve/tools";
-import { agent } from "eve/workflow";
+import { defineWorkflowTool } from "eve/tools";
import { z } from "zod";
-export default defineTool({
+export default defineWorkflowTool({
description: "Run one subagent from a background workflow tool.",
execution: "background",
inputSchema: z.strictObject({ service: z.string() }),
async execute({ service }, ctx) {
"use workflow";
- return await agent(ctx, {
+ return await ctx.agent({
key: "background-child",
message: `${service}:background`,
target: "workflow-marker",
diff --git a/e2e/fixtures/agent-workflow-tools/agent/tools/blocking_agent.ts b/e2e/fixtures/agent-workflow-tools/agent/tools/blocking_agent.ts
index cce17dc21..93fc89d3b 100644
--- a/e2e/fixtures/agent-workflow-tools/agent/tools/blocking_agent.ts
+++ b/e2e/fixtures/agent-workflow-tools/agent/tools/blocking_agent.ts
@@ -1,14 +1,13 @@
-import { defineTool } from "eve/tools";
-import { agent } from "eve/workflow";
+import { defineWorkflowTool } from "eve/tools";
import { z } from "zod";
-export default defineTool({
+export default defineWorkflowTool({
description: "Run one subagent from a waiting workflow tool.",
inputSchema: z.strictObject({ service: z.string() }),
async execute({ service }, ctx) {
"use workflow";
- return await agent(ctx, {
+ return await ctx.agent({
key: "blocking-child",
message: `${service}:blocking`,
target: "workflow-marker",
diff --git a/e2e/fixtures/agent-workflow-tools/agent/tools/blocking_agent_probe.ts b/e2e/fixtures/agent-workflow-tools/agent/tools/blocking_agent_probe.ts
index 312e691b4..541046c9a 100644
--- a/e2e/fixtures/agent-workflow-tools/agent/tools/blocking_agent_probe.ts
+++ b/e2e/fixtures/agent-workflow-tools/agent/tools/blocking_agent_probe.ts
@@ -1,15 +1,16 @@
-import { defineTool } from "eve/tools";
+import { defineWorkflowTool } from "eve/tools";
import {
executeWorkflowAgentProbe,
workflowAgentProbeInputSchema,
} from "../lib/workflow-agent-probe.ts";
-export default defineTool({
+export default defineWorkflowTool({
description: "Run a blocking local or remote subagent HITL/authorization probe.",
inputSchema: workflowAgentProbeInputSchema,
async execute(input, ctx) {
"use workflow";
+
return await executeWorkflowAgentProbe(input, ctx);
},
});
diff --git a/e2e/fixtures/agent-workflow-tools/agent/tools/confirm_deploy.ts b/e2e/fixtures/agent-workflow-tools/agent/tools/confirm_deploy.ts
index 46398d917..ec98d5c31 100644
--- a/e2e/fixtures/agent-workflow-tools/agent/tools/confirm_deploy.ts
+++ b/e2e/fixtures/agent-workflow-tools/agent/tools/confirm_deploy.ts
@@ -1,5 +1,4 @@
-import { defineTool } from "eve/tools";
-import { ask } from "eve/workflow";
+import { defineWorkflowTool } from "eve/tools";
import { z } from "zod";
import { describePlan } from "../lib/plan.ts";
@@ -8,13 +7,13 @@ import { describePlan } from "../lib/plan.ts";
* Waiting workflow tool that asks the human mid-body. The request belongs to
* the run, and the answer resumes the hook `ask` returns.
*/
-export default defineTool({
+export default defineWorkflowTool({
description: "Deploy a service after a human approves the plan.",
inputSchema: z.strictObject({ service: z.string() }),
async execute({ service }, ctx) {
"use workflow";
- const answer = await ask(ctx, {
+ const answer = await ctx.ask({
display: "confirmation",
options: [
{ id: "approve", label: "Deploy", style: "primary" },
diff --git a/e2e/fixtures/agent-workflow-tools/agent/tools/deploy_service.ts b/e2e/fixtures/agent-workflow-tools/agent/tools/deploy_service.ts
index 149c1fd4e..45bd40f65 100644
--- a/e2e/fixtures/agent-workflow-tools/agent/tools/deploy_service.ts
+++ b/e2e/fixtures/agent-workflow-tools/agent/tools/deploy_service.ts
@@ -1,22 +1,14 @@
-import { defineTool } from "eve/tools";
-import { sleep } from "workflow";
+import { defineWorkflowTool } from "eve/tools";
import { z } from "zod";
-import { describePlan, hashPlan } from "../lib/plan.ts";
+import { deployService } from "../lib/deploy.ts";
/**
* Waiting workflow tool: the turn parks while the run hashes the plan and
* sleeps, then resumes with the return value as the tool result.
*/
-export default defineTool({
+export default defineWorkflowTool({
description: "Deploy a service after planning it durably.",
inputSchema: z.strictObject({ service: z.string() }),
- async execute({ service }, ctx) {
- "use workflow";
-
- const plan = describePlan(service);
- const digest = await hashPlan(plan);
- await sleep("50ms");
- return { digest, plan, tool: ctx.toolName };
- },
+ execute: deployService,
});
diff --git a/e2e/fixtures/agent-workflow-tools/agent/tools/escalate_deploy.ts b/e2e/fixtures/agent-workflow-tools/agent/tools/escalate_deploy.ts
index ef2e303cb..11b53f0d9 100644
--- a/e2e/fixtures/agent-workflow-tools/agent/tools/escalate_deploy.ts
+++ b/e2e/fixtures/agent-workflow-tools/agent/tools/escalate_deploy.ts
@@ -1,5 +1,4 @@
-import { defineTool } from "eve/tools";
-import { ask } from "eve/workflow";
+import { defineWorkflowTool } from "eve/tools";
import { sleep } from "workflow";
import { z } from "zod";
@@ -10,13 +9,13 @@ import { describePlan } from "../lib/plan.ts";
* nobody answers before the sleep, the run withdraws the request and returns
* a timeout instead of parking forever.
*/
-export default defineTool({
+export default defineWorkflowTool({
description: "Ask for deploy approval, but give up if no one answers in time.",
inputSchema: z.strictObject({ service: z.string() }),
async execute({ service }, ctx) {
"use workflow";
- const pending = ask(ctx, {
+ const pending = ctx.ask({
display: "confirmation",
options: [
{ id: "approve", label: "Deploy", style: "primary" },
diff --git a/e2e/fixtures/agent-workflow-tools/agent/tools/fanout_agents.ts b/e2e/fixtures/agent-workflow-tools/agent/tools/fanout_agents.ts
index a42cfcd6f..ace4822ab 100644
--- a/e2e/fixtures/agent-workflow-tools/agent/tools/fanout_agents.ts
+++ b/e2e/fixtures/agent-workflow-tools/agent/tools/fanout_agents.ts
@@ -1,20 +1,19 @@
-import { defineTool } from "eve/tools";
-import { agent } from "eve/workflow";
+import { defineWorkflowTool } from "eve/tools";
import { z } from "zod";
-export default defineTool({
+export default defineWorkflowTool({
description: "Call two workflow-owned subagents in parallel and return both inline results.",
inputSchema: z.strictObject({ service: z.string() }),
async execute({ service }, ctx) {
"use workflow";
return await Promise.all([
- agent(ctx, {
+ ctx.agent({
key: "replica-0",
message: `${service}:replica-0`,
target: "workflow-marker",
}),
- agent(ctx, {
+ ctx.agent({
key: "replica-1",
message: `${service}:replica-1`,
target: "workflow-marker",
diff --git a/e2e/fixtures/agent-workflow-tools/agent/tools/fanout_deploy.ts b/e2e/fixtures/agent-workflow-tools/agent/tools/fanout_deploy.ts
index fd1ddc950..bbb0a4d1c 100644
--- a/e2e/fixtures/agent-workflow-tools/agent/tools/fanout_deploy.ts
+++ b/e2e/fixtures/agent-workflow-tools/agent/tools/fanout_deploy.ts
@@ -1,4 +1,4 @@
-import { defineTool } from "eve/tools";
+import { defineWorkflowTool } from "eve/tools";
import { createHook } from "workflow";
import { z } from "zod";
@@ -9,7 +9,7 @@ import { type ReplicaResult, startReplica } from "../lib/fanout.ts";
* their results on reply hooks. Exercises `start` and `resumeHook` from
* steps across the run boundary.
*/
-export default defineTool({
+export default defineWorkflowTool({
description: "Plan several deploy replicas in parallel and combine their digests.",
inputSchema: z.strictObject({ service: z.string() }),
async execute({ service }) {
diff --git a/e2e/fixtures/agent-workflow-tools/agent/tools/hold_deploy.ts b/e2e/fixtures/agent-workflow-tools/agent/tools/hold_deploy.ts
index b1f4ac5b4..627e1a891 100644
--- a/e2e/fixtures/agent-workflow-tools/agent/tools/hold_deploy.ts
+++ b/e2e/fixtures/agent-workflow-tools/agent/tools/hold_deploy.ts
@@ -1,4 +1,4 @@
-import { defineTool } from "eve/tools";
+import { defineWorkflowTool } from "eve/tools";
import { sleep } from "workflow";
import { z } from "zod";
@@ -6,11 +6,12 @@ import { z } from "zod";
* Parks the turn on a long durable sleep so a steer can cancel it. Exercises
* cancellation cascading into a workflow tool run.
*/
-export default defineTool({
+export default defineWorkflowTool({
description: "Hold a deploy open until cancelled.",
inputSchema: z.strictObject({ service: z.string() }),
async execute({ service }) {
"use workflow";
+
await sleep("10m");
return { held: service };
},
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 bb567fb9a..465d57fa0 100644
--- a/e2e/fixtures/agent-workflow-tools/agent/tools/report_deploy.ts
+++ b/e2e/fixtures/agent-workflow-tools/agent/tools/report_deploy.ts
@@ -1,4 +1,4 @@
-import { defineTool } from "eve/tools";
+import { defineWorkflowTool } from "eve/tools";
import { z } from "zod";
import { describePlan, hashPlan } from "../lib/plan.ts";
@@ -7,7 +7,7 @@ import { describePlan, hashPlan } from "../lib/plan.ts";
* 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({
+export default defineWorkflowTool({
description: "Plan a deploy in the background and report when it is ready.",
execution: "background",
inputSchema: z.strictObject({ service: z.string() }),
diff --git a/e2e/fixtures/agent-workflow-tools/evals/deploy-service.wait.eval.ts b/e2e/fixtures/agent-workflow-tools/evals/deploy-service.wait.eval.ts
index 13f39241e..5a3cffdf3 100644
--- a/e2e/fixtures/agent-workflow-tools/evals/deploy-service.wait.eval.ts
+++ b/e2e/fixtures/agent-workflow-tools/evals/deploy-service.wait.eval.ts
@@ -2,7 +2,7 @@ import { defineEval } from "eve/evals";
export default defineEval({
description:
- "A workflow tool parks the turn through a step and a sleep, then its return value settles the call.",
+ "An imported workflow executor parks the turn through a step and a sleep, then its return value settles the call.",
async test(t) {
const turn = await t.send("WORKFLOW-DEPLOY-START");
turn.expectOk();
diff --git a/packages/eve/extension-contracts/entrypoints/tool.ts b/packages/eve/extension-contracts/entrypoints/tool.ts
index c8f62288e..8ec5a2cdd 100644
--- a/packages/eve/extension-contracts/entrypoints/tool.ts
+++ b/packages/eve/extension-contracts/entrypoints/tool.ts
@@ -1,5 +1,6 @@
export {
defineTool,
+ defineWorkflowTool,
disableTool,
isDisabledToolSentinel,
toolOutput,
diff --git a/packages/eve/extension-contracts/reports/tool/v29.json b/packages/eve/extension-contracts/reports/tool/v29.json
new file mode 100644
index 000000000..68076ed21
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/tool/v29.json
@@ -0,0 +1,20 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "tool",
+ "epoch": 29,
+ "sha256": "8cb6a3b5b74161f439217d82f45e4c503270de9f7a0e97b3f804c689624adaf4",
+ "exports": [
+ "defaultWebSearch",
+ "defineTool",
+ "defineWorkflowTool",
+ "disableTool",
+ "experimental_workflow",
+ "isDisabledToolSentinel",
+ "isExperimentalWorkflowToolDefinition",
+ "isWebSearchToolDefinition",
+ "toolOutput",
+ "toolOutputPart",
+ "toolResultFrom",
+ "webSearch"
+ ]
+}
diff --git a/packages/eve/package.json b/packages/eve/package.json
index 8b95c054b..cf25d7da7 100644
--- a/packages/eve/package.json
+++ b/packages/eve/package.json
@@ -181,12 +181,6 @@
"import": "./dist/src/public/tools/workflow.js",
"default": "./dist/src/public/tools/workflow.js"
},
- "./workflow": {
- "eve-source": "./src/public/workflow/index.ts",
- "types": "./dist/src/public/workflow/index.d.ts",
- "import": "./dist/src/public/workflow/index.js",
- "default": "./dist/src/public/workflow/index.js"
- },
"./workflow-modules": {
"eve-source": "./src/public/workflow-modules.d.ts",
"types": "./dist/src/public/workflow-modules.d.ts"
diff --git a/packages/eve/src/compiler/extension-compatibility.ts b/packages/eve/src/compiler/extension-compatibility.ts
index 72e4e8fed..e9c0b5034 100644
--- a/packages/eve/src/compiler/extension-compatibility.ts
+++ b/packages/eve/src/compiler/extension-compatibility.ts
@@ -22,8 +22,8 @@ interface ExtensionCapabilityContract {
const EXTENSION_CAPABILITY_CONTRACTS = {
extension: { current: 1, supported: [1], dropped: {} },
tool: {
- current: 28,
- supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 28],
+ current: 29,
+ supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 28, 29],
dropped: {
14: "TaskExec.delegated was removed; migrate to workflow-backed background tools",
15: "TaskExec replaces stageEffect with send",
diff --git a/packages/eve/src/compiler/normalize-channel.ts b/packages/eve/src/compiler/normalize-channel.ts
index ce00a9277..3b05da643 100644
--- a/packages/eve/src/compiler/normalize-channel.ts
+++ b/packages/eve/src/compiler/normalize-channel.ts
@@ -3,6 +3,8 @@ import type { ChannelSourceRef } from "#discover/manifest.js";
import { normalizeChannelDefinition } from "#internal/authored-definition/channel.js";
import { type ChannelRouteMethod, isDisabledRouteSentinel } from "#public/definitions/channel.js";
import type { CompiledChannelDefinition } from "#compiler/manifest.js";
+import { readWorkflowFunctionId } from "#internal/workflow/reference.js";
+import { workflowCallbackErrorMessage } from "#shared/workflow-tool-context.js";
import {
loadModuleBackedDefinition,
type ModuleBackedDefinitionLoadOptions,
@@ -47,6 +49,14 @@ export async function compileChannelDefinition(
`Expected the channel export "${source.exportName ?? "default"}" from "${source.logicalPath}" to match the public eve shape.`,
);
+ for (const route of definition.routes) {
+ if (readWorkflowFunctionId(route.handler) !== undefined) {
+ throw new Error(
+ `${source.logicalPath} (${route.method} ${route.path}): ${workflowCallbackErrorMessage("channel")}`,
+ );
+ }
+ }
+
return {
definitions: definition.routes.map((route) => ({
kind: "channel" as const,
diff --git a/packages/eve/src/compiler/normalize-manifest.test.ts b/packages/eve/src/compiler/normalize-manifest.test.ts
index 224c1882b..4a5ef43eb 100644
--- a/packages/eve/src/compiler/normalize-manifest.test.ts
+++ b/packages/eve/src/compiler/normalize-manifest.test.ts
@@ -25,6 +25,7 @@ import { defineSkill } from "#public/definitions/skill.js";
import { resolveAgent } from "#runtime/resolve-agent.js";
import { resolveRuntimeAgentGraph } from "#runtime/resolve-agent-graph.js";
import { compiledAgentManifestSchema } from "#compiler/manifest.js";
+import { defineWorkflowTool } from "#tools/workflow-definition.js";
import { defineTool, disableTool } from "#tools/definition.js";
import { defineMemory } from "#public/memory/index.js";
import { defineDynamic } from "#dynamic/definition.js";
@@ -114,14 +115,14 @@ describe("compileAgentManifest source graph", () => {
expect(() => validateCompiledModuleMap(compiled, moduleMap)).not.toThrow();
});
- it("derives workflow handling from programmatic executor metadata", async () => {
+ it("compiles a workflow tool with programmatic executor metadata", async () => {
const execute = async () => ({ ok: true });
Reflect.set(execute, "workflowId", "workflow//example/tool//execute");
const sourceRegistry = registry([
{
logicalPath: "tools/durable.ts",
loadNamespace: async () => ({
- default: defineTool({
+ default: defineWorkflowTool({
description: "Runs durably.",
execute,
inputSchema: { type: "object" },
diff --git a/packages/eve/src/compiler/normalize-schedule.ts b/packages/eve/src/compiler/normalize-schedule.ts
index 177809ca3..6542bbedd 100644
--- a/packages/eve/src/compiler/normalize-schedule.ts
+++ b/packages/eve/src/compiler/normalize-schedule.ts
@@ -3,6 +3,8 @@ import type { ScheduleSourceRef } from "#discover/manifest.js";
import { normalizeScheduleDefinition } from "#internal/authored-definition/core.js";
import type { ScheduleDefinition } from "#public/definitions/schedule.js";
import type { CompiledScheduleDefinition } from "#compiler/manifest.js";
+import { readWorkflowFunctionId } from "#internal/workflow/reference.js";
+import { workflowCallbackErrorMessage } from "#shared/workflow-tool-context.js";
import {
loadModuleBackedDefinition,
requireModuleBackedDefinitionLoadOptions,
@@ -40,6 +42,10 @@ export async function compileScheduleDefinition(
`Expected the schedule export "${source.exportName ?? "default"}" from "${source.logicalPath}" to match the public eve shape.`,
);
+ if (readWorkflowFunctionId(definition.run) !== undefined) {
+ throw new Error(`${source.logicalPath}: ${workflowCallbackErrorMessage("schedule")}`);
+ }
+
const compiled = {
cron: definition.cron,
hasRun: definition.run !== undefined,
diff --git a/packages/eve/src/context/dynamic-tool-lifecycle.test.ts b/packages/eve/src/context/dynamic-tool-lifecycle.test.ts
index 6ba1d02f8..cb10cb2d9 100644
--- a/packages/eve/src/context/dynamic-tool-lifecycle.test.ts
+++ b/packages/eve/src/context/dynamic-tool-lifecycle.test.ts
@@ -1,3 +1,4 @@
+import { defineWorkflowTool } from "#tools/workflow-definition.js";
import { asSchema } from "ai";
import { describe, expect, it, vi } from "vitest";
@@ -1235,6 +1236,30 @@ describe("dispatchDynamicToolEvent", () => {
expect(buildDynamicTools(ctx)).toHaveLength(0);
});
+ it.each(["single", "map"])(
+ "does not advertise a workflow tool returned as a %s",
+ async (shape) => {
+ const ctx = createCtx();
+ const tool = defineWorkflowTool({
+ description: "Invalid dynamic workflow",
+ inputSchema: {},
+ async execute() {
+ return 1;
+ },
+ });
+ const resolver = createResolver("workflow", ["session.started"], () =>
+ shape === "single" ? tool : { workflow: tool },
+ );
+ await dispatchDynamicToolEvent({
+ ctx,
+ resolvers: [resolver],
+ messages: [],
+ event: makeEvent("session.started"),
+ });
+ expect(buildDynamicTools(ctx)).toHaveLength(0);
+ },
+ );
+
it("resolver throwing is logged and skipped — other resolvers still work", async () => {
const ctx = createCtx();
const badResolver = createResolver("bad", ["session.started"], () => {
diff --git a/packages/eve/src/context/dynamic-tool-lifecycle.ts b/packages/eve/src/context/dynamic-tool-lifecycle.ts
index 0a80a9a0b..d400ec295 100644
--- a/packages/eve/src/context/dynamic-tool-lifecycle.ts
+++ b/packages/eve/src/context/dynamic-tool-lifecycle.ts
@@ -1,5 +1,7 @@
import type { ModelMessage } from "ai";
+import { isWorkflowToolDefinition } from "#tools/workflow-definition.js";
+
import { replayDynamicTools } from "#context/build-dynamic-tools.js";
import { contextStorage, type AlsContext } from "#context/container.js";
import type { ContextKey } from "#context/key.js";
@@ -89,6 +91,14 @@ function readDynamicToolResult(
resolver: ResolvedDynamicToolResolver,
value: unknown,
): { readonly entries: Record<string, DynamicToolEntry>; readonly isSingle: boolean } {
+ const assertOrdinaryTool = (entry: unknown): void => {
+ if (isWorkflowToolDefinition(entry)) {
+ throw new Error(
+ `Dynamic tool resolver "${resolver.logicalPath}" cannot return defineWorkflowTool(). Workflow tools must be static tools; use defineTool() for dynamic entries.`,
+ );
+ }
+ };
+ assertOrdinaryTool(value);
if (isBrandedToolEntry(value)) {
return { entries: { _single: value as DynamicToolEntry }, isSingle: true };
}
@@ -100,6 +110,7 @@ function readDynamicToolResult(
const entries: Record<string, DynamicToolEntry> = {};
for (const [name, entry] of Object.entries(value)) {
+ assertOrdinaryTool(entry);
if (!isBrandedToolEntry(entry)) {
throw new Error(
`Dynamic tool resolver "${resolver.logicalPath}" returned "${name}" without defineTool(). Wrap every dynamic tool entry in defineTool().`,
diff --git a/packages/eve/src/execution/tools/subagent/invoke-agent.test.ts b/packages/eve/src/execution/tools/subagent/invoke-agent.test.ts
index 5487fe46c..6d2d94e94 100644
--- a/packages/eve/src/execution/tools/subagent/invoke-agent.test.ts
+++ b/packages/eve/src/execution/tools/subagent/invoke-agent.test.ts
@@ -1,6 +1,6 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
-import { attachWorkflowToolRunContext } from "#execution/tools/workflow/ask.js";
+import { ask, attachWorkflowToolRunContext } from "#execution/tools/workflow/ask.js";
import type { WorkflowToolRunRef } from "#execution/tools/workflow/messages.js";
import { agent, type AgentInvocationReply } from "#execution/tools/subagent/invoke-agent.js";
import type { ToolContext } from "#tools/definition.js";
@@ -25,6 +25,26 @@ vi.mock("#execution/tools/workflow/resume-hook-step.js", () => ({
}));
beforeEach(() => vi.resetAllMocks());
+describe("workflow helper context errors", () => {
+ it.each([
+ ["ordinary tool", { callId: "call-1", session: {} }],
+ ["channel handler", { from() {}, to() {}, waitUntil() {} }],
+ ["schedule handler", { to() {}, waitUntil() {}, appAuth: {} }],
+ ["missing context", undefined],
+ ["null context", null],
+ ])("rejects %s before creating hooks or dispatching work", async (_name, context) => {
+ const ctx = context as ToolContext;
+ await expect(
+ agent(ctx, { key: "review", target: "reviewer", message: "Review" }),
+ ).rejects.toThrow("ctx.agent() requires a defineWorkflowTool() executor context.");
+ expect(() => ask(ctx, { prompt: "Continue?" })).toThrow(
+ "ctx.ask() requires a defineWorkflowTool() executor context.",
+ );
+ expect(mocks.createHook).not.toHaveBeenCalled();
+ expect(mocks.resumeHook).not.toHaveBeenCalled();
+ });
+});
+
describe("background agent invocation routing", () => {
it("stops waiting when the workflow body is cancelled", async () => {
const controller = new AbortController();
diff --git a/packages/eve/src/execution/tools/subagent/invoke-agent.ts b/packages/eve/src/execution/tools/subagent/invoke-agent.ts
index 3abdceac1..1800dd717 100644
--- a/packages/eve/src/execution/tools/subagent/invoke-agent.ts
+++ b/packages/eve/src/execution/tools/subagent/invoke-agent.ts
@@ -15,6 +15,7 @@ import type { RuntimeSubagentChildResult, RuntimeSubagentResult } from "#shared/
import type { JsonValue } from "#shared/json.js";
import type { JsonObject } from "#shared/json.js";
import { claimHookOwnership, disposeHook } from "#execution/hook-ownership.js";
+import type { AgentInput } from "#tools/workflow-definition.js";
import type { ToolContext } from "#tools/definition.js";
import type { TaskInboundUpdate } from "#tasks/types.js";
@@ -25,14 +26,6 @@ export type InternalAgentInput = {
readonly target: string;
};
-export interface AgentInput {
- readonly agentId?: string;
- readonly key: string;
- readonly message: string;
- readonly outputSchema?: JsonObject;
- readonly target: string;
-}
-
/**
* Asks the owning session to spawn an agent for a workflow tool run. Spawning
* needs owner-held material (auth, capabilities, admission, the agent handle
@@ -67,6 +60,7 @@ const AGENT_INVOCATION_IDS = Symbol.for("eve.workflow-tool-run.agent-invocation-
/** Invokes an agent from a task-owned background workflow tool. */
export async function agent(ctx: ToolContext, input: AgentInput): Promise<JsonValue> {
validateAgentInput(input, true);
+ readWorkflowToolRunRef(ctx);
return await invokeAgent(
ctx,
{
diff --git a/packages/eve/src/execution/tools/workflow/ask.ts b/packages/eve/src/execution/tools/workflow/ask.ts
index e7f3adbcd..40bb2e777 100644
--- a/packages/eve/src/execution/tools/workflow/ask.ts
+++ b/packages/eve/src/execution/tools/workflow/ask.ts
@@ -7,9 +7,9 @@ import type {
import { resumeHookStep } from "#execution/tools/workflow/resume-hook-step.js";
import { workflowToolRunAnswerToken } from "#harness/workflow-tool-runs.js";
import type { ToolContext, ToolInputRequest, ToolInputResponse } from "#tools/definition.js";
+import { workflowToolContextErrorMessage } from "#shared/workflow-tool-context.js";
-// `Symbol.for`, not a module-local WeakMap: `ask()` ships via the `eve/workflow`
-// entry while `attachWorkflowToolRunContext` runs from `body.ts`, and those may
+// `Symbol.for`, not a module-local WeakMap: workflow helpers and body setup may
// be different bundled copies of this module.
const WORKFLOW_TOOL_RUN_CONTEXT = Symbol.for("eve.workflow-tool-run.context");
@@ -37,33 +37,34 @@ export function attachWorkflowToolRunContext(
});
}
-function readWorkflowToolRunContext(ctx: ToolContext): WorkflowToolRunContext {
- const context = (ctx as WorkflowToolRunContextCarrier)[WORKFLOW_TOOL_RUN_CONTEXT];
+function readWorkflowToolRunContext(
+ ctx: ToolContext,
+ helper: "agent" | "ask",
+): WorkflowToolRunContext {
+ const context = (ctx as WorkflowToolRunContextCarrier | undefined)?.[WORKFLOW_TOOL_RUN_CONTEXT];
if (context === undefined) {
- throw new Error(
- 'This function must be called with the context of a workflow tool body ("use workflow").',
- );
+ throw new Error(workflowToolContextErrorMessage(helper));
}
return context;
}
export function readWorkflowToolRunRef(ctx: ToolContext): WorkflowToolRunRef {
- return readWorkflowToolRunContext(ctx).from;
+ return readWorkflowToolRunContext(ctx, "agent").from;
}
export function readWorkflowToolRunOwner(ctx: ToolContext): WorkflowToolRunOwner {
- return readWorkflowToolRunContext(ctx).owner;
+ return readWorkflowToolRunContext(ctx, "agent").owner;
}
export function readWorkflowToolRunAdmission(
ctx: ToolContext,
): WorkflowToolRunContext["admission"] {
- return readWorkflowToolRunContext(ctx).admission;
+ return readWorkflowToolRunContext(ctx, "agent").admission;
}
/** Returns an answer hook which may be awaited or raced with another workflow operation. */
export function ask(ctx: ToolContext, request: ToolInputRequest): Hook<ToolInputResponse> {
- const context = readWorkflowToolRunContext(ctx);
+ const context = readWorkflowToolRunContext(ctx, "ask");
const answer = createHook<ToolInputResponse>({
token: workflowToolRunAnswerToken(context.from.runId, context.answerSeq++),
});
diff --git a/packages/eve/src/execution/tools/workflow/body.test.ts b/packages/eve/src/execution/tools/workflow/body.test.ts
new file mode 100644
index 000000000..c00cc704e
--- /dev/null
+++ b/packages/eve/src/execution/tools/workflow/body.test.ts
@@ -0,0 +1,45 @@
+import { expect, it, vi } from "vitest";
+import type { ToolContext } from "#tools/definition.js";
+import type { WorkflowToolContext } from "#tools/workflow-definition.js";
+import { executeWorkflowBody, type WorkflowBodyInput } from "#execution/tools/workflow/body.js";
+import { readWorkflowToolRunRef } from "#execution/tools/workflow/ask.js";
+
+const mocks = vi.hoisted(() => ({ execute: vi.fn(), agent: vi.fn(), ask: vi.fn() }));
+vi.mock("#execution/workflow-registry.js", () => ({ readRegisteredWorkflow: () => mocks.execute }));
+vi.mock("#execution/tools/subagent/invoke-agent.js", () => ({ agent: mocks.agent }));
+vi.mock("#execution/tools/workflow/ask.js", async (importOriginal) => ({
+ ...(await importOriginal()),
+ ask: mocks.ask,
+}));
+
+it("binds workflow-only methods to the run context", async () => {
+ const signal = new AbortController().signal;
+ const input = {
+ callId: "call",
+ input: {},
+ session: { id: "session", turn: { id: "turn", sequence: 1 } },
+ stepIndex: 0,
+ toolName: "deploy",
+ workflowId: "workflow//test//execute",
+ owner: { report: "report" },
+ execution: "blocking",
+ runId: "run",
+ } as WorkflowBodyInput & { execution: "blocking"; runId: string };
+ const question = { prompt: "Continue?" };
+ const invocation = { key: "review", target: "reviewer", message: "Review" };
+ mocks.ask.mockResolvedValue({ optionId: "yes" });
+ mocks.agent.mockResolvedValue("reviewed");
+ mocks.execute.mockImplementation(async (_input, ctx: WorkflowToolContext & ToolContext) => {
+ expect(readWorkflowToolRunRef(ctx).runId).toBe("run");
+ expect(ctx.abortSignal).toBe(signal);
+ const answer = await ctx.ask(question);
+ const result = await ctx.agent(invocation);
+ expect(mocks.ask).toHaveBeenCalledWith(ctx, question);
+ expect(mocks.agent).toHaveBeenCalledWith(ctx, invocation);
+ return { answer, result };
+ });
+ await expect(executeWorkflowBody(input, signal)).resolves.toEqual({
+ outcome: { status: "completed", output: { answer: { optionId: "yes" }, result: "reviewed" } },
+ reportCount: 0,
+ });
+});
diff --git a/packages/eve/src/execution/tools/workflow/body.ts b/packages/eve/src/execution/tools/workflow/body.ts
index d5290c30f..8cdf666fd 100644
--- a/packages/eve/src/execution/tools/workflow/body.ts
+++ b/packages/eve/src/execution/tools/workflow/body.ts
@@ -1,7 +1,9 @@
import { getWorkflowMetadata } from "#compiled/@workflow/core/index.js";
import type { SessionContext } from "#context/session-context.js";
-import { attachWorkflowToolRunContext } from "#execution/tools/workflow/ask.js";
+import { agent } from "#execution/tools/subagent/invoke-agent.js";
+import type { WorkflowToolContext } from "#tools/workflow-definition.js";
+import { ask, attachWorkflowToolRunContext } from "#execution/tools/workflow/ask.js";
import {
type WorkflowToolRunOutcome,
type WorkflowToolRunOwner,
@@ -38,7 +40,7 @@ export interface WorkflowBodyResult {
type WorkflowToolExecute = (
input: unknown,
- ctx: ToolContext,
+ ctx: WorkflowToolContext,
task?: TaskExec,
) => Promise<JsonValue> | AsyncIterable<JsonValue>;
@@ -123,13 +125,18 @@ function resolveWorkflowToolExecute(input: WorkflowBodyInput): WorkflowToolExecu
return execute as WorkflowToolExecute;
}
-function createWorkflowBodyContext(input: WorkflowBodyInput, signal: AbortSignal): ToolContext {
+function createWorkflowBodyContext(
+ input: WorkflowBodyInput,
+ signal: AbortSignal,
+): ToolContext & WorkflowToolContext {
const unavailable = (member: string, hint: string): never => {
throw new Error(
`ctx.${member} is not available inside a workflow tool; ${hint}. Tool "${input.toolName}" runs as a durable workflow body, which only replays deterministic code.`,
);
};
- return {
+ const ctx: ToolContext & WorkflowToolContext = {
+ agent: (input) => agent(ctx, input),
+ ask: (request) => ask(ctx, request),
abortSignal: signal,
callId: input.callId,
getSandbox: () => unavailable("getSandbox()", "the session sandbox belongs to the turn"),
@@ -140,6 +147,7 @@ function createWorkflowBodyContext(input: WorkflowBodyInput, signal: AbortSignal
session: input.session,
toolName: input.toolName,
};
+ return ctx;
}
function createWorkflowTaskExec(input: WorkflowBodyInput): TaskExec {
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 599f2bc87..757575970 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
@@ -1,6 +1,5 @@
import { describe, expect, it } from "vitest";
-import { ROOT_COMPILED_AGENT_NODE_ID } from "#compiler/manifest.js";
import { sessionCommandHookToken } from "#execution/session-command-token.js";
import { executeSleepTool, SLEEP_INPUT_SCHEMA } from "#execution/tools/sleep.js";
import { resumeSessionInbox } from "#execution/wire/session-inbox-resume.js";
@@ -23,7 +22,11 @@ import { workflowToolRunWorkflowReference } from "#execution/workflow-runtime.js
import { createBundledRuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";
import type { InputRequestedStreamEvent } from "#protocol/message.js";
import type { ResolvedToolDefinition } from "#runtime/types.js";
-import { toInputSchema } from "#tools/schema.js";
+import {
+ defineWorkflowTool,
+ type BlockingWorkflowToolDefinition,
+} from "#tools/workflow-definition.js";
+import { serializeInputSchema, toInputSchema } from "#tools/schema.js";
const DEPLOY_INPUT_SCHEMA = toInputSchema({
additionalProperties: false,
@@ -58,32 +61,21 @@ async function createWorkflowToolRuntime(input: {
readonly inputSchema?: ResolvedToolDefinition["inputSchema"];
readonly toolName: string;
}): Promise<TestRuntime> {
- const tool: ResolvedToolDefinition = {
- description: `Deploys a service (${input.toolName}).`,
- execute: input.execute as ResolvedToolDefinition["execute"],
- inputSchema: input.inputSchema ?? DEPLOY_INPUT_SCHEMA,
- logicalPath: `tools/${input.toolName}.ts`,
- name: input.toolName,
- owner: { kind: "application" },
- sourceId: `tools/${input.toolName}.ts`,
- sourceKind: "module",
- };
- const runtime = await createTestRuntime({ agent: { name: input.agentName }, tools: [tool] });
- const manifestTool = runtime.manifest.tools.find((entry) => entry.name === input.toolName);
- if (manifestTool === undefined) {
- throw new Error(`Expected ${input.toolName} to be present in the test manifest.`);
- }
- runtime.moduleMap.nodes[ROOT_COMPILED_AGENT_NODE_ID]!.modules[manifestTool.sourceId] = {
- default: { description: tool.description, execute: input.execute },
- };
- // The compiler derives the workflow id from authored source; an in-memory tool
- // has none, so record the id the test tier's transform stamped on the fixture.
- const workflowId = Reflect.get(input.execute, "workflowId");
- expect(workflowId).toEqual(expect.any(String));
- Object.assign(manifestTool, {
- behavior: { availability: [], handling: { kind: "workflow-tool", workflowId } },
+ return await createTestRuntime({
+ agent: { name: input.agentName },
+ modules: [
+ {
+ logicalPath: `tools/${input.toolName}.ts`,
+ loadNamespace: async () => ({
+ default: defineWorkflowTool({
+ description: `Deploys a service (${input.toolName}).`,
+ execute: input.execute as BlockingWorkflowToolDefinition["execute"],
+ inputSchema: serializeInputSchema(input.inputSchema ?? DEPLOY_INPUT_SCHEMA) ?? {},
+ }),
+ }),
+ },
+ ],
});
- return runtime;
}
/** Ids of every workflow tool run in the shared world, so a test can spot the one it started. */
diff --git a/packages/eve/src/internal/authored-definition/schema-backed.ts b/packages/eve/src/internal/authored-definition/schema-backed.ts
index 2197da6f8..c18425219 100644
--- a/packages/eve/src/internal/authored-definition/schema-backed.ts
+++ b/packages/eve/src/internal/authored-definition/schema-backed.ts
@@ -1,3 +1,5 @@
+import { isWorkflowToolDefinition } from "#tools/workflow-definition.js";
+import { readWorkflowFunctionId } from "#internal/workflow/reference.js";
import { isDisabledToolSentinel } from "#tools/definition.js";
import { isExperimentalWorkflowToolDefinition } from "#tools/workflow.js";
import { isWebSearchToolDefinition } from "#tools/provided/web-search.js";
@@ -101,6 +103,18 @@ export function normalizeToolDefinition(value: unknown, message: string): Normal
}
const record = expectObjectRecord(value, message);
+ const workflowId = readWorkflowFunctionId(record.execute);
+ if (isWorkflowToolDefinition(value)) {
+ if (workflowId === undefined) {
+ throw new Error(
+ `${message} defineWorkflowTool() requires a compiled workflow executor. Start execute with "use workflow" and export defineWorkflowTool() as the default export of a static tool module.`,
+ );
+ }
+ } else if (workflowId !== undefined) {
+ throw new Error(
+ `${message} Workflow executors require defineWorkflowTool() from "eve/tools". Replace defineTool() or the bare tool object with defineWorkflowTool().`,
+ );
+ }
expectOnlyKnownKeys(
record,
[
diff --git a/packages/eve/src/internal/authored-module-loader.scenario.test.ts b/packages/eve/src/internal/authored-module-loader.scenario.test.ts
index 53f7b93c5..e9985e54e 100644
--- a/packages/eve/src/internal/authored-module-loader.scenario.test.ts
+++ b/packages/eve/src/internal/authored-module-loader.scenario.test.ts
@@ -16,6 +16,211 @@ import { useScenarioApp } from "#internal/testing/scenario-app.js";
describe("loadAuthoredModuleNamespace", () => {
const scenarioApp = useScenarioApp();
+ it.each(["agent", "ask"])(
+ "rejects the removed eve/workflow %s import at build time",
+ async (helper) => {
+ const app = await scenarioApp({
+ files: {
+ "agent/agent.ts": 'export default { model: "openai/gpt-5.4" };',
+ "agent/tools/probe.ts": `import { defineTool } from "eve/tools";
+import { ${helper} } from "eve/workflow";
+export default defineTool({ description: "Probe", inputSchema: { type: "object" }, async execute(input, ctx) { return ${helper}(ctx, input); } });`,
+ },
+ installDependencies: true,
+ name: "removed-workflow-helper",
+ });
+ const discovered = await discoverAgent({
+ agentRoot: join(app.appRoot, "agent"),
+ appRoot: app.appRoot,
+ });
+ await expect(compileAgentManifest(discovered.manifest)).rejects.toThrow(/eve\/workflow/);
+ },
+ );
+
+ it.each(["defineTool", "bare object"])(
+ "rejects %s workflow executors during compilation",
+ async (kind) => {
+ const definition = `{ description: "Legacy workflow", inputSchema: {}, async execute() {
+ "use workflow";
+ return 1;
+} }`;
+ const app = await scenarioApp({
+ files: {
+ "agent/agent.ts": 'export default { model: "openai/gpt-5.4" };',
+ "agent/tools/probe.ts": `import { defineTool } from "eve/tools";\nexport default ${kind === "defineTool" ? `defineTool(${definition})` : definition};`,
+ },
+ installDependencies: true,
+ name: "legacy-workflow-tool",
+ });
+ const discovered = await discoverAgent({
+ agentRoot: join(app.appRoot, "agent"),
+ appRoot: app.appRoot,
+ });
+ await expect(compileAgentManifest(discovered.manifest)).rejects.toThrow(
+ "Workflow executors require defineWorkflowTool()",
+ );
+ },
+ );
+
+ it("rejects a named workflow channel handler during compilation", async () => {
+ const app = await scenarioApp({
+ files: {
+ "agent/agent.ts": 'export default { model: "openai/gpt-5.4" };\n',
+ "agent/channels/probe.ts": `import { defineChannel, POST } from "eve/channels";
+export default defineChannel({ routes: [POST("/probe", handler)] });
+async function handler() {
+ "use workflow";
+ return new Response("Done");
+}`,
+ },
+ installDependencies: true,
+ name: "invalid-workflow-channel",
+ });
+ const discovered = await discoverAgent({
+ agentRoot: join(app.appRoot, "agent"),
+ appRoot: app.appRoot,
+ });
+ await expect(compileAgentManifest(discovered.manifest)).rejects.toThrow(
+ '"use workflow" is not supported on channel callbacks',
+ );
+ });
+
+ it.each([
+ ["missing", "async execute() { return 1; }", "", "requires a compiled workflow executor"],
+ ["generator", "async *execute() { yield 1; }", "", "requires a compiled workflow executor"],
+ ["expression body", "execute: async () => 1", "", "requires a compiled workflow executor"],
+ ["synchronous", "execute() { return 1; }", "", "requires a compiled workflow executor"],
+ [
+ "misplaced",
+ 'async execute() { void 0; "use workflow"; return 1; }',
+ "",
+ "requires a compiled workflow executor",
+ ],
+ [
+ "local reference",
+ "execute: run",
+ "async function run() { return 1; }",
+ "requires a compiled workflow executor",
+ ],
+ [
+ "unrelated workflow",
+ "async execute() { return 1; }",
+ 'async function other() { "use workflow"; return 1; }',
+ "requires a compiled workflow executor",
+ ],
+ [
+ "nested only",
+ 'async execute() { async function inner() { "use workflow"; return 1; } return inner(); }',
+ "",
+ 'marks the nested function "inner"',
+ ],
+ ])(
+ "rejects a workflow tool with a %s executor directive during compilation",
+ async (_kind, execute, helper, error) => {
+ const app = await scenarioApp({
+ files: {
+ "agent/agent.ts": 'export default { model: "openai/gpt-5.4" };',
+ "agent/tools/probe.ts": `import { defineWorkflowTool } from "eve/tools";
+export default defineWorkflowTool({ description: "Probe", inputSchema: {}, ${execute} });
+${helper}`,
+ },
+ installDependencies: true,
+ name: "missing-workflow-directive",
+ });
+ const discovered = await discoverAgent({
+ agentRoot: join(app.appRoot, "agent"),
+ appRoot: app.appRoot,
+ });
+ await expect(compileAgentManifest(discovered.manifest)).rejects.toThrow(error);
+ },
+ );
+
+ it.each([
+ ['import { defineWorkflowTool as durable } from "eve/tools";', "durable"],
+ ['import * as tools from "eve/tools";', "tools.defineWorkflowTool"],
+ ])("validates a workflow tool through its compiled definition: %s", async (binding, definer) => {
+ const app = await scenarioApp({
+ files: {
+ "agent/agent.ts": 'export default { model: "openai/gpt-5.4" };',
+ "agent/tools/probe.ts": `${binding}
+import { run } from "../lib/run";
+export default ${definer}({ description: "Probe", inputSchema: {}, execute: run });`,
+ "agent/lib/run.ts": 'export async function run() { "use workflow"; return 1; }',
+ },
+ installDependencies: true,
+ name: "compiled-workflow-reference",
+ });
+ const discovered = await discoverAgent({
+ agentRoot: join(app.appRoot, "agent"),
+ appRoot: app.appRoot,
+ });
+ const compiled = await compileAgentManifest(discovered.manifest);
+ expect(compiled.tools.find((tool) => tool.name === "probe")?.behavior?.handling).toEqual({
+ kind: "workflow-tool",
+ workflowId: "workflow//./agent/lib/run//run",
+ });
+ });
+
+ it("compiles a workflow tool that calls agent through an imported helper", async () => {
+ const app = await scenarioApp({
+ files: {
+ "agent/agent.ts": 'export default { model: "openai/gpt-5.4" };\n',
+ "agent/tools/probe.ts": `import { defineWorkflowTool } from "eve/tools";
+import { delegate } from "../lib/delegate";
+export default defineWorkflowTool({ description: "Probe", inputSchema: { type: "object" }, async execute(input, ctx) {
+ "use workflow";
+ return delegate(ctx, input);
+} });`,
+ "agent/lib/delegate.ts": `export async function delegate(ctx, input) { return ctx.agent(input); }`,
+ },
+ installDependencies: true,
+ name: "valid-workflow-helper",
+ });
+ const discovered = await discoverAgent({
+ agentRoot: join(app.appRoot, "agent"),
+ appRoot: app.appRoot,
+ });
+ await expect(compileAgentManifest(discovered.manifest)).resolves.toBeDefined();
+ });
+
+ it.each([
+ [
+ "channels/probe.ts",
+ "channel",
+ 'import { defineChannel, POST } from "eve/channels";',
+ 'defineChannel({ routes: [POST("/probe", handler)] })',
+ ],
+ [
+ "schedules/probe.ts",
+ "schedule",
+ 'import { defineSchedule } from "eve/schedules";',
+ 'defineSchedule({ cron: "* * * * *", run: handler })',
+ ],
+ ])(
+ "rejects an imported workflow handler while compiling %s",
+ async (path, kind, binding, definition) => {
+ const app = await scenarioApp({
+ files: {
+ "agent/agent.ts": 'export default { model: "openai/gpt-5.4" };\n',
+ [`agent/${path}`]: `${binding}\nimport { handler } from "../lib/handler";\nexport default ${definition};\n`,
+ "agent/lib/handler.ts": `export async function handler() {
+ "use workflow";
+ return undefined;
+}`,
+ },
+ installDependencies: true,
+ name: "imported-workflow-handler",
+ });
+ const discovered = await discoverAgent({
+ agentRoot: join(app.appRoot, "agent"),
+ appRoot: app.appRoot,
+ });
+ await expect(compileAgentManifest(discovered.manifest)).rejects.toThrow(
+ `"use workflow" is not supported on ${kind} callbacks`,
+ );
+ },
+ );
+
it("stamps dynamic callbacks while building the generation module map", async () => {
const app = await scenarioApp({
files: {
diff --git a/packages/eve/src/internal/nitro/dev-generation-artifacts.scenario.test.ts b/packages/eve/src/internal/nitro/dev-generation-artifacts.scenario.test.ts
index 390f08d9b..ad14eb905 100644
--- a/packages/eve/src/internal/nitro/dev-generation-artifacts.scenario.test.ts
+++ b/packages/eve/src/internal/nitro/dev-generation-artifacts.scenario.test.ts
@@ -556,16 +556,17 @@ describe("development generation artifacts", () => {
"agent/instructions.md": "Use the available tools.",
"agent/lib/plan.mjs": 'export const PLAN_PREFIX = "plan:";\n',
"agent/tools/deploy.mjs": [
+ 'import { defineWorkflowTool } from "eve/tools";',
'import { PLAN_PREFIX } from "../lib/plan.mjs";',
"",
- "export default {",
+ "export default defineWorkflowTool({",
' description: "Deploy a service.",',
' inputSchema: { type: "object", properties: { service: { type: "string" } } },',
" async execute({ service }) {",
' "use workflow";',
" return { plan: await planDeploy(service) };",
" },",
- "};",
+ "});",
"",
"async function planDeploy(service) {",
' "use step";',
@@ -578,6 +579,7 @@ describe("development generation artifacts", () => {
"",
].join("\n"),
},
+ installDependencies: true,
name: "authored-workflow-tools-generation",
});
diff --git a/packages/eve/src/internal/testing/workflow-tool-fixtures.ts b/packages/eve/src/internal/testing/workflow-tool-fixtures.ts
index 2955f705d..82e39a863 100644
--- a/packages/eve/src/internal/testing/workflow-tool-fixtures.ts
+++ b/packages/eve/src/internal/testing/workflow-tool-fixtures.ts
@@ -8,8 +8,7 @@
import { createHook, sleep as workflowSleep } from "#compiled/@workflow/core/index.js";
-import { ask } from "#execution/tools/workflow/ask.js";
-import type { ToolContext } from "#tools/definition.js";
+import type { WorkflowToolContext } from "#tools/workflow-definition.js";
import type { TaskExec, TaskMessage } from "#tools/task.js";
export interface DeployInput {
@@ -18,7 +17,7 @@ export interface DeployInput {
export async function deployServiceWorkflow(
input: DeployInput,
- ctx: ToolContext,
+ ctx: WorkflowToolContext,
): Promise<{ readonly callId: string; readonly plan: string; readonly sessionId: string }> {
"use workflow";
@@ -28,12 +27,12 @@ export async function deployServiceWorkflow(
export async function confirmDeployWorkflow(
input: DeployInput,
- ctx: ToolContext,
+ ctx: WorkflowToolContext,
): Promise<{ readonly approved: boolean; readonly service: string }> {
"use workflow";
const plan = await planDeployStep(input.service);
- const answer = await ask(ctx, {
+ const answer = await ctx.ask({
display: "confirmation",
options: [
{ id: "approve", label: "Deploy", style: "primary" },
@@ -83,7 +82,7 @@ export async function* reportingDeployWorkflow(
export async function* backgroundDeployWorkflow(
input: DeployInput,
- _ctx: ToolContext,
+ _ctx: WorkflowToolContext,
task: TaskExec,
): AsyncGenerator<string | TaskMessage, { readonly plan: string }> {
"use workflow";
@@ -113,7 +112,7 @@ export async function stepThenRaceWorkflow(
/** Holds in a step until `ctx.abortSignal` fires, then cleans up in `finally`. */
export async function holdUntilAbortedWorkflow(
input: DeployInput,
- ctx: ToolContext,
+ ctx: WorkflowToolContext,
): Promise<{ readonly held: boolean }> {
"use workflow";
try {
@@ -152,10 +151,10 @@ async function releaseStep(service: string): Promise<string> {
export async function askThenRaceWorkflow(
input: DeployInput,
- ctx: ToolContext,
+ ctx: WorkflowToolContext,
): Promise<{ readonly decided: string; readonly service: string }> {
"use workflow";
- const pending = ask(ctx, {
+ const pending = ctx.ask({
display: "confirmation",
options: [
{ id: "approve", label: "Deploy", style: "primary" },
diff --git a/packages/eve/src/internal/workflow-bundle/authored-workflow-directives.test.ts b/packages/eve/src/internal/workflow-bundle/authored-workflow-directives.test.ts
index 7cda45c1c..23b724870 100644
--- a/packages/eve/src/internal/workflow-bundle/authored-workflow-directives.test.ts
+++ b/packages/eve/src/internal/workflow-bundle/authored-workflow-directives.test.ts
@@ -6,10 +6,10 @@ const FILE = "/app/agent/tools/deploy.ts";
function toolModule(execute: string): string {
return [
- 'import { defineTool } from "eve/tools";',
+ 'import { defineWorkflowTool } from "eve/tools";',
'import { z } from "zod";',
"",
- "export default defineTool({",
+ "export default defineWorkflowTool({",
' description: "Deploy",',
" inputSchema: z.object({ service: z.string() }),",
execute,
@@ -48,7 +48,6 @@ describe("prepareAuthoredWorkflowDirectives", () => {
const prepared = await prepareAuthoredWorkflowDirectives({ filePath: FILE, source });
expect(prepared.hasDirectives).toBe(true);
- expect(prepared.executeWorkflow).toBe("execute");
expect(prepared.source).toContain(" execute,\n toModelOutput: (output) => output,");
expect(prepared.source).toContain(
"async function execute({ service }: { service: string }, ctx: ToolContext): Promise<{ ok: boolean }> {\n" +
@@ -92,28 +91,36 @@ describe("prepareAuthoredWorkflowDirectives", () => {
);
});
- it("hoists the execute method of a plain object default export", async () => {
- const source = [
- "export default {",
- ' description: "d",',
- " async execute(input) {",
- ' "use workflow";',
- " return input;",
- " },",
- "};",
- "",
- ].join("\n");
-
- const prepared = await prepareAuthoredWorkflowDirectives({ filePath: FILE, source });
-
- expect(prepared.source).toContain(" execute,\n};");
- expect(prepared.source).toContain('async function execute(input) {\n "use workflow";');
+ it.each(["use workflow", "use step"])(
+ "rejects nested %s inside a marked executor",
+ async (directive) => {
+ const source = toolModule(`async execute() {
+"use workflow";
+async function inner() {
+"${directive}";
+}
+return inner();
+},`);
+ await expect(prepareAuthoredWorkflowDirectives({ filePath: FILE, source })).rejects.toThrow(
+ /marks the nested function "inner"/u,
+ );
+ },
+ );
+
+ it.each([
+ ['import { defineWorkflowTool as durable } from "eve/tools";', "durable"],
+ ['import * as tools from "eve/tools";', "tools.defineWorkflowTool"],
+ ])("recognizes imported aliases: %s", async (binding, definer) => {
+ const source = `${binding}\nexport default ${definer}({ async execute(input) {\n"use workflow";\nreturn input; } });`;
+ await expect(
+ prepareAuthoredWorkflowDirectives({ filePath: FILE, source }),
+ ).resolves.toMatchObject({ hasWorkflowDirective: true });
});
it("keeps a referenced top-level workflow function as is", async () => {
const source = [
- 'import { defineTool } from "eve/tools";',
- 'export default defineTool({ description: "d", inputSchema: {}, execute: deploy });',
+ 'import { defineWorkflowTool } from "eve/tools";',
+ 'export default defineWorkflowTool({ description: "d", inputSchema: {}, execute: deploy });',
"async function deploy(input: unknown) {",
' "use workflow";',
" return input;",
@@ -122,7 +129,6 @@ describe("prepareAuthoredWorkflowDirectives", () => {
].join("\n");
await expect(prepareAuthoredWorkflowDirectives({ filePath: FILE, source })).resolves.toEqual({
- executeWorkflow: "deploy",
hasDirectives: true,
hasWorkflowDirective: true,
source,
@@ -179,15 +185,16 @@ describe("prepareAuthoredWorkflowDirectives", () => {
[" async execute() {", ' "use step";', " return 1;", " },"].join("\n"),
),
}),
- ).rejects.toThrow(/"use step".*marks the default export's "execute" method/u);
+ ).rejects.toThrow('"use step"');
});
- it("rejects a directive the SDK's line-based pre-scan cannot see", async () => {
- const source = `export default { description: "d", async execute() { "use workflow"; return 1; } };\n`;
-
- await expect(prepareAuthoredWorkflowDirectives({ filePath: FILE, source })).rejects.toThrow(
- /"use workflow" in .* is not on its own line/u,
- );
+ it("accepts a directive as the first statement on the function's opening line", async () => {
+ const source = `export async function standalone() { "use workflow"; return 1; }\n`;
+ await expect(prepareAuthoredWorkflowDirectives({ filePath: FILE, source })).resolves.toEqual({
+ hasDirectives: true,
+ hasWorkflowDirective: true,
+ source,
+ });
});
it("rejects hoisting over an existing top-level execute binding", async () => {
diff --git a/packages/eve/src/internal/workflow-bundle/authored-workflow-directives.ts b/packages/eve/src/internal/workflow-bundle/authored-workflow-directives.ts
index 0b446220d..60375fe99 100644
--- a/packages/eve/src/internal/workflow-bundle/authored-workflow-directives.ts
+++ b/packages/eve/src/internal/workflow-bundle/authored-workflow-directives.ts
@@ -1,5 +1,3 @@
-import { detectWorkflowPatterns } from "#compiled/@workflow/builders/index.js";
-
import { parseWithNitroRolldownAst } from "#internal/bundler/nitro-rolldown.js";
import { readWorkflowDirective } from "#internal/workflow-bundle/workflow-directive-ast.js";
@@ -30,6 +28,7 @@ type AstNode = {
typeParameters?: AstNode | null;
value?: unknown;
arguments?: AstNode[];
+ source?: AstNode;
};
type AstProgram = { body?: AstNode[] };
@@ -40,8 +39,6 @@ interface DirectiveFunctionNode {
}
export interface AuthoredWorkflowDirectiveSource {
- /** Name of the top-level `"use workflow"` function the default export's `execute` is or references. */
- readonly executeWorkflow?: string;
readonly hasDirectives: boolean;
readonly hasWorkflowDirective: boolean;
readonly source: string;
@@ -49,7 +46,7 @@ export interface AuthoredWorkflowDirectiveSource {
/**
* The directive transform understands one shape: a top-level `async function`
- * whose first statement is the directive. A tool's `execute` method is hoisted
+ * whose first statement is the directive. A marked `defineWorkflowTool` executor is hoisted
* into that shape here; every other placement is a build error, because an
* ignored directive would run side effects inline in a replayed body.
*/
@@ -57,9 +54,14 @@ export async function prepareAuthoredWorkflowDirectives(input: {
readonly filePath: string;
readonly source: string;
}): Promise<AuthoredWorkflowDirectiveSource> {
- const program = (await parseWithNitroRolldownAst(input.filePath, input.source)) as AstProgram;
+ const parsePath = /\.[cm]?js$/.test(input.filePath) ? `${input.filePath}.jsx` : input.filePath;
+ const program = (await parseWithNitroRolldownAst(parsePath, input.source)) as AstProgram;
const body = program.body ?? [];
-
+ if (body.some((node) => node.source?.value === "eve/workflow")) {
+ throw new Error(
+ `${input.filePath}: "eve/workflow" has been removed. Use defineWorkflowTool() from "eve/tools" and call ctx.agent(input) or ctx.ask(request) in its executor.`,
+ );
+ }
for (const statement of body) {
if (typeof statement.directive !== "string") break;
const directive = readWorkflowDirective(statement);
@@ -67,7 +69,7 @@ export async function prepareAuthoredWorkflowDirectives(input: {
throw new Error(
`${JSON.stringify(directive)} in "${input.filePath}" is a module-level directive. ` +
`Put it as the first statement of the function it marks: a top-level "async function" declaration` +
- ` or, for "use workflow", the "execute" method of the module's default export.`,
+ ` or the "execute" method of a default-exported defineWorkflowTool().`,
);
}
}
@@ -91,29 +93,21 @@ export async function prepareAuthoredWorkflowDirectives(input: {
isFunctionLike(executeProperty.value)
? executeProperty.value
: undefined;
- if (executeFunction !== undefined) allowed.add(executeFunction);
+ if (executeFunction !== undefined) {
+ allowed.add(executeFunction);
+ }
const found = collectDirectiveFunctions(program as AstNode);
if (found.length === 0) {
return { hasDirectives: false, hasWorkflowDirective: false, source: input.source };
}
const hasWorkflowDirective = found.some((entry) => entry.directive === "use workflow");
- // Discovery gates on the SDK's line-based pre-scan; a directive it cannot see
- // would compile here into a stub with no run behind it.
- const visibleToPrescan = detectWorkflowPatterns(input.source).hasDirective;
-
for (const entry of found) {
- if (!visibleToPrescan) {
- throw new Error(
- `${JSON.stringify(entry.directive)} in "${input.filePath}" is not on its own line. ` +
- `Write it as the first statement of the function body, on a line by itself.`,
- );
- }
if (!allowed.has(entry.fn)) {
throw new Error(
`${JSON.stringify(entry.directive)} in "${input.filePath}" marks ${describeFunction(entry.fn)}. ` +
`Workflow directives must mark a top-level "async function" declaration` +
- ` or, for "use workflow", the "execute" method of the module's default export.`,
+ ` or the "execute" method of a default-exported defineWorkflowTool().`,
);
}
if (entry.fn.async !== true) {
@@ -132,13 +126,11 @@ export async function prepareAuthoredWorkflowDirectives(input: {
const hoist = found.find((entry) => entry.fn === executeFunction);
if (hoist === undefined || executeProperty === undefined) {
- const prepared: AuthoredWorkflowDirectiveSource = {
+ return {
hasDirectives: true,
hasWorkflowDirective,
source: input.source,
};
- const referenced = readExecuteReference(executeProperty, found);
- return referenced === undefined ? prepared : { ...prepared, executeWorkflow: referenced };
}
if (declaresTopLevelBinding(body, HOISTED_EXECUTE_NAME)) {
@@ -149,29 +141,12 @@ export async function prepareAuthoredWorkflowDirectives(input: {
}
return {
- executeWorkflow: HOISTED_EXECUTE_NAME,
hasDirectives: true,
hasWorkflowDirective,
source: hoistExecuteMethod(input.source, executeProperty, hoist.fn),
};
}
-/** `execute: deploy`, where `deploy` is a top-level `"use workflow"` declaration. */
-function readExecuteReference(
- executeProperty: AstNode | undefined,
- found: readonly DirectiveFunctionNode[],
-): string | undefined {
- const value = executeProperty?.value;
- if (!isAstNode(value) || value.type !== "Identifier" || typeof value.name !== "string") {
- return undefined;
- }
- const name = value.name;
- const target = found.find(
- (entry) => entry.directive === "use workflow" && entry.fn.id?.name === name,
- );
- return target === undefined ? undefined : name;
-}
-
function findDefaultExportExecuteProperty(body: readonly AstNode[]): AstNode | undefined {
const exported = body.find((statement) => statement.type === "ExportDefaultDeclaration");
const declaration = exported?.declaration;
diff --git a/packages/eve/src/internal/workflow-bundle/authored-workflow-modules.integration.test.ts b/packages/eve/src/internal/workflow-bundle/authored-workflow-modules.integration.test.ts
index 369c79944..f1f5b99ae 100644
--- a/packages/eve/src/internal/workflow-bundle/authored-workflow-modules.integration.test.ts
+++ b/packages/eve/src/internal/workflow-bundle/authored-workflow-modules.integration.test.ts
@@ -4,7 +4,6 @@ import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
-import { prepareAuthoredWorkflowDirectives } from "./authored-workflow-directives.js";
import { discoverAuthoredWorkflowModules } from "./authored-workflow-modules.js";
let appRoot: string;
@@ -29,9 +28,9 @@ describe("discoverAuthoredWorkflowModules", () => {
it("separates workflow modules from step-only modules and skips the rest", async () => {
const tool = await write(
"agent/tools/deploy.ts",
- `import { defineTool } from "eve/tools";
+ `import { defineWorkflowTool } from "eve/tools";
import { plan } from "../lib/plan.ts";
-export default defineTool({
+export default defineWorkflowTool({
description: "d",
inputSchema: {},
async execute(input) {
@@ -85,18 +84,19 @@ export default defineTool({
await write(
"src/app/layout.js",
`export default function RootLayout({ children }) {
- return <html><body>{children}</body></html>;
+ return <html><body><code>defineWorkflowTool is only text here</code>{children}</body></html>;
}`,
);
const tool = await write(
"agent/tools/deploy.ts",
- `export default {
+ `import { defineWorkflowTool } from "eve/tools";
+export default defineWorkflowTool({
description: "d",
async execute() {
"use workflow";
return 1;
},
-};`,
+});`,
);
await expect(discoverAuthoredWorkflowModules(appRoot)).resolves.toEqual({
@@ -115,23 +115,20 @@ export default defineTool({
});
});
- it("rejects a directive that is not on its own line instead of compiling half of it", async () => {
- const source = `export default { description: "d", async execute() { "use workflow"; return 1; } };`;
- await write("agent/tools/inline.ts", source);
-
- // Discovery pre-scans by line, as the SDK does, and never sees this file;
- // the module transform parses it and must refuse rather than emit a stub
- // with no registered run behind it.
+ it("discovers directives on the same line as their function declaration", async () => {
+ const tool = await write(
+ "agent/tools/inline.ts",
+ `import { defineWorkflowTool } from "eve/tools";
+export default defineWorkflowTool({ async execute() { "use workflow"; return plan(); } });`,
+ );
+ const helper = await write(
+ "agent/lib/plan.ts",
+ `export async function plan() { "use step"; return 1; }`,
+ );
await expect(discoverAuthoredWorkflowModules(appRoot)).resolves.toEqual({
- directiveModules: [],
- workflowModules: [],
+ directiveModules: [helper, tool],
+ workflowModules: [tool],
});
- await expect(
- prepareAuthoredWorkflowDirectives({
- filePath: join(appRoot, "agent/tools/inline.ts"),
- source,
- }),
- ).rejects.toThrow("is not on its own line");
});
it("reports an invalid directive placement as a build error", async () => {
diff --git a/packages/eve/src/internal/workflow-bundle/authored-workflow-modules.ts b/packages/eve/src/internal/workflow-bundle/authored-workflow-modules.ts
index dd3ea77f5..2b6aabc5b 100644
--- a/packages/eve/src/internal/workflow-bundle/authored-workflow-modules.ts
+++ b/packages/eve/src/internal/workflow-bundle/authored-workflow-modules.ts
@@ -2,10 +2,7 @@ import type { Dirent } from "node:fs";
import { readdir, readFile } from "node:fs/promises";
import { join } from "node:path";
-import {
- detectWorkflowPatterns,
- isGeneratedWorkflowFile,
-} from "#compiled/@workflow/builders/index.js";
+import { isGeneratedWorkflowFile } from "#compiled/@workflow/builders/index.js";
import { prepareAuthoredWorkflowDirectives } from "./authored-workflow-directives.js";
import { isWorkflowSourceFile } from "./builder-support.js";
@@ -44,8 +41,7 @@ export interface AuthoredWorkflowModules {
/**
* Scans the whole application root, as the SDK's bundler integrations do, so a
- * step helper can live wherever the tool imports it from. The SDK's pre-scan
- * picks the files worth parsing.
+ * step helper can live wherever the tool imports it from.
*/
export async function discoverAuthoredWorkflowModules(
appRoot: string,
@@ -59,7 +55,7 @@ export async function discoverAuthoredWorkflowModules(
if (!isAuthoredApplicationModule(filePath, appRoot) || isGeneratedWorkflowFile(filePath))
continue;
const source = await readFile(filePath, "utf8");
- if (!detectWorkflowPatterns(source).hasDirective) continue;
+ if (!source.includes("use workflow") && !source.includes("use step")) continue;
const prepared = await prepareAuthoredWorkflowDirectives({ filePath, source });
if (!prepared.hasDirectives) continue;
directiveModules.push(filePath);
diff --git a/packages/eve/src/internal/workflow-bundle/builder.scenario.test.ts b/packages/eve/src/internal/workflow-bundle/builder.scenario.test.ts
index d9465bf91..53c5c0e03 100644
--- a/packages/eve/src/internal/workflow-bundle/builder.scenario.test.ts
+++ b/packages/eve/src/internal/workflow-bundle/builder.scenario.test.ts
@@ -802,14 +802,22 @@ describe("WorkflowBundleBuilder", () => {
"",
].join("\n"),
),
+ writeFile(
+ join(appRoot, "agent", "tools", "imported.ts"),
+ 'import { defineWorkflowTool } from "eve/tools";\nimport { run } from "../lib/run";\nexport default defineWorkflowTool({ description: "Imported", inputSchema: {}, execute: run });',
+ ),
+ writeFile(
+ join(appRoot, "agent", "lib", "run.ts"),
+ 'import { hashPlan } from "./steps";\nexport async function run() { "use workflow"; return hashPlan("imported"); }',
+ ),
writeFile(
toolPath,
[
- 'import { defineTool } from "eve/tools";',
+ 'import { defineWorkflowTool } from "eve/tools";',
'import { sleep } from "workflow";',
'import { describePlan, hashPlan } from "../lib/steps";',
"",
- "export default defineTool({",
+ "export default defineWorkflowTool({",
' description: "Deploy a service.",',
' inputSchema: { type: "object", properties: { service: { type: "string" } } },',
" async execute({ service }: { service: string }) {",
@@ -841,6 +849,7 @@ describe("WorkflowBundleBuilder", () => {
const stepsSource = await readFile(join(outDir, "steps.mjs"), "utf8");
expect(stepsSource).toContain("agent/tools/deploy.ts");
expect(stepsSource).toContain("agent/lib/steps.ts");
+ expect(stepsSource).toContain("agent/lib/run.ts");
expect(stepsSource).not.toContain("vendored");
const workflowsSource = await readFile(join(outDir, "workflows.mjs"), "utf8");
@@ -850,9 +859,10 @@ describe("WorkflowBundleBuilder", () => {
const encodedChunks = JSON.parse(encodedChunksMatch?.[1] ?? "[]") as string[];
const workflowCode = Buffer.from(encodedChunks.join(""), "base64").toString("utf8");
expect(workflowCode).toContain('"workflow//./agent/tools/deploy//execute"');
+ expect(workflowCode).toContain('"workflow//./agent/lib/run//run"');
expect(workflowCode).toContain('"step//./agent/lib/steps//hashPlan"');
expect(workflowCode).toContain("deploy ${service}");
- expect(workflowCode).not.toContain("defineTool");
+ expect(workflowCode).not.toContain("defineWorkflowTool");
expect(workflowCode).not.toContain("node:crypto");
} finally {
await rm(tempRoot, { force: true, recursive: true });
diff --git a/packages/eve/src/internal/workflow-bundle/dynamic-tool-transform.test.ts b/packages/eve/src/internal/workflow-bundle/dynamic-tool-transform.test.ts
index f7d149b92..3c82507e0 100644
--- a/packages/eve/src/internal/workflow-bundle/dynamic-tool-transform.test.ts
+++ b/packages/eve/src/internal/workflow-bundle/dynamic-tool-transform.test.ts
@@ -1972,11 +1972,13 @@ export default defineDynamic({
expect(await transformDynamicToolExecute("tools/null.ts", source)).toBeNull();
});
- it("leaves executes that are workflow functions unstamped", async () => {
- // The shape the directive transform hands over: bodies hoisted to
- // top-level declarations (here already stubbed) and referenced by name.
- const source = `
-import { defineTool } from "eve/tools";
+ it.each(["named", "namespace"])(
+ "leaves workflow executors unstamped with a %s import",
+ async (style) => {
+ // The shape the directive transform hands over: bodies hoisted to
+ // top-level declarations (here already stubbed) and referenced by name.
+ let source = `
+import { defineWorkflowTool } from "eve/tools";
async function execute(input) {
throw new Error("stub");
@@ -1988,28 +1990,34 @@ async function deploy(input) {
}
deploy.workflowId = "workflow//./agent/tools/deploy//deploy";
-export default defineTool({
+export default defineWorkflowTool({
description: "Inline body",
inputSchema: {},
execute,
async toModelOutput(output) { return String(output); },
});
-export const referenced = defineTool({
+export const referenced = defineWorkflowTool({
description: "Referenced body",
inputSchema: {},
execute: deploy,
});
`;
- const result = await transformDynamicToolExecute(
- "agent/tools/deploy.ts",
- source,
- new Set(["execute", "deploy"]),
- );
- expect(result).not.toBeNull();
- expect(result?.code).not.toContain("__eve_dynamic_exec_");
- expect(result?.code).toContain("toModelOutput: __eveStampDynamicCallback(");
- });
+ if (style === "namespace") {
+ source = source
+ .replace("import { defineWorkflowTool }", "import * as tools")
+ .replaceAll("defineWorkflowTool({", "tools.defineWorkflowTool({");
+ }
+ const result = await transformDynamicToolExecute(
+ "agent/tools/deploy.ts",
+ source,
+ new Set(["execute", "deploy"]),
+ );
+ expect(result).not.toBeNull();
+ expect(result?.code).not.toContain("__eve_dynamic_exec_");
+ expect(result?.code).toContain("toModelOutput: __eveStampDynamicCallback(");
+ },
+ );
});
// ===========================================================================
diff --git a/packages/eve/src/internal/workflow-bundle/dynamic-tool-transform.ts b/packages/eve/src/internal/workflow-bundle/dynamic-tool-transform.ts
index a23470940..ee9c869c6 100644
--- a/packages/eve/src/internal/workflow-bundle/dynamic-tool-transform.ts
+++ b/packages/eve/src/internal/workflow-bundle/dynamic-tool-transform.ts
@@ -45,7 +45,7 @@ export async function transformDynamicToolExecute(
source: string,
workflowFunctions: ReadonlySet<string> = NO_WORKFLOW_FUNCTIONS,
): Promise<{ code: string } | null> {
- if (!source.includes("defineTool")) return null;
+ if (!source.includes("defineTool") && !source.includes("defineWorkflowTool")) return null;
const ast = (await parseWithNitroRolldownAst(filename, source)) as AstNode;
const defineToolAliases = findDefineToolAliases(ast);
@@ -80,9 +80,14 @@ function findDefineToolAliases(ast: AstNode): ReadonlySet<string> {
return false;
}
for (const specifier of node.specifiers ?? []) {
+ if (specifier.type === "ImportNamespaceSpecifier" && specifier.local?.name) {
+ aliases.add(`${specifier.local.name}.defineWorkflowTool`);
+ }
if (
specifier.type === "ImportSpecifier" &&
- (specifier.imported?.name ?? specifier.imported?.value) === "defineTool" &&
+ ["defineTool", "defineWorkflowTool"].includes(
+ String(specifier.imported?.name ?? specifier.imported?.value),
+ ) &&
specifier.local?.name
) {
aliases.add(specifier.local.name);
@@ -93,6 +98,13 @@ function findDefineToolAliases(ast: AstNode): ReadonlySet<string> {
return aliases;
}
+function readDefinerName(callee: AstNode | undefined): string | undefined {
+ if (callee?.type === "Identifier") return callee.name;
+ if (callee?.type !== "MemberExpression" || callee.object?.type !== "Identifier") return undefined;
+ const property = callee.computed ? callee.property?.value : callee.property?.name;
+ return typeof property === "string" ? `${callee.object.name}.${property}` : undefined;
+}
+
function walkForCallbacks(
source: string,
node: AstNode | null | undefined,
@@ -118,9 +130,7 @@ function walkForCallbacks(
if (
node.type === "CallExpression" &&
- node.callee?.type === "Identifier" &&
- node.callee.name !== undefined &&
- context.defineToolAliases.has(node.callee.name) &&
+ context.defineToolAliases.has(readDefinerName(node.callee) ?? "") &&
node.arguments?.length === 1 &&
node.arguments[0]?.type === "ObjectExpression"
) {
diff --git a/packages/eve/src/internal/workflow-bundle/workflow-builders.test.ts b/packages/eve/src/internal/workflow-bundle/workflow-builders.test.ts
index 8d7284524..4ccbba5b4 100644
--- a/packages/eve/src/internal/workflow-bundle/workflow-builders.test.ts
+++ b/packages/eve/src/internal/workflow-bundle/workflow-builders.test.ts
@@ -268,20 +268,19 @@ describe("applyWorkflowTransform for authored application modules", () => {
const toolPath = "/app/agent/tools/deploy.ts";
const toolSource = [
'import { readFile } from "node:fs/promises";',
- 'import { defineTool } from "eve/tools";',
- 'import { ask } from "eve/workflow";',
+ 'import { defineWorkflowTool, type WorkflowToolContext } from "eve/tools";',
'import { sleep } from "workflow";',
'import { z } from "zod";',
"",
'const APPROVE = [{ id: "approve", label: "Deploy" }];',
"",
- "export default defineTool({",
+ "export default defineWorkflowTool({",
' description: "Deploy",',
" inputSchema: z.object({ service: z.string() }),",
- " async execute({ service }: { service: string }, ctx: ToolContext) {",
+ " async execute({ service }: { service: string }, ctx: WorkflowToolContext) {",
' "use workflow";',
" const plan = await planDeploy(service);",
- " const answer = await (await ask(ctx, { prompt: plan, options: APPROVE }));",
+ " const answer = await ctx.ask({ prompt: plan, options: APPROVE });",
' await sleep("1s");',
' return { deployed: answer.optionId === "approve" };',
" },",
@@ -325,12 +324,30 @@ describe("applyWorkflowTransform for authored application modules", () => {
expect(transformed.code).toContain("const APPROVE = ");
expect(transformed.code).toContain('import { sleep } from "workflow";');
expect(transformed.code).not.toContain("export default");
- expect(transformed.code).not.toContain("defineTool");
+ expect(transformed.code).not.toContain("defineWorkflowTool");
expect(transformed.code).not.toContain("zod");
expect(transformed.code).not.toContain("node:fs/promises");
expect(transformed.code).not.toContain('"use workflow"');
});
+ it("removes a namespace-imported workflow definition from the driver", async () => {
+ const source = toolSource
+ .replace("import { defineWorkflowTool, type WorkflowToolContext }", "import * as tools")
+ .replace("defineWorkflowTool({", "tools.defineWorkflowTool({");
+ const transformed = await applyWorkflowTransform(
+ "agent/tools/deploy.ts",
+ source,
+ "workflow",
+ toolPath,
+ appRoot,
+ );
+ expect(transformed.code).not.toContain("export default");
+ expect(transformed.code).not.toContain("eve/tools");
+ expect(transformed.workflowManifest.workflows?.["agent/tools/deploy.ts"]?.execute).toEqual({
+ workflowId: "workflow//./agent/tools/deploy//execute",
+ });
+ });
+
it("registers steps and stubs the workflow body in step mode", async () => {
const transformed = await applyWorkflowTransform(
"agent/tools/deploy.ts",
@@ -349,7 +366,7 @@ describe("applyWorkflowTransform for authored application modules", () => {
expect(transformed.code).toContain(
"You attempted to execute workflow execute function directly",
);
- expect(transformed.code).toContain("export default defineTool({");
+ expect(transformed.code).toContain("export default defineWorkflowTool({");
expect(transformed.code).toContain(" execute,\n");
expect(transformed.code).toContain('import { z } from "zod";');
});
diff --git a/packages/eve/src/internal/workflow-bundle/workflow-builders.ts b/packages/eve/src/internal/workflow-bundle/workflow-builders.ts
index 17c14ec35..3fd696272 100644
--- a/packages/eve/src/internal/workflow-bundle/workflow-builders.ts
+++ b/packages/eve/src/internal/workflow-bundle/workflow-builders.ts
@@ -7,7 +7,6 @@ import { EVE_PACKAGE_NAME } from "#internal/package-name.js";
import { SUBAGENT_TOOL_EXECUTE_WORKFLOW_NAME } from "#runtime/subagents/workflow-reference.js";
import { prepareAuthoredWorkflowDirectives } from "#internal/workflow-bundle/authored-workflow-directives.js";
import {
- createWorkflowId,
findWorkflowDirectiveFunctions,
stripJavaScriptExtension,
transformWorkflowDirectives,
@@ -123,15 +122,6 @@ function authoredModuleIdBase(absolutePath: string, appRoot: string): string {
return `./${stripJavaScriptExtension(authoredRelativePath(absolutePath, appRoot))}`;
}
-/** The id the transform mints for an authored `"use workflow"` function. */
-export function authoredWorkflowId(
- absolutePath: string,
- appRoot: string,
- functionName: string,
-): string {
- return createWorkflowId(authoredModuleIdBase(absolutePath, appRoot), functionName);
-}
-
// Bundlers hand back real paths while configuration carries the spelled
// path (for example macOS `/var` → `/private/var`); compare like with like.
function toRealPath(path: string): string {
diff --git a/packages/eve/src/internal/workflow-bundle/workflow-transformer.ts b/packages/eve/src/internal/workflow-bundle/workflow-transformer.ts
index d96a43464..75d8b2b44 100644
--- a/packages/eve/src/internal/workflow-bundle/workflow-transformer.ts
+++ b/packages/eve/src/internal/workflow-bundle/workflow-transformer.ts
@@ -71,6 +71,7 @@ type AstNode = {
kind?: string;
local?: { name?: string } | null;
name?: string;
+ object?: AstNode | null;
source?: AstNode | null;
start?: number;
specifiers?: AstNode[];
@@ -427,7 +428,8 @@ function removeEveDefinerDefaultExport(
const call = node.declaration;
if (call?.type !== "CallExpression" || node.end === undefined) continue;
const callee = call.callee;
- if (callee?.type !== "Identifier" || !eveBindings.has(callee.name ?? "")) continue;
+ const binding = callee?.type === "MemberExpression" ? callee.object : callee;
+ if (binding?.type !== "Identifier" || !eveBindings.has(binding.name ?? "")) continue;
removals.push({ end: node.end, start: node.start, text: "" });
}
diff --git a/packages/eve/src/public/tools/index.ts b/packages/eve/src/public/tools/index.ts
index b11a949b8..28278440b 100644
--- a/packages/eve/src/public/tools/index.ts
+++ b/packages/eve/src/public/tools/index.ts
@@ -33,3 +33,11 @@ export {
type MatchedToolResult,
type ToolResultFromFn,
} from "#public/tools/result.js";
+
+export {
+ defineWorkflowTool,
+ type WorkflowToolContext,
+ type WorkflowToolDefinition,
+ type AgentInput,
+} from "#tools/workflow-definition.js";
+export type { ToolInputRequest, ToolInputResponse } from "#tools/definition.js";
diff --git a/packages/eve/src/public/workflow/index.ts b/packages/eve/src/public/workflow/index.ts
deleted file mode 100644
index ca8bab380..000000000
--- a/packages/eve/src/public/workflow/index.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-/** `eve/workflow`: what eve adds inside a workflow tool body. The SDK's own constructs come from `workflow`. */
-export { ask } from "#execution/tools/workflow/ask.js";
-export { agent } from "#execution/tools/subagent/invoke-agent.js";
-export type { AgentInput } from "#execution/tools/subagent/invoke-agent.js";
-export type { ToolInputRequest, ToolInputResponse } from "#tools/definition.js";
diff --git a/packages/eve/src/shared/workflow-tool-context.ts b/packages/eve/src/shared/workflow-tool-context.ts
new file mode 100644
index 000000000..0a864961b
--- /dev/null
+++ b/packages/eve/src/shared/workflow-tool-context.ts
@@ -0,0 +1,10 @@
+export function workflowToolContextErrorMessage(helper: "agent" | "ask"): string {
+ return `ctx.${helper}() requires a defineWorkflowTool() executor context. Call it inside the workflow tool body.`;
+}
+
+export function workflowCallbackErrorMessage(kind: "channel" | "schedule"): string {
+ return (
+ `"use workflow" is not supported on ${kind} callbacks. ` +
+ 'Use defineWorkflowTool() from "eve/tools" to author a workflow tool.'
+ );
+}
diff --git a/packages/eve/src/tools/definition.ts b/packages/eve/src/tools/definition.ts
index 6f057f777..c6c3d339e 100644
--- a/packages/eve/src/tools/definition.ts
+++ b/packages/eve/src/tools/definition.ts
@@ -94,7 +94,7 @@ export interface PublicToolDefinitionWithExecuteFn<
/**
* A question a workflow tool asks the human on the session's channel, sent
- * with `ask` from `eve/workflow`. Channels render it the way they render
+ * with `ctx.ask` from a `defineWorkflowTool` executor. Channels render it the way they render
* `ask_question` and tool approvals.
*/
export interface ToolInputRequest {
@@ -125,10 +125,8 @@ export interface ToolInputResponse {
* Extends {@link SessionContext} with token accessors. Passing a provider
* resolves that provider inline, which lets one tool use multiple credentials.
*
- * A tool whose `execute` is a workflow (`"use workflow"`) receives the same
- * context inside its durable body, except that `getSandbox`, `getSkill`,
- * `getToken`, and `requireAuth` are unavailable there and throw when touched —
- * read credentials inside a `"use step"` function instead.
+ * Workflow tools use the separate `WorkflowToolContext` provided by
+ * `defineWorkflowTool`.
*/
export type ToolContext = SessionContext & {
/**
@@ -342,9 +340,20 @@ export function defineTool<TInput = unknown, TOutput = unknown>(
export function defineTool<TInput = unknown, TOutput = unknown>(
definition: ToolDefinition<TInput, TOutput> | BackgroundToolDefinition<TInput, TOutput>,
): ToolDefinition<TInput, TOutput> | BackgroundToolDefinition<TInput, TOutput> {
+ return stampToolDefinition(definition, "defineTool");
+}
+
+export function stampToolDefinition<
+ T extends {
+ readonly description: string;
+ readonly execute: (...args: never[]) => unknown;
+ readonly approval?: Approval<never>;
+ readonly toModelOutput?: (...args: never[]) => unknown;
+ },
+>(definition: T, definer: "defineTool" | "defineWorkflowTool"): T {
if ((definition as { readonly auth?: unknown }).auth !== undefined) {
throw new Error(
- `defineTool: The "auth" field is no longer supported. ` +
+ `${definer}: The "auth" field is no longer supported. ` +
`Pass auth providers inline to ctx.getToken(provider) or ctx.requireAuth(provider).`,
);
}
@@ -352,7 +361,7 @@ export function defineTool<TInput = unknown, TOutput = unknown>(
stampDurableDynamicToolCallbacks(
definition,
collectDurableDynamicToolCallbacks({
- approval: definition.approval as Approval<never> | undefined,
+ approval: definition.approval,
execute: definition.execute,
toModelOutput: definition.toModelOutput,
}),
diff --git a/packages/eve/src/tools/provided/sleep.test.ts b/packages/eve/src/tools/provided/sleep.test.ts
index b6d05f4f9..01fd77b63 100644
--- a/packages/eve/src/tools/provided/sleep.test.ts
+++ b/packages/eve/src/tools/provided/sleep.test.ts
@@ -2,6 +2,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import { sleep as workflowSleep } from "#compiled/@workflow/core/index.js";
import { sleep } from "#tools/provided/sleep.js";
+import { isWorkflowToolDefinition } from "#tools/workflow-definition.js";
vi.mock("#compiled/@workflow/core/index.js", () => ({
sleep: vi.fn(),
@@ -15,6 +16,7 @@ describe("sleep", () => {
it("defines a model-facing tool", () => {
const definition = sleep();
+ expect(isWorkflowToolDefinition(definition)).toBe(true);
expect(definition.description).toContain("before continuing");
expect(definition.execute).toBeTypeOf("function");
});
diff --git a/packages/eve/src/tools/provided/sleep.ts b/packages/eve/src/tools/provided/sleep.ts
index 79a8e9576..684862476 100644
--- a/packages/eve/src/tools/provided/sleep.ts
+++ b/packages/eve/src/tools/provided/sleep.ts
@@ -1,4 +1,7 @@
-import { defineTool, type ToolDefinition } from "#tools/definition.js";
+import {
+ defineWorkflowTool,
+ type BlockingWorkflowToolDefinition,
+} from "#tools/workflow-definition.js";
import {
executeSleepTool,
SLEEP_INPUT_SCHEMA,
@@ -24,8 +27,8 @@ export type { SleepToolInput, SleepToolOutput };
* Each call runs as a durable workflow, so the wait does not hold an
* application runtime open.
*/
-export function sleep(): ToolDefinition<SleepToolInput, SleepToolOutput> {
- return defineTool({
+export function sleep(): BlockingWorkflowToolDefinition<SleepToolInput, SleepToolOutput> {
+ return defineWorkflowTool({
description: SLEEP_TOOL_DESCRIPTION,
execute: executeSleepTool,
inputSchema: SLEEP_INPUT_SCHEMA,
diff --git a/packages/eve/src/tools/workflow-definition.test.ts b/packages/eve/src/tools/workflow-definition.test.ts
new file mode 100644
index 000000000..727d809e0
--- /dev/null
+++ b/packages/eve/src/tools/workflow-definition.test.ts
@@ -0,0 +1,97 @@
+import { describe, expect, expectTypeOf, it } from "vitest";
+import { z } from "zod";
+import * as tools from "#public/tools/index.js";
+import { defineTool } from "#tools/definition.js";
+import {
+ defineWorkflowTool,
+ isWorkflowToolDefinition,
+ type WorkflowToolContext,
+} from "#tools/workflow-definition.js";
+import { normalizeToolDefinition } from "#internal/authored-definition/schema-backed.js";
+
+describe("defineWorkflowTool", () => {
+ it("infers input, output, and the workflow context", () => {
+ const definition = defineWorkflowTool({
+ description: "Deploy",
+ inputSchema: z.object({ service: z.string() }),
+ async execute(input, ctx) {
+ expectTypeOf(input).toEqualTypeOf<{ service: string }>();
+ expectTypeOf(ctx).toEqualTypeOf<WorkflowToolContext>();
+ // @ts-expect-error Workflow bodies do not have turn-owned token access.
+ void ctx.getToken;
+ // @ts-expect-error Workflow bodies do not have a session sandbox.
+ void ctx.getSandbox;
+ return { deployed: input.service };
+ },
+ toModelOutput(output) {
+ expectTypeOf(output).toEqualTypeOf<{ deployed: string }>();
+ return { type: "text", value: output.deployed };
+ },
+ });
+ expect(isWorkflowToolDefinition(definition)).toBe(true);
+ expectTypeOf(definition.execute).parameter(0).toEqualTypeOf<{ service: string }>();
+ });
+
+ it("provides task messages and receipt projections for background workflows", () => {
+ const definition = defineWorkflowTool({
+ description: "Report a deployment",
+ execution: "background",
+ inputSchema: z.object({ service: z.string() }),
+ async *execute(input, ctx, task) {
+ expectTypeOf(input).toEqualTypeOf<{ service: string }>();
+ expectTypeOf(ctx).toEqualTypeOf<WorkflowToolContext>();
+ expectTypeOf(task.taskId).toEqualTypeOf<string>();
+ yield { status: "planning" };
+ yield task.postMessage(input.service);
+ return { deployed: input.service };
+ },
+ toModelOutput(receipt) {
+ expectTypeOf(receipt).toEqualTypeOf<import("#tools/task.js").TaskReceipt>();
+ return { type: "text", value: receipt.taskId };
+ },
+ });
+ expect(isWorkflowToolDefinition(definition)).toBe(true);
+ });
+
+ it("keeps workflow capabilities off ordinary tools and top-level exports", () => {
+ const definition = defineTool({
+ description: "Ordinary",
+ inputSchema: z.object({}),
+ async execute(_input, ctx) {
+ // @ts-expect-error agent is available only on WorkflowToolContext.
+ void ctx.agent;
+ // @ts-expect-error ask is available only on WorkflowToolContext.
+ void ctx.ask;
+ return 1;
+ },
+ });
+ expect(isWorkflowToolDefinition(definition)).toBe(false);
+ expect(tools).not.toHaveProperty("agent");
+ expect(tools).not.toHaveProperty("ask");
+ });
+
+ it("rejects an uncompiled workflow tool rather than running it inline", () => {
+ const definition = defineWorkflowTool({
+ description: "Workflow",
+ inputSchema: {},
+ async execute() {
+ "use workflow";
+ return 1;
+ },
+ });
+ expect(() => normalizeToolDefinition(definition, "Invalid tool.")).toThrow(
+ "requires a compiled workflow executor",
+ );
+ });
+
+ it.each(["defineTool", "bare object"])("rejects a workflow executor in %s", (kind) => {
+ const execute = Object.assign(async () => 1, { workflowId: "workflow//test//execute" });
+ const definition = { description: "Ordinary", inputSchema: {}, execute };
+ expect(() =>
+ normalizeToolDefinition(
+ kind === "defineTool" ? defineTool(definition) : definition,
+ "Invalid tool.",
+ ),
+ ).toThrow("Workflow executors require defineWorkflowTool()");
+ });
+});
diff --git a/packages/eve/src/tools/workflow-definition.ts b/packages/eve/src/tools/workflow-definition.ts
new file mode 100644
index 000000000..e5aed7b8b
--- /dev/null
+++ b/packages/eve/src/tools/workflow-definition.ts
@@ -0,0 +1,131 @@
+import type {
+ StandardJSONSchemaV1,
+ StandardSchemaV1,
+} from "#compiled/@standard-schema/spec/index.js";
+import type { Approval } from "#approval/definition.js";
+import type { JsonObject, JsonValue } from "#shared/json.js";
+import {
+ stampToolDefinition,
+ type PublicToolDefinition,
+ type BackgroundToolDefinition,
+ type ToolContext,
+ type ToolInputRequest,
+ type ToolInputResponse,
+} from "#tools/definition.js";
+import type { TaskExec } from "#tools/task.js";
+import type { ToolModelOutput } from "#tools/model-output.js";
+
+export interface AgentInput {
+ readonly agentId?: string;
+ readonly key: string;
+ readonly message: string;
+ readonly outputSchema?: JsonObject;
+ readonly target: string;
+}
+
+/** Context supplied only to a defineWorkflowTool executor, inside its durable run. */
+export type WorkflowToolContext = Pick<
+ ToolContext,
+ "abortSignal" | "callId" | "session" | "toolName"
+> & {
+ /** Invoke a visible subagent. The key must be unique within this workflow run. */
+ agent(input: AgentInput): Promise<JsonValue>;
+ /** Ask the human on the session's channel; awaiting the answer suspends the run. */
+ ask(request: ToolInputRequest): PromiseLike<ToolInputResponse>;
+};
+
+const WORKFLOW_TOOL_BRAND = Symbol.for("eve:workflow-tool-brand");
+
+/** A static tool whose executor runs as a durable workflow. Its executor must start with "use workflow". */
+export interface BlockingWorkflowToolDefinition<
+ TInput = unknown,
+ TOutput = unknown,
+> extends PublicToolDefinition<TInput, TOutput> {
+ readonly [WORKFLOW_TOOL_BRAND]: true;
+ readonly execution?: never;
+ execute(input: TInput, ctx: WorkflowToolContext): Promise<TOutput> | AsyncIterable<TOutput>;
+ approval?: Approval<unknown extends TInput ? Record<string, unknown> : TInput>;
+ toModelOutput?: (output: TOutput) => ToolModelOutput | Promise<ToolModelOutput>;
+}
+
+type BackgroundWorkflowToolDefinition<TInput, TOutput> = Omit<
+ BackgroundToolDefinition<TInput, TOutput>,
+ "execute"
+> & {
+ readonly [WORKFLOW_TOOL_BRAND]: true;
+ execute(
+ input: TInput,
+ ctx: WorkflowToolContext,
+ task: TaskExec,
+ ): Promise<TOutput> | AsyncIterable<unknown>;
+};
+
+/** A static tool whose executor runs as a durable workflow. */
+export type WorkflowToolDefinition<TInput = unknown, TOutput = unknown> =
+ | BlockingWorkflowToolDefinition<TInput, TOutput>
+ | BackgroundWorkflowToolDefinition<TInput, TOutput>;
+
+type Unbranded<T> = T extends unknown ? Omit<T, typeof WORKFLOW_TOOL_BRAND> : never;
+type BackgroundReturn<T> =
+ T extends AsyncGenerator<unknown, infer Output>
+ ? Output
+ : T extends AsyncIterable<unknown>
+ ? null
+ : Awaited<T>;
+type BackgroundDefinition<TInput, TReturn> = Omit<
+ BackgroundWorkflowToolDefinition<TInput, BackgroundReturn<TReturn>>,
+ typeof WORKFLOW_TOOL_BRAND | "execute"
+> & {
+ execute(input: TInput, ctx: WorkflowToolContext, task: TaskExec): TReturn;
+};
+
+type WorkflowReturn<T> = T extends AsyncIterable<infer Output> ? Output : Awaited<T>;
+type Schema = StandardSchemaV1<unknown, unknown> | StandardJSONSchemaV1<unknown, unknown>;
+type Definition<TInput, TReturn> = Omit<
+ BlockingWorkflowToolDefinition<TInput, WorkflowReturn<TReturn>>,
+ typeof WORKFLOW_TOOL_BRAND | "execute"
+> & {
+ execute(input: TInput, ctx: WorkflowToolContext): TReturn;
+};
+
+export function defineWorkflowTool<
+ TSchema extends Schema,
+ TReturn extends Promise<unknown> | AsyncIterable<unknown>,
+>(
+ definition: Omit<
+ BackgroundDefinition<StandardSchemaV1.InferOutput<TSchema>, TReturn>,
+ "inputSchema"
+ > & { inputSchema: TSchema },
+): BackgroundWorkflowToolDefinition<
+ StandardSchemaV1.InferOutput<TSchema>,
+ BackgroundReturn<TReturn>
+>;
+export function defineWorkflowTool<TReturn extends Promise<unknown> | AsyncIterable<unknown>>(
+ definition: BackgroundDefinition<Record<string, unknown>, TReturn> & { inputSchema: JsonObject },
+): BackgroundWorkflowToolDefinition<Record<string, unknown>, BackgroundReturn<TReturn>>;
+export function defineWorkflowTool<
+ TSchema extends Schema,
+ TReturn extends Promise<unknown> | AsyncIterable<unknown>,
+>(
+ definition: Omit<Definition<StandardSchemaV1.InferOutput<TSchema>, TReturn>, "inputSchema"> & {
+ inputSchema: TSchema;
+ },
+): BlockingWorkflowToolDefinition<StandardSchemaV1.InferOutput<TSchema>, WorkflowReturn<TReturn>>;
+export function defineWorkflowTool<TReturn extends Promise<unknown> | AsyncIterable<unknown>>(
+ definition: Definition<Record<string, unknown>, TReturn> & { inputSchema: JsonObject },
+): BlockingWorkflowToolDefinition<Record<string, unknown>, WorkflowReturn<TReturn>>;
+export function defineWorkflowTool<TInput = unknown, TOutput = unknown>(
+ definition: Unbranded<WorkflowToolDefinition<TInput, TOutput>>,
+): WorkflowToolDefinition<TInput, TOutput>;
+export function defineWorkflowTool<TInput, TOutput>(
+ definition: Unbranded<WorkflowToolDefinition<TInput, TOutput>>,
+): WorkflowToolDefinition<TInput, TOutput> {
+ stampToolDefinition(definition, "defineWorkflowTool");
+ return Object.assign(definition, { [WORKFLOW_TOOL_BRAND]: true as const });
+}
+
+export function isWorkflowToolDefinition(value: unknown): boolean {
+ return (
+ typeof value === "object" && value !== null && Reflect.get(value, WORKFLOW_TOOL_BRAND) === true
+ );
+}
diff --git a/packages/eve/test/scenarios/bin-build-output.scenario.test.ts b/packages/eve/test/scenarios/bin-build-output.scenario.test.ts
index 5227d126d..8e3eed12b 100644
--- a/packages/eve/test/scenarios/bin-build-output.scenario.test.ts
+++ b/packages/eve/test/scenarios/bin-build-output.scenario.test.ts
@@ -5,6 +5,7 @@ import { fileURLToPath } from "node:url";
import { describe, expect, it } from "vitest";
+import { useScenarioApp } from "../../src/internal/testing/scenario-app.js";
import { useTemporaryDirectories } from "../../src/internal/testing/use-temporary-app-roots.js";
const EVE_BIN_PATH = fileURLToPath(new URL("../../bin/eve.js", import.meta.url));
@@ -180,6 +181,8 @@ async function runEveBuild(appRoot: string): Promise<ProcessResult> {
}
describe("eve build process output", () => {
+ const scenarioApp = useScenarioApp();
+
it("prints successful build output to stdout", async () => {
const appRoot = await createTemporaryAppRoot({
prefix: "eve-bin-build-output-success-",
@@ -194,8 +197,13 @@ describe("eve build process output", () => {
}, 120_000);
it("bundles authored workflow tools into the server and driver output", async () => {
- const appRoot = await createTemporaryAppRoot({
- prefix: "eve-bin-build-output-workflow-tool-",
+ const { appRoot } = await scenarioApp({
+ files: {
+ "agent/agent.mjs": 'export default { model: "openai/gpt-5.4" };',
+ "agent/instructions.md": "You are a precise assistant.",
+ },
+ installDependencies: true,
+ name: "bin-build-output-workflow-tool",
});
await mkdir(join(appRoot, "agent", "tools"), { recursive: true });
await mkdir(join(appRoot, "agent", "lib"), { recursive: true });
@@ -214,10 +222,11 @@ describe("eve build process output", () => {
await writeFile(
join(appRoot, "agent", "tools", "deploy_service.mjs"),
[
+ 'import { defineWorkflowTool } from "eve/tools";',
'import { sleep } from "workflow";',
'import { hashPlan } from "../lib/plan.mjs";',
"",
- "export default {",
+ "export default defineWorkflowTool({",
' description: "Deploy a service.",',
' inputSchema: { type: "object", properties: { service: { type: "string" } } },',
" async execute({ service }) {",
@@ -226,7 +235,7 @@ describe("eve build process output", () => {
' await sleep("10ms");',
" return { digest };",
" },",
- "};",
+ "});",
"",
].join("\n"),
);
diff --git a/packages/eve/test/scenarios/dev-server-apps.scenario.test.ts b/packages/eve/test/scenarios/dev-server-apps.scenario.test.ts
index d7549fe7b..fdc6d4c9f 100644
--- a/packages/eve/test/scenarios/dev-server-apps.scenario.test.ts
+++ b/packages/eve/test/scenarios/dev-server-apps.scenario.test.ts
@@ -63,12 +63,12 @@ const WORKFLOW_TOOL_DESCRIPTOR: ScenarioAppDescriptor = {
"",
].join("\n"),
"agent/tools/deploy_service.ts": [
- 'import { defineTool } from "eve/tools";',
+ 'import { defineWorkflowTool } from "eve/tools";',
'import { sleep } from "workflow";',
'import { z } from "zod";',
'import { describePlan, hashPlan } from "../lib/deploy/plan.ts";',
"",
- "export default defineTool({",
+ "export default defineWorkflowTool({",
' description: "Deploy a service after planning it durably.",',
" inputSchema: z.object({ service: z.string() }),",
" async execute({ service }, ctx) {",
diff --git a/research/tools-as-workflows.md b/research/tools-as-workflows.md
index 559cb8e9b..2925993e5 100644
--- a/research/tools-as-workflows.md
+++ b/research/tools-as-workflows.md
@@ -1,243 +1,102 @@
---
issue: https://github.com/vercel/eve/issues/1084
status: implemented
-last_updated: "2026-08-31"
+last_updated: "2026-09-04"
---
# Tools as workflows
-## Summary
+`defineWorkflowTool` is the authoring boundary for durable tools, and its executor context owns
+`agent` and `ask`. The executor must explicitly start with `"use workflow"`; the definition
+selects the eve tool contract and the directive marks the function's replay semantics.
-A tool's `execute` may be a Workflow SDK workflow. eve starts one run per tool call and, by
-default, waits for it: the run's return value is the tool result, however long it takes. While the
-run waits on a hook, a webhook, or a sleep, the turn is parked and nothing is running. Mark the same
-tool `execution: "background"` and the model gets a receipt instead; eve wakes the agent with the
-return value when the run ends.
+## Authoring API
-Inside the tool, everything is the Workflow SDK: `"use workflow"`, `"use step"`, `createHook`,
-`createWebhook`, `sleep`, retries, replay. eve adds two things: `ask` from `eve/workflow`, a
-question the human on the session's channel answers, and `yield` from an async-generator body as a
-durable progress report. There is no `agent/workflows/` directory, no eve variant of the Workflow
-API, and no second durable runtime. The unit is the tool, not a workflow file.
-
-## Authoring shape
-
-```ts title="agent/tools/deploy.ts"
-import { defineTool } from "eve/tools";
-import { ask } from "eve/workflow";
+```ts
+import { defineWorkflowTool } from "eve/tools";
import { z } from "zod";
-export default defineTool({
- description: "Deploy a service to production. Pauses for a human to approve the plan.",
+export default defineWorkflowTool({
+ description: "Review and deploy a service after approval.",
inputSchema: z.object({ service: z.string() }),
async execute({ service }, ctx) {
"use workflow";
-
- const plan = await planDeploy(service);
- const answer = await ask(ctx, {
- prompt: `Deploy ${service}?\n\n${plan.summary}`,
+ const review = await ctx.agent({
+ key: "review",
+ target: "reviewer",
+ message: `Review ${service} for deployment.`,
+ });
+ const answer = await ctx.ask({
+ prompt: `Deploy ${service}?\n${JSON.stringify(review)}`,
display: "confirmation",
options: [
{ id: "approve", label: "Deploy", style: "primary" },
{ id: "cancel", label: "Cancel" },
],
});
-
- if (answer.optionId !== "approve") return { deployed: false, reason: "rejected" };
- return { deployed: true, url: await applyDeploy(plan) };
+ if (answer.optionId !== "approve") return { deployed: false };
+ return { deployed: true, service };
},
});
-
-async function planDeploy(service: string) {
- "use step";
- return computePlan(service);
-}
-
-async function applyDeploy(plan: DeployPlan) {
- "use step";
- return runDeploy(plan);
-}
-```
-
-### What is Workflow and what is eve
-
-Workflow SDK, unchanged:
-
-- `"use workflow"` as the first statement of `execute`, on its own line, makes it a durable body.
- eve hoists the method into a workflow function named after the tool. A top-level `async function`
- referenced as `execute: fn` works too.
-- `"use step"` functions may live in the tool module or any module it imports under the application
- root. They retry on failure and never re-run once their result is recorded.
-- `createHook`, `createWebhook`, `sleep`, `getWritable`, `getWorkflowMetadata`, and `FatalError`
- from `workflow` in the body; `start`, `getRun`, and `resumeHook` from `workflow/api` in steps. A
- body that calls `workflow/api` fails the build with the rule. Same types, same semantics, same
- version eve builds and runs.
-
-eve:
-
-- Starts exactly one run per tool call, keyed by session, turn, and call id. A retried harness
- step never starts a second run.
-- Awaits the run, or returns a receipt when `execution: "background"`.
-- Provides `ctx` inside the body.
-- Bridges run and session: `ask` and `yield`.
-- Maps the run's end onto the tool call: the return value is the result, a throw is a tool error,
- cancellation is a cancelled call.
-
-### `ctx` in a workflow body
-
-`ctx` is the same `ToolContext` type. Inside the body it carries `session`, `callId`, `toolName`,
-and `abortSignal`. The members that need the turn's process — `getSandbox`, `getSkill`, `getToken`,
-`requireAuth` — throw when touched, naming the member and what to do instead. Credentials are read
-from the environment inside the step that uses them; provider objects are not serializable and the
-turn's authorization context does not exist in a run.
-
-The tool's parsed input must be a JSON object, because it crosses the run's serialization boundary.
-Workflow bodies are for static tools under `agent/tools/`; tools returned from `defineDynamic`
-resolvers keep their callback contract.
-
-### Wait or run in the background
-
-| | default | `execution: "background"` |
-| ------------------------ | ----------------------------------- | ------------------------------------------- |
-| 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 |
-| cancel | cancelling the turn cancels the run | `task_cancel`, or the session ending |
-
-### Asking a human: `ask`
-
-```ts
-function ask(ctx: ToolContext, request: ToolInputRequest): Hook<ToolInputResponse>;
-
-interface ToolInputRequest {
- readonly prompt: string;
- readonly display?: "confirmation" | "select" | "text";
- readonly options?: readonly InputOption[];
- readonly allowFreeform?: boolean;
-}
-interface ToolInputResponse {
- readonly optionId?: string;
- readonly text?: string;
-}
```
-`ask` publishes the request as an `input.requested` event on the session, rendered the way channels
-already render `ask_question` and tool approvals, and returns the SDK hook the answer resumes — the
-way `createHook` returns one. It is synchronous on purpose: a `Hook` is thenable, so an async `ask`
-would adopt it and could only ever hand back the answer. Awaiting the hook suspends the run;
-`Promise.race([ask(ctx, q), sleep("4h")])` is a deadline.
-
-- The request belongs to the run, not the turn. It stays answerable until it is answered or the run
- ends; in a background tool that means long after the turn that started it.
-- A request is answered once. Ending the run withdraws its pending requests.
-- Several requests may be outstanding at once.
-- A response never steers. A new human message while a request is pending follows the session's
- normal `turnPolicy`.
-
-### Reporting progress: `yield`
-
-A 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. For a waiting tool a `yield` streams
-as an `action.partial` event, last-write-wins by call id, never in model history. For a background
-tool it wakes the owning agent with a note.
-
-### Cancelling: `ctx.abortSignal`
-
-Cancellation sends the run a control message. The body's `ctx.abortSignal` aborts — durably, so
-steps that received it observe the abort — and the run waits up to 30 seconds for the body to
-unwind through `finally`, then ends as cancelled whether or not it did. A body parked on a hook or a
-`sleep` does not observe the signal and is abandoned when the grace period ends. Ending the run
-withdraws its pending requests.
+The executor receives `WorkflowToolContext`: `session`, `callId`, `toolName`, `abortSignal`,
+`agent(input)`, and `ask(request)`. Ordinary `ToolContext`, channel contexts, and schedule contexts
+have no `agent` or `ask` methods. Shared helpers can accept `WorkflowToolContext` explicitly.
+The turn-owned `getSandbox`, `getSkill`, `getToken`, and `requireAuth` methods are absent from this
+public type. Side effects and credential reads belong in top-level `"use step"` helpers.
+
+Export `defineWorkflowTool({ ... })` directly as the default export of a static tool module.
+`execute` is an inline async function or async generator, or a reference to a top-level async
+function in the same module or an imported application module. With `execution: "background"`, the third executor argument is `task`; its `postMessage` method
+creates a yielded message descriptor. Schemas, approvals, and model-output projections have
+the same meaning as for the existing workflow tool runtime.
+
+## Compilation boundary
+
+The source pass validates directive placement and hoists inline executors into the shape consumed
+by the Workflow transform. Definition validation checks the compiled executor's `.workflowId`,
+so missing directives fail during compilation without recognizing the definer's import spelling.
+Discovery filters candidate files by directive text, then uses the same AST validation as the
+transform; directives can be the first statement on the function's opening line. Workflow IDs
+derive from the declaring module's application-relative path and function name, so migrating the
+wrapper does not rename an existing inline executor.
+
+The definition carries a workflow-tool brand. Compilation requires both that brand and a compiled
+executor workflow ID. An ordinary `defineTool` or bare object with a workflow executor fails the
+build; an uncompiled `defineWorkflowTool` also fails instead of running inline. Channel and
+schedule handlers cannot be workflow executors. Dynamic resolvers cannot return workflow tools.
+Standalone Workflow SDK functions used by workflow helpers retain their SDK semantics.
+
+The driver drops the definition and schema imports, then runs the registered executor with a
+context reconstructed for that run. `ctx.agent` and `ctx.ask` bind the existing invocation and
+input-request operations to that context. No callable helpers are serialized across the run
+boundary. This replaces call-site analysis with an explicit definition boundary and context types.
## Observable semantics
-One call, one result. A waiting tool's call resolves once, with the return value, the error, or a
-cancellation. A background tool's call resolves once, with the receipt; everything after arrives as
-separate session input.
-
-While a waiting tool runs, the turn is parked. A `queue` message waits for it. A `steer` message
-cancels the turn, which cancels the run, which withdraws its requests. Input responses never steer.
+Each tool call starts one durable run. By default the turn parks and the eventual return value,
+error, or cancellation resolves the model's tool call. With `execution: "background"`, the model
+receives a task receipt. Ordinary yields are stream-only progress; yielding
+`task.postMessage(message)` wakes the owning agent, as does completion.
-Background runs belong to the session. They survive turn completion and cancellation, appear in the
-session's task index, can be cancelled with `task_cancel`, and are cancelled when the session ends.
+`ctx.agent` delegates to a visible subagent. Its required `key` is unique within the run and keeps
+invocation identity stable across replay. `ctx.ask` publishes an input request on the session's
+channel and returns an awaitable answer. It can be raced against `sleep`; finishing or cancelling
+the run withdraws pending requests. The existing owner hooks and message protocol stay internal.
-Errors follow the SDK. A thrown error in a step retries per the step's policy; `FatalError` does
-not. An error that escapes the body fails the run: a tool error for a waiting tool, a failure
-notification for a background one.
+An async generator's `yield` reports progress. `ctx.abortSignal` remains durable and supports
+cleanup in steps after cancellation. Steps, retries, replay, and Workflow SDK primitives keep
+their existing behavior.
-Identity follows the tool. The workflow id derives from the tool's application-relative path, so
-renaming or moving the file creates a new workflow. Runs in flight finish on the deployment that
-started them; a run that resumes on a deployment without its tool fails with an error naming the
-missing workflow id.
+## Migration
-In development, editing a body, a step, or a module they import rebuilds the server, not only the
-module map: those sources are compiled into the workflow driver and the step registry.
-
-## Boundaries
-
-```
-turn / task (owner) workflow tool run
- inbox hook ──────── starts ───────────────▶ workflowToolRunWorkflow(execute)
- <inbox>:report ◀── yield ───────────────── body
- <inbox>:request ◀── ask (replyTo = answer) ─ body
- <inbox>:outcome ◀── return / throw / cancel body
- answer hook ─── input response ────────▶ ask's hook
- run's own hook ─── cancel ────────────────▶ ctx.abortSignal
-```
+- Replace `defineTool` with `defineWorkflowTool` for workflow tools and keep the executor's
+ `"use workflow"` directive.
+- Replace `agent(ctx, input)` with `ctx.agent(input)` and `ask(ctx, request)` with `ctx.ask(request)`.
+- Remove imports from `eve/workflow`; that entry point is removed. Import `WorkflowToolContext`,
+ `AgentInput`, `ToolInputRequest`, and `ToolInputResponse` from `eve/tools` when needed.
-The owner — the parked turn or the owning task — creates three hooks derived from its inbox token
-and passes their tokens to every run it starts. A run's own hook is its identity claim (a replayed
-start loses the claim and exits) and its control inbox. Each `ask` creates a fresh answer hook whose
-token the owner routes the human's response to directly. These tokens and message shapes are
-framework-internal; the authoring surface is `ask`, `yield`, and `ctx.abortSignal`.
-
-Directive discovery reads the syntax tree. Authored modules are compiled into the existing Workflow
-driver bundle with the module body kept, eve-definer default exports dropped, and unused imports
-stripped, so `defineTool` and the schema library never enter the driver. The compiler derives the
-body's workflow id from the tool's source and records it as the tool's compiled handling; the runtime
-prepares a `workflow-tool-call` dispatch target from it, the same path the task-control and
-self-agent tools take, so the harness parks the turn instead of calling `execute`.
-
-## Decisions made while implementing
-
-- No new flag. Waiting tools work out of the box; `execution: "background"` keeps requiring
- `experimental.tasks`.
-- Inputs are validated at start: a parsed input that is not a JSON object fails the call with a
- `TypeError` naming the tool.
-- `ask` returns the hook rather than a promise of the answer, so deadlines are `Promise.race` with
- the SDK's `sleep` and no timeout option exists. A standing question — one card answered
- repeatedly — is not supported: the channel request is retired on its first answer.
-- `workflow/api` keeps its SDK meaning and runs in steps; a body that calls it fails the driver
- build. An earlier draft aliased it to step wrappers inside the body, which made `start` return a
- run id where the types promised a `Run`.
-- Applications do not install the Workflow SDK. eve resolves `workflow` and `workflow/api` to its
- vendored copy everywhere authored code is bundled, and ships the types as `eve/workflow-modules`,
- an ambient declaration listed in the scaffolded tsconfig's `types`. An installed `workflow`
- package takes precedence for types if an application adds one.
-- The run-to-owner protocol (three owner hooks, `WorkflowToolRunRef`, message shapes) stayed internal. Nothing
- authored needs to construct those messages.
-
-## Open questions
-
-1. Channel UX for a parked tool call. Channels should be able to tell "waiting on a human or an
- external system" from "computing". A tool-call status, or inference from the pending request?
-2. Maximum wait. The session timeout is 30 days by default; hook and run retention have their own
- limits. What happens to a run, and its pending request, when the session expires first?
-3. Authorization from a run. Connection-backed `getToken` needs the turn's authorization context;
- a run-side equivalent would have to park the run on the existing authorization callback.
-4. Standing questions. Keeping a request answerable until the run ends would let `for await` over
- `ask`'s hook work; it needs the owner to keep the route and channels to keep the card live.
-
-## Validation
-
-Unit, integration, and scenario tests cover: directive placement and module-level rejection in
-`eve dev` and `eve build`; a waiting tool parking the turn and returning one result; a thrown error
-as a tool error; a human answer resuming the body; a deadline winning a race against an unanswered
-`ask`; cancelling the waiting turn cancelling the run; a background tool's receipt, progress, and
-completion wake; a background question answered after its turn ended; and the development host
-fingerprint following step helpers. The `agent-workflow-tools` e2e fixture runs the same flows
-through the CLI with a mock model.
-
-Not yet covered: the Vercel and custom worlds (the suites run the local world), `createWebhook`
-end to end, and session expiry while a run is parked.
+This is a breaking public API change. The existing workflow-tool fixture migrates to the new API
+and continues to cover delegation, human answers, deadlines, progress, background execution, and
+cancellation. Compiler tests cover the new entry point and rejection of the old authoring shapes.