The Open Framework for Building Agents
feat(eve): add dynamic workflows (#3310)
Rui8bc931f7bc05
diff --git a/.changeset/add-dynamic-workflows.md b/.changeset/add-dynamic-workflows.mdnew file mode 100644index 000000000..c4dc522e9--- /dev/null+++ b/.changeset/add-dynamic-workflows.md@@ -0,0 +1,5 @@+---+"eve": minor+---++Add the `workflow` factory from `eve/tools/workflow` for running model-supplied JavaScript through durable `ctx.agent` calls. Remove the experimental uppercase `Workflow` tool and `experimental_workflow`; migrate its tool file to the new lowercase factory.diff --git a/docs/guides/dynamic-capabilities.md b/docs/guides/dynamic-capabilities.mdindex 27fa46ba5..86016278e 100644--- a/docs/guides/dynamic-capabilities.md+++ b/docs/guides/dynamic-capabilities.md@@ -136,9 +136,9 @@ shadows the session selection for that turn, including when the turn handlerreturns `null`. If a resolver throws or returns an invalid definition, eve logs thefailure and omits the subagent.-The resolved set applies to local and remote direct delegation. Background subagents are not-exposed inside the model-authored `Workflow` tool. eve-also checks availability again before starting the child, so a stale or+The resolved set applies to local and remote direct delegation. An authored workflow tool can+also call a selected subagent through `ctx.agent`. A generated program can call it through the+provided `workflow` tool. eve checks availability again before starting the child, so a stale ormanually constructed call fails with `SUBAGENT_UNAVAILABLE`. Treat conditionalavailability as capability composition, not as the only authorizationboundary: sensitive child tools still need their own authorization anddiff --git a/docs/reference/typescript-api.md b/docs/reference/typescript-api.mdindex f0fbe0ba0..a0fceb87c 100644--- a/docs/reference/typescript-api.md+++ b/docs/reference/typescript-api.md@@ -55,9 +55,9 @@ export default defineTool({| `mockModel` | `eve/evals` | Deterministic fixture agent models | [Evals](../evals/overview) || `useEveAgent` | `eve/react`, `eve/vue`, `eve/svelte` | frontend | [Frontend](../guides/frontend/overview) |-Tool-wide authoring helpers and types such as `defineTool`, `defineWorkflowTool`, `defineDurableCallback`, `defineDynamic`, `disableTool`, and `ToolLabelDefinition` come from `eve/tools`. Capability-specific definitions and helpers use their own subpaths (see [Built-in tools](../concepts/built-in-tools)): reusable definitions such as `bash` and `glob` come from `eve/tools/<name>`, `webSearch` comes from `eve/tools/web_search`, `experimental_workflow` comes from `eve/tools/workflow`, `sleep` comes from `eve/tools/sleep`, and approval policies and types come from `eve/tools/approval`. The route verbs `GET`/`HEAD`/`POST`/`PUT`/`PATCH`/`DELETE`/`OPTIONS`/`WS` plus `disableRoute` come from `eve/channels`, and the channel auth helpers `localDev`/`vercelOidc`/`placeholderAuth` come from `eve/channels/auth`.+Tool-wide authoring helpers and types such as `defineTool`, `defineWorkflowTool`, `defineDurableCallback`, `defineDynamic`, `disableTool`, and `ToolLabelDefinition` come from `eve/tools`. Capability-specific definitions and helpers use their own subpaths (see [Built-in tools](../concepts/built-in-tools)): reusable definitions such as `bash` and `glob` come from `eve/tools/<name>`, `webSearch` comes from `eve/tools/web_search`, `sleep` comes from `eve/tools/sleep`, and approval policies and types come from `eve/tools/approval`. The route verbs `GET`/`HEAD`/`POST`/`PUT`/`PATCH`/`DELETE`/`OPTIONS`/`WS` plus `disableRoute` come from `eve/channels`, and the channel auth helpers `localDev`/`vercelOidc`/`placeholderAuth` come from `eve/channels/auth`.-`AgentReasoningDefinition` is exported from `eve` for the top-level `defineAgent({ reasoning })` setting. `AgentLimitsDefinition` is exported for `defineAgent({ limits })`. `AgentWorkflowDefinition`, `AgentWorkflowRetentionDefinition`, and `AgentWorkflowWorldDefinition` are exported from `eve` for the `defineAgent({ experimental: { workflow } })` config shape. `ExperimentalWorkflowToolInput` is exported from `eve/tools/workflow`; `WebSearchToolInput` and `WebSearchProvider` are exported from `eve/tools/web_search`.+`AgentReasoningDefinition` is exported from `eve` for the top-level `defineAgent({ reasoning })` setting. `AgentLimitsDefinition` is exported for `defineAgent({ limits })`. `AgentWorkflowDefinition`, `AgentWorkflowRetentionDefinition`, and `AgentWorkflowWorldDefinition` are exported from `eve` for the `defineAgent({ experimental: { workflow } })` config shape. `WebSearchToolInput` and `WebSearchProvider` are exported from `eve/tools/web_search`.`defineInstructions` accepts `{ content: string, role?: "system" | "user" }`; omitted `role` means `"system"`. Its `eve/instructions` version of `defineDynamic` accepts only `session.started` and `turn.started` handlers returning `defineInstructions(...)` or `null`. The legacy `{ markdown: string }` definition remains available as a deprecated system-role form.@@ -74,11 +74,11 @@ cross resolved instances.eve evaluates TypeScript definition modules during compilation so it can validate and normalize the agent. Within one agent node, each module namespace loads at most once during that compile. The resolved definition then determines whether the module is also an entry in the runtime bundle:-| Lifecycle | Authored definitions |-| ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| Compile only | Static instructions and skills, prompt-form TypeScript schedules, static Gateway or default agent config, provider-managed web search, `Workflow` configuration, fully shadowed channels, and a child sandbox that selects its parent's sandbox |-| Compile and runtime | Dynamic instructions, skills, tools, models, and subagents; executable tools; effective channels; connections; hooks; memory; handler schedules; direct-provider models; independent sandboxes; and remote subagents |-| Runtime only | Instrumentation modules and extension mount initialization |+| Lifecycle | Authored definitions |+| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| Compile only | Static instructions and skills, prompt-form TypeScript schedules, static Gateway or default agent config, provider-managed web search, Workflow SDK configuration, fully shadowed channels, and a child sandbox that selects its parent's sandbox |+| Compile and runtime | Dynamic instructions, skills, tools, models, and subagents; executable tools; effective channels; connections; hooks; memory; handler schedules; direct-provider models; independent sandboxes; and remote subagents |+| Runtime only | Instrumentation modules and extension mount initialization |A compile-only module is not imported when the deployed runtime starts. For example, eve stores the resolved content from a static `instructions.ts` in the compiled manifest. A compile-and-runtime module is evaluated during compilation and imported again when a runtime process loads the module map. Keep module-top-level work deterministic, and put request- or session-specific work in the definition's runtime callbacks.@@ -116,7 +116,7 @@ import template from "../../prompts/template.txt?raw";| `eve/tools/{bash,read_file,write_file,todo,web_fetch,load_skill,glob,grep}` | Individual reusable tool definitions || `eve/tools/approval` | Approval types and `always`, `once`, `never` || `eve/tools/web_search` | Provider-managed `webSearch` configuration |-| `eve/tools/workflow` | Experimental `Workflow` tool definition |+| `eve/tools/workflow` | Runtime-generated `workflow` tool factory || `eve/tools/sleep` | Opt-in durable `sleep` tool || `eve/connections` | `defineMcpClientConnection`, `defineOpenAPIConnection`, `defineDynamic` || `eve/channels` | `defineChannel`, `disableRoute`, route verbs |diff --git a/docs/subagents/index.mdx b/docs/subagents/index.mdxindex 5acf92d42..f3d76d78e 100644--- a/docs/subagents/index.mdx+++ b/docs/subagents/index.mdx@@ -32,7 +32,7 @@ The root session receives `agent` by default. The model calls it to delegate a t}```-The copy uses the root's instructions, connections, auth, and sandbox. It receives the same tools except for the root-only `agent` and `Workflow`, and starts with fresh conversation history and fresh state. Its file writes are immediately visible to the root. The built-in `agent` always runs in the background and needs no configuration: each call returns `{ status: "working", taskId, agentId }`, then task notifications wake the parent with completion, failure, or cancellation. Give parallel children non-overlapping write scopes.+The copy uses the root's instructions, connections, auth, and sandbox. It receives the same tools except for the root-only `agent`, and starts with fresh conversation history and fresh state. Its file writes are immediately visible to the root. The built-in `agent` always runs in the background and needs no configuration: each call returns `{ status: "working", taskId, agentId }`, then task notifications wake the parent with completion, failure, or cancellation. Give parallel children non-overlapping write scopes.`agent` is intentionally root-only. Copies created by it cannot call `agent`, and declared subagents never receive the built-in tool. If a stale or forced recursive call reaches execution, eve rejects it instead of starting another child session.@@ -199,7 +199,7 @@ eve lowers every subagent visible to the current agent (the root built-in copy,Declared subagents can call nested subagents defined under their own directories. eve does not apply a separate depth limit; nesting ends where the authored directory tree ends. The built-in `agent` follows the stricter root-only rule above, so `limits.maxSubagentDepth` no longer exists.-Child sessions can still call their own declared or remote subagents, but they receive neither `Workflow` nor the built-in `agent`. Background subagents run through the model tool loop and are not available inside a model-authored `Workflow` program.+Child sessions can still call their own declared or remote subagents, but they do not receive the built-in `agent`. Authored workflow tools use the same subagent availability and authorization checks as direct delegation.A directly declared subagent's tool name is the bare path-derived name, with no prefix. `agent/subagents/researcher/` registers as the tool `researcher`. A subagent supplied by a mounted extension includes the mount namespace, such as `crm__reviewer`. The model, approvals, logs, and evals reference the resulting name. Its input schema is:diff --git a/docs/tools/workflows.mdx b/docs/tools/workflows.mdxindex 56e38f8d2..0fd4ed196 100644--- a/docs/tools/workflows.mdx+++ b/docs/tools/workflows.mdx@@ -99,7 +99,62 @@ workflow and step modules reachable from the agent's runtime modules. Unrelatedin the host application stay outside the agent bundle. An unresolved workflow import failsthe build with the missing import in the error.-### Migrate an existing workflow tool+### Add a runtime-generated workflow tool++Create `agent/tools/workflow.ts` and export the provided `workflow` factory when the model should+supply the JavaScript program at runtime:++```ts title="agent/tools/workflow.ts"+import { workflow } from "eve/tools/workflow";++export default workflow({ maxSubagents: 20 });+```++The model supplies an async function body through the tool's `js` input. Its only host capability is+`ctx.agent(name, { message, agentId?, outputSchema? })`. For example:++```js+const [triage, review] = await Promise.all([+ ctx.agent("ticket-triage", { message: JSON.stringify(tickets) }),+ ctx.agent("ticket-review", { message: JSON.stringify(tickets) }),+]);+return { triage, review };+```++`maxSubagents` defaults to `100` and must be an integer from `1` through `128`. The generated+program cannot access the workflow context, session state,+credentials, imports, or ordinary tools. Agent authorization, questions, approvals, cancellation,+and `agentId` continuation use the same owner-managed behavior as direct `ctx.agent` calls.++The sandbox resumes after every pending call in the current batch settles. `Promise.all` supports+fan-out followed by fan-in, but `Promise.race` does not resume after only the first child settles.+A child failure is thrown at the corresponding `ctx.agent` call, so generated code can catch it.+The program must return a JSON-serializable value.++### Migrate from `experimental_workflow`++The experimental uppercase `Workflow` framework tool and its exports have been removed. Replace the+old sentinel:++```diff+-import { experimental_workflow } from "eve/tools/workflow";+-+-export default experimental_workflow({ maxSubagents: 20 });+```++with the lowercase factory:++```ts+import { workflow } from "eve/tools/workflow";++export default workflow({ maxSubagents: 20 });+```++The path gives the authored tool the model-facing name `workflow`. eve does not discover or inject+an agent catalog. Calls use the same target resolution, availability, and authorization checks as+`ctx.agent` in any other authored workflow tool.++### Migrate an authored workflow toolReplace `defineTool` with `defineWorkflowTool`, keep the executor's `"use workflow"` directive,and replace `agent(ctx, input)` and `ask(ctx, request)` with `ctx.agent(target, input)` anddiff --git a/e2e/fixtures/agent-cancellation/agent/agent.ts b/e2e/fixtures/agent-cancellation/agent/agent.tsindex b8db1a47e..e9c2b5d3b 100644--- a/e2e/fixtures/agent-cancellation/agent/agent.ts+++ b/e2e/fixtures/agent-cancellation/agent/agent.ts@@ -3,6 +3,7 @@ import { defineAgent } from "eve";import type { MockModelRequest, MockModelResponse } from "eve/evals";const RECOVERY_REQUEST = "RESUME-CANCELLED-SLEEPER";+const HITL_REQUEST = "GENERATED-PROGRAM-CHILD-HITL";function respond(request: MockModelRequest): MockModelResponse | string {const message = request.lastUserMessage ?? "";@@ -33,14 +34,23 @@ function respond(request: MockModelRequest): MockModelResponse | string {.join("\n");}if (message.includes("call the sleeper subagent")) {+ const hitl = message.includes(HITL_REQUEST);+ const hitlResult = request.toolResults.find((entry) => entry.id === "hitl-sleeper");+ if (hitlResult !== undefined) {+ return typeof hitlResult.output === "string"+ ? hitlResult.output+ : JSON.stringify(hitlResult.output);+ }return {toolCalls: [{- id: "cancel-sleeper",+ id: hitl ? "hitl-sleeper" : "cancel-sleeper",input: {- js: 'return await tools["sleeper"]({ message: "Call the wait-for-cancellation tool exactly once and wait until this delegated turn is cancelled." });',+ js: hitl+ ? `return await ctx.agent("sleeper", { message: ${JSON.stringify(HITL_REQUEST)} });`+ : 'return await ctx.agent("sleeper", { message: "Call the wait-for-cancellation tool exactly once and wait until this delegated turn is cancelled." });',},- name: "Workflow",+ name: "workflow",},],};@@ -63,9 +73,9 @@ function respond(request: MockModelRequest): MockModelResponse | string {{id: "resume-sleeper",input: {- js: `return await tools["sleeper"]({ agentId: ${agentId}, message: ${JSON.stringify(RECOVERY_REQUEST)} });`,+ js: `return await ctx.agent("sleeper", { agentId: ${agentId}, message: ${JSON.stringify(RECOVERY_REQUEST)} });`,},- name: "Workflow",+ name: "workflow",},],};diff --git a/e2e/fixtures/agent-cancellation/agent/subagents/sleeper/agent.ts b/e2e/fixtures/agent-cancellation/agent/subagents/sleeper/agent.tsindex e39e49104..a736facdd 100644--- a/e2e/fixtures/agent-cancellation/agent/subagents/sleeper/agent.ts+++ b/e2e/fixtures/agent-cancellation/agent/subagents/sleeper/agent.ts@@ -3,21 +3,40 @@ import { defineAgent } from "eve";const RECOVERY_REQUEST = "RESUME-CANCELLED-SLEEPER";const RECOVERY_RESULT = "CANCELLED-SUBAGENT-RECOVERED";+const HITL_REQUEST = "GENERATED-PROGRAM-CHILD-HITL";export default defineAgent({description: "Waits until its delegated turn is cancelled, then supports a recovery probe.",...e2eSubagentConfig({- mock: ({ lastUserMessage }) =>- lastUserMessage?.includes(RECOVERY_REQUEST) === true- ? RECOVERY_RESULT- : {- toolCalls: [- {- id: "wait-for-cancellation",- input: {},- name: "wait-for-cancellation",- },- ],+ mock: ({ lastUserMessage, toolResults }) => {+ if (lastUserMessage?.includes(RECOVERY_REQUEST) === true) return RECOVERY_RESULT;+ if (lastUserMessage?.includes(HITL_REQUEST) === true) {+ const answer = toolResults.find((result) => result.id === "child-question");+ return answer === undefined+ ? {+ toolCalls: [+ {+ id: "child-question",+ input: {+ allowFreeform: true,+ options: [],+ prompt: "What marker should the child return?",+ },+ name: "ask_question",+ },+ ],+ }+ : `CHILD_HITL_RESULT=${JSON.stringify(answer.output)}`;+ }+ return {+ toolCalls: [+ {+ id: "wait-for-cancellation",+ input: {},+ name: "wait-for-cancellation",},+ ],+ };+ },}),});diff --git a/e2e/fixtures/agent-cancellation/agent/subagents/sleeper/instructions.md b/e2e/fixtures/agent-cancellation/agent/subagents/sleeper/instructions.mdindex 28a1b05ef..b409d3e7d 100644--- a/e2e/fixtures/agent-cancellation/agent/subagents/sleeper/instructions.md+++ b/e2e/fixtures/agent-cancellation/agent/subagents/sleeper/instructions.md@@ -5,5 +5,6 @@ You are a cancellation test sleeper.# Rules- If the message contains `RESUME-CANCELLED-SLEEPER`, do not call any tool. Reply with exactly `CANCELLED-SUBAGENT-RECOVERED`.+- If the message contains `GENERATED-PROGRAM-CHILD-HITL`, call `ask_question` exactly once with the prompt `What marker should the child return?`, then reply with `CHILD_HITL_RESULT=` followed by the answer.- Otherwise, call `wait-for-cancellation` exactly once, immediately, with no preamble.- Do not call any other tool.diff --git a/e2e/fixtures/agent-cancellation/agent/tools/workflow.ts b/e2e/fixtures/agent-cancellation/agent/tools/workflow.tsindex 8dafe3e7f..42bd11960 100644--- a/e2e/fixtures/agent-cancellation/agent/tools/workflow.ts+++ b/e2e/fixtures/agent-cancellation/agent/tools/workflow.ts@@ -1,3 +1,3 @@-import { experimental_workflow } from "eve/tools/workflow";+import { workflow } from "eve/tools/workflow";-export default experimental_workflow();+export default workflow();diff --git a/e2e/fixtures/agent-cancellation/evals/cancellation/cancel-subagent.eval.ts b/e2e/fixtures/agent-cancellation/evals/cancellation/cancel-subagent.eval.tsindex af927a81e..3b5278607 100644--- a/e2e/fixtures/agent-cancellation/evals/cancellation/cancel-subagent.eval.ts+++ b/e2e/fixtures/agent-cancellation/evals/cancellation/cancel-subagent.eval.ts@@ -13,7 +13,7 @@ export default defineEval({// Explicit directive phrasing keeps the delegation deterministic so a// scripted mock responder can drive this eval in the world suites.const parent = await t.start(- "Use the Workflow tool exactly once to call the sleeper subagent with message 'Call the wait-for-cancellation tool exactly once and wait until this delegated turn is cancelled.' Return the sleeper result.",+ "Use the workflow tool exactly once to call the sleeper subagent with message 'Call the wait-for-cancellation tool exactly once and wait until this delegated turn is cancelled.' Return the sleeper result.",);const called = await parent.waitForEvent("subagent.called", {data: { name: "sleeper" },@@ -71,9 +71,9 @@ export default defineEval({const resumed = await t.send([- "Use the Workflow tool exactly once.",- `In its JavaScript, call sleeper with agentId ${JSON.stringify(agentId)} and message ${JSON.stringify(RECOVERY_REQUEST)}.`,- "Return the inline result and reply with it verbatim. Do not call sleeper outside Workflow.",+ "Use the workflow tool exactly once.",+ `In its JavaScript, call ctx.agent for sleeper with agentId ${JSON.stringify(agentId)} and message ${JSON.stringify(RECOVERY_REQUEST)}.`,+ "Return the inline result and reply with it verbatim. Do not call sleeper outside workflow.",].join(" "),);resumed.expectOk();diff --git a/e2e/fixtures/agent-cancellation/evals/cancellation/generated-program-child-hitl.eval.ts b/e2e/fixtures/agent-cancellation/evals/cancellation/generated-program-child-hitl.eval.tsnew file mode 100644index 000000000..444dd4efb--- /dev/null+++ b/e2e/fixtures/agent-cancellation/evals/cancellation/generated-program-child-hitl.eval.ts@@ -0,0 +1,31 @@+import { defineEval } from "eve/evals";++export default defineEval({+ description: "A generated workflow program proxies a child question through the existing owner.",+ timeoutMs: 120_000,+ async test(t) {+ await t.send(+ "Use the workflow tool exactly once to call the sleeper subagent with the message GENERATED-PROGRAM-CHILD-HITL. Return the child result.",+ );+ const request = t.requireInputRequest({+ prompt: "What marker should the child return?",+ toolName: "ask_question",+ });+ if (request.kind !== "question") throw new Error("Child input request is not a question.");++ const resumed = await t.respond([+ { requestId: request.requestId, text: "GENERATED-HITL-MARKER" },+ ]);+ resumed.expectOk();++ t.succeeded();+ t.calledTool("workflow", {+ count: 1,+ output: /CHILD_HITL_RESULT=.*GENERATED-HITL-MARKER/su,+ });+ t.calledSubagent("sleeper", { count: 1, status: "pending" });+ t.messageIncludes("CHILD_HITL_RESULT=");+ t.messageIncludes("GENERATED-HITL-MARKER");+ t.noFailedActions();+ },+});diff --git a/e2e/fixtures/agent-prompt-cache/agent/agent.ts b/e2e/fixtures/agent-prompt-cache/agent/agent.tsindex 7f3fdd453..8de030968 100644--- a/e2e/fixtures/agent-prompt-cache/agent/agent.ts+++ b/e2e/fixtures/agent-prompt-cache/agent/agent.ts@@ -1,8 +1,18 @@import { e2eAgentConfig } from "@eve-e2e/config";import { defineAgent } from "eve";+const config = e2eAgentConfig();+export default defineAgent({- ...e2eAgentConfig(),+ ...config,+ // Measure Anthropic cache reuse through its native provider.+ ...(typeof config.model === "string" && config.model.startsWith("anthropic/")+ ? {+ modelOptions: {+ providerOptions: { gateway: { only: ["anthropic"] } },+ },+ }+ : {}),reasoning: "high",limits: { maxInputTokensPerSession: 300_000 },});diff --git a/e2e/fixtures/agent-subagents/agent/subagents/ticket-reproducer/agent.ts b/e2e/fixtures/agent-subagents/agent/subagents/ticket-reproducer/agent.tsnew file mode 100644index 000000000..7862fd23e--- /dev/null+++ b/e2e/fixtures/agent-subagents/agent/subagents/ticket-reproducer/agent.ts@@ -0,0 +1,9 @@+import { e2eSubagentConfig } from "@eve-e2e/config";+import { defineAgent } from "eve";++export default defineAgent({+ description:+ "Software-factory reproduction planner. Give this agent completed triage and review results to produce a concrete reproduction artifact.",+ ...e2eSubagentConfig(),+ reasoning: "high",+});diff --git a/e2e/fixtures/agent-subagents/agent/subagents/ticket-reproducer/instructions.md b/e2e/fixtures/agent-subagents/agent/subagents/ticket-reproducer/instructions.mdnew file mode 100644index 000000000..c7d3c2a29--- /dev/null+++ b/e2e/fixtures/agent-subagents/agent/subagents/ticket-reproducer/instructions.md@@ -0,0 +1 @@+You are the reproduction stage in a software-factory pipeline. Read the supplied triage and review objects and return only an object matching the requested output schema. Set `combinedKey` to the triage `derivedKey`, a `|`, and the review `derivedKey`; set `sampleTicket` to the triage `priorityTicket`; derive the run token by removing `:triage` from the triage key; and set `testCase` to `test("RUN_TOKEN", () => expect(runSyntheticRegression()).not.toThrow());` with RUN_TOKEN replaced by that token. Do not invent values or redo triage or review.diff --git a/e2e/fixtures/agent-subagents/agent/subagents/ticket-review/agent.ts b/e2e/fixtures/agent-subagents/agent/subagents/ticket-review/agent.tsnew file mode 100644index 000000000..1913a0f79--- /dev/null+++ b/e2e/fixtures/agent-subagents/agent/subagents/ticket-review/agent.ts@@ -0,0 +1,9 @@+import { e2eSubagentConfig } from "@eve-e2e/config";+import { defineAgent } from "eve";++export default defineAgent({+ description:+ "Software-factory backlog reviewer. Give this agent a synthetic ticket batch to produce an independent review summary before reproduction planning.",+ ...e2eSubagentConfig(),+ reasoning: "high",+});diff --git a/e2e/fixtures/agent-subagents/agent/subagents/ticket-review/instructions.md b/e2e/fixtures/agent-subagents/agent/subagents/ticket-review/instructions.mdnew file mode 100644index 000000000..418180a6e--- /dev/null+++ b/e2e/fixtures/agent-subagents/agent/subagents/ticket-review/instructions.md@@ -0,0 +1 @@+You are the independent review stage in a software-factory pipeline. Read the complete supplied ticket array and return only an object matching the requested output schema. Set `ticketCount` from the array length, `accepted` to true only when all 200 ids are unique, and `derivedKey` to the unique `reviewKey` found in the tickets. Do not invent values or perform triage or reproduction work.diff --git a/e2e/fixtures/agent-subagents/agent/subagents/ticket-triage/agent.ts b/e2e/fixtures/agent-subagents/agent/subagents/ticket-triage/agent.tsnew file mode 100644index 000000000..2a12443e2--- /dev/null+++ b/e2e/fixtures/agent-subagents/agent/subagents/ticket-triage/agent.ts@@ -0,0 +1,9 @@+import { e2eSubagentConfig } from "@eve-e2e/config";+import { defineAgent } from "eve";++export default defineAgent({+ description:+ "Software-factory ticket triage specialist. Give this agent a synthetic ticket batch to classify before review or reproduction planning.",+ ...e2eSubagentConfig(),+ reasoning: "high",+});diff --git a/e2e/fixtures/agent-subagents/agent/subagents/ticket-triage/instructions.md b/e2e/fixtures/agent-subagents/agent/subagents/ticket-triage/instructions.mdnew file mode 100644index 000000000..d02edcacb--- /dev/null+++ b/e2e/fixtures/agent-subagents/agent/subagents/ticket-triage/instructions.md@@ -0,0 +1 @@+You are the triage stage in a software-factory pipeline. Read the complete supplied ticket array and return only an object matching the requested output schema. Set `ticketCount` from the array length, `priorityTicket` to the first ticket id, and `derivedKey` to the unique `triageKey` found in the tickets. Do not invent values or perform review or reproduction work.diff --git a/e2e/fixtures/agent-subagents/agent/tools/workflow.ts b/e2e/fixtures/agent-subagents/agent/tools/workflow.tsindex 2dc9657d0..7994fb16a 100644--- a/e2e/fixtures/agent-subagents/agent/tools/workflow.ts+++ b/e2e/fixtures/agent-subagents/agent/tools/workflow.ts@@ -1,3 +1,3 @@-import { experimental_workflow } from "eve/tools/workflow";+import { workflow } from "eve/tools/workflow";-export default experimental_workflow({ maxSubagents: 2 });+export default workflow({ maxSubagents: 3 });diff --git a/e2e/fixtures/agent-subagents/evals/dynamic-workflow.eval.ts b/e2e/fixtures/agent-subagents/evals/dynamic-workflow.eval.tsindex 0321c386f..cbe176827 100644--- a/e2e/fixtures/agent-subagents/evals/dynamic-workflow.eval.ts+++ b/e2e/fixtures/agent-subagents/evals/dynamic-workflow.eval.ts@@ -15,41 +15,51 @@ function isFanOutProgram(input: unknown): boolean {);}-/** Dynamic Workflow smoke: sandboxed JavaScript fans out durable children. */+/** Generated workflow-program smoke: sandboxed JavaScript fans out durable children. */export default defineEval({tags: ["real-model"],description:- "Dynamic Workflow smoke: model-authored JavaScript fans out two local subagent calls and combines their results.",+ "Generated workflow-program smoke: model-authored JavaScript fans out two local subagent calls and combines their results.",async test(t) {- const turn = await t.send(- "Use the Workflow tool exactly once to fan out two independent echo-marker subagent calls. In its JavaScript, create the messages 'workflow alpha' and 'workflow beta', map them through echo-marker inside Promise.all, and return the resulting two-element array. Do not call echo-marker outside Workflow. Then reply with the returned array verbatim as JSON.",+ const parent = await t.start(+ "Use the workflow tool exactly once to fan out two independent echo-marker subagent calls. In its JavaScript, create the messages 'workflow alpha' and 'workflow beta', map them through ctx.agent calls to echo-marker inside Promise.all, and return the resulting two-element array. Do not call echo-marker outside workflow. Then reply with the returned array verbatim as JSON.",);-- t.succeeded();- t.calledTool("Workflow", { input: isFanOutProgram, count: 1 });- // Workflow delivery can replay either event; count logical calls, not deliveries.- turn.eventsSatisfy("both distinct children start before either completes", (events) => {- const called = new Map<string, number>();- const completed = new Map<string, number>();- for (const [index, event] of events.entries()) {- if (event.type === "subagent.called" && event.data.name === "echo-marker") {- if (!called.has(event.data.callId)) called.set(event.data.callId, index);- }- if (event.type === "subagent.completed" && event.data.subagentName === "echo-marker") {- if (!completed.has(event.data.callId)) completed.set(event.data.callId, index);- }- }- return (- called.size === 2 &&- completed.size === 2 &&- [...completed.keys()].every((callId) => called.has(callId)) &&- Math.max(...called.values()) < Math.min(...completed.values())- );+ const firstCalled = await parent.waitForEvent("subagent.called", {+ data: { name: "echo-marker" },});- t.calledSubagent("echo-marker", {- output: /SUBAGENT_TOKEN=echo-marker-9F2X/,- count: 2,+ const firstChild = t.target.watchTurn(firstCalled.data.childSessionId).result();+ const secondCalled = await parent.waitForEvent("subagent.called", {+ data: {+ callId: (callId) => callId !== firstCalled.data.callId,+ name: "echo-marker",+ },});+ if (secondCalled.data.childSessionId === firstCalled.data.childSessionId) {+ throw new Error("Parallel workflow calls reused one child session.");+ }+ const secondChild = t.target.watchTurn(secondCalled.data.childSessionId).result();+ const [turn, firstChildTurn, secondChildTurn] = await Promise.all([+ parent.result(),+ firstChild,+ secondChild,+ ]);+ const latestCallAt = [firstCalled.meta.at, secondCalled.meta.at].sort().at(-1)!;++ t.succeeded();+ t.calledTool("workflow", { input: isFanOutProgram, count: 1 });+ turn.calledSubagent("echo-marker", { count: 2, status: "pending" });+ firstChildTurn.eventsSatisfy(+ "first child does not complete before both children start",+ (events) =>+ events.some((event) => event.type === "turn.completed" && event.meta.at > latestCallAt),+ );+ secondChildTurn.eventsSatisfy(+ "second child does not complete before both children start",+ (events) =>+ events.some((event) => event.type === "turn.completed" && event.meta.at > latestCallAt),+ );+ firstChildTurn.messageIncludes(SUBAGENT_TOKEN);+ secondChildTurn.messageIncludes(SUBAGENT_TOKEN);t.messageIncludes(DOUBLE_SUBAGENT_TOKEN);t.noFailedActions();},diff --git a/e2e/fixtures/agent-subagents/evals/runtime-subagent-workflow.eval.ts b/e2e/fixtures/agent-subagents/evals/runtime-subagent-workflow.eval.tsdeleted file mode 100644index d513d995a..000000000--- a/e2e/fixtures/agent-subagents/evals/runtime-subagent-workflow.eval.ts+++ /dev/null@@ -1,44 +0,0 @@-import { defineEval } from "eve/evals";--const CHILD_TOKEN = "CHILD_WORKFLOW_TOOL_NOT_AVAILABLE";--/**- * Runtime subagent Workflow visibility: the root delegates to the built-in- * `agent` child, which should not receive the root-only `Workflow` wrapper.- */-export default defineEval({- tags: ["real-model"],- description: "Runtime subagent sessions do not receive the root-only Workflow tool.",- async test(t) {- const started = await t.send(- [- "Use the built-in agent subagent exactly once.",- "Give the child this task:",- "If a Workflow tool is visible, use Workflow exactly once to call echo-marker with message 'subagent workflow probe', then return WORKFLOW_WAS_VISIBLE.",- `If no Workflow tool is visible, do not call echo-marker or any other subagent. Return exactly ${CHILD_TOKEN}.`,- `After the child returns, reply with its exact output and no other token.`,- ].join(" "),- );- started.expectOk();-- const completed = await t.target- .watchTurn(started.sessionId, { startIndex: requireStreamIndex(t) })- .result();- completed.expectOk();- completed.messageIncludes(CHILD_TOKEN);-- t.succeeded();- t.calledSubagent("agent", { count: 1 });- t.notCalledTool("Workflow");- t.notEvent("subagent.called", { data: { name: "echo-marker" } });- t.noFailedActions();- },-});--function requireStreamIndex(session: {- readonly state?: { readonly streamIndex?: number };-}): number {- const streamIndex = session.state?.streamIndex;- if (streamIndex === undefined) throw new Error("Parent session has no stream index.");- return streamIndex;-}diff --git a/e2e/fixtures/agent-subagents/evals/software-factory-workflow.eval.ts b/e2e/fixtures/agent-subagents/evals/software-factory-workflow.eval.tsnew file mode 100644index 000000000..17626c29a--- /dev/null+++ b/e2e/fixtures/agent-subagents/evals/software-factory-workflow.eval.ts@@ -0,0 +1,119 @@+import { randomUUID } from "node:crypto";++import { defineEval } from "eve/evals";+import { equals } from "eve/evals/expect";++const TRIAGE = "ticket-triage";+const REVIEW = "ticket-review";+const REPRODUCE = "ticket-reproducer";++/** A workflow fans out ticket analysis and feeds both derived results into reproduction. */+export default defineEval({+ tags: ["real-model"],+ description:+ "The root agent runs parallel triage and review over 200 tickets, then passes both derived outputs into reproduction.",+ async test(t) {+ const token = randomUUID();+ const expected = expectedFactoryOutput(token);+ const turn = await t.send(+ [+ `FACTORY_RUN_TOKEN=${token}.`,+ "Alice is processing a manufactured software-factory backlog. Use the workflow tool exactly once, and do not call any of its subagents outside that program.",+ "Create a minimal array of exactly 200 tickets with ids `T-000` through `T-199`. Each ticket must contain only `id`, except `T-000` also has `triageKey` set to FACTORY_RUN_TOKEN:triage and `T-199` also has `reviewKey` set to FACTORY_RUN_TOKEN:review, replacing FACTORY_RUN_TOKEN with the supplied token.",+ "Use Promise.all to run ticket-triage and ticket-review concurrently, passing the complete tickets array to both calls. Use `outputSchema` to request exactly `{ ticketCount: integer, priorityTicket: string, derivedKey: string }` from ticket-triage and `{ ticketCount: integer, accepted: boolean, derivedKey: string }` from ticket-review.",+ "After both complete, call ticket-reproducer with the returned `{ triage, review }` objects and use `outputSchema` to request exactly `{ combinedKey: string, sampleTicket: string, testCase: string }`. Make every listed output field required and allow no additional output fields.",+ "Return `{ reproduction, review, triage }` and reply with only that returned JSON object.",+ ].join(" "),+ );++ turn.expectOk();+ t.succeeded();+ t.calledTool("workflow", { count: 1, output: exactOutput(expected) });+ t.calledSubagent(TRIAGE, { count: 1, status: "pending" });+ t.calledSubagent(REVIEW, { count: 1, status: "pending" });+ t.calledSubagent(REPRODUCE, { count: 1, status: "pending" });+ turn.eventsSatisfy("analysis fans out before reproduction consumes both results", (events) => {+ const called = new Map<string, number>();+ for (const [index, event] of events.entries()) {+ if (event.type === "subagent.called" && !called.has(event.data.name)) {+ called.set(event.data.name, index);+ }+ }++ const triageCalled = called.get(TRIAGE);+ const reviewCalled = called.get(REVIEW);+ const reproduceCalled = called.get(REPRODUCE);+ return (+ triageCalled !== undefined &&+ reviewCalled !== undefined &&+ reproduceCalled !== undefined &&+ Math.max(triageCalled, reviewCalled) < reproduceCalled+ );+ });+ await t.require(parseJsonMessage(turn.message), equals(expected));+ t.noFailedActions();+ },+});++function expectedFactoryOutput(token: string) {+ const triage = {+ derivedKey: `${token}:triage`,+ priorityTicket: "T-000",+ ticketCount: 200,+ };+ const review = {+ accepted: true,+ derivedKey: `${token}:review`,+ ticketCount: 200,+ };+ return {+ reproduction: {+ combinedKey: `${triage.derivedKey}|${review.derivedKey}`,+ sampleTicket: triage.priorityTicket,+ testCase: `test("${token}", () => expect(runSyntheticRegression()).not.toThrow());`,+ },+ review,+ triage,+ };+}++function exactOutput(expected: ReturnType<typeof expectedFactoryOutput>) {+ return (observed: unknown) => structurallyEqual(observed, expected);+}++function structurallyEqual(left: unknown, right: unknown): boolean {+ if (left === right) return true;+ if (Array.isArray(left) || Array.isArray(right)) {+ return (+ Array.isArray(left) &&+ Array.isArray(right) &&+ left.length === right.length &&+ left.every((value, index) => structurallyEqual(value, right[index]))+ );+ }+ if (left === null || right === null || typeof left !== "object" || typeof right !== "object") {+ return false;+ }+ const leftEntries = Object.entries(left);+ const rightRecord = right as Record<string, unknown>;+ return (+ leftEntries.length === Object.keys(rightRecord).length &&+ leftEntries.every(+ ([key, value]) =>+ Object.hasOwn(rightRecord, key) && structurallyEqual(value, rightRecord[key]),+ )+ );+}++function parseJsonMessage(message: string | undefined): unknown {+ if (message === undefined) return undefined;+ const trimmed = message.trim();+ const source = trimmed.startsWith("```json")+ ? trimmed.slice("```json".length, trimmed.endsWith("```") ? -3 : undefined).trim()+ : trimmed;+ try {+ return JSON.parse(source);+ } catch {+ return undefined;+ }+}diff --git a/e2e/fixtures/agent-subagents/evals/workflow-blocking-continuation.eval.ts b/e2e/fixtures/agent-subagents/evals/workflow-blocking-continuation.eval.tsindex 59c60d8cd..0be4e1521 100644--- a/e2e/fixtures/agent-subagents/evals/workflow-blocking-continuation.eval.ts+++ b/e2e/fixtures/agent-subagents/evals/workflow-blocking-continuation.eval.ts@@ -1,15 +1,15 @@import { defineEval } from "eve/evals";-/** Workflow calls block, can continue one child, and share one subagent budget. */+/** Generated workflow-program calls block, continue one child, and share one call budget. */export default defineEval({tags: ["real-model"],description:- "Workflow sandbox agent calls return inline, reuse agentId, and enforce maxSubagents.",+ "Generated workflow-program agent calls return inline, reuse agentId, and enforce maxSubagents.",async test(t) {const started = await t.send([- "Use the Workflow tool exactly once and call echo-marker inside it with message 'blocking first'.",- "Return the inline result and reply with it verbatim. Do not call echo-marker outside Workflow.",+ "Use the workflow tool exactly once and call ctx.agent for echo-marker inside it with message 'blocking first'.",+ "Return the inline result and reply with it verbatim. Do not call echo-marker outside workflow.",].join(" "),);started.expectOk();@@ -24,31 +24,31 @@ export default defineEval({const second = await (firstTurn?.session ?? t).send([- "Use the Workflow tool exactly once. In its JavaScript, call the same echo-marker child twice sequentially",- "using the agentId shown in the latest <agents> block, with messages 'blocking second' and 'blocking third'.",- "Then attempt a third call with that agentId and message 'blocking over limit'.",- "Return all three inline results and reply with them verbatim as JSON. Do not call echo-marker outside Workflow.",+ "Use the workflow tool exactly once. In its JavaScript, call the same echo-marker child three times sequentially with ctx.agent",+ "using the agentId shown in the latest <agents> block, with messages 'blocking second', 'blocking third', and 'blocking fourth'.",+ "Then attempt a fourth call with that agentId and message 'blocking over limit'.",+ "Catch the fourth call's error, return all three inline results followed by its message, and reply with that four-element array verbatim as JSON. Do not call echo-marker outside workflow.",].join(" "),);second.expectOk();t.succeeded();- t.calledTool("Workflow", { count: 2 });- t.calledSubagent("echo-marker", { count: 3 });- t.eventsSatisfy("all Workflow calls continue one child session", (events) => {+ t.calledTool("workflow", { count: 2 });+ t.calledSubagent("echo-marker", { count: 4, status: "pending" });+ t.eventsSatisfy("all workflow-program calls continue one child session", (events) => {const childSessionIds = events.flatMap((event) =>event.type === "subagent.called" && event.data.name === "echo-marker"? [event.data.childSessionId]: [],);return (- childSessionIds.length === 3 &&+ childSessionIds.length === 4 &&childSessionIds[0] !== undefined &&childSessionIds.every((sessionId) => sessionId === childSessionIds[0]));});t.messageIncludes("SUBAGENT_TOKEN=echo-marker-9F2X");- t.messageIncludes("WORKFLOW_SUBAGENT_LIMIT_REACHED");+ t.messageIncludes("WORKFLOW_PROGRAM_SUBAGENT_LIMIT_REACHED");},});diff --git a/e2e/fixtures/agent-subagents/evals/workflow-subagent-limit.eval.ts b/e2e/fixtures/agent-subagents/evals/workflow-subagent-limit.eval.tsindex 54d4f352b..5054519a3 100644--- a/e2e/fixtures/agent-subagents/evals/workflow-subagent-limit.eval.ts+++ b/e2e/fixtures/agent-subagents/evals/workflow-subagent-limit.eval.ts@@ -1,26 +1,57 @@import { defineEval } from "eve/evals";+const MESSAGES = ["limit alpha", "limit beta", "limit gamma", "limit delta"] as const;+const CHILD_TOKEN = "SUBAGENT_TOKEN=echo-marker-9F2X";+const LIMIT_ERROR = "WORKFLOW_PROGRAM_SUBAGENT_LIMIT_REACHED";++function isFourCallProgram(input: unknown): boolean {+ if (typeof input !== "object" || input === null) return false;+ const js = (input as { readonly js?: unknown }).js;+ if (typeof js !== "string") return false;+ const positions = MESSAGES.map((message) => js.indexOf(message));+ return (+ positions.every((position) => position >= 0) &&+ positions.every((position, index) => index === 0 || position > positions[index - 1]!) &&+ js.includes("ctx.agent") &&+ js.includes("catch")+ );+}++function isFourElementLimitResult(output: unknown): boolean {+ return (+ Array.isArray(output) &&+ output.length === 4 &&+ output.slice(0, 3).every((value) => typeof value === "string" && value.includes(CHILD_TOKEN)) &&+ typeof output[3] === "string" &&+ output[3].includes(LIMIT_ERROR)+ );+}+/**- * Workflow subagent budget: the fixture configures `maxSubagents` as 2 on the- * Workflow tool, so three sequential calls spawn two children and the third- * call resolves with a `WORKFLOW_SUBAGENT_LIMIT_REACHED` error after replay.+ * Generated-program subagent budget: the authored `workflow` tool passes+ * `maxSubagents: 3`, so four sequential calls spawn three children and the fourth+ * call throws a catchable `WORKFLOW_PROGRAM_SUBAGENT_LIMIT_REACHED` error after replay.*/export default defineEval({tags: ["real-model"],description:- "Sequential Workflow calls share one maxSubagents budget and resolve excess calls with WORKFLOW_SUBAGENT_LIMIT_REACHED.",+ "Sequential generated-program calls share one maxSubagents budget and resolve excess calls with WORKFLOW_PROGRAM_SUBAGENT_LIMIT_REACHED.",async test(t) {await t.send([- "This is a deliberate test of the Workflow subagent budget, so ignore the advertised call limit and attempt every call.",- "Use the Workflow tool exactly once. In its JavaScript, await three echo-marker subagent calls sequentially with the messages 'limit alpha', 'limit beta', and 'limit gamma', and return the resulting three-element array.",- "Do not call echo-marker outside Workflow and do not retry. Then reply with the returned array verbatim as JSON.",+ "This is a deliberate test of the generated-program subagent budget, so ignore the advertised call limit and attempt every call.",+ "Use the workflow tool exactly once. In its JavaScript, await four ctx.agent calls to echo-marker sequentially with the messages 'limit alpha', 'limit beta', 'limit gamma', and 'limit delta'.",+ "Catch the fourth call's error and return a four-element array containing the first three results followed by the caught error message. Do not call echo-marker outside workflow and do not retry. Then reply with the returned array verbatim as JSON.",].join(" "),);t.succeeded();- t.calledTool("Workflow", { count: 1 });- t.calledSubagent("echo-marker", { count: 2 });- t.messageIncludes("WORKFLOW_SUBAGENT_LIMIT_REACHED");+ t.calledTool("workflow", {+ count: 1,+ input: isFourCallProgram,+ output: isFourElementLimitResult,+ });+ t.calledSubagent("echo-marker", { count: 3, status: "pending" });+ t.messageIncludes("WORKFLOW_PROGRAM_SUBAGENT_LIMIT_REACHED");},});diff --git a/e2e/fixtures/agent-task-reporting/evals/event-matching.test.mjs b/e2e/fixtures/agent-task-reporting/evals/event-matching.test.mjsindex 4354a3ec5..83877d315 100644--- a/e2e/fixtures/agent-task-reporting/evals/event-matching.test.mjs+++ b/e2e/fixtures/agent-task-reporting/evals/event-matching.test.mjs@@ -114,9 +114,13 @@ test("proxy approvals in both ancestors do not count as nested probe executions"assert.deepEqual(toolEvidence(turns, "child", "probe"), []);});-test("only deduplicates event IDs within the owning session, including overlapping watches", () => {+test("deduplicates event and logical-call retries within the owning session", () => {const turns = snapshots();turns.push(...snapshots());+ turns.push({+ sessionId: "child",+ events: [requested("retried-request"), completed("retried-result")],+ });turns.push({sessionId: "sibling",events: [@@ -125,10 +129,19 @@ test("only deduplicates event IDs within the owning session, including overlappi],});assert.deepEqual(toolEvidence(turns, "child", "probe"), expected);- assert.equal(eventsForSession(turns, "child").length, 3);+ assert.equal(eventsForSession(turns, "child").length, 5);assert.deepEqual(toolEvidence(turns, "sibling", "probe")[0].inputs, [{ check: "second" }]);});+test("rejects a logical-call retry that changes its result", () => {+ const turns = snapshots();+ turns.push({+ sessionId: "child",+ events: [completed("changed-result", "probe-call", "completed", { result: "pears" })],+ });+ assert.throws(() => toolEvidence(turns, "child", "probe"), /tool result probe-call changed/);+});+test("does not join a same-call-ID request and result from different sessions", () => {const turns = snapshots();turns[2].sessionId = "sibling";@@ -141,8 +154,6 @@ for (const [name, extra] of ["a second execution with a new call ID",[requested("request-2", "second-call"), completed("result-2", "second-call")],],- ["a duplicate result event for the same call ID", [completed("result-2")]],- ["a duplicate request event for the same call ID", [requested("request-2")]],["an orphan completion", [completed("orphan", "unknown-call")]],["a pending extra call", [requested("pending", "pending-call")]],]) {diff --git a/e2e/fixtures/agent-task-reporting/evals/event-matching.ts b/e2e/fixtures/agent-task-reporting/evals/event-matching.tsindex fc187e739..c7cc7352d 100644--- a/e2e/fixtures/agent-task-reporting/evals/event-matching.ts+++ b/e2e/fixtures/agent-task-reporting/evals/event-matching.ts@@ -1,3 +1,5 @@+import { isDeepStrictEqual } from "node:util";+import type { EveEvalTurn, InputRequest } from "eve/evals";type Event = EveEvalTurn["events"][number];@@ -102,17 +104,29 @@ export function toolEvidence(}return entry;}+ function appendRetry<T>(values: T[], value: T, label: string): void {+ const previous = values[0];+ if (previous === undefined) {+ values.push(value);+ } else if (!isDeepStrictEqual(previous, value)) {+ throw new Error(`Retried ${label} changed its value.`);+ }+ }for (const event of eventsForSession(snapshots, sessionId)) {if (event.type === "actions.requested") {for (const action of event.data.actions) {if (action.kind === "tool-call" && action.toolName === toolName) {- call(action.callId).inputs.push(action.input);+ appendRetry(call(action.callId).inputs, action.input, `tool input ${action.callId}`);}}} else if (event.type === "action.result") {const { result, status } = event.data;if (result.kind === "tool-result" && result.toolName === toolName) {- call(result.callId).results.push({ status, output: result.output });+ appendRetry(+ call(result.callId).results,+ { status, output: result.output },+ `tool result ${result.callId}`,+ );}}}diff --git a/packages/eve/extension-contracts/current/tool.ts b/packages/eve/extension-contracts/current/tool.tsindex 9630b667b..42fa11ae3 100644--- a/packages/eve/extension-contracts/current/tool.ts+++ b/packages/eve/extension-contracts/current/tool.ts@@ -1,3 +1,3 @@export * from "../../src/public/tools/index.ts";-export * from "../../src/public/tools/workflow.ts";export * from "../../src/public/tools/web-search.ts";+export * from "../../src/public/tools/workflow.ts";diff --git a/packages/eve/extension-contracts/entrypoints/tool.ts b/packages/eve/extension-contracts/entrypoints/tool.tsindex 8ec5a2cdd..5849681a1 100644--- a/packages/eve/extension-contracts/entrypoints/tool.ts+++ b/packages/eve/extension-contracts/entrypoints/tool.ts@@ -7,12 +7,14 @@ export {toolOutputPart,toolResultFrom,} from "../../src/public/tools/index.ts";-export {- experimental_workflow,- isExperimentalWorkflowToolDefinition,-} from "../../src/public/tools/workflow.ts";export {defaultWebSearch,isWebSearchToolDefinition,webSearch,} from "../../src/public/tools/web-search.ts";+export {+ workflow,+ type WorkflowTool,+ type WorkflowToolInput,+ type WorkflowToolOptions,+} from "../../src/public/tools/workflow.ts";diff --git a/packages/eve/extension-contracts/reports/dynamicTool/v39.json b/packages/eve/extension-contracts/reports/dynamicTool/v39.jsonnew file mode 100644index 000000000..89a6b60d6--- /dev/null+++ b/packages/eve/extension-contracts/reports/dynamicTool/v39.json@@ -0,0 +1,14 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "dynamicTool",+ "epoch": 39,+ "sha256": "5bed2b325951759dfb19995747c44eb2dd2c5f6c814742f0252b4b09416fe3f2",+ "exports": [+ "DynamicToolEntry",+ "DynamicToolEvents",+ "DynamicToolResult",+ "DynamicToolSet",+ "defineDurableCallback",+ "defineDynamic"+ ]+}diff --git a/packages/eve/extension-contracts/reports/tool/v40.json b/packages/eve/extension-contracts/reports/tool/v40.jsonnew file mode 100644index 000000000..96c35cef0--- /dev/null+++ b/packages/eve/extension-contracts/reports/tool/v40.json@@ -0,0 +1,19 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "tool",+ "epoch": 40,+ "sha256": "6e19148f747bc7edddd32f0435dd3e42f09cb964f97b41f2383989a8915f00fb",+ "exports": [+ "defaultWebSearch",+ "defineTool",+ "defineWorkflowTool",+ "disableTool",+ "isDisabledToolSentinel",+ "isWebSearchToolDefinition",+ "runWorkflowProgram",+ "toolOutput",+ "toolOutputPart",+ "toolResultFrom",+ "webSearch"+ ]+}diff --git a/packages/eve/extension-contracts/reports/tool/v41.json b/packages/eve/extension-contracts/reports/tool/v41.jsonnew file mode 100644index 000000000..129b7a1cf--- /dev/null+++ b/packages/eve/extension-contracts/reports/tool/v41.json@@ -0,0 +1,22 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "tool",+ "epoch": 41,+ "sha256": "b55b7382728d5e07e9d57a228fa75ecb1142115711a266975b604fd7fdb9e025",+ "exports": [+ "WorkflowTool",+ "WorkflowToolInput",+ "WorkflowToolOptions",+ "defaultWebSearch",+ "defineTool",+ "defineWorkflowTool",+ "disableTool",+ "isDisabledToolSentinel",+ "isWebSearchToolDefinition",+ "toolOutput",+ "toolOutputPart",+ "toolResultFrom",+ "webSearch",+ "workflow"+ ]+}diff --git a/packages/eve/extension-contracts/reports/tool/v42.json b/packages/eve/extension-contracts/reports/tool/v42.jsonnew file mode 100644index 000000000..e5d8ca367--- /dev/null+++ b/packages/eve/extension-contracts/reports/tool/v42.json@@ -0,0 +1,22 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "tool",+ "epoch": 42,+ "sha256": "96776fd86151a50c1f9208c64efa049a28db9094f8fed25974912644bc99aa19",+ "exports": [+ "WorkflowTool",+ "WorkflowToolInput",+ "WorkflowToolOptions",+ "defaultWebSearch",+ "defineTool",+ "defineWorkflowTool",+ "disableTool",+ "isDisabledToolSentinel",+ "isWebSearchToolDefinition",+ "toolOutput",+ "toolOutputPart",+ "toolResultFrom",+ "webSearch",+ "workflow"+ ]+}diff --git a/packages/eve/src/client/agent-info-schema.ts b/packages/eve/src/client/agent-info-schema.tsindex 6f2dbcff7..4f6311da8 100644--- a/packages/eve/src/client/agent-info-schema.ts+++ b/packages/eve/src/client/agent-info-schema.ts@@ -271,11 +271,6 @@ const compositionDiagnostic = z}).strict();-const workflow = z.discriminatedUnion("enabled", [- z.object({ enabled: z.literal(false), toolName: z.string() }).strict(),- z.object({ enabled: z.literal(true), source, toolName: z.string() }).strict(),-]);-/** Runtime contract for the authoritative `/eve/v1/info` v4 response. */export const AgentInfoResultSchema = z.object({@@ -319,7 +314,6 @@ export const AgentInfoResultSchema = zsubagents: z.object({ local: z.array(subagent), total: z.number() }).strict(),tools: z.object({ dynamic: z.array(dynamicResolver), static: z.array(tool) }).strict(),version: z.literal(4),- workflow,workspace: z.object({ resourceRoot: z.unknown(), rootEntries: z.array(z.string()) }).strict(),}).strict()@@ -416,9 +410,6 @@ export const AgentInfoResultSchema = z),...value.tools.dynamic.map((entry, index) => [entry, ["tools", "dynamic", index]] as const),...value.tools.static.map((entry, index) => [entry, ["tools", "static", index]] as const),- ...(value.workflow.enabled- ? ([[value.workflow.source, ["workflow", "source"]]] as const)- : []),[value.sandbox, ["sandbox"]],];for (const [entry, path] of boundSources) {diff --git a/packages/eve/src/compiler/extension-compatibility.test.ts b/packages/eve/src/compiler/extension-compatibility.test.tsindex 46950f5ab..7b5924a57 100644--- a/packages/eve/src/compiler/extension-compatibility.test.ts+++ b/packages/eve/src/compiler/extension-compatibility.test.ts@@ -129,6 +129,33 @@ describe("extension compatibility manifest", () => {},);+ it.each([+ { capability: "tool", epoch: 36 },+ { capability: "tool", epoch: 37 },+ { capability: "tool", epoch: 38 },+ { capability: "tool", epoch: 39 },+ { capability: "tool", epoch: 40 },+ { capability: "tool", epoch: 41 },+ { capability: "dynamicTool", epoch: 35 },+ { capability: "dynamicTool", epoch: 36 },+ { capability: "dynamicTool", epoch: 37 },+ { capability: "dynamicTool", epoch: 38 },+ ] as const)(+ "rejects removed workflow surfaces in $capability epoch $epoch",+ ({ capability, epoch }) => {+ const supportedVersions = EXTENSION_CAPABILITY_SUPPORT[capability];+ expect(supportedVersions).not.toContain(epoch);+ expect(+ findUnsupportedExtensionCapabilities({+ kind: EXTENSION_COMPATIBILITY_MANIFEST_KIND,+ formatVersion: EXTENSION_COMPATIBILITY_MANIFEST_FORMAT_VERSION,+ builtWithEve: "0.54.5",+ requires: { [capability]: epoch },+ }),+ ).toEqual([{ capability, requiredVersion: epoch, supportedVersions }]);+ },+ );+it("publishes valid support history for every capability version it stamps", () => {for (const [capability, version] of Object.entries(EXTENSION_CAPABILITY_VERSIONS)) {const supportedVersions = EXTENSION_CAPABILITY_SUPPORT[capability as ExtensionCapability];diff --git a/packages/eve/src/compiler/extension-compatibility.ts b/packages/eve/src/compiler/extension-compatibility.tsindex a20f967a7..924156ede 100644--- a/packages/eve/src/compiler/extension-compatibility.ts+++ b/packages/eve/src/compiler/extension-compatibility.ts@@ -22,10 +22,8 @@ interface ExtensionCapabilityContract {const EXTENSION_CAPABILITY_CONTRACTS = {extension: { current: 1, supported: [1], dropped: {} },tool: {- current: 39,- supported: [- 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 28, 29, 30, 31, 32, 34, 35, 36, 37, 38, 39,- ],+ current: 42,+ supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 28, 29, 30, 31, 32, 34, 35, 42],dropped: {14: "TaskExec.delegated was removed; migrate to workflow-backed background tools",15: "TaskExec replaces stageEffect with send",@@ -42,13 +40,19 @@ const EXTENSION_CAPABILITY_CONTRACTS = {26: "Background tools now use task yield descriptors",27: "TaskExec.delegated was removed; migrate to workflow-backed background tools",33: "ctx.agent now accepts the subagent name as its first argument, derives invocation identity internally, and infers structured output types",+ 36: "experimental_workflow and eve/tools/workflow were removed; migrate to the workflow factory from eve/tools/workflow",+ 37: "experimental_workflow and eve/tools/workflow were removed; migrate to the workflow factory from eve/tools/workflow",+ 38: "experimental_workflow and eve/tools/workflow were removed; migrate to the workflow factory from eve/tools/workflow",+ 39: "experimental_workflow and eve/tools/workflow were removed; migrate to the workflow factory from eve/tools/workflow",+ 40: "runWorkflowProgram was made internal; use the workflow factory from eve/tools/workflow",+ 41: "workflow no longer accepts agents and its options argument is optional; use workflow() or workflow({ maxSubagents })",},},dynamicTool: {- current: 38,+ current: 39,supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 22, 28, 29, 30, 31, 32,- 33, 34, 35, 36, 37, 38,+ 33, 34, 39,],dropped: {21: "Message and reasoning append events now expose deltas instead of cumulative snapshots.",@@ -57,6 +61,10 @@ const EXTENSION_CAPABILITY_CONTRACTS = {25: "TaskExec.delegated was removed; migrate to workflow-backed background tools",26: "Background tools now use task yield descriptors",27: "TaskExec.delegated was removed; migrate to workflow-backed background tools",+ 35: "workflowMaxSubagents was removed with experimental_workflow; configure generated-program limits with the workflow factory",+ 36: "workflowMaxSubagents was removed with experimental_workflow; configure generated-program limits with the workflow factory",+ 37: "workflowMaxSubagents was removed with experimental_workflow; configure generated-program limits with the workflow factory",+ 38: "workflowMaxSubagents was removed with experimental_workflow; configure generated-program limits with the workflow factory",},},channel: {diff --git a/packages/eve/src/compiler/manifest.ts b/packages/eve/src/compiler/manifest.tsindex 2831ef237..f223192df 100644--- a/packages/eve/src/compiler/manifest.ts+++ b/packages/eve/src/compiler/manifest.ts@@ -238,15 +238,11 @@ export type CompiledToolDefinition = InternalToolDefinition &readonly hasExecute: boolean;readonly hasModelOutputProjection: boolean;readonly requiresApproval: boolean;+ readonly workflowProgram?: {+ readonly maxSubagents: number;+ };};-/**- * Serializable configuration for the experimental framework `Workflow` tool.- */-export interface CompiledWorkflowToolDefinition extends ModuleSourceRef {- readonly maxSubagents?: number;-}-/*** Compiled dynamic tool resolver entry. The resolver function lives in the* compiled module map; the manifest entry carries only the metadata needed@@ -596,16 +592,6 @@ const compiledAgentLimitsDefinitionSchema = z}).strict();-const compiledWorkflowToolDefinitionSchema: z.ZodType<CompiledWorkflowToolDefinition> = z- .object({- exportName: z.string().optional(),- logicalPath: z.string(),- maxSubagents: z.number().int().positive().optional(),- sourceId: z.string(),- sourceKind: z.literal("module"),- })- .strict();-const compiledAgentConfigBaseFields = {build: compiledAgentBuildDefinitionSchema.optional(),compaction: compiledAgentCompactionDefinitionSchema.optional(),@@ -883,6 +869,12 @@ const compiledToolDefinitionSchema = zrequiresApproval: z.boolean(),sourceId: z.string(),sourceKind: z.literal("module"),+ workflowProgram: z+ .object({+ maxSubagents: z.number().int().positive(),+ })+ .strict()+ .optional(),}).strict();@@ -970,7 +962,6 @@ const compiledAgentResourceFields = {dynamicConnections: z.array(compiledDynamicConnectionDefinitionSchema).default([]),diagnosticsSummary: discoverDiagnosticsSummarySchema,sourceComposition: agentSourceCompositionSchema,- workflowTool: compiledWorkflowToolDefinitionSchema.optional(),dynamicInstructions: z.array(compiledDynamicInstructionsDefinitionSchema).default([]),dynamicSkills: z.array(compiledDynamicSkillDefinitionSchema).default([]),dynamicTools: z.array(compiledDynamicToolDefinitionSchema).default([]),@@ -1079,7 +1070,6 @@ export const compiledAgentManifestSchema = zdynamicConnections: z.array(compiledDynamicConnectionDefinitionSchema).default([]),diagnosticsSummary: discoverDiagnosticsSummarySchema,sourceComposition: agentSourceCompositionSchema,- workflowTool: compiledWorkflowToolDefinitionSchema.optional(),dynamicInstructions: z.array(compiledDynamicInstructionsDefinitionSchema).default([]),dynamicSkills: z.array(compiledDynamicSkillDefinitionSchema).default([]),dynamicTools: z.array(compiledDynamicToolDefinitionSchema).default([]),@@ -1109,7 +1099,6 @@ export interface CreateCompiledAgentResourcesInput {readonly dynamicConnections?: readonly CompiledDynamicConnectionDefinition[];readonly diagnosticsSummary?: DiscoverDiagnosticsSummary;readonly sourceComposition: AgentSourceComposition;- readonly workflowTool?: CompiledWorkflowToolDefinition;readonly dynamicInstructions?: readonly CompiledDynamicInstructionsDefinition[];readonly dynamicSkills?: readonly CompiledDynamicSkillDefinition[];readonly dynamicTools?: readonly CompiledDynamicToolDefinition[];@@ -1149,7 +1138,6 @@ export function createCompiledAgentResources(sourceComposition: {entries: [...input.sourceComposition.entries],},- workflowTool: input.workflowTool === undefined ? undefined : { ...input.workflowTool },dynamicInstructions: [...(input.dynamicInstructions ?? [])],dynamicSkills: [...(input.dynamicSkills ?? [])],dynamicTools: [...(input.dynamicTools ?? [])],@@ -1298,7 +1286,6 @@ export function createCompiledAgentManifest(input: {readonly dynamicConnections?: readonly CompiledDynamicConnectionDefinition[];readonly diagnosticsSummary?: DiscoverDiagnosticsSummary;readonly sourceComposition: AgentSourceComposition;- readonly workflowTool?: CompiledWorkflowToolDefinition;readonly dynamicInstructions?: readonly CompiledDynamicInstructionsDefinition[];readonly dynamicSkills?: readonly CompiledDynamicSkillDefinition[];readonly dynamicTools?: readonly CompiledDynamicToolDefinition[];diff --git a/packages/eve/src/compiler/normalize-manifest.test.ts b/packages/eve/src/compiler/normalize-manifest.test.tsindex f369e9cd4..f2a82f93b 100644--- a/packages/eve/src/compiler/normalize-manifest.test.ts+++ b/packages/eve/src/compiler/normalize-manifest.test.ts@@ -30,7 +30,6 @@ import { defineWorkflowTool } from "#tools/workflow-definition.js";import { defineTool, disableTool } from "#tools/definition.js";import { defineMemory } from "#public/memory/index.js";import { defineDynamic } from "#dynamic/definition.js";-import { experimental_workflow } from "#tools/workflow.js";import { webSearch } from "#tools/provided/web-search.js";function manifest() {@@ -413,10 +412,6 @@ describe("compileAgentManifest source graph", () => {}),}),},- {- logicalPath: "tools/workflow.ts",- loadNamespace: async () => ({ default: experimental_workflow() }),- },{logicalPath: "tools/web_search.ts",loadNamespace: async () => ({ default: webSearch({ provider: "parallel" }) }),@@ -480,7 +475,6 @@ describe("compileAgentManifest source graph", () => {"tools/dynamic.ts": { compile: true, runtimeEntry: true },"tools/executable.ts": { compile: true, runtimeEntry: true },"tools/web_search.ts": { compile: true, runtimeEntry: false },- "tools/workflow.ts": { compile: true, runtimeEntry: false },});});diff --git a/packages/eve/src/compiler/normalize-manifest.ts b/packages/eve/src/compiler/normalize-manifest.tsindex b7c044299..bad5625d2 100644--- a/packages/eve/src/compiler/normalize-manifest.ts+++ b/packages/eve/src/compiler/normalize-manifest.ts@@ -20,7 +20,6 @@ import {type CompiledSandboxDefinition,type CompiledSubagentNode,type CompiledToolDefinition,- type CompiledWorkflowToolDefinition,createCompiledAgentManifest,createCompiledAgentNodeManifest,createCompiledAgentResources,@@ -69,7 +68,6 @@ import {assertApplicationOverlayCanApplyToAllNodes,assertNonExtensionSpecialTool,assertRootOnlyConfig,- assertRootOwnedSpecialTool,assertUniqueBy,assertUniqueRegistryIds,compileExtensionMounts,@@ -499,7 +497,6 @@ class AgentGraphCompiler {const channels: CompiledChannelDefinition[] = [];let sandbox: CompiledSandboxDefinition | undefined;let instrumentation: ModuleSourceRef | undefined;- let workflowTool: CompiledWorkflowToolDefinition | undefined;const selectedSourceIds = collectSelectedSourceIds(state.composed);const loadNamespace = state.evaluation.loadNamespace;@@ -624,9 +621,6 @@ class AgentGraphCompiler {} else if (result.kind === "dynamic-tool") {dynamicTools.push(withExtensionNamespace(result.definition, candidate.owner));state.evaluation.requireRuntimeEntry(candidate.sourceId);- } else if (result.kind === "workflow-tool") {- assertRootOwnedSpecialTool(candidate as AgentModuleCandidate, "Workflow");- workflowTool = { ...entry.source, maxSubagents: result.maxSubagents };} else {assertNonExtensionSpecialTool(candidate as AgentModuleCandidate, "Web search");tools.push(result.definition);@@ -692,7 +686,6 @@ class AgentGraphCompiler {skills,sourceComposition: state.composed.composition,tools,- workflowTool,});}}diff --git a/packages/eve/src/compiler/normalize-tool.ts b/packages/eve/src/compiler/normalize-tool.tsindex 25ebc3b7a..67c7db1d6 100644--- a/packages/eve/src/compiler/normalize-tool.ts+++ b/packages/eve/src/compiler/normalize-tool.ts@@ -18,7 +18,6 @@ import { readWorkflowFunctionId } from "#internal/workflow/reference.js";export type CompiledToolEntry =| { readonly kind: "tool"; readonly definition: CompiledToolDefinition }| { readonly kind: "disabled"; readonly name: string }- | { readonly kind: "workflow-tool"; readonly maxSubagents?: number }| {readonly definition: CompiledToolDefinition;readonly kind: "web-search-tool";@@ -59,10 +58,6 @@ export async function compileToolEntry(return { kind: "disabled", name: toolName };}- if (entry.kind === "workflow-tool") {- return { kind: "workflow-tool", maxSubagents: entry.maxSubagents };- }-if (entry.kind === "web-search-tool") {if (toolName !== "web_search") {throw new Error(@@ -132,6 +127,7 @@ export async function compileToolEntry(requiresApproval: entry.definition.hasApproval,sourceId: source.sourceId,sourceKind: "module",+ workflowProgram: entry.definition.workflowProgram,},};}diff --git a/packages/eve/src/compiler/validate-artifact.ts b/packages/eve/src/compiler/validate-artifact.tsindex 4eea73ea5..1637d4e62 100644--- a/packages/eve/src/compiler/validate-artifact.ts+++ b/packages/eve/src/compiler/validate-artifact.ts@@ -346,7 +346,6 @@ function collectReferencedModuleSources(for (const value of node.memories) add(value);for (const value of node.instructions) if (value.sourceKind === "module") add(value);if (node.instrumentation !== undefined) add(node.instrumentation);- if (node.workflowTool !== undefined) add(node.workflowTool);for (const value of node.skills) if (value.sourceKind === "module") add(value);for (const value of node.schedules) if (value.sourceKind === "module") add(value);add(node.sandbox);diff --git a/packages/eve/src/execution/agent-messaging.scenario.test.ts b/packages/eve/src/execution/agent-messaging.scenario.test.tsindex 1680ea873..d6f0c35e4 100644--- a/packages/eve/src/execution/agent-messaging.scenario.test.ts+++ b/packages/eve/src/execution/agent-messaging.scenario.test.ts@@ -1,5 +1,4 @@import { spawn, type ChildProcessByStdio } from "node:child_process";-import { readFile } from "node:fs/promises";import { join } from "node:path";import type { Readable } from "node:stream";@@ -8,7 +7,7 @@ import { describe, expect, it } from "vitest";import { Client } from "#client/client.js";import { filterEventsByType } from "#internal/testing/events.js";import { type ScenarioAppDescriptor, useScenarioApp } from "#internal/testing/scenario-app.js";-import { EVE_SESSION_ID_HEADER, type HandleMessageStreamEvent } from "#protocol/message.js";+import type { HandleMessageStreamEvent } from "#protocol/message.js";const scenarioApp = useScenarioApp();const SCENARIO_TIMEOUT_MS = 360_000;@@ -19,6 +18,10 @@ const REMOTE_MEMORY_TOKEN = "remote-memory-scenario-token";function createScriptedParentAgentSource(subagentName: string): string {const agentIdPattern = `<agent id="([^"]+)" name="${subagentName}"(?: [^>]*)?>`;+ const toolName = "run-program";+ const firstProgram = `return ctx.agent(${JSON.stringify(subagentName)}, { message: ${JSON.stringify(`Remember the codeword ${CODEWORD}. Confirm that you stored it.`)} });`;+ const secondProgram = (agentIdExpression: string) =>+ `return ctx.agent(${JSON.stringify(subagentName)}, { agentId: ${agentIdExpression}, message: "What codeword did I ask you to remember? Reply with the codeword." });`;return `import { defineAgent } from "eve";import { mockModel } from "eve/evals";@@ -28,55 +31,48 @@ const SUBAGENT_NAME = ${JSON.stringify(subagentName)};const AGENT_ID_PATTERN = new RegExp(${JSON.stringify(agentIdPattern)}, "u");const model = mockModel((request) => {- const childResults = request.toolResults.filter((result) => result.name === "Workflow");-- if (childResults.length === 0) {+ const firstResult = request.toolResults.find((result) => result.id === "memory-exchange-1");+ if (request.userMessageCount === 1) {+ if (firstResult !== undefined) return "FIRST_EXCHANGE_COMPLETE";return {toolCalls: [{id: "memory-exchange-1",- input: {- js: \`return await tools[\${JSON.stringify(SUBAGENT_NAME)}]({ message: \${JSON.stringify("Remember the codeword " + CODEWORD + ". Confirm that you stored it.")} });\`,- },- name: "Workflow",+ input: { js: ${JSON.stringify(firstProgram)} },+ name: ${JSON.stringify(toolName)},},],};}- if (childResults.length === 1) {- // The agents listing rides the conversation as a framework-injected- // user-role announcement, so scan every message for the latest listing.+ const secondResult = request.toolResults.find((result) => result.id === "memory-exchange-2");+ if (request.userMessageCount === 2) {+ if (secondResult !== undefined) {+ if (typeof secondResult.output !== "string") {+ throw new Error("Second child result was not text.");+ }+ return \`PARENT_RECALLED=\${secondResult.output}\`;+ }const agentsSnippet = request.messages.map((message) => message.text).join("\\n");const agentId = AGENT_ID_PATTERN.exec(agentsSnippet)?.[1];if (agentId === undefined) {throw new Error(\`Parent model did not receive a \${SUBAGENT_NAME} agent id.\`);}-return {toolCalls: [{id: "memory-exchange-2",input: {- js: \`return await tools[\${JSON.stringify(SUBAGENT_NAME)}]({ agentId: \${JSON.stringify(agentId)}, message: "What codeword did I ask you to remember? Reply with the codeword." });\`,+ js: ${JSON.stringify(secondProgram("__AGENT_ID__"))}.replace("__AGENT_ID__", JSON.stringify(agentId)),},- name: "Workflow",+ name: ${JSON.stringify(toolName)},},],};}- if (childResults.length === 2) {- const recalled = childResults[1]?.output;- if (typeof recalled !== "string") {- throw new Error("Second child result was not text.");- }- return \`PARENT_RECALLED=\${recalled}\`;- }-- throw new Error("Parent model received an unexpected number of child results.");+ throw new Error("Parent model received an unexpected conversation length.");});-export default defineAgent({model,modelContextWindowTokens: 32_000,@@ -133,13 +129,19 @@ export default defineAgent({});`;+function createWorkflowProgramToolSource(): string {+ return `import { workflow } from "eve/tools/workflow";++export default workflow({ maxSubagents: 2 });+`;+}+const AGENT_MESSAGING_DESCRIPTOR: ScenarioAppDescriptor = {files: {"agent/agent.ts": createScriptedParentAgentSource("memory-child"),"agent/channels/eve.ts": EVE_CHANNEL_SOURCE,"agent/instructions.md": "Run the scripted memory-child exchanges.\n",- "agent/tools/workflow.ts":- 'import { experimental_workflow } from "eve/tools/workflow";\nexport default experimental_workflow();\n',+ "agent/tools/run-program.ts": createWorkflowProgramToolSource(),"agent/subagents/memory-child/agent.ts": MEMORY_AGENT_SOURCE,"agent/subagents/memory-child/instructions.md":"Remember facts from earlier turns and answer follow-up questions from that history.\n",@@ -165,8 +167,7 @@ function createRemoteAgentMessagingDescriptor(remoteUrl: string): ScenarioAppDes"agent/agent.ts": createScriptedParentAgentSource("remote-memory-child"),"agent/channels/eve.ts": EVE_CHANNEL_SOURCE,"agent/instructions.md": "Run the scripted remote-memory-child exchanges.\n",- "agent/tools/workflow.ts":- 'import { experimental_workflow } from "eve/tools/workflow";\nexport default experimental_workflow();\n',+ "agent/tools/run-program.ts": createWorkflowProgramToolSource(),"agent/subagents/remote-memory-child.ts": `import { defineRemoteAgent } from "eve";import { bearer } from "eve/agents/auth";@@ -199,7 +200,6 @@ describe("agent messaging", () => {client: new Client({ host: server.url }),expectedCompletionCount: 0,});- expect(await readWorkflowRunStatus(app.appRoot, childSessionId)).toBe("cancelled");} catch (error) {throw new Error([`stdout:\n${server.stdout()}`, `stderr:\n${server.stderr()}`].join("\n\n"),@@ -234,7 +234,7 @@ describe("agent messaging", () => {auth: { bearer: REMOTE_MEMORY_TOKEN },host: remoteServer.url,}),- expectedCompletionCount: 1,+ expectedCompletionCount: 0,});} catch (error) {throw new Error(@@ -262,26 +262,16 @@ async function runScriptedParentSession(input: {readonly serverUrl: string;readonly subagentName: string;}): Promise<string> {- const createResponse = await fetch(new URL("eve/v1/session", input.serverUrl), {- body: JSON.stringify({- message: `Run both scripted ${input.subagentName} exchanges.`,- mode: "task",- }),- headers: { "content-type": "application/json" },- method: "POST",- });- expect(createResponse.status).toBe(202);-- const parentSessionId = createResponse.headers.get(EVE_SESSION_ID_HEADER);- if (parentSessionId === null) {- throw new Error("Parent session response did not include a session id.");- }-const client = new Client({ host: input.serverUrl });- const parentEvents = await collectStreamToEnd({- label: "parent task completion",- stream: client.sessions.attach(parentSessionId).stream(),+ const { session: parentSession, response: firstResponse } = await client.sessions.create({+ message: `Run both scripted ${input.subagentName} exchanges.`,});+ const firstTurn = await firstResponse.result();+ const firstTurnEvents = firstTurn.events;+ const secondTurn = await (+ await parentSession.send("Continue the same child and report its recalled codeword.")+ ).result();+ const parentEvents = [...firstTurnEvents, ...secondTurn.events];const calls = filterEventsByType(parentEvents, "subagent.called");if (calls.length !== 2) {@@ -298,12 +288,8 @@ async function runScriptedParentSession(input: {input.expectedRemoteUrl,]);}- expect(parentEvents.at(-1)?.type).toBe("session.completed");- expect(- filterEventsByType(parentEvents, "message.completed").some(- (event) => event.data.message === PARENT_RESULT,- ),- ).toBe(true);+ expect(secondTurn.status).toBe("waiting");+ expect(secondTurn.message).toBe(PARENT_RESULT);const childSessionId = calls[0]?.data.childSessionId;if (childSessionId === undefined) {@@ -374,22 +360,6 @@ function indexesOf(return events.flatMap((event, index) => (event.type === type ? [index] : []));}-async function readWorkflowRunStatus(appRoot: string, sessionId: string): Promise<string> {- const runPath = join(appRoot, ".eve", ".workflow-data", "runs", `${sessionId}.json`);- const run: unknown = JSON.parse(await readFile(runPath, "utf8"));-- if (typeof run !== "object" || run === null) {- throw new Error(`Workflow run ${sessionId} was not an object.`);- }-- const status = Reflect.get(run, "status");- if (typeof status !== "string") {- throw new Error(`Workflow run ${sessionId} did not contain a string status.`);- }-- return status;-}-interface RunningScriptedEveDev {readonly stderr: () => string;readonly stdout: () => string;diff --git a/packages/eve/src/execution/coordination-dispatch-step.ts b/packages/eve/src/execution/coordination-dispatch-step.tsindex e75c9cc00..f4a216861 100644--- a/packages/eve/src/execution/coordination-dispatch-step.ts+++ b/packages/eve/src/execution/coordination-dispatch-step.ts@@ -1,40 +1,19 @@-/** Starts workflow-tool runs for pending blocking actions from either source. */+/** Starts workflow-tool runs and framework controls for pending coordination. */-import { deserializeContext } from "#context/serialize.js";import {prepareCoordinationDispatch,type CoordinationDispatchInput,type CoordinationDispatchResult,} from "#execution/coordination-dispatch-shared.js";-import { createDurableSessionState, readDurableSession } from "#execution/durable-session-store.js";-import { resolveEffectiveAgentRuntime } from "#execution/effective-agent-config.js";-import { hydrateDurableSession } from "#execution/session.js";+import { createDurableSessionState } from "#execution/durable-session-store.js";import { executeTaskControlAction } from "#execution/tasks/parent/dispatch.js";import type { BackgroundTask } from "#execution/tasks/parent/delegate.js";import { cancelBackgroundAgentTask } from "#execution/tools/subagent/task-cancel.js";import { startWorkflowTask } from "#execution/tools/workflow/start.js";-import { setPendingCoordinationBatch } from "#harness/coordination.js";-import {- getPendingWorkflowInterrupt,- setPendingWorkflowUsedCalls,-} from "#harness/workflow-interrupt-state.js";-import {- planWorkflowSubagentDispatch,- type WorkflowSubagentDispatchPlan,-} from "#harness/workflow-subagent-limit.js";-import { buildWorkflowTasksFromInterrupt } from "#harness/workflow-task-state.js";-import { createLogger } from "#internal/logging.js";-import { BundleKey } from "#runtime/sessions/runtime-context-keys.js";-import type {- RuntimeActionResult,- RuntimeSubagentDispatchFailure,- RuntimeWorkflowTaskRequest,-} from "#shared/action-types.js";--const workflowTaskLog = createLogger("execution.dispatch-workflow-tasks");+import type { RuntimeActionResult } from "#shared/action-types.js";type CoordinationDispatchStepInput = CoordinationDispatchInput & {- readonly action: "park" | "dispatch-workflow-tasks";+ readonly action: "park";};export async function dispatchCoordinationStep(@@ -42,20 +21,14 @@ export async function dispatchCoordinationStep(): Promise<CoordinationDispatchResult> {"use step";- // Model-driven actions already have a coordination batch. Dynamic Workflow- // tasks first need their interrupt lowered into that same representation.- const normalized =- input.action === "dispatch-workflow-tasks"- ? await normalizeWorkflowTaskInterrupt(input)- : { results: [], sessionState: input.sessionState };const prepared = await prepareCoordinationDispatch({serializedContext: input.serializedContext,- sessionState: normalized.sessionState,+ sessionState: input.sessionState,});if (prepared === undefined) {return {- results: normalized.results,- sessionState: normalized.sessionState,+ results: [],+ sessionState: input.sessionState,pendingTasks: [],};}@@ -90,12 +63,11 @@ export async function dispatchCoordinationStep(nextSession = control.session;if (control.pendingTask !== undefined) pendingTasks.push(control.pendingTask);results.push(control.result);- continue;}}return {- results: [...results, ...normalized.results],+ results,sessionState:nextSession === session? prepared.sessionState@@ -103,90 +75,3 @@ export async function dispatchCoordinationStep(pendingTasks,};}--async function normalizeWorkflowTaskInterrupt(input: CoordinationDispatchInput): Promise<{- readonly results: readonly RuntimeActionResult[];- readonly sessionState: CoordinationDispatchInput["sessionState"];-}> {- const durableSession = await readDurableSession(input.sessionState);- const pending = getPendingWorkflowInterrupt(durableSession.state);- if (pending === undefined) {- return { results: [], sessionState: input.sessionState };- }-- const tasks = buildWorkflowTasksFromInterrupt(pending.interrupt);- if (tasks.length === 0) {- return { results: [], sessionState: input.sessionState };- }-- const ctx = await deserializeContext(input.serializedContext);- const bundle = ctx.require(BundleKey);- const effectiveAgent = resolveEffectiveAgentRuntime(bundle, ctx);- const plan = planWorkflowSubagentDispatch({- tasks,- maxSubagents: durableSession.workflowMaxSubagents,- usedCalls: pending.usedCalls,- });- const blockedResults = plan.blocked.map((action) => {- workflowTaskLog.warn("workflow subagent limit reached; blocking delegated call", {- callId: action.callId,- maxSubagents: plan.maxSubagents,- subagentName: getWorkflowTaskName(action),- usedCalls: plan.usedCalls,- });- return createWorkflowSubagentLimitResult({ action, plan });- });-- if (plan.allowed.length === 0) {- return { results: blockedResults, sessionState: input.sessionState };- }-- const session = hydrateDurableSession({- compactionOverrides: {- thresholdPercent: effectiveAgent.thresholdPercent,- },- durable: durableSession,- turnAgent: effectiveAgent.turnAgent,- });- const sessionWithUsage = setPendingWorkflowUsedCalls({- session,- usedCalls:- pending.usedCalls + plan.allowed.filter((task) => task.resultKind === "subagent").length,- });- const sessionWithBatch = setPendingCoordinationBatch({- runtimeActions: [],- tasks: plan.allowed,- event: { sequence: 0, stepIndex: 0, turnId: "workflow-dispatch" },- responseMessages: [],- session: sessionWithUsage,- });-- return {- results: blockedResults,- sessionState: createDurableSessionState({ session: sessionWithBatch }),- };-}--function createWorkflowSubagentLimitResult(input: {- readonly action: RuntimeWorkflowTaskRequest;- readonly plan: WorkflowSubagentDispatchPlan;-}): RuntimeSubagentDispatchFailure {- const subagentName = getWorkflowTaskName(input.action);-- return {- callId: input.action.callId,- isError: true,- kind: "subagent-result",- origin: "dispatch",- output: {- code: "WORKFLOW_SUBAGENT_LIMIT_REACHED",- maxSubagents: input.plan.maxSubagents,- message: `Workflow subagent limit reached (${String(input.plan.maxSubagents)}); "${subagentName}" was not called.`,- },- subagentName,- };-}--function getWorkflowTaskName(action: RuntimeWorkflowTaskRequest): string {- return action.resultKind === "subagent" ? action.toolName : action.kind;-}diff --git a/packages/eve/src/execution/create-session-step.test.ts b/packages/eve/src/execution/create-session-step.test.tsindex f83393703..766d33a96 100644--- a/packages/eve/src/execution/create-session-step.test.ts+++ b/packages/eve/src/execution/create-session-step.test.ts@@ -206,22 +206,4 @@ describe("createSessionStep", () => {maxTokenCostUsdPerSession: 1.5,});});-- it("seeds workflow max subagents from the authored Workflow tool", async () => {- vi.mocked(getCompiledRuntimeAgentBundle).mockResolvedValue({- resolvedAgent: {- config: {},- workflowTool: { maxSubagents: 5 },- },- turnAgent: TestTurnAgent,- } as never);-- const { state } = await createSessionStep({- compiledArtifactsSource: { kind: "bundled" },- continuationToken: "http:test",- sessionId: "sess-root",- });-- expect(state.snapshot?.session.workflowMaxSubagents).toBe(5);- });});diff --git a/packages/eve/src/execution/create-session-step.ts b/packages/eve/src/execution/create-session-step.tsindex e8a107608..e4d7c187e 100644--- a/packages/eve/src/execution/create-session-step.ts+++ b/packages/eve/src/execution/create-session-step.ts@@ -82,7 +82,6 @@ export async function createSessionStep(input: {sessionId: input.sessionId,taskId: input.taskId,turnAgent: effectiveAgent.turnAgent,- workflowMaxSubagents: bundle.resolvedAgent.workflowTool?.maxSubagents,});return { state: createDurableSessionState({ session }) };diff --git a/packages/eve/src/execution/durable-session-store.test.ts b/packages/eve/src/execution/durable-session-store.test.tsindex 3e063f9bb..844096c8e 100644--- a/packages/eve/src/execution/durable-session-store.test.ts+++ b/packages/eve/src/execution/durable-session-store.test.ts@@ -132,17 +132,11 @@ describe("durable-session-store cross-version contract", () => {serializedContext: ctx,sessionState: baseState,},- {- kind: "dispatch-workflow-tasks",- pendingCallIds: ["call-2"],- serializedContext: ctx,- sessionState: baseState,- },];// Lock the closed-contract kind set. Adding a new arm is breaking.expect(new Set(arms.map((a) => a.kind))).toEqual(- new Set(["done", "park", "dispatch-coordination", "dispatch-workflow-tasks"]),+ new Set(["done", "park", "dispatch-coordination"]),);});diff --git a/packages/eve/src/execution/durable-session-store.ts b/packages/eve/src/execution/durable-session-store.tsindex b2d8925ed..17c799540 100644--- a/packages/eve/src/execution/durable-session-store.ts+++ b/packages/eve/src/execution/durable-session-store.ts@@ -85,7 +85,6 @@ export interface DurableSession {readonly state?: SessionStateMap;readonly sandboxState?: SandboxState;readonly taskId?: string;- readonly workflowMaxSubagents?: number;readonly agent: {readonly system: string;};diff --git a/packages/eve/src/execution/dynamic-workflow/program-step.scenario.test.ts b/packages/eve/src/execution/dynamic-workflow/program-step.scenario.test.tsnew file mode 100644index 000000000..0f652f258--- /dev/null+++ b/packages/eve/src/execution/dynamic-workflow/program-step.scenario.test.ts@@ -0,0 +1,162 @@+import { describe, expect, it, vi } from "vitest";++import { runWorkflowProgramStep } from "#execution/dynamic-workflow/program-step.js";+import {+ readWorkflowProgramAgentCall,+ readWorkflowProgramCallInterrupt,+ type WorkflowProgramInput,+} from "#execution/dynamic-workflow/schema.js";+import { runJsProgram } from "#execution/dynamic-workflow/workflow.js";++const continuationSecurity = {+ maxAgeMs: 60_000,+ signingKey: "workflow-program-scenario-test-signing-key",+};++function program(js: string, maxSubagents = 10): WorkflowProgramInput {+ return {+ continuationSecurity,+ js,+ maxSubagents,+ };+}++describe("workflow program sandbox", () => {+ it("returns pure JSON and reports syntax failures", async () => {+ await expect(+ runWorkflowProgramStep({+ callId: "pure",+ program: program('return { answer: 42, nested: ["ok"] };'),+ }),+ ).resolves.toEqual({+ output: { answer: 42, nested: ["ok"] },+ status: "completed",+ });++ await expect(+ runWorkflowProgramStep({ callId: "syntax", program: program("return (") }),+ ).rejects.toThrow();+ });++ it("continues parallel calls in request order and then runs a dependent call", async () => {+ const input = program(`+const pair = await Promise.all([+ ctx.agent("researcher", { message: "alpha" }),+ ctx.agent("reviewer", { message: "beta" }),+]);+return ctx.agent("researcher", { message: pair.join("|") });`);+ const first = await runWorkflowProgramStep({ callId: "dependent", program: input });+ expect(first.status).toBe("interrupted");+ if (first.status !== "interrupted") throw new Error("Expected initial calls.");+ expect(+ first.pending.map((entry) =>+ readWorkflowProgramAgentCall(readWorkflowProgramCallInterrupt(entry).toolInput),+ ),+ ).toEqual([+ { input: { message: "alpha" }, target: "researcher" },+ { input: { message: "beta" }, target: "reviewer" },+ ]);++ const second = await runWorkflowProgramStep({+ callId: "dependent",+ program: input,+ resume: {+ interrupt: first.interrupt,+ resolutions: [+ { status: "completed", output: "A" },+ { status: "completed", output: "B" },+ ],+ },+ });+ expect(second.status).toBe("interrupted");+ if (second.status !== "interrupted") throw new Error("Expected dependent call.");+ expect(+ readWorkflowProgramAgentCall(readWorkflowProgramCallInterrupt(second.pending[0]!).toolInput),+ ).toEqual({ input: { message: "A|B" }, target: "researcher" });++ await expect(+ runWorkflowProgramStep({+ callId: "dependent",+ program: input,+ resume: {+ interrupt: second.interrupt,+ resolutions: [{ status: "completed", output: { done: true } }],+ },+ }),+ ).resolves.toEqual({ output: { done: true }, status: "completed" });+ });++ it("lets generated code catch a failed child", async () => {+ const input = program(`+try {+ await ctx.agent("researcher", { message: "fail" });+ return "unexpected";+} catch (error) {+ return { caught: error.message };+}`);+ const first = await runWorkflowProgramStep({ callId: "failure", program: input });+ if (first.status !== "interrupted") throw new Error("Expected agent call.");++ await expect(+ runWorkflowProgramStep({+ callId: "failure",+ program: input,+ resume: {+ interrupt: first.interrupt,+ resolutions: [{ status: "failed", error: "child failed" }],+ },+ }),+ ).resolves.toEqual({ output: { caught: "child failed" }, status: "completed" });+ });++ it("enforces the total call budget through the real sandbox", async () => {+ const agent = vi.fn().mockResolvedValue("ok");+ const ctx = {+ abortSignal: new AbortController().signal,+ agent,+ callId: "policy",+ } as never;++ await expect(+ runJsProgram(+ `+try {+ await ctx.agent("researcher", { message: "one" });+ await ctx.agent("researcher", { message: "two" });+ return "unexpected";+} catch (error) {+ return error.message;+}`,+ ctx,+ { maxSubagents: 1 },+ ),+ ).resolves.toContain("WORKFLOW_PROGRAM_SUBAGENT_LIMIT_REACHED");+ expect(agent).toHaveBeenCalledTimes(1);+ });++ it("rejects oversized source and tampered continuations", async () => {+ await expect(+ runWorkflowProgramStep({+ callId: "large",+ program: program(`return ${JSON.stringify("x".repeat(300 * 1024))};`),+ }),+ ).rejects.toThrow(/source|large|bytes/i);++ const input = program('return ctx.agent("researcher", { message: "x" });');+ const first = await runWorkflowProgramStep({ callId: "tamper", program: input });+ if (first.status !== "interrupted") throw new Error("Expected agent call.");+ const tampered = structuredClone(first.interrupt);+ tampered.continuation.auth.signature = `${tampered.continuation.auth.signature}x`;++ await expect(+ runWorkflowProgramStep({+ callId: "tamper",+ program: input,+ resume: {+ interrupt: tampered,+ resolutions: [{ status: "completed", output: "no" }],+ },+ }),+ ).rejects.toThrow();+ });+});diff --git a/packages/eve/src/execution/dynamic-workflow/program-step.test.ts b/packages/eve/src/execution/dynamic-workflow/program-step.test.tsnew file mode 100644index 000000000..68e877654--- /dev/null+++ b/packages/eve/src/execution/dynamic-workflow/program-step.test.ts@@ -0,0 +1,93 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++const mocks = vi.hoisted(() => ({+ continueWorkflowSandboxInterrupt: vi.fn(),+ createParkingHostTool: vi.fn((input) => input),+ createWorkflowSandboxTool: vi.fn(),+ getWorkflowSandboxPendingInterrupts: vi.fn(),+ unwrapWorkflowSandboxResult: vi.fn(),+}));++vi.mock("#shared/workflow-sandbox.js", () => mocks);++import { runWorkflowProgramStep } from "#execution/dynamic-workflow/program-step.js";+import {+ WORKFLOW_PROGRAM_BRIDGE_REQUEST_LIMIT,+ WORKFLOW_PROGRAM_CALL_INTERRUPT_KIND,+ readWorkflowProgramCallInterrupt,+ type WorkflowProgramInput,+} from "#execution/dynamic-workflow/schema.js";++const program: WorkflowProgramInput = {+ continuationSecurity: { signingKey: "key" },+ js: "return ctx.agent('researcher', { message: 'x' });",+ maxSubagents: 3,+};++const callPayload = {+ kind: WORKFLOW_PROGRAM_CALL_INTERRUPT_KIND,+ task: undefined,+ toolInput: { input: { message: "x" }, target: "researcher" },+ toolName: "agent" as const,+};+const interrupt = { payload: callPayload } as never;++describe("runWorkflowProgramStep", () => {+ beforeEach(() => vi.resetAllMocks());++ it("exposes one restricted agent bridge and returns pending calls", async () => {+ const execute = vi.fn().mockResolvedValue("parked");+ mocks.createWorkflowSandboxTool.mockResolvedValue({ execute });+ mocks.unwrapWorkflowSandboxResult.mockResolvedValue({ interrupt, status: "interrupted" });+ mocks.getWorkflowSandboxPendingInterrupts.mockReturnValue([interrupt]);++ await expect(runWorkflowProgramStep({ callId: "call", program })).resolves.toEqual({+ interrupt,+ pending: [interrupt],+ status: "interrupted",+ });+ expect(mocks.createWorkflowSandboxTool).toHaveBeenCalledWith(+ expect.objectContaining({+ bridgeRequestLimit: WORKFLOW_PROGRAM_BRIDGE_REQUEST_LIMIT,+ continuationSecurity: program.continuationSecurity,+ hostTools: { agent: expect.anything() },+ }),+ );+ expect(mocks.createParkingHostTool).toHaveBeenCalledTimes(1);+ expect(execute).toHaveBeenCalledWith(+ {+ js: expect.stringContaining("agent: (target, input) => tools.agent({ target, input })"),+ },+ { toolCallId: "call" },+ );+ });++ it("returns JSON output after ordered continuation resolutions", async () => {+ mocks.continueWorkflowSandboxInterrupt.mockResolvedValue("complete");+ mocks.unwrapWorkflowSandboxResult.mockResolvedValue({+ output: { ok: true },+ status: "completed",+ });++ await expect(+ runWorkflowProgramStep({+ callId: "call",+ program,+ resume: {+ interrupt,+ resolutions: [{ status: "completed", output: { answer: 1 } }],+ },+ }),+ ).resolves.toEqual({ output: { ok: true }, status: "completed" });+ expect(mocks.continueWorkflowSandboxInterrupt).toHaveBeenCalledWith(+ expect.objectContaining({ bridgeRequestLimit: WORKFLOW_PROGRAM_BRIDGE_REQUEST_LIMIT }),+ );+ });++ it("validates interrupt payloads", () => {+ expect(readWorkflowProgramCallInterrupt(interrupt)).toEqual(callPayload);+ expect(() => readWorkflowProgramCallInterrupt({ payload: { kind: "other" } } as never)).toThrow(+ 'Unsupported workflow program interrupt kind "other"',+ );+ });+});diff --git a/packages/eve/src/execution/dynamic-workflow/program-step.ts b/packages/eve/src/execution/dynamic-workflow/program-step.tsnew file mode 100644index 000000000..0cdd6858d--- /dev/null+++ b/packages/eve/src/execution/dynamic-workflow/program-step.ts@@ -0,0 +1,128 @@+import { jsonSchema, type ToolSet } from "ai";++import {+ WORKFLOW_PROGRAM_BRIDGE_REQUEST_LIMIT,+ WORKFLOW_PROGRAM_CALL_INTERRUPT_KIND,+ parseWorkflowProgramOutput,+ readWorkflowProgramCallInterrupt,+ type WorkflowProgramCallInterrupt,+ type WorkflowProgramInput,+} from "#execution/dynamic-workflow/schema.js";+import {+ continueWorkflowSandboxInterrupt,+ createParkingHostTool,+ createWorkflowSandboxTool,+ getWorkflowSandboxPendingInterrupts,+ unwrapWorkflowSandboxResult,+ type WorkflowSandboxContinuationSecurity,+ type WorkflowSandboxInterrupt,+} from "#shared/workflow-sandbox.js";++export type WorkflowProgramStepOutcome =+ | { readonly output: ReturnType<typeof parseWorkflowProgramOutput>; readonly status: "completed" }+ | {+ readonly interrupt: WorkflowSandboxInterrupt;+ readonly pending: readonly WorkflowSandboxInterrupt[];+ readonly status: "interrupted";+ };++interface WorkflowProgramStepInput {+ readonly callId: string;+ readonly program: WorkflowProgramInput;+ readonly resume?: {+ readonly interrupt: WorkflowSandboxInterrupt;+ readonly resolutions: readonly unknown[];+ };+}++const agentBridgeSchema = jsonSchema({+ additionalProperties: false,+ properties: {+ input: {+ additionalProperties: false,+ properties: {+ agentId: { type: "string" },+ message: { type: "string" },+ outputSchema: { type: "object" },+ },+ required: ["message"],+ type: "object",+ },+ target: { type: "string" },+ },+ required: ["target", "input"],+ type: "object",+});++/** Runs or resumes the side-effect-free JavaScript sandbox for one durable workflow. */+export async function runWorkflowProgramStep(+ input: WorkflowProgramStepInput,+): Promise<WorkflowProgramStepOutcome> {+ "use step";++ const tools = buildWorkflowProgramTools();+ const security = input.program.continuationSecurity as WorkflowSandboxContinuationSecurity;+ let raw: unknown;+ if (input.resume === undefined) {+ const tool = await createWorkflowSandboxTool({+ bridgeRequestLimit: WORKFLOW_PROGRAM_BRIDGE_REQUEST_LIMIT,+ continuationSecurity: security,+ hostTools: tools,+ });+ if (tool.execute === undefined) throw new Error("Workflow program has no sandbox executor.");+ raw = await tool.execute(+ { js: wrapWorkflowProgram(input.program.js) } as never,+ { toolCallId: input.callId } as never,+ );+ } else {+ let current = input.resume.interrupt;+ raw = current;+ for (const resolution of input.resume.resolutions) {+ raw = await continueWorkflowSandboxInterrupt({+ bridgeRequestLimit: WORKFLOW_PROGRAM_BRIDGE_REQUEST_LIMIT,+ continuationSecurity: security,+ interrupt: current,+ resolution,+ tools,+ });+ const unwrapped = await unwrapWorkflowSandboxResult(raw, security);+ if (unwrapped.status === "completed") break;+ const next = getWorkflowSandboxPendingInterrupts(unwrapped.interrupt)[0];+ if (next === undefined) {+ throw new Error("Workflow program continuation contains no pending agent call.");+ }+ current = next;+ }+ }++ const unwrapped = await unwrapWorkflowSandboxResult(raw, security);+ if (unwrapped.status === "completed") {+ return { output: parseWorkflowProgramOutput(unwrapped.output), status: "completed" };+ }+ const pending = getWorkflowSandboxPendingInterrupts(unwrapped.interrupt);+ if (pending.length === 0) {+ throw new Error("Workflow program continuation contains no pending agent call.");+ }+ for (const interrupt of pending) readWorkflowProgramCallInterrupt(interrupt);+ return { interrupt: pending[0]!, pending, status: "interrupted" };+}++function buildWorkflowProgramTools(): ToolSet {+ return {+ agent: createParkingHostTool({+ description: "Invoke one allowlisted child agent.",+ inputSchema: agentBridgeSchema,+ interrupt: (toolInput) =>+ ({+ kind: WORKFLOW_PROGRAM_CALL_INTERRUPT_KIND,+ task: undefined,+ toolInput,+ toolName: "agent",+ }) satisfies WorkflowProgramCallInterrupt,+ }),+ } as ToolSet;+}++function wrapWorkflowProgram(source: string): string {+ return `return await (async (ctx) => {\n${source}\n})(Object.freeze({\n agent: (target, input) => tools.agent({ target, input }),\n}));`;+}diff --git a/packages/eve/src/execution/dynamic-workflow/schema.test.ts b/packages/eve/src/execution/dynamic-workflow/schema.test.tsnew file mode 100644index 000000000..0f6f23122--- /dev/null+++ b/packages/eve/src/execution/dynamic-workflow/schema.test.ts@@ -0,0 +1,43 @@+import { describe, expect, it } from "vitest";++import {+ parseWorkflowProgramOptions,+ readWorkflowProgramAgentCall,+} from "#execution/dynamic-workflow/schema.js";++const options = { maxSubagents: 7 };++describe("workflow program schema", () => {+ it("validates the trusted call budget", () => {+ expect(parseWorkflowProgramOptions(options)).toEqual(options);+ expect(() =>+ parseWorkflowProgramOptions({+ ...options,+ maxSubagents: 129,+ }),+ ).toThrow("between 1 and 128");+ });++ it("validates bridge payloads before owner dispatch", () => {+ expect(+ readWorkflowProgramAgentCall({+ target: "researcher",+ input: {+ agentId: "agent-1",+ message: "continue",+ outputSchema: { properties: { ok: { type: "boolean" } }, type: "object" },+ },+ }),+ ).toEqual({+ target: "researcher",+ input: {+ agentId: "agent-1",+ message: "continue",+ outputSchema: { properties: { ok: { type: "boolean" } }, type: "object" },+ },+ });+ expect(() => readWorkflowProgramAgentCall({ target: "researcher", input: {} })).toThrow(+ 'requires a "message" string',+ );+ });+});diff --git a/packages/eve/src/execution/dynamic-workflow/schema.ts b/packages/eve/src/execution/dynamic-workflow/schema.tsnew file mode 100644index 000000000..ddcf7360c--- /dev/null+++ b/packages/eve/src/execution/dynamic-workflow/schema.ts@@ -0,0 +1,96 @@+import { parseJsonObject, parseJsonValue, type JsonObject, type JsonValue } from "#shared/json.js";++export const DEFAULT_WORKFLOW_PROGRAM_MAX_SUBAGENTS = 100;+export const MAX_WORKFLOW_PROGRAM_MAX_SUBAGENTS = 128;+export const WORKFLOW_PROGRAM_BRIDGE_REQUEST_LIMIT = 256;+export const WORKFLOW_PROGRAM_CALL_INTERRUPT_KIND = "eve.workflow-program-agent-call";++export interface WorkflowProgramCallInterrupt {+ readonly kind: typeof WORKFLOW_PROGRAM_CALL_INTERRUPT_KIND;+ readonly task: undefined;+ readonly toolInput: unknown;+ readonly toolName: "agent";+}++export interface WorkflowProgramContinuationSecurity {+ readonly maxAgeMs?: number;+ readonly signingKey: string;+}++/** Internal durable input pinned for one generated program run. */+export interface WorkflowProgramInput {+ readonly continuationSecurity: WorkflowProgramContinuationSecurity;+ readonly js: string;+ readonly maxSubagents: number;+}++export type WorkflowProgramOptions = Pick<WorkflowProgramInput, "maxSubagents">;++export interface WorkflowProgramAgentCall {+ readonly input: {+ readonly agentId?: string;+ readonly message: string;+ readonly outputSchema?: JsonObject;+ };+ readonly target: string;+}++export function parseWorkflowProgramOptions(value: unknown): WorkflowProgramOptions {+ const input = parseJsonObject(value);+ if (+ !isPositiveInteger(input.maxSubagents) ||+ input.maxSubagents > MAX_WORKFLOW_PROGRAM_MAX_SUBAGENTS+ ) {+ throw new TypeError(+ `workflow maxSubagents must be an integer between 1 and ${String(MAX_WORKFLOW_PROGRAM_MAX_SUBAGENTS)}.`,+ );+ }+ return { maxSubagents: input.maxSubagents };+}++export function readWorkflowProgramCallInterrupt(input: {+ readonly payload: unknown;+}): WorkflowProgramCallInterrupt {+ const payload = input.payload as Partial<WorkflowProgramCallInterrupt>;+ if (payload.kind !== WORKFLOW_PROGRAM_CALL_INTERRUPT_KIND || payload.toolName !== "agent") {+ throw new Error(`Unsupported workflow program interrupt kind "${String(payload.kind)}".`);+ }+ return {+ kind: WORKFLOW_PROGRAM_CALL_INTERRUPT_KIND,+ task: undefined,+ toolInput: payload.toolInput,+ toolName: "agent",+ };+}++export function readWorkflowProgramAgentCall(value: unknown): WorkflowProgramAgentCall {+ const call = parseJsonObject(value);+ if (typeof call.target !== "string" || call.target.trim() === "") {+ throw new TypeError("Workflow program ctx.agent() requires a non-empty agent name.");+ }+ const rawInput = parseJsonObject(call.input);+ if (typeof rawInput.message !== "string") {+ throw new TypeError('Workflow program ctx.agent() requires a "message" string.');+ }+ if (rawInput.agentId !== undefined && typeof rawInput.agentId !== "string") {+ throw new TypeError('Workflow program ctx.agent() "agentId" must be a string.');+ }+ const input: {+ agentId?: string;+ message: string;+ outputSchema?: JsonObject;+ } = { message: rawInput.message };+ if (rawInput.agentId !== undefined) input.agentId = rawInput.agentId;+ if (rawInput.outputSchema !== undefined) {+ input.outputSchema = parseJsonObject(rawInput.outputSchema);+ }+ return { input, target: call.target };+}++export function parseWorkflowProgramOutput(value: unknown): JsonValue {+ return parseJsonValue(value ?? null);+}++function isPositiveInteger(value: unknown): value is number {+ return typeof value === "number" && Number.isSafeInteger(value) && value > 0;+}diff --git a/packages/eve/src/execution/dynamic-workflow/security-step.ts b/packages/eve/src/execution/dynamic-workflow/security-step.tsnew file mode 100644index 000000000..bfefa766c--- /dev/null+++ b/packages/eve/src/execution/dynamic-workflow/security-step.ts@@ -0,0 +1,15 @@+import { randomBytes } from "node:crypto";++import type { WorkflowProgramContinuationSecurity } from "#execution/dynamic-workflow/schema.js";++const WORKFLOW_PROGRAM_CONTINUATION_MAX_AGE_MS = 365 * 24 * 60 * 60 * 1000;++/** Creates replay-stable signing material without exposing it to generated code. */+export async function createWorkflowProgramContinuationSecurityStep(): Promise<WorkflowProgramContinuationSecurity> {+ "use step";++ return {+ maxAgeMs: WORKFLOW_PROGRAM_CONTINUATION_MAX_AGE_MS,+ signingKey: randomBytes(32).toString("base64url"),+ };+}diff --git a/packages/eve/src/execution/dynamic-workflow/tool.ts b/packages/eve/src/execution/dynamic-workflow/tool.tsnew file mode 100644index 000000000..428c70624--- /dev/null+++ b/packages/eve/src/execution/dynamic-workflow/tool.ts@@ -0,0 +1,20 @@+import { runJsProgram } from "#execution/dynamic-workflow/workflow.js";+import type { JsonValue } from "#shared/json.js";+import type { WorkflowToolContext } from "#tools/workflow-definition.js";++export interface WorkflowProgramToolInput {+ readonly js: string;+ readonly maxSubagents?: number;+}++/** Static workflow executor used by the provided `workflow` tool. */+export async function executeWorkflowProgram(+ input: WorkflowProgramToolInput,+ ctx: WorkflowToolContext,+): Promise<JsonValue> {+ "use workflow";++ return runJsProgram(input.js, ctx, {+ maxSubagents: input.maxSubagents ?? 0,+ });+}diff --git a/packages/eve/src/execution/dynamic-workflow/workflow.test.ts b/packages/eve/src/execution/dynamic-workflow/workflow.test.tsnew file mode 100644index 000000000..424301c10--- /dev/null+++ b/packages/eve/src/execution/dynamic-workflow/workflow.test.ts@@ -0,0 +1,161 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++const mocks = vi.hoisted(() => ({+ runWorkflowProgramStep: vi.fn(),+}));+vi.mock("#execution/dynamic-workflow/program-step.js", async (importOriginal) => ({+ ...(await importOriginal()),+ runWorkflowProgramStep: mocks.runWorkflowProgramStep,+}));++import {+ MAX_WORKFLOW_PROGRAM_MAX_SUBAGENTS,+ runJsProgram,+} from "#execution/dynamic-workflow/workflow.js";++const pending = {+ payload: {+ kind: "eve.workflow-program-agent-call",+ toolInput: { input: { message: "one" }, target: "researcher" },+ toolName: "agent",+ },+} as never;+const agent = vi.fn();+const ctx = {+ abortSignal: new AbortController().signal,+ agent,+ callId: "workflow-call",+} as never;+const options = { maxSubagents: 2 } as const;++describe("runJsProgram", () => {+ beforeEach(() => vi.resetAllMocks());++ it("delegates agent interrupts and resumes the sandbox", async () => {+ mocks.runWorkflowProgramStep+ .mockResolvedValueOnce({ interrupt: pending, pending: [pending], status: "interrupted" })+ .mockResolvedValueOnce({ output: { result: "done" }, status: "completed" });+ agent.mockResolvedValue({ result: "child" });++ await expect(runJsProgram("return 1", ctx, options)).resolves.toEqual({ result: "done" });+ expect(agent).toHaveBeenCalledWith("researcher", { message: "one" });+ expect(mocks.runWorkflowProgramStep).toHaveBeenLastCalledWith(+ expect.objectContaining({+ resume: {+ interrupt: pending,+ resolutions: [{ status: "completed", output: { result: "child" } }],+ },+ }),+ );+ });++ it("keeps a pending batch in flight until every child settles", async () => {+ const secondPending = {+ payload: {+ kind: "eve.workflow-program-agent-call",+ toolInput: { input: { message: "two" }, target: "researcher" },+ toolName: "agent",+ },+ } as never;+ const first = Promise.withResolvers<unknown>();+ const second = Promise.withResolvers<unknown>();+ mocks.runWorkflowProgramStep+ .mockResolvedValueOnce({+ interrupt: pending,+ pending: [pending, secondPending],+ status: "interrupted",+ })+ .mockResolvedValueOnce({ output: ["one", "two"], status: "completed" });+ agent.mockImplementation((_target, call: { readonly message: string }) =>+ call.message === "one" ? first.promise : second.promise,+ );++ const result = runJsProgram("return 1", ctx, options);+ await vi.waitFor(() => expect(agent).toHaveBeenCalledTimes(2));+ first.resolve("one");+ await Promise.resolve();+ expect(mocks.runWorkflowProgramStep).toHaveBeenCalledTimes(1);+ second.resolve("two");++ await expect(result).resolves.toEqual(["one", "two"]);+ expect(mocks.runWorkflowProgramStep).toHaveBeenCalledTimes(2);+ });++ it("returns catchable failures for failed children", async () => {+ mocks.runWorkflowProgramStep+ .mockResolvedValueOnce({ interrupt: pending, pending: [pending], status: "interrupted" })+ .mockResolvedValueOnce({ output: "caught", status: "completed" });+ agent.mockRejectedValue(new Error("child failed"));++ await expect(runJsProgram("return 1", ctx, options)).resolves.toBe("caught");+ expect(mocks.runWorkflowProgramStep).toHaveBeenLastCalledWith(+ expect.objectContaining({+ resume: {+ interrupt: pending,+ resolutions: [{ status: "failed", error: "child failed" }],+ },+ }),+ );+ });++ it("bounds total calls across resumed batches", async () => {+ mocks.runWorkflowProgramStep+ .mockResolvedValueOnce({ interrupt: pending, pending: [pending], status: "interrupted" })+ .mockResolvedValueOnce({+ interrupt: pending,+ pending: [pending, pending],+ status: "interrupted",+ })+ .mockResolvedValueOnce({ output: "limited", status: "completed" });+ agent.mockResolvedValueOnce("one").mockResolvedValueOnce("two");++ await expect(runJsProgram("return 1", ctx, options)).resolves.toBe("limited");+ expect(agent).toHaveBeenCalledTimes(2);+ expect(mocks.runWorkflowProgramStep).toHaveBeenLastCalledWith(+ expect.objectContaining({+ resume: expect.objectContaining({+ resolutions: [+ { status: "completed", output: "two" },+ expect.objectContaining({+ status: "failed",+ error: expect.stringContaining("WORKFLOW_PROGRAM_SUBAGENT_LIMIT_REACHED"),+ }),+ ],+ }),+ }),+ );+ });++ it("validates JavaScript and the trusted call budget before starting a program", async () => {+ await expect(runJsProgram(42 as never, ctx, options)).rejects.toThrow('requires a "js" string');+ await expect(+ runJsProgram("return 1", ctx, {+ maxSubagents: MAX_WORKFLOW_PROGRAM_MAX_SUBAGENTS + 1,+ }),+ ).rejects.toThrow("between 1 and 128");+ expect(mocks.runWorkflowProgramStep).not.toHaveBeenCalled();+ });++ it("keeps owner cancellation terminal", async () => {+ const controller = new AbortController();+ const cancelledCtx = {+ abortSignal: controller.signal,+ agent,+ callId: "workflow-call",+ } as never;+ mocks.runWorkflowProgramStep.mockResolvedValueOnce({+ interrupt: pending,+ pending: [pending],+ status: "interrupted",+ });+ agent.mockImplementation(async () => {+ controller.abort(new Error("owner cancelled"));+ throw new Error("child stopped");+ });++ await expect(runJsProgram("return 1", cancelledCtx, options)).rejects.toThrow(+ "owner cancelled",+ );+ expect(mocks.runWorkflowProgramStep).toHaveBeenCalledTimes(1);+ });+});diff --git a/packages/eve/src/execution/dynamic-workflow/workflow.ts b/packages/eve/src/execution/dynamic-workflow/workflow.tsnew file mode 100644index 000000000..2b80f5418--- /dev/null+++ b/packages/eve/src/execution/dynamic-workflow/workflow.ts@@ -0,0 +1,71 @@+import {+ DEFAULT_WORKFLOW_PROGRAM_MAX_SUBAGENTS,+ MAX_WORKFLOW_PROGRAM_MAX_SUBAGENTS,+ parseWorkflowProgramOptions,+ readWorkflowProgramAgentCall,+ readWorkflowProgramCallInterrupt,+ type WorkflowProgramInput,+} from "#execution/dynamic-workflow/schema.js";+import {+ runWorkflowProgramStep,+ type WorkflowProgramStepOutcome,+} from "#execution/dynamic-workflow/program-step.js";+import { createWorkflowProgramContinuationSecurityStep } from "#execution/dynamic-workflow/security-step.js";+import { toErrorMessage } from "#shared/errors.js";+import type { JsonValue } from "#shared/json.js";+import type { WorkflowToolContext } from "#tools/workflow-definition.js";++export interface JsProgramOptions {+ /** Maximum child-agent calls, from 1 to 128. Defaults to 100. */+ readonly maxSubagents?: number;+}++/** Runs a model-generated JavaScript function body inside an isolated workflow sandbox. */+export async function runJsProgram(+ js: string,+ ctx: WorkflowToolContext,+ options: JsProgramOptions,+): Promise<JsonValue> {+ if (typeof js !== "string") throw new TypeError('workflow requires a "js" string.');+ const optionsWithDefaults = parseWorkflowProgramOptions({+ maxSubagents: options.maxSubagents ?? DEFAULT_WORKFLOW_PROGRAM_MAX_SUBAGENTS,+ });+ const program: WorkflowProgramInput = {+ ...optionsWithDefaults,+ continuationSecurity: await createWorkflowProgramContinuationSecurityStep(),+ js,+ };+ const base = { callId: ctx.callId, program };+ let outcome: WorkflowProgramStepOutcome = await runWorkflowProgramStep(base);+ let calls = 0;+ while (outcome.status === "interrupted") {+ ctx.abortSignal.throwIfAborted();+ const resolutions = await Promise.all(+ outcome.pending.map(async (pending) => {+ const interrupt = readWorkflowProgramCallInterrupt(pending);+ const call = readWorkflowProgramAgentCall(interrupt.toolInput);+ const invocationIndex = calls++;+ if (invocationIndex >= program.maxSubagents) {+ return {+ status: "failed" as const,+ error: `WORKFLOW_PROGRAM_SUBAGENT_LIMIT_REACHED: workflow may invoke at most ${String(program.maxSubagents)} agents; "${call.target}" was not called.`,+ };+ }+ try {+ const output = await ctx.agent(call.target, call.input);+ return { status: "completed" as const, output };+ } catch (error) {+ ctx.abortSignal.throwIfAborted();+ return { status: "failed" as const, error: toErrorMessage(error) };+ }+ }),+ );+ outcome = await runWorkflowProgramStep({+ ...base,+ resume: { interrupt: outcome.interrupt, resolutions },+ });+ }+ return outcome.output;+}++export { MAX_WORKFLOW_PROGRAM_MAX_SUBAGENTS };diff --git a/packages/eve/src/execution/inline-turn.ts b/packages/eve/src/execution/inline-turn.tsindex ecdbd28eb..f6aad7df4 100644--- a/packages/eve/src/execution/inline-turn.ts+++ b/packages/eve/src/execution/inline-turn.ts@@ -108,10 +108,7 @@ export async function runInlineTurn(input: {};}- if (- result.action === "dispatch-workflow-tasks" ||- (result.action === "park" && result.pendingCoordinationCallIds !== undefined)- ) {+ if (result.action === "park" && result.pendingCoordinationCallIds !== undefined) {return continueOutcome(control, initialStep);}diff --git a/packages/eve/src/execution/model-call-batching.ts b/packages/eve/src/execution/model-call-batching.tsindex 9d11328ce..49e54de0b 100644--- a/packages/eve/src/execution/model-call-batching.ts+++ b/packages/eve/src/execution/model-call-batching.ts@@ -1,5 +1,4 @@import { derivePendingState } from "#execution/pending-turn-state.js";-import { getPendingWorkflowInterrupt } from "#harness/workflow-interrupt-state.js";import type { HarnessSession, StepInput, StepResult } from "#harness/types.js";export async function runModelCallBatch(input: {@@ -46,8 +45,7 @@ function shouldRunAnotherModelCall(input: {input.completedModelCalls >= input.modelCallsPerStep ||typeof input.result.next !== "function" ||input.result.backgroundTaskSession !== undefined ||- input.result.backgroundTasks !== undefined ||- getPendingWorkflowInterrupt(input.result.session.state) !== undefined+ input.result.backgroundTasks !== undefined) {return false;}diff --git a/packages/eve/src/execution/next-driver-action.ts b/packages/eve/src/execution/next-driver-action.tsindex 4e1539e93..3835b0167 100644--- a/packages/eve/src/execution/next-driver-action.ts+++ b/packages/eve/src/execution/next-driver-action.ts@@ -46,10 +46,6 @@ export type DurableStepResult = (readonly pendingCoordinationCallIds?: readonly string[];readonly settled?: SettledTurn;}- | {- readonly action: "dispatch-workflow-tasks";- readonly pendingTaskCallIds: readonly string[];- }) &DurableStepResultFields;@@ -94,10 +90,4 @@ export type NextDriverAction =readonly pendingCallIds: readonly string[];readonly sessionState: DurableSessionState;readonly serializedContext: Record<string, unknown>;- }- | {- readonly kind: "dispatch-workflow-tasks";- readonly pendingCallIds: readonly string[];- readonly sessionState: DurableSessionState;- readonly serializedContext: Record<string, unknown>;};diff --git a/packages/eve/src/execution/node-step.ts b/packages/eve/src/execution/node-step.tsindex 766e8cabc..5aa40001e 100644--- a/packages/eve/src/execution/node-step.ts+++ b/packages/eve/src/execution/node-step.ts@@ -78,11 +78,6 @@ export interface CreateExecutionNodeStepInput {readonly mode: RunMode;readonly modelResolutionScope: RuntimeModelResolutionScope;readonly node: ResolvedRuntimeAgentNode;- /**- * Effective `maxSubagents` cap configured by the experimental Workflow tool- * definition and materialized on the session at creation.- */- readonly workflowMaxSubagents?: number;}/**@@ -106,8 +101,6 @@ export function createExecutionNodeStep(input: CreateExecutionNodeStepInput): Stcapabilities: input.capabilities,clearOnly: input.clearOnly,compactOnly: input.compactOnly,- workflow: input.node.agent.workflowTool !== undefined,- workflowMaxSubagents: input.workflowMaxSubagents,handleEvent: input.handleEvent,historyProjector: input.historyProjector,historyView: input.historyView,@@ -222,6 +215,7 @@ function resolveHarnessToolDefinition(input: {return createPreparedWorkflowToolHarnessDefinition(input.tool);}return createWorkflowToolHarnessDefinition({+ executeInput: registeredTool.definition.executeInput,definition: createRegisteredHarnessToolDefinition({behavior: input.tool.behavior,definition: registeredTool.definition,@@ -287,6 +281,7 @@ function createRegisteredHarnessToolDefinition(input: {behavior: input.behavior,description: def.description,execution: def.execution,+ executeInput: def.executeInput,execute: isFrameworkRequestInput? undefined: resolveAuthoredExecute({diff --git a/packages/eve/src/execution/session-limit-cancellation.integration.test.ts b/packages/eve/src/execution/session-limit-cancellation.integration.test.tsindex 46e4a4499..fac72a353 100644--- a/packages/eve/src/execution/session-limit-cancellation.integration.test.ts+++ b/packages/eve/src/execution/session-limit-cancellation.integration.test.ts@@ -9,7 +9,6 @@ import {} from "#internal/testing/events.js";import { createBundledRuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";import { workflowEntry } from "#execution/workflow-entry.js";-import { experimental_workflow } from "#tools/workflow.js";import type { UnstampedMessageStreamEvent } from "#protocol/message.js";/**@@ -142,83 +141,4 @@ describe("session-limit continuation decline integration", () => {}});}, 60_000);-- it("fails a zero-quota delegation fast and declines the root's own prompt", async () => {- const runtime = await createTestRuntime({- agent: { limits: { maxInputTokensPerSession: 1 }, name: "limit-decline-child" },- modules: [- {- loadNamespace: async () => ({ default: experimental_workflow() }),- logicalPath: "tools/workflow.ts",- },- ],- });- const continuationToken = "http:limit-decline-child";-- await runtime.run(async () => {- const run = await start(workflowEntry, [- {- input: { message: "Delegate through Workflow to a subagent: summarize the weather." },- serializedContext: {- ...buildSerializedContext({- channelKind: "http",- continuationToken,- mode: "conversation",- }),- "eve.capabilities": { requestInput: true },- },- },- ]);- const stream = captureTurnEvents(run);-- try {- // The root's first model call spends the whole budget, so the- // delegated child inherits a zero remainder and fails fast --- // approving a zero-token window could never grant tokens, so no- // child prompt is raised (`violation.limit > 0` in- // `enforceSessionTokenLimit`). The root receives the child's error- // result, reaches its own pre-model gate, and parks on its OWN- // continuation prompt.- const hitlTurn = await stream.nextTurn();- expect(hitlTurn.at(-1)?.type, JSON.stringify(hitlTurn.at(-1), null, 2)).toBe(- "session.waiting",- );- expect(filterEventsByType(hitlTurn, "subagent.called")).toHaveLength(1);- expect(filterEventsByType(hitlTurn, "input.requested")).toHaveLength(1);- const requestId = requestIdFromPromptTurn(hitlTurn);- // The prompt belongs to the root, not the delegated child.- expect(requestId.startsWith(`${run.runId}:limit:`)).toBe(true);-- // Declining the root's own prompt is a user action the stream must- // show: the turn settles as cancelled and the session stays- // resumable -- same contract as the direct-decline case above.- await deliver(continuationToken, {- inputResponses: [{ optionId: "stop", requestId }],- });- const declinedTurn = await stream.nextTurn();- expect(declinedTurn.at(-1)?.type).toBe("session.waiting");- expect(filterEventsByType(declinedTurn, "turn.cancelled")).toHaveLength(1);- expect(filterEventsByType(declinedTurn, "session.completed")).toHaveLength(0);- expect(filterEventsByType(declinedTurn, "subagent.called")).toHaveLength(0);- expectNoFailureEvents(declinedTurn);-- // The session accepts the next message; the root is still over- // budget, so it re-raises its own prompt (fail-closed) instead of- // running a model call or re-dispatching the delegation.- await deliver(continuationToken, { message: "follow up after decline" });- const followUpTurn = await stream.nextTurn();-- expect(followUpTurn.at(-1)?.type).toBe("session.waiting");- expect(filterEventsByType(followUpTurn, "input.requested")).toHaveLength(1);- expect(filterEventsByType(followUpTurn, "subagent.called")).toHaveLength(0);- expect(filterEventsByType(followUpTurn, "message.completed")).toHaveLength(0);- expect(filterEventsByType(followUpTurn, "session.completed")).toHaveLength(0);- expect(filterEventsByType(followUpTurn, "turn.cancelled")).toHaveLength(0);- expectNoFailureEvents(followUpTurn);- } finally {- stream.dispose();- await run.cancel();- }- });- }, 60_000);});diff --git a/packages/eve/src/execution/session.ts b/packages/eve/src/execution/session.tsindex a32a627ee..be9c18a96 100644--- a/packages/eve/src/execution/session.ts+++ b/packages/eve/src/execution/session.ts@@ -75,7 +75,6 @@ export interface CreateSessionInput {readonly limits?: AuthoredSessionLimits;readonly outputSchema?: HarnessSession["outputSchema"];readonly taskId?: string;- readonly workflowMaxSubagents?: number;}/** Creates a fresh {@link HarnessSession} from the current `turnAgent`. */@@ -106,9 +105,6 @@ export function createSession(input: CreateSessionInput): HarnessSession {if (input.taskId !== undefined) {session.taskId = input.taskId;}- if (input.workflowMaxSubagents !== undefined) {- session.workflowMaxSubagents = input.workflowMaxSubagents;- }return session;}@@ -201,7 +197,6 @@ export function projectToDurableSession(session: HarnessSession): DurableSessionsessionId: string;state?: HarnessSession["state"];taskId?: string;- workflowMaxSubagents?: number;} = {agent: { system: session.agent.system },continuationToken: session.continuationToken,@@ -236,9 +231,6 @@ export function projectToDurableSession(session: HarnessSession): DurableSessionif (session.taskId !== undefined) {durable.taskId = session.taskId;}- if (session.workflowMaxSubagents !== undefined) {- durable.workflowMaxSubagents = session.workflowMaxSubagents;- }return durable;}@@ -293,9 +285,6 @@ export function hydrateDurableSession(input: {if (durable.taskId !== undefined) {session.taskId = durable.taskId;}- if (durable.workflowMaxSubagents !== undefined) {- session.workflowMaxSubagents = durable.workflowMaxSubagents;- }return session;}diff --git a/packages/eve/src/execution/settle-cancelled-turn-step.ts b/packages/eve/src/execution/settle-cancelled-turn-step.tsindex da4adf0b4..06e7795e7 100644--- a/packages/eve/src/execution/settle-cancelled-turn-step.ts+++ b/packages/eve/src/execution/settle-cancelled-turn-step.ts@@ -34,7 +34,6 @@ import { clearPendingCoordinationBatch } from "#harness/coordination.js";import { clearWorkflowToolRuns, getWorkflowToolRuns } from "#harness/workflow-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";import {encodeMessageStreamEvent,type UnstampedMessageStreamEvent,@@ -153,11 +152,9 @@ export async function settleCancelledTurnStep(input: {setHarnessEmissionState(clearPendingSessionLimitPrompt(clearAllProxyInputRequests(- clearPendingWorkflowInterrupt(- clearPendingCoordinationBatch(- clearWorkflowToolRuns(- abandonRunningAgentTurns({ ...session, outputSchema: undefined }),- ),+ clearPendingCoordinationBatch(+ clearWorkflowToolRuns(+ abandonRunningAgentTurns({ ...session, outputSchema: undefined }),),),),diff --git a/packages/eve/src/execution/turn-cancellation.integration.test.ts b/packages/eve/src/execution/turn-cancellation.integration.test.tsindex 02a9c972c..50e8e24b8 100644--- a/packages/eve/src/execution/turn-cancellation.integration.test.ts+++ b/packages/eve/src/execution/turn-cancellation.integration.test.ts@@ -26,7 +26,6 @@ import { defineMemory } from "#public/memory/index.js";import type { ToolContext } from "#tools/definition.js";import type { ResolvedToolDefinition } from "#runtime/types.js";import { toInputSchema } from "#tools/schema.js";-import { experimental_workflow } from "#tools/workflow.js";/*** Turn cancellation settles as `turn.cancelled` → `session.waiting` with@@ -110,12 +109,6 @@ async function createWaitToolRuntime(agentName: string): Promise<WaitToolFixture);const runtime = await createTestRuntime({agent: { name: agentName },- modules: [- {- loadNamespace: async () => ({ default: experimental_workflow() }),- logicalPath: "tools/workflow.ts",- },- ],tools: [waitTool],});const manifestTool = runtime.manifest.tools.find((tool) => tool.name === WAIT_TOOL_NAME);@@ -196,31 +189,6 @@ async function createAbortRecallRuntime(return { recallStarted, recalls: () => recalls, runtime };}-/** Polls the world until the given run reaches `completed`. */-async function waitForRunCompletion(runId: string, timeout = 15_000): Promise<void> {- const world = await getWorld();- const deadline = Date.now() + timeout;- while (Date.now() < deadline) {- const page = await world.runs.list({ pagination: { limit: 100 } });- const row = page.data.find((entry: { runId?: string }) => entry.runId === runId);- if (row?.status === "completed") return;- await new Promise((resolve) => setTimeout(resolve, 50));- }- throw new Error(`Timed out waiting for run "${runId}" to complete.`);-}--/** Polls the world until a hook token is swept (terminal-run cleanup). */-async function waitForHookSweep(token: string, timeout = 15_000): Promise<void> {- const world = await getWorld();- const deadline = Date.now() + timeout;- while (Date.now() < deadline) {- const hook = await world.hooks.getByToken(token).catch(() => null);- if (hook === null || hook === undefined) return;- await new Promise((resolve) => setTimeout(resolve, 50));- }- throw new Error(`Timed out waiting for hook token "${token}" to be swept.`);-}-/** Polls the world for a hook row by token (hooks are per-run; the token is global). */async function waitForHookByToken(token: string, timeout = 15_000): Promise<{ runId: string }> {const world = await getWorld();@@ -756,176 +724,6 @@ describe("turn cancellation integration", () => {});}, 60_000);- it("cascades cancellation to an in-flight subagent and does not re-dispatch it", async () => {- const fixture = await createWaitToolRuntime("turn-cancel-subagent");- const continuationToken = "http:turn-cancel-subagent";-- await fixture.runtime.run(async () => {- const run = await start(workflowEntry, [- {- input: {- message: `Delegate through Workflow to a subagent: use the ${WAIT_TOOL_NAME} tool.`,- },- serializedContext: buildSerializedContext({- channelKind: "http",- continuationToken,- mode: "conversation",- }),- },- ]);- const stream = captureTurnEvents(run);-- try {- // The child (a fresh copy of the same agent) hangs on the wait- // tool, holding the parent in `waitForRuntimeActionResults`.- await fixture.toolStarted;-- const cancelToken = sessionCommandHookToken(run.runId);- await waitForHookByToken(cancelToken);- await resumeHook(cancelToken, { kind: "cancel" });-- const cancelledTurn = await stream.nextTurn();-- expect(cancelledTurn.at(-1)?.type).toBe("session.waiting");- expect(filterEventsByType(cancelledTurn, "turn.cancelled")).toHaveLength(1);- expect(filterEventsByType(cancelledTurn, "subagent.called")).toHaveLength(1);- expectNoFailureEvents(cancelledTurn);-- const childSessionId = filterEventsByType(cancelledTurn, "subagent.called")[0]?.data- .childSessionId;- expect(childSessionId).toBeDefined();- await waitForHookSweep(turnCancellationHookToken(`${childSessionId ?? ""}:turn-control:0`));- expect(fixture.toolAborts()).toBe(1);-- // The cleared pending batch must not re-dispatch on the next turn.- await waitForHook({ runId: run.runId }, { token: continuationToken });- await resumeHook(continuationToken, {- kind: "send",- payload: { message: "follow up after subagent cancel" },- });-- const followUpTurn = await stream.nextTurn();-- expect(followUpTurn.at(-1)?.type).toBe("session.waiting");- expect(filterEventsByType(followUpTurn, "subagent.called")).toHaveLength(0);- expect(filterEventsByType(followUpTurn, "turn.cancelled")).toHaveLength(0);- expectNoFailureEvents(followUpTurn);- expect(- followUpTurn.some(- (event) =>- event.type === "message.completed" &&- event.data.message?.includes("follow up after subagent cancel") === true,- ),- ).toBe(true);- } finally {- stream.dispose();- await run.cancel();- }- });- }, 60_000);-- it("cancels a turn parked on a child HITL request without corrupting the stream", async () => {- const runtime = await createTestRuntime({- agent: { name: "turn-cancel-hitl" },- modules: [- {- loadNamespace: async () => ({ default: experimental_workflow() }),- logicalPath: "tools/workflow.ts",- },- ],- });- const continuationToken = "http:turn-cancel-hitl";-- await runtime.run(async () => {- const run = await start(workflowEntry, [- {- input: {- message:- "Delegate through Workflow to a subagent: Use the ask_question tool exactly once.",- },- serializedContext: {- ...buildSerializedContext({- channelKind: "http",- continuationToken,- mode: "conversation",- }),- "eve.capabilities": { requestInput: true },- },- },- ]);- const stream = captureTurnEvents(run);-- try {- // The child asks a question; the proxy epilogue emits this turn's- // waiting boundary while the parent keeps waiting on the child.- const hitlTurn = await stream.nextTurn();- expect(hitlTurn.at(-1)?.type, JSON.stringify(hitlTurn.at(-1), null, 2)).toBe(- "session.waiting",- );- const requested = filterEventsByType(hitlTurn, "input.requested");- expect(requested).toHaveLength(1);- const requestId = requested[0]?.data.requests[0]?.requestId;- expect(requestId).toBeDefined();- const childSessionId = filterEventsByType(hitlTurn, "subagent.called")[0]?.data- .childSessionId;- expect(childSessionId).toBeDefined();-- const cancelToken = sessionCommandHookToken(run.runId);- await waitForHookByToken(cancelToken);- const cancelHook = await waitForHookByToken(- turnCancellationHookToken(`${run.runId}:turn-control:0`),- );- await resumeHook(cancelToken, { kind: "cancel" });- // Barrier: the answer must not race the cancel — a delivery that- // beats the cancel is legitimately routed to the still-live child.- await waitForRunCompletion(cancelHook.runId);-- // The boundary is already on the stream: settling must not emit a- // fabricated turn.cancelled or a second session.waiting.- const world = await getWorld();- const answer = {- kind: "send",- payload: {- inputResponses: [{ requestId: requestId ?? "", text: "blue" }],- message: "answer after hitl cancel",- },- };- await waitForHook({ runId: run.runId }, { token: continuationToken });- await resumeHook(continuationToken, answer);-- const followUpTurn = await stream.nextTurn();-- expect(followUpTurn.at(-1)?.type).toBe("session.waiting");- expect(filterEventsByType(followUpTurn, "turn.cancelled")).toHaveLength(0);- expect(filterEventsByType(followUpTurn, "turn.started")).toHaveLength(1);- expect(filterEventsByType(followUpTurn, "step.completed")).toHaveLength(1);- expect(filterEventsByType(followUpTurn, "session.waiting")).toHaveLength(1);- expectNoFailureEvents(followUpTurn);- expect(- followUpTurn.some(- (event) =>- event.type === "message.received" &&- typeof event.data.message === "string" &&- event.data.message.includes("answer after hitl cancel"),- ),- ).toBe(true);-- // The cleared proxy map must not route the answer to the orphaned- // child: the child never starts a second turn.- const childSecondTurnInbox = `${childSessionId ?? ""}:turn-control:1:inbox`;- const deadline = Date.now() + 1_500;- while (Date.now() < deadline) {- const hook = await world.hooks.getByToken(childSecondTurnInbox).catch(() => null);- expect(hook ?? null).toBeNull();- await new Promise((resolve) => setTimeout(resolve, 250));- }- } finally {- stream.dispose();- await run.cancel();- }- });- }, 60_000);-it("consumes a cancel with a stale turn guard as a no-op and keeps the turn running", async () => {const fixture = await createWaitToolRuntime("turn-cancel-stale-guard");const continuationToken = "http:turn-cancel-stale-guard";diff --git a/packages/eve/src/execution/turn-workflow.test.ts b/packages/eve/src/execution/turn-workflow.test.tsindex 693bf8fea..df692fad8 100644--- a/packages/eve/src/execution/turn-workflow.test.ts+++ b/packages/eve/src/execution/turn-workflow.test.ts@@ -784,65 +784,6 @@ describe("turnWorkflow", () => {);});- it("keeps dynamic-workflow child dispatch and immediate remote failures in the same turn", async () => {- const now = vi.spyOn(Date, "now").mockReturnValue(2_345);- const pendingState = createSessionState();- const completedState = createSessionState();- installInbox([]);- vi.mocked(dispatchCoordinationStep).mockResolvedValue({- results: [- {- callId: "call-1",- isError: true,- kind: "subagent-result",- origin: "dispatch",- output: { code: "REMOTE_AGENT_START_FAILED", message: "remote unavailable" },- subagentName: "research",- },- ],- sessionState: pendingState,- pendingTasks: [],- });- vi.mocked(turnStep)- .mockResolvedValueOnce({- action: "dispatch-workflow-tasks",- pendingTaskCallIds: ["call-1"],- serializedContext: { state: "pending" },- sessionState: pendingState,- })- .mockResolvedValueOnce({- action: "done",- output: "handled failure",- serializedContext: { state: "done" },- sessionState: completedState,- });-- const { input, parentWritable } = createInput({- driverCapabilities: { turnInbox: true },- mode: "task",- sessionState: pendingState,- });- await turnWorkflow(input);-- expect(dispatchCoordinationStep).toHaveBeenCalledWith({- action: "dispatch-workflow-tasks",- callbackBaseUrl: "https://eve.example.com",- workflowToolRunOwner: { inbox: "generated-owner-token" },- parentWritable,- serializedContext: { state: "pending" },- sessionState: pendingState,- });- expect(vi.mocked(turnStep).mock.calls[1]?.[0].input).toEqual({- acceptedAtMsByCallId: { "call-1": 2_345 },- kind: "runtime-action-result",- results: [expect.objectContaining({ callId: "call-1", isError: true })],- });- expect(- resumeHookMock.mock.calls.filter((call) => call[1]?.kind === "turn-result"),- ).toHaveLength(1);- now.mockRestore();- });-it("proxies child HITL and pulls the response through the active turn", async () => {const runningChildren = [{ callId: "call-1", sessionId: "child-session" }];const pendingState = createSessionState();diff --git a/packages/eve/src/execution/turn-workflow.ts b/packages/eve/src/execution/turn-workflow.tsindex 7cce16c55..f6b426ec3 100644--- a/packages/eve/src/execution/turn-workflow.ts+++ b/packages/eve/src/execution/turn-workflow.ts@@ -131,11 +131,7 @@ export async function runTurnOwnedWorkflow((await turnStep(cursor.createStepInput(nextStepInput, cancellation?.signal)));initialStep = undefined;const pendingCallIds =- result.action === "dispatch-workflow-tasks"- ? result.pendingTaskCallIds- : result.action === "park"- ? result.pendingCoordinationCallIds- : undefined;+ result.action === "park" ? result.pendingCoordinationCallIds : undefined;const hasBackgroundTasks = (result.backgroundTasks?.length ?? 0) > 0;if (hasBackgroundTasks) {@@ -200,13 +196,7 @@ export async function runTurnOwnedWorkflow(return;}- // Both sources converge on coordination dispatch. Model-driven `park`- // already carries a coordination batch; a dynamic Workflow interrupt is- // normalized into that shape inside the dispatch step.- if (- pendingCallIds !== undefined &&- (result.action === "park" || result.action === "dispatch-workflow-tasks")- ) {+ if (pendingCallIds !== undefined && result.action === "park") {await cursor.adopt(result);const dispatchResult = await dispatchCoordinationStep({action: result.action,@@ -504,22 +494,6 @@ async function runLegacyTurnWorkflow(input: TurnWorkflowInput): Promise<void> {return;}- if (result.action === "dispatch-workflow-tasks") {- await sendTurnControlStep({- controlToken: input.completionToken,- payload: {- action: {- kind: "dispatch-workflow-tasks",- pendingCallIds: result.pendingTaskCallIds,- serializedContext: result.serializedContext,- sessionState: result.sessionState,- },- kind: "turn-result",- },- });- return;- }-if (result.action === "park") {const pendingCallIds = result.pendingCoordinationCallIds;const canPark =diff --git a/packages/eve/src/execution/workflow-steps.ts b/packages/eve/src/execution/workflow-steps.tsindex 68b25bdf5..3efdaecbf 100644--- a/packages/eve/src/execution/workflow-steps.ts+++ b/packages/eve/src/execution/workflow-steps.ts@@ -52,8 +52,6 @@ import { observeSessionActivity } from "#execution/session-activity-projection.jimport { hasPendingInputBatch } from "#harness/input-requests.js";import { activeTurnId } from "#harness/active-turn-id.js";import { coalesceTurnInputs, type UserModelMessage } from "#harness/messages.js";-import { getWorkflowTaskCallIds, isWorkflowTaskInterrupt } from "#harness/workflow-task-state.js";-import { getPendingWorkflowInterrupt } from "#harness/workflow-interrupt-state.js";import type { HandleEventFn, HarnessSession, StepInput, StepResult } from "#harness/types.js";import { getTurnUsageState, takeSessionUsageDelta, toUsage } from "#harness/turn-tag-state.js";import type { DurableStepResult } from "#execution/next-driver-action.js";@@ -496,7 +494,6 @@ export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResunodeId: bundle.nodeId,},node: effectiveNode,- workflowMaxSubagents: refreshedSession.workflowMaxSubagents,});return step(modelSession, stepInput);};@@ -647,17 +644,6 @@ export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResuif (stepResult.next === null) {writer.releaseLock();- const workflowInterrupt = getPendingWorkflowInterrupt(stepResult.session.state);- if (workflowInterrupt !== undefined && isWorkflowTaskInterrupt(workflowInterrupt.interrupt)) {- return {- action: "dispatch-workflow-tasks",- ...backgroundTransition,- pendingTaskCallIds: getWorkflowTaskCallIds(workflowInterrupt.interrupt),- serializedContext: nextSerializedContext,- sessionState: nextState,- };- }-const pending = derivePendingState(stepResult.session);// `settledTurn` is the harness's explicit settlement verdict. Pendingdiff --git a/packages/eve/src/harness/advertised-tools.test.ts b/packages/eve/src/harness/advertised-tools.test.tsindex baae58d9a..17e32db47 100644--- a/packages/eve/src/harness/advertised-tools.test.ts+++ b/packages/eve/src/harness/advertised-tools.test.ts@@ -3,9 +3,7 @@ import { describe, expect, it } from "vitest";import { getAdvertisedTools } from "#harness/advertised-tools.js";import type { HarnessToolDefinition } from "#harness/execute-tool.js";-import type { HarnessSession, HarnessToolMap } from "#harness/types.js";-import { buildToolSet } from "#harness/tools.js";-import { WORKFLOW_TOOL_NAME } from "#shared/workflow-sandbox.js";+import type { HarnessToolMap } from "#harness/types.js";describe("getAdvertisedTools", () => {it("keeps the built-in agent tool in the root session", () => {@@ -60,37 +58,6 @@ describe("getAdvertisedTools", () => {expect([...advertisedTools.keys()]).toEqual(["add", "agent"]);});-- it("does not add Workflow in runtime subagent sessions", async () => {- const tools = new Map([["delegate", createSubagentTool("delegate")]]) satisfies HarnessToolMap;-- const advertisedTools = await getAdvertisedTools({- modelTools: buildToolSet({ tools }),- session: createSession({ rootSessionId: "root-session" }),- tools,- workflow: {},- });-- expect(Object.keys(advertisedTools.modelTools)).toEqual(["delegate"]);- expect(advertisedTools.modelTools[WORKFLOW_TOOL_NAME]).toBeUndefined();- });-- it("adds Workflow in root sessions", async () => {- const tools = new Map([- ["add", createTool("add")],- ["delegate", createSubagentTool("delegate")],- ]) satisfies HarnessToolMap;-- const advertisedTools = await getAdvertisedTools({- modelTools: buildToolSet({ tools }),- session: createSession(),- tools,- workflow: {},- });-- expect([...advertisedTools.harnessTools.keys()]).toEqual(["add", "delegate"]);- expect(advertisedTools.modelTools[WORKFLOW_TOOL_NAME]).toBeDefined();- });});describe("getAdvertisedTools for definition arrays", () => {@@ -177,18 +144,3 @@ function createAvailableTool(behavior: { availability },};}--function createSession(overrides: Partial<HarnessSession> = {}): HarnessSession {- return {- agent: {- modelReference: { id: "test-model" },- system: "",- tools: [],- },- compaction: { recentWindowSize: 4, threshold: 1_000_000 },- continuationToken: "test-token",- history: [],- sessionId: "test-session",- ...overrides,- };-}diff --git a/packages/eve/src/harness/advertised-tools.ts b/packages/eve/src/harness/advertised-tools.tsindex b697f45dd..5f8a1d23e 100644--- a/packages/eve/src/harness/advertised-tools.ts+++ b/packages/eve/src/harness/advertised-tools.ts@@ -1,10 +1,5 @@import type { ToolSet } from "ai";import type { HarnessToolDefinition } from "#harness/execute-tool.js";-import {- ensureWorkflowContinuationSecurity,- getWorkflowContinuationSecurity,-} from "#harness/workflow-continuation-security.js";-import { applyWorkflowTool } from "#harness/workflow-sandbox.js";import type { HarnessSession, HarnessToolMap } from "#harness/types.js";type AdvertisedToolSession = Pick<HarnessSession, "rootSessionId" | "taskId">;@@ -23,9 +18,6 @@ type AdvertisedModelToolsInput = {readonly modelTools: ToolSet;readonly session: HarnessSession;readonly tools: HarnessToolMap;- readonly workflow?: {- readonly maxSubagents?: number;- };};type AdvertisedModelTools = {@@ -63,35 +55,10 @@ async function getAdvertisedModelTools(input: AdvertisedModelToolsInput,): Promise<AdvertisedModelTools> {const tools = filterUnavailableToolMap(input.tools, input.session);- if (input.workflow === undefined) {- return {- harnessTools: tools,- modelTools: input.modelTools,- session: input.session,- };- }-- const workflowHostTools = filterWorkflowHostToolsForRootSession(tools, input.session);- if (workflowHostTools.size === 0) {- return {- harnessTools: tools,- modelTools: input.modelTools,- session: input.session,- };- }-- const session = ensureWorkflowContinuationSecurity(input.session);- const { modelTools } = await applyWorkflowTool({- continuationSecurity: getWorkflowContinuationSecurity(session),- harnessTools: workflowHostTools,- maxSubagents: input.workflow.maxSubagents,- tools: input.modelTools,- });-return {harnessTools: tools,- modelTools,- session,+ modelTools: input.modelTools,+ session: input.session,};}@@ -125,24 +92,6 @@ function filterUnavailableToolMap(return filteredTools;}-function filterWorkflowHostToolsForRootSession(- tools: HarnessToolMap,- session: AdvertisedToolSession,-): HarnessToolMap {- const filteredTools = new Map<string, HarnessToolDefinition>();-- if (session.rootSessionId !== undefined) {- return filteredTools;- }-- for (const [name, tool] of tools) {- if (tool.resultKind === "subagent") {- filteredTools.set(name, tool);- }- }- return filteredTools;-}-function shouldHideTool(definition: HarnessToolDefinition,session: AdvertisedToolSession,diff --git a/packages/eve/src/harness/tool-loop.test.ts b/packages/eve/src/harness/tool-loop.test.tsindex c9641b477..6fa27d0a0 100644--- a/packages/eve/src/harness/tool-loop.test.ts+++ b/packages/eve/src/harness/tool-loop.test.ts@@ -1927,70 +1927,6 @@ describe("createToolLoopHarness", () => {expect(events.at(-1)?.type).toBe("session.waiting");});- it("keeps declared subagent tools when Workflow is unavailable outside the root", async () => {- setupMockAgent({- finishReason: "stop",- response: { messages: [{ content: "Hello!", role: "assistant" }] },- text: "Hello!",- toolCalls: [],- toolResults: [],- });-- const config = createTestConfig("conversation", undefined, {- workflow: true,- tools: new Map([- [- "delegate",- {- description: "Delegate to a subagent.",- inputSchema: jsonSchema({ type: "object" }),- name: "delegate",- resultKind: "subagent",- workflowId: "workflow//./agent/subagents/researcher//execute",- },- ],- ]),- });- const runStep = createToolLoopHarness(config);-- await runStep(createTestSession({ rootSessionId: "root-session" }), {- message: "Hi",- });-- const agentCall = vi.mocked(ToolLoopAgent).mock.calls[0]?.[0];- expect(agentCall).toBeDefined();- expect(agentCall!.tools).toHaveProperty("delegate");- expect(agentCall!.tools).not.toHaveProperty("Workflow");- });-- it("omits Workflow from runtime subagent sessions", async () => {- setupMockAgent({- finishReason: "stop",- response: { messages: [{ content: "Hello!", role: "assistant" }] },- text: "Hello!",- toolCalls: [],- toolResults: [],- });-- const config = createTestConfig("conversation", undefined, {- workflow: true,- tools: createDelegationToolMap(),- });- const runStep = createToolLoopHarness(config);-- await runStep(- createTestSession({- rootSessionId: "root-session",- }),- { message: "Hi" },- );-- const agentCall = vi.mocked(ToolLoopAgent).mock.calls[0]?.[0];- expect(agentCall).toBeDefined();- expect(agentCall!.tools).toHaveProperty("delegate");- expect(agentCall!.tools).not.toHaveProperty("Workflow");- });-it("forwards the agent reasoning effort to the model call", async () => {setupMockAgent({finishReason: "stop",diff --git a/packages/eve/src/harness/tool-loop.ts b/packages/eve/src/harness/tool-loop.tsindex bdf1a7fac..5b5c9b109 100644--- a/packages/eve/src/harness/tool-loop.ts+++ b/packages/eve/src/harness/tool-loop.ts@@ -66,32 +66,11 @@ import { ASK_QUESTION_TOOL_NAME } from "#harness/request-input-tool.js";import type { HarnessToolDefinition } from "#harness/execute-tool.js";import { projectParkedAgentHandles, resolveAgentsAnnouncement } from "#subagents/handles/prompt.js";import { getAgentHandleStore } from "#subagents/handles/store.js";-import {- getWorkflowTaskInterrupts,- isWorkflowTaskInterrupt,-} from "#harness/workflow-task-state.js";import type { InputRequest } from "#shared/input.js";import {hydrateSandboxAttachments,stageAttachmentsToSandbox,} from "#harness/attachment-staging.js";-import {- buildWorkflowHostTools,- resolveWorkflowSandboxBridgeRequestLimit,-} from "#harness/workflow-sandbox.js";-import {- getWorkflowContinuationSecurity,- readWorkflowContinuationSecurity,-} from "#harness/workflow-continuation-security.js";-import {- emitWorkflowActionResults,- emitWorkflowActionsRequested,-} from "#harness/workflow-lifecycle.js";-import {- clearPendingWorkflowInterrupt,- getPendingWorkflowInterrupt,- setPendingWorkflowInterrupt,-} from "#harness/workflow-interrupt-state.js";import {compactMessages,getInputTokenCount,@@ -235,12 +214,6 @@ import {buildToolSetFromDefinitions,buildToolSetWithProviderTools,} from "#harness/tools.js";-import {- continueWorkflowSandboxInterrupt,- getWorkflowSandboxInterrupt,- type WorkflowSandboxInterrupt,- unwrapWorkflowSandboxResult,-} from "#shared/workflow-sandbox.js";import { buildFinalOutputTool, FINAL_OUTPUT_TOOL_NAME } from "#harness/final-output.js";import type { RuntimeModelReference } from "#runtime/agent/bootstrap.js";import type { RunMode } from "#shared/run-mode.js";@@ -1405,14 +1378,10 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {flatTools[FINAL_OUTPUT_TOOL_NAME] = buildFinalOutputTool(session.outputSchema);}- const workflowConfig =- config.workflow === true ? { maxSubagents: config.workflowMaxSubagents } : undefined;-const advertisedModelTools = await getAdvertisedTools({modelTools: flatTools,session,tools: advertisedHarnessTools,- workflow: workflowConfig,});session = advertisedModelTools.session;const modelTools = advertisedModelTools.modelTools;@@ -1606,21 +1575,6 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {// capabilities have updated the effective prompt and toolset.const initialModelCallInput = prepareModelCallInput();- // Workflow continuations replay the sandbox after step.started so nested- // action lifecycle events keep the active turn's emission coordinates.- const pendingWorkflowInterrupt = await continuePendingWorkflowInterrupt({- childResults: effectiveStepInput?.runtimeActionResults,- config,- emit,- emissionState,- runStep,- session,- tools: buildHarnessToolsWithDynamicSubagents(config.tools, ctx),- });- if (pendingWorkflowInterrupt !== null) {- return pendingWorkflowInterrupt;- }-const limitResult = await enforceSessionUsageLimit({config,emit,@@ -2480,31 +2434,6 @@ async function handleStepResult(input: {),};- const workflowContinuationSecurity =- config.workflow === true ? readWorkflowContinuationSecurity(baseSession) : undefined;-- if (workflowContinuationSecurity !== undefined) {- const workflowInterrupt = await getWorkflowSandboxInterrupt(- result,- workflowContinuationSecurity,- );- if (workflowInterrupt !== undefined) {- if (!isWorkflowTaskInterrupt(workflowInterrupt)) {- throw new Error(`Unsupported Workflow interrupt kind "${workflowInterrupt.payload.kind}".`);- }- return await parkOnWorkflowInterrupt({- baseSession,- emit,- emissionState,- interrupt: workflowInterrupt,- promptMessages,- responseMessages,- tools: input.coordinationTools,- usedCalls: 0,- });- }- }-const approvalRequests = extractToolApprovalInputRequests({content: result.content ?? [],excludedCallIds: invalidInputToolCallIds,@@ -3010,183 +2939,6 @@ async function finishConversationTurn(input: {return { next: null, session, settledTurn };}-/** Replays a parked dynamic workflow with completed child-agent results. */-async function continuePendingWorkflowInterrupt(input: {- readonly childResults?: readonly { readonly isError?: boolean; readonly output?: unknown }[];- readonly config: ToolLoopHarnessConfig;- readonly emit?: ToolLoopHarnessConfig["handleEvent"];- readonly emissionState: ReturnType<typeof getHarnessEmissionState>;- readonly runStep: StepFn;- readonly session: HarnessSession;- readonly tools: HarnessToolMap;-}): Promise<StepResult | null> {- const pending = getPendingWorkflowInterrupt(input.session.state);- if (pending === undefined) return null;-- const interrupt = pending.interrupt;- if (!isWorkflowTaskInterrupt(interrupt)) {- throw new Error(`Unsupported Workflow interrupt kind "${interrupt.payload.kind}".`);- }-- const childResults = input.childResults ?? [];- const pendingInterrupts = getWorkflowTaskInterrupts(interrupt);- if (input.emit !== undefined && childResults.length > 0) {- await emitWorkflowActionResults({- emit: input.emit,- emissionState: input.emissionState,- interrupts: pendingInterrupts,- results: childResults,- });- }-- const continuationSecurity = getWorkflowContinuationSecurity(input.session);-- let continuationOutput: unknown;- try {- const hostTools = buildWorkflowHostTools({- tools: input.tools,- });-- let currentInterrupt = interrupt;- let resultIndex = 0;- // Promise.all can park several child calls together. Resolve one pending- // interruption per replay until every supplied child result is consumed.- // eslint-disable-next-line no-constant-condition- while (true) {- continuationOutput = await continueWorkflowSandboxInterrupt({- bridgeRequestLimit: resolveWorkflowSandboxBridgeRequestLimit(- input.config.workflowMaxSubagents,- ),- continuationSecurity,- interrupt: currentInterrupt,- resolution: childResults[resultIndex]?.output,- tools: hostTools,- });- const loopUnwrapped = await unwrapWorkflowSandboxResult(- continuationOutput,- continuationSecurity,- );- if (loopUnwrapped.status !== "interrupted") break;- if (!isWorkflowTaskInterrupt(loopUnwrapped.interrupt)) break;- if (resultIndex + 1 >= childResults.length) break;- const nextInterrupt = getWorkflowTaskInterrupts(loopUnwrapped.interrupt)[0];- if (nextInterrupt === undefined) {- throw new Error("Workflow continuation contains no pending workflow-task interrupt.");- }- resultIndex++;- currentInterrupt = nextInterrupt;- }- } catch (error) {- logError(log, "Workflow interrupt continuation failed", error);- continuationOutput = {- error: "workflow_continuation_failed",- message: toErrorMessage(error),- retryable: false,- };- }-- const unwrapped = await unwrapWorkflowSandboxResult(continuationOutput, continuationSecurity);- const finalOutput = unwrapped.status === "interrupted" ? unwrapped.interrupt : unwrapped.output;- const baseMessages = validateHarnessModelMessages([- ...input.session.history,- ...pending.responseMessages,- ]);- const replacedMessages = replaceWorkflowToolResult(- baseMessages,- (interrupt as { outerToolCallId?: string }).outerToolCallId,- finalOutput,- );-- let session = clearPendingWorkflowInterrupt({- ...input.session,- history: replacedMessages,- });-- if (unwrapped.status === "interrupted") {- if (!isWorkflowTaskInterrupt(unwrapped.interrupt)) {- throw new Error(`Unsupported Workflow interrupt kind "${unwrapped.interrupt.payload.kind}".`);- }- const promptMessageCount = input.session.history.length;- const promptMessages = replacedMessages.slice(0, promptMessageCount);- const responseMessages = replacedMessages.slice(promptMessageCount);- session = { ...session, history: promptMessages };- return await parkOnWorkflowInterrupt({- baseSession: session,- emit: input.emit,- emissionState: input.emissionState,- interrupt: unwrapped.interrupt,- promptMessages,- responseMessages,- tools: input.tools,- usedCalls: pending.usedCalls,- });- }-- return { next: input.runStep, session };-}--function replaceWorkflowToolResult(- messages: readonly HarnessModelMessage[],- outerToolCallId: string | undefined,- output: unknown,-): HarnessModelMessage[] {- if (outerToolCallId === undefined) return [...messages];- const outputValue =- typeof output === "string"- ? { type: "text" as const, value: output }- : { type: "json" as const, value: output };- return messages.map((message) => {- if (message.role !== "tool") return message;- const content = (message.content as readonly { type: string; toolCallId?: string }[]).map(- (part) => {- if (part.type !== "tool-result" || part.toolCallId !== outerToolCallId) return part;- return { ...part, output: outputValue };- },- );- return { ...message, content };- }) as HarnessModelMessage[];-}--async function parkOnWorkflowInterrupt(input: {- readonly baseSession: HarnessSession;- readonly emit?: ToolLoopHarnessConfig["handleEvent"];- readonly emissionState: ReturnType<typeof getHarnessEmissionState>;- readonly interrupt: WorkflowSandboxInterrupt;- readonly promptMessages: readonly HarnessModelMessage[];- readonly responseMessages: readonly ModelMessage[];- readonly tools: HarnessToolMap;- readonly usedCalls: number;-}): Promise<StepResult> {- const interrupts = getWorkflowTaskInterrupts(input.interrupt);- const interrupt = interrupts[0];- if (interrupt === undefined) {- throw new Error("Workflow continuation contains no pending workflow-task interrupt.");- }-- if (input.emit !== undefined) {- await emitWorkflowActionsRequested({- emit: input.emit,- emissionState: input.emissionState,- interrupts,- tools: input.tools,- });- }-- const baseSession: HarnessSession = {- ...input.baseSession,- history: [...input.promptMessages],- };-- const parkedSession = setPendingWorkflowInterrupt({- interrupt,- responseMessages: input.responseMessages,- session: baseSession,- usedCalls: input.usedCalls,- });-- return { next: null, session: setHarnessEmissionState(parkedSession, input.emissionState) };-}-function createNextCompactionConfig(current: CompactionConfig,durablePromptMessageCount: number | undefined,diff --git a/packages/eve/src/harness/types.ts b/packages/eve/src/harness/types.tsindex 5987fc37a..bd42083be 100644--- a/packages/eve/src/harness/types.ts+++ b/packages/eve/src/harness/types.ts@@ -97,12 +97,6 @@ export interface HarnessSession {readonly state?: SessionStateMap;/** Framework task that owns this durable session, when present. */readonly taskId?: string;- /**- * Effective maximum subagent calls one `Workflow` invocation may dispatch- * for this session, configured by `experimental_workflow({ maxSubagents })`.- * When omitted, the dispatch step applies the framework default.- */- readonly workflowMaxSubagents?: number;}export function requireSessionModelReference(session: HarnessSession): RuntimeModelReference {@@ -291,21 +285,6 @@ export interface ToolLoopHarnessConfig {readonly clearOnly?: boolean;/** Forces one context-compaction pass without running a model turn. */readonly compactOnly?: boolean;- /**- * Exposes the `Workflow` orchestration tool — an isolated JavaScript sandbox- * whose only callable operations are this agent's subagents and remote- * agents. Resolved from the `experimental_workflow(...)` definition exported- * by `agent/tools/workflow.ts`. Only root sessions ever see the tool.- * Defaults to `false`.- */- readonly workflow?: boolean;- /**- * Maximum subagent calls one `Workflow` invocation may dispatch, from the- * authored Workflow tool definition. Advertised in the tool description;- * the dispatch step enforces it. Defaults to- * {@link import("#harness/workflow-subagent-limit.js").DEFAULT_WORKFLOW_MAX_SUBAGENTS}.- */- readonly workflowMaxSubagents?: number;readonly handleEvent?: HandleEventFn;/** Projects raw durable history before it crosses a message-bearing boundary. */readonly historyProjector?: HistoryViewProjector;diff --git a/packages/eve/src/harness/workflow-continuation-security.test.ts b/packages/eve/src/harness/workflow-continuation-security.test.tsdeleted file mode 100644index 33891b318..000000000--- a/packages/eve/src/harness/workflow-continuation-security.test.ts+++ /dev/null@@ -1,57 +0,0 @@-import { describe, expect, it } from "vitest";--import type { HarnessSession } from "#harness/types.js";-import {- ensureWorkflowContinuationSecurity,- getWorkflowContinuationSecurity,- readWorkflowContinuationSecurity,-} from "#harness/workflow-continuation-security.js";--function makeSession(state?: HarnessSession["state"]): HarnessSession {- return {- agent: {- modelReference: { id: "test-model" },- system: "",- tools: [],- },- compaction: { recentWindowSize: 4, threshold: 1_000_000 },- continuationToken: "test-token",- history: [],- sessionId: "test-session",- state,- };-}--describe("workflow continuation security", () => {- it("persists one stable signing key on session state", () => {- const initial = makeSession({ authored: "preserved" });-- const secured = ensureWorkflowContinuationSecurity(initial);- const security = getWorkflowContinuationSecurity(secured);-- expect(secured).not.toBe(initial);- expect(secured.state?.authored).toBe("preserved");- expect(security.signingKey).toMatch(/^[A-Za-z0-9_-]{43}$/);- expect(security.maxAgeMs).toBe(365 * 24 * 60 * 60 * 1000);- expect(ensureWorkflowContinuationSecurity(secured)).toBe(secured);- expect(getWorkflowContinuationSecurity(secured)).toEqual(security);- expect(readWorkflowContinuationSecurity(secured)).toEqual(security);- });-- it("rejects malformed persisted security state", () => {- const session = makeSession({- "eve.harness.workflowContinuationSecurity": {- signingKey: "not-a-256-bit-key",- version: 1,- },- });-- expect(() => ensureWorkflowContinuationSecurity(session)).toThrow(- "Workflow continuation security state is missing or invalid.",- );- expect(() => getWorkflowContinuationSecurity(session)).toThrow(- "Workflow continuation security state is missing or invalid.",- );- expect(readWorkflowContinuationSecurity(session)).toBeUndefined();- });-});diff --git a/packages/eve/src/harness/workflow-continuation-security.ts b/packages/eve/src/harness/workflow-continuation-security.tsdeleted file mode 100644index 7e4573416..000000000--- a/packages/eve/src/harness/workflow-continuation-security.ts+++ /dev/null@@ -1,61 +0,0 @@-import { randomBytes } from "node:crypto";--import type { HarnessSession } from "#harness/types.js";-import type { WorkflowSandboxContinuationSecurity } from "#shared/workflow-sandbox.js";--const WORKFLOW_CONTINUATION_SECURITY_KEY = "eve.harness.workflowContinuationSecurity";-const WORKFLOW_CONTINUATION_MAX_AGE_MS = 365 * 24 * 60 * 60 * 1000;--interface StoredWorkflowContinuationSecurity {- readonly signingKey: string;- readonly version: 1;-}--export function ensureWorkflowContinuationSecurity(session: HarnessSession): HarnessSession {- if (session.state?.[WORKFLOW_CONTINUATION_SECURITY_KEY] !== undefined) {- getWorkflowContinuationSecurity(session);- return session;- }-- return {- ...session,- state: {- ...session.state,- [WORKFLOW_CONTINUATION_SECURITY_KEY]: {- signingKey: randomBytes(32).toString("base64url"),- version: 1,- } satisfies StoredWorkflowContinuationSecurity,- },- };-}--export function readWorkflowContinuationSecurity(- session: HarnessSession,-): WorkflowSandboxContinuationSecurity | undefined {- const stored = session.state?.[WORKFLOW_CONTINUATION_SECURITY_KEY];- if (- typeof stored !== "object" ||- stored === null ||- (stored as { version?: unknown }).version !== 1 ||- typeof (stored as { signingKey?: unknown }).signingKey !== "string" ||- !/^[A-Za-z0-9_-]{43}$/.test((stored as { signingKey: string }).signingKey)- ) {- return undefined;- }-- return {- signingKey: (stored as StoredWorkflowContinuationSecurity).signingKey,- // A parked workflow can legitimately wait far beyond code mode's one-hour default.- maxAgeMs: WORKFLOW_CONTINUATION_MAX_AGE_MS,- };-}--export function getWorkflowContinuationSecurity(- session: HarnessSession,-): WorkflowSandboxContinuationSecurity {- const security = readWorkflowContinuationSecurity(session);- if (security === undefined) {- throw new Error("Workflow continuation security state is missing or invalid.");- }- return security;-}diff --git a/packages/eve/src/harness/workflow-interrupt-state.test.ts b/packages/eve/src/harness/workflow-interrupt-state.test.tsdeleted file mode 100644index 3e12b40f1..000000000--- a/packages/eve/src/harness/workflow-interrupt-state.test.ts+++ /dev/null@@ -1,52 +0,0 @@-import { describe, expect, it } from "vitest";--import { getPendingWorkflowInterrupt } from "#harness/workflow-interrupt-state.js";-import { WORKFLOW_TASK_INTERRUPT_KIND } from "#harness/workflow-task-state.js";-import type { SessionStateMap } from "#harness/types.js";--describe("pending workflow interrupt state", () => {- it("reads the persisted call budget with an official runtime continuation", () => {- const state = {- "eve.harness.pendingWorkflowInterrupt": {- interrupt: {- continuation: {- outerToolCallId: "workflow-call",- pendingInterruptions: [],- resolutions: [],- version: 2,- },- interruptId: "workflow-call:tool-1:interrupt",- outerToolCallId: "workflow-call",- payload: { kind: WORKFLOW_TASK_INTERRUPT_KIND },- type: "code-mode-interrupt",- },- responseMessages: [],- usedCalls: 3,- },- } as SessionStateMap;-- expect(getPendingWorkflowInterrupt(state)).toMatchObject({ usedCalls: 3 });- });-- it("rejects pending state without a valid persisted call budget", () => {- const state = {- "eve.harness.pendingWorkflowInterrupt": {- interrupt: {- continuation: {- outerToolCallId: "workflow-call",- pendingInterruptions: [],- resolutions: [],- version: 2,- },- interruptId: "workflow-call:tool-1:interrupt",- outerToolCallId: "workflow-call",- payload: { kind: WORKFLOW_TASK_INTERRUPT_KIND },- type: "code-mode-interrupt",- },- responseMessages: [],- },- } as SessionStateMap;-- expect(getPendingWorkflowInterrupt(state)).toBeUndefined();- });-});diff --git a/packages/eve/src/harness/workflow-interrupt-state.ts b/packages/eve/src/harness/workflow-interrupt-state.tsdeleted file mode 100644index fc0f05e4b..000000000--- a/packages/eve/src/harness/workflow-interrupt-state.ts+++ /dev/null@@ -1,93 +0,0 @@-import type { ModelMessage } from "ai";--import type { HarnessSession, SessionStateMap } from "#harness/types.js";-import { WORKFLOW_TASK_INTERRUPT_KIND } from "#harness/workflow-task-state.js";-import type { WorkflowSandboxInterrupt } from "#shared/workflow-sandbox.js";--const PENDING_KEY = "eve.harness.pendingWorkflowInterrupt";--export interface PendingWorkflowInterrupt {- readonly interrupt: WorkflowSandboxInterrupt;- readonly responseMessages: readonly ModelMessage[];- readonly usedCalls: number;-}--export function getPendingWorkflowInterrupt(- state: SessionStateMap | undefined,-): PendingWorkflowInterrupt | undefined {- const value = state?.[PENDING_KEY];- if (!isRecord(value)) return undefined;- if (!isWorkflowInterruptShape(value.interrupt) || !Array.isArray(value.responseMessages)) {- return undefined;- }- if (!Number.isSafeInteger(value.usedCalls) || (value.usedCalls as number) < 0) return undefined;-- return {- interrupt: value.interrupt,- responseMessages: value.responseMessages as ModelMessage[],- usedCalls: value.usedCalls as number,- };-}--export function setPendingWorkflowInterrupt(input: {- readonly interrupt: WorkflowSandboxInterrupt;- readonly responseMessages: readonly ModelMessage[];- readonly session: HarnessSession;- readonly usedCalls: number;-}): HarnessSession {- return {- ...input.session,- state: {- ...input.session.state,- [PENDING_KEY]: {- interrupt: input.interrupt,- responseMessages: input.responseMessages,- usedCalls: input.usedCalls,- } satisfies PendingWorkflowInterrupt,- },- };-}--export function setPendingWorkflowUsedCalls(input: {- readonly session: HarnessSession;- readonly usedCalls: number;-}): HarnessSession {- const pending = getPendingWorkflowInterrupt(input.session.state);- if (pending === undefined) return input.session;- return setPendingWorkflowInterrupt({- ...pending,- session: input.session,- usedCalls: input.usedCalls,- });-}--export function clearPendingWorkflowInterrupt(session: HarnessSession): HarnessSession {- if (session.state?.[PENDING_KEY] === undefined) return session;-- const state = { ...session.state };- delete state[PENDING_KEY];- return {- ...session,- state: Object.keys(state).length > 0 ? state : undefined,- };-}--function isWorkflowInterruptShape(value: unknown): value is WorkflowSandboxInterrupt {- return (- isRecord(value) &&- value.type === "code-mode-interrupt" &&- typeof value.interruptId === "string" &&- typeof value.outerToolCallId === "string" &&- isRecord(value.payload) &&- value.payload.kind === WORKFLOW_TASK_INTERRUPT_KIND &&- isRecord(value.continuation) &&- value.continuation.version === 2 &&- typeof value.continuation.outerToolCallId === "string" &&- Array.isArray(value.continuation.pendingInterruptions) &&- Array.isArray(value.continuation.resolutions)- );-}--function isRecord(value: unknown): value is Record<string, unknown> {- return typeof value === "object" && value !== null && !Array.isArray(value);-}diff --git a/packages/eve/src/harness/workflow-lifecycle.test.ts b/packages/eve/src/harness/workflow-lifecycle.test.tsdeleted file mode 100644index effcde85d..000000000--- a/packages/eve/src/harness/workflow-lifecycle.test.ts+++ /dev/null@@ -1,175 +0,0 @@-import { jsonSchema } from "ai";-import { describe, expect, it } from "vitest";--import { ContextContainer, contextStorage } from "#context/container.js";-import type { HarnessEmissionState } from "#harness/emission.js";-import {- emitWorkflowActionResults,- emitWorkflowActionsRequested,-} from "#harness/workflow-lifecycle.js";-import { WORKFLOW_TASK_INTERRUPT_KIND } from "#harness/workflow-task-state.js";-import type { HarnessToolMap } from "#harness/types.js";-import { defineState } from "#public/definitions/state.js";-import type { UnstampedMessageStreamEvent } from "#protocol/message.js";-import type { WorkflowSandboxInterrupt } from "#shared/workflow-sandbox.js";--const emissionState: HarnessEmissionState = {- sequence: 2,- sessionStarted: true,- stepIndex: 3,- turnId: "turn_abc",-};--function createTools(): HarnessToolMap {- return new Map([- [- "researcher",- {- description: "Delegate to the researcher.",- inputSchema: jsonSchema({ type: "object" }),- name: "researcher",- resultKind: "subagent",- workflowId: "workflow//./agent/subagents/researcher//execute",- },- ],- ]);-}--function workflowInterrupt(): WorkflowSandboxInterrupt {- const payload = {- kind: WORKFLOW_TASK_INTERRUPT_KIND,- task: {- resultKind: "subagent" as const,- workflowId: "workflow//./agent/subagents/researcher//execute",- },- toolInput: { message: "Investigate" },- toolName: "researcher",- };- return {- continuation: {- auth: {- alg: "HMAC-SHA256",- expiresAtMs: 2,- issuedAtMs: 1,- nonce: "nonce",- signature: "signature",- },- js: "return tools.researcher({ message: 'Investigate' })",- outerToolCallId: "outer-call",- pendingInterruptions: [- {- input: { message: "Investigate" },- interruptId: "outer-call:tool-1:interrupt",- payload,- runInterruptionId: "run-interruption-1",- toolCallId: "outer-call:tool-1",- toolName: "researcher",- },- ],- resolutions: [],- token: "token",- toolNames: ["researcher"],- version: 2,- },- input: { message: "Investigate" },- interruptId: "outer-call:tool-1:interrupt",- outerToolCallId: "outer-call",- payload,- toolCallId: "outer-call:tool-1",- toolName: "researcher",- type: "code-mode-interrupt",- };-}--describe("workflow lifecycle projection", () => {- it("emits parked subagent calls and resumed results as action events", async () => {- const events: UnstampedMessageStreamEvent[] = [];- const emit = async (event: UnstampedMessageStreamEvent) => {- events.push(event);- };-- await emitWorkflowActionsRequested({- emit,- emissionState,- interrupts: [workflowInterrupt()],- tools: createTools(),- });- await emitWorkflowActionResults({- emit,- emissionState,- interrupts: [workflowInterrupt()],- results: [{ output: { value: "ok" } }],- });-- expect(events[0]).toMatchObject({- data: {- actions: [- {- callId: "outer-call:tool-1",- kind: "tool-call",- toolName: "researcher",- },- ],- sequence: 2,- stepIndex: 3,- turnId: "turn_abc",- },- type: "actions.requested",- });- expect(events[1]).toMatchObject({- data: {- result: {- callId: "outer-call:tool-1",- output: { value: "ok" },- toolName: "researcher",- },- },- type: "action.result",- });- });-- it("projects failed child results through the shared result contract", async () => {- const events: UnstampedMessageStreamEvent[] = [];- await emitWorkflowActionResults({- emit: async (event) => {- events.push(event);- },- emissionState,- interrupts: [workflowInterrupt()],- results: [{ isError: true, output: "child failed" }],- });-- expect(events[0]).toMatchObject({- data: {- result: { isError: true, output: "child failed" },- status: "failed",- },- type: "action.result",- });- });-- it("emits events in the invoking context", async () => {- const lifecycleDispatches = defineState<string[]>(- "test.workflow.lifecycle.dispatch-context",- () => [],- );- const buildSession = new ContextContainer();- const callSession = new ContextContainer();-- await contextStorage.run(callSession, () =>- emitWorkflowActionsRequested({- emit: async (event) => {- lifecycleDispatches.update((events) => [...events, event.type]);- },- emissionState,- interrupts: [workflowInterrupt()],- tools: createTools(),- }),- );-- expect(contextStorage.run(callSession, () => lifecycleDispatches.get())).toEqual([- "actions.requested",- ]);- expect(contextStorage.run(buildSession, () => lifecycleDispatches.get())).toEqual([]);- });-});diff --git a/packages/eve/src/harness/workflow-lifecycle.ts b/packages/eve/src/harness/workflow-lifecycle.tsdeleted file mode 100644index 2923c798f..000000000--- a/packages/eve/src/harness/workflow-lifecycle.ts+++ /dev/null@@ -1,101 +0,0 @@-import type { ToolSet, TypedToolCall } from "ai";--import { createRuntimeToolResultFromValue } from "#harness/action-result-helpers.js";-import type { HarnessEmissionState } from "#harness/emission.js";-import {- collectActionPresentation,- createPresentedRuntimeActionRequestFromToolCall,-} from "#harness/action-presentation.js";-import type { HarnessEmitFn, HarnessToolMap } from "#harness/types.js";-import { createActionResultEvent, createActionsRequestedEvent } from "#protocol/message.js";-import type { WorkflowSandboxInterrupt } from "#shared/workflow-sandbox.js";-import {- getWorkflowSandboxInterrupt,- type WorkflowSandboxContinuationSecurity,-} from "#shared/workflow-sandbox.js";--export function createWorkflowLifecycle(input: {- readonly emit: EmitWorkflowLifecycleEvent;- readonly emissionState: HarnessEmissionState;- readonly skipReplayed?: boolean;- readonly tools: HarnessToolMap;-}): {- onAfterExecute?: (input: { readonly result: unknown }) => Promise<void>;-} {- return {- async onAfterExecute(result) {- if (input.skipReplayed) return;- const interrupt = await getWorkflowSandboxInterrupt(- result.result,- {} as WorkflowSandboxContinuationSecurity,- );- if (interrupt === undefined) return;- await emitWorkflowActionsRequested({- emit: input.emit,- emissionState: input.emissionState,- interrupts: [interrupt],- tools: input.tools,- });- },- };-}--type EmitWorkflowLifecycleEvent = HarnessEmitFn;--/** Projects newly parked workflow calls onto eve's existing action stream. */-export async function emitWorkflowActionsRequested(input: {- readonly emit: EmitWorkflowLifecycleEvent;- readonly emissionState: HarnessEmissionState;- readonly interrupts: readonly WorkflowSandboxInterrupt[];- readonly tools: HarnessToolMap;-}): Promise<void> {- for (const interrupt of input.interrupts) {- const toolCall = {- input: interrupt.input,- toolCallId: interrupt.toolCallId,- toolName: interrupt.toolName,- type: "tool-call",- } as TypedToolCall<ToolSet>;-- const projection = createPresentedRuntimeActionRequestFromToolCall({- toolCall,- tools: input.tools,- });- await input.emit(- createActionsRequestedEvent({- actions: [projection.action],- presentation: collectActionPresentation([projection]),- sequence: input.emissionState.sequence,- stepIndex: input.emissionState.stepIndex,- turnId: input.emissionState.turnId,- }),- );- }-}--/** Projects completed workflow children before replaying their continuation. */-export async function emitWorkflowActionResults(input: {- readonly emit: EmitWorkflowLifecycleEvent;- readonly emissionState: HarnessEmissionState;- readonly interrupts: readonly WorkflowSandboxInterrupt[];- readonly results: readonly { readonly isError?: boolean; readonly output?: unknown }[];-}): Promise<void> {- for (const [index, result] of input.results.entries()) {- const interrupt = input.interrupts[index];- if (interrupt === undefined) break;-- await input.emit(- createActionResultEvent({- result: createRuntimeToolResultFromValue({- callId: interrupt.toolCallId,- isError: result.isError,- output: result.output,- toolName: interrupt.toolName,- }),- sequence: input.emissionState.sequence,- stepIndex: input.emissionState.stepIndex,- turnId: input.emissionState.turnId,- }),- );- }-}diff --git a/packages/eve/src/harness/workflow-sandbox.scenario.test.ts b/packages/eve/src/harness/workflow-sandbox.scenario.test.tsdeleted file mode 100644index 9c77a44e6..000000000--- a/packages/eve/src/harness/workflow-sandbox.scenario.test.ts+++ /dev/null@@ -1,180 +0,0 @@-import { jsonSchema } from "ai";-import { describe, expect, it } from "vitest";--import type { HarnessToolDefinition } from "#harness/execute-tool.js";-import { getWorkflowTaskInterrupts } from "#harness/workflow-task-state.js";-import {- applyWorkflowTool,- resolveWorkflowSandboxBridgeRequestLimit,-} from "#harness/workflow-sandbox.js";-import { buildToolSet } from "#harness/tools.js";-import type { HarnessToolMap } from "#harness/types.js";-import {- continueWorkflowSandboxInterrupt,- getWorkflowSandboxInterrupt,- unwrapWorkflowSandboxResult,-} from "#shared/workflow-sandbox.js";--function orchestrationTools(): HarnessToolMap {- return new Map<string, HarnessToolDefinition>([- [- "echo-marker",- {- description: "Echo one marker.",- inputSchema: jsonSchema({- properties: { message: { type: "string" } },- required: ["message"],- type: "object",- }),- name: "echo-marker",- resultKind: "subagent",- workflowId: "workflow//./agent/subagents/researcher//execute",- },- ],- ]);-}--const concurrentProgram = `return await Promise.all([- tools["echo-marker"]({ message: "alpha" }),- tools["echo-marker"]({ message: "beta" }),-]);`;-const highFanOutCount = 50;-const highFanOutProgram = `return await Promise.all(Array.from(- { length: ${String(highFanOutCount)} },- (_, index) => tools["echo-marker"]({ message: "marker-" + String(index) }),-));`;-const overBudgetFanOutCount = 257;-const overBudgetFanOutProgram = `return await Promise.all(Array.from(- { length: ${String(overBudgetFanOutCount)} },- (_, index) => tools["echo-marker"]({ message: "over-budget-" + String(index) }),-));`;-const continuationSecurity = {- maxAgeMs: 365 * 24 * 60 * 60 * 1000,- signingKey: "workflow-sandbox-scenario-test-key",-};--describe("Workflow concurrent continuation", () => {- it("collects fan-out above code mode's default in-flight bridge limit", async () => {- const tools = orchestrationTools();- const { modelTools } = await applyWorkflowTool({- continuationSecurity,- harnessTools: tools,- maxSubagents: 100,- tools: buildToolSet({ tools }),- });- const execute = modelTools.Workflow?.execute as- | ((input: { js: string }, options: { messages: []; toolCallId: string }) => Promise<unknown>)- | undefined;-- const initialOutput = await execute!(- { js: highFanOutProgram },- { messages: [], toolCallId: "workflow-high-fan-out" },- );- const interrupt = await getWorkflowSandboxInterrupt(initialOutput, continuationSecurity);-- expect(getWorkflowTaskInterrupts(interrupt!)).toHaveLength(highFanOutCount);- });-- it("collects an over-budget call above the default bridge-request floor", async () => {- const tools = orchestrationTools();- const { modelTools } = await applyWorkflowTool({- continuationSecurity,- harnessTools: tools,- maxSubagents: 256,- tools: buildToolSet({ tools }),- });- const execute = modelTools.Workflow?.execute as- | ((input: { js: string }, options: { messages: []; toolCallId: string }) => Promise<unknown>)- | undefined;-- const initialOutput = await execute!(- { js: overBudgetFanOutProgram },- { messages: [], toolCallId: "workflow-over-budget-fan-out" },- );- const interrupt = await getWorkflowSandboxInterrupt(initialOutput, continuationSecurity);-- expect(getWorkflowTaskInterrupts(interrupt!)).toHaveLength(overBudgetFanOutCount);- });-- it("collects promptly interrupted Promise.all siblings in one ledger", async () => {- const tools = orchestrationTools();- const { modelTools } = await applyWorkflowTool({- continuationSecurity,- harnessTools: tools,- tools: buildToolSet({ tools }),- });- const execute = modelTools.Workflow?.execute as- | ((input: { js: string }, options: { messages: []; toolCallId: string }) => Promise<unknown>)- | undefined;-- const initialOutput = await execute!(- { js: concurrentProgram },- { messages: [], toolCallId: "workflow-call" },- );- const interrupt = await getWorkflowSandboxInterrupt(initialOutput, continuationSecurity);-- expect(interrupt!.continuation.auth.expiresAtMs - interrupt!.continuation.auth.issuedAtMs).toBe(- continuationSecurity.maxAgeMs,- );- expect(getWorkflowTaskInterrupts(interrupt!).map((entry) => entry.input)).toEqual([- { message: "alpha" },- { message: "beta" },- ]);- });-- it("preserves and resolves sibling interrupts in request order", async () => {- const tools = orchestrationTools();- const { hostTools, modelTools } = await applyWorkflowTool({- continuationSecurity,- harnessTools: tools,- tools: buildToolSet({ tools }),- });- const execute = modelTools.Workflow?.execute as- | ((input: { js: string }, options: { messages: []; toolCallId: string }) => Promise<unknown>)- | undefined;- expect(execute).toBeDefined();-- const initialOutput = await execute!(- { js: concurrentProgram },- { messages: [], toolCallId: "workflow-call" },- );- const racedInterrupt = await getWorkflowSandboxInterrupt(initialOutput, continuationSecurity);-- const pending = getWorkflowTaskInterrupts(racedInterrupt!);- expect(pending.map((interrupt) => interrupt.input)).toEqual([- { message: "alpha" },- { message: "beta" },- ]);-- const firstContinuation = await continueWorkflowSandboxInterrupt({- bridgeRequestLimit: resolveWorkflowSandboxBridgeRequestLimit(),- continuationSecurity,- interrupt: pending[0]!,- resolution: "alpha-result",- tools: hostTools,- });- const firstUnwrapped = await unwrapWorkflowSandboxResult(- firstContinuation,- continuationSecurity,- );- expect(firstUnwrapped).toMatchObject({- interrupt: { input: { message: "beta" } },- status: "interrupted",- });- if (firstUnwrapped.status !== "interrupted") throw new Error("Expected second interrupt.");-- const finalContinuation = await continueWorkflowSandboxInterrupt({- bridgeRequestLimit: resolveWorkflowSandboxBridgeRequestLimit(),- continuationSecurity,- interrupt: firstUnwrapped.interrupt,- resolution: "beta-result",- tools: hostTools,- });- await expect(- unwrapWorkflowSandboxResult(finalContinuation, continuationSecurity),- ).resolves.toEqual({- output: ["alpha-result", "beta-result"],- status: "completed",- });- });-});diff --git a/packages/eve/src/harness/workflow-sandbox.test.ts b/packages/eve/src/harness/workflow-sandbox.test.tsdeleted file mode 100644index c82e4b6f1..000000000--- a/packages/eve/src/harness/workflow-sandbox.test.ts+++ /dev/null@@ -1,186 +0,0 @@-import { asSchema, jsonSchema } from "ai";-import { describe, expect, it } from "vitest";--import type { HarnessToolDefinition } from "#harness/execute-tool.js";-import {- applyWorkflowTool,- buildWorkflowHostTools,- resolveWorkflowSandboxBridgeRequestLimit,-} from "#harness/workflow-sandbox.js";-import { buildToolSet } from "#harness/tools.js";-import type { HarnessToolMap } from "#harness/types.js";--const continuationSecurity = { signingKey: "workflow-sandbox-test-key" };--function orchestrationTools(): HarnessToolMap {- return new Map<string, HarnessToolDefinition>([- [- "researcher",- {- behavior: {- availability: [],- handling: {- kind: "dispatch",- target: {- kind: "subagent-call",- nodeId: "subagents/researcher",- subagentName: "researcher",- },- },- },- description: "Delegate to the researcher subagent.",- inputSchema: jsonSchema({ type: "object" }),- name: "researcher",- nodeId: "subagents/researcher",- resultKind: "subagent",- workflowId: "workflow//./agent/subagents/researcher//execute",- },- ],- [- "remote_reviewer",- {- description: "Delegate to the remote reviewer.",- inputSchema: jsonSchema({ type: "object" }),- name: "remote_reviewer",- resultKind: "subagent",- workflowId: "workflow//./agent/subagents/researcher//execute",- },- ],- [- "agent",- {- behavior: {- availability: ["root-session"],- handling: {- kind: "dispatch",- target: {- kind: "self-agent-call",- nodeId: "__root__",- subagentName: "agent",- },- },- },- description: "Delegate to a root-agent copy.",- inputSchema: jsonSchema({ type: "object" }),- name: "agent",- nodeId: "__root__",- resultKind: "subagent",- workflowId: "workflow//eve//subagentToolExecuteWorkflow",- },- ],- [- "bash",- {- description: "Run a shell command.",- execute: async () => "ok",- inputSchema: jsonSchema({ type: "object" }),- name: "bash",- },- ],- ]);-}--describe("applyWorkflowTool", () => {- it("keeps sandbox bridge capacity above the configured dispatch budget", () => {- expect(resolveWorkflowSandboxBridgeRequestLimit()).toBe(256);- expect(resolveWorkflowSandboxBridgeRequestLimit(100)).toBe(256);- expect(resolveWorkflowSandboxBridgeRequestLimit(255)).toBe(256);- expect(resolveWorkflowSandboxBridgeRequestLimit(256)).toBe(257);- expect(resolveWorkflowSandboxBridgeRequestLimit(300)).toBe(301);- });-- it("adds only agent workflow tasks to the sandbox", async () => {- const harnessTools = orchestrationTools();- const flatTools = buildToolSet({ tools: harnessTools });- const { hostTools, modelTools } = await applyWorkflowTool({- continuationSecurity,- harnessTools,- tools: flatTools,- });-- expect(modelTools.Workflow).toBeDefined();- expect(modelTools.researcher).toBeDefined();- expect(modelTools.remote_reviewer).toBeDefined();- expect(modelTools.bash).toBeDefined();- expect(hostTools.researcher?.execute).toBeDefined();- expect(hostTools.remote_reviewer?.execute).toBeDefined();- expect(hostTools.agent?.execute).toBeDefined();- expect(hostTools.bash).toBeUndefined();- });-- it("describes Workflow as an agents-only orchestrator", async () => {- const harnessTools = orchestrationTools();- const { modelTools } = await applyWorkflowTool({- continuationSecurity,- harnessTools,- tools: buildToolSet({ tools: harnessTools }),- });-- const description = (modelTools.Workflow as { description?: string }).description ?? "";- expect(description).toContain("Use `Workflow` for:");- expect(description).toContain("Do not use `Workflow` when:");- expect(description).toContain("Promise.all");- expect(description).toContain("researcher");- expect(description).toContain("Available agent API:");- expect(description).not.toContain("bash");- expect(description).not.toContain("code-mode");-- const inputSchema = asSchema(modelTools.Workflow?.inputSchema).jsonSchema;- expect(inputSchema).toMatchObject({- properties: {- js: { description: expect.stringContaining("JavaScript orchestration program") },- },- });- });-- it("does not add Workflow when no agent workflow tasks exist", async () => {- const harnessTools: HarnessToolMap = new Map([- [- "bash",- {- description: "Run a shell command.",- execute: async () => "ok",- inputSchema: jsonSchema({ type: "object" }),- name: "bash",- },- ],- ]);- const flatTools = buildToolSet({ tools: harnessTools });- const { hostTools, modelTools } = await applyWorkflowTool({- continuationSecurity,- harnessTools,- tools: flatTools,- });-- expect(modelTools.Workflow).toBeUndefined();- expect(modelTools.bash).toBeDefined();- expect(hostTools).toEqual({});- });-- it("rebuilds only workflow agent host tools for continuation", () => {- const hostTools = buildWorkflowHostTools({ tools: orchestrationTools() });-- expect(hostTools.researcher).toBeDefined();- expect(hostTools.remote_reviewer).toBeDefined();- expect(hostTools.agent).toBeDefined();- expect(hostTools.bash).toBeUndefined();- });-- it("does not construct ordinary tools while rebuilding the continuation surface", () => {- const tools: HarnessToolMap = new Map([- [- "bash",- {- description: "Run a shell command.",- execute: async () => "ok",- get inputSchema(): never {- throw new Error("ordinary tool schema should not be read");- },- name: "bash",- },- ],- ]);-- expect(buildWorkflowHostTools({ tools })).toEqual({});- });-});diff --git a/packages/eve/src/harness/workflow-sandbox.ts b/packages/eve/src/harness/workflow-sandbox.tsdeleted file mode 100644index b8dd8a671..000000000--- a/packages/eve/src/harness/workflow-sandbox.ts+++ /dev/null@@ -1,127 +0,0 @@-import type { ToolSet } from "ai";-import { z } from "#compiled/zod/index.js";--import type { HarnessToolDefinition } from "#harness/execute-tool.js";-import type { HarnessToolMap } from "#harness/types.js";-import { WORKFLOW_TASK_INTERRUPT_KIND } from "#harness/workflow-task-state.js";-import { DEFAULT_WORKFLOW_MAX_SUBAGENTS } from "#harness/workflow-subagent-limit.js";-import { workflowToolDescription } from "#harness/workflow-tool-description.js";-import {- createWorkflowSandboxTool,- readWorkflowSandboxResolution,- requestWorkflowSandboxInterrupt,- type WorkflowSandboxContinuationSecurity,- WORKFLOW_TOOL_NAME,-} from "#shared/workflow-sandbox.js";--interface WorkflowToolSet {- readonly hostTools: ToolSet;- readonly modelTools: ToolSet;-}--const DEFAULT_WORKFLOW_SANDBOX_BRIDGE_REQUEST_LIMIT = 256;--const workflowInputSchema = z.strictObject({- js: z- .string()- .describe(- "Complete JavaScript orchestration program. Call only the agents listed in the Workflow description and return one JSON-serializable result.",- ),-});--/**- * Adds the dynamic `Workflow` tool while leaving every ordinary model tool- * untouched. Only workflow-callable delegation tasks enter the sandbox.- */-export async function applyWorkflowTool(input: {- readonly continuationSecurity: WorkflowSandboxContinuationSecurity;- readonly harnessTools: HarnessToolMap;- readonly maxSubagents?: number;- readonly tools: ToolSet;-}): Promise<WorkflowToolSet> {- const hostTools = createWorkflowHostTools(input.harnessTools, Object.keys(input.tools));-- if (Object.keys(hostTools).length === 0) {- return { hostTools, modelTools: input.tools };- }-- const workflowTool = await createWorkflowSandboxTool({- bridgeRequestLimit: resolveWorkflowSandboxBridgeRequestLimit(input.maxSubagents),- continuationSecurity: input.continuationSecurity,- hostTools,- });- const generated = typeof workflowTool.description === "string" ? workflowTool.description : "";- const framing = workflowToolDescription(Object.keys(hostTools), {- maxSubagents: input.maxSubagents,- });- const apiReference = workflowApiReference(generated);- const modelTools: Record<string, ToolSet[string]> = { ...input.tools };- modelTools[WORKFLOW_TOOL_NAME] = {- ...workflowTool,- description: apiReference.length > 0 ? `${framing}\n\n${apiReference}` : framing,- inputSchema: workflowInputSchema,- } as ToolSet[string];-- return {- hostTools,- modelTools: modelTools as ToolSet,- };-}--/**- * Keeps code mode's bridge capacity strictly above eve's dispatch budget.- * The extra request lets the first over-budget call resolve through eve's- * `WORKFLOW_SUBAGENT_LIMIT_REACHED` result instead of failing the sandbox.- */-export function resolveWorkflowSandboxBridgeRequestLimit(maxSubagents?: number): number {- const dispatchBudget = maxSubagents ?? DEFAULT_WORKFLOW_MAX_SUBAGENTS;- return Math.max(DEFAULT_WORKFLOW_SANDBOX_BRIDGE_REQUEST_LIMIT, dispatchBudget + 1);-}--function workflowApiReference(generatedDescription: string): string {- const marker = "Tools:\n";- const start = generatedDescription.indexOf(marker);- if (start < 0) return generatedDescription;- return `Available agent API:\n${generatedDescription.slice(start + marker.length)}`;-}--/** Rebuilds the subagent-only host surface used to resume a parked workflow. */-export function buildWorkflowHostTools(input: { readonly tools: HarnessToolMap }): ToolSet {- return createWorkflowHostTools(input.tools, input.tools.keys());-}--function createWorkflowHostTools(tools: HarnessToolMap, names: Iterable<string>): ToolSet {- const hostTools: Record<string, ToolSet[string]> = {};-- for (const name of names) {- const tool = tools.get(name);- if (tool?.workflowId !== undefined) {- hostTools[name] = createWorkflowTaskHostTool(tool);- }- }-- return hostTools as ToolSet;-}--function createWorkflowTaskHostTool(harnessTool: HarnessToolDefinition): ToolSet[string] {- return {- description: harnessTool.description,- inputSchema: harnessTool.inputSchema,- execute: async (toolInput: unknown, options: unknown) => {- const resolution = readWorkflowSandboxResolution(options);- if (resolution !== undefined) return resolution;-- return requestWorkflowSandboxInterrupt({- kind: WORKFLOW_TASK_INTERRUPT_KIND,- task: {- executeInput: harnessTool.executeInput?.(toolInput),- nodeId: harnessTool.nodeId,- resultKind: harnessTool.resultKind,- workflowId: harnessTool.workflowId,- },- toolInput,- toolName: harnessTool.name,- });- },- } as ToolSet[string];-}diff --git a/packages/eve/src/harness/workflow-subagent-limit.test.ts b/packages/eve/src/harness/workflow-subagent-limit.test.tsdeleted file mode 100644index e1a3688dd..000000000--- a/packages/eve/src/harness/workflow-subagent-limit.test.ts+++ /dev/null@@ -1,76 +0,0 @@-import { describe, expect, it } from "vitest";--import {- DEFAULT_WORKFLOW_MAX_SUBAGENTS,- planWorkflowSubagentDispatch,-} from "#harness/workflow-subagent-limit.js";-import type { RuntimeWorkflowTaskRequest } from "#shared/action-types.js";--function createTask(index: number): RuntimeWorkflowTaskRequest {- return {- callId: `call-${index}`,- input: {},- kind: "workflow-task",- resultKind: "subagent",- toolName: "echo-marker",- workflowId: "workflow//./agent/subagents/researcher//execute",- };-}--describe("planWorkflowSubagentDispatch", () => {- it("allows every pending action while the budget holds", () => {- const tasks = [createTask(1), createTask(2)];- const plan = planWorkflowSubagentDispatch({- tasks,- maxSubagents: 3,- usedCalls: 0,- });-- expect(plan.allowed).toEqual(tasks);- expect(plan.blocked).toEqual([]);- expect(plan.usedCalls).toBe(0);- });-- it("blocks tasks beyond the remaining budget while preserving order", () => {- const tasks = [createTask(1), createTask(2), createTask(3)];- const plan = planWorkflowSubagentDispatch({- tasks,- maxSubagents: 3,- usedCalls: 1,- });-- expect(plan.allowed).toEqual([tasks[0], tasks[1]]);- expect(plan.blocked).toEqual([tasks[2]]);- expect(plan.usedCalls).toBe(1);- });-- it("does not charge ordinary workflow tasks against the subagent budget", () => {- const toolTask = { ...createTask(2), resultKind: "tool" as const };- const tasks = [createTask(1), toolTask, createTask(3)];-- const plan = planWorkflowSubagentDispatch({ tasks, maxSubagents: 1, usedCalls: 0 });-- expect(plan.allowed).toEqual([tasks[0], toolTask]);- expect(plan.blocked).toEqual([tasks[2]]);- });-- it("blocks everything once the persisted budget is spent", () => {- const plan = planWorkflowSubagentDispatch({- tasks: [createTask(1)],- maxSubagents: 2,- usedCalls: 2,- });-- expect(plan.allowed).toEqual([]);- expect(plan.blocked).toHaveLength(1);- });-- it("defaults the budget to DEFAULT_WORKFLOW_MAX_SUBAGENTS", () => {- const plan = planWorkflowSubagentDispatch({- tasks: [createTask(1)],- usedCalls: 0,- });-- expect(plan.maxSubagents).toBe(DEFAULT_WORKFLOW_MAX_SUBAGENTS);- });-});diff --git a/packages/eve/src/harness/workflow-subagent-limit.ts b/packages/eve/src/harness/workflow-subagent-limit.tsdeleted file mode 100644index aa5279eae..000000000--- a/packages/eve/src/harness/workflow-subagent-limit.ts+++ /dev/null@@ -1,54 +0,0 @@-import type { RuntimeWorkflowTaskRequest } from "#shared/action-types.js";--/**- * Default maximum number of subagent (and remote-agent) calls one `Workflow`- * tool invocation may dispatch.- */-export const DEFAULT_WORKFLOW_MAX_SUBAGENTS = 100;--/**- * Partition of one workflow interrupt's pending tasks against the invocation's- * subagent budget. Allowed tasks may dispatch; blocked tasks resolve with an- * error result instead of starting a child.- */-export type WorkflowSubagentDispatchPlan = {- readonly allowed: readonly RuntimeWorkflowTaskRequest[];- readonly blocked: readonly RuntimeWorkflowTaskRequest[];- readonly maxSubagents: number;- readonly usedCalls: number;-};--/**- * Splits the pending actions of one workflow interrupt into the prefix that- * still fits the invocation's `maxSubagents` budget and the remainder that- * must be blocked. Actions keep request order so results pair with the sandbox- * program's call order.- */-export function planWorkflowSubagentDispatch(input: {- readonly tasks: readonly RuntimeWorkflowTaskRequest[];- readonly maxSubagents?: number;- readonly usedCalls: number;-}): WorkflowSubagentDispatchPlan {- const maxSubagents = input.maxSubagents ?? DEFAULT_WORKFLOW_MAX_SUBAGENTS;- const usedCalls = input.usedCalls;- let remaining = Math.max(0, maxSubagents - usedCalls);- const allowed: RuntimeWorkflowTaskRequest[] = [];- const blocked: RuntimeWorkflowTaskRequest[] = [];- for (const task of input.tasks) {- if (task.resultKind !== "subagent") {- allowed.push(task);- } else if (remaining > 0) {- allowed.push(task);- remaining--;- } else {- blocked.push(task);- }- }-- return {- allowed,- blocked,- maxSubagents,- usedCalls,- };-}diff --git a/packages/eve/src/harness/workflow-task-state.test.ts b/packages/eve/src/harness/workflow-task-state.test.tsdeleted file mode 100644index abba5deee..000000000--- a/packages/eve/src/harness/workflow-task-state.test.ts+++ /dev/null@@ -1,120 +0,0 @@-import { describe, expect, it } from "vitest";--import {- buildWorkflowTasksFromInterrupt,- getWorkflowTaskCallIds,- getWorkflowTaskInterrupts,- WORKFLOW_TASK_INTERRUPT_KIND,-} from "#harness/workflow-task-state.js";-import type { WorkflowSandboxInterrupt } from "#shared/workflow-sandbox.js";--function concurrentWorkflowInterrupt(): WorkflowSandboxInterrupt {- const pendingInterruptions = ["alpha", "beta"].map((message, index) => {- const toolCallId = `workflow-call:tool-${index + 1}`;- return {- input: { message },- interruptId: `${toolCallId}:interrupt`,- payload: {- kind: WORKFLOW_TASK_INTERRUPT_KIND,- task: {- action: "subagent-call" as const,- nodeId: "subagents/researcher",- resultKind: "subagent",- workflowId: "workflow//./agent/subagents/researcher//execute",- },- toolInput: { message },- toolName: "echo-marker",- },- runInterruptionId: `run-interruption-${index + 1}`,- toolCallId,- toolName: "echo-marker",- };- });- const continuation = {- auth: {- alg: "HMAC-SHA256" as const,- expiresAtMs: 2,- issuedAtMs: 1,- nonce: "nonce",- signature: "signature",- },- js: "return Promise.all([])",- outerToolCallId: "workflow-call",- pendingInterruptions,- resolutions: [],- token: "token",- toolNames: ["echo-marker"],- version: 2 as const,- };- const returned = pendingInterruptions[1]!;-- return {- continuation,- input: { message: "beta" },- interruptId: returned.interruptId,- outerToolCallId: continuation.outerToolCallId,- payload: returned.payload,- toolCallId: returned.toolCallId,- toolName: returned.toolName,- type: "code-mode-interrupt",- };-}--describe("workflow task state", () => {- it("derives concurrent tasks in request order when a later interrupt wins the race", () => {- const interrupt = concurrentWorkflowInterrupt();-- const pending = getWorkflowTaskInterrupts(interrupt);- expect(pending.map((entry) => entry.input)).toEqual([- { message: "alpha" },- { message: "beta" },- ]);- expect(pending.map((entry) => entry.toolCallId)).toEqual([- "workflow-call:tool-1",- "workflow-call:tool-2",- ]);-- expect(buildWorkflowTasksFromInterrupt(interrupt)).toMatchObject([- {- callId: "echo-marker_workflow-call_tool-1_interrupt",- input: { message: "alpha" },- kind: "workflow-task",- nodeId: "subagents/researcher",- resultKind: "subagent",- toolName: "echo-marker",- workflowId: "workflow//./agent/subagents/researcher//execute",- },- {- callId: "echo-marker_workflow-call_tool-2_interrupt",- input: { message: "beta" },- kind: "workflow-task",- nodeId: "subagents/researcher",- resultKind: "subagent",- toolName: "echo-marker",- workflowId: "workflow//./agent/subagents/researcher//execute",- },- ]);- expect(getWorkflowTaskCallIds(interrupt)).toEqual([- "echo-marker_workflow-call_tool-1_interrupt",- "echo-marker_workflow-call_tool-2_interrupt",- ]);- });-- it("excludes interruptions already resolved in the current continuation batch", () => {- const interrupt = concurrentWorkflowInterrupt();- const resumed = {- ...interrupt,- continuation: {- ...interrupt.continuation,- resolutions: [{ runInterruptionId: "run-interruption-1", value: "alpha-result" }],- },- input: { message: "beta" },- interruptId: "workflow-call:tool-2:interrupt",- toolCallId: "workflow-call:tool-2",- };-- expect(getWorkflowTaskInterrupts(resumed).map((entry) => entry.input)).toEqual([- { message: "beta" },- ]);- });-});diff --git a/packages/eve/src/harness/workflow-task-state.ts b/packages/eve/src/harness/workflow-task-state.tsdeleted file mode 100644index 14c9a7139..000000000--- a/packages/eve/src/harness/workflow-task-state.ts+++ /dev/null@@ -1,78 +0,0 @@-import type { RuntimeWorkflowTaskRequest } from "#shared/action-types.js";-import type { JsonObject } from "#shared/json.js";-import {- getWorkflowSandboxPendingInterrupts,- type WorkflowSandboxInterrupt,-} from "#shared/workflow-sandbox.js";--export const WORKFLOW_TASK_INTERRUPT_KIND = "eve.workflow-task";--interface SerializedWorkflowTaskDefinition {- readonly executeInput?: import("#shared/json.js").JsonValue;- readonly nodeId?: string;- readonly resultKind?: "subagent" | "tool";- readonly workflowId: string;-}--export function isWorkflowTaskInterrupt(interrupt: unknown): boolean {- return (- isRecord(interrupt) &&- isRecord(interrupt.payload) &&- interrupt.payload.kind === WORKFLOW_TASK_INTERRUPT_KIND- );-}--export function buildWorkflowTaskFromInterrupt(- interrupt: WorkflowSandboxInterrupt,-): RuntimeWorkflowTaskRequest {- const raw = interrupt.payload as Record<string, unknown>;- const task = raw.task as SerializedWorkflowTaskDefinition | undefined;- const toolInput = raw.toolInput as JsonObject;- const toolName = raw.toolName as string;- const interruptId = "interruptId" in interrupt ? String(interrupt.interruptId) : "";- const callId = sanitizeCallId(`${toolName}_${interruptId}`);-- if (task === undefined || typeof task.workflowId !== "string") {- throw new Error("Workflow delegation interrupts require a workflow task.");- }- const result: {- -readonly [K in keyof RuntimeWorkflowTaskRequest]: RuntimeWorkflowTaskRequest[K];- } = {- callId,- executeInput: task.executeInput,- input: toolInput,- kind: "workflow-task",- resultKind: task.resultKind,- toolName,- workflowId: task.workflowId,- };- if (task.nodeId !== undefined) result.nodeId = task.nodeId;- return result;-}--/** Returns every pending workflow-task interrupt in deterministic ledger order. */-export function getWorkflowTaskInterrupts(- interrupt: WorkflowSandboxInterrupt,-): WorkflowSandboxInterrupt[] {- return getWorkflowSandboxPendingInterrupts(interrupt).filter(isWorkflowTaskInterrupt);-}--export function buildWorkflowTasksFromInterrupt(- interrupt: WorkflowSandboxInterrupt,-): RuntimeWorkflowTaskRequest[] {- return getWorkflowTaskInterrupts(interrupt).map((pending) =>- buildWorkflowTaskFromInterrupt(pending),- );-}--export function getWorkflowTaskCallIds(interrupt: WorkflowSandboxInterrupt): string[] {- return buildWorkflowTasksFromInterrupt(interrupt).map((task) => task.callId);-}--function sanitizeCallId(id: string): string {- return id.replace(/[^a-zA-Z0-9_-]/g, "_");-}--function isRecord(value: unknown): value is Record<string, unknown> {- return typeof value === "object" && value !== null && !Array.isArray(value);-}diff --git a/packages/eve/src/harness/workflow-tool-description.test.ts b/packages/eve/src/harness/workflow-tool-description.test.tsdeleted file mode 100644index 8d274c19c..000000000--- a/packages/eve/src/harness/workflow-tool-description.test.ts+++ /dev/null@@ -1,48 +0,0 @@-import { describe, expect, it } from "vitest";--import { workflowToolDescription } from "#harness/workflow-tool-description.js";--describe("workflowToolDescription", () => {- it("explains when orchestration is and is not appropriate", () => {- const description = workflowToolDescription(["agent", "researcher"]);-- expect(description).toContain("Use `Workflow` for:");- expect(description).toContain("Do not use `Workflow` when:");- expect(description).toContain("map-reduce");- expect(description).toContain("dependent pipelines");- expect(description).toContain("one delegation");- expect(description).toContain("small fixed set");- expect(description).toContain("ordinary tools");- });-- it("advertises the default subagent-call budget", () => {- const description = workflowToolDescription(["agent"]);-- expect(description).toContain("at most 100 agent calls");- expect(description).toContain("WORKFLOW_SUBAGENT_LIMIT_REACHED");- });-- it("advertises a configured subagent-call budget", () => {- const description = workflowToolDescription(["agent"], { maxSubagents: 4 });-- expect(description).toContain("at most 4 agent calls");- });-- it("names every callable agent and safely formats a hyphenated subagent example", () => {- const description = workflowToolDescription(["agent", "echo-marker", "stock_price"]);-- expect(description).toContain("`agent`");- expect(description).toContain("`echo-marker`");- expect(description).toContain("`stock_price`");- expect(description).toContain('tools["echo-marker"]({');- expect(description).not.toContain("tools.echo-marker");- });-- it("omits the subagent example and demonstrates agent() when only the built-in agent is callable", () => {- const description = workflowToolDescription(["agent"]);-- expect(description).toContain("`agent`");- expect(description).toContain("agent({");- expect(description).not.toContain("researcher");- });-});diff --git a/packages/eve/src/harness/workflow-tool-description.ts b/packages/eve/src/harness/workflow-tool-description.tsdeleted file mode 100644index d2366db12..000000000--- a/packages/eve/src/harness/workflow-tool-description.ts+++ /dev/null@@ -1,78 +0,0 @@-import { DEFAULT_WORKFLOW_MAX_SUBAGENTS } from "#harness/workflow-subagent-limit.js";--/**- * Builds the model-facing description for the `Workflow` orchestration tool.- *- * Dynamic in the agent's callable agents:- * - lists every callable agent by name (the built-in `agent` plus one per- * declared subagent and remote agent);- * - the worked example uses only the built-in `agent`, so it is valid for any- * agent;- * - a single simple subagent example is appended *only when* the agent has a- * declared subagent or remote agent (i.e. an agent other than `agent`).- *- * The sandbox package's generated input signatures are appended after this- * framing.- *- * @param toolNames - Names of the agent functions callable inside the sandbox.- * @param options - `maxSubagents`: the invocation's subagent-call budget- * (defaults to {@link DEFAULT_WORKFLOW_MAX_SUBAGENTS}), surfaced so the- * model sizes its fan-out to fit.- */-export function workflowToolDescription(- toolNames: readonly string[],- options?: { readonly maxSubagents?: number },-): string {- const maxSubagents = options?.maxSubagents ?? DEFAULT_WORKFLOW_MAX_SUBAGENTS;- const agents = toolNames.length > 0 ? toolNames : ["agent"];- const list = agents.map((name) => `\`${name}\``).join(", ");- const subagents = agents.filter((name) => name !== "agent");- const subagentExample =- subagents.length > 0- ? `\n\nDeclared subagents use the same API — e.g. \`const note = await ${agentAccess(subagents[0]!)}({ message: "..." });\`.`- : "";-- return `Use \`Workflow\` when a task needs JavaScript to coordinate multiple child-agent calls as one durable step. It is an orchestration tool, not a general-purpose tool runner.--Use \`Workflow\` for:-- fan-out or map-reduce over a list, especially when the number of calls comes from runtime data;-- dependent pipelines where one agent's result becomes another agent's input;-- conditional branches or follow-up calls chosen from earlier results;-- deterministic filtering, sorting, or aggregation of several agent results before returning one value.--Do not use \`Workflow\` when:-- one delegation, or a small fixed set of unrelated delegations, can be called directly;-- no child-agent call is needed;-- the task needs files, network, shell, connections, skills, or ordinary tools — none are available inside Workflow;-- JavaScript would only wrap work the parent agent can express more clearly with direct calls.--Workflow earns its overhead when code materially controls call count, concurrency, ordering, data flow, or aggregation. Put the complete orchestration in one JavaScript program and return the final JSON-serializable value.--One Workflow program may dispatch at most ${String(maxSubagents)} agent calls in total (sequential and parallel calls alike); calls beyond that budget fail with \`WORKFLOW_SUBAGENT_LIMIT_REACHED\` instead of running. Size fan-outs to fit the budget.--The only callable operations are these agents — no filesystem, network, shell, or other tools: ${list}. Call them only through the \`tools\` object, using the exact member syntax in the API reference below. Each call is async and resolves to the child's result, or a typed object when you pass an \`outputSchema\`. Sequence with \`await\`, run agents concurrently with \`Promise.all([...])\`, and use \`map\`/\`filter\`/\`flatMap\` to build calls and combine results. The program's return value becomes the tool result.--Example — fan out across areas with \`agent\`, then pipe the results into a synthesis step:-\`\`\`js-const areas = ["correctness", "security", "performance"];-const reviews = await Promise.all(- areas.map((area) =>- tools.agent({- message: \`Review the change for \${area}.\`,- outputSchema: { type: "object", properties: { findings: { type: "array", items: { type: "string" } } } },- }),- ),-);-const verdict = await tools.agent({- message: \`Summarize these findings into a verdict: \${JSON.stringify(reviews)}\`,- outputSchema: { type: "object", properties: { verdict: { type: "string" }, blocking: { type: "boolean" } } },-});-return verdict;-\`\`\`${subagentExample}`;-}--function agentAccess(name: string): string {- return /^[A-Za-z_$][A-Za-z0-9_$]*$/u.test(name)- ? `tools.${name}`- : `tools[${JSON.stringify(name)}]`;-}diff --git a/packages/eve/src/internal/authored-definition/schema-backed.test.ts b/packages/eve/src/internal/authored-definition/schema-backed.test.tsindex 766c6d4e3..2499c4913 100644--- a/packages/eve/src/internal/authored-definition/schema-backed.test.ts+++ b/packages/eve/src/internal/authored-definition/schema-backed.test.ts@@ -4,7 +4,6 @@ import { z } from "#compiled/zod/index.js";import { defineDynamic } from "#dynamic/definition.js";import { defineTool, disableTool } from "#tools/definition.js";-import { experimental_workflow } from "#tools/workflow.js";import { once } from "#tools/approval/policies.js";import { webSearch } from "#tools/provided/web-search.js";import { normalizeToolDefinition } from "#internal/authored-definition/schema-backed.js";@@ -78,15 +77,6 @@ describe("normalizeToolDefinition", () => {expect(entry).toEqual({ kind: "disabled" });});- it("returns a configured entry for the experimental Workflow tool", () => {- const entry = normalizeToolDefinition(- experimental_workflow({ maxSubagents: 6 }),- FAILURE_MESSAGE,- );-- expect(entry).toEqual({ kind: "workflow-tool", maxSubagents: 6 });- });-it("returns a configured entry for the provider-managed web search tool", () => {expect(normalizeToolDefinition(webSearch({ provider: "exa" }), FAILURE_MESSAGE)).toEqual({kind: "web-search-tool",@@ -100,15 +90,6 @@ describe("normalizeToolDefinition", () => {).toThrow('Expected "provider" to be one of: exa, parallel');});- it.each([0, 1.5, -1, "6"])("rejects invalid workflow max subagents %j", (maxSubagents) => {- expect(() =>- normalizeToolDefinition(- experimental_workflow({ maxSubagents: maxSubagents as number }),- FAILURE_MESSAGE,- ),- ).toThrow(FAILURE_MESSAGE);- });-it("rejects authored tool exports that carry an authored `name` field", () => {expect(() =>normalizeToolDefinition(diff --git a/packages/eve/src/internal/authored-definition/schema-backed.ts b/packages/eve/src/internal/authored-definition/schema-backed.tsindex 97717c102..ecacc6814 100644--- a/packages/eve/src/internal/authored-definition/schema-backed.ts+++ b/packages/eve/src/internal/authored-definition/schema-backed.ts@@ -1,17 +1,19 @@import { isWorkflowToolDefinition } from "#tools/workflow-definition.js";import { readWorkflowFunctionId } from "#internal/workflow/reference.js";import { isDisabledToolSentinel } from "#tools/definition.js";-import { isExperimentalWorkflowToolDefinition } from "#tools/workflow.js";import { isWebSearchToolDefinition } from "#tools/provided/web-search.js";import {expectFunction,expectObjectRecord,expectOnlyKnownKeys,- expectPositiveInteger,expectString,} from "#internal/authored-module.js";import type { InternalToolDefinition, ToolExecuteFn } from "#tools/definition.js";import { readToolBehavior, type CompiledToolBehavior } from "#tools/behavior.js";+import {+ readWorkflowProgramOptions,+ type WorkflowProgramOptions,+} from "#tools/workflow-program-input.js";import {serializeInputSchema,serializeOutputSchema,@@ -38,6 +40,7 @@ type NormalizedAuthoredTool = Readonly<readonly hasApproval: boolean;readonly hasExecute: boolean;readonly hasModelOutputProjection: boolean;+ readonly workflowProgram?: WorkflowProgramOptions;}>;type MutableNormalizedAuthoredTool = {@@ -54,7 +57,6 @@ type MutableNormalizedAuthoredTool = {type NormalizedToolEntry =| { readonly kind: "tool"; readonly definition: NormalizedAuthoredTool }| { readonly kind: "disabled" }- | { readonly kind: "workflow-tool"; readonly maxSubagents?: number }| { readonly kind: "web-search-tool"; readonly provider: "exa" | "parallel" }| {readonly kind: "dynamic-tool";@@ -65,7 +67,7 @@ type NormalizedToolEntry =/*** Normalizes one authored tool default export. Recognizes real tool* definitions (`defineTool(...)`), disable sentinels (`disableTool()`), and the- * experimental `Workflow` tool definition.+ * provider-managed web-search definitions.** Authored `name` fields are rejected — tool identity is path-derived.*/@@ -81,17 +83,6 @@ export function normalizeToolDefinition(value: unknown, message: string): Normalif (isDisabledToolSentinel(value)) {return { kind: "disabled" };}- if (isExperimentalWorkflowToolDefinition(value)) {- const record = expectObjectRecord(value, message);- expectOnlyKnownKeys(record, ["kind", "maxSubagents"], message);- return {- kind: "workflow-tool",- maxSubagents:- record.maxSubagents === undefined- ? undefined- : expectPositiveInteger(record.maxSubagents, message),- };- }if (isWebSearchToolDefinition(value)) {const record = expectObjectRecord(value, message);expectOnlyKnownKeys(record, ["kind", "provider"], message);@@ -137,6 +128,7 @@ export function normalizeToolDefinition(value: unknown, message: string): Normal: serializeInputSchema(record.inputSchema as ToolSchemaSource);const outputSchema = serializeOutputSchema(record.outputSchema as ToolSchemaSource | undefined);const behavior = readToolBehavior(value);+ const workflowProgram = readWorkflowProgramOptions(value);const hasExecute = record.execute !== undefined;if (!hasExecute &&@@ -155,6 +147,9 @@ export function normalizeToolDefinition(value: unknown, message: string): Normalif (behavior !== undefined) {definition.behavior = behavior;}+ if (workflowProgram !== undefined) {+ definition.workflowProgram = workflowProgram;+ }if (hasExecute) {definition.execute = expectFunction(record.execute, message) as ToolExecuteFn;}diff --git a/packages/eve/src/internal/nitro/host/create-application-nitro.scenario.test.ts b/packages/eve/src/internal/nitro/host/create-application-nitro.scenario.test.tsindex 78f3bb884..c9468311f 100644--- a/packages/eve/src/internal/nitro/host/create-application-nitro.scenario.test.ts+++ b/packages/eve/src/internal/nitro/host/create-application-nitro.scenario.test.ts@@ -31,6 +31,9 @@ import {import { applyWorkflowTransform } from "#internal/workflow-bundle/workflow-builders.js";import { useTemporaryDirectories } from "#internal/testing/use-temporary-app-roots.js";import { defineChannel, WS } from "#public/definitions/channel.js";+import { defineTool } from "#tools/definition.js";+import { defineWorkflowTool } from "#tools/workflow-definition.js";+import { attachWorkflowProgramOptions } from "#tools/workflow-program-input.js";const configureDevelopmentNitroRoutes = vi.fn(async () => undefined);const configureProductionNitroRoutes = vi.fn(async () => undefined);@@ -92,27 +95,64 @@ function createNitroStub(input: { buildDir?: string; dev?: boolean } = {}): Nitr}async function createPreparedHost(- input: { readonly websocket?: boolean } = {},+ input: {+ readonly tool?: "ordinary" | "workflow" | "workflow-program";+ readonly websocket?: boolean;+ } = {},): Promise<PreparedDevelopmentApplicationHost> {const appRoot = "/tmp/weather-agent";const paths = resolveCompilerArtifactPaths(appRoot);+ const modules: Array<NonNullable<Parameters<typeof compileFromMemory>[0]["modules"]>[number]> =+ [];+ if (input.websocket === true) {+ modules.push({+ logicalPath: "channels/voice.ts",+ loadNamespace: async () => ({+ default: defineChannel({+ routes: [WS("/eve/v1/voice/ws", async () => ({ open() {} }))],+ }),+ }),+ });+ }+ if (input.tool === "ordinary") {+ modules.push({+ logicalPath: "tools/weather.ts",+ loadNamespace: async () => ({+ default: defineTool({+ description: "Check the weather.",+ execute: async () => null,+ inputSchema: {},+ }),+ }),+ });+ }+ if (input.tool === "workflow" || input.tool === "workflow-program") {+ const execute = Object.assign(async () => null, {+ workflowId: "workflow//agent/tools/run-program//execute",+ });+ const definition = defineWorkflowTool({+ description: "Run a workflow.",+ execute,+ inputSchema: {},+ });+ const exportedDefinition =+ input.tool === "workflow-program"+ ? attachWorkflowProgramOptions(definition, {+ maxSubagents: 4,+ })+ : definition;+ modules.push({+ logicalPath: "tools/run-program.ts",+ loadNamespace: async () => ({+ default: exportedDefinition,+ }),+ });+ }const { manifest } = await compileFromMemory({agentRoot: `${appRoot}/agent`,appRoot,model: "openai/gpt-5.4",- modules:- input.websocket === true- ? [- {- logicalPath: "channels/voice.ts",- loadNamespace: async () => ({- default: defineChannel({- routes: [WS("/eve/v1/voice/ws", async () => ({ open() {} }))],- }),- }),- },- ]- : [],+ modules,name: "weather-agent",});const metadata: CompileMetadata = {@@ -695,33 +735,77 @@ describe("application Nitro creation", () => {expect(createNitroMock.mock.calls[0]?.[0].traceDeps).toEqual([]);});- it("includes the Workflow sandbox runtime plugin only when Workflow is enabled", async () => {- const directNitroStub = createNitroStub();+ it("includes the workflow sandbox runtime plugin only for generated-program tools", async () => {+ const ordinaryNitroStub = createNitroStub();const workflowNitroStub = createNitroStub();- createNitroMock.mockResolvedValueOnce(directNitroStub.nitro);+ const workflowProgramNitroStub = createNitroStub();+ createNitroMock.mockResolvedValueOnce(ordinaryNitroStub.nitro);createNitroMock.mockResolvedValueOnce(workflowNitroStub.nitro);+ createNitroMock.mockResolvedValueOnce(workflowProgramNitroStub.nitro);const { createProductionApplicationNitro } =await import("#internal/nitro/host/create-application-nitro.js");- const directHost = await createPreparedHost();- const workflowHost = await createPreparedHost();- workflowHost.compileResult.manifest.workflowTool = {- logicalPath: "tools/workflow.ts",- sourceId: "test:workflow",- sourceKind: "module",- };+ const ordinaryHost = await createPreparedHost({ tool: "ordinary" });+ const workflowHost = await createPreparedHost({ tool: "workflow" });+ const workflowProgramHost = await createPreparedHost({ tool: "workflow-program" });- await createProductionApplicationNitro(directHost, createProductionOptions(directHost));+ await createProductionApplicationNitro(ordinaryHost, createProductionOptions(ordinaryHost));await createProductionApplicationNitro(workflowHost, createProductionOptions(workflowHost));+ await createProductionApplicationNitro(+ workflowProgramHost,+ createProductionOptions(workflowProgramHost),+ );- const directPlugins = createNitroMock.mock.calls[0]?.[0].plugins as string[];+ const ordinaryPlugins = createNitroMock.mock.calls[0]?.[0].plugins as string[];const workflowPlugins = createNitroMock.mock.calls[1]?.[0].plugins as string[];+ const workflowProgramPlugins = createNitroMock.mock.calls[2]?.[0].plugins as string[];- expect(directPlugins).not.toEqual(+ expect(ordinaryPlugins).not.toEqual(+ expect.arrayContaining([expect.stringContaining("workflow-sandbox-runtime-plugin.ts")]),+ );+ expect(workflowPlugins).not.toEqual(expect.arrayContaining([expect.stringContaining("workflow-sandbox-runtime-plugin.ts")]),);- expect(workflowPlugins).toEqual(+ expect(workflowProgramPlugins).toEqual(+ expect.arrayContaining([expect.stringContaining("workflow-sandbox-runtime-plugin.ts")]),+ );+ });++ it("includes the workflow sandbox runtime plugin for a subagent generated-program tool", async () => {+ const nitroStub = createNitroStub();+ createNitroMock.mockResolvedValueOnce(nitroStub.nitro);++ const { createProductionApplicationNitro } =+ await import("#internal/nitro/host/create-application-nitro.js");+ const preparedHost = await createPreparedHost();+ const generatedProgramHost = await createPreparedHost({ tool: "workflow-program" });+ const {+ kind: _kind,+ subagents: _subagents,+ version: _version,+ ...subagentAgent+ } = generatedProgramHost.compileResult.manifest;+ preparedHost.compileResult.manifest.subagents = [+ {+ agent: subagentAgent,+ backing: { kind: "resource", sourcePath: "/tmp/weather-agent/agent/subagents/researcher" },+ description: "Researches questions.",+ entryPath: "subagents/researcher",+ logicalPath: "subagents/researcher/agent.ts",+ name: "researcher",+ nodeId: "root:subagents/researcher",+ owner: { kind: "application" },+ parentNodeId: "__root__",+ rootPath: "/tmp/weather-agent/agent/subagents/researcher",+ sourceId: "subagents/researcher/agent.ts",+ sourceKind: "module",+ },+ ];++ await createProductionApplicationNitro(preparedHost, createProductionOptions(preparedHost));++ expect(createNitroMock.mock.calls[0]?.[0].plugins).toEqual(expect.arrayContaining([expect.stringContaining("workflow-sandbox-runtime-plugin.ts")]),);});diff --git a/packages/eve/src/internal/nitro/host/create-application-nitro.ts b/packages/eve/src/internal/nitro/host/create-application-nitro.tsindex 806ed3521..c513f8c4e 100644--- a/packages/eve/src/internal/nitro/host/create-application-nitro.ts+++ b/packages/eve/src/internal/nitro/host/create-application-nitro.ts@@ -77,10 +77,10 @@ function resolveProductionNitroPreset(): "vercel" | undefined {return process.env.VERCEL ? "vercel" : undefined;}-/** Whether any agent needs the dynamic Workflow sandbox runtime. */-function manifestEnablesWorkflow(manifest: CompiledAgentManifest): boolean {+/** Whether any agent exposes a generated-program tool that needs the workflow sandbox runtime. */+function manifestHasWorkflowProgram(manifest: CompiledAgentManifest): boolean {const nodes = [manifest, ...manifest.subagents.map((subagent) => subagent.agent)];- return nodes.some((node) => node.workflowTool !== undefined);+ return nodes.some((node) => node.tools.some((tool) => tool.workflowProgram !== undefined));}function manifestHasWebSocketChannel(manifest: CompiledAgentManifest): boolean {@@ -662,7 +662,7 @@ function createApplicationNitroPlugins(preparedHost: PreparedApplicationHost): spreparedHost.compiledArtifacts.bootstrapPath,preparedHost.compiledArtifacts.workflowWorldPluginPath,];- if (manifestEnablesWorkflow(preparedHost.compileResult.manifest)) {+ if (manifestHasWorkflowProgram(preparedHost.compileResult.manifest)) {nitroPlugins.push(resolvePackageSourceFilePath("src/internal/nitro/host/workflow-sandbox-runtime-plugin.ts"),);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.tsindex baabeb117..6e66d3bbf 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@@ -8,6 +8,9 @@ import { computeDevelopmentHostFingerprint } from "#internal/nitro/host/dev-hostimport type { PreparedDevelopmentApplicationHost } from "#internal/nitro/host/types.js";import { defineChannel, GET } from "#public/definitions/channel.js";import { defineSchedule } from "#public/definitions/schedule.js";+import { defineTool } from "#tools/definition.js";+import { defineWorkflowTool } from "#tools/workflow-definition.js";+import { attachWorkflowProgramOptions } from "#tools/workflow-program-input.js";const temporaryDirectories: string[] = [];@@ -25,6 +28,7 @@ interface HostVariant {readonly instrumentationSlot?: string;readonly instrumentationSource?: string;readonly schedule?: { readonly cron: string; readonly markdown: string };+ readonly tool?: "ordinary" | "workflow" | "workflow-program";readonly workflowSourceFingerprint?: string;readonly workflowWorld?: "local" | "vercel";}@@ -64,6 +68,40 @@ async function createHost(variant: HostVariant = {}): Promise<PreparedDevelopmen}),},]),+ ...(variant.tool === undefined+ ? []+ : [+ {+ logicalPath: "tools/run.ts",+ loadNamespace: async () => {+ if (variant.tool === "ordinary") {+ return {+ default: defineTool({+ description: "Run a tool.",+ execute: async () => null,+ inputSchema: {},+ }),+ };+ }+ const execute = Object.assign(async () => null, {+ workflowId: "workflow//agent/tools/run//execute",+ });+ const definition = defineWorkflowTool({+ description: "Run a workflow.",+ execute,+ inputSchema: {},+ });+ return {+ default:+ variant.tool === "workflow-program"+ ? attachWorkflowProgramOptions(definition, {+ maxSubagents: 4,+ })+ : definition,+ };+ },+ },+ ]),];const { manifest } = await compileFromMemory({agentRoot,@@ -182,6 +220,23 @@ describe("computeDevelopmentHostFingerprint", () => {expect(edited).not.toBe(withWorkflows);});+ it("treats only generated-program tool availability as structural", async () => {+ const base = await computeDevelopmentHostFingerprint(await createHost());+ const ordinary = await computeDevelopmentHostFingerprint(+ await createHost({ tool: "ordinary" }),+ );+ const workflow = await computeDevelopmentHostFingerprint(+ await createHost({ tool: "workflow" }),+ );+ const workflowProgram = await computeDevelopmentHostFingerprint(+ await createHost({ tool: "workflow-program" }),+ );++ expect(ordinary).toBe(base);+ expect(workflow).toBe(base);+ expect(workflowProgram).not.toBe(base);+ });+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.tsindex 5e57502ec..f121d2cae 100644--- a/packages/eve/src/internal/nitro/host/dev-host-fingerprint.ts+++ b/packages/eve/src/internal/nitro/host/dev-host-fingerprint.ts@@ -47,7 +47,9 @@ export async function computeDevelopmentHostFingerprint(// 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),+ enabled: agentNodes.some((node) =>+ node.tools.some((tool) => tool.workflowProgram !== undefined),+ ),world: manifest.config.experimental?.workflow?.world ?? "local",},};diff --git a/packages/eve/src/internal/nitro/host/workflow-sandbox-runtime-plugin.ts b/packages/eve/src/internal/nitro/host/workflow-sandbox-runtime-plugin.tsindex 9753fd435..1b4b5c42c 100644--- a/packages/eve/src/internal/nitro/host/workflow-sandbox-runtime-plugin.ts+++ b/packages/eve/src/internal/nitro/host/workflow-sandbox-runtime-plugin.ts@@ -1,16 +1,16 @@import {+ CodeModeToolError,experimental_continueCodeModeInterrupt as continueCodeModeInterrupt,experimental_createCodeModeTool as createCodeModeTool,- experimental_getCodeModeInterrupt as getCodeModeInterrupt,experimental_requestCodeModeInterrupt as requestCodeModeInterrupt,experimental_unwrapCodeModeResult as unwrapCodeModeResult,} from "#compiled/@ai-sdk/code-mode/index.js";import { installWorkflowSandboxModule } from "#shared/workflow-sandbox.js";installWorkflowSandboxModule({+ CodeModeToolError,continueCodeModeInterrupt,createCodeModeTool,- getCodeModeInterrupt,requestCodeModeInterrupt,unwrapCodeModeResult,});diff --git a/packages/eve/src/internal/nitro/routes/agent-info/build-agent-info-response.test.ts b/packages/eve/src/internal/nitro/routes/agent-info/build-agent-info-response.test.tsindex 586f40f3d..3476e9018 100644--- a/packages/eve/src/internal/nitro/routes/agent-info/build-agent-info-response.test.ts+++ b/packages/eve/src/internal/nitro/routes/agent-info/build-agent-info-response.test.ts@@ -4,7 +4,6 @@ import { compileFromMemory } from "#compiler/compile-from-memory.js";import { AgentInfoResultSchema } from "#client/agent-info-schema.js";import { buildAgentInfoResponse } from "#internal/nitro/routes/agent-info/build-agent-info-response.js";import { defineInstrumentation } from "#public/instrumentation/index.js";-import { experimental_workflow } from "#tools/workflow.js";import { webSearch } from "#tools/provided/web-search.js";import { defineMemory } from "#public/memory/index.js";@@ -157,35 +156,6 @@ describe("buildAgentInfoResponse", () => {});});- it("reports selected Workflow provenance from the compiled graph", async () => {- const { manifest } = await compileFromMemory({- model: "openai/gpt-5.4",- modules: [- {- loadNamespace: async () => ({ default: experimental_workflow({ maxSubagents: 5 }) }),- logicalPath: "tools/workflow.ts",- },- ],- });- const response = buildAgentInfoResponse(- { manifest, schedules: [] },- {- gatewayCredentials: { apiKey: false, oidc: false },- mode: "production",- },- );-- expect(response.workflow).toMatchObject({- enabled: true,- source: {- binding: { backing: { kind: "programmatic" } },- logicalPath: "tools/workflow.ts",- owner: { kind: "application" },- },- toolName: "Workflow",- });- });-it("reports an authored webSearch sentinel as a prepared provider effect", async () => {const { manifest } = await compileFromMemory({model: "openai/gpt-5.4",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.tsindex cb4ae7a18..71baf70d5 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@@ -16,7 +16,6 @@ import {} from "#internal/resolve-model-endpoint-status.js";import type { ChatGptAuthState } from "#public/models/openai/chatgpt/token-broker.js";import type { JsonObject, JsonValue } from "#shared/json.js";-import { WORKFLOW_TOOL_NAME } from "#shared/workflow-sandbox.js";export type AgentInfoResponse = AgentInfoResult;@@ -211,14 +210,6 @@ export function buildAgentInfoResponse(})),},version: 4,- workflow:- manifest.workflowTool === undefined- ? { enabled: false, toolName: WORKFLOW_TOOL_NAME }- : {- enabled: true,- source: toModuleSource(manifest, manifest.workflowTool),- toolName: WORKFLOW_TOOL_NAME,- },workspace: {resourceRoot: manifest.workspaceResourceRoot,rootEntries: [...manifest.workspaceResourceRoot.rootEntries],diff --git a/packages/eve/src/internal/testing/agent-info-fixture.ts b/packages/eve/src/internal/testing/agent-info-fixture.tsindex 2b14928f3..4d657514a 100644--- a/packages/eve/src/internal/testing/agent-info-fixture.ts+++ b/packages/eve/src/internal/testing/agent-info-fixture.ts@@ -72,7 +72,6 @@ export function createTestAgentInfoResult(subagents: { local: [], total: 0 },tools: { dynamic: [], static: [] },version: 4,- workflow: { enabled: false, toolName: "Workflow" },workspace: { resourceRoot: null, rootEntries: [] },};}diff --git a/packages/eve/src/public/definitions/exact.test.ts b/packages/eve/src/public/definitions/exact.test.tsindex bc0074d1c..1df13cf32 100644--- a/packages/eve/src/public/definitions/exact.test.ts+++ b/packages/eve/src/public/definitions/exact.test.ts@@ -31,7 +31,6 @@ import {type TaskReceipt,type ToolDefinition,} from "#public/tools/index.js";-import { experimental_workflow } from "#public/tools/workflow.js";describe("definition helper exact inputs", () => {it("preserves literal inference for valid definitions", () => {@@ -64,7 +63,6 @@ describe("definition helper exact inputs", () => {expect(agent.limits.maxOutputTokensPerSession).toBe(20_000);expect(agent.limits.maxTokenCostUsdPerSession).toBe(1.5);expect(agent.limits.sessionTimeoutMs).toBe(86_400_000);- expect(experimental_workflow({ maxSubagents: 6 }).maxSubagents).toBe(6);expect(schedule.cron).toBe("0 9 * * *");});@@ -240,17 +238,12 @@ function typeOnlyFixtures(): void {defineAgent({limits: {- // @ts-expect-error Workflow fan-out is configured by experimental_workflow.+ // @ts-expect-error Generated-program fan-out is configured by the workflow factory.maxSubagents: 6,},model: "anthropic/claude-sonnet-5",});- experimental_workflow({- // @ts-expect-error Workflow maxSubagents must be a number.- maxSubagents: "6",- });-const agentWithName = {model: "anthropic/claude-sonnet-5",name: "agent-name",diff --git a/packages/eve/src/public/tools/workflow.ts b/packages/eve/src/public/tools/workflow.tsindex dac481cfe..43c9e30b4 100644--- a/packages/eve/src/public/tools/workflow.ts+++ b/packages/eve/src/public/tools/workflow.ts@@ -1,10 +1,6 @@-/**- * Experimental Workflow tool authoring helpers.- */-export {- type ExperimentalWorkflowToolDefinition,- type ExperimentalWorkflowToolInput,- experimental_workflow,- isExperimentalWorkflowToolDefinition,-} from "#tools/workflow.js";+ workflow,+ type WorkflowTool,+ type WorkflowToolInput,+ type WorkflowToolOptions,+} from "#tools/provided/workflow.js";diff --git a/packages/eve/src/runtime/agent/mock-model-adapter.test.ts b/packages/eve/src/runtime/agent/mock-model-adapter.test.tsindex 543fe85dd..7485340bf 100644--- a/packages/eve/src/runtime/agent/mock-model-adapter.test.ts+++ b/packages/eve/src/runtime/agent/mock-model-adapter.test.ts@@ -73,40 +73,6 @@ describe("createMockAuthoredRuntimeModel", () => {]);});- it("delegates through Workflow when the directive requests blocking orchestration", async () => {- const result = await generateWithPrompt(- [- {- content: "Delegate through Workflow to a subagent: use the wait_for_cancel tool.",- role: "user",- },- ],- [- {- inputSchema: {- additionalProperties: false,- properties: { js: { type: "string" } },- required: ["js"],- type: "object",- },- name: "Workflow",- type: "function",- },- ],- );-- expect(result.content).toEqual([- {- input: JSON.stringify({- js: 'return await tools.agent({ message: "use the wait_for_cancel tool." });',- }),- toolCallId: "call_workflow",- toolName: "Workflow",- type: "tool-call",- },- ]);- });-it("reports a task notification instead of re-calling the named tool", async () => {const result = await generateWithPrompt([diff --git a/packages/eve/src/runtime/agent/mock-model-adapter.ts b/packages/eve/src/runtime/agent/mock-model-adapter.tsindex 4b895ee94..4d39d39fb 100644--- a/packages/eve/src/runtime/agent/mock-model-adapter.ts+++ b/packages/eve/src/runtime/agent/mock-model-adapter.ts@@ -207,8 +207,7 @@ function createSkillLoadResult(}const SUBAGENT_TOOL_NAME = "agent";-const SUBAGENT_DELEGATION_DIRECTIVE =- /\bdelegate\s+(?:(through\s+workflow)\s+)?to\s+a\s+subagent\s*:\s*(.+)$/iu;+const SUBAGENT_DELEGATION_DIRECTIVE = /\bdelegate\s+to\s+a\s+subagent\s*:\s*(.+)$/iu;const PARALLEL_AUTHORED_TOOLS_DIRECTIVE = /^call tools in parallel:\s*(.+)$/imu;function createParallelAuthoredToolCallsResult(@@ -274,25 +273,21 @@ function createSubagentDelegationResult(const directive = SUBAGENT_DELEGATION_DIRECTIVE.exec(lastUserMessage);- if (directive?.[2] === undefined) {+ if (directive?.[1] === undefined) {return null;}- const toolName = directive[1] === undefined ? SUBAGENT_TOOL_NAME : "Workflow";+ const toolName = SUBAGENT_TOOL_NAME;const tool = getAvailableTools(options).find((entry) => entry.name === toolName);if (tool === undefined) {return null;}- const message = directive[2].trim();- const toolInput =- toolName === "Workflow"- ? { js: `return await tools.agent({ message: ${JSON.stringify(message)} });` }- : { message };+ const message = directive[1].trim();return createToolCallGenerateResult({- input: toolInput,+ input: { message },inputTokens: estimateTokenCount(getPromptText(options.prompt)),modelId,outputTokens: estimateTokenCount(message),diff --git a/packages/eve/src/runtime/resolve-agent-graph.ts b/packages/eve/src/runtime/resolve-agent-graph.tsindex 2a42b2908..bcb1d0c1b 100644--- a/packages/eve/src/runtime/resolve-agent-graph.ts+++ b/packages/eve/src/runtime/resolve-agent-graph.ts@@ -20,7 +20,6 @@ import { createRuntimeSandboxRegistry } from "#runtime/sandbox/registry.js";import { LOAD_SKILL_TOOL_NAME } from "#runtime/skills/fragment-context.js";import { createRuntimeSubagentRegistry } from "#runtime/subagents/registry.js";import { createRuntimeToolRegistry } from "#runtime/tools/registry.js";-import { WORKFLOW_TOOL_NAME } from "#shared/workflow-sandbox.js";import { createWorkspacePromptSection } from "#runtime/workspace/spec.js";import type {ResolvedDynamicSubagentDefinition,@@ -135,13 +134,7 @@ async function resolveRuntimeAgentNode(moduleMap: input.moduleMap,nodeId: input.nodeId,});- const toolRegistry = await createRuntimeToolRegistry(- { tools: agent.tools },- {- nodeId,- reservedToolNames: [WORKFLOW_TOOL_NAME],- },- );+ const toolRegistry = await createRuntimeToolRegistry({ tools: agent.tools }, { nodeId });const sandboxRegistry = createRuntimeSandboxRegistry({sandbox: agent.sandbox,diff --git a/packages/eve/src/runtime/resolve-agent.ts b/packages/eve/src/runtime/resolve-agent.tsindex 5ab92b695..3b864007b 100644--- a/packages/eve/src/runtime/resolve-agent.ts+++ b/packages/eve/src/runtime/resolve-agent.ts@@ -118,10 +118,6 @@ export async function resolveAgent(input: ResolveAgentInput): Promise<ResolvedAgchannels: resolvedChannels,connections: resolvedConnections,dynamicConnectionResolvers: resolvedDynamicConnectionResolvers,- workflowTool:- input.manifest.workflowTool === undefined- ? undefined- : { maxSubagents: input.manifest.workflowTool.maxSubagents },dynamicInstructionsResolvers: resolvedDynamicInstructionsResolvers,dynamicSkillResolvers: resolvedDynamicSkillResolvers,dynamicToolResolvers: resolvedDynamicToolResolvers,diff --git a/packages/eve/src/runtime/resolve-tool.ts b/packages/eve/src/runtime/resolve-tool.tsindex 55122efdb..12c502059 100644--- a/packages/eve/src/runtime/resolve-tool.ts+++ b/packages/eve/src/runtime/resolve-tool.ts@@ -11,6 +11,7 @@ import { toErrorMessage } from "#shared/errors.js";import { loadResolvedModuleExport, ResolveAgentError } from "#runtime/resolve-helpers.js";import type { ResolvedToolDefinition } from "#runtime/types.js";import type { AgentSourceOwner } from "#compiler/source-graph.js";+import { createWorkflowProgramExecuteInput } from "#tools/workflow-program-input.js";/*** Resolves one compiled authored tool into a runtime-owned definition@@ -74,11 +75,17 @@ export async function resolveToolDefinition(const outputSchema = isToolSchema(resolvedRecord.outputSchema)? resolvedRecord.outputSchema: toOutputSchema(definition.outputSchema);+ const workflowProgram = definition.workflowProgram;+ const executeInput =+ workflowProgram === undefined+ ? undefined+ : (input: unknown) => createWorkflowProgramExecuteInput(workflowProgram, input);return {behavior: definition.behavior,description: definition.description,execute,+ executeInput,execution: definition.execution,exportName: definition.exportName,inputSchema,diff --git a/packages/eve/src/runtime/types.ts b/packages/eve/src/runtime/types.tsindex 51d6c71aa..6c3069130 100644--- a/packages/eve/src/runtime/types.ts+++ b/packages/eve/src/runtime/types.ts@@ -21,7 +21,7 @@ import type {import type { OpenAPISpecSource } from "#public/definitions/connections/openapi.js";import type { CompiledWorkspaceResourceRoot } from "#compiler/manifest.js";import type { WorkspaceRuntimeSpec } from "#runtime/workspace/types.js";-import type { JsonObject } from "#shared/json.js";+import type { JsonObject, JsonValue } from "#shared/json.js";import type { Optional } from "#shared/optional.js";import type { Node } from "#shared/node.js";import type {@@ -173,6 +173,8 @@ export type ResolvedToolDefinition = Readonly<* rehydrated before entering this runtime-owned definition.*/readonly inputSchema: ToolSchema | null;+ /** Framework-owned input projected before a workflow tool executor starts. */+ readonly executeInput?: (input: unknown) => JsonValue;/** Presentation projected from tool lifecycle values. */readonly label?: import("#tools/definition.js").InternalToolLabelDefinition;/**@@ -436,14 +438,6 @@ export interface ResolvedAgent {readonly config?: ResolvedAgentDefinition;readonly connections: readonly ResolvedConnectionDefinition[];readonly dynamicConnectionResolvers?: readonly ResolvedDynamicConnectionResolver[];- /**- * Configuration for the experimental framework `Workflow` orchestration- * tool. Present when an authored tool module exports- * `experimental_workflow(...)`.- */- readonly workflowTool?: {- readonly maxSubagents?: number;- };/** AI Gateway provider selected for the framework `web_search` tool. */readonly dynamicInstructionsResolvers: readonly ResolvedDynamicInstructionsResolver[];readonly dynamicSkillResolvers: readonly ResolvedDynamicSkillResolver[];diff --git a/packages/eve/src/shared/workflow-sandbox.ts b/packages/eve/src/shared/workflow-sandbox.tsindex 93a58c4b7..74e1761cd 100644--- a/packages/eve/src/shared/workflow-sandbox.ts+++ b/packages/eve/src/shared/workflow-sandbox.ts@@ -1,18 +1,15 @@-import type { ToolSet } from "ai";+import type { FlexibleSchema, ToolSet } from "ai";import type * as CodeModeModule from "#compiled/@ai-sdk/code-mode/index.js";-/** Model-facing tool name for eve's dynamic subagent orchestration tool. */-export const WORKFLOW_TOOL_NAME = "Workflow";-const WORKFLOW_SANDBOX_MODULE_KEY = Symbol.for("eve.workflowSandbox.module");const WORKFLOW_SANDBOX_MODULE_SPECIFIER = ["#compiled", "@ai-sdk", "code-mode", "index.js"].join("/",);type WorkflowSandboxModule = {+ readonly CodeModeToolError: typeof CodeModeModule.CodeModeToolError;readonly continueCodeModeInterrupt: typeof CodeModeModule.experimental_continueCodeModeInterrupt;readonly createCodeModeTool: typeof CodeModeModule.experimental_createCodeModeTool;- readonly getCodeModeInterrupt: typeof CodeModeModule.experimental_getCodeModeInterrupt;readonly requestCodeModeInterrupt: typeof CodeModeModule.experimental_requestCodeModeInterrupt;readonly unwrapCodeModeResult: typeof CodeModeModule.experimental_unwrapCodeModeResult;};@@ -43,24 +40,6 @@ export async function createWorkflowSandboxTool(input: {) as ToolSet[string];}-export async function requestWorkflowSandboxInterrupt(input: {- readonly kind: string;- readonly task: unknown;- readonly toolInput: unknown;- readonly toolName: string;-}): Promise<unknown> {- const { requestCodeModeInterrupt } = await loadWorkflowSandboxModule();- return requestCodeModeInterrupt(input);-}--export async function getWorkflowSandboxInterrupt(- result: unknown,- continuationSecurity: WorkflowSandboxContinuationSecurity,-): Promise<WorkflowSandboxInterrupt | undefined> {- const { getCodeModeInterrupt } = await loadWorkflowSandboxModule();- return getCodeModeInterrupt(result as never, continuationSecurity);-}-export async function continueWorkflowSandboxInterrupt(input: {readonly bridgeRequestLimit: number;readonly continuationSecurity: WorkflowSandboxContinuationSecurity;@@ -90,11 +69,41 @@ export async function unwrapWorkflowSandboxResult(| { readonly interrupt: WorkflowSandboxInterrupt; readonly status: "interrupted" };}-export function readWorkflowSandboxResolution(options: unknown): unknown {+export type WorkflowSandboxResolution =+ | { readonly status: "completed"; readonly output: unknown }+ | { readonly status: "failed"; readonly error: string };++/** A host tool that parks on first call and consumes its resolution on replay. */+export function createParkingHostTool(input: {+ readonly description: string;+ readonly inputSchema: FlexibleSchema;+ readonly outputSchema?: FlexibleSchema | null;+ readonly interrupt: (toolInput: unknown) => { readonly kind: string } & Record<string, unknown>;+}): ToolSet[string] {+ return {+ description: input.description,+ inputSchema: input.inputSchema,+ outputSchema: input.outputSchema ?? undefined,+ execute: async (toolInput: unknown, options: unknown) => {+ const module = await loadWorkflowSandboxModule();+ const resolution = readWorkflowProgramResolution(options);+ if (resolution?.status === "failed") throw new module.CodeModeToolError(resolution.error);+ if (resolution?.status === "completed") return resolution.output;+ return module.requestCodeModeInterrupt(input.interrupt(toolInput));+ },+ } as ToolSet[string];+}++function readWorkflowProgramResolution(options: unknown): WorkflowSandboxResolution | undefined {if (typeof options !== "object" || options === null) return undefined;const interrupt = (options as Record<string, unknown>).codeModeInterrupt;if (typeof interrupt !== "object" || interrupt === null) return undefined;- return (interrupt as Record<string, unknown>).resolution;+ const resolution = (interrupt as Record<string, unknown>).resolution;+ if (typeof resolution !== "object" || resolution === null) return undefined;+ const status = (resolution as Record<string, unknown>).status;+ return status === "completed" || status === "failed"+ ? (resolution as WorkflowSandboxResolution)+ : undefined;}/** Reconstructs every unresolved interruption from the authenticated continuation. */@@ -148,9 +157,9 @@ async function loadWorkflowSandboxModule(): Promise<WorkflowSandboxModule> {async function importWorkflowSandboxModule(specifier: string): Promise<WorkflowSandboxModule> {const module = (await import(specifier)) as typeof CodeModeModule;return {+ CodeModeToolError: module.CodeModeToolError,continueCodeModeInterrupt: module.experimental_continueCodeModeInterrupt,createCodeModeTool: module.experimental_createCodeModeTool,- getCodeModeInterrupt: module.experimental_getCodeModeInterrupt,requestCodeModeInterrupt: module.experimental_requestCodeModeInterrupt,unwrapCodeModeResult: module.experimental_unwrapCodeModeResult,};diff --git a/packages/eve/src/tools/provided/workflow.test.ts b/packages/eve/src/tools/provided/workflow.test.tsnew file mode 100644index 000000000..6c339f6c1--- /dev/null+++ b/packages/eve/src/tools/provided/workflow.test.ts@@ -0,0 +1,104 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++const mocks = vi.hoisted(() => ({ runJsProgram: vi.fn() }));+vi.mock("#execution/dynamic-workflow/workflow.js", async (importOriginal) => ({+ ...(await importOriginal()),+ runJsProgram: mocks.runJsProgram,+}));++import { executeWorkflowProgram } from "#execution/dynamic-workflow/tool.js";+import { normalizeToolDefinition } from "#internal/authored-definition/schema-backed.js";+import { workflow } from "#tools/provided/workflow.js";+import { readWorkflowProgramOptions } from "#tools/workflow-program-input.js";+import { isWorkflowToolDefinition } from "#tools/workflow-definition.js";+import { serializeInputSchema } from "#tools/schema.js";++describe("workflow", () => {+ beforeEach(() => vi.resetAllMocks());++ it("defines a branded tool with detailed function-body and agent result guidance", () => {+ const definition = workflow({ maxSubagents: 7 });++ expect(isWorkflowToolDefinition(definition)).toBe(true);+ expect(definition.description).toContain(+ "ctx.agent(name, { message: string, agentId?: string, outputSchema?: object })",+ );+ expect(definition.description).toContain(+ "resolves directly to the child's JSON-serializable output",+ );+ expect(definition.description).toContain("does not return an agent metadata wrapper");+ expect(definition.description).toContain("owning agent resolves the target");+ expect(definition.description).toContain(+ 'return await ctx.agent("researcher", { message: "Describe the task" })',+ );+ expect(definition.description).not.toContain("Available agents");+ expect(definition.description).toContain("at most 7 agents");+ expect(definition.execute).toBe(executeWorkflowProgram);++ const inputSchema = serializeInputSchema(definition.inputSchema);+ expect(inputSchema).toMatchObject({+ additionalProperties: false,+ properties: {+ js: {+ description: expect.stringContaining(+ "Supply only the body, without a surrounding function declaration or arrow function",+ ),+ type: "string",+ },+ },+ required: ["js"],+ type: "object",+ });+ expect(inputSchema).toMatchObject({+ properties: {+ js: {+ description: expect.stringContaining(+ "resolves directly to the child's JSON-serializable output",+ ),+ },+ },+ });+ expect(readWorkflowProgramOptions(definition)).toEqual({ maxSubagents: 7 });+ });++ it("preserves the trusted budget in the compiled definition", () => {+ const previousWorkflowId = Reflect.get(executeWorkflowProgram, "workflowId");+ Reflect.set(executeWorkflowProgram, "workflowId", "workflow//test//executeWorkflowProgram");+ try {+ const normalized = normalizeToolDefinition(+ workflow({ maxSubagents: 4 }),+ "Invalid workflow.",+ );+ expect(normalized).toMatchObject({+ kind: "tool",+ definition: {+ workflowProgram: { maxSubagents: 4 },+ },+ });+ } finally {+ if (previousWorkflowId === undefined) {+ Reflect.deleteProperty(executeWorkflowProgram, "workflowId");+ } else {+ Reflect.set(executeWorkflowProgram, "workflowId", previousWorkflowId);+ }+ }+ });++ it("defaults and validates the trusted call budget", () => {+ expect(readWorkflowProgramOptions(workflow())).toEqual({ maxSubagents: 100 });+ expect(() => workflow({ maxSubagents: 0 })).toThrow("between 1 and 128");+ expect(() => workflow({ maxSubagents: 129 })).toThrow("between 1 and 128");+ });++ it("routes pinned executor input to the private JavaScript adapter", async () => {+ mocks.runJsProgram.mockResolvedValue({ ok: true });+ const ctx = { callId: "call" } as never;++ await expect(executeWorkflowProgram({ js: "return 1", maxSubagents: 3 }, ctx)).resolves.toEqual(+ { ok: true },+ );+ expect(mocks.runJsProgram).toHaveBeenCalledWith("return 1", ctx, {+ maxSubagents: 3,+ });+ });+});diff --git a/packages/eve/src/tools/provided/workflow.ts b/packages/eve/src/tools/provided/workflow.tsnew file mode 100644index 000000000..2d42497fa--- /dev/null+++ b/packages/eve/src/tools/provided/workflow.ts@@ -0,0 +1,65 @@+import { z } from "#compiled/zod/index.js";++import {+ DEFAULT_WORKFLOW_PROGRAM_MAX_SUBAGENTS,+ parseWorkflowProgramOptions,+} from "#execution/dynamic-workflow/schema.js";+import { executeWorkflowProgram } from "#execution/dynamic-workflow/tool.js";+import type { JsonValue } from "#shared/json.js";+import {+ defineWorkflowTool,+ type BlockingWorkflowToolDefinition,+} from "#tools/workflow-definition.js";+import { attachWorkflowProgramOptions } from "#tools/workflow-program-input.js";++export interface WorkflowToolOptions {+ /** Maximum child-agent calls per program, from 1 to 128. Defaults to 100. */+ readonly maxSubagents?: number;+}++export interface WorkflowToolInput {+ readonly js: string;+}++export type WorkflowTool = BlockingWorkflowToolDefinition<WorkflowToolInput, JsonValue>;++const workflowProgramAgentContract =+ "Call ctx.agent(name, { message: string, agentId?: string, outputSchema?: object }). It resolves directly to the child's JSON-serializable output; when outputSchema is provided, the output matches that schema. It does not return an agent metadata wrapper. Use an agentId from the conversation's <agents> block to continue that child. The owning agent resolves the target and applies its existing availability and authorization checks.";++const workflowInputSchema = z.strictObject({+ js: z+ .string()+ .describe(+ `JavaScript statements executed inside an async function. Supply only the body, without a surrounding function declaration or arrow function. ${workflowProgramAgentContract} Return one JSON-serializable value.`,+ ),+});++/** Defines a model-facing workflow tool backed by isolated runtime JavaScript. */+export function workflow(options: WorkflowToolOptions = {}): WorkflowTool {+ const normalized = normalizeWorkflowToolOptions(options);+ const description = [+ "Run an async JavaScript function body that invokes agents and returns one JSON-serializable value.",+ workflowProgramAgentContract,+ 'Supply the body directly, for example: return await ctx.agent("researcher", { message: "Describe the task" });',+ `The program may invoke at most ${String(normalized.maxSubagents)} agents.`,+ ].join(" ");+ return attachWorkflowProgramOptions(+ defineWorkflowTool({+ description,+ execute: executeWorkflowProgram,+ inputSchema: workflowInputSchema,+ }),+ normalized,+ );+}++function normalizeWorkflowToolOptions(options: WorkflowToolOptions): {+ readonly maxSubagents: number;+} {+ if (typeof options !== "object" || options === null) {+ throw new TypeError("workflow options must be an object.");+ }+ return parseWorkflowProgramOptions({+ maxSubagents: options.maxSubagents ?? DEFAULT_WORKFLOW_PROGRAM_MAX_SUBAGENTS,+ });+}diff --git a/packages/eve/src/tools/workflow-program-input.ts b/packages/eve/src/tools/workflow-program-input.tsnew file mode 100644index 000000000..ae578da31--- /dev/null+++ b/packages/eve/src/tools/workflow-program-input.ts@@ -0,0 +1,40 @@+import type { WorkflowProgramOptions } from "#execution/dynamic-workflow/schema.js";+import type { JsonObject } from "#shared/json.js";++export type { WorkflowProgramOptions } from "#execution/dynamic-workflow/schema.js";++const WORKFLOW_PROGRAM_OPTIONS = Symbol.for("eve.workflow-program-options");++type WorkflowProgramOptionsCarrier = {+ readonly [WORKFLOW_PROGRAM_OPTIONS]?: WorkflowProgramOptions;+};++export function attachWorkflowProgramOptions<TDefinition extends object>(+ definition: TDefinition,+ options: WorkflowProgramOptions,+): TDefinition {+ Object.defineProperty(definition, WORKFLOW_PROGRAM_OPTIONS, {+ configurable: false,+ enumerable: false,+ value: options,+ writable: false,+ });+ return definition;+}++export function readWorkflowProgramOptions(value: unknown): WorkflowProgramOptions | undefined {+ if (typeof value !== "object" || value === null) return undefined;+ return (value as WorkflowProgramOptionsCarrier)[WORKFLOW_PROGRAM_OPTIONS];+}++export function createWorkflowProgramExecuteInput(+ options: WorkflowProgramOptions,+ input: unknown,+): JsonObject {+ const js = (input as { readonly js?: unknown } | null)?.js;+ if (typeof js !== "string") throw new TypeError('workflow requires a "js" string.');+ return {+ js,+ maxSubagents: options.maxSubagents,+ };+}diff --git a/packages/eve/src/tools/workflow.ts b/packages/eve/src/tools/workflow.tsdeleted file mode 100644index 166a89ac5..000000000--- a/packages/eve/src/tools/workflow.ts+++ /dev/null@@ -1,61 +0,0 @@-const EXPERIMENTAL_WORKFLOW_TOOL_KIND = "eve:enable-workflow-tool";--/** Configuration accepted by {@link experimental_workflow}. */-export interface ExperimentalWorkflowToolInput {- /**- * Maximum number of subagent or remote-agent calls one `Workflow` program- * may dispatch, counted across sequential and parallel calls alike.- *- * Calls beyond the limit fail with a `WORKFLOW_SUBAGENT_LIMIT_REACHED`- * result instead of starting a child session.- *- * @default 100- */- readonly maxSubagents?: number;-}--/** Framework `Workflow` tool definition returned by {@link experimental_workflow}. */-export interface ExperimentalWorkflowToolDefinition extends ExperimentalWorkflowToolInput {- readonly kind: typeof EXPERIMENTAL_WORKFLOW_TOOL_KIND;-}--/**- * Enables and configures the experimental framework `Workflow` tool, an- * isolated JavaScript sandbox whose only callable operations are this agent's- * subagents and remote agents. Export the result from- * `agent/tools/workflow.ts`:- *- * ```ts- * import { experimental_workflow } from "eve/tools";- *- * export default experimental_workflow({ maxSubagents: 25 });- * ```- *- * Only the root session sees the tool. The resulting model-facing tool is- * still called `Workflow`.- */-export function experimental_workflow(- input: ExperimentalWorkflowToolInput = {},-): ExperimentalWorkflowToolDefinition {- const definition: {- kind: typeof EXPERIMENTAL_WORKFLOW_TOOL_KIND;- maxSubagents?: number;- } = {- kind: EXPERIMENTAL_WORKFLOW_TOOL_KIND,- };- if (input.maxSubagents !== undefined) {- definition.maxSubagents = input.maxSubagents;- }- return definition;-}--/** Type guard for a definition returned by {@link experimental_workflow}. */-export function isExperimentalWorkflowToolDefinition(- value: unknown,-): value is ExperimentalWorkflowToolDefinition {- return (- typeof value === "object" &&- value !== null &&- (value as { kind?: unknown }).kind === EXPERIMENTAL_WORKFLOW_TOOL_KIND- );-}diff --git a/packages/eve/test/scenarios/app-runtime-dependencies.scenario.test.ts b/packages/eve/test/scenarios/app-runtime-dependencies.scenario.test.tsindex 63c2a60ef..4a619ef6a 100644--- a/packages/eve/test/scenarios/app-runtime-dependencies.scenario.test.ts+++ b/packages/eve/test/scenarios/app-runtime-dependencies.scenario.test.ts@@ -294,13 +294,15 @@ describe("app runtime dependency tracing", () => {await import(pathToFileURL(bundledDependencyModule.modulePath).href);}, 30_000);- it("bundles Workflow sandbox worker assets only when an agent enables Workflow", async () => {- async function createWorkflowAssetsApp(label: string, workflow: boolean): Promise<string> {+ it("bundles the generated JavaScript sandbox only for the workflow factory", async () => {+ async function createWorkflowAssetsApp(+ label: string,+ tool: "sleep" | "workflow",+ ): Promise<string> {const appRoot = await createScratchDirectory(`eve-app-workflow-assets-${label}-build-`);- await mkdir(join(appRoot, "agent", "subagents", "researcher"), {- recursive: true,- });+ await mkdir(join(appRoot, "agent", "subagents", "researcher"), { recursive: true });+ await mkdir(join(appRoot, "agent", "tools"), { recursive: true });await writeFile(join(appRoot, "package.json"),@@ -327,47 +329,51 @@ describe("app runtime dependency tracing", () => {join(appRoot, "agent", "subagents", "researcher", "instructions.md"),"Research the request.\n",);- if (workflow) {- await mkdir(join(appRoot, "agent", "tools"), { recursive: true });- await writeFile(- join(appRoot, "agent", "tools", "workflow.ts"),- 'export default { kind: "eve:enable-workflow-tool", maxSubagents: 6 };\n',- );- }+ await writeFile(+ join(appRoot, "agent", "tools", `${tool}.ts`),+ tool === "workflow"+ ? [+ 'import { workflow } from "eve/tools/workflow";',+ "",+ 'export default workflow({ agents: ["researcher"], maxSubagents: 6 });',+ "",+ ].join("\n")+ : 'import { sleep } from "eve/tools/sleep";\n\nexport default sleep();\n',+ );return appRoot;}- const disabledOutputDir = await buildApplication(- await createWorkflowAssetsApp("disabled", false),+ const sleepOutputDir = await buildApplication(+ await createWorkflowAssetsApp("sleep", "sleep"),DEPLOYABLE_BUILD_OPTIONS,);- const disabledTracedPackageJson = await readTracedServerPackageJson(disabledOutputDir);- const disabledServerSource = await readJavaScriptModulesRecursively(- join(disabledOutputDir, "server"),+ const sleepTracedPackageJson = await readTracedServerPackageJson(sleepOutputDir);+ const sleepServerSource = await readJavaScriptModulesRecursively(+ join(sleepOutputDir, "server"),);- expect(disabledServerSource).not.toContain("[Unprintable QuickJS value]");+ expect(sleepServerSource).not.toContain("[Unprintable QuickJS value]");- const enabledOutputDir = await buildApplication(- await createWorkflowAssetsApp("enabled", true),+ const workflowOutputDir = await buildApplication(+ await createWorkflowAssetsApp("workflow", "workflow"),DEPLOYABLE_BUILD_OPTIONS,);- const tracedServerPackageJson = await readTracedServerPackageJson(enabledOutputDir);- const enabledServerSource = await readJavaScriptModulesRecursively(- join(enabledOutputDir, "server"),+ const workflowTracedPackageJson = await readTracedServerPackageJson(workflowOutputDir);+ const workflowServerSource = await readJavaScriptModulesRecursively(+ join(workflowOutputDir, "server"),);- expect(enabledServerSource).toContain("[Unprintable QuickJS value]");- // The Workflow sandbox runtime ships bundled inline, never traced — and+ expect(workflowServerSource).toContain("[Unprintable QuickJS value]");+ // The generated JavaScript sandbox runtime ships bundled inline, never traced — and// these apps do not declare the optional just-bash engine, so its// quickjs dependency must not sneak into the trace either.- expect(disabledTracedPackageJson.dependencies).not.toHaveProperty("@ai-sdk/code-mode");- expect(tracedServerPackageJson.dependencies).not.toHaveProperty("@ai-sdk/code-mode");- expect(disabledTracedPackageJson.dependencies).not.toHaveProperty("run");- expect(tracedServerPackageJson.dependencies).not.toHaveProperty("run");- expect(disabledTracedPackageJson.dependencies).not.toHaveProperty("quickjs-emscripten");- expect(tracedServerPackageJson.dependencies).not.toHaveProperty("quickjs-emscripten");+ expect(sleepTracedPackageJson.dependencies).not.toHaveProperty("@ai-sdk/code-mode");+ expect(workflowTracedPackageJson.dependencies).not.toHaveProperty("@ai-sdk/code-mode");+ expect(sleepTracedPackageJson.dependencies).not.toHaveProperty("run");+ expect(workflowTracedPackageJson.dependencies).not.toHaveProperty("run");+ expect(sleepTracedPackageJson.dependencies).not.toHaveProperty("quickjs-emscripten");+ expect(workflowTracedPackageJson.dependencies).not.toHaveProperty("quickjs-emscripten");}, 60_000);it("includes the optional just-bash engine in hosted output only when the sandbox config selects it", async () => {diff --git a/packages/eve/test/scenarios/turn-cancellation.scenario.test.ts b/packages/eve/test/scenarios/turn-cancellation.scenario.test.tsindex 09e1c4754..50daa2ccf 100644--- a/packages/eve/test/scenarios/turn-cancellation.scenario.test.ts+++ b/packages/eve/test/scenarios/turn-cancellation.scenario.test.ts@@ -64,7 +64,10 @@ export default defineTool({name: "remote-cancellation-child",};-function createParentDescriptor(remoteUrl: string): ScenarioAppDescriptor {+function createParentDescriptor(+ remoteUrl: string,+ options: { readonly sessionInputLimit?: number } = {},+): ScenarioAppDescriptor {return {dependencies: { zod: "^4.3.6" },files: {@@ -73,13 +76,16 @@ import { mockModel } from "eve/evals";const model = mockModel((request) => {const message = request.lastUserMessage ?? "";- if (message.includes("Use Workflow exactly once")) {+ if (message.includes("Use workflow exactly once")) {+ const localOnly = message.includes("local-sleeper only");return {toolCalls: [{- name: "Workflow",+ name: "workflow",input: {- js: 'return await Promise.all([tools["local-sleeper"]({ message: "Use wait-for-cancel." }), tools["remote-sleeper"]({ message: "Use wait-for-cancel." })]);',+ js: localOnly+ ? 'return await ctx.agent("local-sleeper", { message: "Use wait-for-cancel." });'+ : 'return await Promise.all([ctx.agent("local-sleeper", { message: "Use wait-for-cancel." }), ctx.agent("remote-sleeper", { message: "Use wait-for-cancel." })]);',},},],@@ -88,12 +94,16 @@ const model = mockModel((request) => {return "still-alive";});-export default defineAgent({ model, modelContextWindowTokens: 32_000 });+export default defineAgent({+ ${options.sessionInputLimit === undefined ? "" : `limits: { maxInputTokensPerSession: ${String(options.sessionInputLimit)} },`}+ model,+ modelContextWindowTokens: 32_000,+});`,"agent/instructions.md": "Delegate cancellation waits as requested.\n",- "agent/tools/workflow.ts": `import { experimental_workflow } from "eve/tools/workflow";+ "agent/tools/workflow.ts": `import { workflow } from "eve/tools/workflow";-export default experimental_workflow();+export default workflow();`,"agent/subagents/local-sleeper/agent.ts": `import { defineAgent } from "eve";import { mockModel } from "eve/evals";@@ -159,7 +169,7 @@ describe("turn cancellation descendant cascade", () => {const parentClient = new Client({ host: parentServer.url });const { session: parentSession, response } = await parentClient.sessions.create({message: [- "Use Workflow exactly once to call local-sleeper and remote-sleeper in parallel.",+ "Use workflow exactly once to call local-sleeper and remote-sleeper in parallel.",'Pass both the message "Use wait-for-cancel." and return Promise.all of their results.',].join("\n"),});@@ -259,6 +269,55 @@ describe("turn cancellation descendant cascade", () => {},SCENARIO_TIMEOUT_MS,);++ it(+ "declines the root continuation after a generated child inherits zero input quota",+ async () => {+ const parentApp = await scenarioApp(+ createParentDescriptor("http://127.0.0.1:1", { sessionInputLimit: 1 }),+ );+ const parentServer = await startEveDev(parentApp.appRoot, {+ env: { EVE_MOCK_AUTHORED_MODELS: "", NODE_ENV: "production" },+ });++ try {+ const parentClient = new Client({ host: parentServer.url });+ const { session, response } = await parentClient.sessions.create({+ message:+ "Use workflow exactly once to call local-sleeper only with message Use wait-for-cancel.",+ });+ const events = await readThroughBoundary({+ iterator: response[Symbol.asyncIterator](),+ label: "root session-limit prompt",+ });+ const calls = events.filter((event) => event.type === "subagent.called");+ const requests = events.flatMap((event) =>+ event.type === "input.requested" ? event.data.requests : [],+ );+ expect(calls).toHaveLength(1);+ expect(requests).toHaveLength(1);+ expect(requests[0]?.requestId.startsWith(`${response.sessionId}:limit:`)).toBe(true);++ const requestId = requests[0]?.requestId;+ if (requestId === undefined) throw new Error("Root limit prompt has no request id.");+ const declined = await (await session.respond([{ optionId: "stop", requestId }])).result();+ expect(declined.status).toBe("waiting");+ expectCancellationBoundary(declined.events);+ expect(declined.events.some((event) => event.type === "subagent.called")).toBe(false);+ } catch (error) {+ throw new Error(+ [+ `parent stdout:\n${parentServer.stdout()}`,+ `parent stderr:\n${parentServer.stderr()}`,+ ].join("\n\n"),+ { cause: error },+ );+ } finally {+ await parentServer.stop();+ }+ },+ SCENARIO_TIMEOUT_MS,+ );});type SubagentCalledEvent = Extract<MessageStreamEvent, { type: "subagent.called" }>;diff --git a/research/programmatic-agent-sources.md b/research/programmatic-agent-sources.mdindex 5d1a13ed3..6258196c6 100644--- a/research/programmatic-agent-sources.md+++ b/research/programmatic-agent-sources.md@@ -598,10 +598,8 @@ through source composition:Every identity above is replaceable and disableable through ordinary slotcomposition. `glob` and `grep` are published at `eve/tools/glob` and-`eve/tools/grep` but never registered. Workflow shares the slot pattern-without a framework default: an authored `experimental_workflow()` sentinel-at `tools/workflow.ts` opts in at that canonical identity. Authored-`instrumentation.ts` likewise composes as an ordinary module slot with no+`eve/tools/grep` but never registered. Runtime-generated programs use an ordinary path-derived tool created with the provided+`workflow()` factory and existing `ctx.agent` target resolution; there is no framework workflow slot or sentinel. Authored `instrumentation.ts` likewise composes as an ordinary module slot with noframework default and no dedicated plan artifact. Native behavior outsidethese identities is limited to `final_output` and the closed host inventory.diff --git a/scripts/extension-contracts/configuration.mjs b/scripts/extension-contracts/configuration.mjsindex d9acda5e2..03aa7f45d 100644--- a/scripts/extension-contracts/configuration.mjs+++ b/scripts/extension-contracts/configuration.mjs@@ -24,8 +24,8 @@ export const PUBLIC_SURFACES = [{paths: ["src/public/tools/index.ts",- "src/public/tools/workflow.ts","src/public/tools/web-search.ts",+ "src/public/tools/workflow.ts",],capabilities: ["tool", "dynamicTool"],},