Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat(eve): reintroduce ExperimentalWorkflow with a maxSubagents cap (#528)

Rui5ef4ec639c27
diff --git a/.changeset/reintroduce-experimental-workflow.md b/.changeset/reintroduce-experimental-workflow.md
new file mode 100644
index 000000000..d6a89fb3b
--- /dev/null
+++ b/.changeset/reintroduce-experimental-workflow.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Reintroduce the `ExperimentalWorkflow` opt-in marker in `eve/tools`. Re-exporting it from `agent/tools/workflow.ts` enables the `Workflow` orchestration tool, which can spawn the agent's subagents from model-authored JavaScript. Workflow-spawned subagent calls are now capped per program by the new `limits.maxSubagents` agent setting (default 100) — calls beyond the budget resolve with a `WORKFLOW_SUBAGENT_LIMIT_REACHED` error result instead of starting a child session — and the tool stays root-only, so delegated subagent sessions never receive it.
diff --git a/docs/concepts/default-harness.md b/docs/concepts/default-harness.md
index 6b11ce4c9..598533ffa 100644
--- a/docs/concepts/default-harness.md
+++ b/docs/concepts/default-harness.md
@@ -87,6 +87,16 @@ Three moves shape the harness. The right one depends on whether the model should
- **Disable** when the model should not have the capability at all. A `disableTool()` sentinel removes the built-in, and the model never sees it. Reach for this to lock down `bash` or `web_fetch` in an agent that should not run shell commands or fetch arbitrary URLs.
- **Author a new tool** when you want a capability the harness does not ship. Give it a fresh slug under `agent/tools/` and it joins the built-ins instead of replacing one. See [Tools](../tools) for the authoring model.
+## The opt-in `Workflow` tool
+
+An experimental `Workflow` tool ships but stays off by default. To turn it on, re-export the opt-in marker from `agent/tools/workflow.ts`:
+
+```ts
+export { ExperimentalWorkflow as default } from "eve/tools";
+```
+
+With it on, the model can orchestrate the agent's own subagents from model-authored JavaScript, all as one durable step. The tool is root-only — delegated subagent sessions never see it — and one program may dispatch at most `limits.maxSubagents` subagent calls (default 100). See [Dynamic workflows](../guides/dynamic-workflows).
+
## What to read next
- [Tools](../tools): define your own tools, gate them on approval, and shape their output with `toModelOutput`
diff --git a/docs/guides/dynamic-workflows.md b/docs/guides/dynamic-workflows.md
new file mode 100644
index 000000000..d4e5e4582
--- /dev/null
+++ b/docs/guides/dynamic-workflows.md
@@ -0,0 +1,87 @@
+---
+title: "Dynamic Workflows"
+description: "The experimental Workflow tool: let the model orchestrate its own subagents from model-authored JavaScript as one durable step."
+---
+
+The experimental `Workflow` tool lets the model write JavaScript that coordinates the agent's own subagents as a single durable step. The program can run them in sequence, feed one result into the next, fan out over a list, and combine the results. You enable the capability and the model decides and runs the orchestration.
+
+A single turn can already call several subagents, and parallel tool calls dispatch concurrently. What a workflow adds is _programmatic_ coordination. The program decides how many subagents to run based on an earlier result, which output feeds which call, and how to combine everything. That is logic the model cannot express as a few one-off calls.
+
+## Enable the Workflow tool
+
+Re-export the opt-in marker as the default export of `agent/tools/workflow.ts`. The marker name carries the "experimental" warning, but the tool the model actually sees is named `Workflow`.
+
+```ts title="agent/tools/workflow.ts"
+export { ExperimentalWorkflow as default } from "eve/tools";
+```
+
+Without that file, the `Workflow` tool stays off. It earns its keep only when the agent has subagents (or the built-in `agent`) worth coordinating:
+
+```ts title="agent/subagents/analyst/agent.ts"
+import { defineAgent } from "eve";
+
+export default defineAgent({
+ description: "Analyzes one metric: queries, computes, writes a short finding.",
+ model: "anthropic/claude-opus-4.8",
+});
+```
+
+When asked for a weekly business review, the model picks the metrics, runs one `analyst` per metric in parallel, and combines the findings. The program below is the kind of JavaScript the model authors. It fans `analyst` out over a runtime-decided list of metrics and merges the results:
+
+```js
+const metrics = ["revenue", "signups", "churn"];
+const findings = await Promise.all(
+ metrics.map((metric) => tools.analyst({ message: `Summarize last week's ${metric}.` })),
+);
+return findings.join("\n\n");
+```
+
+Each `tools.analyst(...)` call dispatches a child subagent, so the parent stream records one `subagent.called` per metric and one `subagent.completed` as each finishes:
+
+```json
+{ "type": "subagent.called", "data": { "name": "analyst", "toolName": "analyst", "callId": "call_1", "childSessionId": "ses_a1", "sequence": 0 } }
+{ "type": "subagent.called", "data": { "name": "analyst", "toolName": "analyst", "callId": "call_2", "childSessionId": "ses_a2", "sequence": 1 } }
+{ "type": "subagent.called", "data": { "name": "analyst", "toolName": "analyst", "callId": "call_3", "childSessionId": "ses_a3", "sequence": 2 } }
+{ "type": "subagent.completed", "data": { "subagentName": "analyst", "callId": "call_1", "output": "..." } }
+{ "type": "subagent.completed", "data": { "subagentName": "analyst", "callId": "call_2", "output": "..." } }
+{ "type": "subagent.completed", "data": { "subagentName": "analyst", "callId": "call_3", "output": "..." } }
+```
+
+## What a workflow can orchestrate
+
+A workflow reaches only this agent's own agents: the built-in `agent` (a copy of itself), declared [subagents](../subagents), and [remote agents](./remote-agents). That is the whole list. No files, network, shell, skills, or connections. A workflow is a coordination layer over subagents, not a place to do other work. Each call can still request structured output via `outputSchema`, exactly like a direct subagent delegation.
+
+## Caps on workflow-spawned subagents
+
+Workflow orchestration is capped in two independent ways.
+
+**Per-program call budget.** One Workflow program may dispatch at most `limits.maxSubagents` subagent calls in total, counted across the whole program — sequential and parallel calls alike. The default is 100. Calls beyond the budget do not start a child session; they resolve inside the program with a `WORKFLOW_SUBAGENT_LIMIT_REACHED` error result, and the budget is stated in the tool's description so the model sizes its fan-out to fit.
+
+```ts title="agent/agent.ts"
+export default defineAgent({
+ model: "anthropic/claude-sonnet-5",
+ limits: {
+ maxSubagents: 4,
+ },
+});
+```
+
+**Root-only, one level of orchestration.** Only the root session ever sees the `Workflow` tool. The subagents a workflow spawns are ordinary delegated child sessions: they never receive the `Workflow` tool themselves, so a workflow cannot recursively spawn more workflows. Direct (non-workflow) delegation by those children stays subject to the usual `limits.maxSubagentDepth` cap (see [Subagents](../subagents)).
+
+## Where the JavaScript runs
+
+The orchestration code never touches the agent's process. The runtime hands the program text to a small isolated JavaScript engine (a QuickJS sandbox) and runs it there. Nothing from the host realm crosses in, so there is no `process`, no `globalThis` from the agent, and no `import`/`require`. The program can reach exactly two things, the agent functions bridged in as `tools.<name>` and the ordinary language built-ins.
+
+That is an allowlist, not a denylist. The sandbox cannot read files, open a socket, or see an environment variable because those are not present, not because each one is blocked in turn. When the program calls an agent function, that call bridges back out to the runtime, which dispatches it exactly like a direct delegation. The orchestration glue stays inside the sandbox.
+
+## Durability, approvals, and observability
+
+- **Durable.** The whole orchestration counts as one step. Subagents dispatched together run concurrently, and if a run parks (suspends durably without holding compute; see [Execution model & durability](../concepts/execution-model-and-durability)) on a long-running or human-gated child, it resumes where it left off after a restart.
+- **Approval-safe.** A subagent that needs human approval (HITL, human-in-the-loop) mid-run surfaces its request to the user, and the workflow picks back up once that is answered, same as direct delegation.
+- **Observable.** Every orchestrated subagent emits the usual `subagent.called` / `subagent.completed` events on the parent stream and gets its own child session and stream. The telemetry matches direct delegation, so existing dashboards and cost attribution keep working.
+
+## What to read next
+
+- Declare the subagents a workflow orchestrates → [Subagents](../subagents)
+- Call another deployment as one of those agents → [Remote agents](./remote-agents)
+- The `agent/tools/` opt-in mechanism → [Default harness](../concepts/default-harness)
diff --git a/docs/guides/meta.json b/docs/guides/meta.json
index be12e6fd8..f30738049 100644
--- a/docs/guides/meta.json
+++ b/docs/guides/meta.json
@@ -8,6 +8,7 @@
"session-context",
"state",
"dynamic-capabilities",
+ "dynamic-workflows",
"remote-agents",
"dev-tui",
"frontend",
diff --git a/docs/guides/remote-agents.md b/docs/guides/remote-agents.md
index 3dc70d288..bc68da496 100644
--- a/docs/guides/remote-agents.md
+++ b/docs/guides/remote-agents.md
@@ -60,4 +60,5 @@ Both failure paths surface to the parent as a failed tool result, so the caller
## What to read next
- Local delegation and the isolation boundary → [Subagents](../subagents)
+- Have the model orchestrate remote agents programmatically → [Dynamic workflows](./dynamic-workflows)
- Securing the receiving deployment → [Auth & route protection](./auth-and-route-protection)
diff --git a/docs/reference/typescript-api.md b/docs/reference/typescript-api.md
index ebaabd3f1..26db699ed 100644
--- a/docs/reference/typescript-api.md
+++ b/docs/reference/typescript-api.md
@@ -52,7 +52,7 @@ export default defineTool({
| `mockModel` | `eve/evals` | Deterministic fixture agent models | [Evals](../evals/overview) |
| `useEveAgent` | `eve/react`, `eve/vue`, `eve/svelte` | frontend | [Frontend](../guides/frontend/overview) |
-A few non-`define*` helpers round out the set: `disableTool` from `eve/tools` (see [Default harness](../concepts/default-harness)), the route verbs `GET`/`POST`/`PUT`/`PATCH`/`DELETE`/`WS` from `eve/channels`, the approval policies `always`/`once`/`never` from `eve/tools/approval`, and the channel auth helpers `localDev`/`vercelOidc`/`placeholderAuth` from `eve/channels/auth`. To wrap a built-in tool, import its default value from `eve/tools/defaults` (`bash`, `readFile`, `writeFile`, `glob`, `grep`, `webFetch`, `webSearch`, `todo`, `loadSkill`). `AgentReasoningDefinition` is exported from `eve` for the top-level `defineAgent({ reasoning })` setting. `AgentLimitsDefinition` is exported for `defineAgent({ limits })`. `AgentWorkflowDefinition` and `AgentWorkflowWorldDefinition` are exported from `eve` for the `defineAgent({ experimental: { workflow } })` config shape.
+A few non-`define*` helpers round out the set: `disableTool` and `ExperimentalWorkflow` from `eve/tools` (see [Default harness](../concepts/default-harness)), the route verbs `GET`/`POST`/`PUT`/`PATCH`/`DELETE`/`WS` from `eve/channels`, the approval policies `always`/`once`/`never` from `eve/tools/approval`, and the channel auth helpers `localDev`/`vercelOidc`/`placeholderAuth` from `eve/channels/auth`. To wrap a built-in tool, import its default value from `eve/tools/defaults` (`bash`, `readFile`, `writeFile`, `glob`, `grep`, `webFetch`, `webSearch`, `todo`, `loadSkill`). `AgentReasoningDefinition` is exported from `eve` for the top-level `defineAgent({ reasoning })` setting. `AgentLimitsDefinition` is exported for `defineAgent({ limits })`. `AgentWorkflowDefinition` and `AgentWorkflowWorldDefinition` are exported from `eve` for the `defineAgent({ experimental: { workflow } })` config shape.
## Runtime context (`ctx`)
@@ -68,31 +68,31 @@ A few non-`define*` helpers round out the set: `disableTool` from `eve/tools` (s
## Imports at a glance
-| Import | Holds |
-| ----------------------------------------------------------- | --------------------------------------------------------- |
-| `eve` | `defineAgent`, `defineRemoteAgent`, agent config types |
-| `eve/tools` | `defineTool`, `defineDynamic`, `disableTool` |
-| `eve/tools/defaults` | the built-in tools as plain values |
-| `eve/tools/approval` | `always`, `once`, `never` |
-| `eve/connections` | `defineMcpClientConnection`, `defineOpenAPIConnection` |
-| `eve/channels` | `defineChannel`, route verbs |
-| `eve/channels/eve` | `eveChannel` |
-| `eve/channels/auth` | `localDev`, `vercelOidc`, `placeholderAuth` |
-| `eve/channels/{slack,discord,teams,telegram,twilio,github}` | platform channel factories |
-| `eve/hooks` | `defineHook` |
-| `eve/schedules` | `defineSchedule` |
-| `eve/skills` | `defineSkill`, `defineDynamic` |
-| `eve/instructions` | `defineInstructions`, `defineDynamic` |
-| `eve/context` | `defineState`, session and state types |
-| `eve/sandbox` | `defineSandbox`, backends |
-| `eve/instrumentation` | `defineInstrumentation`, `isChannel` |
-| `eve/evals` | `defineEval`, `defineEvalConfig`, `mockModel`, eval types |
-| `eve/evals/expect` | `includes`, `equals`, `matches`, `similarity` |
-| `eve/evals/reporters` | `Braintrust`, `JUnit`, `EvalReporter` |
-| `eve/evals/loaders` | `loadJson`, `loadYaml` |
-| `eve/react`, `eve/vue`, `eve/svelte` | `useEveAgent` |
-| `eve/next`, `eve/nuxt`, `eve/sveltekit` | framework bundler plugins |
-| [`eve/client`](../guides/client/overview) | `Client`, `ClientSession` |
+| Import | Holds |
+| ----------------------------------------------------------- | -------------------------------------------------------------------- |
+| `eve` | `defineAgent`, `defineRemoteAgent`, agent config types |
+| `eve/tools` | `defineTool`, `defineDynamic`, `disableTool`, `ExperimentalWorkflow` |
+| `eve/tools/defaults` | the built-in tools as plain values |
+| `eve/tools/approval` | `always`, `once`, `never` |
+| `eve/connections` | `defineMcpClientConnection`, `defineOpenAPIConnection` |
+| `eve/channels` | `defineChannel`, route verbs |
+| `eve/channels/eve` | `eveChannel` |
+| `eve/channels/auth` | `localDev`, `vercelOidc`, `placeholderAuth` |
+| `eve/channels/{slack,discord,teams,telegram,twilio,github}` | platform channel factories |
+| `eve/hooks` | `defineHook` |
+| `eve/schedules` | `defineSchedule` |
+| `eve/skills` | `defineSkill`, `defineDynamic` |
+| `eve/instructions` | `defineInstructions`, `defineDynamic` |
+| `eve/context` | `defineState`, session and state types |
+| `eve/sandbox` | `defineSandbox`, backends |
+| `eve/instrumentation` | `defineInstrumentation`, `isChannel` |
+| `eve/evals` | `defineEval`, `defineEvalConfig`, `mockModel`, eval types |
+| `eve/evals/expect` | `includes`, `equals`, `matches`, `similarity` |
+| `eve/evals/reporters` | `Braintrust`, `JUnit`, `EvalReporter` |
+| `eve/evals/loaders` | `loadJson`, `loadYaml` |
+| `eve/react`, `eve/vue`, `eve/svelte` | `useEveAgent` |
+| `eve/next`, `eve/nuxt`, `eve/sveltekit` | framework bundler plugins |
+| [`eve/client`](../guides/client/overview) | `Client`, `ClientSession` |
Exported types ship from the same entrypoint as the helper they describe (for example `ToolDefinition` and `ToolContext` from `eve/tools`). For the exhaustive list, read `packages/eve/src/public/index.ts`.
diff --git a/docs/subagents.mdx b/docs/subagents.mdx
index cd34ab854..83a0074c0 100644
--- a/docs/subagents.mdx
+++ b/docs/subagents.mdx
@@ -94,7 +94,7 @@ at depths 1 through 4; a session already at depth 4 cannot delegate again.
At the configured depth, eve stops advertising subagent tools, including declared local subagents, remote-agent tools, the built-in `agent` tool, and the `Workflow` orchestration tool when it would only expose subagents. If a stale or forced subagent call still reaches execution, eve blocks it and returns an error tool result instead of starting another child session.
-`Workflow` is root-only. Delegated subagent sessions can still call their own visible subagent tools until the depth cap, but they do not receive the `Workflow` orchestration wrapper.
+`Workflow` is root-only. Delegated subagent sessions can still call their own visible subagent tools until the depth cap, but they do not receive the `Workflow` orchestration wrapper. The number of subagent calls one Workflow program may dispatch is capped separately by `limits.maxSubagents` (default 100); see [Dynamic workflows](./guides/dynamic-workflows).
A declared subagent's tool name is the bare path-derived name, with no prefix. `agent/subagents/researcher/` registers as the tool `researcher`. Unlike connection tools (`<connection>__<tool>`), it carries no namespace, so the model, approvals, logs, and evals all reference it by that name. Its input schema is:
@@ -118,3 +118,4 @@ Split out a subagent when the task needs a different prompt or specialist role,
## What to read next
- [Remote agents](./guides/remote-agents): call another eve deployment as a subagent.
+- [Dynamic workflows](./guides/dynamic-workflows): have the model orchestrate its subagents programmatically (fan-out, map-reduce).
diff --git a/e2e/fixtures/agent-subagents/agent/agent.ts b/e2e/fixtures/agent-subagents/agent/agent.ts
index c7dff0d63..eb2028cef 100644
--- a/e2e/fixtures/agent-subagents/agent/agent.ts
+++ b/e2e/fixtures/agent-subagents/agent/agent.ts
@@ -3,6 +3,7 @@ import { defineAgent } from "eve";
export default defineAgent({
limits: {
maxSubagentDepth: 4,
+ maxSubagents: 2,
},
model: "anthropic/claude-sonnet-5",
reasoning: "high",
diff --git a/e2e/fixtures/agent-subagents/agent/tools/workflow.ts b/e2e/fixtures/agent-subagents/agent/tools/workflow.ts
index 4b31fcd00..783084219 100644
--- a/e2e/fixtures/agent-subagents/agent/tools/workflow.ts
+++ b/e2e/fixtures/agent-subagents/agent/tools/workflow.ts
@@ -1 +1 @@
-export default Object.freeze({ kind: "eve:enable-workflow-tool" });
+export { ExperimentalWorkflow as default } from "eve/tools";
diff --git a/e2e/fixtures/agent-subagents/evals/workflow-subagent-limit.eval.ts b/e2e/fixtures/agent-subagents/evals/workflow-subagent-limit.eval.ts
new file mode 100644
index 000000000..3dee5f5d8
--- /dev/null
+++ b/e2e/fixtures/agent-subagents/evals/workflow-subagent-limit.eval.ts
@@ -0,0 +1,25 @@
+import { defineEval } from "eve/evals";
+
+/**
+ * Workflow subagent budget: the fixture caps `limits.maxSubagents` at 2, so a
+ * three-call fan-out spawns two children and the third call resolves inside
+ * the program with a `WORKFLOW_SUBAGENT_LIMIT_REACHED` error result.
+ */
+export default defineEval({
+ description:
+ "Workflow calls beyond limits.maxSubagents resolve with WORKFLOW_SUBAGENT_LIMIT_REACHED instead of spawning children.",
+ 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, fan out three echo-marker subagent calls with the messages 'limit alpha', 'limit beta', and 'limit gamma' inside one Promise.all, 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.",
+ ].join(" "),
+ );
+
+ t.succeeded();
+ t.calledTool("Workflow", { count: 1 });
+ t.calledSubagent("echo-marker", { count: 2 });
+ t.messageIncludes("WORKFLOW_SUBAGENT_LIMIT_REACHED");
+ },
+});
diff --git a/packages/eve/src/compiler/manifest.ts b/packages/eve/src/compiler/manifest.ts
index 19bc73a39..1371f11e2 100644
--- a/packages/eve/src/compiler/manifest.ts
+++ b/packages/eve/src/compiler/manifest.ts
@@ -360,6 +360,7 @@ const compiledAgentCompactionDefinitionSchema: z.ZodType<CompiledAgentCompaction
const compiledAgentLimitsDefinitionSchema = z
.object({
maxSubagentDepth: z.number().int().positive().optional(),
+ maxSubagents: z.number().int().positive().optional(),
maxInputTokensPerSession: z.number().int().positive().optional(),
maxOutputTokensPerSession: z.number().int().positive().optional(),
})
@@ -733,6 +734,7 @@ export function createCompiledAgentNodeManifest(input: {
maxInputTokensPerSession: input.config.limits.maxInputTokensPerSession,
maxOutputTokensPerSession: input.config.limits.maxOutputTokensPerSession,
maxSubagentDepth: input.config.limits.maxSubagentDepth,
+ maxSubagents: input.config.limits.maxSubagents,
},
source:
input.config.source === undefined
diff --git a/packages/eve/src/compiler/normalize-agent-config.ts b/packages/eve/src/compiler/normalize-agent-config.ts
index ffab2600f..0e3452c1a 100644
--- a/packages/eve/src/compiler/normalize-agent-config.ts
+++ b/packages/eve/src/compiler/normalize-agent-config.ts
@@ -107,6 +107,7 @@ export async function compileAgentConfig(
if (definition.limits !== undefined) {
compiledConfig.limits = {
maxSubagentDepth: definition.limits.maxSubagentDepth,
+ maxSubagents: definition.limits.maxSubagents,
maxInputTokensPerSession: definition.limits.maxInputTokensPerSession,
maxOutputTokensPerSession: definition.limits.maxOutputTokensPerSession,
};
diff --git a/packages/eve/src/execution/dispatch-workflow-runtime-actions-step.ts b/packages/eve/src/execution/dispatch-workflow-runtime-actions-step.ts
index 19197118b..ae9ac7fc8 100644
--- a/packages/eve/src/execution/dispatch-workflow-runtime-actions-step.ts
+++ b/packages/eve/src/execution/dispatch-workflow-runtime-actions-step.ts
@@ -9,8 +9,19 @@ import { hydrateDurableSession } from "#execution/session.js";
import { getPendingWorkflowInterrupt } from "#harness/workflow-interrupt-state.js";
import { setPendingRuntimeActionBatch } from "#harness/runtime-actions.js";
import { buildRuntimeActionsFromWorkflowInterrupt } from "#harness/workflow-runtime-action-state.js";
+import {
+ planWorkflowSubagentDispatch,
+ type WorkflowSubagentDispatchPlan,
+} from "#harness/workflow-subagent-limit.js";
+import { getSubagentDelegationName, isSubagentDelegationAction } from "#harness/subagent-depth.js";
+import { createLogger } from "#internal/logging.js";
import { BundleKey } from "#runtime/sessions/runtime-context-keys.js";
-import type { RuntimeSubagentResultActionResult } from "#runtime/actions/types.js";
+import type {
+ RuntimeActionRequest,
+ RuntimeSubagentResultActionResult,
+} from "#runtime/actions/types.js";
+
+const log = createLogger("execution.dispatch-workflow-runtime-actions");
/** Dispatches the child-agent action currently blocking a dynamic workflow. */
export async function dispatchWorkflowRuntimeActionsStep(input: {
@@ -34,6 +45,29 @@ export async function dispatchWorkflowRuntimeActionsStep(input: {
const ctx = await deserializeContext(input.serializedContext);
const bundle = ctx.require(BundleKey);
+
+ const plan = planWorkflowSubagentDispatch({
+ actions,
+ interrupt: pending.interrupt,
+ maxSubagents: bundle.resolvedAgent.config.limits?.maxSubagents,
+ });
+
+ const blockedResults = plan.blocked.map((action) => {
+ log.warn("workflow subagent limit reached; blocking delegated call", {
+ callId: action.callId,
+ maxSubagents: plan.maxSubagents,
+ subagentName: isSubagentDelegationAction(action)
+ ? getSubagentDelegationName(action)
+ : action.kind,
+ usedCalls: plan.usedCalls,
+ });
+ return createWorkflowSubagentLimitResult({ action, plan });
+ });
+
+ if (plan.allowed.length === 0) {
+ return { results: blockedResults, sessionState: input.sessionState };
+ }
+
const session = hydrateDurableSession({
compactionOverrides: {
thresholdPercent: bundle.resolvedAgent.config.compaction?.thresholdPercent,
@@ -43,17 +77,47 @@ export async function dispatchWorkflowRuntimeActionsStep(input: {
});
const sessionWithBatch = setPendingRuntimeActionBatch({
- actions,
+ actions: plan.allowed,
event: { sequence: 0, stepIndex: 0, turnId: "workflow-dispatch" },
responseMessages: [],
session,
});
- return dispatchRuntimeActionsStep({
+ const dispatched = await dispatchRuntimeActionsStep({
callbackBaseUrl: input.callbackBaseUrl,
parentContinuationToken: input.parentContinuationToken,
parentWritable: input.parentWritable,
serializedContext: input.serializedContext,
sessionState: createDurableSessionState({ session: sessionWithBatch }),
});
+
+ if (blockedResults.length === 0) {
+ return dispatched;
+ }
+
+ return {
+ results: [...dispatched.results, ...blockedResults],
+ sessionState: dispatched.sessionState,
+ };
+}
+
+function createWorkflowSubagentLimitResult(input: {
+ readonly action: RuntimeActionRequest;
+ readonly plan: WorkflowSubagentDispatchPlan;
+}): RuntimeSubagentResultActionResult {
+ const subagentName = isSubagentDelegationAction(input.action)
+ ? getSubagentDelegationName(input.action)
+ : input.action.kind;
+
+ return {
+ callId: input.action.callId,
+ isError: true,
+ kind: "subagent-result",
+ output: {
+ code: "WORKFLOW_SUBAGENT_LIMIT_REACHED",
+ maxSubagents: input.plan.maxSubagents,
+ message: `Workflow subagent limit reached (${String(input.plan.maxSubagents)}); "${subagentName}" was not called.`,
+ },
+ subagentName,
+ };
}
diff --git a/packages/eve/src/execution/node-step.ts b/packages/eve/src/execution/node-step.ts
index 4082f7f25..7647f70ff 100644
--- a/packages/eve/src/execution/node-step.ts
+++ b/packages/eve/src/execution/node-step.ts
@@ -77,6 +77,7 @@ export function createExecutionNodeStep(input: CreateExecutionNodeStepInput): St
abortSignal: input.abortSignal,
capabilities: input.capabilities,
workflow: input.node.agent.workflowEnabled === true,
+ workflowMaxSubagents: input.node.agent.config?.limits?.maxSubagents,
handleEvent: input.handleEvent,
mode: input.mode,
onCompaction: preserveFrameworkStateOnCompaction,
diff --git a/packages/eve/src/harness/advertised-tools.ts b/packages/eve/src/harness/advertised-tools.ts
index 03b202d7c..f21ae5ab8 100644
--- a/packages/eve/src/harness/advertised-tools.ts
+++ b/packages/eve/src/harness/advertised-tools.ts
@@ -33,6 +33,7 @@ type AdvertisedModelToolsInput = {
readonly session: HarnessSession;
readonly tools: HarnessToolMap;
}) => WorkflowSandboxLifecycle | undefined;
+ readonly maxSubagents?: number;
};
};
@@ -93,6 +94,7 @@ async function getAdvertisedModelTools(
continuationSecurity: getWorkflowContinuationSecurity(session),
harnessTools: workflowHostTools,
lifecycle: input.workflow.lifecycle?.({ session, tools: workflowHostTools }),
+ maxSubagents: input.workflow.maxSubagents,
tools: input.modelTools,
});
diff --git a/packages/eve/src/harness/tool-loop.ts b/packages/eve/src/harness/tool-loop.ts
index 478afa5a4..0a9b1eba5 100644
--- a/packages/eve/src/harness/tool-loop.ts
+++ b/packages/eve/src/harness/tool-loop.ts
@@ -688,7 +688,9 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {
})
: undefined;
const workflowConfig =
- config.workflow === true ? { lifecycle: workflowLifecycle } : undefined;
+ config.workflow === true
+ ? { lifecycle: workflowLifecycle, maxSubagents: config.workflowMaxSubagents }
+ : undefined;
const advertisedModelTools = await getAdvertisedTools({
modelTools: flatTools,
diff --git a/packages/eve/src/harness/types.ts b/packages/eve/src/harness/types.ts
index de1f46064..2f455d6f5 100644
--- a/packages/eve/src/harness/types.ts
+++ b/packages/eve/src/harness/types.ts
@@ -223,10 +223,18 @@ export interface ToolLoopHarnessConfig {
* Exposes the `Workflow` orchestration tool — an isolated JavaScript sandbox
* whose only callable operations are this agent's subagents and remote
* agents. Resolved by the runtime from the agent's `workflowEnabled` flag
- * in the compiled manifest.
+ * (set when `agent/tools/workflow.ts` re-exports the `ExperimentalWorkflow`
+ * marker). Only root sessions ever see the tool.
* Defaults to `false`.
*/
readonly workflow?: boolean;
+ /**
+ * Maximum subagent calls one `Workflow` invocation may dispatch, from the
+ * agent's `limits.maxSubagents`. 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;
/**
* Execution mode for the current harness.
diff --git a/packages/eve/src/harness/workflow-sandbox.ts b/packages/eve/src/harness/workflow-sandbox.ts
index f53efae4f..1e8d5aad7 100644
--- a/packages/eve/src/harness/workflow-sandbox.ts
+++ b/packages/eve/src/harness/workflow-sandbox.ts
@@ -26,6 +26,7 @@ export async function applyWorkflowTool(input: {
readonly continuationSecurity: WorkflowSandboxContinuationSecurity;
readonly harnessTools: HarnessToolMap;
readonly lifecycle?: WorkflowSandboxLifecycle;
+ readonly maxSubagents?: number;
readonly tools: ToolSet;
}): Promise<WorkflowToolSet> {
const hostTools = createWorkflowHostTools(input.harnessTools, Object.keys(input.tools));
@@ -40,7 +41,9 @@ export async function applyWorkflowTool(input: {
lifecycle: input.lifecycle,
});
const generated = typeof workflowTool.description === "string" ? workflowTool.description : "";
- const framing = workflowToolDescription(Object.keys(hostTools));
+ 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] = {
diff --git a/packages/eve/src/harness/workflow-subagent-limit.test.ts b/packages/eve/src/harness/workflow-subagent-limit.test.ts
new file mode 100644
index 000000000..7f3095aa7
--- /dev/null
+++ b/packages/eve/src/harness/workflow-subagent-limit.test.ts
@@ -0,0 +1,155 @@
+import { describe, expect, it } from "vitest";
+
+import { WORKFLOW_RUNTIME_ACTION_INTERRUPT_KIND } from "#harness/workflow-runtime-action-state.js";
+import {
+ countResolvedWorkflowSubagentCalls,
+ DEFAULT_WORKFLOW_MAX_SUBAGENTS,
+ planWorkflowSubagentDispatch,
+} from "#harness/workflow-subagent-limit.js";
+import type { RuntimeActionRequest } from "#runtime/actions/types.js";
+import type { WorkflowSandboxInterrupt } from "#shared/workflow-sandbox.js";
+
+type LedgerEntry = WorkflowSandboxInterrupt["continuation"]["ledger"][number];
+
+function fulfilledEntry(index: number): LedgerEntry {
+ return {
+ dateNowMs: 1,
+ inputJson: JSON.stringify({ message: `done-${index}` }),
+ kind: "tool",
+ name: "echo-marker",
+ status: "fulfilled",
+ toolCallId: `workflow-call:tool-${index}`,
+ valueJson: JSON.stringify({ output: "ok" }),
+ };
+}
+
+function interruptedEntry(index: number): LedgerEntry {
+ const toolCallId = `workflow-call:tool-${index}`;
+ return {
+ inputJson: JSON.stringify({ message: `pending-${index}` }),
+ interruptId: `${toolCallId}:interrupt`,
+ interruptPayload: {
+ kind: WORKFLOW_RUNTIME_ACTION_INTERRUPT_KIND,
+ runtimeAction: {
+ kind: "subagent-call",
+ nodeId: "subagents/echo-marker",
+ subagentName: "echo-marker",
+ },
+ toolInput: { message: `pending-${index}` },
+ toolName: "echo-marker",
+ },
+ kind: "tool",
+ name: "echo-marker",
+ status: "interrupted",
+ toolCallId,
+ };
+}
+
+function createInterrupt(ledger: LedgerEntry[]): WorkflowSandboxInterrupt {
+ return {
+ continuation: {
+ auth: {
+ alg: "HMAC-SHA256",
+ expiresAtMs: 2,
+ issuedAtMs: 1,
+ nonce: "nonce",
+ signature: "signature",
+ },
+ determinism: { dateNowMs: 1, randomSeed: "00000000000000000000000000000000" },
+ js: "return 1",
+ ledger,
+ outerToolCallId: "workflow-call",
+ version: 1,
+ },
+ input: {},
+ interruptId: "workflow-call:tool-1:interrupt",
+ outerToolCallId: "workflow-call",
+ payload: { kind: WORKFLOW_RUNTIME_ACTION_INTERRUPT_KIND },
+ toolCallId: "workflow-call:tool-1",
+ toolName: "echo-marker",
+ type: "code-mode-interrupt",
+ };
+}
+
+function createAction(index: number): RuntimeActionRequest {
+ return {
+ callId: `call-${index}`,
+ description: "",
+ input: {},
+ kind: "subagent-call",
+ name: "echo-marker",
+ nodeId: "subagents/echo-marker",
+ subagentName: "echo-marker",
+ };
+}
+
+describe("countResolvedWorkflowSubagentCalls", () => {
+ it("counts fulfilled and rejected tool entries but not pending interrupts", () => {
+ const interrupt = createInterrupt([
+ fulfilledEntry(1),
+ {
+ dateNowMs: 1,
+ error: { message: "boom", name: "Error" },
+ inputJson: "{}",
+ kind: "tool",
+ name: "echo-marker",
+ status: "rejected",
+ toolCallId: "workflow-call:tool-2",
+ },
+ interruptedEntry(3),
+ ]);
+
+ expect(countResolvedWorkflowSubagentCalls(interrupt)).toBe(2);
+ });
+});
+
+describe("planWorkflowSubagentDispatch", () => {
+ it("allows every pending action while the budget holds", () => {
+ const actions = [createAction(1), createAction(2)];
+ const plan = planWorkflowSubagentDispatch({
+ actions,
+ interrupt: createInterrupt([interruptedEntry(1), interruptedEntry(2)]),
+ maxSubagents: 3,
+ });
+
+ expect(plan.allowed).toEqual(actions);
+ expect(plan.blocked).toEqual([]);
+ expect(plan.usedCalls).toBe(0);
+ });
+
+ it("blocks the actions beyond the remaining budget, preserving ledger order", () => {
+ const actions = [createAction(1), createAction(2), createAction(3)];
+ const plan = planWorkflowSubagentDispatch({
+ actions,
+ interrupt: createInterrupt([
+ fulfilledEntry(0),
+ ...actions.map((_, i) => interruptedEntry(i + 1)),
+ ]),
+ maxSubagents: 3,
+ });
+
+ expect(plan.allowed).toEqual([actions[0], actions[1]]);
+ expect(plan.blocked).toEqual([actions[2]]);
+ expect(plan.usedCalls).toBe(1);
+ });
+
+ it("blocks everything once the budget is spent", () => {
+ const plan = planWorkflowSubagentDispatch({
+ actions: [createAction(1)],
+ interrupt: createInterrupt([fulfilledEntry(1), fulfilledEntry(2), interruptedEntry(3)]),
+ maxSubagents: 2,
+ });
+
+ expect(plan.allowed).toEqual([]);
+ expect(plan.blocked).toHaveLength(1);
+ });
+
+ it("defaults the budget to DEFAULT_WORKFLOW_MAX_SUBAGENTS", () => {
+ const plan = planWorkflowSubagentDispatch({
+ actions: [createAction(1)],
+ interrupt: createInterrupt([interruptedEntry(1)]),
+ });
+
+ 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.ts
new file mode 100644
index 000000000..ca3470cf2
--- /dev/null
+++ b/packages/eve/src/harness/workflow-subagent-limit.ts
@@ -0,0 +1,61 @@
+import type { RuntimeActionRequest } from "#runtime/actions/types.js";
+import type { WorkflowSandboxInterrupt } from "#shared/workflow-sandbox.js";
+
+/**
+ * Default for `limits.maxSubagents`: the 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 runtime actions against the
+ * invocation's subagent budget. `allowed` actions may dispatch; `blocked`
+ * actions must resolve with an error result instead of starting a child.
+ */
+export type WorkflowSubagentDispatchPlan = {
+ readonly allowed: readonly RuntimeActionRequest[];
+ readonly blocked: readonly RuntimeActionRequest[];
+ readonly maxSubagents: number;
+ readonly usedCalls: number;
+};
+
+/**
+ * Counts the subagent calls this Workflow invocation has already resolved.
+ *
+ * Every host tool bridged into the workflow sandbox is a subagent or
+ * remote-agent call, so each fulfilled or rejected `tool` ledger entry is one
+ * consumed call. Entries still `interrupted` are the pending actions being
+ * planned, not consumed budget.
+ */
+export function countResolvedWorkflowSubagentCalls(interrupt: WorkflowSandboxInterrupt): number {
+ let count = 0;
+ for (const entry of interrupt.continuation.ledger) {
+ if (entry.kind === "tool" && entry.status !== "interrupted") {
+ count += 1;
+ }
+ }
+ return count;
+}
+
+/**
+ * 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 ledger order so results pair with the
+ * sandbox program's call order.
+ */
+export function planWorkflowSubagentDispatch(input: {
+ readonly actions: readonly RuntimeActionRequest[];
+ readonly interrupt: WorkflowSandboxInterrupt;
+ readonly maxSubagents?: number;
+}): WorkflowSubagentDispatchPlan {
+ const maxSubagents = input.maxSubagents ?? DEFAULT_WORKFLOW_MAX_SUBAGENTS;
+ const usedCalls = countResolvedWorkflowSubagentCalls(input.interrupt);
+ const remaining = Math.max(0, maxSubagents - usedCalls);
+
+ return {
+ allowed: input.actions.slice(0, remaining),
+ blocked: input.actions.slice(remaining),
+ maxSubagents,
+ usedCalls,
+ };
+}
diff --git a/packages/eve/src/harness/workflow-tool-description.test.ts b/packages/eve/src/harness/workflow-tool-description.test.ts
index 0b40168bf..8d274c19c 100644
--- a/packages/eve/src/harness/workflow-tool-description.test.ts
+++ b/packages/eve/src/harness/workflow-tool-description.test.ts
@@ -15,6 +15,19 @@ describe("workflowToolDescription", () => {
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"]);
diff --git a/packages/eve/src/harness/workflow-tool-description.ts b/packages/eve/src/harness/workflow-tool-description.ts
index d29953aac..d2366db12 100644
--- a/packages/eve/src/harness/workflow-tool-description.ts
+++ b/packages/eve/src/harness/workflow-tool-description.ts
@@ -1,3 +1,5 @@
+import { DEFAULT_WORKFLOW_MAX_SUBAGENTS } from "#harness/workflow-subagent-limit.js";
+
/**
* Builds the model-facing description for the `Workflow` orchestration tool.
*
@@ -13,8 +15,15 @@
* 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[]): string {
+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");
@@ -39,6 +48,8 @@ Do not use \`Workflow\` when:
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:
diff --git a/packages/eve/src/internal/authored-definition/core.test.ts b/packages/eve/src/internal/authored-definition/core.test.ts
index e0ccdeef7..4103989c4 100644
--- a/packages/eve/src/internal/authored-definition/core.test.ts
+++ b/packages/eve/src/internal/authored-definition/core.test.ts
@@ -40,6 +40,7 @@ describe("normalizeAgentDefinition", () => {
maxInputTokensPerSession: 200_000,
maxOutputTokensPerSession: 20_000,
maxSubagentDepth: 4,
+ maxSubagents: 6,
},
},
FAILURE_MESSAGE,
@@ -49,6 +50,7 @@ describe("normalizeAgentDefinition", () => {
maxInputTokensPerSession: 200_000,
maxOutputTokensPerSession: 20_000,
maxSubagentDepth: 4,
+ maxSubagents: 6,
});
});
@@ -64,6 +66,18 @@ describe("normalizeAgentDefinition", () => {
).toThrow(FAILURE_MESSAGE);
});
+ it.each([0, 1.5, -1, "6"])("rejects invalid workflow max subagents %j", (maxSubagents) => {
+ expect(() =>
+ normalizeAgentDefinition(
+ {
+ model: "openai/gpt-5.5",
+ limits: { maxSubagents },
+ },
+ FAILURE_MESSAGE,
+ ),
+ ).toThrow(FAILURE_MESSAGE);
+ });
+
it.each([
["maxInputTokensPerSession", 0],
["maxInputTokensPerSession", 1.5],
diff --git a/packages/eve/src/internal/authored-definition/core.ts b/packages/eve/src/internal/authored-definition/core.ts
index 49e8a7a93..a325d1773 100644
--- a/packages/eve/src/internal/authored-definition/core.ts
+++ b/packages/eve/src/internal/authored-definition/core.ts
@@ -135,7 +135,7 @@ function normalizeAgentLimitsDefinition(
const record = expectObjectRecord(value, message);
expectOnlyKnownKeys(
record,
- ["maxInputTokensPerSession", "maxOutputTokensPerSession", "maxSubagentDepth"],
+ ["maxInputTokensPerSession", "maxOutputTokensPerSession", "maxSubagentDepth", "maxSubagents"],
message,
);
const normalizedDefinition: Mutable<NonNullable<NormalizedAgentDefinition["limits"]>> = {};
@@ -155,6 +155,9 @@ function normalizeAgentLimitsDefinition(
if (record.maxSubagentDepth !== undefined) {
normalizedDefinition.maxSubagentDepth = expectPositiveInteger(record.maxSubagentDepth, message);
}
+ if (record.maxSubagents !== undefined) {
+ normalizedDefinition.maxSubagents = expectPositiveInteger(record.maxSubagents, message);
+ }
return normalizedDefinition;
}
diff --git a/packages/eve/src/internal/authored-definition/schema-backed.test.ts b/packages/eve/src/internal/authored-definition/schema-backed.test.ts
index 8a426c1fe..eb0669184 100644
--- a/packages/eve/src/internal/authored-definition/schema-backed.test.ts
+++ b/packages/eve/src/internal/authored-definition/schema-backed.test.ts
@@ -1,7 +1,12 @@
import { describe, expect, it } from "vitest";
import { z } from "#compiled/zod/index.js";
-import { defineTool, defineDynamic, disableTool } from "#public/definitions/tool.js";
+import {
+ defineTool,
+ defineDynamic,
+ disableTool,
+ ExperimentalWorkflow,
+} from "#public/definitions/tool.js";
import { once } from "#public/tools/approval/approval-helpers.js";
import { normalizeToolDefinition } from "#internal/authored-definition/schema-backed.js";
@@ -35,11 +40,8 @@ describe("normalizeToolDefinition", () => {
expect(entry).toEqual({ kind: "disabled" });
});
- it("returns an enable-workflow entry for the internal workflow marker shape", () => {
- const entry = normalizeToolDefinition(
- Object.freeze({ kind: "eve:enable-workflow-tool" }),
- FAILURE_MESSAGE,
- );
+ it("returns an enable-workflow entry for the ExperimentalWorkflow marker", () => {
+ const entry = normalizeToolDefinition(ExperimentalWorkflow, FAILURE_MESSAGE);
expect(entry).toEqual({ kind: "enable-workflow" });
});
diff --git a/packages/eve/src/internal/authored-definition/schema-backed.ts b/packages/eve/src/internal/authored-definition/schema-backed.ts
index 5989b89e7..869f5b0de 100644
--- a/packages/eve/src/internal/authored-definition/schema-backed.ts
+++ b/packages/eve/src/internal/authored-definition/schema-backed.ts
@@ -1,4 +1,4 @@
-import { isDisabledToolSentinel } from "#public/definitions/tool.js";
+import { isDisabledToolSentinel, isEnableWorkflowToolSentinel } from "#public/definitions/tool.js";
import {
expectFunction,
expectObjectRecord,
@@ -19,19 +19,6 @@ type NormalizedAuthoredTool = Readonly<Omit<InternalToolDefinitionWithExecuteFn,
type MutableNormalizedAuthoredTool = {
-readonly [K in keyof NormalizedAuthoredTool]: NormalizedAuthoredTool[K];
};
-const ENABLE_WORKFLOW_TOOL_SENTINEL_KIND = "eve:enable-workflow-tool";
-
-interface EnableWorkflowToolSentinel {
- readonly kind: typeof ENABLE_WORKFLOW_TOOL_SENTINEL_KIND;
-}
-
-function isEnableWorkflowToolSentinel(value: unknown): value is EnableWorkflowToolSentinel {
- return (
- typeof value === "object" &&
- value !== null &&
- (value as { kind?: unknown }).kind === ENABLE_WORKFLOW_TOOL_SENTINEL_KIND
- );
-}
/**
* Result of normalizing one authored tool default export. Either a real tool
diff --git a/packages/eve/src/public/definitions/exact.test.ts b/packages/eve/src/public/definitions/exact.test.ts
index 5e57c8a5c..eaf9b0cad 100644
--- a/packages/eve/src/public/definitions/exact.test.ts
+++ b/packages/eve/src/public/definitions/exact.test.ts
@@ -20,6 +20,7 @@ describe("definition helper exact inputs", () => {
maxInputTokensPerSession: 200_000,
maxOutputTokensPerSession: 20_000,
maxSubagentDepth: 4,
+ maxSubagents: 6,
},
model: "anthropic/claude-sonnet-5",
});
@@ -33,6 +34,7 @@ describe("definition helper exact inputs", () => {
expect(agent.limits.maxInputTokensPerSession).toBe(200_000);
expect(agent.limits.maxOutputTokensPerSession).toBe(20_000);
expect(agent.limits.maxSubagentDepth).toBe(4);
+ expect(agent.limits.maxSubagents).toBe(6);
expect(schedule.cron).toBe("0 9 * * *");
});
});
diff --git a/packages/eve/src/public/definitions/tool.ts b/packages/eve/src/public/definitions/tool.ts
index 0399a29f2..7af38a376 100644
--- a/packages/eve/src/public/definitions/tool.ts
+++ b/packages/eve/src/public/definitions/tool.ts
@@ -306,3 +306,52 @@ export function isDisabledToolSentinel(value: unknown): value is DisabledToolSen
(value as { kind?: unknown }).kind === DISABLED_TOOL_SENTINEL_KIND
);
}
+
+/**
+ * Marker discriminator written into the {@link ExperimentalWorkflow} opt-in
+ * sentinel.
+ */
+const ENABLE_WORKFLOW_TOOL_SENTINEL_KIND = "eve:enable-workflow-tool";
+
+/**
+ * Marker value re-exported as the default export of a file in `agent/tools/`
+ * (conventionally `agent/tools/workflow.ts`) to enable the framework `Workflow`
+ * orchestration tool. The tool is off unless this marker is present,
+ * mirroring the {@link disableTool} opt-out in reverse.
+ */
+export interface EnableWorkflowToolSentinel {
+ readonly kind: typeof ENABLE_WORKFLOW_TOOL_SENTINEL_KIND;
+}
+
+/**
+ * Opt-in marker for the framework `Workflow` tool, an isolated JavaScript sandbox whose
+ * only callable operations are this agent's subagents and remote agents, for
+ * orchestrating them from model-authored JavaScript. Re-export it as the
+ * default export of `agent/tools/workflow.ts`:
+ *
+ * ```ts
+ * export { ExperimentalWorkflow as default } from "eve/tools";
+ * ```
+ *
+ * Only the root session sees the `Workflow` tool — delegated subagent sessions
+ * never get it — and one Workflow program may dispatch at most
+ * `limits.maxSubagents` subagent calls (default 100).
+ *
+ * The capability is experimental. The resulting model-facing tool is still
+ * called `Workflow`.
+ */
+export const ExperimentalWorkflow: EnableWorkflowToolSentinel = Object.freeze({
+ kind: ENABLE_WORKFLOW_TOOL_SENTINEL_KIND,
+});
+
+/**
+ * Type guard: returns whether `value` is the {@link ExperimentalWorkflow}
+ * opt-in sentinel.
+ */
+export function isEnableWorkflowToolSentinel(value: unknown): value is EnableWorkflowToolSentinel {
+ return (
+ typeof value === "object" &&
+ value !== null &&
+ (value as { kind?: unknown }).kind === ENABLE_WORKFLOW_TOOL_SENTINEL_KIND
+ );
+}
diff --git a/packages/eve/src/public/tools/index.ts b/packages/eve/src/public/tools/index.ts
index 3e7a57478..c738bcbed 100644
--- a/packages/eve/src/public/tools/index.ts
+++ b/packages/eve/src/public/tools/index.ts
@@ -4,10 +4,13 @@
export {
type DisabledToolSentinel,
+ type EnableWorkflowToolSentinel,
defineDynamic,
defineTool,
disableTool,
isDisabledToolSentinel,
+ isEnableWorkflowToolSentinel,
+ ExperimentalWorkflow,
type ToolAuthOptions,
type ToolAuthProvider,
type ToolDefinition,
diff --git a/packages/eve/src/runtime/resolve-agent.ts b/packages/eve/src/runtime/resolve-agent.ts
index ccc9b0a34..e5e63f3b7 100644
--- a/packages/eve/src/runtime/resolve-agent.ts
+++ b/packages/eve/src/runtime/resolve-agent.ts
@@ -234,6 +234,7 @@ function createResolvedAgentConfig(manifest: CompiledAgentNodeManifest): Resolve
if (manifest.config.limits !== undefined) {
config.limits = {
maxSubagentDepth: manifest.config.limits.maxSubagentDepth,
+ maxSubagents: manifest.config.limits.maxSubagents,
maxInputTokensPerSession: manifest.config.limits.maxInputTokensPerSession,
maxOutputTokensPerSession: manifest.config.limits.maxOutputTokensPerSession,
};
diff --git a/packages/eve/src/shared/agent-definition.ts b/packages/eve/src/shared/agent-definition.ts
index af2001ccc..0c426379e 100644
--- a/packages/eve/src/shared/agent-definition.ts
+++ b/packages/eve/src/shared/agent-definition.ts
@@ -109,6 +109,19 @@ export interface AgentLimitsDefinition {
* @default 3
*/
readonly maxSubagentDepth?: number;
+ /**
+ * Maximum number of subagent calls one `Workflow` tool invocation may
+ * dispatch.
+ *
+ * Applies to the opt-in `Workflow` orchestration tool: a single
+ * model-authored workflow program may spawn at most this many subagent or
+ * remote-agent calls, counted across the whole program (sequential and
+ * parallel calls alike). Calls beyond the limit fail with an error result
+ * instead of starting a child session.
+ *
+ * @default 100
+ */
+ readonly maxSubagents?: number;
/**
* Maximum provider-reported input tokens accumulated by one durable session.
*