Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat(eve): run tool execute bodies as durable workflows (#2477)

Casey Gowrieb7321c98542c
diff --git a/.changeset/durable-workflow-tools.md b/.changeset/durable-workflow-tools.md
new file mode 100644
index 000000000..58edf2b34
--- /dev/null
+++ b/.changeset/durable-workflow-tools.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+A tool's `execute` can now be a Workflow body: start it with `"use workflow"`, write helpers as `"use step"` functions, and use `createHook`, `createWebhook`, and `sleep` from `workflow` in the body and `start`, `getRun`, and `resumeHook` from `workflow/api` in steps. eve runs each call as a durable run and, by default, parks the turn until it returns. Import `ask` from `eve/workflow` to ask the human on the channel — it returns the hook the answer resumes, so it can be awaited or raced against a `sleep` deadline — and the request stays answerable even after the turn that started it ended. A workflow body may be an async generator whose `yield`s are durable progress. `ctx.abortSignal` aborts on cancellation, and the run waits a grace period for steps to stop and `finally` to clean up. With `execution: "background"` the model gets a receipt and is woken with the result. eve also serves the Workflow webhook route so `createWebhook()` URLs work.
diff --git a/docs/tools/meta.json b/docs/tools/meta.json
index 981a49cdc..b6f3245ee 100644
--- a/docs/tools/meta.json
+++ b/docs/tools/meta.json
@@ -1,5 +1,5 @@
{
"title": "Tools",
"defaultOpen": false,
- "pages": ["overview", "human-in-the-loop"]
+ "pages": ["overview", "human-in-the-loop", "workflows"]
}
diff --git a/docs/tools/overview.mdx b/docs/tools/overview.mdx
index 7513490a0..9d1839fb0 100644
--- a/docs/tools/overview.mdx
+++ b/docs/tools/overview.mdx
@@ -78,6 +78,13 @@ 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.
+### Durable tools
+
+A tool whose `execute` starts with `"use workflow"` runs as a durable Workflow run instead of
+inside the model step. It can wait for a person, a webhook, or a timer for as long as it takes, with
+nothing running in between, and its return value still settles the tool call. See
+[Durable tools](/docs/tools/workflows).
+
### The `ctx` parameter
`execute` gets a `ctx` carrying the runtime accessors:
diff --git a/docs/tools/workflows.mdx b/docs/tools/workflows.mdx
new file mode 100644
index 000000000..fd7b62e86
--- /dev/null
+++ b/docs/tools/workflows.mdx
@@ -0,0 +1,288 @@
+---
+title: "Durable Tools"
+description: "Write a tool as a workflow so it can wait for a person, a webhook, or a timer for as long as it takes, with nothing running in between."
+url: /tools/workflows
+---
+
+A tool's `execute` may be a workflow. eve starts one durable 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 person, 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.
+
+Inside the tool, everything is the [Workflow SDK](https://workflow-sdk.dev): `"use workflow"`,
+`"use step"`, `createHook`, `createWebhook`, `sleep`, retries, replay. eve adds `ask` from
+`eve/workflow` — a question the human on the session's channel answers — and treats each `yield` as
+a durable progress report.
+
+## Write one
+
+```ts title="agent/tools/deploy.ts"
+import { defineTool } from "eve/tools";
+import { ask } from "eve/workflow";
+import { z } from "zod";
+
+export default defineTool({
+ 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, {
+ prompt: `Deploy ${service}?\n\n${plan.summary}`,
+ 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) };
+ },
+});
+
+async function planDeploy(service: string) {
+ "use step";
+ return computePlan(service);
+}
+
+async function applyDeploy(plan: DeployPlan) {
+ "use step";
+ return runDeploy(plan);
+}
+```
+
+The model calls `deploy`. The turn parks while the human reads the plan. When they answer, minutes
+or days later, the run resumes, deploys, and returns. The model sees one tool result.
+
+### 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`.
+- `"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 in a step instead.
+- The tool's input must be a JSON object. Workflow bodies are for static tools under `agent/tools/`,
+ not tools returned from `defineDynamic` resolvers.
+
+## 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 |
+
+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 require
+`experimental.tasks` on the root agent, like every background tool.
+
+## Ask a human: `ask`
+
+```ts
+import { ask } from "eve/workflow";
+
+const answer = await ask(ctx, {
+ prompt: string,
+ display?: "confirmation" | "select" | "text",
+ options?: { id: string; label: string; description?: string; style?: "primary" | "danger" | "default" }[],
+ allowFreeform?: boolean,
+}); // { 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:
+
+```ts
+const pending = ask(ctx, { prompt: `Deploy ${service}?`, options: APPROVE_OR_CANCEL });
+const answer = await Promise.race([pending, sleep("4h")]);
+if (answer === undefined) return { deployed: false, reason: "timed out" };
+```
+
+- 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. Ask again for the next answer.
+- Ending the run, by returning, throwing, or cancellation, withdraws its pending requests.
+- Several requests may be outstanding at once.
+- A response never steers. A new human message while a request is pending follows the session's
+ 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.
+
+## Report progress: `yield`
+
+A workflow body may be an async generator. Each `yield` is a durable progress snapshot; the return
+value is the result, or the last `yield` when the body returns nothing.
+
+```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) };
+}
+```
+
+For a waiting tool each `yield` streams as an `action.partial` event, last-write-wins by tool call
+id, and never enters model history — the same contract as an in-process generator tool. For a
+background tool each `yield` wakes the owning agent with a note. Returning ends the run with the
+result; throwing ends it with the failure.
+
+## Cancel and clean up: `ctx.abortSignal`
+
+`ctx.abortSignal` aborts when the run is cancelled: a steered turn for a waiting tool, `task_cancel`
+or the session ending for a background one. It is durable — it survives replay, and a step that
+receives it observes the abort. Pass it into the steps that should stop, and clean up in
+`try/finally`:
+
+```ts
+async execute({ projectId }, ctx) {
+ "use workflow";
+ const jobId = await submitRender(projectId);
+ try {
+ return await waitForRender(jobId, ctx.abortSignal);
+ } finally {
+ if (ctx.abortSignal.aborted) await abortRender(jobId);
+ }
+}
+```
+
+After the signal fires, the run waits up to 30 seconds for the body to finish unwinding, then ends
+as cancelled whether or not it did. A body parked on a hook or a `sleep` does not observe the signal;
+it is abandoned when the grace period ends. Steps that received the signal are how you clean up
+first.
+
+## Flows
+
+### Approve with a deadline and an escalation
+
+```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 });
+
+ let answer = await Promise.race([pending, sleep("4h")]);
+ if (answer === undefined) {
+ await pageOnCall(service);
+ answer = await Promise.race([pending, sleep("20h")]);
+ }
+
+ if (answer === undefined) return { deployed: false, reason: "timed out" };
+ if (answer.optionId !== "approve") return { deployed: false, reason: "rejected" };
+ return { deployed: true, url: await applyDeploy(plan) };
+}
+```
+
+One request stays on the channel the whole time. `sleep` is the deadline, `pageOnCall` is a step,
+and returning withdraws the request.
+
+### Wait for an external system to call back
+
+```ts
+import { createWebhook, FatalError } from "workflow";
+
+export default defineTool({
+ 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;
+ const { status, url } = await callback.json();
+
+ if (status !== "ok") throw new FatalError(`Render ${jobId} failed: ${status}`);
+ return { url };
+ },
+});
+```
+
+`createWebhook` mints a URL under `/.well-known/workflow/v1/webhook/` that eve serves. The external
+system posts to it when it is done. Nothing runs in between.
+
+### Ask now, act when answered
+
+```ts
+import { ask } from "eve/workflow";
+
+export default defineTool({
+ 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, {
+ prompt: `Refund $${amount} on order ${orderId}?`,
+ display: "confirmation",
+ options: [
+ { id: "approve", label: "Refund", style: "primary" },
+ { id: "deny", label: "Deny" },
+ ],
+ });
+
+ if (decision.optionId !== "approve") return { refunded: false };
+ return { refunded: true, receipt: await issueRefund(orderId, amount) };
+ },
+});
+```
+
+The model reports that approval is pending and the conversation continues. The approval card stays
+on the channel. When it is answered, the refund runs and the agent is woken with the outcome.
+
+### Remind me later
+
+```ts
+import { sleep } from "workflow";
+
+export default defineTool({
+ description: "Remind the user about something after a delay.",
+ inputSchema: z.object({ note: z.string(), delay: z.string() }),
+ execution: "background",
+ async execute({ note, delay }) {
+ "use workflow";
+ await sleep(delay);
+ return { reminder: note };
+ },
+});
+```
+
+The session parks between the receipt and the wake. The agent receives the return value and relays
+it.
+
+## 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.
+
+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.
+
+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
+resumes on a deployment without its tool fails with an error naming the missing workflow.
diff --git a/e2e/fixtures/agent-workflow-tools/agent/agent.ts b/e2e/fixtures/agent-workflow-tools/agent/agent.ts
new file mode 100644
index 000000000..52d2aa5a8
--- /dev/null
+++ b/e2e/fixtures/agent-workflow-tools/agent/agent.ts
@@ -0,0 +1,59 @@
+import { e2eAgentConfig } from "@eve-e2e/config";
+import { defineAgent } from "eve";
+import { mockModel, type MockModelRequest, type MockModelResponse } from "eve/evals";
+
+/**
+ * Deterministic script: each directive names the workflow tool to call with
+ * service "api"; once the turn holds a tool result the reply echoes it.
+ */
+function respond(request: MockModelRequest): MockModelResponse | string {
+ const message = [...request.userMessages].reverse().find((entry) => entry.trim() !== "") ?? "";
+ const roles = request.messages.map((entry) => entry.role);
+ const turnHasToolResult = roles.lastIndexOf("tool") > roles.lastIndexOf("user");
+
+ for (const [directive, tool] of [
+ ["WORKFLOW-DEPLOY-START", "deploy_service"],
+ ["WORKFLOW-CONFIRM-START", "confirm_deploy"],
+ ["WORKFLOW-REPORT-START", "report_deploy"],
+ ["WORKFLOW-ESCALATE-START", "escalate_deploy"],
+ ["WORKFLOW-HOLD-START", "hold_deploy"],
+ ["WORKFLOW-FANOUT-START", "fanout_deploy"],
+ ] as const) {
+ if (!message.includes(directive)) continue;
+ if (!turnHasToolResult) {
+ return { toolCalls: [{ input: { service: "api" }, name: tool }] };
+ }
+ const output = [...request.toolResults]
+ .reverse()
+ .find((result) => result.name === tool)?.output;
+ return `${directive.replace("-START", "-RESULT")} ${
+ typeof output === "string" ? output : JSON.stringify(output ?? null)
+ }`;
+ }
+
+ if (message.includes("update: WORKFLOW-REPORT-PROGRESS")) {
+ return "WORKFLOW-REPORT-UPDATE-RECEIVED";
+ }
+ if (message.includes("is completed") && message.includes("WORKFLOW-REPORT-COMPLETE")) {
+ return "WORKFLOW-REPORT-DONE";
+ }
+ if (message.startsWith("Background task ")) {
+ return "WORKFLOW-REPORT-ACK";
+ }
+
+ return "WORKFLOW-IDLE";
+}
+
+const base = e2eAgentConfig({ mock: respond });
+
+export default defineAgent({
+ ...base,
+ experimental: {
+ ...base.experimental,
+ tasks: true,
+ },
+ // Always author the deterministic script so this fixture never depends on a
+ // live model; world suites already set EVE_E2E_MODEL=mock.
+ model: mockModel(respond),
+ modelContextWindowTokens: base.modelContextWindowTokens ?? 1_000_000,
+});
diff --git a/e2e/fixtures/agent-workflow-tools/agent/instructions.md b/e2e/fixtures/agent-workflow-tools/agent/instructions.md
new file mode 100644
index 000000000..ee8a1d3ac
--- /dev/null
+++ b/e2e/fixtures/agent-workflow-tools/agent/instructions.md
@@ -0,0 +1 @@
+You are a test agent for workflow tools. Follow the mock model script.
diff --git a/e2e/fixtures/agent-workflow-tools/agent/lib/fanout.ts b/e2e/fixtures/agent-workflow-tools/agent/lib/fanout.ts
new file mode 100644
index 000000000..020f07b89
--- /dev/null
+++ b/e2e/fixtures/agent-workflow-tools/agent/lib/fanout.ts
@@ -0,0 +1,39 @@
+import { resumeHook, start } from "workflow/api";
+
+import { describePlan, hashPlan } from "./plan.ts";
+
+export interface ReplicaInput {
+ readonly replica: number;
+ readonly replyTo: string;
+ readonly service: string;
+}
+
+export interface ReplicaResult {
+ readonly digest: string;
+ readonly replica: number;
+}
+
+/**
+ * A standalone workflow the fan-out tool starts once per replica. It reports
+ * its result to the reply hook the caller passed in.
+ */
+export async function planReplica(input: ReplicaInput): Promise<void> {
+ "use workflow";
+
+ const digest = await hashPlan(`${describePlan(input.service)} #${input.replica}`);
+ await reportReplica(input.replyTo, { digest, replica: input.replica });
+}
+
+/** `workflow/api` runs in steps; a body starts a child run through one. */
+export async function startReplica(input: ReplicaInput): Promise<string> {
+ "use step";
+
+ const run = await start(planReplica, [input]);
+ return run.runId;
+}
+
+async function reportReplica(replyTo: string, result: ReplicaResult): Promise<void> {
+ "use step";
+
+ await resumeHook(replyTo, result);
+}
diff --git a/e2e/fixtures/agent-workflow-tools/agent/lib/plan.ts b/e2e/fixtures/agent-workflow-tools/agent/lib/plan.ts
new file mode 100644
index 000000000..378cf01e0
--- /dev/null
+++ b/e2e/fixtures/agent-workflow-tools/agent/lib/plan.ts
@@ -0,0 +1,11 @@
+import { createHash } from "node:crypto";
+
+export function describePlan(service: string): string {
+ return `deploy ${service}`;
+}
+
+/** Hashing is a step: it runs in the app runtime and its result is recorded once. */
+export async function hashPlan(plan: string): Promise<string> {
+ "use step";
+ return createHash("sha256").update(plan).digest("hex").slice(0, 12);
+}
diff --git a/e2e/fixtures/agent-workflow-tools/agent/tools/confirm_deploy.ts b/e2e/fixtures/agent-workflow-tools/agent/tools/confirm_deploy.ts
new file mode 100644
index 000000000..46398d917
--- /dev/null
+++ b/e2e/fixtures/agent-workflow-tools/agent/tools/confirm_deploy.ts
@@ -0,0 +1,27 @@
+import { defineTool } from "eve/tools";
+import { ask } from "eve/workflow";
+import { z } from "zod";
+
+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({
+ 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, {
+ display: "confirmation",
+ options: [
+ { id: "approve", label: "Deploy", style: "primary" },
+ { id: "cancel", label: "Cancel" },
+ ],
+ prompt: `Apply ${describePlan(service)}?`,
+ });
+ return { approved: answer.optionId === "approve", service };
+ },
+});
diff --git a/e2e/fixtures/agent-workflow-tools/agent/tools/deploy_service.ts b/e2e/fixtures/agent-workflow-tools/agent/tools/deploy_service.ts
new file mode 100644
index 000000000..149c1fd4e
--- /dev/null
+++ b/e2e/fixtures/agent-workflow-tools/agent/tools/deploy_service.ts
@@ -0,0 +1,22 @@
+import { defineTool } from "eve/tools";
+import { sleep } from "workflow";
+import { z } from "zod";
+
+import { describePlan, hashPlan } from "../lib/plan.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({
+ 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 };
+ },
+});
diff --git a/e2e/fixtures/agent-workflow-tools/agent/tools/escalate_deploy.ts b/e2e/fixtures/agent-workflow-tools/agent/tools/escalate_deploy.ts
new file mode 100644
index 000000000..ef2e303cb
--- /dev/null
+++ b/e2e/fixtures/agent-workflow-tools/agent/tools/escalate_deploy.ts
@@ -0,0 +1,32 @@
+import { defineTool } from "eve/tools";
+import { ask } from "eve/workflow";
+import { sleep } from "workflow";
+import { z } from "zod";
+
+import { describePlan } from "../lib/plan.ts";
+
+/**
+ * `ask` returns the hook, so the question can be raced against a deadline: if
+ * nobody answers before the sleep, the run withdraws the request and returns
+ * a timeout instead of parking forever.
+ */
+export default defineTool({
+ 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, {
+ display: "confirmation",
+ options: [
+ { id: "approve", label: "Deploy", style: "primary" },
+ { id: "cancel", label: "Cancel" },
+ ],
+ prompt: `Apply ${describePlan(service)}?`,
+ });
+
+ const answer = await Promise.race([pending, sleep("10m")]);
+ if (answer === undefined) return { decided: "timed out", service };
+ return { decided: answer.optionId === "approve" ? "approved" : "rejected", service };
+ },
+});
diff --git a/e2e/fixtures/agent-workflow-tools/agent/tools/fanout_deploy.ts b/e2e/fixtures/agent-workflow-tools/agent/tools/fanout_deploy.ts
new file mode 100644
index 000000000..fd1ddc950
--- /dev/null
+++ b/e2e/fixtures/agent-workflow-tools/agent/tools/fanout_deploy.ts
@@ -0,0 +1,25 @@
+import { defineTool } from "eve/tools";
+import { createHook } from "workflow";
+import { z } from "zod";
+
+import { type ReplicaResult, startReplica } from "../lib/fanout.ts";
+
+/**
+ * Starts a fan-out of child workflow runs from inside a body and collects
+ * their results on reply hooks. Exercises `start` and `resumeHook` from
+ * steps across the run boundary.
+ */
+export default defineTool({
+ description: "Plan several deploy replicas in parallel and combine their digests.",
+ inputSchema: z.strictObject({ service: z.string() }),
+ async execute({ service }) {
+ "use workflow";
+
+ const replies = [0, 1].map(() => createHook<ReplicaResult>());
+ await Promise.all(
+ replies.map((reply, replica) => startReplica({ replica, replyTo: reply.token, service })),
+ );
+ const replicas = await Promise.all(replies.map((reply) => reply));
+ return { replicas };
+ },
+});
diff --git a/e2e/fixtures/agent-workflow-tools/agent/tools/hold_deploy.ts b/e2e/fixtures/agent-workflow-tools/agent/tools/hold_deploy.ts
new file mode 100644
index 000000000..b1f4ac5b4
--- /dev/null
+++ b/e2e/fixtures/agent-workflow-tools/agent/tools/hold_deploy.ts
@@ -0,0 +1,17 @@
+import { defineTool } from "eve/tools";
+import { sleep } from "workflow";
+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({
+ 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
new file mode 100644
index 000000000..325c7ec63
--- /dev/null
+++ b/e2e/fixtures/agent-workflow-tools/agent/tools/report_deploy.ts
@@ -0,0 +1,22 @@
+import { defineTool } from "eve/tools";
+import { z } from "zod";
+
+import { describePlan, hashPlan } from "../lib/plan.ts";
+
+/**
+ * Background workflow tool: the model gets a receipt, each `yield` is a
+ * durable progress note, and the agent is woken with the return value.
+ */
+export default defineTool({
+ description: "Plan a deploy in the background and report when it is ready.",
+ execution: "background",
+ inputSchema: z.strictObject({ service: z.string() }),
+ async *execute({ service }) {
+ "use workflow";
+
+ const plan = describePlan(service);
+ yield `WORKFLOW-REPORT-PROGRESS ${plan}`;
+ const digest = await hashPlan(plan);
+ return { digest, plan, result: "WORKFLOW-REPORT-COMPLETE" };
+ },
+});
diff --git a/e2e/fixtures/agent-workflow-tools/evals/confirm-deploy.hitl.eval.ts b/e2e/fixtures/agent-workflow-tools/evals/confirm-deploy.hitl.eval.ts
new file mode 100644
index 000000000..c942c586e
--- /dev/null
+++ b/e2e/fixtures/agent-workflow-tools/evals/confirm-deploy.hitl.eval.ts
@@ -0,0 +1,31 @@
+import { defineEval } from "eve/evals";
+
+export default defineEval({
+ description:
+ "A workflow tool asks the human mid-body; the answer resumes the run and the result settles the call.",
+ async test(t) {
+ const parked = await t.send("WORKFLOW-CONFIRM-START");
+ t.requireInputRequest({
+ display: "confirmation",
+ optionIds: ["approve", "cancel"],
+ toolName: "confirm_deploy",
+ });
+ parked.calledTool("confirm_deploy", { status: "pending", count: 1 });
+
+ const approved = await t.respondAll("approve");
+ approved.expectOk();
+ approved.event("action.result", {
+ count: 1,
+ data: {
+ result: {
+ kind: "tool-result",
+ output: /"approved":true/u,
+ toolName: "confirm_deploy",
+ },
+ status: "completed",
+ },
+ });
+ approved.messageIncludes("WORKFLOW-CONFIRM-RESULT");
+ t.noFailedActions();
+ },
+});
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
new file mode 100644
index 000000000..13f39241e
--- /dev/null
+++ b/e2e/fixtures/agent-workflow-tools/evals/deploy-service.wait.eval.ts
@@ -0,0 +1,19 @@
+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.",
+ async test(t) {
+ const turn = await t.send("WORKFLOW-DEPLOY-START");
+ turn.expectOk();
+ turn.calledTool("deploy_service", {
+ output: /"plan":"deploy api"/u,
+ });
+ turn.calledTool("deploy_service", {
+ output: /"tool":"deploy_service"/u,
+ });
+ turn.messageIncludes("WORKFLOW-DEPLOY-RESULT");
+ turn.messageIncludes("deploy api");
+ t.noFailedActions();
+ },
+});
diff --git a/e2e/fixtures/agent-workflow-tools/evals/escalate-deploy.deadline.eval.ts b/e2e/fixtures/agent-workflow-tools/evals/escalate-deploy.deadline.eval.ts
new file mode 100644
index 000000000..d6e1e0188
--- /dev/null
+++ b/e2e/fixtures/agent-workflow-tools/evals/escalate-deploy.deadline.eval.ts
@@ -0,0 +1,26 @@
+import { defineEval } from "eve/evals";
+
+/**
+ * `ask` returns the hook, so the question composes with `Promise.race` — here
+ * against a long deadline. The human answers, the race resolves to their
+ * choice, and the run settles the call.
+ */
+export default defineEval({
+ description:
+ "A workflow tool races ask against a deadline; the answer wins and settles the call.",
+ async test(t) {
+ const parked = await t.send("WORKFLOW-ESCALATE-START");
+ t.requireInputRequest({
+ display: "confirmation",
+ optionIds: ["approve", "cancel"],
+ toolName: "escalate_deploy",
+ });
+ parked.calledTool("escalate_deploy", { status: "pending", count: 1 });
+
+ const answered = await t.respondAll("approve");
+ answered.expectOk();
+ answered.calledTool("escalate_deploy", { output: /"decided":"approved"/u });
+ answered.messageIncludes("WORKFLOW-ESCALATE-RESULT");
+ t.noFailedActions();
+ },
+});
diff --git a/e2e/fixtures/agent-workflow-tools/evals/evals.config.ts b/e2e/fixtures/agent-workflow-tools/evals/evals.config.ts
new file mode 100644
index 000000000..cc97a613b
--- /dev/null
+++ b/e2e/fixtures/agent-workflow-tools/evals/evals.config.ts
@@ -0,0 +1,8 @@
+import { defineEvalConfig } from "eve/evals";
+
+export default defineEvalConfig({
+ // Workflow tools dispatch durable runs; serialize so the runs are never
+ // starved past the per-eval timeout.
+ maxConcurrency: 1,
+ timeoutMs: 120_000,
+});
diff --git a/e2e/fixtures/agent-workflow-tools/evals/fanout-deploy.eval.ts b/e2e/fixtures/agent-workflow-tools/evals/fanout-deploy.eval.ts
new file mode 100644
index 000000000..78dcf1602
--- /dev/null
+++ b/e2e/fixtures/agent-workflow-tools/evals/fanout-deploy.eval.ts
@@ -0,0 +1,17 @@
+import { defineEval } from "eve/evals";
+
+/**
+ * A workflow body starts a fan-out of child runs through a `start` step and
+ * collects their results on reply hooks. Both replicas come back.
+ */
+export default defineEval({
+ description: "A workflow tool starts child workflow runs and combines their results.",
+ async test(t) {
+ const turn = await t.send("WORKFLOW-FANOUT-START");
+ turn.expectOk();
+ turn.calledTool("fanout_deploy", { output: /"replica":0/u });
+ turn.calledTool("fanout_deploy", { output: /"replica":1/u });
+ turn.messageIncludes("WORKFLOW-FANOUT-RESULT");
+ t.noFailedActions();
+ },
+});
diff --git a/e2e/fixtures/agent-workflow-tools/evals/hold-deploy.cancel.eval.ts b/e2e/fixtures/agent-workflow-tools/evals/hold-deploy.cancel.eval.ts
new file mode 100644
index 000000000..8c66ddee3
--- /dev/null
+++ b/e2e/fixtures/agent-workflow-tools/evals/hold-deploy.cancel.eval.ts
@@ -0,0 +1,40 @@
+import { defineEval } from "eve/evals";
+import { satisfies } from "eve/evals/expect";
+
+/**
+ * Cancelling the turn cancels the workflow tool run holding it open. The turn
+ * settles as cancelled followed by session.waiting, with no failure events,
+ * and the session keeps taking messages.
+ */
+export default defineEval({
+ timeoutMs: 60_000,
+ description: "Steering a turn cancels the workflow tool run it is parked on.",
+ async test(t) {
+ const live = await t.start("WORKFLOW-HOLD-START");
+ await live.waitForEvent("actions.requested", {
+ data: {
+ actions: (actions) =>
+ actions.some((action) => "toolName" in action && action.toolName === "hold_deploy"),
+ },
+ });
+
+ const cancelled = await live.cancel();
+ await t.require(
+ cancelled,
+ satisfies(
+ (value: typeof cancelled) => value.status === "accepted",
+ "cancel request is accepted",
+ ),
+ );
+
+ const turn = await live.result();
+ turn.event("turn.cancelled", { count: 1 });
+ turn.eventOrder([{ type: "turn.cancelled" }, { type: "session.waiting" }]);
+ turn.notEvent("turn.failed");
+ turn.notEvent("session.failed");
+
+ const next = await t.send("WORKFLOW-IDLE-PING");
+ next.expectOk();
+ next.messageIncludes("WORKFLOW-IDLE");
+ },
+});
diff --git a/e2e/fixtures/agent-workflow-tools/evals/report-deploy.background.eval.ts b/e2e/fixtures/agent-workflow-tools/evals/report-deploy.background.eval.ts
new file mode 100644
index 000000000..08f3178ef
--- /dev/null
+++ b/e2e/fixtures/agent-workflow-tools/evals/report-deploy.background.eval.ts
@@ -0,0 +1,83 @@
+import { defineEval } from "eve/evals";
+import { satisfies } from "eve/evals/expect";
+
+export default defineEval({
+ description:
+ "A background workflow tool returns a receipt, reports progress, and wakes the agent with its result.",
+ async test(t) {
+ const started = await t.send("WORKFLOW-REPORT-START");
+ started.expectOk();
+ started.calledTool("report_deploy");
+
+ const receipt = started.requireToolCall("report_deploy");
+ const taskId = readTaskId(receipt.output);
+ if (taskId === undefined) throw new Error("report_deploy receipt is missing taskId.");
+
+ const sessionId = t.sessionId;
+ if (sessionId === undefined) throw new Error("Eval has no parent session id.");
+
+ const updateLive = t.target.watchTurn(sessionId, {
+ startIndex: requireStreamIndex(t, "update wait"),
+ });
+ const updateTurn = await updateLive.result();
+ updateTurn.expectOk();
+ updateTurn.messageIncludes("WORKFLOW-REPORT-UPDATE-RECEIVED");
+ await t.require(
+ updateTurn.events,
+ satisfies(
+ (events: typeof updateTurn.events) =>
+ events.some(
+ (event) =>
+ event.type === "message.received" &&
+ messageText(event.data.message).includes(
+ `Background task ${taskId} (report_deploy) update: WORKFLOW-REPORT-PROGRESS deploy api`,
+ ),
+ ),
+ "parent receives the run's progress note with task identity",
+ ),
+ );
+
+ const doneLive = t.target.watchTurn(sessionId, {
+ startIndex: requireStreamIndex(updateLive.session, "completion wait"),
+ });
+ const doneTurn = await doneLive.result();
+ doneTurn.expectOk();
+ doneTurn.messageIncludes("WORKFLOW-REPORT-DONE");
+ await t.require(
+ doneTurn.events,
+ satisfies(
+ (events: typeof doneTurn.events) =>
+ events.some(
+ (event) =>
+ event.type === "message.received" &&
+ messageText(event.data.message).includes(
+ `Background task ${taskId} (report_deploy) is completed.`,
+ ) &&
+ messageText(event.data.message).includes("WORKFLOW-REPORT-COMPLETE"),
+ ),
+ "parent receives the run's return value with task identity",
+ ),
+ );
+ t.noFailedActions();
+ },
+});
+
+function readTaskId(output: unknown): string | undefined {
+ if (output === null || typeof output !== "object") return undefined;
+ const taskId = Reflect.get(output, "taskId");
+ return typeof taskId === "string" ? taskId : undefined;
+}
+
+function requireStreamIndex(
+ session: { readonly state?: { readonly streamIndex?: number } },
+ operation: string,
+): number {
+ const streamIndex = session.state?.streamIndex;
+ if (streamIndex === undefined) throw new Error(`${operation} has no session stream index.`);
+ return streamIndex;
+}
+
+function messageText(message: unknown): string {
+ if (typeof message === "string") return message;
+ return JSON.stringify(message);
+}
diff --git a/e2e/fixtures/agent-workflow-tools/package.json b/e2e/fixtures/agent-workflow-tools/package.json
new file mode 100644
index 000000000..9e7d8a39d
--- /dev/null
+++ b/e2e/fixtures/agent-workflow-tools/package.json
@@ -0,0 +1,23 @@
+{
+ "name": "agent-workflow-tools",
+ "version": "0.0.0",
+ "private": true,
+ "type": "module",
+ "scripts": {
+ "build": "eve build",
+ "dev": "eve dev",
+ "start": "eve start",
+ "typecheck": "eve build && tsc",
+ "test:e2e": "eve eval --strict"
+ },
+ "dependencies": {
+ "@eve-e2e/config": "workspace:*",
+ "@workflow/world-postgres": "catalog:",
+ "eve": "workspace:*",
+ "zod": "catalog:"
+ },
+ "devDependencies": {
+ "@types/node": "catalog:",
+ "typescript": "catalog:"
+ }
+}
diff --git a/e2e/fixtures/agent-workflow-tools/tsconfig.json b/e2e/fixtures/agent-workflow-tools/tsconfig.json
new file mode 100644
index 000000000..f825104a4
--- /dev/null
+++ b/e2e/fixtures/agent-workflow-tools/tsconfig.json
@@ -0,0 +1,18 @@
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ "module": "esnext",
+ "moduleResolution": "bundler",
+ "outDir": "dist",
+ "rootDir": ".",
+ "strict": true,
+ "esModuleInterop": true,
+ "skipLibCheck": true,
+ "forceConsistentCasingInFileNames": true,
+ "declaration": false,
+ "noEmit": true,
+ "types": ["node", "eve/workflow-modules"],
+ "allowImportingTsExtensions": true
+ },
+ "include": ["agent/**/*.ts", "evals/**/*.ts"]
+}
diff --git a/packages/eve/extension-contracts/compatibility/tool/v23.ts b/packages/eve/extension-contracts/compatibility/tool/v23.ts
new file mode 100644
index 000000000..ce4b8a817
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/tool/v23.ts
@@ -0,0 +1,12 @@
+import { z } from "zod";
+
+import { defineTool, toolOutput } from "#public/tools/index.js";
+
+export default defineTool({
+ description: "Look up a service and project a short summary for the model.",
+ inputSchema: z.object({ service: z.string() }),
+ execute({ service }, ctx) {
+ return { callId: ctx.callId, service, status: "healthy" };
+ },
+ toModelOutput: (output) => toolOutput.text(`${output.service} is ${output.status}`),
+});
diff --git a/packages/eve/extension-contracts/reports/tool/v24.json b/packages/eve/extension-contracts/reports/tool/v24.json
new file mode 100644
index 000000000..a5f32080f
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/tool/v24.json
@@ -0,0 +1,19 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "tool",
+ "epoch": 24,
+ "sha256": "b0f4d9d3de6db28e98df892c10853abc6df7e7465d9613666f6c2687766ea8a8",
+ "exports": [
+ "defaultWebSearch",
+ "defineTool",
+ "disableTool",
+ "experimental_workflow",
+ "isDisabledToolSentinel",
+ "isExperimentalWorkflowToolDefinition",
+ "isWebSearchToolDefinition",
+ "toolOutput",
+ "toolOutputPart",
+ "toolResultFrom",
+ "webSearch"
+ ]
+}
diff --git a/packages/eve/package.json b/packages/eve/package.json
index 2371f3773..18564fc9b 100644
--- a/packages/eve/package.json
+++ b/packages/eve/package.json
@@ -181,6 +181,16 @@
"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"
+ },
"./models/openai": {
"types": "./dist/src/public/models/openai/index.d.ts",
"import": "./dist/src/public/models/openai/index.js",
@@ -438,6 +448,7 @@
"@vercel/sandbox-delete": "catalog:",
"@vercel/sandbox-drives": "catalog:",
"@vercel/sdk": "1.28.8",
+ "@workflow/builders": "5.0.0-beta.44",
"@workflow/core": "5.0.0-beta.43",
"@workflow/errors": "5.0.0-beta.17",
"@workflow/serde": "5.0.0-beta.2",
diff --git a/packages/eve/scripts/copy-runtime-assets.mjs b/packages/eve/scripts/copy-runtime-assets.mjs
index f03467230..af406289d 100644
--- a/packages/eve/scripts/copy-runtime-assets.mjs
+++ b/packages/eve/scripts/copy-runtime-assets.mjs
@@ -7,9 +7,13 @@ const packageRoot = fileURLToPath(new URL("..", import.meta.url));
// section files (see cli/commands/agent-instructions.ts), so they must ship in
// the package next to the compiled module that reads them.
const runtimeAssetDirs = ["src/cli/commands/agent-prompt"];
+// Hand-written declaration files are tsc inputs, not outputs. The ambient
+// `workflow` module types are referenced from `eve/tools` and exported as
+// `eve/workflow-modules`, so they ship beside the emitted declarations.
+const runtimeAssetFiles = ["src/public/workflow-modules.d.ts"];
export async function copyRuntimeAssets() {
- for (const relativePath of runtimeAssetDirs) {
+ for (const relativePath of [...runtimeAssetDirs, ...runtimeAssetFiles]) {
const destinationPath = join(packageRoot, "dist", relativePath);
await mkdir(dirname(destinationPath), { recursive: true });
await cp(join(packageRoot, relativePath), destinationPath, { recursive: true });
diff --git a/packages/eve/scripts/vendor-compiled/@workflow/builders.mjs b/packages/eve/scripts/vendor-compiled/@workflow/builders.mjs
new file mode 100644
index 000000000..6415709c5
--- /dev/null
+++ b/packages/eve/scripts/vendor-compiled/@workflow/builders.mjs
@@ -0,0 +1,18 @@
+import { createDeclarationCopier } from "../_shared.mjs";
+
+/**
+ * Only `transform-utils` is vendored: the Workflow SDK's directive pre-scan
+ * (`detectWorkflowPatterns`, `isGeneratedWorkflowFile`), which eve's authored
+ * module discovery shares so both sides classify source files identically.
+ * The rest of `@workflow/builders` is the SDK's esbuild/SWC build pipeline,
+ * which eve replaces with its own bundler and must not ship.
+ */
+export default {
+ packageName: "@workflow/builders",
+ compiledPath: "@workflow/builders",
+ chunkGroup: "workflow",
+ entry: "dist/transform-utils.js",
+ copyDeclarations: createDeclarationCopier({
+ files: [{ source: "transform-utils.d.ts", output: "index.d.ts" }],
+ }),
+};
diff --git a/packages/eve/scripts/vendor-compiled/index.mjs b/packages/eve/scripts/vendor-compiled/index.mjs
index 43f8fd066..0e7b84f9c 100644
--- a/packages/eve/scripts/vendor-compiled/index.mjs
+++ b/packages/eve/scripts/vendor-compiled/index.mjs
@@ -30,6 +30,7 @@ import vercelOtel from "./@vercel/otel.mjs";
import vercelSandbox from "./@vercel/sandbox.mjs";
import vercelSandboxDelete from "./@vercel/sandbox-delete.mjs";
import vercelSandboxStable from "./@vercel/sandbox-stable.mjs";
+import workflowBuilders from "./@workflow/builders.mjs";
import workflowCore from "./@workflow/core.mjs";
import workflowErrors from "./@workflow/errors.mjs";
import workflowSerde from "./@workflow/serde.mjs";
@@ -94,6 +95,7 @@ export const MODULES = [
vercelSandbox,
vercelSandboxDelete,
vercelSandboxStable,
+ workflowBuilders,
workflowCore,
workflowErrors,
workflowSerde,
diff --git a/packages/eve/src/channel/types.ts b/packages/eve/src/channel/types.ts
index 6fff33532..955aa69a8 100644
--- a/packages/eve/src/channel/types.ts
+++ b/packages/eve/src/channel/types.ts
@@ -3,7 +3,10 @@ import type { UserContent } from "ai";
import type { MessageStreamEvent, UnstampedMessageStreamEvent } from "#protocol/message.js";
import type { CancelTurnResult as ProtocolCancelTurnResult } from "#protocol/cancel-turn.js";
import type { RunMode } from "#shared/run-mode.js";
-import type { RuntimeSubagentChildResult } from "#shared/action-types.js";
+import type {
+ RuntimeSubagentChildResult,
+ RuntimeToolResultActionResult,
+} from "#shared/action-types.js";
import type { InputRequest, InputResponse } from "#shared/input.js";
import type { ChannelAdapter } from "#channel/adapter.js";
import type { AgentLimitsDefinition } from "#shared/agent-definition.js";
@@ -287,14 +290,13 @@ export interface ClearSessionHookPayload {
}
/**
- * Child-produced subagent results resumed back into a parked parent workflow.
- *
- * The `runtime-action-result` discriminator predates this subagent-only inbox
- * lane. Parent-produced dispatch results never travel through this hook.
+ * Results resumed back into a parked parent workflow by the work it
+ * dispatched: child-produced subagent results and authored workflow tool
+ * results. Parent-produced dispatch results never travel through this hook.
*/
export interface RuntimeActionResultHookPayload {
readonly kind: "runtime-action-result";
- readonly results: readonly RuntimeSubagentChildResult[];
+ readonly results: readonly (RuntimeSubagentChildResult | RuntimeToolResultActionResult)[];
}
/**
diff --git a/packages/eve/src/client/agent-info-schema.ts b/packages/eve/src/client/agent-info-schema.ts
index 12dc1a46a..9ff44ad74 100644
--- a/packages/eve/src/client/agent-info-schema.ts
+++ b/packages/eve/src/client/agent-info-schema.ts
@@ -254,7 +254,9 @@ const remoteAgent = entry
const kernelEffect = z
.object({
- action: z.enum(["subagent-call", "task-update", "task-cancel"]).optional(),
+ action: z
+ .enum(["subagent-call", "task-update", "task-cancel", "workflow-tool-call"])
+ .optional(),
audience: z.array(
z.enum([
"root-session",
diff --git a/packages/eve/src/compiler/extension-compatibility.ts b/packages/eve/src/compiler/extension-compatibility.ts
index 8aa57a978..3ddf49d83 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: 23,
- supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 18, 19, 20, 21, 22, 23],
+ current: 24,
+ supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 18, 19, 20, 21, 22, 23, 24],
dropped: { 15: "TaskExec replaces stageEffect with send" },
},
dynamicTool: {
diff --git a/packages/eve/src/compiler/manifest.ts b/packages/eve/src/compiler/manifest.ts
index e1e43ebfd..568e34496 100644
--- a/packages/eve/src/compiler/manifest.ts
+++ b/packages/eve/src/compiler/manifest.ts
@@ -54,7 +54,7 @@ export const ROOT_COMPILED_AGENT_NODE_ID = "__root__";
/**
* Current compiled manifest schema version.
*/
-export const COMPILED_AGENT_MANIFEST_VERSION = 46;
+export const COMPILED_AGENT_MANIFEST_VERSION = 47;
/**
* Compiled channel entry preserved in the compiled manifest.
@@ -844,6 +844,12 @@ const compiledToolBehaviorSchema: z.ZodType<CompiledToolBehavior> = z
request: z.literal("question"),
})
.strict(),
+ z
+ .object({
+ kind: z.literal("workflow-tool"),
+ workflowId: z.string(),
+ })
+ .strict(),
])
.optional(),
presentation: z.literal("load-skill").optional(),
diff --git a/packages/eve/src/compiler/normalize-tool.ts b/packages/eve/src/compiler/normalize-tool.ts
index e9e3a6a00..e2be83cc9 100644
--- a/packages/eve/src/compiler/normalize-tool.ts
+++ b/packages/eve/src/compiler/normalize-tool.ts
@@ -6,6 +6,9 @@ import {
loadModuleBackedDefinition,
type ModuleBackedDefinitionLoadOptions,
} from "#compiler/normalize-helpers.js";
+import type { AgentModuleBinding } from "#compiler/source-graph.js";
+import { resolveAuthoredPackageRoot } from "#internal/authored-module-loader.js";
+import { readAuthoredExecuteWorkflowId } from "#internal/workflow-bundle/authored-workflow-modules.js";
/**
* Compiled tool entry produced from one authored `tools/*.ts` file.
@@ -105,10 +108,14 @@ export async function compileToolEntry(
};
}
+ const workflowId = await readToolWorkflowId(options.binding);
return {
kind: "tool",
definition: {
- behavior: entry.definition.behavior,
+ behavior:
+ workflowId === undefined
+ ? entry.definition.behavior
+ : { availability: [], handling: { kind: "workflow-tool", workflowId } },
description: entry.definition.description,
execution: entry.definition.execution,
exportName: source.exportName,
@@ -124,3 +131,12 @@ export async function compileToolEntry(
},
};
}
+
+async function readToolWorkflowId(binding: AgentModuleBinding): Promise<string | undefined> {
+ if (binding.backing.kind !== "filesystem") return undefined;
+ const filePath = binding.backing.sourcePath;
+ return await readAuthoredExecuteWorkflowId({
+ appRoot: resolveAuthoredPackageRoot(filePath),
+ filePath,
+ });
+}
diff --git a/packages/eve/src/eve-channel/index.ts b/packages/eve/src/eve-channel/index.ts
index ff8979893..072115f9c 100644
--- a/packages/eve/src/eve-channel/index.ts
+++ b/packages/eve/src/eve-channel/index.ts
@@ -9,6 +9,10 @@ import {
import { handleActivityRequest } from "#execution/activity-route.js";
import { handleSessionCallbackRequest } from "#execution/session-callback-route.js";
import { handleTaskInputResponseRequest } from "#execution/task-input-response-route.js";
+import {
+ handleWorkflowWebhookRequest,
+ WORKFLOW_WEBHOOK_ROUTE_PATTERN,
+} from "#execution/workflow-webhook-route.js";
import { createLogger, logError } from "#internal/logging.js";
import {
readAgentInfoRouteResponse,
@@ -48,7 +52,7 @@ import type { ResetResponse } from "#protocol/reset-session.js";
import { parseTraceparent } from "#protocol/traceparent.js";
import { routeAuth } from "#public/channels/auth.js";
import { mergeUploadPolicy } from "#public/channels/upload-policy.js";
-import { defineChannel, GET, HEAD, POST } from "#public/definitions/channel.js";
+import { defineChannel, DELETE, GET, HEAD, PATCH, POST, PUT } from "#public/definitions/channel.js";
import {
checkUploadPolicy,
createSessionStreamResponse,
@@ -118,6 +122,11 @@ export function eveChannel(input: EveChannelInput): EveChannel {
POST(EVE_ACTIVITY_ROUTE_PATTERN, handleActivityRequest),
POST(EVE_CALLBACK_ROUTE_PATTERN, handleSessionCallbackRequest),
POST(EVE_TASK_INPUT_ROUTE_PATTERN, handleTaskInputResponseRequest),
+ GET(WORKFLOW_WEBHOOK_ROUTE_PATTERN, handleWorkflowWebhookRequest),
+ POST(WORKFLOW_WEBHOOK_ROUTE_PATTERN, handleWorkflowWebhookRequest),
+ PUT(WORKFLOW_WEBHOOK_ROUTE_PATTERN, handleWorkflowWebhookRequest),
+ PATCH(WORKFLOW_WEBHOOK_ROUTE_PATTERN, handleWorkflowWebhookRequest),
+ DELETE(WORKFLOW_WEBHOOK_ROUTE_PATTERN, handleWorkflowWebhookRequest),
POST(EVE_SESSION_ROUTE_PATH, async (req, args) => {
const authResult = await routeAuth(req, input.auth);
diff --git a/packages/eve/src/execution/cancel-descendant-turns-step.ts b/packages/eve/src/execution/cancel-descendant-turns-step.ts
index 70730f243..a6d940fb9 100644
--- a/packages/eve/src/execution/cancel-descendant-turns-step.ts
+++ b/packages/eve/src/execution/cancel-descendant-turns-step.ts
@@ -7,7 +7,9 @@ import {
isRetryableRemoteAgentCancelError,
resolveRemoteAgentForAction,
} from "#execution/remote-agent-dispatch.js";
+import { cancelToolRun } from "#execution/tool-run/cancel.js";
import { requestWorkflowTurnCancellation } from "#execution/workflow-runtime.js";
+import { getToolRuns, type ToolRunRecord } from "#harness/tool-runs.js";
import { getAgentHandleStore, type AgentHandle } from "#harness/handles/store.js";
import { createLogger, logError } from "#internal/logging.js";
import type { RuntimeSubagentRegistry } from "#runtime/subagents/registry.js";
@@ -24,7 +26,10 @@ const log = createLogger("execution.cancel-descendant-turns");
type RunningAgentHandle = Extract<AgentHandle, { phase: "running" }>;
-/** Cancels every running delegated child recorded in the agent handle store. */
+/**
+ * Cancels every running delegated child recorded in the agent handle store
+ * and every workflow tool run the turn is waiting on.
+ */
export async function cancelDescendantTurnsStep(input: {
readonly serializedContext: Record<string, unknown>;
readonly sessionState: DurableSessionState;
@@ -32,11 +37,13 @@ export async function cancelDescendantTurnsStep(input: {
"use step";
let running: readonly RunningAgentHandle[];
+ let toolRuns: readonly ToolRunRecord[];
try {
const session = await readDurableSession(input.sessionState);
running = (getAgentHandleStore(session.state)?.handles ?? []).filter(
(handle): handle is RunningAgentHandle => handle.phase === "running",
);
+ toolRuns = getToolRuns(session.state);
} catch (error) {
logError(log, "failed to read pending descendants during cancellation", error, {
sessionId: input.sessionState.sessionId,
@@ -44,6 +51,9 @@ export async function cancelDescendantTurnsStep(input: {
return;
}
+ await Promise.all(
+ toolRuns.map((record) => cancelToolRun(record, "The turn that called the tool was cancelled.")),
+ );
if (running.length === 0) return;
let remoteContext:
diff --git a/packages/eve/src/execution/delegation-tool.ts b/packages/eve/src/execution/delegation-tool.ts
index ba4ab9b31..e2763cd17 100644
--- a/packages/eve/src/execution/delegation-tool.ts
+++ b/packages/eve/src/execution/delegation-tool.ts
@@ -45,7 +45,11 @@ export function createBackgroundSubagentHarnessDefinition(
if (target?.kind !== "dispatch") {
throw new Error(`Background subagent tool "${tool.name}" has no prepared dispatch target.`);
}
- if (target.target.kind === "task-cancel" || target.target.kind === "task-update") {
+ if (
+ target.target.kind === "task-cancel" ||
+ target.target.kind === "task-update" ||
+ target.target.kind === "workflow-tool-call"
+ ) {
throw new Error(
`Background subagent tool "${tool.name}" cannot dispatch ${target.target.kind}.`,
);
diff --git a/packages/eve/src/execution/dispatch-runtime-actions-shared.ts b/packages/eve/src/execution/dispatch-runtime-actions-shared.ts
index 79d6c3502..c6b93d07e 100644
--- a/packages/eve/src/execution/dispatch-runtime-actions-shared.ts
+++ b/packages/eve/src/execution/dispatch-runtime-actions-shared.ts
@@ -8,7 +8,7 @@
*/
import { buildAdapterContext } from "#channel/adapter-context.js";
-import type { ActivityObserverConfig } from "#channel/types.js";
+import type { ActivityObserverConfig, SessionParent } from "#channel/types.js";
import {
callAdapterEventHandler,
type ChannelAdapter,
@@ -20,6 +20,7 @@ import {
CapabilitiesKey,
ChannelInstrumentationKey,
InitiatorAuthKey,
+ ParentSessionKey,
SandboxKey,
type LocalDevRequestProvenance,
} from "#context/keys.js";
@@ -59,6 +60,7 @@ import type {
PendingAgentDispatchAction,
PendingDispatchAction,
PendingTaskControlAction,
+ PendingWorkflowToolAction,
} from "#shared/dispatch-action.js";
import { type DurableSessionState, readDurableSession } from "#execution/durable-session-store.js";
import {
@@ -77,6 +79,7 @@ import { resolveSubagentDepth } from "#harness/subagent-depth.js";
import { getDynamicSubagentSelection } from "#context/dynamic-subagent-lifecycle.js";
import { resolveEffectiveAgentRuntime } from "#execution/effective-agent-config.js";
import { isTaskControlAction } from "#execution/tasks/parent/dispatch.js";
+import { isWorkflowToolAction } from "#execution/tool-run/dispatch.js";
import { isSubagentDelegationAction } from "#harness/subagent-depth.js";
import { resolvePreparedAgentAction } from "#execution/prepared-agent-action.js";
@@ -105,7 +108,8 @@ export type DispatchPlanEntry =
}
| { readonly kind: "reject"; readonly result: RuntimeSubagentDispatchFailure }
| { readonly kind: "start"; readonly target: DispatchStartTarget }
- | { readonly kind: "task-control"; readonly action: PendingTaskControlAction };
+ | { readonly kind: "task-control"; readonly action: PendingTaskControlAction }
+ | { readonly kind: "workflow-tool"; readonly action: PendingWorkflowToolAction };
export type DispatchStartTarget =
| {
@@ -165,6 +169,8 @@ export interface PreparedRuntimeActionDispatch {
readonly fanoutSize: number;
readonly initiatorAuth: Parameters<typeof buildSubagentRunInput>[0]["initiatorAuth"];
readonly localDevRequest?: LocalDevRequestProvenance;
+ /** Lineage of the session running this dispatch, when it is itself a delegated child. */
+ readonly parentSession: SessionParent | undefined;
readonly parentTraceContext: Parameters<typeof buildSubagentRunInput>[0]["parentTraceContext"];
readonly activityObserver?: ActivityObserverConfig & {
readonly workIdentity: ActivityWorkIdentityV1;
@@ -295,6 +301,7 @@ async function prepareActionDispatch(input: {
plan.filter((entry) => entry.kind === "start" && entry.target.kind === "local").length,
initiatorAuth: ctx.get(InitiatorAuthKey) ?? null,
localDevRequest: ctx.localDevRequest,
+ parentSession: ctx.get(ParentSessionKey),
parentTraceContext: readSessionTraceContext(input.serializedContext, session.sessionId),
plan,
activityObserver: resolvePreparedActivity(
@@ -439,6 +446,9 @@ function planDispatch(input: {
if (input.taskControls && isTaskControlAction(action)) {
return { action, kind: "task-control" };
}
+ if (isWorkflowToolAction(action)) {
+ return { action, kind: "workflow-tool" };
+ }
if (!isSubagentDelegationAction(action)) {
throw new Error(
diff --git a/packages/eve/src/execution/dispatch-runtime-actions-step.ts b/packages/eve/src/execution/dispatch-runtime-actions-step.ts
index 2b9a3b242..42472531e 100644
--- a/packages/eve/src/execution/dispatch-runtime-actions-step.ts
+++ b/packages/eve/src/execution/dispatch-runtime-actions-step.ts
@@ -24,6 +24,7 @@ import {
type RuntimeActionDispatchResult,
startSubagent,
} from "#execution/dispatch-runtime-actions-shared.js";
+import { startWorkflowTool } from "#execution/tool-run/dispatch.js";
import { createDurableSessionState } from "#execution/durable-session-store.js";
import { deriveChildActivityObserverConfig } from "#execution/activity-work.js";
import type { RuntimeActionResult } from "#shared/action-types.js";
@@ -56,6 +57,18 @@ export async function dispatchRuntimeActionsStep(
results.push(entry.result);
continue;
}
+ if (entry.kind === "workflow-tool") {
+ const started = await startWorkflowTool({
+ action: entry.action,
+ batchEvent: batch.event,
+ ownerInboxToken: input.parentContinuationToken,
+ prepared,
+ session: nextSession,
+ });
+ nextSession = started.session;
+ if (started.result !== undefined) results.push(started.result);
+ continue;
+ }
if (entry.kind === "task-control") {
// Unreachable: the plan was built with `taskControls: false`.
throw new Error("Task-control actions require the task dispatch step.");
diff --git a/packages/eve/src/execution/next-driver-action.ts b/packages/eve/src/execution/next-driver-action.ts
index 3ccdb0cf4..f776c7070 100644
--- a/packages/eve/src/execution/next-driver-action.ts
+++ b/packages/eve/src/execution/next-driver-action.ts
@@ -40,6 +40,8 @@ export type DurableStepResult = (
readonly hasPendingAuthorization: boolean;
readonly hasPendingInputBatch: boolean;
readonly pendingRuntimeActionKeys?: readonly string[];
+ /** The batch starts workflow tool runs, which report to the turn's run channels. */
+ readonly startsWorkflowToolRuns?: boolean;
readonly tasksEnabled?: boolean;
readonly sleepDurationMs?: number;
readonly settled?: SettledTurn;
diff --git a/packages/eve/src/execution/node-step.ts b/packages/eve/src/execution/node-step.ts
index 4e06ce413..a5d5db73e 100644
--- a/packages/eve/src/execution/node-step.ts
+++ b/packages/eve/src/execution/node-step.ts
@@ -14,6 +14,8 @@ import type { HandleEventFn, HarnessToolMap, StepFn } from "#harness/types.js";
import { resolveInstalledPackageInfo } from "#internal/application/package.js";
import { createLogger } from "#internal/logging.js";
import type { RuntimeIdentity } from "#protocol/message.js";
+import type { PreparedDispatchTarget } from "#tools/behavior.js";
+import type { ToolExecution } from "#tools/definition.js";
import { UNSPECIFIED_INPUT_SCHEMA } from "#tools/schema.js";
import type { RunMode } from "#shared/run-mode.js";
import {
@@ -28,6 +30,7 @@ import { findRegisteredRuntimeTool } from "#runtime/tools/registry.js";
import type { ResolvedToolDefinition } from "#runtime/types.js";
import { preserveFrameworkStateOnCompaction } from "#execution/compaction.js";
import { createToolExecuteWithAuth } from "#execution/tool-auth.js";
+import { createWorkflowToolBackgroundExecute } from "#execution/tool-run/background.js";
const log = createLogger("execution.node-step");
@@ -262,6 +265,8 @@ function resolveHarnessToolDefinition(input: {
description: def.description,
execution: def.execution,
execute: resolveAuthoredExecute({
+ dispatchTarget,
+ execution: def.execution,
rawExecute,
scope: def.name,
}),
@@ -280,12 +285,24 @@ function resolveHarnessToolDefinition(input: {
* which builds a token-aware context. Providers passed to
* `ctx.getToken(provider)` use tool-qualified auth scopes.
* - Tools without `execute` (provider-managed) stay `undefined`.
+ * - A workflow body never runs inside the model step: a background one is
+ * started from the harness, a waiting one is dispatched by the turn.
*/
function resolveAuthoredExecute(input: {
+ readonly dispatchTarget: PreparedDispatchTarget | undefined;
+ readonly execution: ToolExecution | undefined;
readonly rawExecute: ResolvedToolDefinition["execute"];
readonly scope: string;
}): HarnessToolDefinition["execute"] {
const { rawExecute, scope } = input;
+ if (input.dispatchTarget?.kind === "workflow-tool-call") {
+ return input.execution === "background"
+ ? createWorkflowToolBackgroundExecute({
+ toolName: scope,
+ workflowId: input.dispatchTarget.workflowId,
+ })
+ : undefined;
+ }
if (rawExecute === undefined) {
return undefined;
}
diff --git a/packages/eve/src/execution/pending-turn-state.ts b/packages/eve/src/execution/pending-turn-state.ts
index 538b83229..7be2369e2 100644
--- a/packages/eve/src/execution/pending-turn-state.ts
+++ b/packages/eve/src/execution/pending-turn-state.ts
@@ -11,6 +11,7 @@ export function derivePendingState(session: HarnessSession): {
readonly hasPendingAuthorization: boolean;
readonly hasPendingInputBatch: boolean;
readonly pendingRuntimeActionKeys?: readonly string[];
+ readonly startsWorkflowToolRuns?: boolean;
} {
const batch = getPendingRuntimeActionBatch(session.state);
const pendingAuth = getPendingAuthorization(session.state);
@@ -26,5 +27,8 @@ export function derivePendingState(session: HarnessSession): {
return {
...base,
pendingRuntimeActionKeys: batch.actions.map((action) => getPendingDispatchActionKey(action)),
+ startsWorkflowToolRuns: batch.actions.some(
+ (action) => action.target.kind === "workflow-tool-call",
+ ),
};
}
diff --git a/packages/eve/src/execution/proxied-deliver-step.ts b/packages/eve/src/execution/proxied-deliver-step.ts
index 75641ac5e..ba8c017bd 100644
--- a/packages/eve/src/execution/proxied-deliver-step.ts
+++ b/packages/eve/src/execution/proxied-deliver-step.ts
@@ -8,6 +8,8 @@ import {
import { routeDeliverPayload } from "#execution/subagent-hitl-proxy.js";
import { sendTaskInboundPayload } from "#execution/tasks/parent/run-parent.js";
import { resumeSessionInbox } from "#execution/wire/session-inbox-resume.js";
+import { resumeToolRunAnswers } from "#execution/tool-run/answer.js";
+import type { AnswerHookRoute } from "#harness/proxy-input-requests.js";
import type { InputResponse } from "#shared/input.js";
import { findSessionTaskEntry } from "#tasks/session-index.js";
import {
@@ -42,6 +44,7 @@ type LegacyRoutedDeliverResult =
};
interface ChildBucket {
+ readonly answerHook?: AnswerHookRoute;
readonly childContinuationToken: string;
readonly childResponseUrl?: string;
readonly metadata: NonNullable<DeliverHookPayload["deliveryMetadata"]>[number][];
@@ -114,6 +117,7 @@ export async function routeProxiedDeliverStep(
forChild.taskId,
].join("\0");
const child = children.get(key) ?? {
+ answerHook: forChild.answerHook,
childContinuationToken: forChild.childContinuationToken,
childResponseUrl: forChild.childResponseUrl,
metadata: [],
@@ -173,6 +177,16 @@ export async function routeProxiedDeliverStep(
continue;
}
+ if (child.answerHook !== undefined) {
+ await resumeToolRunAnswers(
+ child.childContinuationToken,
+ coalesceDeliverPayloads(child.payloads).inputResponses,
+ );
+ durableSession = retireProxyInputRequests(durableSession, child.retireRequestIds);
+ retired = true;
+ continue;
+ }
+
const childDelivery: DeliverHookPayload = {
...sourceDelivery,
deliveryMetadata: child.metadata.length === 0 ? undefined : child.metadata,
diff --git a/packages/eve/src/execution/settle-cancelled-turn-step.ts b/packages/eve/src/execution/settle-cancelled-turn-step.ts
index 051c610c4..acd9b3b8f 100644
--- a/packages/eve/src/execution/settle-cancelled-turn-step.ts
+++ b/packages/eve/src/execution/settle-cancelled-turn-step.ts
@@ -27,6 +27,7 @@ import {
} from "#harness/proxy-input-requests.js";
import { abandonRunningAgentTurns } from "#harness/handles/transitions.js";
import { clearPendingRuntimeActionBatch } from "#harness/runtime-actions.js";
+import { clearToolRuns } from "#harness/tool-runs.js";
import { bindSessionInstrumentation } from "#instrumentation/runtime.js";
import { getTurnUsageState, toUsage } from "#harness/turn-tag-state.js";
import { clearPendingWorkflowInterrupt } from "#harness/workflow-interrupt-state.js";
@@ -145,7 +146,7 @@ export async function settleCancelledTurnStep(input: {
clearAllProxyInputRequests(
clearPendingWorkflowInterrupt(
clearPendingRuntimeActionBatch(
- abandonRunningAgentTurns({ ...session, outputSchema: undefined }),
+ clearToolRuns(abandonRunningAgentTurns({ ...session, outputSchema: undefined })),
),
),
),
diff --git a/packages/eve/src/execution/stable-workflow-names.ts b/packages/eve/src/execution/stable-workflow-names.ts
new file mode 100644
index 000000000..eb74c46e7
--- /dev/null
+++ b/packages/eve/src/execution/stable-workflow-names.ts
@@ -0,0 +1,20 @@
+/**
+ * eve workflow functions whose bundled id carries no `@<version>` stamp, so
+ * `start(ref, args, { deploymentId: "latest" })` finds them on a newer
+ * deployment. Dependency-free so the bundler can import it.
+ */
+export const WORKFLOW_ENTRY_NAME = "workflowEntry";
+export const TURN_WORKFLOW_NAME = "turnWorkflow";
+export const SESSION_TIMEOUT_WORKFLOW_NAME = "sessionTimeoutWorkflow";
+export const TASK_RUN_WORKFLOW_NAME = "taskRunWorkflow";
+export const TOOL_RUN_WORKFLOW_NAME = "toolRunWorkflow";
+export const ACTIVITY_COLLECTOR_WORKFLOW_NAME = "activityCollectorWorkflow";
+
+export const STABLE_WORKFLOW_NAMES: ReadonlySet<string> = new Set([
+ WORKFLOW_ENTRY_NAME,
+ TURN_WORKFLOW_NAME,
+ SESSION_TIMEOUT_WORKFLOW_NAME,
+ TASK_RUN_WORKFLOW_NAME,
+ TOOL_RUN_WORKFLOW_NAME,
+ ACTIVITY_COLLECTOR_WORKFLOW_NAME,
+]);
diff --git a/packages/eve/src/execution/subagent-event-proxy-step.ts b/packages/eve/src/execution/subagent-event-proxy-step.ts
index acb2e6654..5cb27a3e1 100644
--- a/packages/eve/src/execution/subagent-event-proxy-step.ts
+++ b/packages/eve/src/execution/subagent-event-proxy-step.ts
@@ -19,7 +19,7 @@ import { reconcileSessionContinuationToken } from "#execution/reconcile-session-
import { hydrateDurableSession } from "#execution/session.js";
import { emitProxiedInputRequest } from "#execution/subagent-hitl-proxy.js";
import { upsertProxyInputRequests } from "#harness/proxy-input-requests.js";
-import type { ProxyInputRequest } from "#harness/proxy-input-requests.js";
+import type { AnswerHookRoute, ProxyInputRequest } from "#harness/proxy-input-requests.js";
import type { HarnessSession } from "#harness/types.js";
import type { UnstampedMessageStreamEvent } from "#protocol/message.js";
import { encodeMessageStreamEvent, stampMessageStreamEvent } from "#protocol/message.js";
@@ -39,6 +39,7 @@ interface ProxySubagentEventResult {
/** Proxies one child event through its parent channel across a durable step boundary. */
export async function runProxySubagentEventStep(input: {
+ readonly answerHook?: AnswerHookRoute;
readonly hookPayload: SubagentEventHookPayload;
readonly parentWritable: WritableStream<Uint8Array>;
readonly serializedContext: Record<string, unknown>;
@@ -50,6 +51,7 @@ export async function runProxySubagentEventStep(input: {
const ctx = await deserializeContext(input.serializedContext);
return emitProxiedSubagentEvent({
+ answerHook: input.answerHook,
ctx,
durableSession,
hookPayload: input.hookPayload,
@@ -99,6 +101,7 @@ export async function emitRecordedTaskAuthorizationEventStep(input: {
/** Applies one proxied child event to an already-hydrated parent context. */
export async function emitProxiedSubagentEvent(input: {
+ readonly answerHook?: AnswerHookRoute;
readonly ctx: ContextContainer;
readonly durableSession: DurableSession;
readonly hookPayload: SubagentEventHookPayload;
@@ -156,8 +159,12 @@ export async function emitProxiedSubagentEvent(input: {
proxyEntries !== undefined &&
input.hookPayload.kind === "subagent-input-request"
) {
+ const answerHook = input.answerHook;
scopedSession = upsertProxyInputRequests({
- entries: proxyEntries,
+ entries:
+ answerHook === undefined
+ ? proxyEntries
+ : proxyEntries.map(([requestId, route]) => [requestId, { ...route, answerHook }]),
forChildContinuationToken: input.hookPayload.childContinuationToken,
session: scopedSession,
});
diff --git a/packages/eve/src/execution/subagent-hitl-proxy.ts b/packages/eve/src/execution/subagent-hitl-proxy.ts
index db4135cf6..c334a709f 100644
--- a/packages/eve/src/execution/subagent-hitl-proxy.ts
+++ b/packages/eve/src/execution/subagent-hitl-proxy.ts
@@ -8,7 +8,7 @@ import {
getProxyInputRequests,
toProxyInputRequestEntries,
} from "#harness/proxy-input-requests.js";
-import type { ProxyInputRequest } from "#harness/proxy-input-requests.js";
+import type { AnswerHookRoute, ProxyInputRequest } from "#harness/proxy-input-requests.js";
import type { HarnessEmitFn, HarnessSession, SessionStateMap } from "#harness/types.js";
import { createInputRequestedEvent } from "#protocol/message.js";
import type { RunMode } from "#shared/run-mode.js";
@@ -62,6 +62,7 @@ export async function emitProxiedInputRequest(input: {
/** One proxied-child bucket of a routed deliver payload. */
export interface RoutedChildDelivery {
+ readonly answerHook?: AnswerHookRoute;
readonly childContinuationToken: string;
readonly childResponseUrl?: string;
readonly payload: { readonly inputResponses: readonly InputResponse[] };
@@ -84,6 +85,7 @@ export interface RoutedDeliverPayload {
/** In-progress accumulation for one `forChildren` bucket. */
interface ChildResponseBucket {
+ readonly answerHook?: AnswerHookRoute;
readonly childContinuationToken: string;
readonly childResponseUrl?: string;
/** Parent-visible request IDs answered in this bucket. */
@@ -130,6 +132,7 @@ export function routeDeliverPayload(input: {
parentRequestIds: [response.requestId],
responses: [toChildInputResponse(response, route)],
routes: [route],
+ ...(route.answerHook !== undefined && { answerHook: route.answerHook }),
...(route.childResponseUrl !== undefined && { childResponseUrl: route.childResponseUrl }),
...(route.taskId !== undefined && { taskId: route.taskId }),
});
@@ -142,6 +145,7 @@ export function routeDeliverPayload(input: {
const forChildren = [...responsesByChild.values()].map(
({
+ answerHook,
childContinuationToken,
childResponseUrl,
parentRequestIds,
@@ -168,6 +172,7 @@ export function routeDeliverPayload(input: {
childContinuationToken,
payload: { inputResponses: responses },
retireRequestIds: [...retireRequestIds],
+ ...(answerHook !== undefined && { answerHook }),
...(childResponseUrl !== undefined && { childResponseUrl }),
...(taskId !== undefined && { taskId }),
};
diff --git a/packages/eve/src/execution/tasks/child/steps.ts b/packages/eve/src/execution/tasks/child/steps.ts
index bab9ab528..2c554b343 100644
--- a/packages/eve/src/execution/tasks/child/steps.ts
+++ b/packages/eve/src/execution/tasks/child/steps.ts
@@ -9,6 +9,8 @@ import type {
import { submitActivity } from "#execution/submit-activity.js";
import { isTaskWorkflowTargetGone } from "#execution/tasks/workflow-target.js";
import { resumeSessionInbox } from "#execution/wire/session-inbox-resume.js";
+import { resumeToolRunAnswers } from "#execution/tool-run/answer.js";
+import type { AnswerHookRoute } from "#harness/proxy-input-requests.js";
import { createLogger } from "#internal/logging.js";
import type { ActivityEventV1 } from "#protocol/activity.js";
import type { JsonValue } from "#shared/json.js";
@@ -217,6 +219,7 @@ export async function wakeTaskInputRequestParentStep(input: {
*/
export async function deliverTaskInputResponsesStep(input: {
readonly answer: TaskInboundAnswerInput;
+ readonly answerHook?: AnswerHookRoute;
readonly requestIds: readonly string[];
}): Promise<"delivered" | "unreachable"> {
"use step";
@@ -243,6 +246,11 @@ export async function deliverTaskInputResponsesStep(input: {
if (response.status === 404) return "unreachable";
if (!response.ok)
throw new Error(`Remote task input delivery failed with HTTP ${response.status}.`);
+ } else if (input.answerHook !== undefined) {
+ await resumeToolRunAnswers(
+ input.answer.childContinuationToken,
+ command.payload.inputResponses,
+ );
} else {
await resumeSessionInbox(input.answer.childContinuationToken, command);
}
diff --git a/packages/eve/src/execution/tasks/child/workflow.test.ts b/packages/eve/src/execution/tasks/child/workflow.test.ts
index 2e7c47350..3af5b84d9 100644
--- a/packages/eve/src/execution/tasks/child/workflow.test.ts
+++ b/packages/eve/src/execution/tasks/child/workflow.test.ts
@@ -21,6 +21,15 @@ import type {
vi.mock("#compiled/@workflow/core/index.js", () => ({
createHook: vi.fn(),
+ defineHook: () => ({
+ create: (options?: { readonly token?: string }) => ({
+ [Symbol.asyncIterator]: () => ({ next: () => new Promise(() => {}) }),
+ dispose: async () => {},
+ getConflict: async () => null,
+ token: options?.token ?? "hook",
+ }),
+ resume: async () => null,
+ }),
}));
vi.mock("#execution/hook-ownership.js", async (importOriginal) => ({
@@ -177,6 +186,26 @@ describe("taskRunWorkflow", () => {
expect(disposeHook).toHaveBeenCalledTimes(1);
});
+ it("opens and disposes the run channels only for a background tool's task", async () => {
+ mockCommandHook([
+ { command: { kind: "ready" }, kind: "task-command" },
+ { command: { data: "done", kind: "complete" }, kind: "task-command" },
+ ]);
+
+ await taskRunWorkflow({
+ taskInboxToken: "task-token",
+ initialView: {
+ metadata: { kind: "tool", name: "deploy" },
+ status: "working",
+ taskId: "task_abc123",
+ },
+ parentContinuationToken: "parent-session-token",
+ });
+
+ expect(appendedStatuses()).toEqual(["working", "working", "completed"]);
+ expect(disposeHook).toHaveBeenCalledTimes(4);
+ });
+
it("skips views for rejected and noop commands", async () => {
mockCommandHook([
{ command: { kind: "answered", requestIds: ["req-1"] }, kind: "task-command" }, // noop on working
diff --git a/packages/eve/src/execution/tasks/child/workflow.ts b/packages/eve/src/execution/tasks/child/workflow.ts
index 16d030c4a..61df2a649 100644
--- a/packages/eve/src/execution/tasks/child/workflow.ts
+++ b/packages/eve/src/execution/tasks/child/workflow.ts
@@ -1,3 +1,4 @@
+import type { AnswerHookRoute } from "#harness/proxy-input-requests.js";
import { createHook } from "#compiled/@workflow/core/index.js";
import type {
@@ -15,6 +16,13 @@ import {
} from "#execution/tasks/child/steps.js";
import { applyTaskTransition } from "#tasks/transitions.js";
import { translateTaskInboundPayload } from "#tasks/wire.js";
+import { createChannelReader, raceChannelReads } from "#execution/tool-run/owner-channels.js";
+import { openRunOwnerChannels } from "#execution/tool-run/owner.js";
+import {
+ runOutcomeToTaskCommand,
+ runReportToTaskUpdate,
+ runRequestToInputRequestPayload,
+} from "#execution/tool-run/owner-inbox.js";
import {
isReadyTaskStatus,
isTerminalTaskStatus,
@@ -78,7 +86,18 @@ export async function taskRunWorkflow(input: TaskRunWorkflowInput): Promise<void
// The iterator shares the hook's durable cursor; create it before
// claiming so conflict replay is consumed by getConflict(), not a
// later iterator read.
- const iterator = commands[Symbol.asyncIterator]();
+ const commandReader = createChannelReader("commands", commands);
+ // Only a background tool's task can own a workflow tool run. Opened before
+ // the claim: the parent hands the token to the run as soon as the claim
+ // lands, and the run may report at once.
+ const runChannels =
+ input.initialView.metadata.kind === "tool"
+ ? openRunOwnerChannels(input.taskInboxToken)
+ : undefined;
+ const readers =
+ runChannels === undefined
+ ? ([commandReader] as const)
+ : ([...runChannels.readers, commandReader] as const);
let ownsHook = false;
try {
@@ -98,15 +117,27 @@ export async function taskRunWorkflow(input: TaskRunWorkflowInput): Promise<void
let pendingAuthorizationEvents: TaskInboundAuthorizationEvent[] = [];
let pendingUpdates: TaskInboundUpdate[] = [];
let dispatchAcknowledged = false;
+ let runUpdateIndex = 0;
+ // The parent answers with the request's token; only this run knows it was a hook.
+ const answerHooks = new Map<string, AnswerHookRoute>();
await appendTaskViewStep({ activityObserver: input.activityObserver, view });
while (!isTaskRunFinished(view, dispatchAcknowledged)) {
- const next = await iterator.next();
- if (next.done === true) return;
+ const read = await raceChannelReads(readers);
+ if (read.next.done === true) return;
+ if (read.channel === "request") {
+ answerHooks.set(read.next.value.answerToken, { runId: read.next.value.from.runId });
+ }
+ const raw: TaskRunHookPayload =
+ read.channel === "report"
+ ? runReportToTaskUpdate(read.next.value, view.taskId, runUpdateIndex++)
+ : read.channel === "request"
+ ? runRequestToInputRequestPayload(read.next.value)
+ : read.channel === "outcome"
+ ? { command: runOutcomeToTaskCommand(read.next.value), kind: "task-command" }
+ : read.next.value;
const payload: TaskRunInboundPayload =
- next.value.kind === "subagent-authorization-event"
- ? { ...next.value, kind: "authorization-event" }
- : next.value;
+ raw.kind === "subagent-authorization-event" ? { ...raw, kind: "authorization-event" } : raw;
// Approval lifecycle events (`approval.candidate`/`approval.settled`)
// are intra-child responder bookkeeping, not task blockers: only
// `authorization.required`/`authorization.completed` may block or
@@ -153,7 +184,11 @@ export async function taskRunWorkflow(input: TaskRunWorkflowInput): Promise<void
};
} else if (isTaskInputAnswer) {
if (view.status !== "input_required") continue;
- command = await resolveAnsweredCommand(view, payload);
+ command = await resolveAnsweredCommand(
+ view,
+ payload,
+ answerHooks.get(payload.childContinuationToken),
+ );
} else {
command = translateTaskInboundPayload(payload);
}
@@ -224,7 +259,10 @@ export async function taskRunWorkflow(input: TaskRunWorkflowInput): Promise<void
// Dispose-only teardown: `iterator.return()` would await a pending
// durable read that never settles, leaving this run `running`
// forever and its hook unswept.
- if (ownsHook) await disposeHook(commands);
+ if (ownsHook) {
+ await runChannels?.dispose();
+ await disposeHook(commands);
+ }
}
}
@@ -241,6 +279,7 @@ export async function taskRunWorkflow(input: TaskRunWorkflowInput): Promise<void
async function resolveAnsweredCommand(
view: Extract<TaskView, { status: "input_required" }>,
answer: TaskInboundAnswerInput,
+ answerHook: AnswerHookRoute | undefined,
): Promise<TaskCommand | undefined> {
if (answer.taskId !== view.taskId) return undefined;
@@ -255,6 +294,6 @@ async function resolveAnsweredCommand(
.filter((requestId) => outstanding.has(requestId));
if (requestIds.length === 0) return undefined;
- const delivery = await deliverTaskInputResponsesStep({ answer, requestIds });
+ const delivery = await deliverTaskInputResponsesStep({ answer, answerHook, requestIds });
return delivery === "delivered" ? { kind: "answered", requestIds } : undefined;
}
diff --git a/packages/eve/src/execution/tasks/parent/dispatch-task-step.ts b/packages/eve/src/execution/tasks/parent/dispatch-task-step.ts
index 20591012b..4894a7f3e 100644
--- a/packages/eve/src/execution/tasks/parent/dispatch-task-step.ts
+++ b/packages/eve/src/execution/tasks/parent/dispatch-task-step.ts
@@ -28,6 +28,7 @@ import {
type RuntimeActionDispatchResult,
startSubagent,
} from "#execution/dispatch-runtime-actions-shared.js";
+import { startWorkflowTool } from "#execution/tool-run/dispatch.js";
import { createDurableSessionState } from "#execution/durable-session-store.js";
import { deriveChildActivityObserverConfig } from "#execution/activity-work.js";
import {
@@ -74,6 +75,18 @@ export async function dispatchTaskStep(
results.push(entry.result);
continue;
}
+ if (entry.kind === "workflow-tool") {
+ const started = await startWorkflowTool({
+ action: entry.action,
+ batchEvent: batch.event,
+ ownerInboxToken: input.parentContinuationToken,
+ prepared,
+ session: nextSession,
+ });
+ nextSession = started.session;
+ if (started.result !== undefined) results.push(started.result);
+ continue;
+ }
if (entry.kind === "task-control") {
const control = await executeTaskControlAction({
diff --git a/packages/eve/src/execution/tasks/parent/dispatch.ts b/packages/eve/src/execution/tasks/parent/dispatch.ts
index f503048df..ff1366f04 100644
--- a/packages/eve/src/execution/tasks/parent/dispatch.ts
+++ b/packages/eve/src/execution/tasks/parent/dispatch.ts
@@ -15,6 +15,8 @@ import {
readTaskView,
} from "#execution/tasks/parent/control-shared.js";
import { executeTaskUpdate } from "#execution/tasks/child/update.js";
+import { readWorkflowToolExecutor } from "#execution/tool-run/background.js";
+import { cancelToolRun } from "#execution/tool-run/cancel.js";
import type { ChannelAdapter } from "#channel/adapter.js";
import type { DelegatedTask } from "#execution/tasks/parent/delegate.js";
import { sendTaskCommand } from "#execution/tasks/parent/run-parent.js";
@@ -140,6 +142,7 @@ export async function cancelOwnedTask(input: {
await propagateTaskCancel({
bundle: input.bundle,
serializedContext: input.serializedContext,
+ entry,
session: input.session,
view: settledView,
});
@@ -157,9 +160,22 @@ export async function cancelOwnedTask(input: {
async function propagateTaskCancel(input: {
readonly bundle: CompiledBundle;
readonly serializedContext?: Record<string, unknown>;
+ readonly entry: SessionTaskIndexEntry;
readonly session: RuntimeSession;
readonly view: TaskView;
}): Promise<void> {
+ const toolRun = readWorkflowToolExecutor(input.view.executor?.binding);
+ if (toolRun !== undefined) {
+ // The run reports its own end only after its cancel grace period; settle
+ // the executor now so the task run finishes and releases its hook.
+ await cancelToolRun(toolRun, `Task ${input.entry.taskId} was cancelled.`);
+ await sendTaskCommand({
+ command: { kind: "settle-executor" },
+ taskInboxToken: input.entry.taskInboxToken,
+ });
+ return;
+ }
+
const metadata = readSubagentTaskMetadata(input.view);
if (metadata === undefined) return;
const executor =
diff --git a/packages/eve/src/execution/tasks/parent/hitl-proxy-steps.ts b/packages/eve/src/execution/tasks/parent/hitl-proxy-steps.ts
index a0876fcc9..66306d6ec 100644
--- a/packages/eve/src/execution/tasks/parent/hitl-proxy-steps.ts
+++ b/packages/eve/src/execution/tasks/parent/hitl-proxy-steps.ts
@@ -1,6 +1,11 @@
import type { SubagentInputRequestHookPayload } from "#channel/types.js";
import type { SubagentAuthorizationEventHookPayload } from "#channel/types.js";
-import { type DurableSessionState, readDurableSession } from "#execution/durable-session-store.js";
+import {
+ type DurableSession,
+ type DurableSessionState,
+ readDurableSession,
+} from "#execution/durable-session-store.js";
+import { readWorkflowToolExecutor } from "#execution/tool-run/background.js";
import { createTaskInputCapabilityToken } from "#execution/task-input-capability.js";
import { readLatestTaskView } from "#execution/tasks/parent/run-parent.js";
import { createRemoteTaskInputCallbackUrl } from "#execution/workflow-callback-url.js";
@@ -9,10 +14,14 @@ import {
toProxyInputRequestEntries,
upsertProxyInputRequestState,
} from "#harness/proxy-input-requests.js";
-import { getAgentHandleStore } from "#harness/handles/store.js";
+import { type AgentHandle, getAgentHandleStore } from "#harness/handles/store.js";
import { removeTaskAgentAddressFromState } from "#harness/handles/transitions.js";
import { isInputRequest } from "#shared/input.js";
-import { cacheTerminalTaskView, findSessionTaskEntry } from "#tasks/session-index.js";
+import {
+ cacheTerminalTaskView,
+ findSessionTaskEntry,
+ type SessionTaskIndexEntry,
+} from "#tasks/session-index.js";
import { createEveTaskInputRoutePath } from "#protocol/routes.js";
import { isTerminalTaskStatus, readSubagentTaskMetadata, type TaskView } from "#tasks/types.js";
@@ -34,24 +43,10 @@ export async function recordTaskInputRequestStep(input: {
const durableSession = await readDurableSession(input.sessionState);
const entry = findSessionTaskEntry(durableSession.state, input.taskId);
- const entryMetadata = entry === undefined ? undefined : readSubagentTaskMetadata(entry);
- const handle = (getAgentHandleStore(durableSession.state)?.handles ?? []).find(
- (candidate) =>
- candidate.phase === "addressed" && candidate.identity.id === entryMetadata?.agentId,
- );
- if (
- entry === undefined ||
- handle?.phase !== "addressed" ||
- handle.address.sessionId !== input.hookPayload.childSessionId
- ) {
+ if (entry === undefined) {
return { accepted: false, sessionState: input.sessionState };
}
- // Remote creates are ID-addressed and return no continuation token, so
- // provenance rests on the sessionId match above plus the strict view
- // checks below; the child-advertised token is only used as the answer
- // route, never as an identity anchor.
const view = await readLatestTaskView({ taskRunId: entry.taskRunId });
- const viewMetadata = view === undefined ? undefined : readSubagentTaskMetadata(view);
const eventRequestIds = input.hookPayload.event.requests.map((request) => request.requestId);
const viewRequestIds =
view?.inputRequests?.map((request) =>
@@ -62,9 +57,6 @@ export async function recordTaskInputRequestStep(input: {
if (
view?.status !== "input_required" ||
!input.hookPayload.event.requests.every(isInputRequest) ||
- viewMetadata?.mode !== (handle.address.kind === "agent/remote" ? "remote" : "local") ||
- viewMetadata.agentId !== entryMetadata?.agentId ||
- view.executor?.childSessionId !== input.hookPayload.childSessionId ||
new Set(eventRequestIds).size !== eventRequestIds.length ||
eventRequestIds.length !== viewRequestIds.length ||
eventRequestIds.some((requestId, index) => requestId !== viewRequestIds[index])
@@ -72,6 +64,28 @@ export async function recordTaskInputRequestStep(input: {
return { accepted: false, sessionState: input.sessionState };
}
+ // The child-advertised token is an answer route, not an identity anchor: a
+ // tool run is identified by its run id, a subagent child by its addressed handle.
+ const toolRun = readWorkflowToolExecutor(view.executor?.binding);
+ if (toolRun !== undefined && toolRun.runId !== input.hookPayload.childSessionId) {
+ return { accepted: false, sessionState: input.sessionState };
+ }
+ const handle =
+ toolRun === undefined ? findAddressedTaskHandle(durableSession.state, entry) : undefined;
+ if (toolRun === undefined) {
+ const entryMetadata = readSubagentTaskMetadata(entry);
+ const viewMetadata = readSubagentTaskMetadata(view);
+ if (
+ handle === undefined ||
+ handle.address.sessionId !== input.hookPayload.childSessionId ||
+ viewMetadata?.mode !== (handle.address.kind === "agent/remote" ? "remote" : "local") ||
+ viewMetadata.agentId !== entryMetadata?.agentId ||
+ view.executor?.childSessionId !== input.hookPayload.childSessionId
+ ) {
+ return { accepted: false, sessionState: input.sessionState };
+ }
+ }
+
const hookPayload = namespaceTaskInputRequests(input.hookPayload, input.taskId);
let entries = toProxyInputRequestEntries(hookPayload, input.taskId).map(
([requestId, route], index) => {
@@ -85,7 +99,7 @@ export async function recordTaskInputRequestStep(input: {
] as const;
},
);
- if (handle.address.kind === "agent/remote") {
+ if (handle?.address.kind === "agent/remote") {
const childResponseUrl = createRemoteTaskInputCallbackUrl(
handle.address.url,
createEveTaskInputRoutePath(
@@ -115,6 +129,18 @@ export async function recordTaskInputRequestStep(input: {
};
}
+function findAddressedTaskHandle(
+ state: DurableSession["state"],
+ entry: SessionTaskIndexEntry,
+): Extract<AgentHandle, { phase: "addressed" }> | undefined {
+ const agentId = readSubagentTaskMetadata(entry)?.agentId;
+ if (agentId === undefined) return undefined;
+ return (getAgentHandleStore(state)?.handles ?? []).find(
+ (candidate): candidate is Extract<AgentHandle, { phase: "addressed" }> =>
+ candidate.phase === "addressed" && candidate.identity.id === agentId,
+ );
+}
+
function namespaceTaskInputRequests(
hookPayload: SubagentInputRequestHookPayload,
taskId: string,
diff --git a/packages/eve/src/execution/tasks/parent/tool-execution.ts b/packages/eve/src/execution/tasks/parent/tool-execution.ts
index 3b13afd0d..735d0f3a3 100644
--- a/packages/eve/src/execution/tasks/parent/tool-execution.ts
+++ b/packages/eve/src/execution/tasks/parent/tool-execution.ts
@@ -35,6 +35,8 @@ import {
type BackgroundTask,
} from "#execution/tasks/parent/delegate.js";
import { propagateSubagentExecutorCancel } from "#execution/tasks/parent/dispatch.js";
+import { readWorkflowToolExecutor } from "#execution/tool-run/background.js";
+import { cancelToolRun } from "#execution/tool-run/cancel.js";
import { sendTaskCommand, sendTaskInboundPayload } from "#execution/tasks/parent/run-parent.js";
interface BackgroundToolExecutionRecord {
@@ -338,7 +340,7 @@ async function compensateBackgroundToolExecution(
failures.push(error);
}
// Reject first so the task is terminal and a late child result cannot
- // revive it, then best-effort abort the already-dispatched child using
+ // revive it, then best-effort abort the already-dispatched executor using
// the address carried on its durable executor binding.
const subagent = readSubagentExecutor(record.task.executor);
if (subagent !== undefined) {
@@ -348,6 +350,10 @@ async function compensateBackgroundToolExecution(
taskId: record.task.taskId,
});
}
+ const toolRun = readWorkflowToolExecutor(record.task.executor);
+ if (toolRun !== undefined) {
+ await cancelToolRun(toolRun, "The step that started the tool failed.");
+ }
}
if (failures.length > 0) {
throw new AggregateError(
diff --git a/packages/eve/src/execution/tool-run/answer.ts b/packages/eve/src/execution/tool-run/answer.ts
new file mode 100644
index 000000000..7417721d0
--- /dev/null
+++ b/packages/eve/src/execution/tool-run/answer.ts
@@ -0,0 +1,14 @@
+import { resumeHook } from "#internal/workflow/runtime.js";
+import type { InputResponse } from "#shared/input.js";
+import type { ToolInputResponse } from "#tools/definition.js";
+
+/** Resumed with the bare response, not a session-inbox delivery, so the body can race the hook. */
+export async function resumeToolRunAnswers(
+ answerToken: string,
+ responses: readonly InputResponse[] | undefined,
+): Promise<void> {
+ for (const response of responses ?? []) {
+ const answer: ToolInputResponse = { optionId: response.optionId, text: response.text };
+ await resumeHook(answerToken, answer);
+ }
+}
diff --git a/packages/eve/src/execution/tool-run/background.test.ts b/packages/eve/src/execution/tool-run/background.test.ts
new file mode 100644
index 000000000..376f23d69
--- /dev/null
+++ b/packages/eve/src/execution/tool-run/background.test.ts
@@ -0,0 +1,17 @@
+import { describe, expect, it } from "vitest";
+
+import { parseWorkflowToolInput } from "./background.js";
+
+describe("parseWorkflowToolInput", () => {
+ it("passes a JSON object through", () => {
+ expect(parseWorkflowToolInput({ service: "api" }, "deploy")).toEqual({ service: "api" });
+ });
+
+ it("rejects an input that cannot cross the run boundary, naming the tool", () => {
+ for (const input of [new Date(0), "api", 42, null, undefined, ["api"]]) {
+ expect(() => parseWorkflowToolInput(input, "deploy")).toThrow(
+ /Tool "deploy" is a workflow, so its parsed input must be a JSON object/u,
+ );
+ }
+ });
+});
diff --git a/packages/eve/src/execution/tool-run/background.ts b/packages/eve/src/execution/tool-run/background.ts
new file mode 100644
index 000000000..3d0dc9933
--- /dev/null
+++ b/packages/eve/src/execution/tool-run/background.ts
@@ -0,0 +1,70 @@
+import { buildCallbackContext } from "#context/build-callback-context.js";
+import { deriveRunOwner } from "#execution/tool-run/messages.js";
+import { startToolRun } from "#execution/tool-run/start.js";
+import { WORKFLOW_TOOL_EXECUTOR_KIND, type ToolRunAddress } from "#execution/tool-run/types.js";
+import { getHarnessEmissionState } from "#harness/emission.js";
+import type { HarnessToolDefinition } from "#harness/execute-tool.js";
+import { type JsonObject, parseJsonObject } from "#shared/json.js";
+import type { ToolExecuteOptions } from "#tools/definition.js";
+import type { TaskDelegated, TaskExec, TaskExecutorBinding } from "#tools/task.js";
+
+/** Harness `execute` for a background workflow tool: starts the run as the task's executor. */
+export function createWorkflowToolBackgroundExecute(input: {
+ readonly toolName: string;
+ readonly workflowId: string;
+}): NonNullable<HarnessToolDefinition["execute"]> {
+ return async (
+ toolInput: unknown,
+ options: ToolExecuteOptions,
+ task?: TaskExec,
+ ): Promise<TaskDelegated> => {
+ if (task === undefined) {
+ throw new Error(`Background tool "${input.toolName}" requires a task runtime.`);
+ }
+
+ const started = await startToolRun({
+ callId: options.toolCallId,
+ input: parseWorkflowToolInput(toolInput, input.toolName),
+ owner: deriveRunOwner(task.task.taskInboxToken),
+ session: buildCallbackContext().session,
+ stepIndex: getHarnessEmissionState(task.session.state).stepIndex,
+ toolName: input.toolName,
+ workflowId: input.workflowId,
+ });
+
+ return task.delegated({
+ executor: createWorkflowToolExecutorBinding(started),
+ receipt: {},
+ });
+ };
+}
+
+export function createWorkflowToolExecutorBinding(data: ToolRunAddress): TaskExecutorBinding {
+ return {
+ data: { hookToken: data.hookToken, runId: data.runId },
+ kind: WORKFLOW_TOOL_EXECUTOR_KIND,
+ };
+}
+
+/** Reads the tool run recorded on a task's executor binding, if that is what runs it. */
+export function readWorkflowToolExecutor(
+ binding: TaskExecutorBinding | undefined,
+): ToolRunAddress | undefined {
+ if (binding?.kind !== WORKFLOW_TOOL_EXECUTOR_KIND) return undefined;
+ const { hookToken, runId } = binding.data;
+ return typeof hookToken === "string" && typeof runId === "string"
+ ? { hookToken, runId }
+ : undefined;
+}
+
+/** The input crosses the run's serialization boundary; a schema may emit a `Date`, which cannot. */
+export function parseWorkflowToolInput(toolInput: unknown, toolName: string): JsonObject {
+ try {
+ return parseJsonObject(toolInput);
+ } catch (error) {
+ throw new TypeError(
+ `Tool "${toolName}" is a workflow, so its parsed input must be a JSON object.`,
+ { cause: error },
+ );
+ }
+}
diff --git a/packages/eve/src/execution/tool-run/cancel.ts b/packages/eve/src/execution/tool-run/cancel.ts
new file mode 100644
index 000000000..13e5482fd
--- /dev/null
+++ b/packages/eve/src/execution/tool-run/cancel.ts
@@ -0,0 +1,34 @@
+import type { RunControlMessage } from "#execution/tool-run/messages.js";
+import type { ToolRunAddress } from "#execution/tool-run/types.js";
+import { isTaskWorkflowTargetGone } from "#execution/tasks/workflow-target.js";
+import { cancelRun, getWorld, resumeHook } from "#internal/workflow/runtime.js";
+import { createLogger, logError } from "#internal/logging.js";
+
+const log = createLogger("execution.tool-run");
+
+/**
+ * Asks the run to cancel itself; cancels it outright only if the message cannot
+ * be delivered. Failures are logged, not thrown: the caller has already
+ * committed the cancellation the run was serving.
+ */
+export async function cancelToolRun(run: ToolRunAddress, reason: string): Promise<void> {
+ const cancel: RunControlMessage = { kind: "cancel", reason };
+ try {
+ await resumeHook(run.hookToken, cancel);
+ return;
+ } catch (error) {
+ if (isTaskWorkflowTargetGone(error)) return;
+ logError(log, "failed to signal a workflow tool run to cancel; cancelling it outright", error, {
+ runId: run.runId,
+ });
+ }
+
+ try {
+ await cancelRun(await getWorld(), run.runId, { cancelReason: reason });
+ } catch (error) {
+ if (isTaskWorkflowTargetGone(error)) return;
+ logError(log, "failed to cancel workflow tool run; it may run to completion", error, {
+ runId: run.runId,
+ });
+ }
+}
diff --git a/packages/eve/src/execution/tool-run/dispatch.ts b/packages/eve/src/execution/tool-run/dispatch.ts
new file mode 100644
index 000000000..dda43edbe
--- /dev/null
+++ b/packages/eve/src/execution/tool-run/dispatch.ts
@@ -0,0 +1,83 @@
+import type { PreparedRuntimeActionDispatch } from "#execution/dispatch-runtime-actions-shared.js";
+import { deriveRunOwner } from "#execution/tool-run/messages.js";
+import { startToolRun } from "#execution/tool-run/start.js";
+import { createRuntimeToolResultFromValue } from "#harness/action-result-helpers.js";
+import { recordToolRun } from "#harness/tool-runs.js";
+import { createLogger, logError } from "#internal/logging.js";
+import type { RuntimeSession } from "#execution/agent-handle-dispatch.js";
+import type { RuntimeToolResultActionResult } from "#shared/action-types.js";
+import type { PendingDispatchAction, PendingWorkflowToolAction } from "#shared/dispatch-action.js";
+import { toError } from "#shared/errors.js";
+
+const log = createLogger("execution.tool-run");
+
+export function isWorkflowToolAction(
+ action: PendingDispatchAction,
+): action is PendingWorkflowToolAction {
+ return action.target.kind === "workflow-tool-call";
+}
+
+/**
+ * Starts the run and records it on the session so the turn can bind its
+ * result, route its requests, and cancel it. A start failure settles the call
+ * with an error and records nothing, so nothing is left to cancel.
+ */
+export async function startWorkflowTool(input: {
+ readonly action: PendingWorkflowToolAction;
+ readonly batchEvent: {
+ readonly sequence: number;
+ readonly stepIndex: number;
+ readonly turnId: string;
+ };
+ readonly ownerInboxToken: string | undefined;
+ readonly prepared: Pick<
+ PreparedRuntimeActionDispatch,
+ "auth" | "initiatorAuth" | "parentSession"
+ >;
+ readonly session: RuntimeSession;
+}): Promise<{ readonly result?: RuntimeToolResultActionResult; readonly session: RuntimeSession }> {
+ const { action, batchEvent, prepared, session } = input;
+ if (input.ownerInboxToken === undefined) {
+ throw new Error(
+ `Workflow tool "${action.toolName}" was dispatched without the turn inbox its run reports to.`,
+ );
+ }
+ try {
+ const started = await startToolRun({
+ callId: action.callId,
+ input: action.input,
+ owner: deriveRunOwner(input.ownerInboxToken),
+ session: {
+ auth: { current: prepared.auth, initiator: prepared.initiatorAuth },
+ id: session.sessionId,
+ parent: prepared.parentSession,
+ turn: { id: batchEvent.turnId, sequence: batchEvent.sequence },
+ },
+ stepIndex: batchEvent.stepIndex,
+ toolName: action.toolName,
+ workflowId: action.target.workflowId,
+ });
+ return {
+ session: recordToolRun(session, {
+ callId: action.callId,
+ hookToken: started.hookToken,
+ runId: started.runId,
+ toolName: action.toolName,
+ }),
+ };
+ } catch (error) {
+ logError(log, "workflow tool run failed to start", error, {
+ callId: action.callId,
+ toolName: action.toolName,
+ });
+ return {
+ result: createRuntimeToolResultFromValue({
+ callId: action.callId,
+ isError: true,
+ output: toError(error),
+ toolName: action.toolName,
+ }),
+ session,
+ };
+ }
+}
diff --git a/packages/eve/src/execution/tool-run/emit-run-report-step.ts b/packages/eve/src/execution/tool-run/emit-run-report-step.ts
new file mode 100644
index 000000000..6bad715d4
--- /dev/null
+++ b/packages/eve/src/execution/tool-run/emit-run-report-step.ts
@@ -0,0 +1,33 @@
+import type { RunRef } from "#execution/tool-run/messages.js";
+import { createRuntimeToolResultFromValue } from "#harness/action-result-helpers.js";
+import {
+ createActionPartialEvent,
+ encodeMessageStreamEvent,
+ stampMessageStreamEvent,
+} from "#protocol/message.js";
+import type { JsonValue } from "#shared/json.js";
+
+export async function emitRunReportStep(input: {
+ readonly from: RunRef;
+ readonly parentWritable: WritableStream<Uint8Array>;
+ readonly update: JsonValue;
+}): Promise<void> {
+ "use step";
+
+ const event = createActionPartialEvent({
+ result: createRuntimeToolResultFromValue({
+ callId: input.from.callId,
+ output: input.update,
+ toolName: input.from.toolName,
+ }),
+ sequence: input.from.sequence,
+ stepIndex: input.from.stepIndex,
+ turnId: input.from.turnId,
+ });
+ const writer = input.parentWritable.getWriter();
+ try {
+ await writer.write(encodeMessageStreamEvent(stampMessageStreamEvent(event)));
+ } finally {
+ writer.releaseLock();
+ }
+}
diff --git a/packages/eve/src/execution/tool-run/messages.ts b/packages/eve/src/execution/tool-run/messages.ts
new file mode 100644
index 000000000..daca198b8
--- /dev/null
+++ b/packages/eve/src/execution/tool-run/messages.ts
@@ -0,0 +1,115 @@
+import { createHook, defineHook, type Hook } from "#compiled/@workflow/core/index.js";
+
+import { resumeHookStep } from "#execution/tool-run/resume-hook-step.js";
+import { toolRunAnswerToken } from "#harness/tool-runs.js";
+
+import type { ToolContext, ToolInputRequest, ToolInputResponse } from "#tools/definition.js";
+import type { JsonObject, JsonValue } from "#shared/json.js";
+
+export interface ToolRunOwner {
+ readonly outcome: string;
+ readonly report: string;
+ readonly request: string;
+}
+
+/** Identifies the sending run to an owner that shares its channels across many runs. */
+export interface RunRef {
+ readonly callId: string;
+ /** The tool's parsed input, shown as the request's action when the run asks. */
+ readonly input: JsonObject;
+ readonly runId: string;
+ /** Stream coordinates of the model call that made the tool call. */
+ readonly sequence: number;
+ readonly stepIndex: number;
+ readonly toolName: string;
+ readonly turnId: string;
+}
+
+export type RunOutcome =
+ | { readonly status: "completed"; readonly output: JsonValue }
+ | { readonly status: "failed"; readonly error: unknown }
+ | { readonly status: "cancelled"; readonly reason?: string };
+
+/** Progress sent up from a run; the owner streams it as a turn partial or a task update. */
+export interface RunReport {
+ readonly from: RunRef;
+ readonly update: JsonValue;
+}
+
+/** A question sent up from a run; the owner puts it to the human and resumes `answerToken` with the reply. */
+export interface RunRequestMessage {
+ readonly answerToken: string;
+ readonly from: RunRef;
+ readonly request: ToolInputRequest;
+}
+
+/** The end of a run, sent up once; the owner settles the tool call or the task with it. */
+export interface RunOutcomeMessage {
+ readonly from: RunRef;
+ readonly result: RunOutcome;
+}
+
+export const reportHook = defineHook<RunReport>();
+export const requestHook = defineHook<RunRequestMessage>();
+export const outcomeHook = defineHook<RunOutcomeMessage>();
+
+/** Derived from the owner's inbox token so owner and run agree without exchanging tokens. */
+export function deriveRunOwner(inboxToken: string): ToolRunOwner {
+ return {
+ outcome: `${inboxToken}:outcome`,
+ report: `${inboxToken}:report`,
+ request: `${inboxToken}:request`,
+ };
+}
+
+export type RunControlMessage = { readonly kind: "cancel"; readonly reason: string };
+
+// Not a zod schema: this runs in the replayed body, and zod would ship in every function bundle.
+export function isRunControlMessage(value: unknown): value is RunControlMessage {
+ if (typeof value !== "object" || value === null) return false;
+ const { kind, reason } = value as { kind?: unknown; reason?: unknown };
+ return kind === "cancel" && typeof reason === "string";
+}
+
+// Carried on `ctx` under a global-registry symbol: the framework and application
+// driver layers are separate bundles and share only the objects they pass around.
+const RUN_CONTEXT = Symbol.for("eve.tool-run.context");
+
+interface RunContext {
+ answerSeq: number;
+ readonly from: RunRef;
+ readonly owner: ToolRunOwner;
+}
+
+export function attachRunContext(ctx: ToolContext, context: Omit<RunContext, "answerSeq">): void {
+ Object.defineProperty(ctx, RUN_CONTEXT, {
+ enumerable: false,
+ value: { ...context, answerSeq: 0 },
+ });
+}
+
+function readRunContext(ctx: ToolContext): RunContext {
+ const context = (ctx as { [RUN_CONTEXT]?: RunContext })[RUN_CONTEXT];
+ if (context === undefined) {
+ throw new Error(
+ 'ask() must be called with the context of a workflow tool body ("use workflow").',
+ );
+ }
+ return context;
+}
+
+/**
+ * Asks the human on the session's channel and returns the hook the answer
+ * resumes, as `createHook` would: await it for the answer, or race it against
+ * a `sleep` for a deadline. Synchronous because a `Hook` is thenable: an async
+ * `ask` would resolve to the answer, never the hook.
+ */
+export function ask(ctx: ToolContext, request: ToolInputRequest): Hook<ToolInputResponse> {
+ const context = readRunContext(ctx);
+ const answer = createHook<ToolInputResponse>({
+ token: toolRunAnswerToken(context.from.runId, context.answerSeq++),
+ });
+ const message: RunRequestMessage = { answerToken: answer.token, from: context.from, request };
+ void resumeHookStep(context.owner.request, message);
+ return answer;
+}
diff --git a/packages/eve/src/execution/tool-run/owner-channels.test.ts b/packages/eve/src/execution/tool-run/owner-channels.test.ts
new file mode 100644
index 000000000..ca3be9dbe
--- /dev/null
+++ b/packages/eve/src/execution/tool-run/owner-channels.test.ts
@@ -0,0 +1,85 @@
+import { describe, expect, it } from "vitest";
+
+import { createChannelReader, raceChannelReads } from "./owner-channels.js";
+
+/** A hook stand-in: an async iterable fed by hand. */
+function channel<T>() {
+ const queue: T[] = [];
+ const waiters: ((value: IteratorResult<T>) => void)[] = [];
+ return {
+ iterable: {
+ [Symbol.asyncIterator]: () => ({
+ next: () =>
+ new Promise<IteratorResult<T>>((resolve) => {
+ const value = queue.shift();
+ if (value !== undefined) resolve({ done: false, value });
+ else waiters.push(resolve);
+ }),
+ }),
+ },
+ push(value: T) {
+ const waiter = waiters.shift();
+ if (waiter) waiter({ done: false, value });
+ else queue.push(value);
+ },
+ };
+}
+
+describe("raceChannelReads", () => {
+ it("keeps a read that lands between races for the next race to claim", async () => {
+ const report = channel<string>();
+ const outcome = channel<string>();
+ const readers = [
+ createChannelReader("report", report.iterable),
+ createChannelReader("outcome", outcome.iterable),
+ ] as const;
+
+ const first = raceChannelReads(readers);
+ outcome.push("done");
+ expect(await first).toEqual({ channel: "outcome", next: { done: false, value: "done" } });
+
+ // The report lands while no race is waiting — as when an owner is
+ // awaiting a step — and must be delivered by the next race.
+ report.push("progress");
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(await raceChannelReads(readers)).toEqual({
+ channel: "report",
+ next: { done: false, value: "progress" },
+ });
+ });
+
+ it("claims landed reads in array order so progress precedes an outcome", async () => {
+ const report = channel<string>();
+ const outcome = channel<string>();
+ const readers = [
+ createChannelReader("report", report.iterable),
+ createChannelReader("outcome", outcome.iterable),
+ ] as const;
+
+ const race = raceChannelReads(readers);
+ outcome.push("done");
+ report.push("progress");
+ expect((await race).channel).toBe("report");
+ expect((await raceChannelReads(readers)).channel).toBe("outcome");
+ });
+
+ it("returns the extra value when it settles before any channel", async () => {
+ const report = channel<string>();
+ const readers = [createChannelReader("report", report.iterable)] as const;
+ const cancelled = Promise.resolve("cancel" as const);
+
+ expect(await raceChannelReads(readers, cancelled)).toBe("cancel");
+ report.push("late");
+ expect((await raceChannelReads(readers)).channel).toBe("report");
+ });
+
+ it("rethrows a failed read from the race that would have claimed it", async () => {
+ const failing = {
+ [Symbol.asyncIterator]: () => ({
+ next: () => Promise.reject(new Error("hook gone")),
+ }),
+ };
+ const readers = [createChannelReader("report", failing)] as const;
+ await expect(raceChannelReads(readers)).rejects.toThrow("hook gone");
+ });
+});
diff --git a/packages/eve/src/execution/tool-run/owner-channels.ts b/packages/eve/src/execution/tool-run/owner-channels.ts
new file mode 100644
index 000000000..4318ea5f5
--- /dev/null
+++ b/packages/eve/src/execution/tool-run/owner-channels.ts
@@ -0,0 +1,67 @@
+/**
+ * Races reads across several hooks. A read that lands while no race is waiting
+ * is kept until one claims it: the owner awaits steps between races, and a
+ * resume arriving then must not be dropped or re-issued. Claims follow array
+ * order because separate hooks carry no order between them.
+ */
+export interface ChannelReader<C extends string, T> {
+ readonly channel: C;
+ readonly iterator: AsyncIterator<T>;
+ /** Reads that have landed and not yet been claimed, oldest first. */
+ readonly landed: IteratorResult<T>[];
+ failure?: { readonly error: unknown };
+ pending?: Promise<void>;
+}
+
+export function createChannelReader<C extends string, T>(
+ channel: C,
+ iterable: AsyncIterable<T>,
+): ChannelReader<C, T> {
+ return { channel, iterator: iterable[Symbol.asyncIterator](), landed: [] };
+}
+
+export type ChannelRead<R extends readonly ChannelReader<string, unknown>[]> = {
+ [I in keyof R]: R[I] extends ChannelReader<infer C, infer T>
+ ? { readonly channel: C; readonly next: IteratorResult<T> }
+ : never;
+}[number];
+
+/**
+ * Channel reads wake the loop with `undefined` after buffering their result;
+ * a cancel wins the race outright.
+ */
+export function raceChannelReads<const R extends readonly ChannelReader<string, unknown>[]>(
+ readers: R,
+): Promise<ChannelRead<R>>;
+export function raceChannelReads<const R extends readonly ChannelReader<string, unknown>[]>(
+ readers: R,
+ cancelled: Promise<"cancel"> | undefined,
+): Promise<ChannelRead<R> | "cancel">;
+export async function raceChannelReads<const R extends readonly ChannelReader<string, unknown>[]>(
+ readers: R,
+ cancelled?: Promise<"cancel">,
+): Promise<ChannelRead<R> | "cancel"> {
+ while (true) {
+ for (const reader of readers) {
+ if (reader.failure !== undefined) throw reader.failure.error;
+ const next = reader.landed.shift();
+ if (next !== undefined) return { channel: reader.channel, next } as ChannelRead<R>;
+ }
+ const waits: Promise<unknown>[] = [];
+ for (const reader of readers) {
+ reader.pending ??= reader.iterator.next().then(
+ (next) => {
+ reader.landed.push(next);
+ reader.pending = undefined;
+ },
+ (error: unknown) => {
+ reader.failure = { error };
+ reader.pending = undefined;
+ },
+ );
+ waits.push(reader.pending);
+ }
+ if (cancelled !== undefined) waits.push(cancelled);
+ if ((await Promise.race(waits)) === "cancel") return "cancel";
+ }
+}
diff --git a/packages/eve/src/execution/tool-run/owner-inbox.ts b/packages/eve/src/execution/tool-run/owner-inbox.ts
new file mode 100644
index 000000000..e7c13c8c4
--- /dev/null
+++ b/packages/eve/src/execution/tool-run/owner-inbox.ts
@@ -0,0 +1,108 @@
+import type { SubagentInputRequestHookPayload } from "#channel/types.js";
+import type {
+ RunOutcomeMessage,
+ RunRef,
+ RunReport,
+ RunRequestMessage,
+} from "#execution/tool-run/messages.js";
+import type { RuntimeToolResultActionResult } from "#shared/action-types.js";
+import type { InputRequest } from "#shared/input.js";
+import type { JsonValue } from "#shared/json.js";
+import type { TaskCommand, TaskInboundUpdate } from "#tasks/types.js";
+import type { ToolInputRequest } from "#tools/definition.js";
+
+// Type-only imports: these run in the turn and task driver bodies.
+
+/** A cancelled run settles the call as an error so the owner never waits on it. */
+export function runOutcomeToToolResult(message: RunOutcomeMessage): RuntimeToolResultActionResult {
+ const { from, result } = message;
+ if (result.status === "completed") {
+ return {
+ callId: from.callId,
+ kind: "tool-result",
+ output: result.output,
+ toolName: from.toolName,
+ };
+ }
+ const output: JsonValue =
+ result.status === "failed"
+ ? errorMessage(result.error)
+ : (result.reason ?? "The tool run was cancelled.");
+ return {
+ callId: from.callId,
+ isError: true,
+ kind: "tool-result",
+ output,
+ toolName: from.toolName,
+ };
+}
+
+function errorMessage(error: unknown): string {
+ if (typeof error === "object" && error !== null && "message" in error) {
+ const message = (error as { message?: unknown }).message;
+ if (typeof message === "string") return message;
+ }
+ return String(error);
+}
+
+/** The answer hook token is both the request id and the route, so one resume reaches the body. */
+export function runRequestToInputRequestPayload(
+ message: RunRequestMessage,
+): SubagentInputRequestHookPayload {
+ const { answerToken, from, request } = message;
+ return {
+ callId: from.callId,
+ childContinuationToken: answerToken,
+ childSessionId: from.runId,
+ event: {
+ requests: [toInputRequest(request, from, answerToken)],
+ sequence: from.sequence,
+ stepIndex: from.stepIndex,
+ turnId: from.turnId,
+ },
+ kind: "subagent-input-request",
+ subagentName: from.toolName,
+ };
+}
+
+function toInputRequest(request: ToolInputRequest, from: RunRef, requestId: string): InputRequest {
+ if (typeof request.prompt !== "string" || request.prompt.length === 0) {
+ throw new TypeError("A tool run request needs a non-empty `prompt`.");
+ }
+ const normalized: InputRequest = {
+ action: { callId: from.callId, input: from.input, kind: "tool-call", toolName: from.toolName },
+ kind: "question",
+ prompt: request.prompt,
+ requestId,
+ };
+ if (request.allowFreeform !== undefined) normalized.allowFreeform = request.allowFreeform;
+ if (request.display !== undefined) normalized.display = request.display;
+ if (request.options !== undefined) normalized.options = [...request.options];
+ return normalized;
+}
+
+export function runReportToTaskUpdate(
+ message: RunReport,
+ taskId: string,
+ updateIndex: number,
+): TaskInboundUpdate {
+ return {
+ callId: message.from.callId,
+ kind: "task-update",
+ message: typeof message.update === "string" ? message.update : JSON.stringify(message.update),
+ updateEpoch: taskId,
+ updateIndex,
+ };
+}
+
+/** A cancelled run only settles the executor: the task itself was already cancelled. */
+export function runOutcomeToTaskCommand(message: RunOutcomeMessage): TaskCommand {
+ const { result } = message;
+ if (result.status === "completed") {
+ return { data: result.output, kind: "complete", lifecycle: "terminal" };
+ }
+ if (result.status === "failed") {
+ return { data: errorMessage(result.error), kind: "fail", lifecycle: "terminal" };
+ }
+ return { kind: "settle-executor" };
+}
diff --git a/packages/eve/src/execution/tool-run/owner.ts b/packages/eve/src/execution/tool-run/owner.ts
new file mode 100644
index 000000000..ab4f23506
--- /dev/null
+++ b/packages/eve/src/execution/tool-run/owner.ts
@@ -0,0 +1,40 @@
+import { disposeHook } from "#execution/hook-ownership.js";
+import {
+ deriveRunOwner,
+ outcomeHook,
+ reportHook,
+ requestHook,
+ type RunOutcomeMessage,
+ type RunReport,
+ type RunRequestMessage,
+} from "#execution/tool-run/messages.js";
+import { type ChannelReader, createChannelReader } from "#execution/tool-run/owner-channels.js";
+
+/** In read priority: what a run said before its outcome lands first. */
+export type RunOwnerReaders = readonly [
+ ChannelReader<"report", RunReport>,
+ ChannelReader<"request", RunRequestMessage>,
+ ChannelReader<"outcome", RunOutcomeMessage>,
+];
+
+export interface RunOwnerChannels {
+ readonly readers: RunOwnerReaders;
+ dispose(): Promise<void>;
+}
+
+export function openRunOwnerChannels(inboxToken: string): RunOwnerChannels {
+ const owner = deriveRunOwner(inboxToken);
+ const report = reportHook.create({ token: owner.report });
+ const request = requestHook.create({ token: owner.request });
+ const outcome = outcomeHook.create({ token: owner.outcome });
+ return {
+ readers: [
+ createChannelReader("report", report),
+ createChannelReader("request", request),
+ createChannelReader("outcome", outcome),
+ ],
+ async dispose() {
+ await Promise.all([disposeHook(report), disposeHook(request), disposeHook(outcome)]);
+ },
+ };
+}
diff --git a/packages/eve/src/execution/tool-run/resume-hook-step.ts b/packages/eve/src/execution/tool-run/resume-hook-step.ts
new file mode 100644
index 000000000..3f1c74b5e
--- /dev/null
+++ b/packages/eve/src/execution/tool-run/resume-hook-step.ts
@@ -0,0 +1,18 @@
+import { isTaskWorkflowTargetGone } from "#execution/tasks/workflow-target.js";
+import { resumeHook } from "#internal/workflow/runtime.js";
+
+/** `resumeHook` as a step, so the runtime API stays out of the driver. */
+export async function resumeHookStep(
+ token: string,
+ payload: unknown,
+ options?: { readonly ifPresent?: boolean },
+): Promise<void> {
+ "use step";
+
+ try {
+ await resumeHook(token, payload);
+ } catch (error) {
+ if (options?.ifPresent === true && isTaskWorkflowTargetGone(error)) return;
+ throw error;
+ }
+}
diff --git a/packages/eve/src/execution/tool-run/run-control.ts b/packages/eve/src/execution/tool-run/run-control.ts
new file mode 100644
index 000000000..c190fefab
--- /dev/null
+++ b/packages/eve/src/execution/tool-run/run-control.ts
@@ -0,0 +1,65 @@
+import { createHook, type Hook } from "#compiled/@workflow/core/index.js";
+
+import { isRunControlMessage, type RunControlMessage } from "#execution/tool-run/messages.js";
+
+/**
+ * The run's control inbox. An unawaited hook read is not scheduled under
+ * replay, so `cancelled` must be raced for a cancel to be observed at all.
+ */
+export interface RunControlInbox {
+ readonly hook: Hook<RunControlMessage>;
+ readonly signal: AbortSignal;
+ /** Rejects with {@link RunCancelledError} when a cancel message arrives; never resolves. */
+ readonly cancelled: Promise<never>;
+ reason(): string | undefined;
+}
+
+/** Opens without claiming, so a losing duplicate start never trips the signal. */
+export function openRunControlInbox(hookToken: string): RunControlInbox {
+ const hook = createHook<RunControlMessage>({ token: hookToken });
+ // Hook promises and iterators share one durable cursor. Create the iterator
+ // before the caller claims so conflict replay is consumed by getConflict().
+ const iterator = hook[Symbol.asyncIterator]();
+ const controller = new AbortController();
+ let cancelReason: string | undefined;
+
+ const cancelled = consumeCancel(iterator, (reason) => {
+ cancelReason = reason;
+ controller.abort(new RunCancelledError(reason));
+ });
+ // Racing drives the read; a lone reference must not surface as unhandled.
+ cancelled.catch(() => {});
+
+ return {
+ cancelled,
+ hook,
+ reason: () => cancelReason,
+ signal: controller.signal,
+ };
+}
+
+// End-of-stream parks forever so the race is simply never won.
+async function consumeCancel(
+ iterator: AsyncIterator<RunControlMessage>,
+ onCancel: (reason: string) => void,
+): Promise<never> {
+ while (true) {
+ let next: IteratorResult<RunControlMessage>;
+ try {
+ next = await iterator.next();
+ } catch {
+ return await new Promise<never>(() => {});
+ }
+ if (next.done === true) return await new Promise<never>(() => {});
+ if (!isRunControlMessage(next.value)) continue;
+ onCancel(next.value.reason);
+ throw new RunCancelledError(next.value.reason);
+ }
+}
+
+export class RunCancelledError extends Error {
+ constructor(reason: string) {
+ super(reason);
+ this.name = "RunCancelledError";
+ }
+}
diff --git a/packages/eve/src/execution/tool-run/start.ts b/packages/eve/src/execution/tool-run/start.ts
new file mode 100644
index 000000000..b58c055bc
--- /dev/null
+++ b/packages/eve/src/execution/tool-run/start.ts
@@ -0,0 +1,32 @@
+import type { ToolRunWorkflowInput } from "#execution/tool-run/types.js";
+import {
+ startWorkflowPreferLatest,
+ toolRunWorkflowReference,
+ waitForCommandHookOwner,
+} from "#execution/workflow-runtime.js";
+import { deriveAgentOperationId } from "#harness/handles/operation-id.js";
+
+// Derived from the call alone so a replayed dispatch starts a duplicate that
+// loses the claim and still resolves to the run that owns the call.
+export function deriveToolRunHookToken(input: {
+ readonly callId: string;
+ readonly parentSessionId: string;
+ readonly parentTurnId: string;
+}): string {
+ return `eve:tool-run:${deriveAgentOperationId(input)}`;
+}
+
+/** Resolves once the run owns its hook. Call from inside a `"use step"` body. */
+export async function startToolRun(
+ input: Omit<ToolRunWorkflowInput, "hookToken">,
+): Promise<{ readonly hookToken: string; readonly runId: string }> {
+ const hookToken = deriveToolRunHookToken({
+ callId: input.callId,
+ parentSessionId: input.session.id,
+ parentTurnId: input.session.turn.id,
+ });
+ const workflowInput: ToolRunWorkflowInput = { ...input, hookToken };
+ await startWorkflowPreferLatest(toolRunWorkflowReference, [workflowInput]);
+ const owner = await waitForCommandHookOwner(hookToken);
+ return { hookToken, runId: owner.runId };
+}
diff --git a/packages/eve/src/execution/tool-run/tool-run.integration.test.ts b/packages/eve/src/execution/tool-run/tool-run.integration.test.ts
new file mode 100644
index 000000000..fc9f62079
--- /dev/null
+++ b/packages/eve/src/execution/tool-run/tool-run.integration.test.ts
@@ -0,0 +1,565 @@
+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 { resumeSessionInbox } from "#execution/wire/session-inbox-resume.js";
+import { workflowEntry } from "#execution/workflow-entry.js";
+import { createTestRuntime, type TestRuntime } from "#internal/testing/app-harness.js";
+import { captureTurnEvents, filterEventsByType } from "#internal/testing/events.js";
+import {
+ askThenRaceWorkflow,
+ confirmDeployWorkflow,
+ deployServiceWorkflow,
+ failingDeployWorkflow,
+ holdUntilAbortedWorkflow,
+ reportingDeployWorkflow,
+ stepThenRaceWorkflow,
+} from "#internal/testing/workflow-tool-fixtures.js";
+import { waitForHook } from "#internal/testing/workflow-test-helpers.js";
+import { getRun, getWorld, start } from "#internal/workflow/runtime.js";
+import { toolRunWorkflowReference } 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";
+
+const DEPLOY_INPUT_SCHEMA = toInputSchema({
+ additionalProperties: false,
+ properties: { service: { type: "string" } },
+ required: ["service"],
+ type: "object",
+});
+
+function buildSerializedContext(input: {
+ readonly continuationToken: string;
+ readonly mode: "conversation" | "task";
+ readonly requestInput?: boolean;
+}): Record<string, unknown> {
+ return {
+ "eve.auth": null,
+ "eve.bundle": { source: createBundledRuntimeCompiledArtifactsSource() },
+ "eve.capabilities": { requestInput: input.requestInput ?? false },
+ "eve.channel": { kind: "http", state: {} },
+ "eve.continuationToken": input.continuationToken,
+ "eve.mode": input.mode,
+ };
+}
+
+/**
+ * Registers one fixture workflow as an authored tool. The fixture module
+ * passed through the test tier's client transform, so `execute` is the stub
+ * the real pipeline produces: a function carrying its `workflowId`.
+ */
+async function createWorkflowToolRuntime(input: {
+ readonly agentName: string;
+ readonly execute: (...args: never[]) => unknown;
+ readonly toolName: string;
+}): Promise<TestRuntime> {
+ const tool: ResolvedToolDefinition = {
+ description: `Deploys a service (${input.toolName}).`,
+ execute: input.execute as ResolvedToolDefinition["execute"],
+ 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: { 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 runtime;
+}
+
+/** Ids of every tool run in the shared world, so a test can spot the one it started. */
+async function listToolRunIds(): Promise<Set<string>> {
+ const world = await getWorld();
+ const page = await world.runs.list({ pagination: { limit: 100 } });
+ return new Set(
+ page.data
+ .filter(
+ (entry: { readonly workflowName?: string }) =>
+ entry.workflowName === toolRunWorkflowReference.workflowId,
+ )
+ .map((entry: { readonly runId: string }) => entry.runId),
+ );
+}
+
+/** Polls until exactly one tool run exists that was not in `before`. */
+async function waitForNewToolRun(before: ReadonlySet<string>, timeout = 15_000): Promise<string> {
+ const deadline = Date.now() + timeout;
+ while (Date.now() < deadline) {
+ const started = [...(await listToolRunIds())].filter((runId) => !before.has(runId));
+ if (started.length === 1) return started[0]!;
+ if (started.length > 1) throw new Error(`Expected one new tool run, found ${started.length}.`);
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ }
+ throw new Error("Timed out waiting for a tool run to start.");
+}
+
+/** Polls one run until it reaches a terminal status, returning that status. */
+async function waitForRunTerminal(runId: string, timeout = 15_000): Promise<string> {
+ const terminal = new Set(["completed", "failed", "cancelled"]);
+ const deadline = Date.now() + timeout;
+ while (Date.now() < deadline) {
+ const status = await getRun(runId).status;
+ if (terminal.has(status)) return status;
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ }
+ throw new Error(`Timed out waiting for run ${runId} to reach a terminal status.`);
+}
+
+function eventsText(events: readonly { readonly data?: unknown }[]): string {
+ return events.map((event) => JSON.stringify(event.data ?? null)).join("\n");
+}
+
+describe("workflow tools", () => {
+ it("parks the turn on a workflow tool and resumes with its return value", async () => {
+ const runtime = await createWorkflowToolRuntime({
+ agentName: "workflow-tool-wait",
+ execute: deployServiceWorkflow,
+ toolName: "deploy_service",
+ });
+
+ const output = await runtime.run(async () => {
+ const run = await start(workflowEntry, [
+ {
+ input: { message: 'Run deploy_service with service "api"' },
+ serializedContext: buildSerializedContext({
+ continuationToken: "schedule:workflow-tool-wait",
+ mode: "task",
+ }),
+ },
+ ]);
+ const result = await run.returnValue;
+ return String(result.output);
+ });
+
+ expect(output).toContain('"plan":"plan:api"');
+ expect(output).toContain('"callId":"call_deploy_service');
+ });
+
+ it("settles the call with an error when the workflow body throws", async () => {
+ const runtime = await createWorkflowToolRuntime({
+ agentName: "workflow-tool-fail",
+ execute: failingDeployWorkflow,
+ toolName: "deploy_service",
+ });
+
+ const output = await runtime.run(async () => {
+ const run = await start(workflowEntry, [
+ {
+ input: { message: 'Run deploy_service with service "api"' },
+ serializedContext: buildSerializedContext({
+ continuationToken: "schedule:workflow-tool-fail",
+ mode: "task",
+ }),
+ },
+ ]);
+ const result = await run.returnValue;
+ return String(result.output);
+ });
+
+ expect(output).toContain("deploy of api exploded");
+ });
+
+ it("routes a human answer to the waiting workflow body", async () => {
+ const runtime = await createWorkflowToolRuntime({
+ agentName: "workflow-tool-hitl",
+ execute: confirmDeployWorkflow,
+ toolName: "confirm_deploy",
+ });
+
+ await runtime.run(async () => {
+ const run = await start(workflowEntry, [
+ {
+ input: { message: 'Run confirm_deploy with service "api"' },
+ serializedContext: buildSerializedContext({
+ continuationToken: "http:workflow-tool-hitl",
+ mode: "conversation",
+ requestInput: true,
+ }),
+ },
+ ]);
+ const stream = captureTurnEvents(run);
+
+ try {
+ const asked = await stream.nextTurn();
+ const requested = filterEventsByType(asked, "input.requested");
+ expect(requested).toHaveLength(1);
+ const request = (requested[0] as InputRequestedStreamEvent).data.requests[0]!;
+ expect(request).toMatchObject({
+ action: { input: { service: "api" }, kind: "tool-call", toolName: "confirm_deploy" },
+ display: "confirmation",
+ kind: "question",
+ prompt: "Apply plan:api?",
+ });
+ expect(request.options?.map((option) => option.id)).toEqual(["approve", "cancel"]);
+
+ const commandToken = sessionCommandHookToken(run.runId);
+ await waitForHook(run, { token: commandToken });
+ await resumeSessionInbox(commandToken, {
+ kind: "send",
+ payload: { inputResponses: [{ optionId: "approve", requestId: request.requestId }] },
+ });
+
+ const answered = await stream.nextTurn();
+ const results = filterEventsByType(answered, "action.result");
+ expect(results.map((event) => JSON.stringify(event.data.result.output))).toContainEqual(
+ JSON.stringify({ approved: true, service: "api" }),
+ );
+ expect(filterEventsByType(answered, "turn.failed")).toHaveLength(0);
+ } finally {
+ stream.dispose();
+ await run.cancel();
+ }
+ });
+ }, 60_000);
+
+ it("times out a hook raced against a sleep when it is not resumed", async () => {
+ const runtime = await createWorkflowToolRuntime({
+ agentName: "workflow-tool-deadline",
+ execute: stepThenRaceWorkflow,
+ toolName: "deploy_service",
+ });
+
+ await runtime.run(async () => {
+ const run = await start(workflowEntry, [
+ {
+ input: { message: "Run deploy_service" },
+ serializedContext: buildSerializedContext({
+ continuationToken: "http:workflow-tool-deadline",
+ mode: "conversation",
+ }),
+ },
+ ]);
+ const stream = captureTurnEvents(run);
+ try {
+ const settled = await stream.nextTurn();
+ const outputs = filterEventsByType(settled, "action.result").map((event) =>
+ JSON.stringify(event.data.result.output),
+ );
+ expect(outputs.some((output) => output.includes('"decided":"timed out"'))).toBe(true);
+ expect(filterEventsByType(settled, "turn.failed")).toHaveLength(0);
+ } finally {
+ stream.dispose();
+ await run.cancel();
+ }
+ });
+ }, 30_000);
+
+ it("lets a deadline win a race against an unanswered ask", async () => {
+ const runtime = await createWorkflowToolRuntime({
+ agentName: "workflow-tool-ask-deadline",
+ execute: askThenRaceWorkflow,
+ toolName: "confirm_deploy",
+ });
+
+ await runtime.run(async () => {
+ const run = await start(workflowEntry, [
+ {
+ input: { message: 'Run confirm_deploy with service "api"' },
+ serializedContext: buildSerializedContext({
+ continuationToken: "http:workflow-tool-ask-deadline",
+ mode: "conversation",
+ requestInput: true,
+ }),
+ },
+ ]);
+ const stream = captureTurnEvents(run);
+ try {
+ // Asking parks the turn; the sleep then wins and the same turn resumes.
+ const asked = await stream.nextTurn();
+ expect(filterEventsByType(asked, "input.requested")).toHaveLength(1);
+
+ const resumed = await stream.nextTurn();
+ const outputs = filterEventsByType(resumed, "action.result").map((event) =>
+ JSON.stringify(event.data.result.output),
+ );
+ expect(outputs.some((output) => output.includes('"decided":"timed out"'))).toBe(true);
+ expect(filterEventsByType(resumed, "turn.failed")).toHaveLength(0);
+ } finally {
+ stream.dispose();
+ await run.cancel();
+ }
+ });
+ }, 30_000);
+
+ it("cancels the run when the waiting turn is cancelled and lets the body clean up", async () => {
+ const runtime = await createWorkflowToolRuntime({
+ agentName: "workflow-tool-cancel",
+ execute: holdUntilAbortedWorkflow,
+ toolName: "deploy_service",
+ });
+
+ await runtime.run(async () => {
+ const before = await listToolRunIds();
+ const run = await start(workflowEntry, [
+ {
+ input: { message: 'Run deploy_service with service "api"' },
+ serializedContext: buildSerializedContext({
+ continuationToken: "http:workflow-tool-cancel",
+ mode: "conversation",
+ }),
+ },
+ ]);
+ const stream = captureTurnEvents(run);
+
+ try {
+ const toolRunId = await waitForNewToolRun(before);
+ const commandToken = sessionCommandHookToken(run.runId);
+ await waitForHook(run, { token: commandToken });
+ await resumeSessionInbox(commandToken, { kind: "cancel", turnId: "turn_0" });
+
+ // The body is holding in a step that received ctx.abortSignal, so the
+ // run ends well inside its grace period once the step rejects and
+ // `finally` runs; a run that ignored the signal would still be running.
+ expect(await waitForRunTerminal(toolRunId)).toBe("completed");
+
+ await resumeSessionInbox(commandToken, {
+ kind: "send",
+ payload: { message: "Thanks, no deploy today." },
+ });
+ const next = await stream.nextTurn();
+ expect(filterEventsByType(next, "turn.started")).toHaveLength(1);
+ expect(filterEventsByType(next, "turn.failed")).toHaveLength(0);
+ expect(next.at(-1)?.type).toBe("session.waiting");
+ } finally {
+ stream.dispose();
+ await run.cancel();
+ }
+ });
+ }, 60_000);
+
+ it("runs a background workflow tool as its task's executor", async () => {
+ const runtime = await createWorkflowToolRuntime({
+ agentName: "workflow-tool-background",
+ execute: reportingDeployWorkflow,
+ toolName: "report_deploy",
+ });
+
+ await runtime.run(async () => {
+ enableBackgroundTool(runtime, "report_deploy");
+
+ const run = await start(workflowEntry, [
+ {
+ input: { message: 'Run report_deploy with service "api"' },
+ serializedContext: buildSerializedContext({
+ continuationToken: "http:workflow-tool-background",
+ mode: "conversation",
+ }),
+ },
+ ]);
+ const stream = captureTurnEvents(run);
+
+ try {
+ const receiptTurn = await stream.nextTurn();
+ const receipt = filterEventsByType(receiptTurn, "action.result").find(
+ (event) => event.data.result.kind === "tool-result",
+ );
+ expect(receipt?.data.result.output).toMatchObject({ status: "working" });
+ expect(filterEventsByType(receiptTurn, "turn.failed")).toHaveLength(0);
+
+ const notifications: string[] = [];
+ for (
+ let turn = 0;
+ turn < 3 && !notifications.some((text) => text.includes("is completed"));
+ turn += 1
+ ) {
+ const woken = await stream.nextTurn();
+ expect(filterEventsByType(woken, "turn.failed")).toHaveLength(0);
+ notifications.push(eventsText(filterEventsByType(woken, "message.received")));
+ }
+ const text = notifications.join("\n");
+ expect(text).toContain("update: planned api");
+ expect(text).toContain("is completed");
+ expect(text).toContain("plan:api");
+ } finally {
+ stream.dispose();
+ await run.cancel();
+ }
+ });
+ }, 90_000);
+
+ it("streams a waiting tool's yields as action.partial and settles with its return", async () => {
+ const runtime = await createWorkflowToolRuntime({
+ agentName: "workflow-tool-progress",
+ execute: reportingDeployWorkflow,
+ toolName: "deploy_service",
+ });
+
+ await runtime.run(async () => {
+ const run = await start(workflowEntry, [
+ {
+ input: { message: 'Run deploy_service with service "api"' },
+ serializedContext: buildSerializedContext({
+ continuationToken: "http:workflow-tool-progress",
+ mode: "conversation",
+ }),
+ },
+ ]);
+ const stream = captureTurnEvents(run);
+ try {
+ const settled = await stream.nextTurn();
+ const partials = filterEventsByType(settled, "action.partial").map((event) =>
+ JSON.stringify(event.data.result.output),
+ );
+ expect(partials).toContainEqual(JSON.stringify("planned api"));
+ const results = filterEventsByType(settled, "action.result").map((event) =>
+ JSON.stringify(event.data.result.output),
+ );
+ expect(results).toContainEqual(JSON.stringify({ plan: "plan:api" }));
+ expect(filterEventsByType(settled, "turn.failed")).toHaveLength(0);
+ } finally {
+ stream.dispose();
+ await run.cancel();
+ }
+ });
+ }, 30_000);
+
+ it("wakes the agent with the failure when a background workflow tool throws", async () => {
+ const runtime = await createWorkflowToolRuntime({
+ agentName: "workflow-tool-background-fail",
+ execute: failingDeployWorkflow,
+ toolName: "deploy_service",
+ });
+
+ await runtime.run(async () => {
+ enableBackgroundTool(runtime, "deploy_service");
+
+ const run = await start(workflowEntry, [
+ {
+ input: { message: 'Run deploy_service with service "api"' },
+ serializedContext: buildSerializedContext({
+ continuationToken: "http:workflow-tool-background-fail",
+ mode: "conversation",
+ }),
+ },
+ ]);
+ const stream = captureTurnEvents(run);
+
+ try {
+ const receiptTurn = await stream.nextTurn();
+ expect(filterEventsByType(receiptTurn, "turn.failed")).toHaveLength(0);
+
+ const notifications: string[] = [];
+ for (
+ let turn = 0;
+ turn < 3 && !notifications.some((t) => t.includes("failed"));
+ turn += 1
+ ) {
+ const woken = await stream.nextTurn();
+ expect(filterEventsByType(woken, "turn.failed")).toHaveLength(0);
+ notifications.push(eventsText(filterEventsByType(woken, "message.received")));
+ }
+ const text = notifications.join("\n");
+ expect(text).toContain("(deploy_service) failed.");
+ expect(text).toContain("deploy of api exploded");
+ } finally {
+ stream.dispose();
+ await run.cancel();
+ }
+ });
+ }, 90_000);
+
+ it("lets a background workflow tool ask now and act when answered", async () => {
+ const runtime = await createWorkflowToolRuntime({
+ agentName: "workflow-tool-background-hitl",
+ execute: confirmDeployWorkflow,
+ toolName: "confirm_deploy",
+ });
+
+ await runtime.run(async () => {
+ enableBackgroundTool(runtime, "confirm_deploy");
+
+ const run = await start(workflowEntry, [
+ {
+ input: { message: 'Run confirm_deploy with service "api"' },
+ serializedContext: buildSerializedContext({
+ continuationToken: "http:workflow-tool-background-hitl",
+ mode: "conversation",
+ requestInput: true,
+ }),
+ },
+ ]);
+ const stream = captureTurnEvents(run);
+
+ try {
+ const receiptTurn = await stream.nextTurn();
+ expect(filterEventsByType(receiptTurn, "turn.failed")).toHaveLength(0);
+ expect(
+ filterEventsByType(receiptTurn, "action.result").some(
+ (event) =>
+ event.data.result.kind === "tool-result" &&
+ typeof event.data.result.output === "object" &&
+ event.data.result.output !== null &&
+ "taskId" in event.data.result.output,
+ ),
+ ).toBe(true);
+
+ // The question arrives after the turn that called the tool ended.
+ let request: InputRequestedStreamEvent["data"]["requests"][number] | undefined;
+ for (let turn = 0; turn < 3 && request === undefined; turn += 1) {
+ const woken = await stream.nextTurn();
+ expect(filterEventsByType(woken, "turn.failed")).toHaveLength(0);
+ request = (
+ filterEventsByType(woken, "input.requested")[0] as InputRequestedStreamEvent | undefined
+ )?.data.requests[0];
+ }
+ expect(request).toMatchObject({ kind: "question", prompt: "Apply plan:api?" });
+
+ // The stable session inbox already took the task's wake, so it is
+ // known to exist; answer through it directly.
+ await resumeSessionInbox(sessionCommandHookToken(run.runId), {
+ kind: "send",
+ payload: { inputResponses: [{ optionId: "approve", requestId: request!.requestId }] },
+ });
+
+ const notifications: string[] = [];
+ for (
+ let turn = 0;
+ turn < 3 && !notifications.some((text) => text.includes("is completed"));
+ turn += 1
+ ) {
+ const woken = await stream.nextTurn();
+ expect(filterEventsByType(woken, "turn.failed")).toHaveLength(0);
+ notifications.push(eventsText(filterEventsByType(woken, "message.received")));
+ }
+ const text = notifications.join("\n");
+ expect(text).toContain("is completed");
+ expect(text).toContain('\\"approved\\":true');
+ } finally {
+ stream.dispose();
+ await run.cancel();
+ }
+ });
+ }, 90_000);
+});
+
+/** Flags one manifest tool as `execution: "background"` under `experimental.tasks`. */
+function enableBackgroundTool(runtime: TestRuntime, toolName: string): void {
+ const artifacts = runtime.session.compiledArtifacts;
+ if (artifacts === null) throw new Error("expected installed compiled artifacts");
+ runtime.session.compiledArtifacts = {
+ ...artifacts,
+ manifest: {
+ ...artifacts.manifest,
+ config: { ...artifacts.manifest.config, experimental: { tasks: true } },
+ tools: artifacts.manifest.tools.map((tool) =>
+ tool.name === toolName ? { ...tool, execution: "background" as const } : tool,
+ ),
+ },
+ };
+}
diff --git a/packages/eve/src/execution/tool-run/types.ts b/packages/eve/src/execution/tool-run/types.ts
new file mode 100644
index 000000000..1da635aef
--- /dev/null
+++ b/packages/eve/src/execution/tool-run/types.ts
@@ -0,0 +1,25 @@
+import type { SessionContext } from "#context/session-context.js";
+import type { ToolRunOwner } from "#execution/tool-run/messages.js";
+import type { JsonObject } from "#shared/json.js";
+
+export type ToolRunSessionContext = SessionContext["session"];
+
+export interface ToolRunWorkflowInput {
+ readonly callId: string;
+ /** Deterministic per call: a replayed start re-derives it, loses the claim, and exits. */
+ readonly hookToken: string;
+ readonly input: JsonObject;
+ readonly owner: ToolRunOwner;
+ readonly session: ToolRunSessionContext;
+ /** Harness step index of the model call that made this tool call. */
+ readonly stepIndex: number;
+ readonly toolName: string;
+ readonly workflowId: string;
+}
+
+export interface ToolRunAddress {
+ readonly hookToken: string;
+ readonly runId: string;
+}
+
+export const WORKFLOW_TOOL_EXECUTOR_KIND = "workflow-tool";
diff --git a/packages/eve/src/execution/tool-run/workflow.ts b/packages/eve/src/execution/tool-run/workflow.ts
new file mode 100644
index 000000000..fadebda86
--- /dev/null
+++ b/packages/eve/src/execution/tool-run/workflow.ts
@@ -0,0 +1,163 @@
+import { getWorkflowMetadata, sleep as workflowSleep } from "#compiled/@workflow/core/index.js";
+
+import { claimHookOwnership, disposeHook, isHookConflictError } from "#execution/hook-ownership.js";
+import {
+ attachRunContext,
+ type RunOutcome,
+ type RunOutcomeMessage,
+ type RunRef,
+ type RunReport,
+} from "#execution/tool-run/messages.js";
+import { openRunControlInbox } from "#execution/tool-run/run-control.js";
+import type { ToolRunWorkflowInput } from "#execution/tool-run/types.js";
+import { resumeHookStep } from "#execution/tool-run/resume-hook-step.js";
+import { normalizeSerializableError } from "#execution/workflow-errors.js";
+import { readRegisteredWorkflow } from "#execution/workflow-registry.js";
+import type { ToolContext } from "#tools/definition.js";
+import type { JsonValue } from "#shared/json.js";
+
+/** How long a cancelled run waits for its body to unwind before it ends. */
+const CANCEL_GRACE = "30s";
+
+function noop(): void {}
+
+type WorkflowToolStream = AsyncIterable<JsonValue, JsonValue | undefined, void>;
+type WorkflowToolExecute = (
+ input: unknown,
+ ctx: ToolContext,
+) => Promise<JsonValue> | WorkflowToolStream;
+
+/**
+ * Runs one authored workflow tool call. The run's own hook is its identity
+ * claim and its control inbox: a duplicate start loses the claim and exits; a
+ * `cancel` message aborts `ctx.abortSignal`, and the run waits up to
+ * {@link CANCEL_GRACE} for the body to unwind before ending as cancelled, so a
+ * body parked on a hook or sleep cannot keep a cancelled run alive.
+ */
+export async function toolRunWorkflow(input: ToolRunWorkflowInput): Promise<void> {
+ "use workflow";
+
+ const control = openRunControlInbox(input.hookToken);
+ let ownsInbox = false;
+
+ try {
+ try {
+ await claimHookOwnership(control.hook);
+ ownsInbox = true;
+ } catch (error) {
+ if (isHookConflictError(error)) return;
+ throw error;
+ }
+
+ const runId = readRunId();
+ const from: RunRef = {
+ callId: input.callId,
+ input: input.input,
+ runId,
+ sequence: input.session.turn.sequence,
+ stepIndex: input.stepIndex,
+ toolName: input.toolName,
+ turnId: input.session.turn.id,
+ };
+ const ctx = createWorkflowToolContext(input, control.signal);
+ attachRunContext(ctx, { from, owner: input.owner });
+
+ const body = runBody(input, ctx, from);
+ // A body abandoned by a lost race must not surface as an unhandled rejection.
+ const settled = body.catch(noop);
+
+ let outcome: RunOutcome;
+ try {
+ // Racing the control read is what drives it; an unawaited durable read
+ // is not scheduled under replay, so a cancel would never be observed.
+ outcome = { output: await Promise.race([body, control.cancelled]), status: "completed" };
+ } catch (error) {
+ if (!control.signal.aborted) {
+ outcome = { error: normalizeSerializableError(error), status: "failed" };
+ } else {
+ await Promise.race([settled, workflowSleep(CANCEL_GRACE)]);
+ outcome = { reason: control.reason(), status: "cancelled" };
+ }
+ }
+
+ const message: RunOutcomeMessage = { from, result: outcome };
+ // An owner that cancelled the run may have finished before the grace
+ // period ended; a cancelled outcome has nobody left to reach.
+ await resumeHookStep(input.owner.outcome, message, {
+ ifPresent: outcome.status === "cancelled",
+ });
+ } finally {
+ if (ownsInbox) await disposeHook(control.hook);
+ }
+}
+
+async function runBody(
+ input: ToolRunWorkflowInput,
+ ctx: ToolContext,
+ from: RunRef,
+): Promise<JsonValue> {
+ const execute = resolveWorkflowToolExecute(input);
+ const result = execute(input.input, ctx);
+ if (!isAsyncIterable(result)) return await result;
+
+ // `for await` discards a generator's return value; it is the tool result.
+ const iterator = result[Symbol.asyncIterator]();
+ let last: JsonValue | undefined;
+ let next = await iterator.next();
+ while (next.done !== true) {
+ last = next.value;
+ const report: RunReport = { from, update: next.value };
+ await resumeHookStep(input.owner.report, report);
+ next = await iterator.next();
+ }
+ return next.value ?? last ?? null;
+}
+
+function isAsyncIterable(value: unknown): value is WorkflowToolStream {
+ return (
+ typeof value === "object" &&
+ value !== null &&
+ typeof (value as WorkflowToolStream)[Symbol.asyncIterator] === "function"
+ );
+}
+
+function readRunId(): string {
+ const runId = getWorkflowMetadata().workflowRunId;
+ if (typeof runId !== "string") {
+ throw new Error("The tool run has no workflow run id.");
+ }
+ return runId;
+}
+
+function resolveWorkflowToolExecute(input: ToolRunWorkflowInput): WorkflowToolExecute {
+ const execute = readRegisteredWorkflow(input.workflowId);
+ if (typeof execute !== "function") {
+ throw new Error(
+ `Tool "${input.toolName}" is not registered as a workflow in this deployment (${input.workflowId}). ` +
+ "The tool was renamed or removed after this run started.",
+ );
+ }
+ return execute as WorkflowToolExecute;
+}
+
+function createWorkflowToolContext(input: ToolRunWorkflowInput, signal: AbortSignal): ToolContext {
+ const { callId, session, toolName } = input;
+ const unavailable = (member: string, hint: string): never => {
+ throw new Error(
+ `ctx.${member} is not available inside a workflow tool; ${hint}. ` +
+ `Tool "${toolName}" runs as a durable workflow body, which only replays deterministic code.`,
+ );
+ };
+
+ return {
+ abortSignal: signal,
+ callId,
+ getSandbox: () => unavailable("getSandbox()", "the session sandbox belongs to the turn"),
+ getSkill: () => unavailable("getSkill()", "skills are read through the session sandbox"),
+ getToken: () =>
+ unavailable("getToken()", 'read credentials from the environment inside a "use step" helper'),
+ requireAuth: () => unavailable("requireAuth()", "a workflow body cannot park on authorization"),
+ session,
+ toolName,
+ };
+}
diff --git a/packages/eve/src/execution/tools/subagent/local.ts b/packages/eve/src/execution/tools/subagent/local.ts
index d3ed746d7..45767215b 100644
--- a/packages/eve/src/execution/tools/subagent/local.ts
+++ b/packages/eve/src/execution/tools/subagent/local.ts
@@ -180,7 +180,7 @@ async function dispatchSubagent(input: SubagentDispatchInput): Promise<SubagentD
sessionState: input.sessionState,
});
const entry = prepared.plan[0];
- if (entry === undefined || entry.kind === "task-control") {
+ if (entry === undefined || entry.kind === "task-control" || entry.kind === "workflow-tool") {
throw new Error("Subagent tool dispatch produced no executable plan entry.");
}
if (entry.kind === "reject") {
diff --git a/packages/eve/src/execution/turn-workflow.test.ts b/packages/eve/src/execution/turn-workflow.test.ts
index 24f21ace6..3e08c66dd 100644
--- a/packages/eve/src/execution/turn-workflow.test.ts
+++ b/packages/eve/src/execution/turn-workflow.test.ts
@@ -19,10 +19,23 @@ import { AGENT_HANDLES_STATE_KEY } from "#harness/handles/store.js";
const resumeHookMock = vi.fn();
const createHookMock = vi.fn();
+const createOwnerHookMock = vi.fn();
const sleepMock = vi.fn(async (_duration: unknown) => {});
vi.mock("#compiled/@workflow/core/index.js", () => ({
createHook: (...args: unknown[]) => createHookMock(...args),
+ defineHook: () => ({
+ create: (options?: { readonly token?: string }) => {
+ createOwnerHookMock(options?.token);
+ return {
+ [Symbol.asyncIterator]: () => ({ next: () => new Promise(() => {}) }),
+ dispose: async () => {},
+ getConflict: async () => null,
+ token: options?.token ?? "hook",
+ };
+ },
+ resume: async () => null,
+ }),
getWorkflowMetadata: vi.fn(() => ({ url: "https://eve.example.com" })),
sleep: (duration: unknown) => sleepMock(duration),
}));
@@ -68,6 +81,7 @@ describe("turnWorkflow", () => {
vi.clearAllMocks();
resumeHookMock.mockReset();
createHookMock.mockReset();
+ createOwnerHookMock.mockReset();
sleepMock.mockClear();
});
@@ -98,6 +112,8 @@ describe("turnWorkflow", () => {
},
kind: "turn-result",
});
+ // A turn that starts no workflow tool run never opens run channels.
+ expect(createOwnerHookMock).not.toHaveBeenCalled();
});
it("migrates a pre-version (unversioned) input and runs the first turn step", async () => {
diff --git a/packages/eve/src/execution/turn-workflow.ts b/packages/eve/src/execution/turn-workflow.ts
index 6d79a7065..33108b5a3 100644
--- a/packages/eve/src/execution/turn-workflow.ts
+++ b/packages/eve/src/execution/turn-workflow.ts
@@ -1,4 +1,5 @@
import { isInboxSubagentResultFromRunningHandle } from "#harness/handles/query.js";
+import { isInboxToolResultFromRecordedRun } from "#harness/tool-runs.js";
import {
createHook,
getWorkflowMetadata,
@@ -22,6 +23,21 @@ import { claimHookOwnership, disposeHook, isHookConflictError } from "#execution
import type { NextDriverAction } from "#execution/next-driver-action.js";
import { routeDeliverToChildren } from "#execution/route-child-delivery.js";
import { runProxySubagentEventStep } from "#execution/subagent-event-proxy-step.js";
+import { emitRunReportStep } from "#execution/tool-run/emit-run-report-step.js";
+import {
+ type ChannelReader,
+ createChannelReader,
+ raceChannelReads,
+} from "#execution/tool-run/owner-channels.js";
+import {
+ openRunOwnerChannels,
+ type RunOwnerChannels,
+ type RunOwnerReaders,
+} from "#execution/tool-run/owner.js";
+import {
+ runOutcomeToToolResult,
+ runRequestToInputRequestPayload,
+} from "#execution/tool-run/owner-inbox.js";
import {
createTurnCancellationControl,
type TurnCancellationControl,
@@ -64,7 +80,7 @@ async function runTurnOwnedWorkflow(input: TurnWorkflowInput): Promise<void> {
const inbox = createHook<TurnInboxPayload>({ token: `${input.completionToken}:inbox` });
// Hook promises and iterators share one durable cursor. Create the iterator before
// claiming so conflict replay is consumed by getConflict(), not a later iterator read.
- const iterator = inbox[Symbol.asyncIterator]();
+ const inboxReader = createChannelReader("inbox", inbox);
const cursor = new TurnExecutionCursor({
controlToken: input.completionToken,
parentWritable: input.stepInput.parentWritable,
@@ -80,6 +96,7 @@ async function runTurnOwnedWorkflow(input: TurnWorkflowInput): Promise<void> {
const bufferedDeliveries: DeliverHookPayload[] = [];
let nextStepInput = input.stepInput.input;
let ownsInbox = false;
+ let runChannels: RunOwnerChannels | undefined;
let cancellation: TurnCancellationControl | undefined;
try {
@@ -193,6 +210,11 @@ async function runTurnOwnedWorkflow(input: TurnWorkflowInput): Promise<void> {
// runs `experimental.tasks`.
if (pendingActionKeys !== undefined) {
await cursor.adopt(result);
+ // Opened before the dispatch step suspends, so the hooks exist when
+ // the first run reports; a turn that starts no run never pays for them.
+ if (result.action === "park" && result.startsWorkflowToolRuns === true) {
+ runChannels ??= openRunOwnerChannels(inbox.token);
+ }
const hasPendingTasks = result.action === "park" && result.tasksEnabled;
let dispatch;
if (result.action === "dispatch-workflow-runtime-actions") {
@@ -220,8 +242,9 @@ async function runTurnOwnedWorkflow(input: TurnWorkflowInput): Promise<void> {
inboxToken: inbox.token,
initialAcceptedAtMs,
initialResults: dispatchResult.results,
- iterator,
nextDeliveryRequestId,
+ readers:
+ runChannels === undefined ? [inboxReader] : [...runChannels.readers, inboxReader],
pendingActionKeys,
});
if (results === "cancelled") {
@@ -273,10 +296,15 @@ async function runTurnOwnedWorkflow(input: TurnWorkflowInput): Promise<void> {
// terminal result publishes so the next turn's claim never races this
// run's teardown; this backstop covers the error path.
if (cancellation !== undefined) await cancellation.dispose();
+ if (runChannels !== undefined) await runChannels.dispose();
if (ownsInbox) await disposeHook(inbox);
}
}
+type TurnReaders =
+ | readonly [...RunOwnerReaders, ChannelReader<"inbox", TurnInboxPayload>]
+ | readonly [ChannelReader<"inbox", TurnInboxPayload>];
+
async function finishCancelledTurn(input: {
readonly bufferedDeliveries: readonly DeliverHookPayload[];
readonly cancellation: TurnCancellationControl | undefined;
@@ -318,9 +346,9 @@ async function waitForRuntimeActionResults(input: {
readonly inboxToken: string;
readonly initialAcceptedAtMs: number | undefined;
readonly initialResults: readonly RuntimeActionResult[];
- readonly iterator: AsyncIterator<TurnInboxPayload>;
readonly nextDeliveryRequestId: () => string;
readonly pendingActionKeys: readonly string[];
+ readonly readers: TurnReaders;
}): Promise<AcceptedRuntimeActionBatch | "cancelled" | "cancel-turn"> {
let pendingDeliveryRequest: string | undefined;
const results: RuntimeActionResult[] = [...input.initialResults];
@@ -366,15 +394,10 @@ async function waitForRuntimeActionResults(input: {
});
}
- const nextPromise = input.iterator.next();
- // When a cancel wins the race, the dangling inbox `next()` is dropped
- // by disposal in teardown; pre-attach a handler so a late rejection
- // never surfaces as unhandled.
- nextPromise.catch(() => {});
- const next = await (input.cancellation === undefined
- ? nextPromise
- : Promise.race([nextPromise, input.cancellation.requested]));
- if (next === "cancel") {
+ // A read that loses to a cancel stays pending and is dropped by disposal
+ // in teardown.
+ const read = await raceChannelReads(input.readers, input.cancellation?.requested);
+ if (read === "cancel") {
if (pendingDeliveryRequest !== undefined) {
// Release the raced public input back to the driver so it stays
// available for the next turn.
@@ -385,21 +408,52 @@ async function waitForRuntimeActionResults(input: {
}
return "cancelled";
}
- if (next.done) throw new Error("Turn inbox closed before runtime actions completed.");
+ if (read.next.done) throw new Error("Turn inbox closed before runtime actions completed.");
+
+ if (read.channel === "outcome") {
+ const result = runOutcomeToToolResult(read.next.value);
+ const sessionSnapshotState = input.cursor.sessionState.snapshot?.session.state;
+ if (isInboxToolResultFromRecordedRun(sessionSnapshotState, result)) {
+ const acceptedAtMs = Date.now();
+ results.push(result);
+ acceptedAtMsByKey.set(getRuntimeActionResultKey(result), acceptedAtMs);
+ }
+ continue;
+ }
+ if (read.channel === "request") {
+ const proxyResult = await runProxySubagentEventStep({
+ answerHook: { runId: read.next.value.from.runId },
+ hookPayload: runRequestToInputRequestPayload(read.next.value),
+ parentWritable: input.cursor.parentWritable,
+ serializedContext: input.cursor.serializedContext,
+ sessionState: input.cursor.sessionState,
+ });
+ await input.cursor.adopt(proxyResult);
+ continue;
+ }
+ if (read.channel === "report") {
+ await emitRunReportStep({
+ from: read.next.value.from,
+ parentWritable: input.cursor.parentWritable,
+ update: read.next.value.update,
+ });
+ continue;
+ }
- const value = next.value;
+ const value = read.next.value;
if (value.kind === "runtime-action-result") {
// The inbox token is shared by every callee in the batch, so an inbox
- // subagent result must bind to a running agent handle in the adopted
- // session snapshot: its callId on the handle's operation and, when it
- // claims a sessionId, that session on the handle's address (older eve
- // deployments claim none and bind by callId alone). Anything else — a
- // callee settling a sibling's call, or a result for a callId whose
- // dispatch failed — is dropped; the genuine child's result (or the
- // dispatch error already in `results`) still resolves the wait.
+ // result must bind to the adopted session snapshot: a subagent result
+ // to a running agent handle carrying its callId, a tool result to the
+ // tool run recorded for its callId. Anything else — a callee settling a
+ // sibling's call, or a result for a callId whose dispatch failed — is
+ // dropped; the genuine result (or the dispatch error already in
+ // `results`) still resolves the wait.
const sessionSnapshotState = input.cursor.sessionState.snapshot?.session.state;
const accepted = value.results.filter((result) =>
- isInboxSubagentResultFromRunningHandle(sessionSnapshotState, result),
+ result.kind === "tool-result"
+ ? isInboxToolResultFromRecordedRun(sessionSnapshotState, result)
+ : isInboxSubagentResultFromRunningHandle(sessionSnapshotState, result),
);
if (accepted.length > 0) {
const acceptedAtMs = Date.now();
diff --git a/packages/eve/src/execution/workflow-entry.test.ts b/packages/eve/src/execution/workflow-entry.test.ts
index 2ed5c1263..54f38e62e 100644
--- a/packages/eve/src/execution/workflow-entry.test.ts
+++ b/packages/eve/src/execution/workflow-entry.test.ts
@@ -32,6 +32,15 @@ import { sessionCommandHookToken } from "#execution/session-command-token.js";
vi.mock("#compiled/@workflow/core/index.js", () => ({
createHook: vi.fn(),
+ defineHook: () => ({
+ create: (options?: { readonly token?: string }) => ({
+ [Symbol.asyncIterator]: () => ({ next: () => new Promise(() => {}) }),
+ dispose: async () => {},
+ getConflict: async () => null,
+ token: options?.token ?? "hook",
+ }),
+ resume: async () => null,
+ }),
getWorkflowMetadata: vi.fn(() => ({
url: "https://eve.example.com",
workflowRunId: "wrun_test_123",
diff --git a/packages/eve/src/execution/workflow-registry.ts b/packages/eve/src/execution/workflow-registry.ts
new file mode 100644
index 000000000..375b0d911
--- /dev/null
+++ b/packages/eve/src/execution/workflow-registry.ts
@@ -0,0 +1,11 @@
+declare global {
+ // The Workflow SDK's generated entrypoint resolves a run's function from this
+ // map; eve's transform creates it and registers every `"use workflow"` function.
+ var __private_workflows: Map<string, unknown> | undefined;
+}
+
+export const WORKFLOW_REGISTRY_GLOBAL = "__private_workflows";
+
+export function readRegisteredWorkflow(workflowId: string): unknown {
+ return globalThis[WORKFLOW_REGISTRY_GLOBAL]?.get(workflowId);
+}
diff --git a/packages/eve/src/execution/workflow-runtime.ts b/packages/eve/src/execution/workflow-runtime.ts
index cd795d399..7053d40be 100644
--- a/packages/eve/src/execution/workflow-runtime.ts
+++ b/packages/eve/src/execution/workflow-runtime.ts
@@ -65,12 +65,14 @@ import { sessionCommandHookToken } from "#execution/session-command-token.js";
import { resumeSessionInbox } from "#execution/wire/session-inbox-resume.js";
import type { DynamicSubagentAgentConfig } from "#runtime/subagents/dynamic-agent-config.js";
import { initializeSessionInstrumentation } from "#instrumentation/runtime.js";
-
-const WORKFLOW_ENTRY_NAME = "workflowEntry";
-const TURN_WORKFLOW_NAME = "turnWorkflow";
-const SESSION_TIMEOUT_WORKFLOW_NAME = "sessionTimeoutWorkflow";
-const TASK_RUN_WORKFLOW_NAME = "taskRunWorkflow";
-const ACTIVITY_COLLECTOR_WORKFLOW_NAME = "activityCollectorWorkflow";
+import {
+ ACTIVITY_COLLECTOR_WORKFLOW_NAME,
+ SESSION_TIMEOUT_WORKFLOW_NAME,
+ TASK_RUN_WORKFLOW_NAME,
+ TOOL_RUN_WORKFLOW_NAME,
+ TURN_WORKFLOW_NAME,
+ WORKFLOW_ENTRY_NAME,
+} from "#execution/stable-workflow-names.js";
const EVE_PACKAGE_INFO = resolveInstalledPackageInfo();
const COMMAND_HOOK_READY_TIMEOUT_MS = 30_000;
const DEFAULT_ACTIVITY_COLLECTOR_RETENTION_MS = 24 * 60 * 60 * 1_000;
@@ -78,24 +80,6 @@ const DEFAULT_ACTIVITY_COLLECTOR_RETENTION_MS = 24 * 60 * 60 * 1_000;
export const LATEST_DEPLOYMENT_UNSUPPORTED_MESSAGE =
"deploymentId 'latest' requires a World that implements resolveLatestDeploymentId()";
-/**
- * Workflow function names whose bundled id is stable across deployments
- * (no `@<pkg.version>` stamp). The bundler reads this set when emitting
- * the workflow id so cross-deployment routing — `start(ref, args, {
- * deploymentId: "latest" })` — finds the same workflow on a newer
- * deployment even when the eve version differs.
- *
- * Both halves of the contract (bundler output and runtime reference
- * template) read this single set so they cannot drift.
- */
-export const STABLE_WORKFLOW_NAMES: ReadonlySet<string> = new Set([
- WORKFLOW_ENTRY_NAME,
- TURN_WORKFLOW_NAME,
- SESSION_TIMEOUT_WORKFLOW_NAME,
- TASK_RUN_WORKFLOW_NAME,
- ACTIVITY_COLLECTOR_WORKFLOW_NAME,
-]);
-
const STABLE_ID_BASE = EVE_PACKAGE_INFO.name;
const log = createLogger("execution.workflow-runtime");
@@ -140,6 +124,11 @@ export const activityCollectorWorkflowReference = {
workflowId: `workflow//${STABLE_ID_BASE}//${ACTIVITY_COLLECTOR_WORKFLOW_NAME}`,
};
+/** Stable workflow reference for authored workflow tool runs. */
+export const toolRunWorkflowReference = {
+ workflowId: `workflow//${STABLE_ID_BASE}//${TOOL_RUN_WORKFLOW_NAME}`,
+};
+
/**
* Creates a workflow-backed runtime whose long-lived driver owns the
* event stream and dispatches each turn as a child workflow run.
diff --git a/packages/eve/src/execution/workflow-webhook-route.test.ts b/packages/eve/src/execution/workflow-webhook-route.test.ts
new file mode 100644
index 000000000..7a563f709
--- /dev/null
+++ b/packages/eve/src/execution/workflow-webhook-route.test.ts
@@ -0,0 +1,58 @@
+import { describe, expect, it, vi } from "vitest";
+
+const runtime = vi.hoisted(() => ({
+ resumeWebhook: vi.fn<(token: string, request: Request) => Promise<Response>>(),
+}));
+
+vi.mock("#internal/workflow/runtime.js", () => ({ resumeWebhook: runtime.resumeWebhook }));
+
+const { HookNotFoundError } = await import("#compiled/@workflow/errors/index.js");
+const { handleWorkflowWebhookRequest, WORKFLOW_WEBHOOK_ROUTE_PATTERN } =
+ await import("#execution/workflow-webhook-route.js");
+
+function route(params: Record<string, string>) {
+ return { params } as Parameters<typeof handleWorkflowWebhookRequest>[1];
+}
+
+describe("workflow webhook route", () => {
+ it("serves the SDK's conventional webhook path", () => {
+ expect(WORKFLOW_WEBHOOK_ROUTE_PATTERN).toBe("/.well-known/workflow/v1/webhook/:token");
+ });
+
+ it("resumes the webhook with the request and returns the SDK's response", async () => {
+ const accepted = Response.json({ ok: true }, { status: 202 });
+ runtime.resumeWebhook.mockResolvedValueOnce(accepted);
+ const request = new Request("https://agent.example/.well-known/workflow/v1/webhook/tok", {
+ body: "{}",
+ method: "POST",
+ });
+
+ const response = await handleWorkflowWebhookRequest(request, route({ token: "tok" }));
+
+ expect(response).toBe(accepted);
+ expect(runtime.resumeWebhook).toHaveBeenCalledWith("tok", request);
+ });
+
+ it("rejects a missing token and reports an unknown hook as not pending", async () => {
+ const missing = await handleWorkflowWebhookRequest(new Request("https://x/"), route({}));
+ expect(missing.status).toBe(400);
+
+ runtime.resumeWebhook.mockRejectedValueOnce(new HookNotFoundError("gone"));
+ const gone = await handleWorkflowWebhookRequest(
+ new Request("https://x/", { method: "POST" }),
+ route({ token: "gone" }),
+ );
+ expect(gone.status).toBe(404);
+ await expect(gone.json()).resolves.toEqual({ error: "Webhook not pending.", ok: false });
+ });
+
+ it("lets unexpected failures surface", async () => {
+ runtime.resumeWebhook.mockRejectedValueOnce(new Error("world down"));
+ await expect(
+ handleWorkflowWebhookRequest(
+ new Request("https://x/", { method: "POST" }),
+ route({ token: "t" }),
+ ),
+ ).rejects.toThrow("world down");
+ });
+});
diff --git a/packages/eve/src/execution/workflow-webhook-route.ts b/packages/eve/src/execution/workflow-webhook-route.ts
new file mode 100644
index 000000000..dd8094a63
--- /dev/null
+++ b/packages/eve/src/execution/workflow-webhook-route.ts
@@ -0,0 +1,29 @@
+import { HookNotFoundError } from "#compiled/@workflow/errors/index.js";
+
+import { resumeWebhook } from "#internal/workflow/runtime.js";
+import type { RouteContext } from "#public/definitions/channel.js";
+import { walkCauseChain } from "#shared/errors.js";
+
+/** The path `createWebhook()` mints, so external systems call back without knowing eve. */
+export const WORKFLOW_WEBHOOK_ROUTE_PATTERN = "/.well-known/workflow/v1/webhook/:token";
+
+export async function handleWorkflowWebhookRequest(
+ request: Request,
+ ctx: RouteContext,
+): Promise<Response> {
+ const token = ctx.params.token;
+ if (typeof token !== "string" || token.length === 0) {
+ return Response.json({ error: "Missing webhook token.", ok: false }, { status: 400 });
+ }
+
+ try {
+ return await resumeWebhook(token, request);
+ } catch (error) {
+ for (const candidate of walkCauseChain(error)) {
+ if (HookNotFoundError.is(candidate)) {
+ return Response.json({ error: "Webhook not pending.", ok: false }, { status: 404 });
+ }
+ }
+ throw error;
+ }
+}
diff --git a/packages/eve/src/harness/proxy-input-requests.ts b/packages/eve/src/harness/proxy-input-requests.ts
index 8315125b6..edc803c9f 100644
--- a/packages/eve/src/harness/proxy-input-requests.ts
+++ b/packages/eve/src/harness/proxy-input-requests.ts
@@ -11,8 +11,17 @@ const PROXY_INPUT_REQUEST_KINDS = {
"tool-approval": true,
} satisfies Readonly<Record<InputRequestKind, true>>;
+/**
+ * Marks a continuation token as a bare hook a workflow tool run created for one
+ * request, resumed with the plain response, rather than a child session inbox.
+ */
+export interface AnswerHookRoute {
+ readonly runId: string;
+}
+
/** Routing and control metadata for one descendant-owned input request. */
export interface ProxyInputRequest {
+ readonly answerHook?: AnswerHookRoute;
/** Batch semantics are optional so sessions written before this field remain routable. */
readonly batch?: ProxyInputRequestBatch;
readonly childContinuationToken: string;
@@ -114,24 +123,31 @@ export function upsertProxyInputRequestState(input: {
export function clearProxyInputRequestsForChild(
session: HarnessSession,
childContinuationToken: string,
+): HarnessSession {
+ return clearProxyInputRequestsWhere(
+ session,
+ (route) => route.childContinuationToken === childContinuationToken,
+ );
+}
+
+/** Removes every proxy route the predicate selects. */
+export function clearProxyInputRequestsWhere(
+ session: HarnessSession,
+ select: (route: ProxyInputRequest) => boolean,
): HarnessSession {
const current = readMap(session.state);
const next: Record<string, ProxyInputRequest> = {};
let changed = false;
for (const [requestId, route] of Object.entries(current)) {
- if (route.childContinuationToken === childContinuationToken) {
+ if (select(route)) {
changed = true;
continue;
}
next[requestId] = route;
}
- if (!changed) {
- return session;
- }
-
- return writeMap(session, next);
+ return changed ? writeMap(session, next) : session;
}
/** Removes only the request IDs whose responses were successfully forwarded. */
@@ -158,17 +174,7 @@ export function clearProxyInputRequestsForTask(
session: HarnessSession,
taskId: string,
): HarnessSession {
- const current = readMap(session.state);
- const next: Record<string, ProxyInputRequest> = {};
- let changed = false;
- for (const [requestId, route] of Object.entries(current)) {
- if (route.taskId === taskId) {
- changed = true;
- } else {
- next[requestId] = route;
- }
- }
- return changed ? writeMap(session, next) : session;
+ return clearProxyInputRequestsWhere(session, (route) => route.taskId === taskId);
}
/**
@@ -208,6 +214,7 @@ export function toProxyInputRequestEntries(
kind: request.kind,
};
if (taskId !== undefined) route.taskId = taskId;
+
return [request.requestId, route] as const;
});
}
@@ -277,7 +284,10 @@ function parseProxyInputRequest(value: unknown, requestId: string): ProxyInputRe
return undefined;
}
const batch = "batch" in value ? parseProxyInputRequestBatch(value.batch) : undefined;
+ const answerHook = "answerHook" in value ? parseAnswerHookRoute(value.answerHook) : undefined;
+ if ("answerHook" in value && answerHook === undefined) return undefined;
const request: {
+ answerHook?: AnswerHookRoute;
batch?: ProxyInputRequestBatch;
readonly childContinuationToken: string;
childRequestId?: string;
@@ -288,6 +298,7 @@ function parseProxyInputRequest(value: unknown, requestId: string): ProxyInputRe
childContinuationToken: value.childContinuationToken,
kind: value.kind,
};
+ if (answerHook !== undefined) request.answerHook = answerHook;
if (batch !== undefined && batch.requestIds.includes(requestId)) request.batch = batch;
if (typeof childRequestId === "string") request.childRequestId = childRequestId;
if (typeof childResponseUrl === "string") request.childResponseUrl = childResponseUrl;
@@ -295,6 +306,13 @@ function parseProxyInputRequest(value: unknown, requestId: string): ProxyInputRe
return request;
}
+function parseAnswerHookRoute(value: unknown): AnswerHookRoute | undefined {
+ if (value === null || typeof value !== "object" || !("runId" in value)) return undefined;
+ return typeof value.runId === "string" && value.runId.length > 0
+ ? { runId: value.runId }
+ : undefined;
+}
+
function parseProxyInputRequestBatch(value: unknown): ProxyInputRequestBatch | undefined {
if (value === null || typeof value !== "object" || Array.isArray(value)) return undefined;
if (!("approvalRequestIds" in value) || !("requestIds" in value)) return undefined;
diff --git a/packages/eve/src/harness/runtime-actions.test.ts b/packages/eve/src/harness/runtime-actions.test.ts
index 34993a90b..7de40f24e 100644
--- a/packages/eve/src/harness/runtime-actions.test.ts
+++ b/packages/eve/src/harness/runtime-actions.test.ts
@@ -20,6 +20,8 @@ import {
prepareAgentStart,
} from "#harness/handles/transitions.js";
import { getProxyInputRequests, upsertProxyInputRequests } from "#harness/proxy-input-requests.js";
+import { getToolRuns, recordToolRun } from "#harness/tool-runs.js";
+import { toolOutput } from "#tools/model-output.js";
import { getSessionTokenUsage, setTurnUsageState } from "#harness/turn-tag-state.js";
import type { HarnessSession } from "#harness/types.js";
import type { UnstampedMessageStreamEvent } from "#protocol/message.js";
@@ -339,6 +341,118 @@ describe("resolvePendingRuntimeActions", () => {
expect(getProxyInputRequests(resolved.session.state).size).toBe(0);
});
+ it("forgets a finished workflow tool run and withdraws only its unanswered requests", async () => {
+ const parked = setPendingRuntimeActionBatch({
+ actions: [
+ {
+ callId: "call-1",
+ description: "Deploy.",
+ input: { service: "api" },
+ target: {
+ kind: "workflow-tool-call",
+ workflowId: "workflow//./agent/tools/deploy//execute",
+ },
+ toolName: "deploy",
+ },
+ ],
+ event: { sequence: 0, stepIndex: 0, turnId: "turn_0" },
+ responseMessages: [],
+ session: createParkedSession(),
+ });
+ const withRun = recordToolRun(parked, {
+ callId: "call-1",
+ hookToken: "eve:tool-run:op-1",
+ runId: "run-1",
+ toolName: "deploy",
+ });
+ const answerToken = "eve:tool-run-answer:run-1:0";
+ const session = upsertProxyInputRequests({
+ entries: [
+ ["other-request", { childContinuationToken: CHILD_CONTINUATION_TOKEN, kind: "question" }],
+ ],
+ forChildContinuationToken: CHILD_CONTINUATION_TOKEN,
+ session: upsertProxyInputRequests({
+ entries: [
+ [
+ answerToken,
+ {
+ answerHook: { runId: "run-1" },
+ childContinuationToken: answerToken,
+ kind: "question",
+ },
+ ],
+ ],
+ forChildContinuationToken: answerToken,
+ session: withRun,
+ }),
+ });
+
+ const resolved = await resolvePendingRuntimeActions({
+ session,
+ stepInput: {
+ runtimeActionResults: [
+ { callId: "call-1", kind: "tool-result", output: { deployed: true }, toolName: "deploy" },
+ ],
+ },
+ });
+
+ expect(resolved.outcome).toBe("resolved");
+ expect(getToolRuns(resolved.session.state)).toEqual([]);
+ expect([...getProxyInputRequests(resolved.session.state).keys()]).toEqual(["other-request"]);
+ });
+
+ it("projects a workflow tool's result through its toModelOutput", async () => {
+ const parked = setPendingRuntimeActionBatch({
+ actions: [
+ {
+ callId: "call-1",
+ description: "Deploy.",
+ input: { service: "api" },
+ target: {
+ kind: "workflow-tool-call",
+ workflowId: "workflow//./agent/tools/deploy//execute",
+ },
+ toolName: "deploy",
+ },
+ ],
+ event: { sequence: 0, stepIndex: 0, turnId: "turn_0" },
+ responseMessages: [],
+ session: createParkedSession(),
+ });
+ const tools = new Map([
+ [
+ "deploy",
+ {
+ description: "Deploy.",
+ inputSchema: jsonSchema({ type: "object" }),
+ name: "deploy",
+ toModelOutput: (output: unknown) =>
+ toolOutput.text(`deployed to ${(output as { url: string }).url}`),
+ },
+ ],
+ ]);
+
+ const resolved = await resolvePendingRuntimeActions({
+ session: parked,
+ stepInput: {
+ runtimeActionResults: [
+ {
+ callId: "call-1",
+ kind: "tool-result",
+ output: { deployed: true, url: "https://api.example" },
+ toolName: "deploy",
+ },
+ ],
+ },
+ tools,
+ });
+
+ const toolMessage = resolved.messages.at(-1);
+ expect(toolMessage?.role).toBe("tool");
+ expect(JSON.stringify(toolMessage?.content)).toContain("deployed to https://api.example");
+ expect(JSON.stringify(toolMessage?.content)).not.toContain('"deployed":true');
+ });
+
it("accepts a dispatch-origin failure result by callId", async () => {
const resolved = await resolvePendingRuntimeActions({
session: createParkedSession(),
diff --git a/packages/eve/src/harness/runtime-actions.ts b/packages/eve/src/harness/runtime-actions.ts
index 8759d99d2..74b7a972b 100644
--- a/packages/eve/src/harness/runtime-actions.ts
+++ b/packages/eve/src/harness/runtime-actions.ts
@@ -9,7 +9,13 @@ import { parseJsonObject, type JsonObject } from "#shared/json.js";
import type { AgentTurnOutcome } from "#shared/agent-turn-outcome.js";
import { findRunningAgentHandle, isResultBoundToRunningHandle } from "#harness/handles/query.js";
import { settleAgentTurn } from "#harness/handles/transitions.js";
-import { clearProxyInputRequestsForChild } from "#harness/proxy-input-requests.js";
+import {
+ clearProxyInputRequestsForChild,
+ clearProxyInputRequestsWhere,
+} from "#harness/proxy-input-requests.js";
+import { findToolRun, removeToolRun } from "#harness/tool-runs.js";
+import { normalizeToolModelOutput } from "#harness/tool-model-output.js";
+import type { HarnessToolDefinition } from "#harness/execute-tool.js";
import {
accumulateSessionUsage,
getTurnUsageState,
@@ -188,6 +194,8 @@ export async function resolvePendingRuntimeActions(input: {
readonly emit?: HarnessEmitFn;
readonly session: HarnessSession;
readonly stepInput?: StepInput;
+ /** Definitions whose `toModelOutput` projects a workflow tool's result for the model. */
+ readonly tools?: HarnessToolMap;
}): Promise<ResolvePendingRuntimeActionsResult> {
const batch = getPendingRuntimeActionBatch(input.session.state);
@@ -276,6 +284,20 @@ export async function resolvePendingRuntimeActions(input: {
}
}
+ // Drop a finished run's unanswered requests so a late click cannot reach it.
+ for (const result of readyResults) {
+ if (result.kind !== "tool-result") continue;
+ const record = findToolRun(nextSession.state, result.callId);
+ if (record === undefined) continue;
+ nextSession = removeToolRun(
+ clearProxyInputRequestsWhere(
+ nextSession,
+ (route) => route.answerHook?.runId === record.runId,
+ ),
+ record.callId,
+ );
+ }
+
const state = { ...nextSession.state };
delete state[PENDING_RUNTIME_ACTION_BATCH_KEY];
nextSession = {
@@ -307,33 +329,37 @@ export async function resolvePendingRuntimeActions(input: {
);
}
- const toolResults = readyResults.map((result) => {
+ const toolResults: ToolResultPart[] = [];
+ for (const result of readyResults) {
switch (result.kind) {
case "load-skill-result":
- return {
+ toolResults.push({
output: toToolResultOutput(result),
toolCallId: result.callId,
toolName: "load_skill",
- type: "tool-result" as const,
- };
+ type: "tool-result",
+ });
+ continue;
case "subagent-result":
- return {
+ toolResults.push({
output: toToolResultOutput(result),
toolCallId: result.callId,
toolName: result.subagentName,
- type: "tool-result" as const,
- };
+ type: "tool-result",
+ });
+ continue;
case "tool-result":
- return {
- output: toToolResultOutput(result),
+ toolResults.push({
+ output: await projectToolResultOutput(result, input.tools?.get(result.toolName)),
toolCallId: result.callId,
toolName: result.toolName,
- type: "tool-result" as const,
- };
+ type: "tool-result",
+ });
+ continue;
}
throw new Error(`Unsupported runtime action result kind "${String(result)}".`);
- });
+ }
const messages = [...nextSession.history, ...batch.responseMessages];
@@ -480,6 +506,21 @@ function parseJsonStringInput(value: string): unknown {
return JSON.parse(value);
}
+/** Errors bypass `toModelOutput`, as they do for local execution. */
+async function projectToolResultOutput(
+ result: Extract<RuntimeActionResult, { kind: "tool-result" }>,
+ definition: HarnessToolDefinition | undefined,
+): Promise<ToolResultPart["output"]> {
+ if (result.isError === true || definition?.toModelOutput === undefined) {
+ return toToolResultOutput(result);
+ }
+ return normalizeToolModelOutput({
+ output: await definition.toModelOutput(result.output),
+ toolCallId: result.callId,
+ toolName: result.toolName,
+ });
+}
+
function toToolResultOutput(result: RuntimeActionResult): ToolResultPart["output"] {
if (typeof result.output === "string") {
if (result.isError === true) {
diff --git a/packages/eve/src/harness/tool-loop.ts b/packages/eve/src/harness/tool-loop.ts
index ec56d02d1..f087c810d 100644
--- a/packages/eve/src/harness/tool-loop.ts
+++ b/packages/eve/src/harness/tool-loop.ts
@@ -636,6 +636,7 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {
emit,
session,
stepInput: stepInput.input,
+ tools: config.tools,
});
if (resolvedRuntimeActions.outcome === "unresolved") {
return { next: null, session: resolvedRuntimeActions.session };
diff --git a/packages/eve/src/harness/tool-runs.test.ts b/packages/eve/src/harness/tool-runs.test.ts
new file mode 100644
index 000000000..246860765
--- /dev/null
+++ b/packages/eve/src/harness/tool-runs.test.ts
@@ -0,0 +1,63 @@
+import { describe, expect, it } from "vitest";
+
+import {
+ clearToolRuns,
+ findToolRun,
+ getToolRuns,
+ isInboxToolResultFromRecordedRun,
+ recordToolRun,
+ removeToolRun,
+} from "#harness/tool-runs.js";
+import type { HarnessSession } from "#harness/types.js";
+
+const RECORD = {
+ callId: "call_1",
+ hookToken: "eve:tool-run:abc",
+ runId: "wrun_1",
+ toolName: "deploy",
+};
+
+function session(state?: HarnessSession["state"]): HarnessSession {
+ return { state } as HarnessSession;
+}
+
+describe("tool run records", () => {
+ it("records, finds, and removes runs by call id", () => {
+ const recorded = recordToolRun(session({ other: true }), RECORD);
+ expect(getToolRuns(recorded.state)).toEqual([RECORD]);
+ expect(findToolRun(recorded.state, "call_1")).toEqual(RECORD);
+
+ const replaced = recordToolRun(recorded, { ...RECORD, runId: "wrun_2" });
+ expect(getToolRuns(replaced.state)).toEqual([{ ...RECORD, runId: "wrun_2" }]);
+
+ const removed = removeToolRun(replaced, "call_1");
+ expect(getToolRuns(removed.state)).toEqual([]);
+ expect(removed.state).toEqual({ other: true });
+ expect(removeToolRun(removed, "call_1")).toBe(removed);
+ });
+
+ it("drops the state map entirely when nothing else is recorded", () => {
+ const recorded = recordToolRun(session(), RECORD);
+ expect(clearToolRuns(recorded).state).toBeUndefined();
+ expect(clearToolRuns(session())).toEqual(session());
+ });
+
+ it("binds inbox tool results to the recorded run by call id and tool name", () => {
+ const state = recordToolRun(session(), RECORD).state;
+ const result = {
+ callId: "call_1",
+ kind: "tool-result" as const,
+ output: 1,
+ toolName: "deploy",
+ };
+
+ expect(isInboxToolResultFromRecordedRun(state, result)).toBe(true);
+ expect(isInboxToolResultFromRecordedRun(state, { ...result, toolName: "other" })).toBe(false);
+ expect(isInboxToolResultFromRecordedRun(state, { ...result, callId: "call_2" })).toBe(false);
+ expect(isInboxToolResultFromRecordedRun(undefined, result)).toBe(false);
+ });
+
+ it("ignores malformed state", () => {
+ expect(getToolRuns({ "eve.runtime.toolRuns": { not: "an array" } })).toEqual([]);
+ });
+});
diff --git a/packages/eve/src/harness/tool-runs.ts b/packages/eve/src/harness/tool-runs.ts
new file mode 100644
index 000000000..b37033a27
--- /dev/null
+++ b/packages/eve/src/harness/tool-runs.ts
@@ -0,0 +1,71 @@
+import type { HarnessSession, SessionStateMap } from "#harness/types.js";
+import type { RuntimeToolResultActionResult } from "#shared/action-types.js";
+
+const TOOL_RUNS_STATE_KEY = "eve.runtime.toolRuns";
+export function toolRunAnswerToken(runId: string, seq: number): string {
+ return `eve:tool-run-answer:${runId}:${seq}`;
+}
+
+/** A workflow tool run the active turn waits on. Background runs live in the task index. */
+export interface ToolRunRecord {
+ readonly callId: string;
+ readonly hookToken: string;
+ readonly runId: string;
+ readonly toolName: string;
+}
+
+// Schema-free: this is bundled into the workflow driver.
+export function getToolRuns(state: SessionStateMap | undefined): readonly ToolRunRecord[] {
+ const raw = state?.[TOOL_RUNS_STATE_KEY];
+ return Array.isArray(raw) ? (raw as readonly ToolRunRecord[]) : [];
+}
+
+export function findToolRun(
+ state: SessionStateMap | undefined,
+ callId: string,
+): ToolRunRecord | undefined {
+ return getToolRuns(state).find((record) => record.callId === callId);
+}
+
+export function recordToolRun<T extends { readonly state?: SessionStateMap }>(
+ session: T,
+ record: ToolRunRecord,
+): T {
+ const others = getToolRuns(session.state).filter((entry) => entry.callId !== record.callId);
+ return writeToolRuns(session, [...others, record]);
+}
+
+export function removeToolRun<T extends { readonly state?: SessionStateMap }>(
+ session: T,
+ callId: string,
+): T {
+ const records = getToolRuns(session.state);
+ const remaining = records.filter((entry) => entry.callId !== callId);
+ return remaining.length === records.length ? session : writeToolRuns(session, remaining);
+}
+
+export function clearToolRuns(session: HarnessSession): HarnessSession {
+ return getToolRuns(session.state).length === 0 ? session : writeToolRuns(session, []);
+}
+
+/** The turn inbox is shared; a result settles a call only if the turn recorded that run. */
+export function isInboxToolResultFromRecordedRun(
+ state: SessionStateMap | undefined,
+ result: RuntimeToolResultActionResult,
+): boolean {
+ const record = findToolRun(state, result.callId);
+ return record !== undefined && record.toolName === result.toolName;
+}
+
+function writeToolRuns<T extends { readonly state?: SessionStateMap }>(
+ session: T,
+ records: readonly ToolRunRecord[],
+): T {
+ const state = { ...session.state };
+ if (records.length === 0) {
+ delete state[TOOL_RUNS_STATE_KEY];
+ } else {
+ state[TOOL_RUNS_STATE_KEY] = records;
+ }
+ return { ...session, state: Object.keys(state).length > 0 ? state : undefined };
+}
diff --git a/packages/eve/src/internal/authored-directive-prologue.test.ts b/packages/eve/src/internal/authored-directive-prologue.test.ts
deleted file mode 100644
index b6e579b0f..000000000
--- a/packages/eve/src/internal/authored-directive-prologue.test.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-import { describe, expect, it } from "vitest";
-
-import { assertNoWorkflowDirectivePrologue } from "#internal/authored-directive-prologue.js";
-
-describe("assertNoWorkflowDirectivePrologue", () => {
- it.each(["use step", "use workflow"])("rejects an authored %s directive", async (directive) => {
- await expect(
- assertNoWorkflowDirectivePrologue({
- filePath: "/app/agent/tools/example.ts",
- source: `'use strict';\n${JSON.stringify(directive)};\nexport const value = 1;\n`,
- }),
- ).rejects.toThrow(new RegExp(`actual .*${directive}.* directive`, "u"));
- });
-
- it("accepts comments and ordinary strings containing directive text", async () => {
- await expect(
- assertNoWorkflowDirectivePrologue({
- filePath: "/app/agent/tools/example.ts",
- source: [
- '// "use step" is documentation, not a directive.',
- 'const message = "use workflow";',
- '"use step";',
- "export { message };",
- "",
- ].join("\n"),
- }),
- ).resolves.toBeUndefined();
- });
-});
diff --git a/packages/eve/src/internal/authored-directive-prologue.ts b/packages/eve/src/internal/authored-directive-prologue.ts
deleted file mode 100644
index 331f7118c..000000000
--- a/packages/eve/src/internal/authored-directive-prologue.ts
+++ /dev/null
@@ -1,35 +0,0 @@
-import { parseWithNitroRolldownAst } from "#internal/bundler/nitro-rolldown.js";
-
-const UNSUPPORTED_WORKFLOW_DIRECTIVES = new Set(["use step", "use workflow"]);
-
-interface DirectiveStatement {
- readonly directive?: unknown;
-}
-
-interface Program {
- readonly body?: unknown;
-}
-
-export async function assertNoWorkflowDirectivePrologue(input: {
- readonly filePath: string;
- readonly source: string;
-}): Promise<void> {
- const program = (await parseWithNitroRolldownAst(input.filePath, input.source)) as Program;
-
- if (!Array.isArray(program.body)) {
- throw new Error(`Failed to parse authored module "${input.filePath}".`);
- }
-
- for (const statement of program.body as DirectiveStatement[]) {
- if (typeof statement.directive !== "string") {
- break;
- }
-
- if (UNSUPPORTED_WORKFLOW_DIRECTIVES.has(statement.directive)) {
- throw new Error(
- `Authored module "${input.filePath}" contains an actual "${statement.directive}" directive. ` +
- "Workflow directives are reserved for eve-generated workflow entrypoints.",
- );
- }
- }
-}
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 7e1777441..53f7b93c5 100644
--- a/packages/eve/src/internal/authored-module-loader.scenario.test.ts
+++ b/packages/eve/src/internal/authored-module-loader.scenario.test.ts
@@ -46,7 +46,7 @@ describe("loadAuthoredModuleNamespace", () => {
});
const manifest = await compileAgentManifest(discovered.manifest);
- const code = await bundleAuthoredModuleMapForGeneration({
+ const { code } = await bundleAuthoredModuleMapForGeneration({
manifest,
moduleMapPath: join(app.appRoot, ".eve", "compile", "module-map.mjs"),
});
diff --git a/packages/eve/src/internal/authored-module-loader.ts b/packages/eve/src/internal/authored-module-loader.ts
index 3695a6d51..bdd5aa0b8 100644
--- a/packages/eve/src/internal/authored-module-loader.ts
+++ b/packages/eve/src/internal/authored-module-loader.ts
@@ -1,11 +1,10 @@
import { createHash } from "node:crypto";
import { existsSync, mkdirSync, realpathSync, writeFileSync } from "node:fs";
-import { dirname, join, resolve } from "node:path";
+import { dirname, join, relative, resolve, sep } from "node:path";
import type { CompiledAgentManifest } from "#compiler/manifest.js";
import { createCompiledModuleMapSource } from "#compiler/module-map.js";
import { createAuthoredAssetImportPlugin } from "#internal/authored-asset-import-plugin.js";
-import { assertNoWorkflowDirectivePrologue } from "#internal/authored-directive-prologue.js";
import { createAuthoredModuleBundleError } from "#internal/authored-module-bundle.js";
import { createAuthoredModuleEvaluationError } from "#internal/authored-module-evaluation-error.js";
import { createAuthoredPackageTsConfigPathsPlugin } from "#internal/authored-package-tsconfig-paths.js";
@@ -32,7 +31,13 @@ import {
buildWithNitroRolldown,
} from "#internal/bundler/nitro-rolldown.js";
import { createNodeEsmCompatBannerPlugin } from "#internal/node-esm-compat-banner.js";
+import { prepareAuthoredWorkflowDirectives } from "#internal/workflow-bundle/authored-workflow-directives.js";
import { createDynamicCapabilityTransformPlugin } from "#internal/workflow-bundle/dynamic-capability-transform-plugin.js";
+import {
+ applyWorkflowTransform,
+ isAuthoredApplicationModule,
+ type WorkflowManifest,
+} from "#internal/workflow-bundle/workflow-builders.js";
const AUTHORED_BUNDLED_MODULE_EXTENSION = /\.[cm]?[jt]sx?$/;
const AUTHORED_MODULE_BUNDLE_DIRECTORY_PATH = join(
@@ -148,13 +153,14 @@ export async function bundleAuthoredModuleCode(
modulePath: string,
options: AuthoredModuleLoadOptions = {},
): Promise<string> {
+ const packageRoot = resolveAuthoredPackageRoot(modulePath);
return await buildAuthoredModuleBundle(modulePath, options, {
channelIdentity: true,
packageBoundaryPlugin: createRuntimeLoaderPackageBoundaryPlugin({
externalDependencies: normalizeExternalDependencies(options.externalDependencies),
- packageRoot: resolveAuthoredPackageRoot(modulePath),
+ packageRoot,
}),
- plugins: [],
+ plugins: [createAuthoredWorkflowDirectivePlugin({ appRoot: packageRoot })],
sourcemap: "inline",
});
}
@@ -256,10 +262,16 @@ export async function bundleExtensionDistributionGraph(input: {
* Shared dependencies are parsed and emitted once instead of once per authored
* entry.
*/
+export interface AuthoredModuleMapBundle {
+ readonly code: string;
+ /** Fingerprint of the sources that also feed the driver and step registry; a change rebuilds the host. */
+ readonly workflowSourceFingerprint: string | undefined;
+}
+
export async function bundleAuthoredModuleMapForGeneration(input: {
readonly manifest: CompiledAgentManifest;
readonly moduleMapPath: string;
-}): Promise<string> {
+}): Promise<AuthoredModuleMapBundle> {
const packageRoot = resolveAuthoredPackageRoot(input.manifest.agentRoot);
const programmaticLoaderImportSpecifier = resolvePackageSourceFilePath(
"src/internal/programmatic-source-loader.ts",
@@ -286,14 +298,19 @@ export async function bundleAuthoredModuleMapForGeneration(input: {
})),
),
);
+ const workflowSources = new AuthoredWorkflowSourceRecorder(packageRoot);
const plugins = [
createVirtualGenerationModuleMapPlugin({
id: input.moduleMapPath,
source: moduleMapSource,
}),
createExternalRuntimeImportPlugin(programmaticLoaderImportSpecifier),
- createDynamicCapabilityTransformPlugin(),
- createAuthoredDirectiveGuardPlugin(),
+ // Before callback stamping, which must see the stub and never the directive.
+ createAuthoredWorkflowDirectivePlugin({ appRoot: packageRoot, recorder: workflowSources }),
+ createDynamicCapabilityTransformPlugin({
+ workflowFunctions: (id) => workflowSources.workflowFunctions(id),
+ }),
+ workflowSources.graphPlugin(),
extensionScopePlugin,
createAuthoredRelativeExtensionResolverPlugin({ extensions: RESOLVE_EXTENSIONS }),
createAuthoredAssetImportPlugin({ packageRoot }),
@@ -322,7 +339,10 @@ export async function bundleAuthoredModuleMapForGeneration(input: {
sourcemap: false,
},
});
- return removeRolldownModuleRegionComments(chunk.code);
+ return {
+ code: removeRolldownModuleRegionComments(chunk.code),
+ workflowSourceFingerprint: workflowSources.fingerprint(),
+ };
} catch (error) {
throw createAuthoredModuleBundleError(input.moduleMapPath, error);
}
@@ -340,6 +360,76 @@ function createExternalRuntimeImportPlugin(importSpecifier: string): Record<stri
};
}
+/** Reuses the build's own resolution so the fingerprint is exact without a second resolver. */
+class AuthoredWorkflowSourceRecorder {
+ readonly #appRoot: string;
+ readonly #directiveModules = new Set<string>();
+ readonly #imports = new Map<string, readonly string[]>();
+ readonly #sources = new Map<string, string>();
+ readonly #workflowFunctions = new Map<string, ReadonlySet<string>>();
+
+ constructor(appRoot: string) {
+ this.#appRoot = appRoot;
+ }
+
+ record(id: string, source: string, manifest: WorkflowManifest): void {
+ this.#sources.set(id, source);
+ if (manifest.steps !== undefined || manifest.workflows !== undefined) {
+ this.#directiveModules.add(id);
+ }
+ const workflows = Object.values(manifest.workflows ?? {})[0];
+ if (workflows !== undefined) this.#workflowFunctions.set(id, new Set(Object.keys(workflows)));
+ }
+
+ workflowFunctions(id: string): ReadonlySet<string> | undefined {
+ return this.#workflowFunctions.get(id);
+ }
+
+ graphPlugin(): Record<string, unknown> {
+ const imports = this.#imports;
+ return {
+ name: "eve-authored-module-graph",
+ buildEnd(this: RolldownModuleGraphContext) {
+ for (const id of this.getModuleIds()) {
+ const info = this.getModuleInfo(id);
+ if (info === null) continue;
+ imports.set(id, [...info.importedIds, ...info.dynamicallyImportedIds]);
+ }
+ },
+ };
+ }
+
+ fingerprint(): string | undefined {
+ if (this.#directiveModules.size === 0) return undefined;
+
+ const reachable = new Set<string>();
+ const queue = [...this.#directiveModules];
+ for (let id = queue.shift(); id !== undefined; id = queue.shift()) {
+ if (reachable.has(id) || !this.#sources.has(id)) continue;
+ reachable.add(id);
+ queue.push(...(this.#imports.get(id) ?? []));
+ }
+
+ const hash = createHash("sha256");
+ for (const id of [...reachable].sort()) {
+ hash
+ .update(relative(this.#appRoot, id).split(sep).join("/"))
+ .update("\0")
+ .update(this.#sources.get(id) ?? "")
+ .update("\0");
+ }
+ return hash.digest("hex");
+ }
+}
+
+interface RolldownModuleGraphContext {
+ getModuleIds(): Iterable<string>;
+ getModuleInfo(id: string): {
+ readonly dynamicallyImportedIds: readonly string[];
+ readonly importedIds: readonly string[];
+ } | null;
+}
+
function createVirtualGenerationModuleMapPlugin(input: {
readonly id: string;
readonly source: string;
@@ -462,12 +552,41 @@ function createAuthoredDirectiveGuardPlugin(): Record<string, unknown> {
return undefined;
}
- await assertNoWorkflowDirectivePrologue({ filePath: id, source });
+ const { hasDirectives } = await prepareAuthoredWorkflowDirectives({ filePath: id, source });
+ if (hasDirectives) {
+ throw new Error(
+ `Module "${id}" uses Workflow directives ("use step" or "use workflow"). ` +
+ "Workflow directives are supported in application modules only, not in extensions or instrumentation.",
+ );
+ }
return undefined;
},
};
}
+// Client mode: steps keep their bodies, workflows become references. Step
+// registration happens once, in the host's step entrypoint.
+function createAuthoredWorkflowDirectivePlugin(input: {
+ readonly appRoot: string;
+ readonly recorder?: AuthoredWorkflowSourceRecorder;
+}): Record<string, unknown> {
+ return {
+ name: "eve-authored-workflow-directives",
+ async transform(source: string, id: string) {
+ if (!AUTHORED_BUNDLED_MODULE_EXTENSION.test(id) || isNodeModulesPath(id)) {
+ return undefined;
+ }
+ if (!isAuthoredApplicationModule(id, input.appRoot)) {
+ return undefined;
+ }
+
+ const transformed = await applyWorkflowTransform(id, source, "client", id, input.appRoot);
+ input.recorder?.record(id, source, transformed.workflowManifest);
+ return transformed.code === source ? undefined : { code: transformed.code, map: null };
+ },
+ };
+}
+
function removeRolldownModuleRegionComments(code: string): string {
return code
.split("\n")
@@ -529,7 +648,7 @@ function resolveAuthoredTsConfigPath(packageRoot: string): string | false {
return false;
}
-function resolveAuthoredPackageRoot(modulePath: string): string {
+export function resolveAuthoredPackageRoot(modulePath: string): string {
let currentDirectory = dirname(modulePath);
while (true) {
diff --git a/packages/eve/src/internal/authored-package-boundary.ts b/packages/eve/src/internal/authored-package-boundary.ts
index 2c470f842..dc05dc4f3 100644
--- a/packages/eve/src/internal/authored-package-boundary.ts
+++ b/packages/eve/src/internal/authored-package-boundary.ts
@@ -3,6 +3,7 @@ import { isBuiltin } from "node:module";
import { dirname, join, resolve, sep } from "node:path";
import { normalizeEsmImportSpecifier } from "#internal/application/import-specifier.js";
+import { resolveWorkflowModulePath } from "#internal/application/package.js";
export const CACHED_CHANNEL_PREFIX = "eve-cached-channel:";
@@ -52,10 +53,7 @@ export function createGenerationPackageBoundaryPlugin(input: {
}
if (isFrameworkRuntimeImport(source, importer)) {
- return {
- external: true,
- id: source,
- };
+ return { external: true, id: resolveFrameworkRuntimeImport(source) };
}
const externalModule = await resolveConfiguredExternalModule.call(this, {
@@ -93,7 +91,7 @@ export function createRuntimeLoaderPackageBoundaryPlugin(input: {
}
if (isFrameworkRuntimeImport(source, importer)) {
- return { external: true, id: source };
+ return { external: true, id: resolveFrameworkRuntimeImport(source) };
}
const externalModule = await resolveConfiguredExternalModule.call(this, {
@@ -366,6 +364,19 @@ function isFrameworkRuntimeImport(source: string, importer: string | undefined):
return false;
}
+/**
+ * `eve` and `eve/*` stay bare: the application installs eve, so Node resolves
+ * them to the one installed copy. The public `workflow` surface is not a
+ * dependency of the application; eve vendors it, so those specifiers bind to
+ * eve's own modules by path and share the process-wide Workflow runtime.
+ */
+function resolveFrameworkRuntimeImport(source: string): string {
+ if (source === "eve" || source.startsWith("eve/")) {
+ return source;
+ }
+ return normalizeEsmImportSpecifier(resolveWorkflowModulePath(source));
+}
+
export function isNodeModulesPath(path: string): boolean {
return path.replaceAll("\\", "/").includes("/node_modules/");
}
diff --git a/packages/eve/src/internal/authored-runtime-modules.ts b/packages/eve/src/internal/authored-runtime-modules.ts
index d349eb3b4..631ae8bc7 100644
--- a/packages/eve/src/internal/authored-runtime-modules.ts
+++ b/packages/eve/src/internal/authored-runtime-modules.ts
@@ -13,6 +13,8 @@ interface PreparedAuthoredRuntimeInstrumentation {
export interface PreparedAuthoredRuntimeModules {
readonly instrumentation?: PreparedAuthoredRuntimeInstrumentation;
readonly moduleMapCode: string;
+ /** Identity of authored sources shared by the workflow driver and step registrations. */
+ readonly workflowSourceFingerprint: string | undefined;
}
/** Builds the authored runtime graph before a development or production host packages it. */
@@ -20,7 +22,8 @@ export async function prepareAuthoredRuntimeModules(input: {
readonly manifest: CompiledAgentManifest;
readonly moduleMapPath: string;
}): Promise<PreparedAuthoredRuntimeModules> {
- const moduleMapCode = await bundleAuthoredModuleMapForGeneration(input);
+ const { code: moduleMapCode, workflowSourceFingerprint } =
+ await bundleAuthoredModuleMapForGeneration(input);
const providersEnabled = input.manifest.config.experimental?.instrumentationProviders ?? false;
const layout = providersEnabled
? resolveInstrumentationLayout({ agentRoot: input.manifest.agentRoot, providersEnabled: true })
@@ -38,5 +41,7 @@ export async function prepareAuthoredRuntimeModules(input: {
instrumentation = { kind: "directory", moduleCodeBySlot };
}
- return instrumentation === undefined ? { moduleMapCode } : { instrumentation, moduleMapCode };
+ return instrumentation === undefined
+ ? { moduleMapCode, workflowSourceFingerprint }
+ : { instrumentation, moduleMapCode, workflowSourceFingerprint };
}
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 e0a8bd570..390f08d9b 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
@@ -549,7 +549,81 @@ describe("development generation artifacts", () => {
expect(changedResources.fingerprint).not.toBe(changed.fingerprint);
});
- it("rejects only authored workflow directives", async () => {
+ it("compiles authored workflow tools for the development runtime", async () => {
+ const app = await scenarioApp({
+ files: {
+ "agent/agent.mjs": 'export default { model: "openai/gpt-5.4" };\n',
+ "agent/instructions.md": "Use the available tools.",
+ "agent/lib/plan.mjs": 'export const PLAN_PREFIX = "plan:";\n',
+ "agent/tools/deploy.mjs": [
+ 'import { PLAN_PREFIX } from "../lib/plan.mjs";',
+ "",
+ "export default {",
+ ' 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";',
+ " return `${PLAN_PREFIX}${service}`;",
+ "}",
+ "",
+ ].join("\n"),
+ "agent/tools/plain.mjs": [
+ 'export default { description: "Plain tool.", execute: () => "plain" };',
+ "",
+ ].join("\n"),
+ },
+ name: "authored-workflow-tools-generation",
+ });
+
+ const compileResult = await compileAgent({ startPath: app.appRoot });
+ const generation = await stageDevelopmentGeneration(compileResult);
+ expect(generation.workflowSourceFingerprint).toEqual(expect.any(String));
+
+ const moduleMap = await loadCompiledModuleMapFromAuthoredSource({
+ compiledArtifactsSource: createAuthoredSourceRuntimeCompiledArtifactsSource(
+ generation.runtimeAppRoot,
+ ),
+ });
+ const deploySourceId = compileResult.manifest.tools.find(
+ (tool) => tool.name === "deploy",
+ )?.sourceId;
+ const deploy = moduleMap.nodes[ROOT_COMPILED_AGENT_NODE_ID]?.modules[deploySourceId!] as {
+ default: { execute: { (input: unknown): Promise<unknown>; workflowId?: string } };
+ };
+ expect(deploy.default.execute.workflowId).toBe("workflow//./agent/tools/deploy//execute");
+ await expect(deploy.default.execute({ service: "api" })).rejects.toThrow(
+ /use start\(execute\) from workflow\/api/u,
+ );
+
+ // A helper the step imports is part of the workflow source graph; an
+ // unrelated tool is not.
+ await writeFile(
+ join(app.appRoot, "agent", "lib", "plan.mjs"),
+ 'export const PLAN_PREFIX = "plan v2:";\n',
+ );
+ const helperChanged = await stageDevelopmentGeneration(
+ await compileAgent({ startPath: app.appRoot }),
+ );
+ expect(helperChanged.workflowSourceFingerprint).not.toBe(generation.workflowSourceFingerprint);
+
+ await writeFile(
+ join(app.appRoot, "agent", "tools", "plain.mjs"),
+ 'export default { description: "Plain tool.", execute: () => "plain v2" };\n',
+ );
+ const plainChanged = await stageDevelopmentGeneration(
+ await compileAgent({ startPath: app.appRoot }),
+ );
+ expect(plainChanged.workflowSourceFingerprint).toBe(helperChanged.workflowSourceFingerprint);
+ expect(plainChanged.fingerprint).not.toBe(helperChanged.fingerprint);
+ });
+
+ it("rejects module-level authored workflow directives", async () => {
const app = await scenarioApp({
files: {
"agent/agent.mjs": 'export default { model: "openai/gpt-5.4" };\n',
@@ -578,10 +652,8 @@ describe("development generation artifacts", () => {
"",
].join("\n"),
);
- const invalidCompile = await compileAgent({ startPath: app.appRoot });
-
- await expect(stageDevelopmentGeneration(invalidCompile)).rejects.toThrow(
- /actual "use step" directive/u,
+ await expect(compileAgent({ startPath: app.appRoot })).rejects.toThrow(
+ /"use step" in .* is a module-level directive/u,
);
await expect(readdir(snapshotsRoot)).resolves.toEqual(stagedGenerations);
});
diff --git a/packages/eve/src/internal/nitro/development-generation.ts b/packages/eve/src/internal/nitro/development-generation.ts
index 2f8d1cca2..96d78b308 100644
--- a/packages/eve/src/internal/nitro/development-generation.ts
+++ b/packages/eve/src/internal/nitro/development-generation.ts
@@ -13,6 +13,8 @@ import {
export interface DevelopmentGeneration extends DevelopmentRuntimeArtifactsSnapshot {
readonly fingerprint: string;
+ /** Identity of the authored sources the workflow driver and step registrations are built from. */
+ readonly workflowSourceFingerprint?: string;
}
interface DevelopmentGenerationPruneState {
@@ -37,10 +39,13 @@ export async function stageDevelopmentGeneration(
runtimeAppRoot: snapshot.runtimeAppRoot,
});
- return {
- ...snapshot,
- fingerprint: materialized.fingerprint,
- };
+ return prepared.workflowSourceFingerprint === undefined
+ ? { ...snapshot, fingerprint: materialized.fingerprint }
+ : {
+ ...snapshot,
+ fingerprint: materialized.fingerprint,
+ workflowSourceFingerprint: prepared.workflowSourceFingerprint,
+ };
} catch (error) {
try {
await rm(snapshot.snapshotRoot, { force: true, recursive: true });
diff --git a/packages/eve/src/internal/nitro/host/dev-host-fingerprint.integration.test.ts b/packages/eve/src/internal/nitro/host/dev-host-fingerprint.integration.test.ts
index afa6f5d40..baabeb117 100644
--- a/packages/eve/src/internal/nitro/host/dev-host-fingerprint.integration.test.ts
+++ b/packages/eve/src/internal/nitro/host/dev-host-fingerprint.integration.test.ts
@@ -25,6 +25,7 @@ interface HostVariant {
readonly instrumentationSlot?: string;
readonly instrumentationSource?: string;
readonly schedule?: { readonly cron: string; readonly markdown: string };
+ readonly workflowSourceFingerprint?: string;
readonly workflowWorld?: "local" | "vercel";
}
@@ -94,6 +95,12 @@ async function createHost(variant: HostVariant = {}): Promise<PreparedDevelopmen
workflowWorldPluginPath: join(appRoot, "workflow-world.mjs"),
},
compileResult: { manifest } as PreparedDevelopmentApplicationHost["compileResult"],
+ generation: {
+ fingerprint: "generation",
+ ...(variant.workflowSourceFingerprint === undefined
+ ? {}
+ : { workflowSourceFingerprint: variant.workflowSourceFingerprint }),
+ } as PreparedDevelopmentApplicationHost["generation"],
} as PreparedDevelopmentApplicationHost;
}
@@ -162,6 +169,19 @@ describe("computeDevelopmentHostFingerprint", () => {
expect(vercel).not.toBe(local);
});
+ it("treats authored workflow sources as structural", async () => {
+ const base = await computeDevelopmentHostFingerprint(await createHost());
+ const withWorkflows = await computeDevelopmentHostFingerprint(
+ await createHost({ workflowSourceFingerprint: "a" }),
+ );
+ const edited = await computeDevelopmentHostFingerprint(
+ await createHost({ workflowSourceFingerprint: "b" }),
+ );
+
+ expect(withWorkflows).not.toBe(base);
+ expect(edited).not.toBe(withWorkflows);
+ });
+
it("leaves schedule definitions runtime-only", async () => {
const base = await computeDevelopmentHostFingerprint(await createHost());
const withSchedule = await computeDevelopmentHostFingerprint(
diff --git a/packages/eve/src/internal/nitro/host/dev-host-fingerprint.ts b/packages/eve/src/internal/nitro/host/dev-host-fingerprint.ts
index 06a011456..5e57502ec 100644
--- a/packages/eve/src/internal/nitro/host/dev-host-fingerprint.ts
+++ b/packages/eve/src/internal/nitro/host/dev-host-fingerprint.ts
@@ -44,6 +44,9 @@ export async function computeDevelopmentHostFingerprint(
environment: readDevelopmentEnvironmentHostValues(host.appRoot),
instrumentation: await readInstrumentationSource(host),
workflow: {
+ // Authored workflow bodies and step registrations are bundled into the
+ // host, so their sources are structural, not runtime, state.
+ authoredSources: host.generation.workflowSourceFingerprint ?? null,
enabled: agentNodes.some((node) => node.workflowTool !== undefined),
world: manifest.config.experimental?.workflow?.world ?? "local",
},
diff --git a/packages/eve/src/internal/nitro/routes/agent-info/build-agent-info-response.ts b/packages/eve/src/internal/nitro/routes/agent-info/build-agent-info-response.ts
index 8dd6af88d..82f5968f9 100644
--- a/packages/eve/src/internal/nitro/routes/agent-info/build-agent-info-response.ts
+++ b/packages/eve/src/internal/nitro/routes/agent-info/build-agent-info-response.ts
@@ -402,6 +402,14 @@ function projectPreparedKernelEffects(
sourceId: tool.sourceId,
});
break;
+ case "workflow-tool":
+ effects.push({
+ action: "workflow-tool-call",
+ audience: [...behavior.availability],
+ kind: "dispatch",
+ sourceId: tool.sourceId,
+ });
+ break;
default: {
const _exhaustive: never = handling;
throw new Error(`Unsupported compiled tool handling: ${String(_exhaustive)}`);
diff --git a/packages/eve/src/internal/testing/workflow-tool-fixtures.ts b/packages/eve/src/internal/testing/workflow-tool-fixtures.ts
new file mode 100644
index 000000000..30a288f87
--- /dev/null
+++ b/packages/eve/src/internal/testing/workflow-tool-fixtures.ts
@@ -0,0 +1,134 @@
+/**
+ * Authored workflow tool bodies for integration tests. Each exported
+ * `"use workflow"` function stands in for a tool's `execute`: the test tier's
+ * bundler registers them in the driver, and the harness sees the stubs the
+ * client transform leaves behind, exactly as it would for an application's
+ * `agent/tools/*.ts`.
+ */
+
+import { createHook, sleep as workflowSleep } from "#compiled/@workflow/core/index.js";
+
+import { ask } from "#execution/tool-run/messages.js";
+import type { ToolContext } from "#tools/definition.js";
+
+export interface DeployInput {
+ readonly service: string;
+}
+
+export async function deployServiceWorkflow(
+ input: DeployInput,
+ ctx: ToolContext,
+): Promise<{ readonly callId: string; readonly plan: string; readonly sessionId: string }> {
+ "use workflow";
+
+ const plan = await planDeployStep(input.service);
+ return { callId: ctx.callId, plan, sessionId: ctx.session.id };
+}
+
+export async function confirmDeployWorkflow(
+ input: DeployInput,
+ ctx: ToolContext,
+): Promise<{ readonly approved: boolean; readonly service: string }> {
+ "use workflow";
+
+ const plan = await planDeployStep(input.service);
+ const answer = await ask(ctx, {
+ display: "confirmation",
+ options: [
+ { id: "approve", label: "Deploy", style: "primary" },
+ { id: "cancel", label: "Cancel" },
+ ],
+ prompt: `Apply ${plan}?`,
+ });
+ return { approved: answer.optionId === "approve", service: input.service };
+}
+
+export async function failingDeployWorkflow(input: DeployInput): Promise<never> {
+ "use workflow";
+
+ await planDeployStep(input.service);
+ throw new Error(`deploy of ${input.service} exploded`);
+}
+
+export async function* reportingDeployWorkflow(
+ input: DeployInput,
+): AsyncGenerator<string, { readonly plan: string }> {
+ "use workflow";
+
+ const plan = await planDeployStep(input.service);
+ yield `planned ${input.service}`;
+ return { plan };
+}
+
+async function planDeployStep(service: string): Promise<string> {
+ "use step";
+
+ return `plan:${service}`;
+}
+
+export async function stepThenRaceWorkflow(
+ input: DeployInput,
+): Promise<{ readonly decided: string; readonly service: string }> {
+ "use workflow";
+ const gate = createHook<{ readonly optionId: string }>();
+ await planDeployStep(input.service);
+ const answer = await Promise.race([gate, workflowSleep("50ms")]);
+ return { decided: answer === undefined ? "timed out" : "answered", service: input.service };
+}
+
+/** Holds in a step until `ctx.abortSignal` fires, then cleans up in `finally`. */
+export async function holdUntilAbortedWorkflow(
+ input: DeployInput,
+ ctx: ToolContext,
+): Promise<{ readonly held: boolean }> {
+ "use workflow";
+ try {
+ await holdStep(ctx.abortSignal);
+ return { held: true };
+ } finally {
+ await releaseStep(input.service);
+ }
+}
+
+async function holdStep(signal: AbortSignal): Promise<void> {
+ "use step";
+
+ await new Promise<void>((resolve, reject) => {
+ if (signal.aborted) {
+ reject(signal.reason);
+ return;
+ }
+ const timer = setTimeout(resolve, 60_000);
+ signal.addEventListener(
+ "abort",
+ () => {
+ clearTimeout(timer);
+ reject(signal.reason);
+ },
+ { once: true },
+ );
+ });
+}
+
+async function releaseStep(service: string): Promise<string> {
+ "use step";
+
+ return `released ${service}`;
+}
+
+export async function askThenRaceWorkflow(
+ input: DeployInput,
+ ctx: ToolContext,
+): Promise<{ readonly decided: string; readonly service: string }> {
+ "use workflow";
+ const pending = ask(ctx, {
+ display: "confirmation",
+ options: [
+ { id: "approve", label: "Deploy", style: "primary" },
+ { id: "cancel", label: "Cancel" },
+ ],
+ prompt: `Apply ${input.service}?`,
+ });
+ const answer = await Promise.race([pending, workflowSleep("50ms")]);
+ return { decided: answer === undefined ? "timed out" : "answered", service: input.service };
+}
diff --git a/packages/eve/src/internal/testing/workflow-vitest-plugin.ts b/packages/eve/src/internal/testing/workflow-vitest-plugin.ts
index c89e14516..dbf9b7a56 100644
--- a/packages/eve/src/internal/testing/workflow-vitest-plugin.ts
+++ b/packages/eve/src/internal/testing/workflow-vitest-plugin.ts
@@ -1,9 +1,6 @@
import { join, relative } from "node:path";
-import {
- applyWorkflowTransform,
- detectWorkflowPatterns,
-} from "#internal/workflow-bundle/workflow-builders.js";
+import { applyWorkflowTransform } from "#internal/workflow-bundle/workflow-builders.js";
const WORKFLOW_TEST_OUTPUT_DIR = ".workflow-vitest";
@@ -48,12 +45,6 @@ function createWorkflowTransformPlugin(): Plugin {
return null;
}
- const patterns = detectWorkflowPatterns(code);
-
- if (!patterns.hasUseStep && !patterns.hasUseWorkflow && !patterns.hasSerde) {
- return null;
- }
-
const workingDir = process.cwd();
const transformed = await applyWorkflowTransform(
createRelativeTransformFilename(workingDir, id),
@@ -63,10 +54,7 @@ function createWorkflowTransformPlugin(): Plugin {
workingDir,
);
- return {
- code: transformed.code,
- map: null,
- };
+ return transformed.code === code ? null : { code: transformed.code, map: null };
},
};
}
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
new file mode 100644
index 000000000..7cda45c1c
--- /dev/null
+++ b/packages/eve/src/internal/workflow-bundle/authored-workflow-directives.test.ts
@@ -0,0 +1,200 @@
+import { describe, expect, it } from "vitest";
+
+import { prepareAuthoredWorkflowDirectives } from "./authored-workflow-directives.js";
+
+const FILE = "/app/agent/tools/deploy.ts";
+
+function toolModule(execute: string): string {
+ return [
+ 'import { defineTool } from "eve/tools";',
+ 'import { z } from "zod";',
+ "",
+ "export default defineTool({",
+ ' description: "Deploy",',
+ " inputSchema: z.object({ service: z.string() }),",
+ execute,
+ " toModelOutput: (output) => output,",
+ "});",
+ "",
+ "async function planDeploy(service: string): Promise<string> {",
+ ' "use step";',
+ " return service;",
+ "}",
+ "",
+ ].join("\n");
+}
+
+describe("prepareAuthoredWorkflowDirectives", () => {
+ it("leaves modules without directives untouched", async () => {
+ const source = 'export const value = "use step is only text here";\n';
+ await expect(prepareAuthoredWorkflowDirectives({ filePath: FILE, source })).resolves.toEqual({
+ hasDirectives: false,
+ hasWorkflowDirective: false,
+ source,
+ });
+ });
+
+ it("hoists a shorthand execute method into a top-level declaration", async () => {
+ const source = toolModule(
+ [
+ " async execute({ service }: { service: string }, ctx: ToolContext): Promise<{ ok: boolean }> {",
+ ' "use workflow";',
+ " const plan = await planDeploy(service);",
+ " return { ok: plan.length > 0 };",
+ " },",
+ ].join("\n"),
+ );
+
+ 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" +
+ ' "use workflow";',
+ );
+ expect(prepared.source).not.toContain("async execute(");
+ });
+
+ it("hoists an arrow function execute property", async () => {
+ const source = toolModule(
+ [
+ " execute: async (input: { service: string }) => {",
+ ' "use workflow";',
+ " return input;",
+ " },",
+ ].join("\n"),
+ );
+
+ const prepared = await prepareAuthoredWorkflowDirectives({ filePath: FILE, source });
+
+ expect(prepared.source).toContain(
+ 'async function execute(input: { service: string }) {\n "use workflow";\n return input;\n }',
+ );
+ expect(prepared.source).toContain(" execute,\n");
+ });
+
+ it("hoists a function expression execute property", async () => {
+ const source = toolModule(
+ [
+ " execute: async function (input: { service: string }) {",
+ ' "use workflow";',
+ " return input;",
+ " },",
+ ].join("\n"),
+ );
+
+ const prepared = await prepareAuthoredWorkflowDirectives({ filePath: FILE, source });
+
+ expect(prepared.source).toContain(
+ 'async function execute(input: { service: string }) {\n "use workflow";',
+ );
+ });
+
+ 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("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 });',
+ "async function deploy(input: unknown) {",
+ ' "use workflow";',
+ " return input;",
+ "}",
+ "",
+ ].join("\n");
+
+ await expect(prepareAuthoredWorkflowDirectives({ filePath: FILE, source })).resolves.toEqual({
+ executeWorkflow: "deploy",
+ hasDirectives: true,
+ hasWorkflowDirective: true,
+ source,
+ });
+ });
+
+ it("rejects a module-level directive", async () => {
+ await expect(
+ prepareAuthoredWorkflowDirectives({
+ filePath: FILE,
+ source: '"use step";\nexport const value = 1;\n',
+ }),
+ ).rejects.toThrow(/"use step" in .* is a module-level directive/u);
+ });
+
+ it("rejects a directive on a nested or anonymous function", async () => {
+ await expect(
+ prepareAuthoredWorkflowDirectives({
+ filePath: FILE,
+ source: 'const run = async () => {\n "use step";\n return 1;\n};\nexport { run };\n',
+ }),
+ ).rejects.toThrow(/marks an arrow function/u);
+
+ await expect(
+ prepareAuthoredWorkflowDirectives({
+ filePath: FILE,
+ source: [
+ "export async function outer() {",
+ " async function inner() {",
+ ' "use step";',
+ " }",
+ " return inner();",
+ "}",
+ "",
+ ].join("\n"),
+ }),
+ ).rejects.toThrow(/marks the nested function "inner"/u);
+ });
+
+ it("rejects a directive on a synchronous declaration", async () => {
+ await expect(
+ prepareAuthoredWorkflowDirectives({
+ filePath: FILE,
+ source: 'export function ping() {\n "use step";\n return 1;\n}\n',
+ }),
+ ).rejects.toThrow(/is not async/u);
+ });
+
+ it("rejects a step directive on the execute method", async () => {
+ await expect(
+ prepareAuthoredWorkflowDirectives({
+ filePath: FILE,
+ source: toolModule(
+ [" async execute() {", ' "use step";', " return 1;", " },"].join("\n"),
+ ),
+ }),
+ ).rejects.toThrow(/"use step".*marks the default export's "execute" method/u);
+ });
+
+ 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("rejects hoisting over an existing top-level execute binding", async () => {
+ const source = `${toolModule([" async execute() {", ' "use workflow";', " return 1;", " },"].join("\n"))}const execute = 1;\n`;
+
+ await expect(prepareAuthoredWorkflowDirectives({ filePath: FILE, source })).rejects.toThrow(
+ /also declares a top-level "execute" binding/u,
+ );
+ });
+});
diff --git a/packages/eve/src/internal/workflow-bundle/authored-workflow-directives.ts b/packages/eve/src/internal/workflow-bundle/authored-workflow-directives.ts
new file mode 100644
index 000000000..0b446220d
--- /dev/null
+++ b/packages/eve/src/internal/workflow-bundle/authored-workflow-directives.ts
@@ -0,0 +1,308 @@
+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";
+
+const HOISTED_EXECUTE_NAME = "execute";
+
+type AstNode = {
+ async?: boolean;
+ generator?: boolean;
+ body?: AstNode | AstNode[] | null;
+ computed?: boolean;
+ declaration?: AstNode | null;
+ declarations?: AstNode[];
+ directive?: string;
+ end?: number;
+ expression?: AstNode | boolean | null;
+ id?: AstNode | null;
+ key?: AstNode | null;
+ kind?: string;
+ local?: AstNode | null;
+ method?: boolean;
+ name?: string;
+ params?: AstNode[];
+ properties?: AstNode[];
+ returnType?: AstNode | null;
+ specifiers?: AstNode[];
+ start?: number;
+ type?: string;
+ typeParameters?: AstNode | null;
+ value?: unknown;
+ arguments?: AstNode[];
+};
+
+type AstProgram = { body?: AstNode[] };
+
+interface DirectiveFunctionNode {
+ readonly directive: string;
+ readonly fn: AstNode;
+}
+
+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;
+}
+
+/**
+ * The directive transform understands one shape: a top-level `async function`
+ * whose first statement is the directive. A tool's `execute` method is hoisted
+ * into that shape here; every other placement is a build error, because an
+ * ignored directive would run side effects inline in a replayed body.
+ */
+export async function prepareAuthoredWorkflowDirectives(input: {
+ readonly filePath: string;
+ readonly source: string;
+}): Promise<AuthoredWorkflowDirectiveSource> {
+ const program = (await parseWithNitroRolldownAst(input.filePath, input.source)) as AstProgram;
+ const body = program.body ?? [];
+
+ for (const statement of body) {
+ if (typeof statement.directive !== "string") break;
+ const directive = readWorkflowDirective(statement);
+ if (directive !== undefined) {
+ 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.`,
+ );
+ }
+ }
+
+ const allowed = new Set<AstNode>();
+ for (const statement of body) {
+ const declaration =
+ statement.type === "FunctionDeclaration"
+ ? statement
+ : statement.type === "ExportNamedDeclaration" &&
+ statement.declaration?.type === "FunctionDeclaration"
+ ? statement.declaration
+ : undefined;
+ if (declaration !== undefined) allowed.add(declaration);
+ }
+
+ const executeProperty = findDefaultExportExecuteProperty(body);
+ const executeFunction =
+ executeProperty !== undefined &&
+ isAstNode(executeProperty.value) &&
+ isFunctionLike(executeProperty.value)
+ ? executeProperty.value
+ : undefined;
+ if (executeFunction !== undefined) allowed.add(executeFunction);
+
+ const 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.`,
+ );
+ }
+ if (entry.fn.async !== true) {
+ throw new Error(
+ `${JSON.stringify(entry.directive)} in "${input.filePath}" marks ${describeFunction(entry.fn)}, which is not async. ` +
+ `Declare it with "async function".`,
+ );
+ }
+ if (entry.fn === executeFunction && entry.directive !== "use workflow") {
+ throw new Error(
+ `"use step" in "${input.filePath}" marks the default export's "execute" method. ` +
+ `A tool's "execute" can be a workflow ("use workflow"); steps are the helper functions it calls.`,
+ );
+ }
+ }
+
+ const hoist = found.find((entry) => entry.fn === executeFunction);
+ if (hoist === undefined || executeProperty === undefined) {
+ const prepared: AuthoredWorkflowDirectiveSource = {
+ hasDirectives: true,
+ hasWorkflowDirective,
+ source: input.source,
+ };
+ const referenced = readExecuteReference(executeProperty, found);
+ return referenced === undefined ? prepared : { ...prepared, executeWorkflow: referenced };
+ }
+
+ if (declaresTopLevelBinding(body, HOISTED_EXECUTE_NAME)) {
+ throw new Error(
+ `"use workflow" in "${input.filePath}" marks the "execute" method, but the module also declares a top-level "${HOISTED_EXECUTE_NAME}" binding. ` +
+ `eve hoists that method to a top-level "async function ${HOISTED_EXECUTE_NAME}"; rename the existing binding.`,
+ );
+ }
+
+ 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;
+ const definition =
+ declaration?.type === "CallExpression" ? declaration.arguments?.[0] : declaration;
+ if (definition?.type !== "ObjectExpression") return undefined;
+
+ return definition.properties?.find(
+ (property) =>
+ property.type === "Property" &&
+ property.kind === "init" &&
+ property.computed !== true &&
+ readPropertyName(property.key) === HOISTED_EXECUTE_NAME,
+ );
+}
+
+function hoistExecuteMethod(source: string, property: AstNode, fn: AstNode): string {
+ if (
+ property.start === undefined ||
+ property.end === undefined ||
+ !isAstNode(fn.body) ||
+ fn.body.start === undefined ||
+ fn.body.end === undefined
+ ) {
+ throw new Error("Cannot hoist an execute method without source ranges.");
+ }
+
+ const params = fn.params ?? [];
+ const first = params[0];
+ const last = params[params.length - 1];
+ const paramsText =
+ first?.start === undefined || last?.end === undefined
+ ? ""
+ : source.slice(first.start, last.end);
+ const typeParametersText = sliceNode(source, fn.typeParameters);
+ const returnTypeText = sliceNode(source, fn.returnType);
+ const bodyText = source.slice(fn.body.start, fn.body.end);
+ const star = fn.generator === true ? "*" : "";
+ const declaration = `async function${star} ${HOISTED_EXECUTE_NAME}${typeParametersText}(${paramsText})${returnTypeText} ${bodyText}`;
+
+ return `${source.slice(0, property.start)}${HOISTED_EXECUTE_NAME}${source.slice(property.end)}\n${declaration}\n`;
+}
+
+function sliceNode(source: string, node: AstNode | null | undefined): string {
+ if (node === null || node === undefined || node.start === undefined || node.end === undefined) {
+ return "";
+ }
+ return source.slice(node.start, node.end);
+}
+
+function declaresTopLevelBinding(body: readonly AstNode[], name: string): boolean {
+ for (const statement of body) {
+ const declaration =
+ statement.type === "ExportNamedDeclaration" ? statement.declaration : statement;
+ if (declaration === null || declaration === undefined) continue;
+ if (
+ (declaration.type === "FunctionDeclaration" || declaration.type === "ClassDeclaration") &&
+ declaration.id?.name === name
+ ) {
+ return true;
+ }
+ if (declaration.type === "VariableDeclaration") {
+ for (const declarator of declaration.declarations ?? []) {
+ if (declarator.id?.name === name) return true;
+ }
+ }
+ if (declaration.type === "ImportDeclaration") {
+ for (const specifier of declaration.specifiers ?? []) {
+ if (specifier.local?.name === name) return true;
+ }
+ }
+ }
+ return false;
+}
+
+function collectDirectiveFunctions(root: AstNode): DirectiveFunctionNode[] {
+ const found: DirectiveFunctionNode[] = [];
+ visit(root, (node) => {
+ if (!isFunctionLike(node)) return;
+ const directive = readLeadingDirective(node);
+ if (directive !== undefined) found.push({ directive, fn: node });
+ });
+ return found;
+}
+
+function readLeadingDirective(fn: AstNode): string | undefined {
+ if (!isAstNode(fn.body) || fn.body.type !== "BlockStatement" || !Array.isArray(fn.body.body)) {
+ return undefined;
+ }
+ return readWorkflowDirective(fn.body.body[0]);
+}
+
+function describeFunction(fn: AstNode): string {
+ if (fn.type === "FunctionDeclaration") {
+ return fn.id?.name === undefined
+ ? "a nested function declaration"
+ : `the nested function "${fn.id.name}"`;
+ }
+ if (fn.type === "ArrowFunctionExpression") return "an arrow function";
+ return fn.id?.name === undefined ? "a function expression" : `the function "${fn.id.name}"`;
+}
+
+function readPropertyName(key: AstNode | null | undefined): string | undefined {
+ if (key === null || key === undefined) return undefined;
+ if (key.type === "Identifier") return key.name;
+ if (key.type === "Literal" && typeof key.value === "string") return key.value;
+ return undefined;
+}
+
+function isFunctionLike(node: AstNode): boolean {
+ return (
+ node.type === "FunctionDeclaration" ||
+ node.type === "FunctionExpression" ||
+ node.type === "ArrowFunctionExpression"
+ );
+}
+
+function visit(node: AstNode, visitor: (node: AstNode) => void): void {
+ if (node.type?.startsWith("TS")) return;
+ visitor(node);
+ for (const value of Object.values(node)) {
+ if (Array.isArray(value)) {
+ for (const item of value) {
+ if (isAstNode(item)) visit(item, visitor);
+ }
+ } else if (isAstNode(value)) {
+ visit(value, visitor);
+ }
+ }
+}
+
+function isAstNode(value: unknown): value is AstNode {
+ return value !== null && typeof value === "object" && typeof (value as AstNode).type === "string";
+}
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
new file mode 100644
index 000000000..e2b99bb25
--- /dev/null
+++ b/packages/eve/src/internal/workflow-bundle/authored-workflow-modules.integration.test.ts
@@ -0,0 +1,201 @@
+import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+
+import { prepareAuthoredWorkflowDirectives } from "./authored-workflow-directives.js";
+import {
+ discoverAuthoredWorkflowModules,
+ readAuthoredExecuteWorkflowId,
+} from "./authored-workflow-modules.js";
+
+let appRoot: string;
+
+async function write(relativePath: string, source: string): Promise<string> {
+ const filePath = join(appRoot, relativePath);
+ await mkdir(join(filePath, ".."), { recursive: true });
+ await writeFile(filePath, source);
+ return filePath;
+}
+
+beforeEach(async () => {
+ appRoot = await mkdtemp(join(tmpdir(), "eve-authored-workflows-"));
+ await write("package.json", JSON.stringify({ name: "fixture-app", type: "module" }));
+});
+
+afterEach(async () => {
+ await rm(appRoot, { force: true, recursive: true });
+});
+
+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 { plan } from "../lib/plan.ts";
+export default defineTool({
+ description: "d",
+ inputSchema: {},
+ async execute(input) {
+ "use workflow";
+ return plan(input);
+ },
+});`,
+ );
+ const helper = await write(
+ "agent/lib/plan.ts",
+ `export async function plan(input) {
+ "use step";
+ return input;
+}`,
+ );
+ await write(
+ "agent/tools/plain.ts",
+ `export default { description: "p", async execute() { return 1; } };`,
+ );
+ await write(
+ "agent/lib/quoted.ts",
+ `export const text = '"use workflow" is only a directive as a statement';`,
+ );
+ await write("node_modules/dep/index.js", `export async function f() { "use workflow"; }`);
+ await write(
+ ".output.eve-backup-crashed/server/_libs/eve+zod.mjs",
+ `const step = async function () { "use step"; };\nexport { step };`,
+ );
+ await write(
+ ".eve/builds/x/output/server/index.mjs",
+ `export async function f() { "use step"; }`,
+ );
+ await write(
+ "src/components/banner.js",
+ `// "use step" helpers live in ../lib\nexport function Banner() { return <b>hi</b>; }`,
+ );
+ await write(
+ ".well-known/workflow/v1/flow.js",
+ `export async function generated() {\n "use workflow";\n}`,
+ );
+ await write("dist/out.js", `export async function f() { "use step"; }`);
+ await write("agent/README.md", `"use workflow"`);
+
+ await expect(discoverAuthoredWorkflowModules(appRoot)).resolves.toEqual({
+ directiveModules: [helper, tool],
+ workflowModules: [tool],
+ });
+ });
+
+ it("leaves modules without a directive unparsed, so JSX in plain .js never fails the scan", async () => {
+ await write(
+ "src/app/layout.js",
+ `export default function RootLayout({ children }) {
+ return <html><body>{children}</body></html>;
+}`,
+ );
+ const tool = await write(
+ "agent/tools/deploy.ts",
+ `export default {
+ description: "d",
+ async execute() {
+ "use workflow";
+ return 1;
+ },
+};`,
+ );
+
+ await expect(discoverAuthoredWorkflowModules(appRoot)).resolves.toEqual({
+ directiveModules: [tool],
+ workflowModules: [tool],
+ });
+ });
+
+ it("finds nothing without an application package.json", async () => {
+ await rm(join(appRoot, "package.json"));
+ await write("agent/tools/deploy.ts", `export async function run() { "use workflow"; }`);
+
+ await expect(discoverAuthoredWorkflowModules(appRoot)).resolves.toEqual({
+ directiveModules: [],
+ workflowModules: [],
+ });
+ });
+
+ 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.
+ await expect(discoverAuthoredWorkflowModules(appRoot)).resolves.toEqual({
+ directiveModules: [],
+ workflowModules: [],
+ });
+ 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 () => {
+ await write(
+ "agent/tools/bad.ts",
+ `export default {
+ execute() {
+ const inner = async () => {
+ "use workflow";
+ };
+ return inner();
+ },
+};`,
+ );
+
+ await expect(discoverAuthoredWorkflowModules(appRoot)).rejects.toThrow(/use workflow/);
+ });
+});
+
+describe("readAuthoredExecuteWorkflowId", () => {
+ it("names the run a tool's execute compiles to, in both authoring shapes", async () => {
+ const inline = await write(
+ "agent/tools/deploy.ts",
+ [
+ 'import { defineTool } from "eve/tools";',
+ "export default defineTool({",
+ ' description: "d",',
+ " inputSchema: {},",
+ " async execute() {",
+ ' "use workflow";',
+ " return 1;",
+ " },",
+ "});",
+ "",
+ ].join("\n"),
+ );
+ const referenced = await write(
+ "agent/tools/nested/release.ts",
+ [
+ 'import { defineTool } from "eve/tools";',
+ 'export default defineTool({ description: "d", inputSchema: {}, execute: release });',
+ "async function release() {",
+ ' "use workflow";',
+ " return 1;",
+ "}",
+ "",
+ ].join("\n"),
+ );
+ const plain = await write(
+ "agent/tools/ping.ts",
+ 'import { defineTool } from "eve/tools";\nexport default defineTool({ description: "d", inputSchema: {}, execute: () => 1 });\n',
+ );
+
+ await expect(readAuthoredExecuteWorkflowId({ appRoot, filePath: inline })).resolves.toBe(
+ "workflow//./agent/tools/deploy//execute",
+ );
+ await expect(readAuthoredExecuteWorkflowId({ appRoot, filePath: referenced })).resolves.toBe(
+ "workflow//./agent/tools/nested/release//release",
+ );
+ await expect(
+ readAuthoredExecuteWorkflowId({ appRoot, filePath: plain }),
+ ).resolves.toBeUndefined();
+ });
+});
diff --git a/packages/eve/src/internal/workflow-bundle/authored-workflow-modules.ts b/packages/eve/src/internal/workflow-bundle/authored-workflow-modules.ts
new file mode 100644
index 000000000..931f429f0
--- /dev/null
+++ b/packages/eve/src/internal/workflow-bundle/authored-workflow-modules.ts
@@ -0,0 +1,122 @@
+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 { prepareAuthoredWorkflowDirectives } from "./authored-workflow-directives.js";
+import { isWorkflowSourceFile } from "./builder-support.js";
+import {
+ authoredWorkflowId,
+ isAuthoredApplicationModule,
+ isAuthoredApplicationRoot,
+} from "./workflow-builders.js";
+
+// The SDK's own ignore list (`BaseBuilder.getInputFiles`) plus eve's generated locations.
+const IGNORED_DIRECTORIES = new Set([
+ ".cache",
+ ".eve",
+ ".git",
+ ".next",
+ ".nitro",
+ ".nuxt",
+ ".output",
+ ".pnpm-store",
+ ".svelte-kit",
+ ".swc",
+ ".turbo",
+ ".vercel",
+ ".workflow-data",
+ ".workflow-vitest",
+ ".yarn",
+ "coverage",
+ "dist",
+ "node_modules",
+]);
+
+function isIgnoredDirectory(name: string): boolean {
+ return IGNORED_DIRECTORIES.has(name) || name.startsWith(".output.");
+}
+
+export interface AuthoredWorkflowModules {
+ readonly directiveModules: readonly string[];
+ readonly workflowModules: readonly string[];
+}
+
+/**
+ * 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.
+ */
+export async function discoverAuthoredWorkflowModules(
+ appRoot: string,
+): Promise<AuthoredWorkflowModules> {
+ const directiveModules: string[] = [];
+ const workflowModules: string[] = [];
+ if (!isAuthoredApplicationRoot(appRoot)) return { directiveModules, workflowModules };
+
+ const files = await collectSourceFiles(appRoot);
+ for (const filePath of files.sort()) {
+ if (!isAuthoredApplicationModule(filePath, appRoot) || isGeneratedWorkflowFile(filePath))
+ continue;
+ const source = await readFile(filePath, "utf8");
+ if (!detectWorkflowPatterns(source).hasDirective) continue;
+ const prepared = await prepareAuthoredWorkflowDirectives({ filePath, source });
+ if (!prepared.hasDirectives) continue;
+ directiveModules.push(filePath);
+ if (prepared.hasWorkflowDirective) workflowModules.push(filePath);
+ }
+
+ return { directiveModules, workflowModules };
+}
+
+async function collectSourceFiles(root: string): Promise<string[]> {
+ const files: string[] = [];
+
+ async function visit(directory: string): Promise<void> {
+ let entries: Dirent[];
+ try {
+ entries = await readdir(directory, { withFileTypes: true });
+ } catch (error) {
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") return;
+ throw error;
+ }
+
+ for (const entry of entries) {
+ const entryPath = join(directory, entry.name);
+ if (entry.isDirectory()) {
+ if (!isIgnoredDirectory(entry.name)) await visit(entryPath);
+ continue;
+ }
+ if (!entry.isFile()) continue;
+ if (isWorkflowSourceFile(entry.name)) files.push(entryPath);
+ }
+ }
+
+ await visit(root);
+ return files;
+}
+
+/**
+ * The workflow id a tool's `execute` will run as, or `undefined` for an
+ * ordinary tool. Derived from the source the way the transform derives it, so
+ * the compiled manifest and the driver registry name the same run.
+ */
+export async function readAuthoredExecuteWorkflowId(input: {
+ readonly appRoot: string;
+ readonly filePath: string;
+}): Promise<string | undefined> {
+ if (!isAuthoredApplicationModule(input.filePath, input.appRoot)) return undefined;
+ const source = await readFile(input.filePath, "utf8");
+ if (!detectWorkflowPatterns(source).hasDirective) return undefined;
+ const { executeWorkflow } = await prepareAuthoredWorkflowDirectives({
+ filePath: input.filePath,
+ source,
+ });
+ return executeWorkflow === undefined
+ ? undefined
+ : authoredWorkflowId(input.filePath, input.appRoot, executeWorkflow);
+}
diff --git a/packages/eve/src/internal/workflow-bundle/builder-support.ts b/packages/eve/src/internal/workflow-bundle/builder-support.ts
index 9f8721cba..484dd432e 100644
--- a/packages/eve/src/internal/workflow-bundle/builder-support.ts
+++ b/packages/eve/src/internal/workflow-bundle/builder-support.ts
@@ -1,7 +1,8 @@
+import { WORKFLOW_REGISTRY_GLOBAL } from "#execution/workflow-registry.js";
import { builtinModules } from "node:module";
import { existsSync } from "node:fs";
import { mkdir, readFile, readdir } from "node:fs/promises";
-import { dirname, join, relative, resolve } from "node:path";
+import { dirname, extname, join, relative, resolve } from "node:path";
import { atomicWriteFile } from "#shared/atomic-write-file.js";
@@ -37,7 +38,7 @@ const NODE_BUILTIN_MODULES = new Set([
...builtinModules,
...builtinModules.map((moduleName) => `node:${moduleName}`),
]);
-const WORKFLOW_INPUT_EXTENSIONS = new Set([
+export const WORKFLOW_SOURCE_EXTENSIONS: readonly string[] = [
".ts",
".tsx",
".mts",
@@ -46,7 +47,11 @@ const WORKFLOW_INPUT_EXTENSIONS = new Set([
".jsx",
".mjs",
".cjs",
-]);
+];
+
+export function isWorkflowSourceFile(fileName: string): boolean {
+ return WORKFLOW_SOURCE_EXTENSIONS.includes(extname(fileName));
+}
const IGNORED_INPUT_DIRECTORIES = new Set([
"node_modules",
".git",
@@ -80,8 +85,9 @@ export interface WorkflowBundleDiscoveredEntries {
export interface WorkflowBundleCreateWorkflowsBundleOptions {
readonly additionalOutputs?: readonly WorkflowBundleOutput[];
- readonly discoveredEntries?: WorkflowBundleDiscoveredEntries;
- readonly inputFiles: readonly string[];
+ readonly appWorkflowFiles: readonly string[];
+ readonly frameworkSerdeFiles: readonly string[];
+ readonly frameworkWorkflowFiles: readonly string[];
readonly outfile: string;
readonly stepRegistrationsPath: string;
readonly tsconfigPath?: string;
@@ -140,9 +146,7 @@ export async function collectWorkflowInputFiles(root: string): Promise<string[]>
continue;
}
- const extension = entry.name.match(/\.[^.]+$/)?.[0];
-
- if (extension !== undefined && WORKFLOW_INPUT_EXTENSIONS.has(extension)) {
+ if (isWorkflowSourceFile(entry.name)) {
files.push(join(directory, entry.name));
}
}
@@ -222,6 +226,39 @@ export function createWorkflowRuntimeAliasPlugin(): WorkflowRolldownPlugin {
};
}
+/**
+ * `workflow` resolves to the body-side shim. A `workflow/api` import still live
+ * after step bodies were stubbed means a body calls the runtime API; fail the
+ * build here rather than the driver later.
+ */
+export function createWorkflowDriverAliasPlugin(workingDir: string): WorkflowRolldownPlugin {
+ return {
+ name: "eve-workflow-driver-aliases",
+ resolveId(source: string, importer?: string) {
+ if (source === "workflow/errors") {
+ return resolveWorkflowModulePath(source);
+ }
+
+ if (source === "workflow/api" || source === "workflow/runtime") {
+ const via = importer ? ` (imported by "${importer}")` : "";
+ throw new Error(
+ `Workflow bundle cannot import "${source}"${via}: the runtime API is not available ` +
+ `inside a workflow body. Call it from a "use step" function and await that step from the body.`,
+ );
+ }
+
+ if (source !== "workflow") {
+ return undefined;
+ }
+
+ return resolveFirstExistingPath([
+ join(workingDir, "src", "internal", "workflow-bundle", "workflow-core-shim.ts"),
+ join(workingDir, "dist", "src", "internal", "workflow-bundle", "workflow-core-shim.js"),
+ ]);
+ },
+ };
+}
+
export function createEvePackageImportsPlugin(
workingDir: string,
options: { workflowCondition?: boolean } = {},
@@ -252,7 +289,7 @@ export function createEvePackageImportsPlugin(
}
return resolveFirstExistingPath(
- [".ts", ".tsx", ".mts", ".cts", ".js", ".jsx", ".mjs", ".cjs"].flatMap((extension) => [
+ WORKFLOW_SOURCE_EXTENSIONS.flatMap((extension) => [
join(workingDir, "src", `${sourceSubpath}${extension}`),
join(workingDir, "dist", "src", `${sourceSubpath}${extension}`),
]),
@@ -346,7 +383,7 @@ export async function bundleWorkflowStepRegistrations(input: {
],
resolve: {
conditionNames: ["eve-source"],
- extensions: [".ts", ".tsx", ".mts", ".cts", ".js", ".jsx", ".mjs", ".cjs"],
+ extensions: WORKFLOW_SOURCE_EXTENSIONS,
mainFields: ["module", "main"],
},
tsconfig: input.tsconfigPath ?? false,
@@ -405,6 +442,22 @@ export async function bundleFinalWorkflowOutput(input: {
await writeWorkflowBundleAtomically(input.outfile, workflowFunctionCode);
}
+// The transform emits bare `.set(...)` calls, so the Map must exist before any chunk runs.
+const WORKFLOW_REGISTRY_BANNER = `globalThis.${WORKFLOW_REGISTRY_GLOBAL} = new Map();`;
+
+/**
+ * Chunks share state only through globals (the workflow registry, the serde
+ * class registry, `Symbol.for` keys), so each runs in its own IIFE and their
+ * top-level declarations never collide.
+ */
+export function composeWorkflowDriverCode(chunks: readonly string[]): string {
+ const bodies = chunks
+ .map((chunk) => chunk.trim())
+ .filter((chunk) => chunk.length > 0)
+ .map((chunk) => `(function () {\n${chunk}\n})();`);
+ return [WORKFLOW_REGISTRY_BANNER, ...bodies].join("\n");
+}
+
export function createWorkflowEntrypointSource(input: {
readonly code: string;
readonly queueNamespace: string;
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 4eaad4f0c..d0d43c166 100644
--- a/packages/eve/src/internal/workflow-bundle/builder.scenario.test.ts
+++ b/packages/eve/src/internal/workflow-bundle/builder.scenario.test.ts
@@ -533,6 +533,61 @@ describe("WorkflowBundleBuilder", () => {
}
});
+ it("fails the driver build when a workflow body calls workflow/api", async () => {
+ const tempRoot = await mkdtemp(join(tmpdir(), "eve-workflow-bundle-api-in-body-"));
+ const outDir = join(tempRoot, "workflow-build");
+ const flowFilePath = join(tempRoot, "flow.ts");
+ const compiledArtifactsBootstrapPath = join(tempRoot, "compiled-artifacts-bootstrap.mjs");
+
+ try {
+ await Promise.all([
+ writeFile(
+ compiledArtifactsBootstrapPath,
+ [
+ "export async function __eveInstallCompiledArtifactsStep() {",
+ ' "use step";',
+ " return null;",
+ "}",
+ "",
+ ].join("\n"),
+ ),
+ writeFile(
+ flowFilePath,
+ [
+ 'import { start } from "workflow/api";',
+ "export async function child() {",
+ ' "use workflow";',
+ " return 1;",
+ "}",
+ "export async function parent() {",
+ ' "use workflow";',
+ " return await start(child, []);",
+ "}",
+ "",
+ ].join("\n"),
+ ),
+ ]);
+
+ const builder = new FixtureWorkflowBundleBuilder(
+ {
+ agentName: "test-agent",
+ appRoot: tempRoot,
+ compiledArtifactsBootstrapPath,
+ outDir,
+ rootDir: tempRoot,
+ watch: false,
+ },
+ [flowFilePath],
+ );
+
+ await expect(builder.build()).rejects.toThrow(
+ /cannot import "workflow\/api".*not available inside a workflow body.*"use step"/s,
+ );
+ } finally {
+ await rm(tempRoot, { force: true, recursive: true });
+ }
+ });
+
it("bundles hook ownership checks through the workflow core shim", async () => {
const tempRoot = await mkdtemp(join(tmpdir(), "eve-workflow-bundle-hook-conflict-"));
const outDir = join(tempRoot, "workflow-build");
@@ -657,4 +712,107 @@ describe("WorkflowBundleBuilder", () => {
await rm(tempRoot, { force: true, recursive: true });
}
});
+
+ it("bundles authored workflow tools from the application root", async () => {
+ const tempRoot = await mkdtemp(join(tmpdir(), "eve-workflow-bundle-authored-"));
+ const appRoot = join(tempRoot, "app");
+ const outDir = join(tempRoot, "workflow-build");
+ const flowFilePath = join(tempRoot, "flow.ts");
+ const compiledArtifactsBootstrapPath = join(tempRoot, "compiled-artifacts-bootstrap.mjs");
+ const toolPath = join(appRoot, "agent", "tools", "deploy.ts");
+ const stepsPath = join(appRoot, "agent", "lib", "steps.ts");
+
+ try {
+ await mkdir(join(appRoot, "agent", "tools"), { recursive: true });
+ await mkdir(join(appRoot, "agent", "lib"), { recursive: true });
+ await mkdir(join(appRoot, "node_modules", "vendored"), { recursive: true });
+ await Promise.all([
+ writeFile(compiledArtifactsBootstrapPath, "export {};\n"),
+ writeFile(
+ flowFilePath,
+ ["export async function flow() {", ' "use workflow";', " return 1;", "}", ""].join(
+ "\n",
+ ),
+ ),
+ writeFile(
+ join(appRoot, "package.json"),
+ `${JSON.stringify({ dependencies: { eve: "*" }, name: "authored-app", version: "0.0.0" })}\n`,
+ ),
+ // Dependency trees are never authored modules, even with directives.
+ writeFile(
+ join(appRoot, "node_modules", "vendored", "index.js"),
+ 'export async function vendored() {\n "use step";\n}\n',
+ ),
+ writeFile(
+ stepsPath,
+ [
+ 'import { createHash } from "node:crypto";',
+ "",
+ "export function describePlan(service: string): string {",
+ " return `deploy ${service}`;",
+ "}",
+ "",
+ "export async function hashPlan(plan: string): Promise<string> {",
+ ' "use step";',
+ ' return createHash("sha256").update(plan).digest("hex");',
+ "}",
+ "",
+ ].join("\n"),
+ ),
+ writeFile(
+ toolPath,
+ [
+ 'import { defineTool } from "eve/tools";',
+ 'import { sleep } from "workflow";',
+ 'import { describePlan, hashPlan } from "../lib/steps";',
+ "",
+ "export default defineTool({",
+ ' description: "Deploy a service.",',
+ ' inputSchema: { type: "object", properties: { service: { type: "string" } } },',
+ " async execute({ service }: { service: string }) {",
+ ' "use workflow";',
+ " const digest = await hashPlan(describePlan(service));",
+ ' await sleep("1s");',
+ " return { digest };",
+ " },",
+ "});",
+ "",
+ ].join("\n"),
+ ),
+ ]);
+
+ const builder = new FixtureWorkflowBundleBuilder(
+ {
+ agentName: "test-agent",
+ appRoot,
+ compiledArtifactsBootstrapPath,
+ outDir,
+ rootDir: resolvePackageRoot(),
+ watch: false,
+ },
+ [flowFilePath],
+ );
+
+ await builder.build();
+
+ 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).not.toContain("vendored");
+
+ const workflowsSource = await readFile(join(outDir, "workflows.mjs"), "utf8");
+ const encodedChunksMatch = workflowsSource.match(
+ /Buffer\.from\((\[[\s\S]*?\])\.join\(""\), "base64"\)\.toString\("utf8"\)/,
+ );
+ 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('"step//./agent/lib/steps//hashPlan"');
+ expect(workflowCode).toContain("deploy ${service}");
+ expect(workflowCode).not.toContain("defineTool");
+ expect(workflowCode).not.toContain("node:crypto");
+ } finally {
+ await rm(tempRoot, { force: true, recursive: true });
+ }
+ });
});
diff --git a/packages/eve/src/internal/workflow-bundle/builder.ts b/packages/eve/src/internal/workflow-bundle/builder.ts
index f04951034..1ddf7cd7c 100644
--- a/packages/eve/src/internal/workflow-bundle/builder.ts
+++ b/packages/eve/src/internal/workflow-bundle/builder.ts
@@ -10,18 +10,27 @@ import {
writeEveVersionedCacheMetadata,
} from "#internal/application/cache-metadata.js";
import { runQueuedWorkflowBuild } from "#internal/workflow-bundle/build-queue.js";
+import { createAuthoredPackageTsConfigPathsPlugin } from "#internal/authored-package-tsconfig-paths.js";
+import { createAuthoredRelativeExtensionResolverPlugin } from "#internal/authored-relative-extension-resolver.js";
+import {
+ type AuthoredWorkflowModules,
+ discoverAuthoredWorkflowModules,
+} from "#internal/workflow-bundle/authored-workflow-modules.js";
import {
bundleFinalWorkflowOutput,
collectWorkflowInputFiles,
+ composeWorkflowDriverCode,
convertClassesManifest,
convertStepsManifest,
convertWorkflowsManifest,
createEvePackageImportsPlugin,
createWorkflowImport,
createWorkflowNodeBuiltinGuardPlugin,
+ createWorkflowDriverAliasPlugin,
createWorkflowPseudoPackagePlugin,
createWorkflowTransformPlugin,
createWorkflowVirtualEntryPlugin,
+ WORKFLOW_SOURCE_EXTENSIONS,
WORKFLOW_VIRTUAL_ENTRY_ID,
type WorkflowBundleBuilderConfig,
type WorkflowBundleBuilderOptions,
@@ -30,13 +39,16 @@ import {
type WorkflowBundleDiscoveredEntries,
} from "#internal/workflow-bundle/builder-support.js";
import { buildSingleRolldownChunk } from "#internal/bundler/nitro-rolldown.js";
-import { writeNitroStepEntrypoint } from "#internal/workflow-bundle/nitro-step-entry.js";
+import {
+ type NitroStepEntrypointDiscoveredEntries,
+ writeNitroStepEntrypoint,
+} from "#internal/workflow-bundle/nitro-step-entry.js";
import {
WORKFLOW_BUILDER_DEFERRED_PACKAGES,
WORKFLOW_STEP_EXTERNAL_PACKAGES,
} from "#internal/workflow-bundle/vercel-workflow-output.js";
import {
- detectWorkflowPatterns,
+ findWorkflowPatterns,
type WorkflowManifest,
} from "#internal/workflow-bundle/workflow-builders.js";
import { deriveEveWorkflowQueueNamespace } from "#internal/workflow/queue-namespace.js";
@@ -46,7 +58,6 @@ export class WorkflowBundleBuilder {
readonly #outDir: string;
readonly #queueNamespace: string;
protected readonly config: WorkflowBundleBuilderConfig;
- readonly #discoveredEntries = new WeakMap<readonly string[], WorkflowBundleDiscoveredEntries>();
constructor(options: WorkflowBundleBuilderOptions) {
const dirs = [resolvePackageSourceDirectoryPath("src/execution")];
@@ -80,9 +91,9 @@ export class WorkflowBundleBuilder {
}): Promise<void> {
await prepareEveVersionedCacheDirectory(this.#outDir);
- const inputFiles = await this.#getBuildInputFiles();
+ const frameworkInputFiles = await this.#getBuildInputFiles();
- if (inputFiles.length === 0) {
+ if (frameworkInputFiles.length === 0) {
throw new Error(
`Expected the execution workflow source file under "${resolvePackageSourceDirectoryPath("src/execution")}".`,
);
@@ -91,31 +102,27 @@ export class WorkflowBundleBuilder {
const tsconfigPath = await this.findTsConfigPath();
await mkdir(this.#outDir, { recursive: true });
- const discoveredEntries = await this.discoverEntries(inputFiles, this.#outDir, tsconfigPath);
+ const frameworkEntries = await this.discoverEntries(frameworkInputFiles);
+ const appEntries = await discoverAuthoredWorkflowModules(this.transformProjectRoot);
+ const stepEntries = mergeStepEntries(frameworkEntries, appEntries);
const stepsOutfile = join(this.#outDir, "steps.mjs");
const workflowsOutfile = join(this.#outDir, "workflows.mjs");
const nitroStepOutfile = options.nitroStepOutfile;
const nitroWorkflowOutfile = options.nitroWorkflowOutfile;
- const stepsManifest = await writeNitroStepEntrypoint({
- builtinsPath: resolveWorkflowModulePath("workflow/internal/builtins"),
- discoveredEntries,
- outfile: stepsOutfile,
- preferAbsoluteFileImports: true,
- projectRoot: this.config.projectRoot ?? this.config.workingDir,
- sideEffectFiles: [this.#compiledArtifactsBootstrapPath],
- workingDir: this.config.workingDir,
- });
- if (nitroStepOutfile !== undefined && nitroStepOutfile !== stepsOutfile) {
- await writeNitroStepEntrypoint({
+ const writeStepEntry = (outfile: string) =>
+ writeNitroStepEntrypoint({
builtinsPath: resolveWorkflowModulePath("workflow/internal/builtins"),
- discoveredEntries,
- outfile: nitroStepOutfile,
+ discoveredEntries: stepEntries,
+ outfile,
preferAbsoluteFileImports: true,
projectRoot: this.config.projectRoot ?? this.config.workingDir,
sideEffectFiles: [this.#compiledArtifactsBootstrapPath],
workingDir: this.config.workingDir,
});
+ const stepsManifest = await writeStepEntry(stepsOutfile);
+ if (nitroStepOutfile !== undefined && nitroStepOutfile !== stepsOutfile) {
+ await writeStepEntry(nitroStepOutfile);
}
const { manifest: workflowsManifest } = await this.createWorkflowsBundle({
additionalOutputs:
@@ -127,9 +134,10 @@ export class WorkflowBundleBuilder {
stepRegistrationsPath: nitroStepOutfile ?? stepsOutfile,
},
],
- discoveredEntries,
+ appWorkflowFiles: appEntries.workflowModules,
+ frameworkSerdeFiles: frameworkEntries.discoveredSerdeFiles,
+ frameworkWorkflowFiles: frameworkEntries.discoveredWorkflows,
outfile: workflowsOutfile,
- inputFiles,
stepRegistrationsPath: stepsOutfile,
tsconfigPath,
});
@@ -194,15 +202,7 @@ export class WorkflowBundleBuilder {
protected async discoverEntries(
inputs: readonly string[],
- _outdir: string,
- _tsconfigPath?: string,
): Promise<WorkflowBundleDiscoveredEntries> {
- const cached = this.#discoveredEntries.get(inputs);
-
- if (cached !== undefined) {
- return cached;
- }
-
const discovered: WorkflowBundleDiscoveredEntries = {
discoveredSerdeFiles: [],
discoveredSteps: [],
@@ -211,84 +211,46 @@ export class WorkflowBundleBuilder {
for (const filePath of inputs) {
const source = await readFile(filePath, "utf8");
- const patterns = detectWorkflowPatterns(source);
-
- if (patterns.hasUseStep) {
- discovered.discoveredSteps.push(filePath);
- }
-
- if (patterns.hasUseWorkflow) {
- discovered.discoveredWorkflows.push(filePath);
- }
+ const patterns = await findWorkflowPatterns(filePath, source);
- if (patterns.hasSerde) {
- discovered.discoveredSerdeFiles.push(filePath);
- }
+ if (patterns.hasUseStep) discovered.discoveredSteps.push(filePath);
+ if (patterns.hasUseWorkflow) discovered.discoveredWorkflows.push(filePath);
+ if (patterns.hasSerde) discovered.discoveredSerdeFiles.push(filePath);
}
- this.#discoveredEntries.set(inputs, discovered);
return discovered;
}
protected async createWorkflowsBundle({
additionalOutputs = [],
- discoveredEntries,
- inputFiles,
+ appWorkflowFiles,
+ frameworkSerdeFiles,
+ frameworkWorkflowFiles,
outfile,
stepRegistrationsPath,
tsconfigPath,
}: WorkflowBundleCreateWorkflowsBundleOptions): Promise<WorkflowBundleCreateWorkflowsBundleResult> {
- const discovered =
- discoveredEntries ?? (await this.discoverEntries(inputFiles, dirname(outfile), tsconfigPath));
- const workflowFiles = [...discovered.discoveredWorkflows].sort();
- const workflowFileSet = new Set(workflowFiles);
- const serdeOnlyFiles = [...discovered.discoveredSerdeFiles]
- .sort()
- .filter((filePath) => !workflowFileSet.has(filePath));
- const workflowManifest: WorkflowManifest = {};
- const virtualEntrySource = [
- ...workflowFiles.map((filePath) => createWorkflowImport(filePath, this.config.workingDir)),
- ...serdeOnlyFiles.map((filePath) => createWorkflowImport(filePath, this.config.workingDir)),
- ].join("\n");
- const interimBundle = await buildSingleRolldownChunk(
- `intermediate workflow bundle for "${outfile}"`,
- {
- cwd: this.config.workingDir,
- input: WORKFLOW_VIRTUAL_ENTRY_ID,
- platform: "neutral",
- plugins: [
- createWorkflowVirtualEntryPlugin(virtualEntrySource),
- createWorkflowPseudoPackagePlugin(),
- createEvePackageImportsPlugin(this.config.workingDir, { workflowCondition: true }),
- createWorkflowTransformPlugin({
- manifest: workflowManifest,
- projectRoot: this.transformProjectRoot,
- sideEffectFiles: [...workflowFiles, ...serdeOnlyFiles],
- workingDir: this.config.workingDir,
- }),
- // Must run after the transform so `"use step"` bodies are already
- // stubbed and their node:* imports stripped from this graph.
- createWorkflowNodeBuiltinGuardPlugin(),
- ],
- resolve: {
- conditionNames: ["eve-source", "workflow"],
- extensions: [".ts", ".tsx", ".mts", ".cts", ".js", ".jsx", ".mjs", ".cjs"],
- mainFields: ["module", "main"],
- },
- tsconfig: tsconfigPath ?? false,
- output: {
- banner: "globalThis.__private_workflows = new Map();",
- comments: false,
- format: "cjs",
- sourcemap: "inline",
- },
- },
- );
+ const manifest: WorkflowManifest = {};
+ const frameworkChunk = await this.#buildDriverChunk({
+ label: "framework",
+ manifest,
+ serdeFiles: frameworkSerdeFiles,
+ tsconfigPath,
+ workflowFiles: frameworkWorkflowFiles,
+ });
+ const appChunk = await this.#buildDriverChunk({
+ label: "app",
+ manifest,
+ serdeFiles: [],
+ tsconfigPath,
+ workflowFiles: appWorkflowFiles,
+ });
+ const workflowCode = composeWorkflowDriverCode([frameworkChunk, appChunk]);
await Promise.all(
[{ outfile, stepRegistrationsPath }, ...additionalOutputs].map((output) =>
bundleFinalWorkflowOutput({
- code: interimBundle.code,
+ code: workflowCode,
outfile: output.outfile,
queueNamespace: this.#queueNamespace,
stepRegistrationsPath: output.stepRegistrationsPath,
@@ -296,7 +258,70 @@ export class WorkflowBundleBuilder {
),
);
- return { manifest: workflowManifest };
+ return { manifest };
+ }
+
+ /**
+ * One driver layer, without registry banner or entrypoint wrapper so
+ * `composeWorkflowDriverCode` can concatenate layers. `""` when the layer has
+ * nothing to bundle, the common case for an app with no workflow tools.
+ */
+ async #buildDriverChunk(options: {
+ label: string;
+ manifest: WorkflowManifest;
+ serdeFiles: readonly string[];
+ tsconfigPath?: string;
+ workflowFiles: readonly string[];
+ }): Promise<string> {
+ const workflowFiles = [...options.workflowFiles].sort();
+ const workflowFileSet = new Set(workflowFiles);
+ const serdeOnlyFiles = [...options.serdeFiles]
+ .sort()
+ .filter((filePath) => !workflowFileSet.has(filePath));
+ if (workflowFiles.length === 0 && serdeOnlyFiles.length === 0) return "";
+
+ const virtualEntrySource = [
+ ...workflowFiles.map((filePath) => createWorkflowImport(filePath, this.config.workingDir)),
+ ...serdeOnlyFiles.map((filePath) => createWorkflowImport(filePath, this.config.workingDir)),
+ ].join("\n");
+ const interimBundle = await buildSingleRolldownChunk(`${options.label} workflow driver chunk`, {
+ cwd: this.config.workingDir,
+ input: WORKFLOW_VIRTUAL_ENTRY_ID,
+ platform: "neutral",
+ plugins: [
+ createWorkflowVirtualEntryPlugin(virtualEntrySource),
+ createWorkflowPseudoPackagePlugin(),
+ createWorkflowDriverAliasPlugin(this.config.workingDir),
+ createAuthoredRelativeExtensionResolverPlugin({
+ extensions: WORKFLOW_SOURCE_EXTENSIONS,
+ }),
+ createAuthoredPackageTsConfigPathsPlugin({
+ appPackageRoot: this.transformProjectRoot,
+ extensions: WORKFLOW_SOURCE_EXTENSIONS,
+ }),
+ createEvePackageImportsPlugin(this.config.workingDir, { workflowCondition: true }),
+ createWorkflowTransformPlugin({
+ manifest: options.manifest,
+ projectRoot: this.transformProjectRoot,
+ sideEffectFiles: [...workflowFiles, ...serdeOnlyFiles],
+ workingDir: this.config.workingDir,
+ }),
+ // After the transform, so stubbed step bodies' node:* imports are already gone.
+ createWorkflowNodeBuiltinGuardPlugin(),
+ ],
+ resolve: {
+ conditionNames: ["eve-source", "workflow"],
+ extensions: WORKFLOW_SOURCE_EXTENSIONS,
+ mainFields: ["module", "main"],
+ },
+ tsconfig: options.tsconfigPath ?? false,
+ output: {
+ comments: false,
+ format: "cjs",
+ sourcemap: "inline",
+ },
+ });
+ return interimBundle.code;
}
protected async createManifest({
@@ -324,3 +349,14 @@ export class WorkflowBundleBuilder {
return await this.getInputFiles();
}
}
+
+/** App step modules register with the framework's server steps; driver inputs stay per-layer. */
+function mergeStepEntries(
+ framework: WorkflowBundleDiscoveredEntries,
+ app: AuthoredWorkflowModules,
+): NitroStepEntrypointDiscoveredEntries {
+ return {
+ discoveredSerdeFiles: framework.discoveredSerdeFiles,
+ discoveredSteps: [...new Set([...framework.discoveredSteps, ...app.directiveModules])],
+ };
+}
diff --git a/packages/eve/src/internal/workflow-bundle/dynamic-capability-transform-plugin.ts b/packages/eve/src/internal/workflow-bundle/dynamic-capability-transform-plugin.ts
index 085439f48..eaefbedef 100644
--- a/packages/eve/src/internal/workflow-bundle/dynamic-capability-transform-plugin.ts
+++ b/packages/eve/src/internal/workflow-bundle/dynamic-capability-transform-plugin.ts
@@ -5,6 +5,8 @@ export function createDynamicCapabilityTransformPlugin(
options: {
readonly dynamicRemoteAgents?: boolean;
readonly dynamicTools?: boolean;
+ /** Names of a module's `"use workflow"` functions, when a directive transform ran before this one. */
+ readonly workflowFunctions?: (id: string) => ReadonlySet<string> | undefined;
} = {},
) {
return {
@@ -20,7 +22,11 @@ export function createDynamicCapabilityTransformPlugin(
let transformed = code;
let changed = false;
if (transformDynamicTools) {
- const result = await transformDynamicToolExecute(id, transformed);
+ const result = await transformDynamicToolExecute(
+ id,
+ transformed,
+ options.workflowFunctions?.(id),
+ );
if (result !== null) {
transformed = result.code;
changed = true;
diff --git a/packages/eve/src/internal/workflow-bundle/dynamic-tool-ast-references.ts b/packages/eve/src/internal/workflow-bundle/dynamic-tool-ast-references.ts
index bb425414c..c6c31f50f 100644
--- a/packages/eve/src/internal/workflow-bundle/dynamic-tool-ast-references.ts
+++ b/packages/eve/src/internal/workflow-bundle/dynamic-tool-ast-references.ts
@@ -11,6 +11,7 @@ export type DynamicToolAstNode = {
computed?: boolean;
declaration?: DynamicToolAstNode | null;
declarations?: DynamicToolAstNode[];
+ directive?: string;
end?: number;
expression?: DynamicToolAstNode | null;
generator?: boolean;
@@ -23,8 +24,10 @@ export type DynamicToolAstNode = {
local?: { name?: string } | null;
method?: boolean;
name?: string;
+ object?: DynamicToolAstNode | null;
params?: DynamicToolAstNode[];
properties?: DynamicToolAstNode[];
+ property?: DynamicToolAstNode | null;
right?: DynamicToolAstNode | null;
source?: { value?: unknown } | null;
specifiers?: DynamicToolAstNode[];
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 ad4f19941..f7d149b92 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
@@ -1971,6 +1971,45 @@ 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";
+
+async function execute(input) {
+ throw new Error("stub");
+}
+execute.workflowId = "workflow//./agent/tools/deploy//execute";
+
+async function deploy(input) {
+ throw new Error("stub");
+}
+deploy.workflowId = "workflow//./agent/tools/deploy//deploy";
+
+export default defineTool({
+ description: "Inline body",
+ inputSchema: {},
+ execute,
+ async toModelOutput(output) { return String(output); },
+});
+
+export const referenced = defineTool({
+ 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(");
+ });
});
// ===========================================================================
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 05933330e..a23470940 100644
--- a/packages/eve/src/internal/workflow-bundle/dynamic-tool-transform.ts
+++ b/packages/eve/src/internal/workflow-bundle/dynamic-tool-transform.ts
@@ -43,6 +43,7 @@ interface ScopeEntry {
export async function transformDynamicToolExecute(
filename: string,
source: string,
+ workflowFunctions: ReadonlySet<string> = NO_WORKFLOW_FUNCTIONS,
): Promise<{ code: string } | null> {
if (!source.includes("defineTool")) return null;
@@ -51,10 +52,22 @@ export async function transformDynamicToolExecute(
if (defineToolAliases.size === 0) return null;
const callbacks: CallbackInfo[] = [];
- walkForCallbacks(source, ast, callbacks, [], defineToolAliases);
+ walkForCallbacks(source, ast, callbacks, [], { defineToolAliases, workflowFunctions });
return callbacks.length === 0 ? null : applyTransform(source, callbacks);
}
+const NO_WORKFLOW_FUNCTIONS: ReadonlySet<string> = new Set();
+
+interface WalkContext {
+ readonly defineToolAliases: ReadonlySet<string>;
+ /**
+ * Top-level `"use workflow"` functions the directive transform already
+ * hoisted and stubbed. A tool whose `execute` is one never runs as a
+ * callback, so it keeps its identity and is not stamped.
+ */
+ readonly workflowFunctions: ReadonlySet<string>;
+}
+
// Keep the old export name for backward compatibility with the plugin.
export { transformDynamicToolExecute as transformDynamicToolAwait };
@@ -85,7 +98,7 @@ function walkForCallbacks(
node: AstNode | null | undefined,
results: CallbackInfo[],
nestedScopes: readonly ScopeEntry[],
- defineToolAliases: ReadonlySet<string>,
+ context: WalkContext,
): void {
if (!node) return;
@@ -99,7 +112,7 @@ function walkForCallbacks(
vars: collectScopeVarDeclarations(bodyNode),
},
];
- walkForCallbacks(source, bodyNode, results, extended, defineToolAliases);
+ walkForCallbacks(source, bodyNode, results, extended, context);
return;
}
@@ -107,11 +120,11 @@ function walkForCallbacks(
node.type === "CallExpression" &&
node.callee?.type === "Identifier" &&
node.callee.name !== undefined &&
- defineToolAliases.has(node.callee.name) &&
+ context.defineToolAliases.has(node.callee.name) &&
node.arguments?.length === 1 &&
node.arguments[0]?.type === "ObjectExpression"
) {
- collectToolCallbacks(source, node.arguments[0], results, nestedScopes);
+ collectToolCallbacks(source, node.arguments[0], results, nestedScopes, context);
return;
}
@@ -119,29 +132,35 @@ function walkForCallbacks(
if (Array.isArray(value)) {
for (const child of value) {
if (isAstNode(child)) {
- walkForCallbacks(source, child, results, nestedScopes, defineToolAliases);
+ walkForCallbacks(source, child, results, nestedScopes, context);
}
}
} else if (isAstNode(value)) {
- walkForCallbacks(source, value, results, nestedScopes, defineToolAliases);
+ walkForCallbacks(source, value, results, nestedScopes, context);
}
}
}
+function isWorkflowExecute(property: AstNode | undefined, context: WalkContext): boolean {
+ const value = property?.value as AstNode | undefined;
+ return (
+ value?.type === "Identifier" &&
+ value.name !== undefined &&
+ context.workflowFunctions.has(value.name)
+ );
+}
+
function collectToolCallbacks(
source: string,
tool: AstNode,
results: CallbackInfo[],
nestedScopes: readonly ScopeEntry[],
+ context: WalkContext,
): void {
- collectCallbackProperty(
- source,
- findProperty(tool, "execute"),
- "execute",
- "execute",
- results,
- nestedScopes,
- );
+ const execute = findProperty(tool, "execute");
+ if (!isWorkflowExecute(execute, context)) {
+ collectCallbackProperty(source, execute, "execute", "execute", results, nestedScopes);
+ }
collectCallbackProperty(
source,
findProperty(tool, "toModelOutput"),
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 20624bb35..06834035f 100644
--- a/packages/eve/src/internal/workflow-bundle/workflow-builders.test.ts
+++ b/packages/eve/src/internal/workflow-bundle/workflow-builders.test.ts
@@ -207,3 +207,172 @@ describe("applyWorkflowTransform", () => {
);
});
});
+
+describe("applyWorkflowTransform for authored application modules", () => {
+ const appRoot = "/app";
+ 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 { sleep } from "workflow";',
+ 'import { z } from "zod";',
+ "",
+ 'const APPROVE = [{ id: "approve", label: "Deploy" }];',
+ "",
+ "export default defineTool({",
+ ' description: "Deploy",',
+ " inputSchema: z.object({ service: z.string() }),",
+ " async execute({ service }: { service: string }, ctx: ToolContext) {",
+ ' "use workflow";',
+ " const plan = await planDeploy(service);",
+ " const answer = await (await ask(ctx, { prompt: plan, options: APPROVE }));",
+ ' await sleep("1s");',
+ ' return { deployed: answer.optionId === "approve" };',
+ " },",
+ "});",
+ "",
+ "async function planDeploy(service: string): Promise<string> {",
+ ' "use step";',
+ ' return await readFile(`/plans/${service}`, "utf8");',
+ "}",
+ "",
+ ].join("\n");
+
+ it("mints application-relative ids and keeps the module body in workflow mode", async () => {
+ const transformed = await applyWorkflowTransform(
+ "agent/tools/deploy.ts",
+ toolSource,
+ "workflow",
+ toolPath,
+ appRoot,
+ );
+
+ expect(transformed.workflowManifest).toEqual({
+ steps: {
+ "agent/tools/deploy.ts": {
+ planDeploy: { stepId: "step//./agent/tools/deploy//planDeploy" },
+ },
+ },
+ workflows: {
+ "agent/tools/deploy.ts": {
+ execute: { workflowId: "workflow//./agent/tools/deploy//execute" },
+ },
+ },
+ });
+ expect(transformed.code).toContain(
+ 'var planDeploy = globalThis[Symbol.for("WORKFLOW_USE_STEP")]("step//./agent/tools/deploy//planDeploy");',
+ );
+ expect(transformed.code).toContain(
+ 'globalThis.__private_workflows.set("workflow//./agent/tools/deploy//execute", execute);',
+ );
+ expect(transformed.code).toContain("async function execute({ service }");
+ 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("zod");
+ expect(transformed.code).not.toContain("node:fs/promises");
+ expect(transformed.code).not.toContain('"use workflow"');
+ });
+
+ it("registers steps and stubs the workflow body in step mode", async () => {
+ const transformed = await applyWorkflowTransform(
+ "agent/tools/deploy.ts",
+ toolSource,
+ "step",
+ toolPath,
+ appRoot,
+ );
+
+ expect(transformed.code).toContain(
+ 'registerStepFunction("step//./agent/tools/deploy//planDeploy", planDeploy);',
+ );
+ expect(transformed.code).toContain(
+ 'execute.workflowId = "workflow//./agent/tools/deploy//execute";',
+ );
+ expect(transformed.code).toContain(
+ "You attempted to execute workflow execute function directly",
+ );
+ expect(transformed.code).toContain("export default defineTool({");
+ expect(transformed.code).toContain(" execute,\n");
+ expect(transformed.code).toContain('import { z } from "zod";');
+ });
+
+ it("stamps ids without registering in client mode", async () => {
+ const transformed = await applyWorkflowTransform(
+ "agent/tools/deploy.ts",
+ toolSource,
+ "client",
+ toolPath,
+ appRoot,
+ );
+
+ expect(transformed.code).toContain(
+ 'planDeploy.stepId = "step//./agent/tools/deploy//planDeploy";',
+ );
+ expect(transformed.code).not.toContain("registerStepFunction");
+ expect(transformed.code).toContain(
+ 'execute.workflowId = "workflow//./agent/tools/deploy//execute";',
+ );
+ });
+
+ it("leaves authored modules without directives untouched", async () => {
+ const source = 'export const helper = () => "use step";\n';
+ const transformed = await applyWorkflowTransform(
+ "agent/lib/helper.ts",
+ source,
+ "workflow",
+ "/app/agent/lib/helper.ts",
+ appRoot,
+ );
+
+ expect(transformed).toEqual({ code: source, workflowManifest: {} });
+ });
+
+ it("keeps non-step exports of an authored step module in workflow mode", async () => {
+ const transformed = await applyWorkflowTransform(
+ "agent/lib/steps.ts",
+ [
+ 'import { createHash } from "node:crypto";',
+ "",
+ "export function formatPlan(plan: string): string {",
+ " return `plan: ${plan}`;",
+ "}",
+ "",
+ "export async function hashPlan(plan: string): Promise<string> {",
+ ' "use step";',
+ ' return createHash("sha256").update(plan).digest("hex");',
+ "}",
+ "",
+ ].join("\n"),
+ "workflow",
+ "/app/agent/lib/steps.ts",
+ appRoot,
+ );
+
+ expect(transformed.code).toContain("export function formatPlan(plan: string): string {");
+ expect(transformed.code).toContain(
+ 'export var hashPlan = globalThis[Symbol.for("WORKFLOW_USE_STEP")]("step//./agent/lib/steps//hashPlan");',
+ );
+ expect(transformed.code).not.toContain("node:crypto");
+ });
+
+ it("treats eve package sources as framework modules even under the project root", async () => {
+ const eveRoot = resolvePackageRoot();
+ const filename = "src/execution/turn-workflow.ts";
+ const transformed = await applyWorkflowTransform(
+ filename,
+ ["export async function turnWorkflow(): Promise<void> {", ' "use workflow";', "}", ""].join(
+ "\n",
+ ),
+ "workflow",
+ resolvePackageSourceFilePath(filename),
+ eveRoot,
+ );
+
+ expect(transformed.workflowManifest.workflows?.[filename]?.turnWorkflow?.workflowId).toBe(
+ "workflow//eve//turnWorkflow",
+ );
+ });
+});
diff --git a/packages/eve/src/internal/workflow-bundle/workflow-builders.ts b/packages/eve/src/internal/workflow-bundle/workflow-builders.ts
index 926ed1221..f3ab4dca3 100644
--- a/packages/eve/src/internal/workflow-bundle/workflow-builders.ts
+++ b/packages/eve/src/internal/workflow-bundle/workflow-builders.ts
@@ -1,10 +1,16 @@
-import { existsSync, readFileSync } from "node:fs";
+import { existsSync, readFileSync, realpathSync } from "node:fs";
import { readFile } from "node:fs/promises";
import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
-import { STABLE_WORKFLOW_NAMES } from "#execution/workflow-runtime.js";
+import { STABLE_WORKFLOW_NAMES } from "#execution/stable-workflow-names.js";
import { EVE_PACKAGE_NAME } from "#internal/package-name.js";
-import { transformWorkflowDirectives } from "./workflow-transformer.js";
+import { prepareAuthoredWorkflowDirectives } from "./authored-workflow-directives.js";
+import {
+ createWorkflowId,
+ findWorkflowDirectiveFunctions,
+ stripJavaScriptExtension,
+ transformWorkflowDirectives,
+} from "./workflow-transformer.js";
export type WorkflowManifest = {
steps?: {
@@ -65,6 +71,27 @@ export async function applyWorkflowTransform(
resolvedProjectRoot,
);
+ if (
+ absolutePath !== undefined &&
+ isAuthoredApplicationModule(absolutePath, resolvedProjectRoot)
+ ) {
+ const prepared =
+ mode === false
+ ? undefined
+ : await prepareAuthoredWorkflowDirectives({ filePath: absolutePath, source });
+ // Ids derive from the app root so the driver bundle (built from eve's
+ // package directory) and the server bundle (built from the app) agree.
+ return transformWorkflowDirectives({
+ authored: true,
+ filename: authoredRelativePath(absolutePath, resolvedProjectRoot),
+ mode: prepared?.hasDirectives === true ? mode : false,
+ moduleSpecifier: authoredModuleIdBase(absolutePath, resolvedProjectRoot),
+ source: prepared?.source ?? source,
+ stableModuleSpecifier: undefined,
+ stableWorkflowNames,
+ });
+ }
+
return transformWorkflowDirectives({
filename,
mode,
@@ -75,19 +102,71 @@ export async function applyWorkflowTransform(
});
}
-export function detectWorkflowPatterns(source: string): {
+export function isAuthoredApplicationModule(absolutePath: string, appRoot: string): boolean {
+ const normalizedRoot = toRealPath(appRoot).replace(/\\/g, "/").replace(/\/$/, "");
+ const normalizedPath = toRealPath(absolutePath).replace(/\\/g, "/");
+ if (!normalizedPath.startsWith(`${normalizedRoot}/`)) return false;
+ if (isInNodeModules(normalizedPath)) return false;
+ return findPackageJson(normalizedPath)?.name !== EVE_PACKAGE_NAME;
+}
+
+function authoredRelativePath(absolutePath: string, appRoot: string): string {
+ return toRelativeImportPath(toRealPath(absolutePath), toRealPath(appRoot)).replace(/^\.\//, "");
+}
+
+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 {
+ try {
+ return realpathSync(path);
+ } catch {
+ return resolve(path);
+ }
+}
+
+// Reads the manifest directly: applications need not declare a `version`,
+// which the package-specifier cache requires.
+export function isAuthoredApplicationRoot(appRoot: string): boolean {
+ const packageJsonPath = join(appRoot, "package.json");
+ if (!existsSync(packageJsonPath)) return false;
+ try {
+ const parsed = JSON.parse(readFileSync(packageJsonPath, "utf8")) as { name?: unknown };
+ return parsed.name !== EVE_PACKAGE_NAME;
+ } catch {
+ return false;
+ }
+}
+
+export async function findWorkflowPatterns(
+ filename: string,
+ source: string,
+): Promise<{
hasSerde: boolean;
hasUseStep: boolean;
hasUseWorkflow: boolean;
-} {
+}> {
+ const directives = await findWorkflowDirectiveFunctions(filename, source);
return {
hasSerde:
source.includes("workflow.serde") ||
source.includes("@serde") ||
source.includes("workflowSerde") ||
source.includes("__workflow_serde"),
- hasUseStep: /["']use step["']/.test(source),
- hasUseWorkflow: /["']use workflow["']/.test(source),
+ hasUseStep: directives.some((fn) => fn.directive === "use step"),
+ hasUseWorkflow: directives.some((fn) => fn.directive === "use workflow"),
};
}
diff --git a/packages/eve/src/internal/workflow-bundle/workflow-core-shim.ts b/packages/eve/src/internal/workflow-bundle/workflow-core-shim.ts
index 7303b5029..9a5a13622 100644
--- a/packages/eve/src/internal/workflow-bundle/workflow-core-shim.ts
+++ b/packages/eve/src/internal/workflow-bundle/workflow-core-shim.ts
@@ -6,9 +6,22 @@ const WORKFLOW_USE_STEP = Symbol.for("WORKFLOW_USE_STEP");
const STREAM_NAME_SYMBOL = Symbol.for("WORKFLOW_STREAM_NAME");
const workflowGlobal = globalThis as typeof globalThis & Record<symbol, unknown>;
-export class RetryableError extends Error {}
+// The SDK matches these by `name` and `fatal` when it serializes an error out of a body.
+export class RetryableError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = "RetryableError";
+ }
+}
+
+export class FatalError extends Error {
+ readonly fatal = true;
-export class FatalError extends Error {}
+ constructor(message: string) {
+ super(message);
+ this.name = "FatalError";
+ }
+}
interface WorkflowHook<T> extends AsyncIterable<T> {
readonly token: string;
diff --git a/packages/eve/src/internal/workflow-bundle/workflow-directive-ast.ts b/packages/eve/src/internal/workflow-bundle/workflow-directive-ast.ts
new file mode 100644
index 000000000..21773880c
--- /dev/null
+++ b/packages/eve/src/internal/workflow-bundle/workflow-directive-ast.ts
@@ -0,0 +1,21 @@
+export type WorkflowDirective = "use step" | "use workflow";
+
+export interface DirectiveStatementNode {
+ readonly directive?: unknown;
+ readonly expression?: unknown;
+ readonly type?: unknown;
+}
+
+// Some parsers record a directive prologue on the statement; others leave a
+// plain string-literal expression.
+export function readWorkflowDirective(
+ statement: DirectiveStatementNode | undefined,
+): WorkflowDirective | undefined {
+ const expression = statement?.expression as { type?: unknown; value?: unknown } | undefined;
+ const value =
+ statement?.directive ??
+ (statement?.type === "ExpressionStatement" && expression?.type === "Literal"
+ ? expression.value
+ : undefined);
+ return value === "use step" || value === "use workflow" ? value : undefined;
+}
diff --git a/packages/eve/src/internal/workflow-bundle/workflow-transformer.ts b/packages/eve/src/internal/workflow-bundle/workflow-transformer.ts
index 7f9558517..89069b262 100644
--- a/packages/eve/src/internal/workflow-bundle/workflow-transformer.ts
+++ b/packages/eve/src/internal/workflow-bundle/workflow-transformer.ts
@@ -1,3 +1,8 @@
+import { WORKFLOW_REGISTRY_GLOBAL } from "#execution/workflow-registry.js";
+import {
+ readWorkflowDirective,
+ type WorkflowDirective,
+} from "#internal/workflow-bundle/workflow-directive-ast.js";
import { parseWithNitroRolldownAst } from "#internal/bundler/nitro-rolldown.js";
import type { WorkflowManifest } from "./workflow-builders.js";
@@ -19,7 +24,7 @@ const BUILTIN_STEP_NAMES = new Set([
type WorkflowDirectiveMode = "workflow" | "step" | "client" | false;
type DirectiveFunction = {
- directive: "use workflow" | "use step";
+ directive: WorkflowDirective;
directiveEnd: number;
directiveStart: number;
/**
@@ -52,6 +57,7 @@ type AstNode = {
argument?: AstNode | null;
async?: boolean;
body?: AstNode[] | { body?: AstNode[] };
+ callee?: AstNode | null;
declaration?: AstNode | null;
declarations?: AstNode[];
directive?: string;
@@ -72,7 +78,22 @@ type AstNode = {
value?: unknown;
};
+/** Reads the syntax tree, so a directive quoted in a string or comment never counts. */
+export async function findWorkflowDirectiveFunctions(
+ filename: string,
+ source: string,
+): Promise<readonly { readonly directive: WorkflowDirective; readonly name: string }[]> {
+ const ast = await parseWorkflowSource(filename, source);
+ return findDirectiveFunctions(ast).map((fn) => ({ directive: fn.directive, name: fn.name }));
+}
+
export async function transformWorkflowDirectives(input: {
+ /**
+ * Authored modules keep their body in workflow mode (steps become proxies in
+ * place) and lose an eve-definer default export, so the driver never
+ * evaluates the tool definition or its schema dependencies.
+ */
+ authored?: boolean;
filename: string;
mode: WorkflowDirectiveMode;
moduleSpecifier: string | undefined;
@@ -87,7 +108,7 @@ export async function transformWorkflowDirectives(input: {
/**
* Workflow function names whose bundled id should be emitted without
* the package version stamp. See `STABLE_WORKFLOW_NAMES` in
- * `workflow-runtime.ts` for the canonical set eve itself uses.
+ * `stable-workflow-names.ts` for the canonical set eve itself uses.
*/
stableWorkflowNames?: ReadonlySet<string>;
}): Promise<{
@@ -145,7 +166,7 @@ export async function transformWorkflowDirectives(input: {
}
const isStable = input.stableWorkflowNames?.has(fn.name) === true;
- const workflowId = `workflow//${isStable ? stableIdBase : defaultIdBase}//${fn.name}`;
+ const workflowId = createWorkflowId(isStable ? stableIdBase : defaultIdBase, fn.name);
manifest.workflows ??= {};
const workflowsForFile = (manifest.workflows[input.filename] ??= {});
workflowsForFile[fn.name] = { workflowId };
@@ -154,7 +175,7 @@ export async function transformWorkflowDirectives(input: {
replacements.push({ end: fn.directiveEnd, start: fn.directiveStart, text: "" });
suffixes.push(`${fn.name}.workflowId = ${JSON.stringify(workflowId)};`);
suffixes.push(
- `globalThis.__private_workflows.set(${JSON.stringify(workflowId)}, ${fn.name});`,
+ `globalThis.${WORKFLOW_REGISTRY_GLOBAL}.set(${JSON.stringify(workflowId)}, ${fn.name});`,
);
} else {
replacements.push({
@@ -171,13 +192,17 @@ export async function transformWorkflowDirectives(input: {
const manifestComment = `/**__internal_workflows${JSON.stringify(manifest)}*/;`;
const hasWorkflowDirective = functions.some((fn) => fn.directive === "use workflow");
- if (input.mode === "workflow" && !hasWorkflowDirective) {
+ if (input.mode === "workflow" && !hasWorkflowDirective && input.authored !== true) {
return {
code: `${manifestComment}\n${createWorkflowStepProxySource(input.source, ast, functions, defaultIdBase)}`,
workflowManifest: manifest,
};
}
+ if (input.mode === "workflow" && input.authored === true) {
+ replacements.push(...removeEveDefinerDefaultExport(ast));
+ }
+
const replacedSource = applySourceReplacements(input.source, replacements);
const transformedSource =
input.mode === "workflow"
@@ -350,21 +375,11 @@ function readBlockStatements(block: AstNode["body"]): AstNode[] | undefined {
function readFunctionDirective(
statement: AstNode | undefined,
-): { end: number; start: number; value: "use workflow" | "use step" } | null {
- const value =
- statement?.directive ??
- (statement?.type === "ExpressionStatement" && statement.expression?.type === "Literal"
- ? statement.expression.value
- : undefined);
-
- if (
- (value !== "use workflow" && value !== "use step") ||
- statement?.start === undefined ||
- statement.end === undefined
- ) {
+): { end: number; start: number; value: WorkflowDirective } | null {
+ const value = readWorkflowDirective(statement);
+ if (value === undefined || statement?.start === undefined || statement.end === undefined) {
return null;
}
-
return { end: statement.end, start: statement.start, value };
}
@@ -384,6 +399,37 @@ function applySourceReplacements(
return result + source.slice(cursor);
}
+// The driver needs only the workflow and step functions; evaluating the
+// definition would pull the definer and the schema library into the bundle.
+function removeEveDefinerDefaultExport(
+ ast: AstProgram,
+): { end: number; start: number; text: string }[] {
+ const eveBindings = new Set<string>();
+
+ for (const node of ast.body ?? []) {
+ if (node.type !== "ImportDeclaration" || node.importKind === "type") continue;
+ const source = node.source?.value;
+ if (typeof source !== "string" || !/^eve(?:\/|$)/.test(source)) continue;
+ for (const specifier of node.specifiers ?? []) {
+ if (specifier.importKind === "type") continue;
+ const name = specifier.local?.name;
+ if (name !== undefined) eveBindings.add(name);
+ }
+ }
+
+ const removals: { end: number; start: number; text: string }[] = [];
+ for (const node of ast.body ?? []) {
+ if (node.type !== "ExportDefaultDeclaration" || node.start === undefined) continue;
+ 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;
+ removals.push({ end: node.end, start: node.start, text: "" });
+ }
+
+ return removals;
+}
+
async function stripUnusedValueImports(filename: string, source: string): Promise<string> {
const ast = await parseWorkflowSource(filename, source);
const referencedIdentifiers = collectReferencedIdentifiers(ast);
@@ -594,10 +640,14 @@ function extendRemovalEnd(source: string, end: number): number {
return cursor;
}
-function stripJavaScriptExtension(path: string): string {
+export function stripJavaScriptExtension(path: string): string {
return path.replace(/\.(?:[cm]?[jt]sx?)$/, "");
}
+export function createWorkflowId(idBase: string, functionName: string): string {
+ return `workflow//${idBase}//${functionName}`;
+}
+
function createStepId(idBase: string, functionName: string): string {
if (BUILTIN_STEP_NAMES.has(functionName)) {
return functionName;
diff --git a/packages/eve/src/public/workflow-modules.d.ts b/packages/eve/src/public/workflow-modules.d.ts
new file mode 100644
index 000000000..82d4d4043
--- /dev/null
+++ b/packages/eve/src/public/workflow-modules.d.ts
@@ -0,0 +1,11 @@
+/**
+ * Types for the `workflow` specifiers eve resolves to its vendored SDK. Ambient,
+ * so an installed `workflow` package takes precedence.
+ */
+declare module "workflow" {
+ export * from "#internal/workflow/index.js";
+}
+
+declare module "workflow/api" {
+ export * from "#internal/workflow/runtime.js";
+}
diff --git a/packages/eve/src/public/workflow/index.ts b/packages/eve/src/public/workflow/index.ts
new file mode 100644
index 000000000..191b47121
--- /dev/null
+++ b/packages/eve/src/public/workflow/index.ts
@@ -0,0 +1,3 @@
+/** `eve/workflow`: what eve adds inside a workflow tool body. The SDK's own constructs come from `workflow`. */
+export { ask } from "#execution/tool-run/messages.js";
+export type { ToolInputRequest, ToolInputResponse } from "#tools/definition.js";
diff --git a/packages/eve/src/runtime/actions/keys.ts b/packages/eve/src/runtime/actions/keys.ts
index 01410e6e9..2e60792f6 100644
--- a/packages/eve/src/runtime/actions/keys.ts
+++ b/packages/eve/src/runtime/actions/keys.ts
@@ -28,6 +28,7 @@ export function getPendingDispatchActionKey(action: PendingDispatchAction): stri
return `subagent-call:${action.target.subagentName}:${action.callId}`;
case "task-cancel":
case "task-update":
+ case "workflow-tool-call":
return `tool-call:${action.toolName}:${action.callId}`;
default: {
const _exhaustive: never = action.target;
diff --git a/packages/eve/src/runtime/tools/registry.ts b/packages/eve/src/runtime/tools/registry.ts
index 2af15f983..5c9ee3edb 100644
--- a/packages/eve/src/runtime/tools/registry.ts
+++ b/packages/eve/src/runtime/tools/registry.ts
@@ -102,6 +102,15 @@ function prepareToolBehavior(
presentation: behavior.presentation,
};
}
+ if (behavior.handling.kind === "workflow-tool") {
+ return {
+ ...behavior,
+ handling: {
+ kind: "dispatch",
+ target: { kind: "workflow-tool-call", workflowId: behavior.handling.workflowId },
+ },
+ };
+ }
if (behavior.handling.kind !== "dispatch") {
return { ...behavior, handling: behavior.handling };
}
diff --git a/packages/eve/src/setup/scaffold/create/project.ts b/packages/eve/src/setup/scaffold/create/project.ts
index db8d2f888..1811071b3 100644
--- a/packages/eve/src/setup/scaffold/create/project.ts
+++ b/packages/eve/src/setup/scaffold/create/project.ts
@@ -269,7 +269,7 @@ eve deploy
"target": "ES2022",
"module": "esnext",
"moduleResolution": "bundler",
- "types": ["node"],
+ "types": ["node", "eve/workflow-modules"],
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
diff --git a/packages/eve/src/setup/scaffold/index.integration.test.ts b/packages/eve/src/setup/scaffold/index.integration.test.ts
index 9ec827f9d..148cbbe2e 100644
--- a/packages/eve/src/setup/scaffold/index.integration.test.ts
+++ b/packages/eve/src/setup/scaffold/index.integration.test.ts
@@ -1071,7 +1071,7 @@ describe("scaffoldBaseProject", () => {
compilerOptions: { types?: string[] };
include?: string[];
};
- expect(tsconfig.compilerOptions.types).toEqual(["node"]);
+ expect(tsconfig.compilerOptions.types).toEqual(["node", "eve/workflow-modules"]);
expect(tsconfig.include).toEqual(["agent/**/*.ts", "evals/**/*.ts"]);
await expect(readFile(join(projectRoot, "pnpm-workspace.yaml"), "utf8")).resolves.toBe(
PNPM_WORKSPACE_CONTENT,
diff --git a/packages/eve/src/shared/dispatch-action.ts b/packages/eve/src/shared/dispatch-action.ts
index 3039d8d67..a088fe343 100644
--- a/packages/eve/src/shared/dispatch-action.ts
+++ b/packages/eve/src/shared/dispatch-action.ts
@@ -26,5 +26,10 @@ export type PendingTaskControlAction = PendingDispatchAction & {
>;
};
+/** Pending action that runs a tool's execute body as a durable workflow. */
+export type PendingWorkflowToolAction = PendingDispatchAction & {
+ readonly target: Extract<PreparedDispatchTarget, { readonly kind: "workflow-tool-call" }>;
+};
+
/** Fields common to task-control dispatch and its result projection helpers. */
export type TaskControlInvocation = Pick<PendingDispatchAction, "callId" | "input" | "toolName">;
diff --git a/packages/eve/src/tools/behavior.ts b/packages/eve/src/tools/behavior.ts
index 5c9ebdfe7..3191b28b2 100644
--- a/packages/eve/src/tools/behavior.ts
+++ b/packages/eve/src/tools/behavior.ts
@@ -10,7 +10,8 @@ export type ToolAvailabilityCondition =
export type CompiledToolHandling =
| { readonly kind: "dispatch"; readonly action: "self-agent" | "task-cancel" | "task-update" }
| { readonly kind: "provider-tool"; readonly provider: WebSearchProvider }
- | { readonly kind: "request-input"; readonly request: "question" };
+ | { readonly kind: "request-input"; readonly request: "question" }
+ | { readonly kind: "workflow-tool"; readonly workflowId: string };
/** Closed, serializable behavior carried by one selected compiled tool. */
export interface CompiledToolBehavior {
@@ -37,7 +38,8 @@ export type PreparedDispatchTarget =
readonly subagentName: string;
}
| { readonly kind: "task-cancel" }
- | { readonly kind: "task-update" };
+ | { readonly kind: "task-update" }
+ | { readonly kind: "workflow-tool-call"; readonly workflowId: string };
/** Runtime-prepared handling consumed by the harness and execution boundary. */
export type PreparedToolHandling =
diff --git a/packages/eve/src/tools/definition.ts b/packages/eve/src/tools/definition.ts
index 06574309a..a64829312 100644
--- a/packages/eve/src/tools/definition.ts
+++ b/packages/eve/src/tools/definition.ts
@@ -10,6 +10,7 @@ import { stampDefinitionKey } from "#internal/authored-definition/source-identit
import type { JsonObject } from "#shared/json.js";
import type { TokenResult } from "#shared/connection-types.js";
import type { ToolAuthOptions, ToolAuthProvider } from "#tools/auth.js";
+import type { InputOption } from "#shared/input.js";
import {
collectDurableDynamicToolCallbacks,
stampDurableDynamicToolCallbacks,
@@ -98,15 +99,52 @@ export interface PublicToolDefinitionWithExecuteFn<
execute: ToolExecuteFn<TInput, TOutput>;
}
+/**
+ * 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
+ * `ask_question` and tool approvals.
+ */
+export interface ToolInputRequest {
+ /**
+ * Whether the user may answer with free text instead of one of the
+ * {@link options}.
+ */
+ readonly allowFreeform?: boolean;
+ /** Rendering hint: confirmation buttons, a selection list, or a text field. */
+ readonly display?: "confirmation" | "select" | "text";
+ /** Selectable answers. */
+ readonly options?: readonly InputOption[];
+ readonly prompt: string;
+}
+
+/** The human's answer to a {@link ToolInputRequest}. */
+export interface ToolInputResponse {
+ /** The selected option's `id`, when the user picked one. */
+ readonly optionId?: string;
+ /** Free text, when the user typed an answer. */
+ readonly text?: string;
+}
+
/**
* Authored tool context. Passed as the last argument to
* {@link ToolDefinition.execute}.
*
* 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.
*/
export type ToolContext = SessionContext & {
- /** Aborts when the active turn is cancelled. */
+ /**
+ * Aborts when the work this tool is doing is cancelled: the active turn
+ * for an ordinary tool, the durable run for a workflow tool. In a workflow
+ * body the signal is durable — it survives replay and steps that receive it
+ * observe the abort — and the run waits a grace period for the body to
+ * unwind through `finally` before it ends.
+ */
readonly abortSignal: AbortSignal;
/**
* Id of the current tool call — the same `callId` carried by the call's
@@ -178,7 +216,7 @@ export interface BackgroundToolDefinition<
input: TInput,
ctx: ToolContext,
task: TaskExec,
- ): Promise<TaskDelegated | TOutput> | TaskDelegated | TOutput;
+ ): Promise<TaskDelegated | TOutput> | TaskDelegated | TOutput | AsyncIterable<TOutput>;
approval?: Approval<ApprovalContextInput<TInput>>;
toModelOutput?: (output: TOutput) => ToolModelOutput | Promise<ToolModelOutput>;
}
@@ -227,11 +265,7 @@ export function defineTool<
unknown,
BackgroundToolOutputFromExecuteReturn<TReturn>
>["outputSchema"];
- execute(
- input: StandardSchemaV1.InferOutput<TSchema>,
- ctx: ToolContext,
- task: TaskExec,
- ): TReturn extends AsyncIterable<unknown> ? never : TReturn;
+ execute(input: StandardSchemaV1.InferOutput<TSchema>, ctx: ToolContext, task: TaskExec): TReturn;
approval?: BackgroundToolDefinition<StandardSchemaV1.InferOutput<TSchema>, unknown>["approval"];
toModelOutput?: BackgroundToolDefinition<
unknown,
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 e4741d0cd..122be2a23 100644
--- a/packages/eve/test/scenarios/bin-build-output.scenario.test.ts
+++ b/packages/eve/test/scenarios/bin-build-output.scenario.test.ts
@@ -1,5 +1,5 @@
import { spawn } from "node:child_process";
-import { mkdir, realpath, writeFile } from "node:fs/promises";
+import { mkdir, readdir, readFile, realpath, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
@@ -97,6 +97,23 @@ async function createTemporaryAppRoot(input: {
return appRoot;
}
+async function readDirectorySources(root: string): Promise<string> {
+ const entries = await readdir(root, { recursive: true, withFileTypes: true });
+ const sources = await Promise.all(
+ entries
+ .filter((entry) => entry.isFile() && /\.(?:m?js|cjs)$/u.test(entry.name))
+ .map((entry) => readFile(join(entry.parentPath, entry.name), "utf8")),
+ );
+ return sources.join("\n");
+}
+
+function decodeEmbeddedWorkflowCode(source: string): string {
+ const chunks = [...source.matchAll(/Buffer\.from\((\[[\s\S]*?\])\.join\(""\), "base64"\)/gu)].map(
+ (match) => JSON.parse(match[1]!) as string[],
+ );
+ return chunks.map((chunk) => Buffer.from(chunk.join(""), "base64").toString("utf8")).join("\n");
+}
+
async function runEveBuild(appRoot: string): Promise<ProcessResult> {
return await new Promise((resolve, reject) => {
const child = spawn(process.execPath, [EVE_BIN_PATH, "build"], {
@@ -175,6 +192,61 @@ describe("eve build process output", () => {
expect(result.stdout).toContain(".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-",
+ });
+ await mkdir(join(appRoot, "agent", "tools"), { recursive: true });
+ await mkdir(join(appRoot, "agent", "lib"), { recursive: true });
+ await writeFile(
+ join(appRoot, "agent", "lib", "plan.mjs"),
+ [
+ 'import { createHash } from "node:crypto";',
+ "",
+ "export async function hashPlan(plan) {",
+ ' "use step";',
+ ' return createHash("sha256").update(plan).digest("hex");',
+ "}",
+ "",
+ ].join("\n"),
+ );
+ await writeFile(
+ join(appRoot, "agent", "tools", "deploy_service.mjs"),
+ [
+ 'import { sleep } from "workflow";',
+ 'import { hashPlan } from "../lib/plan.mjs";',
+ "",
+ "export default {",
+ ' description: "Deploy a service.",',
+ ' inputSchema: { type: "object", properties: { service: { type: "string" } } },',
+ " async execute({ service }) {",
+ ' "use workflow";',
+ " const digest = await hashPlan(service);",
+ ' await sleep("10ms");',
+ " return { digest };",
+ " },",
+ "};",
+ "",
+ ].join("\n"),
+ );
+
+ const result = await runEveBuild(appRoot);
+ expect(result.code, `stderr:\n${result.stderr}`).toBe(0);
+
+ const output = join(appRoot, ".output", "server");
+ const serverSources = await readDirectorySources(output);
+ expect(serverSources).toContain('"step//./agent/lib/plan//hashPlan"');
+ expect(serverSources).toContain('"workflow//./agent/tools/deploy_service//execute"');
+ // The driver body is base64-embedded; decode and check it registers the
+ // authored workflow and proxies the authored step without its Node import.
+ const driverCode = decodeEmbeddedWorkflowCode(serverSources);
+ expect(driverCode).toContain(
+ '__private_workflows.set("workflow//./agent/tools/deploy_service//execute"',
+ );
+ expect(driverCode).toContain('WORKFLOW_USE_STEP")]("step//./agent/lib/plan//hashPlan")');
+ expect(driverCode).not.toContain("node:crypto");
+ }, 180_000);
+
it("prints discovery diagnostics to stderr when build fails", async () => {
const appRoot = await createTemporaryAppRoot({
omitInstructionsSource: true,
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 cfb7d26ac..d7549fe7b 100644
--- a/packages/eve/test/scenarios/dev-server-apps.scenario.test.ts
+++ b/packages/eve/test/scenarios/dev-server-apps.scenario.test.ts
@@ -45,6 +45,45 @@ const NPM_LAYOUT_DESCRIPTOR: ScenarioAppDescriptor = {
name: "weather-agent-npm",
packageManager: "npm",
};
+const WORKFLOW_TOOL_DESCRIPTOR: ScenarioAppDescriptor = {
+ ...WEATHER_AGENT_DESCRIPTOR,
+ files: {
+ ...WEATHER_AGENT_DESCRIPTOR.files,
+ "agent/lib/deploy/plan.ts": [
+ 'import { createHash } from "node:crypto";',
+ "",
+ "export function describePlan(service: string): string {",
+ " return `deploy ${service}`;",
+ "}",
+ "",
+ "export async function hashPlan(plan: string): Promise<string> {",
+ ' "use step";',
+ ' return createHash("sha256").update(plan).digest("hex").slice(0, 8);',
+ "}",
+ "",
+ ].join("\n"),
+ "agent/tools/deploy_service.ts": [
+ 'import { defineTool } from "eve/tools";',
+ 'import { sleep } from "workflow";',
+ 'import { z } from "zod";',
+ 'import { describePlan, hashPlan } from "../lib/deploy/plan.ts";',
+ "",
+ "export default defineTool({",
+ ' description: "Deploy a service after planning it durably.",',
+ " inputSchema: z.object({ service: z.string() }),",
+ " async execute({ service }, ctx) {",
+ ' "use workflow";',
+ " const plan = describePlan(service);",
+ " const digest = await hashPlan(plan);",
+ ' await sleep("10ms");',
+ " return { digest, plan, session: ctx.session.id, tool: ctx.toolName };",
+ " },",
+ "});",
+ "",
+ ].join("\n"),
+ },
+ name: "weather-agent-workflow-tool",
+};
const WORKSPACE_EXTENSION_HMR_DESCRIPTOR: ScenarioAppDescriptor = {
dependencies: {
"@acme/workspace-extension": "workspace:*",
@@ -225,6 +264,40 @@ describe("eve dev server app layouts", () => {
DEV_SERVER_SCENARIO_TIMEOUT_MS,
);
+ it(
+ "runs an authored workflow tool through the development server",
+ async () => {
+ const app = await scenarioApp(WORKFLOW_TOOL_DESCRIPTOR);
+ const server = await startEveDev(app.appRoot);
+
+ try {
+ const messageResult = await sendDevelopmentMessage({
+ message: 'Run deploy_service with service "api"',
+ session: createDevelopmentSessionState(),
+ serverUrl: server.url,
+ });
+ const results = messageResult.events.filter((event) => event.type === "action.result");
+ const outputs = results.map((event) => JSON.stringify(event.data));
+ expect(
+ outputs.some((output) => output.includes('"plan":"deploy api"')),
+ [
+ "Expected the workflow tool's return value to settle the tool call.",
+ `events:\n${messageResult.events.map((event) => event.type).join(",")}`,
+ `results:\n${outputs.join("\n")}`,
+ `stdout:\n${server.stdout()}`,
+ `stderr:\n${server.stderr()}`,
+ ].join("\n\n"),
+ ).toBe(true);
+ expect(outputs.some((output) => output.includes('"tool":"deploy_service"'))).toBe(true);
+ expect(messageResult.events.some((event) => event.type === "message.completed")).toBe(true);
+ expect(hasKnownDevServerFailure(`${server.stdout()}\n${server.stderr()}`)).toBe(false);
+ } finally {
+ await server.stop();
+ }
+ },
+ DEV_SERVER_SCENARIO_TIMEOUT_MS,
+ );
+
it(
"serves an npm-installed app with hoisted real-directory dependencies",
async () => {
diff --git a/packages/eve/test/setup/workflow-global-setup.ts b/packages/eve/test/setup/workflow-global-setup.ts
index e26e423a6..51f260080 100644
--- a/packages/eve/test/setup/workflow-global-setup.ts
+++ b/packages/eve/test/setup/workflow-global-setup.ts
@@ -16,7 +16,7 @@ import {
collectWorkflowInputFiles,
type WorkflowBundleDiscoveredEntries,
} from "#internal/workflow-bundle/builder-support.js";
-import { detectWorkflowPatterns } from "#internal/workflow-bundle/workflow-builders.js";
+import { findWorkflowPatterns } from "#internal/workflow-bundle/workflow-builders.js";
import { installEveWorkflowQueueNamespace } from "#internal/workflow/queue-namespace.js";
import { resolveLocalWorkflowWorldDataDirectory } from "#internal/workflow/local-world-data-directory.js";
@@ -66,7 +66,7 @@ async function discoverWorkflowEntries(): Promise<WorkflowBundleDiscoveredEntrie
for (const filePath of inputFiles) {
const source = await readFile(filePath, "utf8");
- const patterns = detectWorkflowPatterns(source);
+ const patterns = await findWorkflowPatterns(filePath, source);
if (patterns.hasUseStep) {
discovered.discoveredSteps.push(filePath);
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 00e643b13..a0d0b39ba 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1098,6 +1098,28 @@ importers:
specifier: 'catalog:'
version: 7.0.2
+ e2e/fixtures/agent-workflow-tools:
+ dependencies:
+ '@eve-e2e/config':
+ specifier: workspace:*
+ version: link:../e2e-config
+ '@workflow/world-postgres':
+ specifier: 'catalog:'
+ eve:
+ specifier: workspace:*
+ version: link:../../../packages/eve
+ zod:
+ specifier: 'catalog:'
+ version: 4.5.4
+ devDependencies:
+ '@types/node':
+ specifier: 'catalog:'
+ version: 25.9.1
+ typescript:
+ specifier: 'catalog:'
+ version: 7.0.2
+
e2e/fixtures/dist-extensions:
dependencies:
'@eve-e2e/config':
@@ -1382,6 +1404,9 @@ importers:
'@vercel/sdk':
specifier: 1.28.8
version: 1.28.8
+ '@workflow/builders':
+ specifier: 5.0.0-beta.44
'@workflow/core':
specifier: 5.0.0-beta.43
@@ -1619,12 +1644,6 @@ packages:
peerDependencies:
zod: ^3.25.76 || ^4.1.8
- '@ai-sdk/[email protected]':
- resolution: {integrity: sha512-iayK1z11I0b3sgbP3j6eKQypfpwO5Fbtaq1Mkwv7YxwGQG1YTNr5QAjyYsSfqyf/58WUOLWz2cTBpk+ExZVgpw==}
- engines: {node: '>=22'}
- peerDependencies:
- zod: ^3.25.76 || ^4.1.8
-
'@ai-sdk/[email protected]':
resolution: {integrity: sha512-XKvZv6HFoMOWK64zXMaQatk4SxBzBDkGg7enXPWsCkxqPP4zDhFewOoBKasf3FPnZP9ceE+Yj3BgW925blAWtw==}
engines: {node: '>=22'}
@@ -1719,12 +1738,6 @@ packages:
peerDependencies:
zod: ^3.25.76 || ^4.1.8
- '@ai-sdk/[email protected]':
- resolution: {integrity: sha512-9TyxUXolql77ntHIeygLqt7PO1O0HZPB73cJhLG2OsPecSBRIZhNXLxT1T7rlL6Zpm1eDoLMFrMV99kAJ28/Sg==}
- engines: {node: '>=22'}
- peerDependencies:
- zod: ^3.25.76 || ^4.1.8
-
'@ai-sdk/[email protected]':
resolution: {integrity: sha512-TfjJqJmRsQyxAlb+3hGmP1o1xLUIT79yhOgtJuTF4hqsB37IC3CufGsuFhU04EeTOg7R9iptQ6Bzm0MW0n/c3g==}
engines: {node: '>=22'}
@@ -7063,12 +7076,91 @@ packages:
peerDependencies:
'@svta/cml-utils': 1.0.1
+ resolution: {integrity: sha512-AXfeQn0CvcQ4cndlIshETx6jrAM45oeUrK8YeEY6oUZU/qzz0Id0CyvlEywxkWVC81Ajpd8TQQ1fW5yx6zQWkQ==}
+ engines: {node: '>=10'}
+ cpu: [arm64]
+ os: [darwin]
+
+ resolution: {integrity: sha512-p68OeCz1ui+MZYG4wmfJGvcsAcFYb6Sl25H9TxWl+GkBgmNimIiRdnypK9nBGlqMZAcxngNPtnG3kEMNnvoJ2A==}
+ engines: {node: '>=10'}
+ cpu: [x64]
+ os: [darwin]
+
+ resolution: {integrity: sha512-Nuj5iF4JteFgwrai97mUX+xUOl+rQRHqTvnvHMATL/l9xE6/TJfPBpd3hk/PVpClMXG3Uvk1MxUFOEzM1JrMYg==}
+ engines: {node: '>=10'}
+ cpu: [arm]
+ os: [linux]
+
+ resolution: {integrity: sha512-2Nc/s8jE6mW2EjXWxO/lyQuLKShcmTrym2LRf5Ayp3ICEMX6HwFqB1EzDhwoMa2DcUgmnZIalesq2lG3krrUNw==}
+ engines: {node: '>=10'}
+ cpu: [arm64]
+ os: [linux]
+ libc: [glibc]
+
+ resolution: {integrity: sha512-j4SJniZ/qaZ5g8op+p1G9K1z22s/EYGg1UXIb3+Cg4nsxEpF5uSIGEE4mHUfA70L0BR9wKT2QF/zv3vkhfpX4g==}
+ engines: {node: '>=10'}
+ cpu: [arm64]
+ os: [linux]
+ libc: [musl]
+
+ resolution: {integrity: sha512-aKttAZnz8YB1VJwPQZtyU8Uk0BfMP63iDMkvjhJzRZVgySmqt/apWSdnoIcZlUoGheBrcqbMC17GGUmur7OT5A==}
+ engines: {node: '>=10'}
+ cpu: [x64]
+ os: [linux]
+ libc: [glibc]
+
+ resolution: {integrity: sha512-oe8FctPu1gnUsdtGJRO2rvOUIkkIIaHqsO9xxN0bTR7dFTlPTGi2Fhk1tnvXeyAvCPxLIcwD8phzKg6wLv9yug==}
+ engines: {node: '>=10'}
+ cpu: [x64]
+ os: [linux]
+ libc: [musl]
+
+ resolution: {integrity: sha512-L9AjzP2ZQ/Xh58e0lTRMLvEDrcJpR7GwZqAtIeNLcTK7JVE+QineSyHp0kLkO1rttCHyCy0U74kDTj0dRz6raA==}
+ engines: {node: '>=10'}
+ cpu: [arm64]
+ os: [win32]
+
+ resolution: {integrity: sha512-B8UtogMzErUPDWUoKONSVBdsgKYd58rRyv2sHJWKOIMCHfZ22FVXICR4O/VwIYtlnZ7ahERcjayBHDlBZpR0aw==}
+ engines: {node: '>=10'}
+ cpu: [ia32]
+ os: [win32]
+
+ resolution: {integrity: sha512-SpZKMR9QBTecHeqpzJdYEfgw30Oo8b/Xl6rjSzBt1g0ZsXyy60KLXrp6IagQyfTYqNYE/caDvwtF2FPn7pomog==}
+ engines: {node: '>=10'}
+ cpu: [x64]
+ os: [win32]
+
+ resolution: {integrity: sha512-Qd8eBPkUFL4eAONgGjycZXj1jFCBW8Fd+xF0PzdTlBCWQIV1xnUT7B93wUANtW3KGjl3TRcOyxwSx/u/jyKw/Q==}
+ engines: {node: '>=10'}
+ peerDependencies:
+ '@swc/helpers': '>=0.5.17'
+ peerDependenciesMeta:
+ '@swc/helpers':
+ optional: true
+
+ resolution: {integrity: sha512-e2BR4lsJkkRlKZ/qCHPw9ZaSxc0MVUd7gtbtaB7aMvHeJVYe8sOB8DBZkP2DtISHGSku9sCK6T6cnY0CtXrOCQ==}
+
resolution: {integrity: sha512-JQ5TuMi45Owi4/BIMAJBoSQoOJu12oOk/gADqlcUL9JEdHB8vyjUSsxqeNXnmXHjYKMi2WcYtezGEEhqUI/E2g==}
resolution: {integrity: sha512-5lSsMOTXURePglDfvuAQUqkGek9Hg2kksOYay2m0+XR++b2NWYL/4sWyuvVBIs8oKnJaxkdi9whaL/sqN13afw==}
+ resolution: {integrity: sha512-V6Mnml8v09QALx6K0elJ7o9K/MkVDtW3t6L+7Ou/JcWtb3xwId2AH4FeOceySd2JaO87IMw4+6vSZxLm34LPbw==}
+
'@tailwindcss/[email protected]':
resolution: {integrity: sha512-aFb4gUhFOgdh9AXo4IzBEOzBkkAxm9VigwDJnMIYv3lcfXCJVesNfbEaBl4BNgVRyid92AmdviqwBUBRKSeY3g==}
@@ -8373,6 +8465,9 @@ packages:
'@webgpu/[email protected]':
resolution: {integrity: sha512-mMy8/ODcKhab808co15eW+yN+HgXoQxRQHTiBV9Mrvl1r0ufnid7YOcI+gi4eUWSWl9ezD6TW2KXccrL8HCh2A==}
+ '@workflow/[email protected]':
+ resolution: {integrity: sha512-GqbujuOGppDDVt27qOl15fPpgoTbNMc2+/2VEmuhnQmC9vVcmwFrLGf1aAnGsZl1xYpn1+IT97317mdW095VFw==}
+
'@workflow/[email protected]':
resolution: {integrity: sha512-o3vdzxhL9HNJ3zA7GzCw0dkFNQryMVv8FUfb8c1XdKx4+gnQuOQFYj1TQadmPnCsRoJh1eVVe2y8OtvevuZwsg==}
peerDependencies:
@@ -8381,9 +8476,20 @@ packages:
'@opentelemetry/api':
optional: true
+ '@workflow/[email protected]':
+ resolution: {integrity: sha512-LaQfLMCYTHnV8cZtMhXROIOld61xi0c0LlxH24d7ToHoh6hrzKN8lAh04ZccFRQ+/Qo0f+7ewItUmSSxDiZncQ==}
+ peerDependencies:
+ '@opentelemetry/api': '1'
+ peerDependenciesMeta:
+ '@opentelemetry/api':
+ optional: true
+
'@workflow/[email protected]':
resolution: {integrity: sha512-orc86yllgOKpss/o5YD4kuhRbng+4aq8i4pPJR4uZCFeNpn4I4A+ek83lelQf31EJ5tyf12ikceOjabQxp317A==}
+ '@workflow/[email protected]':
+ resolution: {integrity: sha512-Q2J0dz/yJJv6JNH7hyyqQ6ERc/Xpup7HNelFL+cNE0zU5We1c6GgV37bAoc2qsmyJO8Is5wSo4phlkorEQNfTA==}
+
'@workflow/[email protected]':
resolution: {integrity: sha512-pav4F2BoirECWR7Nf1TKt+2eETcBj7jj4cBefQ8VXQCA6NPkaKeLfj/zMgi+3zYV5ZIBT4GuUiphsj0/b9hPQQ==}
@@ -8393,9 +8499,17 @@ packages:
'@workflow/[email protected]':
resolution: {integrity: sha512-INB+FcEKQkkFZa+s53sEMTNRFiBa2g9vzjsNuEDagvWxtI0t/cnCyoc57i7kS7nj+3/vGeRjO4Yn5ccbT0hyBQ==}
+ '@workflow/[email protected]':
+ resolution: {integrity: sha512-Xk2UQePkuxTrgqU0EWZPRWM9Ttj9bcMAY+x700yg/0TQnD3MSxjY6/yC3e8wGr2dfzXik5zuH+Ixrog1CdBqeg==}
+ peerDependencies:
+ '@swc/core': 1.15.3
+
'@workflow/[email protected]':
resolution: {integrity: sha512-dDiQ/LT05g9HyOicqWNNX/Gw/fmO7Ma2kZ+ddUXXpm/EFTMRS9eiI69suSe1+1NnhMzdV6ObI8wrO5lvQqPIbg==}
+ '@workflow/[email protected]':
+ resolution: {integrity: sha512-EvwbO41RiiuFZlGuAt4f10BkrhfNmz7YKgqUm2VmL6Ib5WFcfIpoaLStCML91LeGgMyO5bwsf1m7Zm8IPprSdQ==}
+
'@workflow/[email protected]':
resolution: {integrity: sha512-rruX3MZUqIyaFIEeHrdHyG6caogSFtf06Zxz1FYBOjNTKs4dE3W67obHM5rzD/5mjlQc9dmTye1/3+0NQ6wyag==}
peerDependencies:
@@ -8404,6 +8518,14 @@ packages:
'@opentelemetry/api':
optional: true
+ '@workflow/[email protected]':
+ resolution: {integrity: sha512-XOTfsmiaV3F9qzAWDyoHmAn8RYnVLouE4E6254kxc5VfzrOXsW5jcfIXHhRC6dwGYNC2aZVjiX4SMV2io8Ardw==}
+ peerDependencies:
+ '@opentelemetry/api': '1'
+ peerDependenciesMeta:
+ '@opentelemetry/api':
+ optional: true
+
'@workflow/[email protected]':
resolution: {integrity: sha512-VkkjYslEXb1gfdUyP+wJYlZGkEr2ZtdLRWaiDahYDWG/5YTWQ5tdBJBY1qEBm4XLEJp2wfVGu6ko5utzypD98Q==}
hasBin: true
@@ -8416,9 +8538,20 @@ packages:
'@opentelemetry/api':
optional: true
+ '@workflow/[email protected]':
+ resolution: {integrity: sha512-QDh5Zi/OeIBK5O3zRHG0yPhDAplcXoCgODivq6WGgvKWwvSNVUiBswtu+R4uCB7HnZCzJgSC/knc5yE09vnZXA==}
+ peerDependencies:
+ '@opentelemetry/api': '1'
+ peerDependenciesMeta:
+ '@opentelemetry/api':
+ optional: true
+
'@workflow/[email protected]':
resolution: {integrity: sha512-dW1gH4lL4GClAzklgQhQvKVo4pCmWwqrUN06ni+a6jdVt9Uk5MEPdDTBzYpDYH0caYvlFscIzajaYpE5ol2aRA==}
+ '@workflow/[email protected]':
+ resolution: {integrity: sha512-3z5GHEJgvb2AFfznQ4JfT1rm5U9jNupuG4YtrUUrtJ+807JkcjhP85fMN7Jo30975CcPPgnZmlnYI4sM0Y1d/w==}
+
'@zernio/[email protected]':
resolution: {integrity: sha512-YYcnbCqUhJOymTd3UPaKd1H6Kn8atFE075I5vDETYkTjToIeZd90as/JvShB7OurMdDLLSmJRMJs3RWVqAGW9w==}
engines: {node: '>=20'}
@@ -8492,12 +8625,6 @@ packages:
peerDependencies:
zod: ^3.25.76 || ^4.1.8
- resolution: {integrity: sha512-zZkSUq6MgmXjwIfML2wkPFeQ5Azk8kGEWkciAtE0NgnFy3slj4ljsw5LvigsCbYXxTSVr+6iCHBTPZafpx1P0w==}
- engines: {node: '>=22'}
- peerDependencies:
- zod: ^3.25.76 || ^4.1.8
-
resolution: {integrity: sha512-znHNBWADOy79k8EK7636kDm5LmnjF4tMzegC2TfmlLDobDZbs0z0OXD2sxtH3eDTp5Re+pJQESvjinWJ6+kadQ==}
engines: {node: '>=22'}
@@ -8938,6 +9065,10 @@ packages:
resolution: {integrity: sha512-lHblz4ahamxpTmnsk+MNTRWsjYKv965MwOrSJyeD588rR3Jcu7swE+0wN5F+PbL5cjgu/9ObkhfzEPuofEMwLA==}
engines: {node: '>=10.0.0'}
+ resolution: {integrity: sha512-bkXY9WsVpY7CvMhKSR6pZilZu9Ln5WDrKVBUXf2S443etkmEO4V58heTecXcUIsNsi4Rx8JUO4NfX1IcQl4deg==}
+ engines: {node: '>=18.20'}
+
resolution: {integrity: sha512-tjwM5exMg6BGRI+kNmTntNsvdZS1X8BFYS6tnJ2hdH0kVxM6/eVZ2xy+FqStSWvYmtfFMDLIxurorHwDKfDz5Q==}
engines: {node: '>=18'}
@@ -10026,6 +10157,10 @@ packages:
resolution: {integrity: sha512-clKkw4C7nJ22mGgoVcCg6V/W/TxdNyIOTr89k2ONZu81qqkddPFDF0LXcbAwhzPD8DjkiRCjzuiO6Y+fkpD4vg==}
engines: {node: '>=10.2.0'}
+ resolution: {integrity: sha512-phv3E1Xl4tQOShqSte26C7Fl84EwUdZsyOuSSk9qtAGyyQs2s3jJzComh+Abf4g187lUUAvH+H26omrqia2aGg==}
+ engines: {node: '>=10.13.0'}
+
resolution: {integrity: sha512-xYcDWrpELkFzz9SpZ3PlI6Eu6eD93Yf0WLDRxikGhWJ3MAir2SNZTIVCVZqZ/NUyx8AdMc2gT9C0gPiw18kG+A==}
engines: {node: '>=10.13.0'}
@@ -10153,6 +10288,7 @@ packages:
resolution: {integrity: sha512-HrJrvZv5ayxBzPfwphOoNzkzOIIlifzk0KJrGK2c8R4+LKpMtpYLQeUdjnwjWv/LZlkH2laZk+4w78pi99D4Vw==}
engines: {node: '>=18'}
+ hasBin: true
resolution: {integrity: sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==}
@@ -10575,6 +10711,10 @@ packages:
resolution: {integrity: sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==}
engines: {node: '>=10'}
+ resolution: {integrity: sha512-YyZM99iHrqLKjmt4LJDj58KI+fYyufRLBSYcqycxf//KpBk9FoewoGX0450m9nB44qrZnovzC2oeP5hUibxc/g==}
+ engines: {node: '>=18'}
+
resolution: {integrity: sha512-f7ccFPK3SXFHpx15UIGyRJ/FJQctuKZ0zVuN3frBo4HnK3cay9VEW0R6yPYFHC0AgqhukPzKjq22t5DmAyqGyw==}
engines: {node: '>=16'}
@@ -11654,10 +11794,12 @@ packages:
resolution: {integrity: sha512-g1MWMLBiz8FKi1e4w0UyVL3w+iJceWAFBAaBnnGKOpNa5f8TLktkbre1+s6oICydWAm+HRUGTmI+//xv2hvXYA==}
+ hasBin: true
resolution: {integrity: sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==}
engines: {node: '>=6'}
+ hasBin: true
resolution: {integrity: sha512-HUgH65KyejrUFPvHFPbqOY0rsFip3Bo5wb4ngvdi1EpCYWUQDC5V+Y7mZws+DLkr4M//zQJoanu1SP+87Dv1oQ==}
@@ -11897,6 +12039,10 @@ packages:
resolution: {integrity: sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==}
engines: {node: '>=10'}
+ resolution: {integrity: sha512-gvVijfZvn7R+2qyPX8mAuKcFGDf6Nc61GdvGafQsHL0sBIxfKzA+usWn4GFC/bk+QdwPUD4kWFJLhElipq+0VA==}
+ engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0}
+
resolution: {integrity: sha512-J8xewKD/Gk22OZbhpOVSwcs60zhd95ESDwezOFuA3/099925PdHJ7OFHNTGtajL3AlZkykD32HykiMo+BIBI8A==}
@@ -13007,6 +13153,10 @@ packages:
resolution: {integrity: sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==}
engines: {node: '>=10'}
+ resolution: {integrity: sha512-5b0R4txpzjPWVw/cXXUResoD4hb6U/x9BH08L7nw+GN1sezDzPdxeRvpc9c433fZhBan/wusjbCsqwqm4EIBIQ==}
+ engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0}
+
resolution: {integrity: sha512-kuUqqHNUqoIWp/c467RI4X6mmyuojY5jGutNU0wVTmEOOfcuwLqyMVoAi9MKi2Ak+5i9+nhmrK4ufZE8069kHA==}
engines: {node: '>=18'}
@@ -13023,6 +13173,10 @@ packages:
resolution: {integrity: sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==}
engines: {node: '>=10'}
+ resolution: {integrity: sha512-wPrq66Llhl7/4AGC6I+cqxT07LhXvWL08LNXz1fENOw0Ap4sRZZ/gZpTTJ5jpurzzzfS2W/Ge9BY3LgLjCShcw==}
+ engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0}
+
resolution: {integrity: sha512-y3b8Kpd8OAN444hxfBbFfj1FY/RjtTd8tzYwhUqNYXx0fXx2iX4maP4Qr6qhIKbQXI02wTLAda4fYUbDagTUFw==}
engines: {node: '>=6'}
@@ -13128,6 +13282,10 @@ packages:
resolution: {integrity: sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==}
engines: {node: '>=8'}
+ resolution: {integrity: sha512-RjhtfwJOxzcFmNOi6ltcbcu4Iu+FL3zEj83dk4kAS+fVpTxXLO1b38RvJgT/0QwvV/L3aY9TAnyv0EOqW4GoMQ==}
+ engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0}
+
resolution: {integrity: sha512-cbrerZV+6rvdQrrD+iGMcZFEiiSrbv9Tfdkvnusy6y0x0GKBXREFg/Y65GhIfm0tnLntThhzCnfKwp1WRjeCyQ==}
engines: {node: '>=14.0.0'}
@@ -14993,6 +15151,10 @@ packages:
resolution: {integrity: sha512-7uvcWI3hWshSADBu4JpnyYbTVc7YlhF5GDW/oPD5AxIxl34k4wXR3WDkPnzLxkN32LiTCTKMQLtKVZiwki3zGg==}
+ resolution: {integrity: sha512-lRfVq8fE8gz6QMBuDM6a+LO3IAzTi05H6gCVaUpir2E1Rwpo4ZUog45KpNXKC/Mn3Yb9UDuHumeFTo9iV/D9FQ==}
+ engines: {node: '>=18'}
+
resolution: {integrity: sha512-+QBBXBCvifc56fsbuxZQ6Sic3wqqc3WWaqxs58gvJrcOuN83HGTCwz3oS5phzU9LthRNE9VrJCFCLUgHeeFnfA==}
engines: {node: '>=18'}
@@ -15998,13 +16160,6 @@ snapshots:
'@vercel/oidc': 3.2.0
zod: 4.5.4
- dependencies:
- '@ai-sdk/provider': 4.0.8
- '@ai-sdk/provider-utils': 5.0.30([email protected])
- '@vercel/oidc': 3.2.0
- zod: 4.5.4
-
dependencies:
'@ai-sdk/provider': 4.0.8
@@ -16131,15 +16286,6 @@ snapshots:
undici: 7.29.0
zod: 4.5.4
- dependencies:
- '@ai-sdk/provider': 4.0.8
- '@standard-schema/spec': 1.1.0
- '@workflow/serde': 4.1.0
- eventsource-parser: 3.1.0
- undici: 7.29.0
- zod: 4.5.4
-
dependencies:
'@ai-sdk/provider': 4.0.8
@@ -21537,6 +21683,55 @@ snapshots:
dependencies:
'@svta/cml-utils': 1.0.1
+ optional: true
+
+ optional: true
+
+ optional: true
+
+ optional: true
+
+ optional: true
+
+ optional: true
+
+ optional: true
+
+ optional: true
+
+ optional: true
+
+ optional: true
+
+ dependencies:
+ '@swc/counter': 0.1.3
+ '@swc/types': 0.1.28
+ optionalDependencies:
+ '@swc/core-darwin-arm64': 1.15.3
+ '@swc/core-darwin-x64': 1.15.3
+ '@swc/core-linux-arm-gnueabihf': 1.15.3
+ '@swc/core-linux-arm64-gnu': 1.15.3
+ '@swc/core-linux-arm64-musl': 1.15.3
+ '@swc/core-linux-x64-gnu': 1.15.3
+ '@swc/core-linux-x64-musl': 1.15.3
+ '@swc/core-win32-arm64-msvc': 1.15.3
+ '@swc/core-win32-ia32-msvc': 1.15.3
+ '@swc/core-win32-x64-msvc': 1.15.3
+ '@swc/helpers': 0.5.23
+
+ '@swc/[email protected]': {}
+
dependencies:
tslib: 2.8.1
@@ -21545,6 +21740,10 @@ snapshots:
dependencies:
tslib: 2.8.1
+ dependencies:
+ '@swc/counter': 0.1.3
+
'@tailwindcss/[email protected]':
dependencies:
'@jridgewell/remapping': 2.3.5
@@ -23154,6 +23353,28 @@ snapshots:
'@webgpu/[email protected]': {}
+ dependencies:
+ '@swc/core': 1.15.3(@swc/[email protected])
+ '@workflow/errors': 5.0.0-beta.18
+ '@workflow/swc-plugin': 5.0.0-beta.5(@swc/[email protected](@swc/[email protected]))
+ '@workflow/utils': 5.0.0-beta.9
+ builtin-modules: 5.0.0
+ chalk: 5.6.2
+ enhanced-resolve: 5.19.0
+ esbuild: 0.28.1
+ find-up: 7.0.0
+ json5: 2.2.3
+ tinyglobby: 0.2.17
+ transitivePeerDependencies:
+ - '@opentelemetry/api'
+ - '@swc/helpers'
+ - bufferutil
+ - supports-color
+ - utf-8-validate
+ - ws
+
dependencies:
'@aws-sdk/credential-provider-web-identity': 3.972.49
@@ -23184,21 +23405,64 @@ snapshots:
- utf-8-validate
- ws
+ dependencies:
+ '@aws-sdk/credential-provider-web-identity': 3.972.49
+ '@jridgewell/trace-mapping': 0.3.31
+ '@standard-schema/spec': 1.0.0
+ '@types/ms': 2.1.0
+ '@vercel/functions': 3.9.3(@aws-sdk/[email protected])([email protected]([email protected]))
+ '@workflow/errors': 5.0.0-beta.18
+ '@workflow/serde': 5.0.0-beta.2
+ '@workflow/utils': 5.0.0-beta.9
+ '@workflow/world': 5.0.0-beta.29
+ '@workflow/world-local': 5.0.0-beta.38(@opentelemetry/[email protected])
+ '@workflow/world-vercel': 5.0.0-beta.40(@aws-sdk/[email protected])(@opentelemetry/[email protected])([email protected])
+ debug: 4.4.3([email protected])
+ devalue: 5.9.0
+ ms: 2.1.3
+ nanoid: 5.1.6
+ quickjs-wasi: 3.4.0
+ seedrandom: 3.0.5
+ semver: 7.7.4
+ ulid: 3.0.2
+ zod: 4.3.6
+ optionalDependencies:
+ '@opentelemetry/api': 1.9.1
+ transitivePeerDependencies:
+ - bufferutil
+ - supports-color
+ - utf-8-validate
+ - ws
+
'@workflow/[email protected]':
dependencies:
'@workflow/utils': 5.0.0-beta.8
ms: 2.1.3
+ '@workflow/[email protected]':
+ dependencies:
+ '@workflow/utils': 5.0.0-beta.9
+ ms: 2.1.3
+
'@workflow/[email protected]': {}
'@workflow/[email protected]': {}
'@workflow/[email protected]': {}
+ dependencies:
+ '@swc/core': 1.15.3(@swc/[email protected])
+
'@workflow/[email protected]':
dependencies:
ms: 2.1.3
+ '@workflow/[email protected]':
+ dependencies:
+ ms: 2.1.3
+
'@workflow/[email protected](@opentelemetry/[email protected])':
dependencies:
'@vercel/queue': 0.5.0(@opentelemetry/[email protected])
@@ -23213,6 +23477,20 @@ snapshots:
optionalDependencies:
'@opentelemetry/api': 1.9.1
+ '@workflow/[email protected](@opentelemetry/[email protected])':
+ dependencies:
+ '@vercel/queue': 0.5.0(@opentelemetry/[email protected])
+ '@workflow/errors': 5.0.0-beta.18
+ '@workflow/utils': 5.0.0-beta.9
+ '@workflow/world': 5.0.0-beta.29
+ async-sema: 3.1.1
+ proper-lockfile: 4.1.2
+ ulid: 3.0.2
+ undici: 7.29.0
+ zod: 4.3.6
+ optionalDependencies:
+ '@opentelemetry/api': 1.9.1
+
dependencies:
'@vercel/queue': 0.5.0(@opentelemetry/[email protected])
@@ -23279,11 +23557,36 @@ snapshots:
- bufferutil
- utf-8-validate
+ dependencies:
+ '@vercel/functions': 3.9.3(@aws-sdk/[email protected])([email protected]([email protected]))
+ '@vercel/oidc': 3.2.0
+ '@vercel/queue': 0.5.0(@opentelemetry/[email protected])
+ '@workflow/errors': 5.0.0-beta.18
+ '@workflow/utils': 5.0.0-beta.9
+ '@workflow/world': 5.0.0-beta.29
+ cbor-x: 1.6.0
+ ulid: 3.0.2
+ undici: 7.29.0
+ ws: 8.21.3([email protected])
+ zod: 4.3.6
+ optionalDependencies:
+ '@opentelemetry/api': 1.9.1
+ transitivePeerDependencies:
+ - '@aws-sdk/credential-provider-web-identity'
+ - bufferutil
+ - utf-8-validate
+
'@workflow/[email protected]':
dependencies:
ulid: 3.0.2
zod: 4.3.6
+ '@workflow/[email protected]':
+ dependencies:
+ ulid: 3.0.2
+ zod: 4.3.6
+
dependencies:
@@ -23368,13 +23671,6 @@ snapshots:
'@ai-sdk/provider-utils': 5.0.25([email protected])
zod: 4.5.4
- dependencies:
- '@ai-sdk/gateway': 4.0.64([email protected])
- '@ai-sdk/provider': 4.0.8
- '@ai-sdk/provider-utils': 5.0.30([email protected])
- zod: 4.5.4
-
dependencies:
'@ai-sdk/gateway': 4.0.68([email protected])
@@ -23882,6 +24178,8 @@ snapshots:
optional: true
+
dependencies:
run-applescript: 7.1.0
@@ -24947,6 +25245,11 @@ snapshots:
- supports-color
- utf-8-validate
+ dependencies:
+ graceful-fs: 4.2.11
+ tapable: 2.3.3
+
dependencies:
graceful-fs: 4.2.11
@@ -25840,6 +26143,12 @@ snapshots:
locate-path: 6.0.0
path-exists: 4.0.0
+ dependencies:
+ locate-path: 7.2.0
+ path-exists: 5.0.0
+ unicorn-magic: 0.1.0
+
dependencies:
flatted: 3.4.2
@@ -27446,6 +27755,10 @@ snapshots:
dependencies:
p-locate: 5.0.0
+ dependencies:
+ p-locate: 6.0.0
+
@@ -29602,6 +29915,10 @@ snapshots:
dependencies:
yocto-queue: 0.1.0
+ dependencies:
+ yocto-queue: 1.2.2
+
dependencies:
yocto-queue: 1.2.2
@@ -29618,6 +29935,10 @@ snapshots:
dependencies:
p-limit: 3.1.0
+ dependencies:
+ p-limit: 4.0.0
+
@@ -29732,6 +30053,8 @@ snapshots:
+
@@ -32120,6 +32443,8 @@ snapshots:
+
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index 935c2ca9b..6d9d8fe28 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -8,6 +8,7 @@ packages:
allowBuilds:
"@google/genai": false # No-op preinstall.
"@parcel/watcher": false # Builds from source only when explicitly requested.
+ "@swc/core": false # Only its pure transform-utils module is vendored (via @workflow/builders); eve never runs SWC.
braintrust: false # Installs an optional CLI binary; the SDK does not need it.
bufferutil: false # The package already includes the supported prebuilt bindings.
cpu-features: false # Optional ssh2 acceleration; JavaScript fallback is sufficient.
diff --git a/research/tools-as-workflows.md b/research/tools-as-workflows.md
new file mode 100644
index 000000000..42e9b0871
--- /dev/null
+++ b/research/tools-as-workflows.md
@@ -0,0 +1,243 @@
+---
+issue: https://github.com/vercel/eve/issues/1084
+status: implemented
+last_updated: "2026-08-31"
+---
+
+# Tools as workflows
+
+## Summary
+
+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.
+
+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";
+import { z } from "zod";
+
+export default defineTool({
+ 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, {
+ prompt: `Deploy ${service}?\n\n${plan.summary}`,
+ 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) };
+ },
+});
+
+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.
+
+## 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.
+
+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.
+
+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.
+
+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.
+
+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) tool run
+ inbox hook ──────── starts ───────────────▶ toolRunWorkflow(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
+```
+
+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, `RunRef`, 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.
diff --git a/scripts/extension-capability-contracts.mjs b/scripts/extension-capability-contracts.mjs
index 9f5230890..cefa5cc89 100644
--- a/scripts/extension-capability-contracts.mjs
+++ b/scripts/extension-capability-contracts.mjs
@@ -157,11 +157,9 @@ async function main() {
const selectedMismatch = reportIssues.find(
(issue) => issue.kind === "contract-mismatch" && issue.capability === request.capability,
);
- initialIssues.push(
- ...reportIssues.filter(
- (issue) => issue.kind !== "contract-mismatch" || issue.capability !== request.capability,
- ),
- );
+ // Other capabilities' mismatches are bumped by their own --update runs and
+ // re-reported by the closing check, so they do not block this one.
+ initialIssues.push(...reportIssues.filter((issue) => issue.kind !== "contract-mismatch"));
if (selectedMismatch === undefined) {
initialIssues.push({
file: toPosix(relative(REPO_ROOT, COMPATIBILITY_SOURCE)),
diff --git a/scripts/guard-invariants.mjs b/scripts/guard-invariants.mjs
index 117aaeb57..4c52926a7 100644
--- a/scripts/guard-invariants.mjs
+++ b/scripts/guard-invariants.mjs
@@ -303,6 +303,10 @@ const WORKFLOW_QUEUE_NAMESPACE_MODULE = "packages/eve/src/internal/workflow/queu
* @param {Violation[]} violations
*/
function checkRule33(posix, lines, violations) {
+ // The single-runtime-identity boundary is eve's own source. Application code
+ // (fixtures, templates) legitimately imports the public `workflow/api`
+ // surface, which eve's bundler resolves to its own runtime.
+ if (!posix.startsWith("packages/eve/src/")) return;
lines.forEach((line, idx) => {
const isTypeOnlyImport = /^\s*(?:import|export)\s+type\b/.test(line);
const isRuntimeImport =