The Open Framework for Building Agents
feat(eve): sleep - run as a workflow tool (#2917)
Andrew Barba3b7307395015
diff --git a/.changeset/calm-tools-sleep.md b/.changeset/calm-tools-sleep.mdnew file mode 100644index 000000000..34a9ec56d--- /dev/null+++ b/.changeset/calm-tools-sleep.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Run each opt-in `sleep` tool call as its own durable workflow. Parallel calls still resume the turn after the longest wait, while sleep now follows the same execution and cancellation lifecycle as other workflow-backed tools.diff --git a/docs/concepts/built-in-tools.md b/docs/concepts/built-in-tools.mdindex d7a9ca435..735907dfb 100644--- a/docs/concepts/built-in-tools.md+++ b/docs/concepts/built-in-tools.md@@ -134,7 +134,7 @@ import { sleep } from "eve/tools/sleep";export default sleep();```-The model calls it with `{ seconds }` when it is useful to wait before checking progress or status again. The pause sleeps the durable turn workflow, so it does not hold an application runtime open, and the same turn continues automatically when the duration elapses. If one model response makes concurrent `sleep` calls, eve waits for the longest requested duration.+The model calls it with `{ seconds }` when it is useful to wait before checking progress or status again. Each call runs as a durable tool workflow, so it does not hold an application runtime open, and the same turn continues automatically when the duration elapses. Concurrent `sleep` calls run in parallel, so the turn continues after the longest requested duration.## What to read nextdiff --git a/packages/eve/scripts/build-rolldown.mjs b/packages/eve/scripts/build-rolldown.mjsindex 2f6ad7a73..a12eeff38 100644--- a/packages/eve/scripts/build-rolldown.mjs+++ b/packages/eve/scripts/build-rolldown.mjs@@ -103,6 +103,28 @@ function createDynamicToolTransformPlugin() {};}+/**+ * Keeps framework workflow bodies available to the downstream driver builder+ * while stamping the same callback metadata that application modules receive+ * from their client transform.+ */+function createWorkflowMetadataTransformPlugin() {+ let transformPromise;+ return {+ name: "eve:workflow-metadata-transform",+ async transform(code, id) {+ if (!code.includes("use workflow")) return null;+ transformPromise ??= import("../src/internal/workflow-bundle/workflow-builders.ts").then(+ (mod) => mod.applyWorkflowTransform,+ );+ const transformFn = await transformPromise;+ const filename = relative(process.cwd(), id).replaceAll("\\", "/");+ const result = await transformFn(filename, code, "metadata", id, process.cwd());+ return result.code === code ? null : { code: result.code, map: null };+ },+ };+}+const SRC_ROOT = "src";const OUTPUT_DIR = "dist/src";@@ -233,7 +255,11 @@ await buildWithNitroRolldown({input,external: isExternalPackageSpecifier,platform: "node",- plugins: [createStripUnusedRolldownRuntimeImportPlugin(), createDynamicToolTransformPlugin()],+ plugins: [+ createStripUnusedRolldownRuntimeImportPlugin(),+ createDynamicToolTransformPlugin(),+ createWorkflowMetadataTransformPlugin(),+ ],resolve: {// `eve-source` makes `#*.js` resolve to `./src/*.ts` at build time so// sibling source files become part of the graph instead of barediff --git a/packages/eve/src/compiler/normalize-manifest.test.ts b/packages/eve/src/compiler/normalize-manifest.test.tsindex 65f72e4a7..1bbca6f0c 100644--- a/packages/eve/src/compiler/normalize-manifest.test.ts+++ b/packages/eve/src/compiler/normalize-manifest.test.ts@@ -114,6 +114,35 @@ describe("compileAgentManifest source graph", () => {expect(() => validateCompiledModuleMap(compiled, moduleMap)).not.toThrow();});+ it("derives workflow handling from programmatic executor metadata", async () => {+ const execute = async () => ({ ok: true });+ Reflect.set(execute, "workflowId", "workflow//example/tool//execute");+ const sourceRegistry = registry([+ {+ logicalPath: "tools/durable.ts",+ loadNamespace: async () => ({+ default: defineTool({+ description: "Runs durably.",+ execute,+ inputSchema: { type: "object" },+ }),+ }),+ },+ ]);++ const compiled = await compileAgentManifest(manifest(), {+ sourceRegistries: [sourceRegistry],+ });++ expect(compiled.tools.find((tool) => tool.name === "durable")?.behavior).toEqual({+ availability: [],+ handling: {+ kind: "workflow-tool",+ workflowId: "workflow//example/tool//execute",+ },+ });+ });+it("preserves selected native behavior through serialization and runtime preparation", async () => {const sourceRegistry = registry([{diff --git a/packages/eve/src/compiler/normalize-tool.ts b/packages/eve/src/compiler/normalize-tool.tsindex e2be83cc9..4f6756e71 100644--- a/packages/eve/src/compiler/normalize-tool.ts+++ b/packages/eve/src/compiler/normalize-tool.ts@@ -6,9 +6,7 @@ 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";+import { readWorkflowFunctionId } from "#internal/workflow/reference.js";/*** Compiled tool entry produced from one authored `tools/*.ts` file.@@ -108,7 +106,7 @@ export async function compileToolEntry(};}- const workflowId = await readToolWorkflowId(options.binding);+ const workflowId = readWorkflowFunctionId(entry.definition.execute);return {kind: "tool",definition: {@@ -131,12 +129,3 @@ 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/execution/inline-turn.ts b/packages/eve/src/execution/inline-turn.tsindex 767023eda..ed89d2ea1 100644--- a/packages/eve/src/execution/inline-turn.ts+++ b/packages/eve/src/execution/inline-turn.ts@@ -83,7 +83,6 @@ export async function runInlineTurn(input: {if (control.initialCancellation !== undefined ||result.action === "cancelled" ||- result.sleepDurationMs !== undefined ||(result.backgroundTasks?.length ?? 0) > 0) {return childOutcome(control, initialStep);diff --git a/packages/eve/src/execution/next-driver-action.ts b/packages/eve/src/execution/next-driver-action.tsindex 1ffc4930d..2ed457345 100644--- a/packages/eve/src/execution/next-driver-action.ts+++ b/packages/eve/src/execution/next-driver-action.ts@@ -31,7 +31,6 @@ export type DurableStepResult = (readonly action: "continue" | "done";readonly output?: unknown;readonly isError?: boolean;- readonly sleepDurationMs?: number;readonly usage?: TokenUsage;readonly usageDelta?: TokenUsage;}@@ -43,13 +42,11 @@ export type DurableStepResult = (readonly hasPendingAuthorization: boolean;readonly hasPendingInputBatch: boolean;readonly pendingCoordinationCallIds?: readonly string[];- readonly sleepDurationMs?: number;readonly settled?: SettledTurn;}| {readonly action: "dispatch-workflow-tasks";readonly pendingTaskCallIds: readonly string[];- readonly sleepDurationMs?: number;}) &DurableStepResultFields;diff --git a/packages/eve/src/execution/tools/sleep-workflow.ts b/packages/eve/src/execution/tools/sleep-workflow.tsnew file mode 100644index 000000000..7f7eda358--- /dev/null+++ b/packages/eve/src/execution/tools/sleep-workflow.ts@@ -0,0 +1,11 @@+import { sleep } from "#compiled/@workflow/core/index.js";++import type { SleepToolInput, SleepToolOutput } from "#execution/tools/sleep.js";++/** Waits durably in a workflow dedicated to this tool call. */+export async function executeSleepTool(input: SleepToolInput): Promise<SleepToolOutput> {+ "use workflow";++ await sleep(Math.ceil(input.seconds * 1_000));+ return { waitedSeconds: input.seconds };+}diff --git a/packages/eve/src/execution/tools/sleep.ts b/packages/eve/src/execution/tools/sleep.tsindex 4e23d115f..c7ebeac08 100644--- a/packages/eve/src/execution/tools/sleep.ts+++ b/packages/eve/src/execution/tools/sleep.ts@@ -1,6 +1,6 @@import { z } from "#compiled/zod/index.js";-import { requestTurnSleep } from "#harness/turn-sleep.js";+export { executeSleepTool } from "#execution/tools/sleep-workflow.js";const MAX_SLEEP_SECONDS = Math.floor(Number.MAX_SAFE_INTEGER / 1_000);@@ -17,12 +17,3 @@ export const SLEEP_OUTPUT_SCHEMA = z.strictObject({export type SleepToolInput = z.infer<typeof SLEEP_INPUT_SCHEMA>;export type SleepToolOutput = z.infer<typeof SLEEP_OUTPUT_SCHEMA>;--/**- * Records a durable wait for the owning turn workflow to fulfill after the- * current atomic step finishes.- */-export function executeSleepTool(input: SleepToolInput): SleepToolOutput {- requestTurnSleep(Math.ceil(input.seconds * 1_000));- return { waitedSeconds: input.seconds };-}diff --git a/packages/eve/src/execution/tools/workflow/workflow-tool-run.integration.test.ts b/packages/eve/src/execution/tools/workflow/workflow-tool-run.integration.test.tsindex d4f34ac0e..ec8cd8793 100644--- a/packages/eve/src/execution/tools/workflow/workflow-tool-run.integration.test.ts+++ b/packages/eve/src/execution/tools/workflow/workflow-tool-run.integration.test.ts@@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest";import { ROOT_COMPILED_AGENT_NODE_ID } from "#compiler/manifest.js";import { sessionCommandHookToken } from "#execution/session-command-token.js";+import { executeSleepTool, SLEEP_INPUT_SCHEMA } from "#execution/tools/sleep.js";import { resumeSessionInbox } from "#execution/wire/session-inbox-resume.js";import { workflowEntry } from "#execution/workflow-entry.js";import { createTestRuntime, type TestRuntime } from "#internal/testing/app-harness.js";@@ -53,12 +54,13 @@ function buildSerializedContext(input: {async function createWorkflowToolRuntime(input: {readonly agentName: string;readonly execute: (...args: never[]) => unknown;+ readonly inputSchema?: ResolvedToolDefinition["inputSchema"];readonly toolName: string;}): Promise<TestRuntime> {const tool: ResolvedToolDefinition = {description: `Deploys a service (${input.toolName}).`,execute: input.execute as ResolvedToolDefinition["execute"],- inputSchema: DEPLOY_INPUT_SCHEMA,+ inputSchema: input.inputSchema ?? DEPLOY_INPUT_SCHEMA,logicalPath: `tools/${input.toolName}.ts`,name: input.toolName,owner: { kind: "application" },@@ -71,7 +73,7 @@ async function createWorkflowToolRuntime(input: {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 },+ default: { description: tool.description, execute: input.execute },};// The compiler derives the workflow id from authored source; an in-memory tool// has none, so record the id the test tier's transform stamped on the fixture.@@ -130,6 +132,31 @@ function eventsText(events: readonly { readonly data?: unknown }[]): string {}describe("workflow tools", () => {+ it("runs the framework sleep tool through the workflow tool path", async () => {+ const runtime = await createWorkflowToolRuntime({+ agentName: "workflow-tool-sleep",+ execute: executeSleepTool,+ inputSchema: SLEEP_INPUT_SCHEMA,+ toolName: "sleep",+ });++ const output = await runtime.run(async () => {+ const run = await start(workflowEntry, [+ {+ input: { message: "Run sleep" },+ serializedContext: buildSerializedContext({+ continuationToken: "schedule:workflow-tool-sleep",+ mode: "task",+ }),+ },+ ]);+ const result = await run.returnValue;+ return String(result.output);+ });++ expect(output).toContain('"waitedSeconds":1');+ });+it("parks the turn on a workflow tool and resumes with its return value", async () => {const runtime = await createWorkflowToolRuntime({agentName: "workflow-tool-wait",diff --git a/packages/eve/src/execution/turn-workflow.test.ts b/packages/eve/src/execution/turn-workflow.test.tsindex 406d93cea..b93582cbb 100644--- a/packages/eve/src/execution/turn-workflow.test.ts+++ b/packages/eve/src/execution/turn-workflow.test.ts@@ -23,7 +23,6 @@ import { recordWorkflowToolRun } from "#harness/workflow-tool-runs.js";const resumeHookMock = vi.fn();const createHookMock = vi.fn();-const sleepMock = vi.fn(async (_duration: unknown) => {});const definedHookPayloads = new Map<string, readonly unknown[]>();function createDefinedHookMock(token: string, values: readonly unknown[]): unknown {@@ -54,7 +53,6 @@ vi.mock("#compiled/@workflow/core/index.js", () => ({resume: async () => null,}),getWorkflowMetadata: vi.fn(() => ({ url: "https://eve.example.com" })),- sleep: (duration: unknown) => sleepMock(duration),}));vi.mock("#compiled/@workflow/core/runtime.js", () => ({@@ -106,7 +104,6 @@ describe("turnWorkflow", () => {vi.clearAllMocks();resumeHookMock.mockReset();createHookMock.mockReset();- sleepMock.mockClear();vi.mocked(applyTaskAgentRequest).mockReset();vi.mocked(releaseAgentInvocationOwnerStep).mockReset();vi.mocked(cancelAgentInvocationOwnerStep).mockReset();@@ -286,60 +283,6 @@ describe("turnWorkflow", () => {);});- it("durably sleeps the turn before continuing the tool loop", async () => {- const sessionState = createSessionState();- vi.mocked(turnStep)- .mockResolvedValueOnce({- action: "continue",- sleepDurationMs: 2_500,- serializedContext: { state: "sleeping" },- sessionState,- })- .mockResolvedValueOnce({- action: "done",- output: "checked again",- serializedContext: { state: "done" },- sessionState,- });-- const { input } = createInput({ sessionState });- await turnWorkflow(input);-- expect(sleepMock).toHaveBeenCalledExactlyOnceWith(2_500);- expect(sleepMock.mock.invocationCallOrder[0]).toBeLessThan(- vi.mocked(turnStep).mock.invocationCallOrder[1]!,- );- });-- it("durably sleeps a turn-owned workflow before continuing the tool loop", async () => {- const sessionState = createSessionState();- installInbox([]);- vi.mocked(turnStep)- .mockResolvedValueOnce({- action: "continue",- sleepDurationMs: 1_250,- serializedContext: { state: "sleeping" },- sessionState,- })- .mockResolvedValueOnce({- action: "done",- output: "checked again",- serializedContext: { state: "done" },- sessionState,- });-- const { input } = createInput({- driverCapabilities: { turnInbox: true },- sessionState,- });- await turnWorkflow(input);-- expect(sleepMock).toHaveBeenCalledExactlyOnceWith(1_250);- expect(sleepMock.mock.invocationCallOrder[0]).toBeLessThan(- vi.mocked(turnStep).mock.invocationCallOrder[1]!,- );- });-it("parks when an authorization is pending", async () => {const sessionState = createSessionState();vi.mocked(turnStep).mockResolvedValueOnce({diff --git a/packages/eve/src/execution/turn-workflow.ts b/packages/eve/src/execution/turn-workflow.tsindex cd8b9ee5c..4842d386e 100644--- a/packages/eve/src/execution/turn-workflow.ts+++ b/packages/eve/src/execution/turn-workflow.ts@@ -6,11 +6,7 @@ import {isInboxSubagentResultFromRecordedWorkflowToolRun,isInboxToolResultFromRecordedWorkflowToolRun,} from "#harness/workflow-tool-runs.js";-import {- createHook,- getWorkflowMetadata,- sleep as workflowSleep,-} from "#compiled/@workflow/core/index.js";+import { createHook, getWorkflowMetadata } from "#compiled/@workflow/core/index.js";import type { DeliverHookPayload } from "#channel/types.js";import { preserveSerializedSessionDynamicModelSelection } from "#context/serialized-dynamic-model-selection.js";@@ -195,14 +191,6 @@ async function runTurnOwnedWorkflow(input: TurnWorkflowInput): Promise<void> {return;}- if (result.sleepDurationMs !== undefined) {- const outcome = await waitForTurnSleep(result.sleepDurationMs, cancellation);- if (outcome === "cancel") {- await finishCancelledTurn({ bufferedDeliveries, cancellation, cursor });- return;- }- }-if (result.action === "done") {await cancellation?.dispose();await cursor.finish(@@ -326,15 +314,6 @@ async function finishCancelledTurn(input: {);}-async function waitForTurnSleep(- durationMs: number,- cancellation: TurnCancellationControl | undefined,-): Promise<"cancel" | "slept"> {- if (cancellation?.signal.aborted === true) return "cancel";- const slept = workflowSleep(durationMs).then(() => "slept" as const);- return cancellation === undefined ? slept : Promise.race([slept, cancellation.requested]);-}-// These sentinels stay outside `RuntimeActionResult`. That union is the// schema-validated wire type projected into harness resume calls; these are// turn-workflow control outcomes that never leave the workflow.@@ -522,10 +501,6 @@ async function runLegacyTurnWorkflow(input: TurnWorkflowInput): Promise<void> {while (true) {const result = await turnStep(currentStepInput);- if (result.action !== "cancelled" && result.sleepDurationMs !== undefined) {- await workflowSleep(result.sleepDurationMs);- }-if (result.action === "done") {await sendTurnControlStep({controlToken: input.completionToken,diff --git a/packages/eve/src/execution/workflow-steps.test.ts b/packages/eve/src/execution/workflow-steps.test.tsindex 6246de3a5..1f78b1be5 100644--- a/packages/eve/src/execution/workflow-steps.test.ts+++ b/packages/eve/src/execution/workflow-steps.test.ts@@ -28,7 +28,6 @@ import {import { BundleKey, ChannelKey } from "#runtime/sessions/runtime-context-keys.js";import { serializeContext } from "#context/serialize.js";import { getPendingCoordinationBatch, setPendingCoordinationBatch } from "#harness/coordination.js";-import { requestTurnSleep } from "#harness/turn-sleep.js";import { TurnCancelledError } from "#harness/turn-cancellation.js";import { getPendingAuthorization, setPendingAuthorization } from "#harness/authorization.js";import { getProxyInputRequests, upsertProxyInputRequests } from "#harness/proxy-input-requests.js";@@ -2132,36 +2131,6 @@ describe("turnStep", () => {expect(observedInput).toBeUndefined();});- it("projects a requested sleep onto the durable step result", async () => {- const session = createStubSession();- installSessionStoreMocks([session]);- vi.mocked(createExecutionNodeStep).mockImplementation(() => {- return async (stepSession): Promise<StepResult> => {- requestTurnSleep(2_500);- return {- next: async () => ({ next: null, session: stepSession }),- session: stepSession,- };- };- });-- const result = await turnStep({- input: {- kind: "deliver",- payloads: [{ message: "wait before checking" }],- },- parentWritable: createTestWritable(),- serializedContext: createSerializedContext(),- sessionState: createStubSessionState(),- });-- expect(result).toMatchObject({- action: "continue",- sleepDurationMs: 2_500,- });- expect(result.serializedContext).not.toHaveProperty("eve.pendingTurnSleepDuration");- });-it("persists onDeliver context into the next durable step", async () => {const seenMessages: string[] = [];const session = createStubSession();diff --git a/packages/eve/src/execution/workflow-steps.ts b/packages/eve/src/execution/workflow-steps.tsindex d90c98651..1abf98021 100644--- a/packages/eve/src/execution/workflow-steps.ts+++ b/packages/eve/src/execution/workflow-steps.ts@@ -44,7 +44,6 @@ import { preserveSerializedInstrumentationState } from "#instrumentation/state.jimport { RuntimeActionSettlementTimesKey } from "#harness/runtime-action-settlement-state.js";import { preserveSerializedAgentTraceState } from "#tracing/agent-trace-context-store.js";import { matchAuthorizationCallbacks } from "#execution/authorization-callback-match.js";-import { readTurnSleepDurationMs } from "#harness/turn-sleep.js";import { isTurnCancellation, throwIfTurnAborted } from "#harness/turn-cancellation.js";import { setChannelContext } from "#execution/channel-context.js";import { observeSessionActivity } from "#execution/session-activity-projection.js";@@ -583,8 +582,6 @@ export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResustepResult = { ...stepResult, session: rekeyed };const nextState = createDurableSessionState({ session: stepResult.session });- const sleepDurationMs = readTurnSleepDurationMs(ctx);- const sleepTransition = sleepDurationMs === undefined ? {} : { sleepDurationMs };const backgroundTransition =stepResult.backgroundTasks === undefined || stepResult.backgroundTaskSession === undefined? {}@@ -611,7 +608,6 @@ export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResu...backgroundTransition,output: stepResult.next.output,isError: stepResult.next.isError,- ...sleepTransition,serializedContext: nextSerializedContext,sessionState: nextState,usage: sessionTotals === undefined ? undefined : toUsage(sessionTotals),@@ -628,7 +624,6 @@ export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResuaction: "dispatch-workflow-tasks",...backgroundTransition,pendingTaskCallIds: getWorkflowTaskCallIds(workflowInterrupt.interrupt),- ...sleepTransition,serializedContext: nextSerializedContext,sessionState: nextState,};@@ -646,7 +641,6 @@ export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResuaction: "park",...backgroundTransition,...pending,- ...sleepTransition,serializedContext: nextSerializedContext,sessionState: createDurableSessionState({ session: reportedSession }),settled: {@@ -661,7 +655,6 @@ export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResuaction: "park",...backgroundTransition,...pending,- ...sleepTransition,serializedContext: nextSerializedContext,sessionState: nextState,};@@ -671,7 +664,6 @@ export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResureturn {action: "continue",...backgroundTransition,- ...sleepTransition,serializedContext: nextSerializedContext,sessionState: nextState,};diff --git a/packages/eve/src/harness/turn-sleep.ts b/packages/eve/src/harness/turn-sleep.tsdeleted file mode 100644index d4da47d4e..000000000--- a/packages/eve/src/harness/turn-sleep.ts+++ /dev/null@@ -1,34 +0,0 @@-import { type AlsContext, type ContextContainer, loadContext } from "#context/container.js";-import { ContextKey } from "#context/key.js";--const PendingTurnSleepDurationKey = new ContextKey<number>("eve.pendingTurnSleepDuration");--/**- * Requests a durable pause before the turn's next action.- *- * The request is step-local: tool execution records it in virtual context,- * then `turnStep` projects it onto its result for `turnWorkflow` to fulfill.- * Concurrent sleep calls share the wait, so the longest requested duration- * wins.- */-export function requestTurnSleep(durationMs: number): void {- if (!Number.isSafeInteger(durationMs) || durationMs <= 0) {- throw new Error("Sleep duration must resolve to a positive safe integer of milliseconds.");- }-- const ctx = loadContext();- const pendingDurationMs = ctx.get(PendingTurnSleepDurationKey) ?? 0;- asContainer(ctx).setVirtualContext(- PendingTurnSleepDurationKey,- Math.max(pendingDurationMs, durationMs),- );-}--/** Returns the longest sleep requested during the current turn step. */-export function readTurnSleepDurationMs(ctx: AlsContext): number | undefined {- return ctx.get(PendingTurnSleepDurationKey);-}--function asContainer(ctx: AlsContext): ContextContainer {- return ctx as ContextContainer;-}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.tsindex e2b99bb25..369c79944 100644--- a/packages/eve/src/internal/workflow-bundle/authored-workflow-modules.integration.test.ts+++ b/packages/eve/src/internal/workflow-bundle/authored-workflow-modules.integration.test.ts@@ -5,10 +5,7 @@ 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";+import { discoverAuthoredWorkflowModules } from "./authored-workflow-modules.js";let appRoot: string;@@ -153,49 +150,3 @@ export default defineTool({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.tsindex 931f429f0..dd3ea77f5 100644--- a/packages/eve/src/internal/workflow-bundle/authored-workflow-modules.ts+++ b/packages/eve/src/internal/workflow-bundle/authored-workflow-modules.ts@@ -9,11 +9,7 @@ import {import { prepareAuthoredWorkflowDirectives } from "./authored-workflow-directives.js";import { isWorkflowSourceFile } from "./builder-support.js";-import {- authoredWorkflowId,- isAuthoredApplicationModule,- isAuthoredApplicationRoot,-} from "./workflow-builders.js";+import { isAuthoredApplicationModule, isAuthoredApplicationRoot } from "./workflow-builders.js";// The SDK's own ignore list (`BaseBuilder.getInputFiles`) plus eve's generated locations.const IGNORED_DIRECTORIES = new Set([@@ -99,24 +95,3 @@ async function collectSourceFiles(root: string): Promise<string[]> {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.scenario.test.ts b/packages/eve/src/internal/workflow-bundle/builder.scenario.test.tsindex 0c5598825..d9465bf91 100644--- a/packages/eve/src/internal/workflow-bundle/builder.scenario.test.ts+++ b/packages/eve/src/internal/workflow-bundle/builder.scenario.test.ts@@ -659,6 +659,45 @@ describe("WorkflowBundleBuilder", () => {}});+ it("keeps the sleep tool schemas out of the workflow driver", async () => {+ const tempRoot = await mkdtemp(join(tmpdir(), "eve-workflow-bundle-sleep-tool-"));+ const outDir = join(tempRoot, "workflow-build");+ const compiledArtifactsBootstrapPath = join(tempRoot, "compiled-artifacts-bootstrap.mjs");+ const sleepWorkflowPath = resolvePackageSourceFilePath("src/execution/tools/sleep-workflow.ts");++ try {+ await writeFile(compiledArtifactsBootstrapPath, "export {};\n");++ const builder = new FixtureWorkflowBundleBuilder(+ {+ agentName: "test-agent",+ appRoot: tempRoot,+ compiledArtifactsBootstrapPath,+ outDir,+ rootDir: resolvePackageRoot(),+ watch: false,+ },+ [sleepWorkflowPath],+ );++ await builder.build();++ const workflowsSource = await readFile(join(outDir, "workflows.mjs"), "utf8");+ const encodedChunksMatch = workflowsSource.match(+ /Buffer\.from\((\[[\s\S]*?\])\.join\(""\), "base64"\)\.toString\("utf8"\)/,+ );+ expect(encodedChunksMatch).not.toBeNull();++ const encodedChunks = JSON.parse(encodedChunksMatch?.[1] ?? "[]") as string[];+ const decodedWorkflowCode = Buffer.from(encodedChunks.join(""), "base64").toString("utf8");++ expect(decodedWorkflowCode).toContain("executeSleepTool");+ expect(decodedWorkflowCode).not.toContain("compiled/zod");+ } finally {+ await rm(tempRoot, { force: true, recursive: true });+ }+ });+it("allows a node builtin used only inside a use step body", async () => {const tempRoot = await mkdtemp(join(tmpdir(), "eve-workflow-bundle-node-step-ok-"));const outDir = join(tempRoot, "workflow-build");diff --git a/packages/eve/src/internal/workflow-bundle/workflow-builders.test.ts b/packages/eve/src/internal/workflow-bundle/workflow-builders.test.tsindex 08199d706..8d7284524 100644--- a/packages/eve/src/internal/workflow-bundle/workflow-builders.test.ts+++ b/packages/eve/src/internal/workflow-bundle/workflow-builders.test.ts@@ -2,7 +2,11 @@ import { readFileSync } from "node:fs";import { describe, expect, it } from "vitest";-import { resolvePackageRoot, resolvePackageSourceFilePath } from "#internal/application/package.js";+import {+ resolveInstalledPackageInfo,+ resolvePackageRoot,+ resolvePackageSourceFilePath,+} from "#internal/application/package.js";import { applyWorkflowTransform } from "./workflow-builders.js";import { transformWorkflowDirectives } from "./workflow-transformer.js";@@ -50,6 +54,31 @@ describe("applyWorkflowTransform", () => {);});+ it("stamps versioned package workflow metadata without consuming the framework body", async () => {+ const filename = "src/execution/tools/sleep.ts";+ const transformed = await applyWorkflowTransform(+ filename,+ [+ "export async function executeSleepTool(): Promise<string> {",+ ' "use workflow";',+ ' return "done";',+ "}",+ "",+ ].join("\n"),+ "metadata",+ resolvePackageSourceFilePath(filename),+ resolvePackageRoot(),+ );++ expect(transformed.code).toContain('"use workflow";');+ expect(transformed.code).toContain('return "done";');+ const packageInfo = resolveInstalledPackageInfo();+ expect(transformed.code).toContain(+ `executeSleepTool.workflowId = "workflow//${packageInfo.name}@${packageInfo.version}//executeSleepTool";`,+ );+ expect(transformed.code).not.toContain("__private_workflows.set");+ });+it("registers step functions in step mode", async () => {const transformed = await applyWorkflowTransform("steps/ping.ts",diff --git a/packages/eve/src/internal/workflow-bundle/workflow-builders.ts b/packages/eve/src/internal/workflow-bundle/workflow-builders.tsindex 992758ead..17c14ec35 100644--- a/packages/eve/src/internal/workflow-bundle/workflow-builders.ts+++ b/packages/eve/src/internal/workflow-bundle/workflow-builders.ts@@ -5,13 +5,13 @@ import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";import { STABLE_WORKFLOW_NAMES } from "#execution/stable-workflow-names.js";import { EVE_PACKAGE_NAME } from "#internal/package-name.js";import { SUBAGENT_TOOL_EXECUTE_WORKFLOW_NAME } from "#runtime/subagents/workflow-reference.js";-import { prepareAuthoredWorkflowDirectives } from "./authored-workflow-directives.js";+import { prepareAuthoredWorkflowDirectives } from "#internal/workflow-bundle/authored-workflow-directives.js";import {createWorkflowId,findWorkflowDirectiveFunctions,stripJavaScriptExtension,transformWorkflowDirectives,-} from "./workflow-transformer.js";+} from "#internal/workflow-bundle/workflow-transformer.js";export type WorkflowManifest = {steps?: {@@ -52,7 +52,7 @@ const projectDepsCache = new Map<string, Set<string>>();export async function applyWorkflowTransform(filename: string,source: string,- mode: "workflow" | "step" | "client" | false,+ mode: "workflow" | "step" | "client" | "metadata" | false,absolutePath?: string,projectRoot?: string,stableWorkflowNames: ReadonlySet<string> = new Set([@@ -73,6 +73,7 @@ export async function applyWorkflowTransform(const { moduleSpecifier, stableModuleSpecifier } = resolveModuleSpecifier(absoluteFilename,resolvedProjectRoot,+ mode === "metadata",);if (@@ -212,6 +213,7 @@ export function getImportPath(function resolveModuleSpecifier(filePath: string,projectRoot: string,+ packageBuild: boolean = false,): {moduleSpecifier: string | undefined;stableModuleSpecifier: string | undefined;@@ -220,6 +222,13 @@ function resolveModuleSpecifier(const inWorkspace = !inNodeModules && isWorkspacePackage(filePath, projectRoot);const pkg = findPackageJson(filePath);+ if (packageBuild && pkg !== null) {+ return {+ moduleSpecifier: `${pkg.name}@${pkg.version}`,+ stableModuleSpecifier: pkg.name,+ };+ }+if (!inNodeModules && !inWorkspace) {return {moduleSpecifier: undefined,diff --git a/packages/eve/src/internal/workflow-bundle/workflow-transformer.ts b/packages/eve/src/internal/workflow-bundle/workflow-transformer.tsindex 89069b262..d96a43464 100644--- a/packages/eve/src/internal/workflow-bundle/workflow-transformer.ts+++ b/packages/eve/src/internal/workflow-bundle/workflow-transformer.ts@@ -21,7 +21,7 @@ const BUILTIN_STEP_NAMES = new Set(["__builtin_set_attributes",]);-type WorkflowDirectiveMode = "workflow" | "step" | "client" | false;+type WorkflowDirectiveMode = "workflow" | "step" | "client" | "metadata" | false;type DirectiveFunction = {directive: WorkflowDirective;@@ -151,6 +151,8 @@ export async function transformWorkflowDirectives(input: {start: fn.rangeStart,text: `${exportPrefix}var ${fn.name} = globalThis[Symbol.for("WORKFLOW_USE_STEP")](${JSON.stringify(stepId)});`,});+ } else if (input.mode === "metadata") {+ continue;} else {replacements.push({ end: fn.directiveEnd, start: fn.directiveStart, text: "" });@@ -177,6 +179,8 @@ export async function transformWorkflowDirectives(input: {suffixes.push(`globalThis.${WORKFLOW_REGISTRY_GLOBAL}.set(${JSON.stringify(workflowId)}, ${fn.name});`,);+ } else if (input.mode === "metadata") {+ suffixes.push(`${fn.name}.workflowId = ${JSON.stringify(workflowId)};`);} else {replacements.push({end: fn.directiveEnd,diff --git a/packages/eve/src/internal/workflow/reference.ts b/packages/eve/src/internal/workflow/reference.tsnew file mode 100644index 000000000..b0f2ea2ce--- /dev/null+++ b/packages/eve/src/internal/workflow/reference.ts@@ -0,0 +1,6 @@+/** Reads build-generated workflow identity from a transformed callback. */+export function readWorkflowFunctionId(value: unknown): string | undefined {+ if (typeof value !== "function") return undefined;+ const workflowId = Reflect.get(value, "workflowId");+ return typeof workflowId === "string" && workflowId.length > 0 ? workflowId : undefined;+}diff --git a/packages/eve/src/tools/provided/sleep.test.ts b/packages/eve/src/tools/provided/sleep.test.tsindex 7996f5f68..b6d05f4f9 100644--- a/packages/eve/src/tools/provided/sleep.test.ts+++ b/packages/eve/src/tools/provided/sleep.test.ts@@ -1,32 +1,41 @@-import { describe, expect, it } from "vitest";+import { afterEach, describe, expect, it, vi } from "vitest";-import { ContextContainer, contextStorage } from "#context/container.js";-import { readTurnSleepDurationMs } from "#harness/turn-sleep.js";+import { sleep as workflowSleep } from "#compiled/@workflow/core/index.js";import { sleep } from "#tools/provided/sleep.js";+vi.mock("#compiled/@workflow/core/index.js", () => ({+ sleep: vi.fn(),+}));+describe("sleep", () => {- it("defines a model-facing tool that requests a turn sleep in seconds", async () => {- const definition = sleep();- const ctx = new ContextContainer();+ afterEach(() => {+ vi.clearAllMocks();+ });- const output = await contextStorage.run(ctx, () =>- definition.execute({ seconds: 2.5 }, {} as never),- );+ it("defines a model-facing tool", () => {+ const definition = sleep();expect(definition.description).toContain("before continuing");- expect(output).toEqual({ waitedSeconds: 2.5 });- expect(readTurnSleepDurationMs(ctx)).toBe(2_500);+ expect(definition.execute).toBeTypeOf("function");});- it("shares concurrent waits by keeping the longest duration", async () => {+ it("waits for the requested number of seconds in its workflow body", async () => {+ let wake: (() => void) | undefined;+ vi.mocked(workflowSleep).mockImplementation(+ () =>+ new Promise<void>((resolve) => {+ wake = resolve;+ }),+ );const definition = sleep();- const ctx = new ContextContainer();+ const output = definition.execute({ seconds: 2.5001 }, {} as never);- await contextStorage.run(ctx, async () => {- await definition.execute({ seconds: 4 }, {} as never);- await definition.execute({ seconds: 1 }, {} as never);+ await vi.waitFor(() => {+ expect(workflowSleep).toHaveBeenCalledExactlyOnceWith(2_501);});- expect(readTurnSleepDurationMs(ctx)).toBe(4_000);+ wake?.();++ await expect(output).resolves.toEqual({ waitedSeconds: 2.5001 });});});diff --git a/packages/eve/src/tools/provided/sleep.ts b/packages/eve/src/tools/provided/sleep.tsindex 91ffb6f99..79a8e9576 100644--- a/packages/eve/src/tools/provided/sleep.ts+++ b/packages/eve/src/tools/provided/sleep.ts@@ -21,8 +21,8 @@ export type { SleepToolInput, SleepToolOutput };* export default sleep();* ```*- * Calls pause the durable turn workflow rather than holding an application- * runtime open with an in-process timer.+ * Each call runs as a durable workflow, so the wait does not hold an+ * application runtime open.*/export function sleep(): ToolDefinition<SleepToolInput, SleepToolOutput> {return defineTool({diff --git a/packages/eve/test/scenarios/compile-agent.scenario.test.ts b/packages/eve/test/scenarios/compile-agent.scenario.test.tsindex fd28795a5..a666c17f3 100644--- a/packages/eve/test/scenarios/compile-agent.scenario.test.ts+++ b/packages/eve/test/scenarios/compile-agent.scenario.test.ts@@ -156,6 +156,38 @@ describe("compiler artifacts", () => {);});+ it("compiles the provided sleep definition as a workflow tool", async () => {+ const { agentRoot, appRoot } = await createAppRoot(+ "eve-compiler-workflow-sleep-",+ APP_ROOT_OPTIONS,+ );+ await mkdir(join(agentRoot, "tools"), { recursive: true });+ await writeFile(join(agentRoot, "instructions.md"), "Wait when requested.");+ await writeFile(+ join(agentRoot, "tools", "sleep.mjs"),+ 'import { sleep } from "eve/tools/sleep";\nexport default sleep();\n',+ );++ const result = await compileAgent({ startPath: appRoot });+ const packageInfo = resolveInstalledPackageInfo();++ expect(result.manifest.tools).toContainEqual(+ expect.objectContaining({+ behavior: {+ availability: [],+ handling: {+ kind: "workflow-tool",+ workflowId: `workflow//${packageInfo.name}@${packageInfo.version}//executeSleepTool`,+ },+ },+ logicalPath: "tools/sleep.mjs",+ name: "sleep",+ sourceId: "tools/sleep.mjs",+ sourceKind: "module",+ }),+ );+ });+it("writes stable discovery artifacts under .eve", async () => {const { agentRoot, appRoot } = await createAppRoot("eve-compiler-artifacts-", APP_ROOT_OPTIONS);