Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat(eve): support dynamic remote subagents (#1501)

Casey Gowrie13420abb8a97
diff --git a/.changeset/dynamic-remote-subagents.md b/.changeset/dynamic-remote-subagents.md
new file mode 100644
index 000000000..864e47711
--- /dev/null
+++ b/.changeset/dynamic-remote-subagents.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Allow dynamic subagent resolvers to return `defineRemoteAgent(...)`. Session and turn selections can now conditionally expose a remote deployment and change its runtime connection settings.
diff --git a/docs/guides/dynamic-capabilities.md b/docs/guides/dynamic-capabilities.md
index e4d1afa48..a82419b47 100644
--- a/docs/guides/dynamic-capabilities.md
+++ b/docs/guides/dynamic-capabilities.md
@@ -51,12 +51,37 @@ compiled manifest. Each resolution can return a different model or other
runtime agent settings. Runtime-selected models must use string model IDs;
build and Workflow-world configuration cannot be selected at runtime.
+A single-file remote subagent uses the same lifecycle. Return
+`defineRemoteAgent(...)` to expose the selected deployment, or nil to omit it:
+
+```ts title="agent/subagents/finance.ts"
+import { defineDynamic, defineRemoteAgent } from "eve";
+
+export default defineDynamic({
+ events: {
+ "session.started": (_event, ctx) =>
+ ctx.session.auth.current?.attributes.plan === "enterprise"
+ ? defineRemoteAgent({
+ description: "Analyze financial and accounting data.",
+ url: "https://finance-agent.example.com",
+ })
+ : null,
+ },
+});
+```
+
+The returned remote definition can change its URL, path, headers, auth,
+principal forwarding, and output schema. Function-valued URLs resolve when the
+dynamic event runs. Auth and headers remain lazy and resolve before each
+outbound request without entering durable workflow state.
+
Dynamic subagents support `session.started` and `turn.started`. A turn selection
shadows the session selection for that turn, including when the turn handler
returns nil. If a resolver throws or returns an invalid definition, eve logs the
failure and omits the subagent.
-The resolved set applies to direct delegation and the `Workflow` tool. eve
+The resolved set applies to local and remote direct delegation and the
+`Workflow` tool. eve
also checks availability again before starting the child, so a stale or
manually constructed call fails with `SUBAGENT_UNAVAILABLE`. Treat conditional
availability as capability composition, not as the only authorization
diff --git a/docs/guides/remote-agents.md b/docs/guides/remote-agents.md
index 8f876c7cc..4941eb082 100644
--- a/docs/guides/remote-agents.md
+++ b/docs/guides/remote-agents.md
@@ -30,6 +30,39 @@ export default defineRemoteAgent({
| `path` | `string` | No | `/eve/v1/session` | Route appended to `url` for the create-session request. |
| `outputSchema` | `StandardSchema \| JSON Schema` | No | none | Structured return type the caller requires. Lowered to JSON Schema at compile time and enforced by the remote like any task-mode output schema. |
+## Dynamic remote agents
+
+Wrap the file in `defineDynamic` when the target or its availability depends on
+the current session. Return `defineRemoteAgent(...)` to expose it and nil to
+omit it:
+
+```ts title="agent/subagents/weather.ts"
+import { defineDynamic, defineRemoteAgent } from "eve";
+
+export default defineDynamic({
+ events: {
+ "session.started": (_event, ctx) =>
+ ctx.session.auth.current?.attributes.region === "us"
+ ? defineRemoteAgent({
+ description: "Answers weather questions for US customers.",
+ url: "https://us-weather-agent.example.com",
+ })
+ : null,
+ },
+});
+```
+
+Dynamic remote subagents support `session.started` and `turn.started`. The
+returned definition may select different remote settings at either scope. eve
+resolves function-valued URLs when the event handler runs. Auth and headers
+remain lazy and resolve before each outbound request without entering durable
+workflow state.
+
+Author `auth` and `headers` directly in the `defineRemoteAgent({ ... })` object
+and keep their functions self-contained with module imports or environment
+variables. They are rehydrated outside the event handler, so they cannot close
+over `_event`, `ctx`, or handler-local values.
+
## Runtime URLs
A string `url` is read at compile time and frozen into the build. When the target comes from a runtime env var — known only once the deployment runs — pass a function instead. eve calls it when it resolves the agent graph at runtime, so it can read `process.env`:
diff --git a/e2e/fixtures/agent-subagents/agent/subagents/remote-loopback.ts b/e2e/fixtures/agent-subagents/agent/subagents/remote-loopback.ts
index 49ce3e624..e5c4f0af3 100644
--- a/e2e/fixtures/agent-subagents/agent/subagents/remote-loopback.ts
+++ b/e2e/fixtures/agent-subagents/agent/subagents/remote-loopback.ts
@@ -1,4 +1,4 @@
-import { defineRemoteAgent } from "eve";
+import { defineDynamic, defineRemoteAgent } from "eve";
/**
* A remote agent pointing back at this same deployment, so one fixture plays
@@ -10,24 +10,29 @@ import { defineRemoteAgent } from "eve";
* The URL resolves at runtime to the deployment's own address: `VERCEL_URL`
* on Vercel, or the dev server's self-published origin locally.
*/
-export default defineRemoteAgent({
- description:
- "Remote loopback agent. Call this only when the user explicitly asks to use the remote-loopback agent, passing the user's requested message through unchanged. Call it with only the `message` argument — never pass `outputSchema`.",
- url: () =>
- process.env.VERCEL_URL !== undefined && process.env.VERCEL_URL !== ""
- ? `https://${process.env.VERCEL_URL}`
- : (process.env.WORKFLOW_LOCAL_BASE_URL ?? "http://127.0.0.1:3000"),
- headers: () => {
- const headers: Record<string, string> = {
- authorization: "Bearer e2e-principal-forwarding-router",
- };
- // Preview deployments behind Vercel deployment protection need the
- // bypass header on the self-call; harmless when protection is off.
- const bypass = process.env.VERCEL_AUTOMATION_BYPASS_SECRET;
- if (bypass !== undefined && bypass !== "") {
- headers["x-vercel-protection-bypass"] = bypass;
- }
- return headers;
+export default defineDynamic({
+ events: {
+ "session.started": () =>
+ defineRemoteAgent({
+ description:
+ "Remote loopback agent. Call this only when the user explicitly asks to use the remote-loopback agent, passing the user's requested message through unchanged. Call it with only the `message` argument — never pass `outputSchema`.",
+ url: () =>
+ process.env.VERCEL_URL !== undefined && process.env.VERCEL_URL !== ""
+ ? `https://${process.env.VERCEL_URL}`
+ : (process.env.WORKFLOW_LOCAL_BASE_URL ?? "http://127.0.0.1:3000"),
+ headers: () => {
+ const headers: Record<string, string> = {
+ authorization: "Bearer e2e-principal-forwarding-router",
+ };
+ // Preview deployments behind Vercel deployment protection need the
+ // bypass header on the self-call; harmless when protection is off.
+ const bypass = process.env.VERCEL_AUTOMATION_BYPASS_SECRET;
+ if (bypass !== undefined && bypass !== "") {
+ headers["x-vercel-protection-bypass"] = bypass;
+ }
+ return headers;
+ },
+ forwardPrincipal: true,
+ }),
},
- forwardPrincipal: true,
});
diff --git a/e2e/fixtures/agent-subagents/evals/remote-principal-forwarding.eval.ts b/e2e/fixtures/agent-subagents/evals/remote-principal-forwarding.eval.ts
index 1bfac3979..1a74da5b0 100644
--- a/e2e/fixtures/agent-subagents/evals/remote-principal-forwarding.eval.ts
+++ b/e2e/fixtures/agent-subagents/evals/remote-principal-forwarding.eval.ts
@@ -2,8 +2,8 @@ import { defineEval } from "eve/evals";
/**
* Principal forwarding across a real remote-agent hop, end to end. The
- * fixture deployment plays both sides: `remote-loopback` is a
- * `defineRemoteAgent({ forwardPrincipal: true })` pointing back at this
+ * fixture deployment plays both sides: `remote-loopback` dynamically selects
+ * a `defineRemoteAgent({ forwardPrincipal: true })` pointing back at this
* deployment, whose authored eve channel trusts principals only from the
* hop's `router-app` bearer (`trustedForwarders`).
*
@@ -24,7 +24,7 @@ const FORWARDED_MARKER =
export default defineEval({
tags: ["real-model"],
description:
- "Remote-agent principal forwarding: the child session runs as the parent's end user, with the distinct initiator preserved and the forwarder stamped.",
+ "Dynamic remote-agent selection and principal forwarding: the child session runs as the parent's end user, with the distinct initiator preserved and the forwarder stamped.",
async test(t) {
await t.send("Reply with the single word: ready.");
diff --git a/packages/eve/src/compiler/normalize-subagent.ts b/packages/eve/src/compiler/normalize-subagent.ts
index 17a4fbb9e..7c7dc2eff 100644
--- a/packages/eve/src/compiler/normalize-subagent.ts
+++ b/packages/eve/src/compiler/normalize-subagent.ts
@@ -288,7 +288,7 @@ function normalizeDynamicSubagentDefinition(
const record = expectObjectRecord(value, message);
if (Object.hasOwn(record, "fallback")) {
throw new Error(
- `${message} Dynamic subagent definitions do not support "fallback". Return defineAgent(...) from an event handler instead.`,
+ `${message} Dynamic subagent definitions do not support "fallback". Return defineAgent(...) or defineRemoteAgent(...) from an event handler instead.`,
);
}
expectOnlyKnownKeys(record, ["events", "kind"], message);
diff --git a/packages/eve/src/context/dynamic-subagent-lifecycle.test.ts b/packages/eve/src/context/dynamic-subagent-lifecycle.test.ts
index b8e208404..5cf083991 100644
--- a/packages/eve/src/context/dynamic-subagent-lifecycle.test.ts
+++ b/packages/eve/src/context/dynamic-subagent-lifecycle.test.ts
@@ -9,6 +9,7 @@ import {
} from "#context/dynamic-subagent-lifecycle.js";
import { SessionDynamicSubagentRuntimeRevisionKey, SessionIdKey } from "#context/keys.js";
import { defineAgent } from "#public/definitions/agent.js";
+import { defineRemoteAgent } from "#public/definitions/remote-agent.js";
import { createSessionStartedEvent, createTurnStartedEvent } from "#protocol/message.js";
import type { ResolvedDynamicSubagentResolver } from "#runtime/subagents/registry.js";
@@ -115,9 +116,11 @@ describe("dynamic subagent lifecycle", () => {
messages: [],
resolvers: [resolver],
});
- expect(getDynamicSubagentSelection(ctx, resolver.nodeId)?.agentConfig.model.id).toBe(
- "anthropic/claude-sonnet-4.5",
- );
+ const sessionSelection = getDynamicSubagentSelection(ctx, resolver.nodeId);
+ expect(sessionSelection?.kind).toBe("subagent");
+ expect(
+ sessionSelection?.kind === "subagent" ? sessionSelection.agentConfig.model.id : null,
+ ).toBe("anthropic/claude-sonnet-4.5");
await dispatchDynamicSubagentEvent({
ctx,
@@ -125,12 +128,75 @@ describe("dynamic subagent lifecycle", () => {
messages: [],
resolvers: [resolver],
});
- expect(getDynamicSubagentSelection(ctx, resolver.nodeId)?.agentConfig).toMatchObject({
+ const turnSelection = getDynamicSubagentSelection(ctx, resolver.nodeId);
+ expect(turnSelection?.kind).toBe("subagent");
+ expect(turnSelection?.kind === "subagent" ? turnSelection.agentConfig : null).toMatchObject({
description: "Research the request deeply.",
model: { id: "anthropic/claude-opus-4.6" },
});
});
+ it("exposes a remote subagent with the returned remote config", async () => {
+ const ctx = createContext();
+ const created = createResolver();
+ const auth = vi.fn(async () => ({ headers: { authorization: "Bearer selected" } }));
+ const headers = vi.fn(async () => ({ "x-tenant": "acme" }));
+ const remoteAgent = defineRemoteAgent({
+ auth,
+ description: "Research on the remote deployment.",
+ forwardPrincipal: true,
+ headers,
+ outputSchema: { properties: { answer: { type: "string" } }, type: "object" },
+ url: async () => "https://research.example.com",
+ });
+ const credentialsFactory = Object.assign(
+ () => ({ auth: remoteAgent.auth, headers: remoteAgent.headers }),
+ { stepId: "eve:dynamic-remote-agent//researcher" },
+ );
+ Object.defineProperty(remoteAgent, "__eveResolveRemoteAgentCredentials", {
+ value: credentialsFactory,
+ });
+ const resolver: ResolvedDynamicSubagentResolver = {
+ ...created.resolver,
+ events: {
+ "session.started": () => remoteAgent,
+ },
+ };
+
+ await dispatchDynamicSubagentEvent({
+ ctx,
+ event: createSessionStartedEvent(),
+ messages: [],
+ resolvers: [resolver],
+ });
+
+ expect(buildDynamicSubagentTools(ctx)).toMatchObject([
+ {
+ description: "Research on the remote deployment.",
+ name: "researcher",
+ runtimeAction: {
+ kind: "remote-agent-call",
+ nodeId: "subagents/researcher",
+ remoteAgentName: "researcher",
+ },
+ },
+ ]);
+ expect(getDynamicSubagentSelection(ctx, resolver.nodeId)).toMatchObject({
+ kind: "remote",
+ remoteAgent: {
+ credentialsStepId: "eve:dynamic-remote-agent//researcher",
+ forwardPrincipal: true,
+ path: "/eve/v1/session",
+ url: "https://research.example.com",
+ },
+ });
+ expect(auth).not.toHaveBeenCalled();
+ expect(headers).not.toHaveBeenCalled();
+ expect(JSON.stringify(getDynamicSubagentSelection(ctx, resolver.nodeId))).not.toContain(
+ "Bearer selected",
+ );
+ });
+
it("omits an invalid non-null result", async () => {
const ctx = createContext();
const { resolver } = createResolver({
diff --git a/packages/eve/src/context/dynamic-subagent-lifecycle.ts b/packages/eve/src/context/dynamic-subagent-lifecycle.ts
index 6251f637c..9dd8767c1 100644
--- a/packages/eve/src/context/dynamic-subagent-lifecycle.ts
+++ b/packages/eve/src/context/dynamic-subagent-lifecycle.ts
@@ -16,6 +16,7 @@ import type { SessionStartedStreamEvent, UnstampedMessageStreamEvent } from "#pr
import type { ResolvedDynamicSubagentResolver } from "#runtime/subagents/registry.js";
import { createPreparedRuntimeSubagentTool } from "#runtime/subagents/registry.js";
import { normalizeDynamicSubagentAgentConfig } from "#runtime/subagents/dynamic-agent-config.js";
+import { normalizeDynamicRemoteAgentConfig } from "#runtime/subagents/dynamic-remote-agent-config.js";
import { toErrorMessage } from "#shared/errors.js";
const log = createLogger("dynamic-subagents");
@@ -40,13 +41,34 @@ async function resolveSelections(input: {
if (result === null || result === undefined) {
return [resolver.nodeId, null] as const;
}
+ if (isRemoteAgentDefinition(result)) {
+ const remoteAgent = await normalizeDynamicRemoteAgentConfig({
+ name: resolver.name,
+ value: result,
+ });
+ const prepared = createPreparedRuntimeSubagentTool({
+ description: remoteAgent.description,
+ kind: "remote",
+ logicalPath: resolver.logicalPath,
+ name: resolver.name,
+ nodeId: resolver.nodeId,
+ outputSchema: remoteAgent.outputSchema,
+ path: remoteAgent.path,
+ sourceId: resolver.sourceId,
+ sourceKind: resolver.sourceKind,
+ url: remoteAgent.url,
+ });
+
+ return [resolver.nodeId, { kind: "remote", prepared, remoteAgent }] as const;
+ }
+
const agentConfig = normalizeDynamicSubagentAgentConfig({
name: resolver.name,
value: result,
});
const prepared = createPreparedRuntimeSubagentTool({
description: agentConfig.description,
- kind: resolver.kind,
+ kind: "subagent",
logicalPath: resolver.logicalPath,
name: resolver.name,
nodeId: resolver.nodeId,
@@ -54,7 +76,7 @@ async function resolveSelections(input: {
sourceKind: resolver.sourceKind,
});
- return [resolver.nodeId, { agentConfig, prepared }] as const;
+ return [resolver.nodeId, { agentConfig, kind: "subagent", prepared }] as const;
}),
);
const selections: Record<string, DurableDynamicSubagentSelection> = {};
@@ -76,6 +98,14 @@ async function resolveSelections(input: {
return selections;
}
+function isRemoteAgentDefinition(value: unknown): boolean {
+ return (
+ typeof value === "object" &&
+ value !== null &&
+ (value as { readonly kind?: unknown }).kind === "remote"
+ );
+}
+
export async function dispatchDynamicSubagentEvent(input: {
readonly ctx: ContextContainer;
readonly event: UnstampedMessageStreamEvent;
diff --git a/packages/eve/src/context/keys.ts b/packages/eve/src/context/keys.ts
index 8723a2018..917c188bc 100644
--- a/packages/eve/src/context/keys.ts
+++ b/packages/eve/src/context/keys.ts
@@ -19,6 +19,7 @@ import type {
import { ContextKey } from "#context/key.js";
import type { HarnessToolDefinition } from "#harness/execute-tool.js";
import type { DynamicSubagentAgentConfig } from "#runtime/subagents/dynamic-agent-config.js";
+import type { DynamicRemoteAgentConfig } from "#runtime/subagents/dynamic-remote-agent-config.js";
import type { SandboxAccess } from "#sandbox/state.js";
import type { RunMode } from "#shared/run-mode.js";
import type { RuntimeModelReference } from "#runtime/agent/bootstrap.js";
@@ -167,10 +168,20 @@ export const TurnDynamicToolMetadataKey = new ContextKey<readonly DurableDynamic
*/
export const LiveStepToolsKey = new ContextKey<HarnessToolDefinition[]>("eve.liveStepTools");
-export type DurableDynamicSubagentSelection = {
- readonly agentConfig: DynamicSubagentAgentConfig;
- readonly prepared: PreparedRuntimeDelegationTool;
-} | null;
+export type DurableDynamicSubagentSelection =
+ | {
+ readonly agentConfig: DynamicSubagentAgentConfig;
+ readonly kind: "subagent";
+ readonly prepared: PreparedRuntimeDelegationTool;
+ readonly remoteAgent?: never;
+ }
+ | {
+ readonly agentConfig?: never;
+ readonly kind: "remote";
+ readonly prepared: PreparedRuntimeDelegationTool;
+ readonly remoteAgent: DynamicRemoteAgentConfig;
+ }
+ | null;
export const SessionDynamicSubagentSelectionsKey = new ContextKey<
Readonly<Record<string, DurableDynamicSubagentSelection>>
diff --git a/packages/eve/src/execution/cancel-descendant-turns-step.test.ts b/packages/eve/src/execution/cancel-descendant-turns-step.test.ts
index 9dbe9ac62..2c409f68b 100644
--- a/packages/eve/src/execution/cancel-descendant-turns-step.test.ts
+++ b/packages/eve/src/execution/cancel-descendant-turns-step.test.ts
@@ -79,6 +79,7 @@ describe("cancelDescendantTurnsStep", () => {
sessionId: "local-child",
});
expect(resolveRemoteAgentForAction).toHaveBeenCalledWith({
+ dynamicRemoteAgent: undefined,
nodeId: remoteAction.nodeId,
registry: expect.any(Map),
remoteAgentName: remoteAction.remoteAgentName,
@@ -103,6 +104,35 @@ describe("cancelDescendantTurnsStep", () => {
expect(deserializeContext).not.toHaveBeenCalled();
});
+ it("uses the selected dynamic remote config when cancelling", async () => {
+ const dynamicRemoteAgent = {
+ description: "Selected remote.",
+ path: "/eve/v1/session",
+ url: "https://selected.example.com",
+ };
+ installRemoteRegistry({
+ agentConfig: undefined,
+ kind: "remote",
+ prepared: {} as never,
+ remoteAgent: dynamicRemoteAgent,
+ });
+ vi.mocked(resolveRemoteAgentForAction).mockReturnValue(remote);
+ vi.mocked(requestWorkflowTurnCancellation).mockResolvedValue({ status: "accepted" });
+ vi.mocked(cancelRemoteAgentTurn).mockResolvedValue({ status: "accepted" });
+
+ await cancelDescendantTurnsStep({
+ serializedContext: {},
+ sessionState: createPendingState(),
+ });
+
+ expect(resolveRemoteAgentForAction).toHaveBeenCalledWith({
+ dynamicRemoteAgent,
+ nodeId: remoteAction.nodeId,
+ registry: expect.any(Map),
+ remoteAgentName: remoteAction.remoteAgentName,
+ });
+ });
+
it("retries no-active-turn responses during the child adoption window", async () => {
vi.useFakeTimers();
installRemoteRegistry();
@@ -206,8 +236,9 @@ describe("cancelDescendantTurnsStep", () => {
});
});
-function installRemoteRegistry(): void {
+function installRemoteRegistry(selection?: unknown): void {
vi.mocked(deserializeContext).mockResolvedValue({
+ get: vi.fn(() => (selection === undefined ? undefined : { [remoteAction.nodeId]: selection })),
require: vi.fn(() => ({
subagentRegistry: { subagentsByNodeId: new Map([[remoteAction.nodeId, remote]]) },
})),
diff --git a/packages/eve/src/execution/cancel-descendant-turns-step.ts b/packages/eve/src/execution/cancel-descendant-turns-step.ts
index 9924b7173..365648d08 100644
--- a/packages/eve/src/execution/cancel-descendant-turns-step.ts
+++ b/packages/eve/src/execution/cancel-descendant-turns-step.ts
@@ -15,6 +15,8 @@ import type {
RuntimeSubagentCallActionRequest,
} from "#runtime/actions/types.js";
import type { RuntimeSubagentRegistry } from "#runtime/subagents/registry.js";
+import { getDynamicSubagentSelection } from "#context/dynamic-subagent-lifecycle.js";
+import type { ContextContainer } from "#context/container.js";
// Retry through transient world contention (queue wakes, hook-claim
// conflicts), then log loudly: a silently dropped cancel leaves the child
@@ -57,11 +59,17 @@ export async function cancelDescendantTurnsStep(input: {
return;
}
- let remoteRegistry: Promise<RuntimeSubagentRegistry["subagentsByNodeId"]> | undefined;
- const getRemoteRegistry = () =>
- (remoteRegistry ??= deserializeContext(input.serializedContext).then(
- (ctx) => ctx.require(BundleKey).subagentRegistry.subagentsByNodeId,
- ));
+ let remoteContext:
+ | Promise<{
+ readonly ctx: ContextContainer;
+ readonly registry: RuntimeSubagentRegistry["subagentsByNodeId"];
+ }>
+ | undefined;
+ const getRemoteContext = () =>
+ (remoteContext ??= deserializeContext(input.serializedContext).then((ctx) => ({
+ ctx,
+ registry: ctx.require(BundleKey).subagentRegistry.subagentsByNodeId,
+ })));
const cancellations = batch.actions.flatMap((action): Promise<void>[] => {
const childSessionId = childSessionIds[action.callId];
@@ -75,7 +83,7 @@ export async function cancelDescendantTurnsStep(input: {
cancelRemoteDescendant({
action,
childSessionId,
- remoteRegistry: getRemoteRegistry(),
+ remoteContext: getRemoteContext(),
}),
];
}
@@ -115,11 +123,16 @@ async function cancelLocalDescendant(input: {
async function cancelRemoteDescendant(input: {
readonly action: RuntimeRemoteAgentCallActionRequest;
readonly childSessionId: string;
- readonly remoteRegistry: Promise<RuntimeSubagentRegistry["subagentsByNodeId"]>;
+ readonly remoteContext: Promise<{
+ readonly ctx: ContextContainer;
+ readonly registry: RuntimeSubagentRegistry["subagentsByNodeId"];
+ }>;
}): Promise<void> {
try {
- const registry = await input.remoteRegistry;
- const remote = resolveRemoteAgentForAction({
+ const { ctx, registry } = await input.remoteContext;
+ const selection = getDynamicSubagentSelection(ctx, input.action.nodeId);
+ const remote = await resolveRemoteAgentForAction({
+ dynamicRemoteAgent: selection?.kind === "remote" ? selection.remoteAgent : undefined,
nodeId: input.action.nodeId,
remoteAgentName: input.action.remoteAgentName,
registry,
diff --git a/packages/eve/src/execution/dispatch-runtime-actions-step.ts b/packages/eve/src/execution/dispatch-runtime-actions-step.ts
index 06493bccc..42ccbaedf 100644
--- a/packages/eve/src/execution/dispatch-runtime-actions-step.ts
+++ b/packages/eve/src/execution/dispatch-runtime-actions-step.ts
@@ -107,7 +107,7 @@ export async function dispatchRuntimeActionsStep(input: {
try {
for (const action of batch.actions) {
const isDynamicSubagent =
- action.kind === "subagent-call" &&
+ (action.kind === "subagent-call" || action.kind === "remote-agent-call") &&
bundle.subagentRegistry.dynamicNodeIds?.has(action.nodeId) === true;
const dynamicSubagentSelection = isDynamicSubagent
? getDynamicSubagentSelection(ctx, action.nodeId)
@@ -126,7 +126,12 @@ export async function dispatchRuntimeActionsStep(input: {
continue;
}
- if (isDynamicSubagent && dynamicSubagentSelection === undefined) {
+ if (
+ isDynamicSubagent &&
+ (dynamicSubagentSelection === undefined ||
+ (action.kind === "subagent-call" && dynamicSubagentSelection.kind !== "subagent") ||
+ (action.kind === "remote-agent-call" && dynamicSubagentSelection.kind !== "remote"))
+ ) {
const subagentName = getSubagentName(action);
log.warn("dynamic subagent call blocked after availability changed", {
callId: action.callId,
@@ -144,9 +149,13 @@ export async function dispatchRuntimeActionsStep(input: {
switch (action.kind) {
case "subagent-call": {
+ const dynamicAgentConfig =
+ dynamicSubagentSelection?.kind === "subagent"
+ ? dynamicSubagentSelection.agentConfig
+ : undefined;
const registered = bundle.subagentRegistry.subagentsByNodeId.get(action.nodeId);
const description =
- dynamicSubagentSelection?.agentConfig.description ??
+ dynamicAgentConfig?.description ??
(registered?.definition.kind === "subagent"
? registered.definition.description
: undefined);
@@ -154,7 +163,7 @@ export async function dispatchRuntimeActionsStep(input: {
description !== undefined ? { description, type: "local" } : { type: "runtime" };
const childRuntime = createWorkflowRuntime({
compiledArtifactsSource: bundle.compiledArtifactsSource,
- dynamicSubagentAgentConfig: dynamicSubagentSelection?.agentConfig,
+ dynamicSubagentAgentConfig: dynamicAgentConfig,
nodeId: action.nodeId,
});
const { childContinuationToken, runInput } = buildSubagentRunInput({
@@ -208,7 +217,11 @@ export async function dispatchRuntimeActionsStep(input: {
case "remote-agent-call": {
let resolvedRemote;
try {
- resolvedRemote = resolveRemoteAgentForAction({
+ resolvedRemote = await resolveRemoteAgentForAction({
+ dynamicRemoteAgent:
+ dynamicSubagentSelection?.kind === "remote"
+ ? dynamicSubagentSelection.remoteAgent
+ : undefined,
nodeId: action.nodeId,
remoteAgentName: action.remoteAgentName,
registry: bundle.subagentRegistry.subagentsByNodeId,
diff --git a/packages/eve/src/execution/remote-agent-dispatch.test.ts b/packages/eve/src/execution/remote-agent-dispatch.test.ts
index 3e55ba6dd..2f2786df9 100644
--- a/packages/eve/src/execution/remote-agent-dispatch.test.ts
+++ b/packages/eve/src/execution/remote-agent-dispatch.test.ts
@@ -4,11 +4,70 @@ import type { SessionAuthContext } from "#channel/types.js";
import {
cancelRemoteAgentTurn,
isRetryableRemoteAgentCancelError,
+ resolveRemoteAgentForAction,
startRemoteAgentSession,
} from "#execution/remote-agent-dispatch.js";
import type { RuntimeRemoteAgentCallActionRequest } from "#runtime/actions/types.js";
import type { ResolvedRuntimeRemoteAgentNode } from "#runtime/types.js";
+describe("resolveRemoteAgentForAction", () => {
+ it("overlays a selected dynamic remote config on the compiled delegation node", async () => {
+ const definition = {
+ dynamic: {
+ eventNames: ["session.started"],
+ events: { "session.started": () => null },
+ logicalPath: "subagents/research.ts",
+ sourceId: "subagents/research.ts",
+ sourceKind: "module",
+ },
+ kind: "subagent",
+ logicalPath: "subagents/research.ts",
+ name: "research",
+ nodeId: "subagents/research.ts",
+ sourceId: "subagents/research.ts",
+ sourceKind: "module",
+ } as const;
+
+ const credentialsStepId = "eve:dynamic-remote-agent//selected-research";
+ const registryKey = Symbol.for("@workflow/core//registeredSteps");
+ const globalRecord = globalThis as Record<symbol, Map<string, Function> | undefined>;
+ const stepRegistry = globalRecord[registryKey] ?? new Map<string, Function>();
+ globalRecord[registryKey] = stepRegistry;
+ stepRegistry.set(credentialsStepId, () => ({
+ auth: async () => ({ headers: { authorization: "Bearer selected" } }),
+ headers: { "x-selected": "yes" },
+ }));
+
+ const resolved = await resolveRemoteAgentForAction({
+ dynamicRemoteAgent: {
+ credentialsStepId,
+ description: "Selected remote research.",
+ path: "/custom/session",
+ url: "https://selected.example.com",
+ },
+ nodeId: definition.nodeId,
+ registry: new Map([[definition.nodeId, { definition }]]),
+ remoteAgentName: "research",
+ });
+
+ expect(resolved).toMatchObject({
+ description: "Selected remote research.",
+ headers: { "x-selected": "yes" },
+ kind: "remote",
+ logicalPath: "subagents/research.ts",
+ name: "research",
+ nodeId: "subagents/research.ts",
+ path: "/custom/session",
+ sourceId: "subagents/research.ts",
+ sourceKind: "module",
+ url: "https://selected.example.com",
+ });
+ await expect(resolved.auth?.()).resolves.toEqual({
+ headers: { authorization: "Bearer selected" },
+ });
+ });
+});
+
describe("startRemoteAgentSession", () => {
afterEach(() => {
vi.unstubAllGlobals();
diff --git a/packages/eve/src/execution/remote-agent-dispatch.ts b/packages/eve/src/execution/remote-agent-dispatch.ts
index 219b35e2a..95f4be150 100644
--- a/packages/eve/src/execution/remote-agent-dispatch.ts
+++ b/packages/eve/src/execution/remote-agent-dispatch.ts
@@ -3,6 +3,7 @@ import { CancelTurnResponseSchema } from "#protocol/cancel-turn.js";
import { createEveCallbackRoutePath, createEveCancelTurnRoutePath } from "#protocol/routes.js";
import type { CancelTurnResult, SessionAuthContext } from "#channel/types.js";
import type { ForwardedPrincipal } from "#channel/forwarded-principal.js";
+import type { HeadersValue } from "#client/types.js";
import { createWorkflowCallbackUrl } from "#execution/workflow-callback-url.js";
import {
formatSubagentInput,
@@ -11,7 +12,9 @@ import {
import type { HarnessSession } from "#harness/types.js";
import type { RuntimeRemoteAgentCallActionRequest } from "#runtime/actions/types.js";
import type { RuntimeSubagentRegistry } from "#runtime/subagents/registry.js";
+import type { DynamicRemoteAgentConfig } from "#runtime/subagents/dynamic-remote-agent-config.js";
import type { ResolvedRuntimeRemoteAgentNode } from "#runtime/types.js";
+import { expectFunction, expectObjectRecord } from "#internal/authored-module.js";
class RemoteAgentCancelRequestError extends Error {
readonly retryable: boolean;
@@ -172,19 +175,114 @@ export function isRetryableRemoteAgentCancelError(error: unknown): boolean {
return !(error instanceof RemoteAgentCancelRequestError) || error.retryable;
}
-export function resolveRemoteAgentForAction(input: {
+export async function resolveRemoteAgentForAction(input: {
+ readonly dynamicRemoteAgent?: DynamicRemoteAgentConfig;
readonly nodeId: string;
readonly registry: RuntimeSubagentRegistry["subagentsByNodeId"];
readonly remoteAgentName: string;
-}): ResolvedRuntimeRemoteAgentNode {
+}): Promise<ResolvedRuntimeRemoteAgentNode> {
const registered = input.registry.get(input.nodeId);
const definition = registered?.definition;
+ if (input.dynamicRemoteAgent !== undefined) {
+ if (definition === undefined) {
+ throw new Error(`Missing remote agent "${input.remoteAgentName}" in runtime registry.`);
+ }
+ const credentials = resolveDynamicRemoteAgentCredentials(input.dynamicRemoteAgent);
+ const config = input.dynamicRemoteAgent;
+ const remote: {
+ auth?: ResolvedRuntimeRemoteAgentNode["auth"];
+ description: string;
+ forwardPrincipal?: boolean;
+ headers?: HeadersValue;
+ kind: "remote";
+ logicalPath: string;
+ name: string;
+ nodeId: string;
+ outputSchema?: ResolvedRuntimeRemoteAgentNode["outputSchema"];
+ path: string;
+ sourceId: string;
+ sourceKind: "module";
+ url: string;
+ } = {
+ description: config.description,
+ kind: "remote",
+ logicalPath: definition.logicalPath,
+ name: input.remoteAgentName,
+ nodeId: input.nodeId,
+ outputSchema: config.outputSchema,
+ path: config.path,
+ sourceId: definition.sourceId,
+ sourceKind: "module",
+ url: config.url,
+ };
+ if (config.forwardPrincipal !== undefined) {
+ remote.forwardPrincipal = config.forwardPrincipal;
+ }
+ if (credentials.auth !== undefined) {
+ remote.auth = credentials.auth;
+ }
+ if (credentials.headers !== undefined) {
+ remote.headers = credentials.headers;
+ }
+ return remote;
+ }
if (definition?.kind !== "remote") {
throw new Error(`Missing remote agent "${input.remoteAgentName}" in runtime registry.`);
}
return definition;
}
+function resolveDynamicRemoteAgentCredentials(config: DynamicRemoteAgentConfig): {
+ readonly auth?: ResolvedRuntimeRemoteAgentNode["auth"];
+ readonly headers?: HeadersValue;
+} {
+ if (config.credentialsStepId === undefined) {
+ return {};
+ }
+ const factory = getStepRegistry().get(config.credentialsStepId);
+ if (factory === undefined) {
+ throw new Error(
+ `Dynamic remote subagent credentials function "${config.credentialsStepId}" is not registered.`,
+ );
+ }
+ const record = expectObjectRecord(factory(), "Dynamic remote subagent credentials are invalid.");
+ const credentials: {
+ auth?: ResolvedRuntimeRemoteAgentNode["auth"];
+ headers?: HeadersValue;
+ } = {};
+ if (record.auth !== undefined) {
+ credentials.auth = expectFunction(record.auth, "Dynamic remote subagent auth is invalid.");
+ }
+ if (record.headers !== undefined) {
+ credentials.headers = resolveDynamicRemoteAgentHeaders(record.headers);
+ }
+ return credentials;
+}
+
+function resolveDynamicRemoteAgentHeaders(value: unknown): HeadersValue {
+ if (typeof value === "function") {
+ return value as Exclude<HeadersValue, Readonly<Record<string, string>>>;
+ }
+ const record = expectObjectRecord(value, "Dynamic remote subagent headers are invalid.");
+ for (const headerValue of Object.values(record)) {
+ if (typeof headerValue !== "string") {
+ throw new Error("Dynamic remote subagent headers are invalid.");
+ }
+ }
+ return record as Readonly<Record<string, string>>;
+}
+
+function getStepRegistry(): Map<string, Function> {
+ const key = Symbol.for("@workflow/core//registeredSteps");
+ const global = globalThis as Record<symbol, Map<string, Function> | undefined>;
+ let registry = global[key];
+ if (registry === undefined) {
+ registry = new Map();
+ global[key] = registry;
+ }
+ return registry;
+}
+
function createRemoteAgentSessionUrl(remote: ResolvedRuntimeRemoteAgentNode): string {
return createRemoteAgentRouteUrl(remote.url, remote.path);
}
diff --git a/packages/eve/src/execution/workflow-steps.test.ts b/packages/eve/src/execution/workflow-steps.test.ts
index c6d42b6d4..138d3dbfa 100644
--- a/packages/eve/src/execution/workflow-steps.test.ts
+++ b/packages/eve/src/execution/workflow-steps.test.ts
@@ -9,6 +9,7 @@ import {
ContinuationTokenKey,
DynamicSubagentAgentConfigKey,
ModeKey,
+ SessionDynamicSubagentSelectionsKey,
SessionDynamicToolMetadataKey,
SessionDynamicToolRuntimeRevisionKey,
SessionIdKey,
@@ -659,6 +660,119 @@ describe("dispatchRuntimeActionsStep", () => {
);
});
+ it("starts a remote agent from the current dynamic selection", async () => {
+ const nodeId = "subagents/research";
+ const compiledBundle = {
+ adapterRegistry: {
+ adaptersByKind: new Map([[threadContextAdapter.kind, threadContextAdapter]]),
+ },
+ compiledArtifactsSource: {},
+ graph: {
+ nodesByNodeId: new Map(),
+ root: {
+ sandboxRegistry: { sandbox: null },
+ turnAgent: TestTurnAgent,
+ },
+ },
+ hookRegistry: createEmptyHookRegistry(),
+ resolvedAgent: { config: {} },
+ subagentRegistry: {
+ dynamicNodeIds: new Set([nodeId]),
+ subagentsByNodeId: new Map([
+ [
+ nodeId,
+ {
+ definition: {
+ kind: "subagent",
+ logicalPath: "subagents/research.ts",
+ name: "research",
+ nodeId,
+ sourceId: "subagents/research.ts",
+ sourceKind: "module",
+ },
+ },
+ ],
+ ]),
+ },
+ toolRegistry: {},
+ turnAgent: TestTurnAgent,
+ } as never;
+ vi.mocked(getCompiledRuntimeAgentBundle).mockResolvedValue(compiledBundle);
+ const credentialsStepId = "eve:dynamic-remote-agent//workflow-research";
+ const registryKey = Symbol.for("@workflow/core//registeredSteps");
+ const globalRecord = globalThis as Record<symbol, Map<string, Function> | undefined>;
+ const stepRegistry = globalRecord[registryKey] ?? new Map<string, Function>();
+ globalRecord[registryKey] = stepRegistry;
+ stepRegistry.set(credentialsStepId, () => ({
+ headers: { authorization: "Bearer selected" },
+ }));
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValue(
+ Response.json(
+ { sessionId: "dynamic-remote-child" },
+ { headers: { "x-eve-session-id": "dynamic-remote-child" }, status: 202 },
+ ),
+ );
+ vi.stubGlobal("fetch", fetchMock);
+
+ const session = setPendingRuntimeActionBatch({
+ actions: [
+ {
+ callId: "call-dynamic-remote",
+ description: "Delegate the work.",
+ input: { message: "investigate latest routing" },
+ kind: "remote-agent-call",
+ name: "research",
+ nodeId,
+ remoteAgentName: "research",
+ },
+ ],
+ event: { sequence: 0, stepIndex: 0, turnId: "turn_0" },
+ responseMessages: [],
+ session: createStubSession({
+ continuationToken: "http:parent",
+ sessionId: "parent-session",
+ }),
+ });
+ installSessionStoreMocks([session]);
+ const serializedContext = createSerializedContext();
+ serializedContext[SessionDynamicSubagentSelectionsKey.name] = {
+ [nodeId]: {
+ kind: "remote",
+ prepared: {},
+ remoteAgent: {
+ credentialsStepId,
+ description: "Selected remote research.",
+ path: "/custom/session",
+ url: "https://selected.example.com",
+ },
+ },
+ };
+
+ const result = await dispatchRuntimeActionsStep({
+ callbackBaseUrl: "https://caller.example.com",
+ parentContinuationToken: "turn-inbox",
+ parentWritable: createTestWritable(),
+ serializedContext,
+ sessionState: createStubSessionState({
+ continuationToken: "http:parent",
+ sessionId: "parent-session",
+ }),
+ });
+
+ expect(result.results).toEqual([]);
+ expect(fetchMock).toHaveBeenCalledWith(
+ "https://selected.example.com/custom/session",
+ expect.objectContaining({
+ headers: {
+ authorization: "Bearer selected",
+ "content-type": "application/json",
+ },
+ }),
+ );
+ });
+
it("blocks a stale recursive agent call from a delegated session", async () => {
const compiledBundle = {
adapterRegistry: {
diff --git a/packages/eve/src/harness/tool-loop.test.ts b/packages/eve/src/harness/tool-loop.test.ts
index a6dd48996..63e315d7d 100644
--- a/packages/eve/src/harness/tool-loop.test.ts
+++ b/packages/eve/src/harness/tool-loop.test.ts
@@ -966,6 +966,7 @@ describe("createToolLoopHarness", () => {
description: "Research the request.",
model: { id: "openai/gpt-5.5" },
},
+ kind: "subagent",
prepared: {
description: "Research the request.",
inputSchema: { type: "object" },
diff --git a/packages/eve/src/internal/authored-module-loader.ts b/packages/eve/src/internal/authored-module-loader.ts
index 7bd85af55..2274216fe 100644
--- a/packages/eve/src/internal/authored-module-loader.ts
+++ b/packages/eve/src/internal/authored-module-loader.ts
@@ -30,6 +30,7 @@ import {
buildWithNitroRolldown,
} from "#internal/bundler/nitro-rolldown.js";
import { createNodeEsmCompatBannerPlugin } from "#internal/node-esm-compat-banner.js";
+import { createDynamicCapabilityTransformPlugin } from "#internal/workflow-bundle/dynamic-capability-transform-plugin.js";
const AUTHORED_BUNDLED_MODULE_EXTENSION = /\.[cm]?[jt]sx?$/;
const AUTHORED_MODULE_BUNDLE_DIRECTORY_PATH = join(
@@ -278,6 +279,7 @@ export async function bundleAuthoredModuleMapForGeneration(input: {
id: input.moduleMapPath,
source: moduleMapSource,
}),
+ createDynamicCapabilityTransformPlugin({ dynamicTools: false }),
createAuthoredDirectiveGuardPlugin(),
extensionScopePlugin,
createAuthoredRelativeExtensionResolverPlugin({ extensions: RESOLVE_EXTENSIONS }),
diff --git a/packages/eve/src/internal/nitro/dev-generation-artifacts.scenario.test.ts b/packages/eve/src/internal/nitro/dev-generation-artifacts.scenario.test.ts
index 618749044..893c4e438 100644
--- a/packages/eve/src/internal/nitro/dev-generation-artifacts.scenario.test.ts
+++ b/packages/eve/src/internal/nitro/dev-generation-artifacts.scenario.test.ts
@@ -82,6 +82,65 @@ describe("development generation artifacts", () => {
expect(subagentTool.default.execute()).toBe(sharedMarker);
});
+ it("materializes dynamic remote credential metadata for the development runtime", async () => {
+ const app = await scenarioApp({
+ files: {
+ "agent/agent.mjs": 'export default { model: "openai/gpt-5.4" };\n',
+ "agent/instructions.md": "Use the available tools.",
+ "agent/subagents/remote.mjs": [
+ 'const defineDynamic = (definition) => ({ ...definition, kind: "eve:dynamic" });',
+ "const defineRemoteAgent = (definition) => ({",
+ " ...definition,",
+ ' kind: "remote",',
+ ' path: "/eve/v1/session",',
+ "});",
+ "export default defineDynamic({",
+ " events: {",
+ ' "session.started": () =>',
+ " defineRemoteAgent({",
+ ' description: "Remote research.",',
+ ' headers: () => ({ authorization: "Bearer fresh" }),',
+ ' url: "https://research.example.com",',
+ " }),",
+ " },",
+ "});",
+ "",
+ ].join("\n"),
+ },
+ name: "dynamic-remote-development-generation",
+ });
+
+ const compileResult = await compileAgent({ startPath: app.appRoot });
+ const snapshot = await stageDevelopmentGeneration(compileResult);
+ const moduleMap = await loadCompiledModuleMapFromAuthoredSource({
+ compiledArtifactsSource: createAuthoredSourceRuntimeCompiledArtifactsSource(
+ snapshot.runtimeAppRoot,
+ ),
+ });
+ const subagent = compileResult.manifest.subagents[0];
+ const sourceId = subagent?.agent.config.source?.sourceId;
+ expect(sourceId).toBeDefined();
+ const moduleNamespace = moduleMap.nodes[subagent!.nodeId]?.modules[sourceId!] as {
+ default: { events: Record<string, Function> };
+ };
+ const handler = moduleNamespace.default.events["session.started"];
+ expect(handler).toBeDefined();
+ const remote = handler!() as Record<string, unknown>;
+ const credentialsFactory = remote.__eveResolveRemoteAgentCredentials as {
+ stepId?: string;
+ };
+
+ expect(Object.keys(remote)).not.toContain("__eveResolveRemoteAgentCredentials");
+ expect(credentialsFactory.stepId).toMatch(/^eve:dynamic-remote-agent\/\//);
+ const registry = (globalThis as Record<symbol, Map<string, Function> | undefined>)[
+ Symbol.for("@workflow/core//registeredSteps")
+ ];
+ const registered = registry?.get(credentialsFactory.stepId!);
+ expect(registered).toBeDefined();
+ const credentials = registered!() as { headers(): Record<string, string> };
+ expect(credentials.headers()).toEqual({ authorization: "Bearer fresh" });
+ });
+
it("preserves extension scope in a shared generation graph", async () => {
const packageName = "@acme/shared-graph-extension";
const app = await scenarioApp({
diff --git a/packages/eve/src/internal/nitro/host/create-application-nitro.ts b/packages/eve/src/internal/nitro/host/create-application-nitro.ts
index 89e78ca19..aad689d31 100644
--- a/packages/eve/src/internal/nitro/host/create-application-nitro.ts
+++ b/packages/eve/src/internal/nitro/host/create-application-nitro.ts
@@ -36,7 +36,7 @@ import type {
} from "#internal/nitro/host/types.js";
import { createEveVercelOptions } from "#internal/nitro/host/vercel-build-output-config.js";
import { applyWorkflowTransform } from "#internal/workflow-bundle/workflow-builders.js";
-import { transformDynamicToolExecute } from "#internal/workflow-bundle/dynamic-tool-transform.js";
+import { createDynamicCapabilityTransformPlugin } from "#internal/workflow-bundle/dynamic-capability-transform-plugin.js";
import type { CompiledAgentManifest } from "#compiler/manifest.js";
/**
@@ -503,26 +503,12 @@ function addNitroStepTransformPlugin(
return clearCachedStepTransformTargets;
}
-/**
- * Adds the dynamic tool transform plugin that hoists execute functions
- * from defineDynamic event handlers to module scope. Runs
- * unconditionally for all tool files regardless of workflow mode.
- */
-function addDynamicToolTransformPlugin(nitro: Nitro): void {
+function addDynamicCapabilityTransformPlugin(nitro: Nitro): void {
nitro.hooks.hook("rollup:before", (_nitro, config) => {
if (!Array.isArray(config.plugins)) {
return;
}
-
- config.plugins.unshift({
- async transform(code: string, id: string) {
- if (!id.includes("/tools/")) return null;
- const result = await transformDynamicToolExecute(id, code);
- if (result === null) return null;
- return { code: result.code, map: null };
- },
- name: "eve:dynamic-tool-transform",
- });
+ config.plugins.unshift(createDynamicCapabilityTransformPlugin());
});
}
@@ -688,7 +674,7 @@ function configureSharedApplicationNitro(
addWorkflowModuleSideEffectsPlugin(nitro, preparedHost.workflowBuildDir);
patchWorkflowTransformExcludePath(nitro, preparedHost.workflowBuildDir);
- addDynamicToolTransformPlugin(nitro);
+ addDynamicCapabilityTransformPlugin(nitro);
if (preparedHost.compiledArtifacts.instrumentationSourcePath !== undefined) {
addInstrumentationModuleSideEffectsPlugin(
diff --git a/packages/eve/src/internal/workflow-bundle/dynamic-capability-transform-plugin.ts b/packages/eve/src/internal/workflow-bundle/dynamic-capability-transform-plugin.ts
new file mode 100644
index 000000000..03ca5f81f
--- /dev/null
+++ b/packages/eve/src/internal/workflow-bundle/dynamic-capability-transform-plugin.ts
@@ -0,0 +1,42 @@
+import { transformDynamicRemoteAgentCredentials } from "#internal/workflow-bundle/dynamic-remote-agent-transform.js";
+import { transformDynamicToolExecute } from "#internal/workflow-bundle/dynamic-tool-transform.js";
+
+export function createDynamicCapabilityTransformPlugin(
+ options: {
+ readonly dynamicRemoteAgents?: boolean;
+ readonly dynamicTools?: boolean;
+ } = {},
+) {
+ return {
+ async transform(code: string, id: string) {
+ const normalizedId = id.replaceAll("\\", "/");
+ const transformDynamicTools =
+ options.dynamicTools !== false && normalizedId.includes("/tools/");
+ const transformDynamicRemoteAgents =
+ options.dynamicRemoteAgents !== false && normalizedId.includes("/subagents/");
+ if (!transformDynamicTools && !transformDynamicRemoteAgents) {
+ return null;
+ }
+
+ let transformed = code;
+ let changed = false;
+ if (transformDynamicTools) {
+ const result = await transformDynamicToolExecute(id, transformed);
+ if (result !== null) {
+ transformed = result.code;
+ changed = true;
+ }
+ }
+ if (transformDynamicRemoteAgents) {
+ const result = await transformDynamicRemoteAgentCredentials(id, transformed);
+ if (result !== null) {
+ transformed = result.code;
+ changed = true;
+ }
+ }
+
+ return changed ? { code: transformed, map: null } : null;
+ },
+ name: "eve:dynamic-capability-transform",
+ };
+}
diff --git a/packages/eve/src/internal/workflow-bundle/dynamic-remote-agent-transform.test.ts b/packages/eve/src/internal/workflow-bundle/dynamic-remote-agent-transform.test.ts
new file mode 100644
index 000000000..5d4635901
--- /dev/null
+++ b/packages/eve/src/internal/workflow-bundle/dynamic-remote-agent-transform.test.ts
@@ -0,0 +1,142 @@
+import { beforeEach, describe, expect, it } from "vitest";
+
+import { transformDynamicRemoteAgentCredentials } from "./dynamic-remote-agent-transform.js";
+
+beforeEach(() => {
+ const key = Symbol.for("@workflow/core//registeredSteps");
+ const registry = (globalThis as Record<symbol, Map<string, Function> | undefined>)[key];
+ registry?.clear();
+});
+
+async function transformSource(source: string): Promise<string> {
+ const result = await transformDynamicRemoteAgentCredentials("subagents/research.ts", source);
+ if (result === null) throw new Error("Transform returned null");
+ return result.code;
+}
+
+function evaluateSessionHandler(code: string): Function {
+ const executable = code
+ .replace(/import\s+[^;]+;/g, "")
+ .replace(/export\s+default\s+/g, "var __exported = ");
+ let handler: Function | undefined;
+ const defineDynamic = (definition: { events: Record<string, Function> }) => {
+ handler = definition.events["session.started"];
+ return definition;
+ };
+ const defineRemoteAgent = (definition: Record<string, unknown>) => ({
+ ...definition,
+ kind: "remote",
+ path: "/eve/v1/session",
+ });
+ const evaluate = new Function(
+ "defineDynamic",
+ "defineRemoteAgent",
+ `${executable}\nreturn __exported;`,
+ );
+ evaluate(defineDynamic, defineRemoteAgent);
+ if (handler === undefined) throw new Error("No handler captured");
+ return handler;
+}
+
+describe("transformDynamicRemoteAgentCredentials", () => {
+ it("registers remote auth and headers without making them enumerable", async () => {
+ const source = `
+import { defineDynamic, defineRemoteAgent } from "eve";
+
+function createAuth() {
+ return async () => ({ headers: { authorization: "Bearer fresh" } });
+}
+
+export default defineDynamic({
+ events: {
+ "session.started": () =>
+ defineRemoteAgent({
+ auth: createAuth(),
+ description: "Remote research.",
+ headers: () => ({ "x-runtime": "fresh" }),
+ url: "https://research.example.com",
+ }),
+ },
+});
+`;
+ const handler = evaluateSessionHandler(await transformSource(source));
+ const remote = handler() as Record<string, unknown>;
+ const credentialsFactory = remote.__eveResolveRemoteAgentCredentials as {
+ stepId?: string;
+ };
+ expect(Object.keys(remote)).not.toContain("__eveResolveRemoteAgentCredentials");
+ expect(credentialsFactory.stepId).toMatch(/^eve:dynamic-remote-agent\/\//);
+ const key = Symbol.for("@workflow/core//registeredSteps");
+ const registry = (globalThis as Record<symbol, Map<string, Function> | undefined>)[key];
+ if (registry === undefined) throw new Error("Step registry was not created");
+ const registered = registry.get(credentialsFactory.stepId!);
+ expect(registered).toBeDefined();
+ const credentials = registered!() as Record<string, Function>;
+ await expect(credentials.auth!()).resolves.toEqual({
+ headers: { authorization: "Bearer fresh" },
+ });
+ expect(await credentials.headers!()).toEqual({ "x-runtime": "fresh" });
+ });
+
+ it("transforms remote definitions inside conditional expressions", async () => {
+ const source = `
+import { defineDynamic, defineRemoteAgent } from "eve";
+
+const enabled = true;
+export default defineDynamic({
+ events: {
+ "session.started": () =>
+ enabled
+ ? defineRemoteAgent({
+ description: "Remote research.",
+ headers: () => ({ "x-runtime": "fresh" }),
+ url: "https://research.example.com",
+ })
+ : null,
+ },
+});
+`;
+ const handler = evaluateSessionHandler(await transformSource(source));
+ const remote = handler() as Record<string, unknown>;
+
+ expect(remote.__eveResolveRemoteAgentCredentials).toBeTypeOf("function");
+ });
+
+ it("preserves quoted credential keys and method shorthand", async () => {
+ const source = `
+import { defineDynamic, defineRemoteAgent } from "eve";
+
+export default defineDynamic({
+ events: {
+ "session.started": () =>
+ defineRemoteAgent({
+ "auth": async () => ({ headers: { authorization: "Bearer fresh" } }),
+ description: "Remote research.",
+ headers() {
+ return { "x-runtime": "fresh" };
+ },
+ url: "https://research.example.com",
+ }),
+ },
+});
+`;
+ const handler = evaluateSessionHandler(await transformSource(source));
+ const remote = handler() as Record<string, unknown>;
+ const credentialsFactory = remote.__eveResolveRemoteAgentCredentials as Function;
+ const credentials = credentialsFactory() as Record<string, Function>;
+
+ await expect(credentials.auth!()).resolves.toEqual({
+ headers: { authorization: "Bearer fresh" },
+ });
+ expect(credentials.headers!()).toEqual({ "x-runtime": "fresh" });
+ });
+
+ it("does not transform public remote definitions without credentials", async () => {
+ await expect(
+ transformDynamicRemoteAgentCredentials(
+ "subagents/research.ts",
+ `export default defineDynamic({ events: { "session.started": () => defineRemoteAgent({ description: "Research", url: "https://example.com" }) } });`,
+ ),
+ ).resolves.toBeNull();
+ });
+});
diff --git a/packages/eve/src/internal/workflow-bundle/dynamic-remote-agent-transform.ts b/packages/eve/src/internal/workflow-bundle/dynamic-remote-agent-transform.ts
new file mode 100644
index 000000000..25f243378
--- /dev/null
+++ b/packages/eve/src/internal/workflow-bundle/dynamic-remote-agent-transform.ts
@@ -0,0 +1,127 @@
+import { parseWithNitroRolldownAst } from "#internal/bundler/nitro-rolldown.js";
+import {
+ findProperty,
+ type DynamicToolAstNode as AstNode,
+ walkNode,
+} from "#internal/workflow-bundle/dynamic-tool-ast-references.js";
+
+interface CredentialsFactoryInfo {
+ readonly authPropertySource?: string;
+ readonly callEnd: number;
+ readonly callSource: string;
+ readonly callStart: number;
+ readonly headersPropertySource?: string;
+ readonly hoistedName: string;
+}
+
+let transformCounter = 0;
+
+/**
+ * Hoists dynamic remote auth and headers into registered factories so durable
+ * selections carry only a function id, never credential values or closures.
+ */
+export async function transformDynamicRemoteAgentCredentials(
+ filename: string,
+ source: string,
+): Promise<{ code: string } | null> {
+ if (
+ !source.includes("defineDynamic") ||
+ !source.includes("defineRemoteAgent") ||
+ (!source.includes("auth") && !source.includes("headers"))
+ ) {
+ return null;
+ }
+
+ const ast = (await parseWithNitroRolldownAst(filename, source)) as AstNode;
+ const factories = findCredentialsFactories(source, ast);
+ return factories.length === 0 ? null : applyTransform(source, factories);
+}
+
+function findCredentialsFactories(source: string, ast: AstNode): CredentialsFactoryInfo[] {
+ const factories: CredentialsFactoryInfo[] = [];
+
+ walkNode(ast, (node) => {
+ if (
+ node.type !== "CallExpression" ||
+ node.callee?.type !== "Identifier" ||
+ node.callee.name !== "defineRemoteAgent" ||
+ node.arguments?.length !== 1 ||
+ node.start === undefined ||
+ node.end === undefined
+ ) {
+ return true;
+ }
+ const argument = node.arguments[0]!;
+ if (argument.type !== "ObjectExpression") {
+ return false;
+ }
+ const auth = findProperty(argument, "auth");
+ const headers = findProperty(argument, "headers");
+ if (auth === undefined && headers === undefined) {
+ return false;
+ }
+ factories.push({
+ authPropertySource: sliceNode(source, auth),
+ callEnd: node.end,
+ callSource: source.slice(node.start, node.end),
+ callStart: node.start,
+ headersPropertySource: sliceNode(source, headers),
+ hoistedName: `__eve_dynamic_remote_credentials_${transformCounter++}`,
+ });
+ return false;
+ });
+
+ return factories;
+}
+
+function applyTransform(
+ source: string,
+ factories: readonly CredentialsFactoryInfo[],
+): {
+ code: string;
+} {
+ const replacements: Array<{ start: number; end: number; text: string }> = [];
+ const hoistedFunctions: string[] = [];
+ const registrations: string[] = [];
+
+ for (const credentials of factories) {
+ const properties = [credentials.authPropertySource, credentials.headersPropertySource].filter(
+ (property) => property !== undefined,
+ );
+ const stepId = `eve:dynamic-remote-agent//${credentials.hoistedName}`;
+ hoistedFunctions.push(
+ `function ${credentials.hoistedName}() {\n` +
+ ` return { ${properties.join(", ")} };\n` +
+ `}`,
+ );
+ registrations.push(`${credentials.hoistedName}.stepId = ${JSON.stringify(stepId)};`);
+ registrations.push(
+ `__eveStepRegistry.set(${JSON.stringify(stepId)}, ${credentials.hoistedName});`,
+ );
+ replacements.push({
+ start: credentials.callStart,
+ end: credentials.callEnd,
+ text: `Object.defineProperty(${credentials.callSource}, "__eveResolveRemoteAgentCredentials", { value: ${credentials.hoistedName} })`,
+ });
+ }
+
+ let code = source;
+ for (const replacement of replacements.sort((a, b) => b.start - a.start)) {
+ code = code.slice(0, replacement.start) + replacement.text + code.slice(replacement.end);
+ }
+
+ const registrySetup = [
+ `var __eveStepRegistrySym = Symbol.for("@workflow/core//registeredSteps");`,
+ `if (!globalThis[__eveStepRegistrySym]) globalThis[__eveStepRegistrySym] = new Map();`,
+ `var __eveStepRegistry = globalThis[__eveStepRegistrySym];`,
+ ].join("\n");
+ return {
+ code: `${registrySetup}\n${code}\n\n${[...hoistedFunctions, ...registrations].join("\n")}\n`,
+ };
+}
+
+function sliceNode(source: string, node: AstNode | undefined): string | undefined {
+ return node?.start === undefined || node.end === undefined
+ ? undefined
+ : source.slice(node.start, node.end);
+}
diff --git a/packages/eve/src/internal/workflow-bundle/dynamic-tool-ast-references.ts b/packages/eve/src/internal/workflow-bundle/dynamic-tool-ast-references.ts
index 0650e5c13..b891b61ba 100644
--- a/packages/eve/src/internal/workflow-bundle/dynamic-tool-ast-references.ts
+++ b/packages/eve/src/internal/workflow-bundle/dynamic-tool-ast-references.ts
@@ -30,6 +30,37 @@ export type DynamicToolAstNode = {
type IdentifierContext = "binding" | "reference";
+export function findProperty(
+ object: DynamicToolAstNode,
+ name: string,
+): DynamicToolAstNode | undefined {
+ return object.properties?.find(
+ (property) =>
+ property.type === "Property" &&
+ !property.computed &&
+ (property.key?.type === "Identifier"
+ ? property.key.name === name
+ : property.key?.value === name),
+ );
+}
+
+export function walkNode(
+ node: DynamicToolAstNode,
+ visitor: (node: DynamicToolAstNode) => boolean,
+): void {
+ if (!visitor(node)) return;
+
+ for (const value of Object.values(node)) {
+ if (Array.isArray(value)) {
+ for (const child of value) {
+ if (isAstNode(child)) walkNode(child, visitor);
+ }
+ } else if (isAstNode(value)) {
+ walkNode(value, visitor);
+ }
+ }
+}
+
/**
* Collects identifiers used as runtime references in a function body AST.
*/
diff --git a/packages/eve/src/internal/workflow-bundle/dynamic-tool-transform.ts b/packages/eve/src/internal/workflow-bundle/dynamic-tool-transform.ts
index db1d30493..2e84651d6 100644
--- a/packages/eve/src/internal/workflow-bundle/dynamic-tool-transform.ts
+++ b/packages/eve/src/internal/workflow-bundle/dynamic-tool-transform.ts
@@ -28,7 +28,9 @@
import { parseWithNitroRolldownAst } from "#internal/bundler/nitro-rolldown.js";
import {
collectReferencedIdentifierNames,
+ findProperty,
type DynamicToolAstNode as AstNode,
+ walkNode,
} from "#internal/workflow-bundle/dynamic-tool-ast-references.js";
interface HandlerInfo {
@@ -557,47 +559,6 @@ function applyTransform(source: string, handlers: HandlerInfo[]): { code: string
return { code: result };
}
-// ---------------------------------------------------------------------------
-// Helpers
-// ---------------------------------------------------------------------------
-
-function walkNode(node: AstNode, visitor: (node: AstNode) => boolean): void {
- if (!visitor(node)) return;
-
- if (Array.isArray(node.body)) {
- for (const child of node.body) walkNode(child, visitor);
- } else if (node.body && typeof node.body === "object" && "type" in node.body) {
- walkNode(node.body as AstNode, visitor);
- }
- if (node.declarations) {
- for (const decl of node.declarations) walkNode(decl, visitor);
- }
- if (node.init) walkNode(node.init, visitor);
- if (node.expression) walkNode(node.expression, visitor);
- if (node.declaration) walkNode(node.declaration, visitor);
- if (node.argument) walkNode(node.argument, visitor);
- if (node.arguments) {
- for (const arg of node.arguments) walkNode(arg, visitor);
- }
- if (node.properties) {
- for (const prop of node.properties) {
- walkNode(prop, visitor);
- if (prop.value && typeof prop.value === "object" && "type" in (prop.value as AstNode)) {
- walkNode(prop.value as AstNode, visitor);
- }
- }
- }
- if (node.left) walkNode(node.left, visitor);
- if (node.right) walkNode(node.right, visitor);
-}
-
-function findProperty(obj: AstNode, name: string): AstNode | undefined {
- return obj.properties?.find(
- (p) =>
- p.type === "Property" && !p.computed && p.key?.type === "Identifier" && p.key.name === name,
- );
-}
-
/**
* Splits a parameter string on top-level commas, respecting nested
* angle brackets (`<>`), parentheses, square brackets, and curly
diff --git a/packages/eve/src/public/definitions/agent.ts b/packages/eve/src/public/definitions/agent.ts
index 38de0ba32..267a8eb72 100644
--- a/packages/eve/src/public/definitions/agent.ts
+++ b/packages/eve/src/public/definitions/agent.ts
@@ -1,5 +1,6 @@
import type { PublicAgentDefinition } from "#shared/agent-definition.js";
import type { ExactDefinition } from "#public/definitions/exact.js";
+import type { RemoteAgentDefinition } from "#public/definitions/remote-agent.js";
import { defineDynamic as defineDynamicBase } from "#public/definitions/tool.js";
import type {
DynamicEvents,
@@ -48,10 +49,13 @@ export type DefinedAgent<TAgent extends AgentDefinition = AgentDefinition> = TAg
* Agent configuration returned by a dynamic subagent resolver. The description
* tells the parent agent when to delegate.
*/
-export type DynamicSubagentDefinition = AgentDefinition & {
+export type DynamicLocalSubagentDefinition = AgentDefinition & {
readonly description: string;
};
+/** Definition a dynamic subagent resolver may select at runtime. */
+export type DynamicSubagentDefinition = DynamicLocalSubagentDefinition | RemoteAgentDefinition;
+
type DynamicEventHandler<TEvents extends DynamicEvents> = Extract<
NonNullable<TEvents[keyof TEvents]>,
(...args: never[]) => unknown
@@ -62,7 +66,7 @@ type DynamicEventResult<TEvents extends DynamicEvents> = Awaited<
type DynamicSubagentDescriptionConstraint<TEvents extends DynamicEvents> =
Exclude<
Extract<DynamicEventResult<TEvents>, DefinedAgent>,
- DynamicSubagentDefinition
+ DynamicLocalSubagentDefinition
> extends never
? unknown
: { readonly "Dynamic subagent definitions require a description": never };
diff --git a/packages/eve/src/public/definitions/exact.test.ts b/packages/eve/src/public/definitions/exact.test.ts
index 854930faa..9b97ccb11 100644
--- a/packages/eve/src/public/definitions/exact.test.ts
+++ b/packages/eve/src/public/definitions/exact.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, expectTypeOf, it } from "vitest";
import type { UnstampedMessageStreamEvent } from "#protocol/message.js";
import { defineAgent, defineDynamic } from "#public/definitions/agent.js";
+import { defineRemoteAgent } from "#public/definitions/remote-agent.js";
import { none } from "#public/channels/auth.js";
import { eveChannel, defaultEveAuth } from "#public/channels/eve.js";
import { defineChannel, POST } from "#public/definitions/channel.js";
@@ -59,6 +60,21 @@ function typeOnlyFixtures(): void {
},
});
+ defineDynamic({
+ events: {
+ "session.started": () =>
+ Math.random() > 0.5
+ ? defineAgent({
+ description: "Delegate local research tasks.",
+ model: "anthropic/claude-sonnet-5",
+ })
+ : defineRemoteAgent({
+ description: "Delegate remote research tasks.",
+ url: "https://research.example.com",
+ }),
+ },
+ });
+
defineDynamic({
events: {
"session.started": () =>
diff --git a/packages/eve/src/public/index.ts b/packages/eve/src/public/index.ts
index c2906e651..2af5757f8 100644
--- a/packages/eve/src/public/index.ts
+++ b/packages/eve/src/public/index.ts
@@ -14,6 +14,7 @@ export {
type AgentWorkflowWorldDefinition,
type DefinedAgent,
type DynamicSubagentDefinition,
+ type DynamicLocalSubagentDefinition,
defineAgent,
defineDynamic,
} from "#public/definitions/agent.js";
diff --git a/packages/eve/src/runtime/subagents/dynamic-agent-config.ts b/packages/eve/src/runtime/subagents/dynamic-agent-config.ts
index c65db0f43..8ba4f8558 100644
--- a/packages/eve/src/runtime/subagents/dynamic-agent-config.ts
+++ b/packages/eve/src/runtime/subagents/dynamic-agent-config.ts
@@ -31,7 +31,7 @@ export function normalizeDynamicSubagentAgentConfig(input: {
readonly name: string;
readonly value: unknown;
}): DynamicSubagentAgentConfig {
- const message = `Dynamic subagent "${input.name}" must return defineAgent({ description, model, ... }) or null.`;
+ const message = `Dynamic subagent "${input.name}" must return defineAgent(...), defineRemoteAgent(...), or null.`;
const definition = normalizeAgentDefinition(input.value, message);
if (!definition.description) {
diff --git a/packages/eve/src/runtime/subagents/dynamic-remote-agent-config.ts b/packages/eve/src/runtime/subagents/dynamic-remote-agent-config.ts
new file mode 100644
index 000000000..a662fcf45
--- /dev/null
+++ b/packages/eve/src/runtime/subagents/dynamic-remote-agent-config.ts
@@ -0,0 +1,106 @@
+import {
+ expectBoolean,
+ expectFunction,
+ expectObjectRecord,
+ expectOnlyKnownKeys,
+ expectString,
+ getOptionalStringRecordProperty,
+} from "#internal/authored-module.js";
+import type { OutboundAuthFn } from "#public/agents/auth.js";
+import { EVE_CREATE_SESSION_ROUTE_PATH } from "#protocol/routes.js";
+import type { JsonObject } from "#shared/json.js";
+import { serializeOutputSchema, type ToolSchemaSource } from "#shared/tool-schema.js";
+
+export interface DynamicRemoteAgentConfig {
+ readonly credentialsStepId?: string;
+ readonly description: string;
+ readonly forwardPrincipal?: boolean;
+ readonly outputSchema?: JsonObject;
+ readonly path: string;
+ readonly url: string;
+}
+
+export async function normalizeDynamicRemoteAgentConfig(input: {
+ readonly name: string;
+ readonly value: unknown;
+}): Promise<DynamicRemoteAgentConfig> {
+ const message = `Dynamic subagent "${input.name}" must return defineAgent(...), defineRemoteAgent(...), or null.`;
+ const record = expectObjectRecord(input.value, message);
+ expectOnlyKnownKeys(
+ record,
+ ["auth", "description", "forwardPrincipal", "headers", "kind", "outputSchema", "path", "url"],
+ message,
+ );
+
+ if (record.kind !== "remote") {
+ throw new Error(message);
+ }
+
+ const url = await resolveUrl(record.url, message);
+ const credentialsStepId = readCredentialsStepId(record);
+ validateCredentials(record, message);
+ if (
+ (record.auth !== undefined || record.headers !== undefined) &&
+ credentialsStepId === undefined
+ ) {
+ throw new Error(
+ `${message} Dynamic remote auth and headers must be compiled by eve so credentials stay out of durable workflow state.`,
+ );
+ }
+ const config: {
+ credentialsStepId?: string;
+ description: string;
+ forwardPrincipal?: boolean;
+ outputSchema?: JsonObject;
+ path: string;
+ url: string;
+ } = {
+ description: expectString(record.description, message),
+ path:
+ record.path === undefined
+ ? EVE_CREATE_SESSION_ROUTE_PATH
+ : expectString(record.path, message),
+ url,
+ };
+
+ if (credentialsStepId !== undefined) {
+ config.credentialsStepId = credentialsStepId;
+ }
+ if (record.forwardPrincipal !== undefined) {
+ config.forwardPrincipal = expectBoolean(record.forwardPrincipal, message);
+ }
+ if (record.outputSchema !== undefined) {
+ config.outputSchema = serializeOutputSchema(record.outputSchema as ToolSchemaSource);
+ }
+
+ return config;
+}
+
+async function resolveUrl(value: unknown, message: string): Promise<string> {
+ const url =
+ typeof value === "function"
+ ? await expectFunction<() => string | Promise<string>>(value, message)()
+ : expectString(value, message);
+ if (url.length === 0) {
+ throw new Error(`${message} The "url" field must resolve to a non-empty string.`);
+ }
+ return url;
+}
+
+function validateCredentials(record: Record<string, unknown>, message: string): void {
+ if (record.auth !== undefined) {
+ expectFunction<OutboundAuthFn>(record.auth, message);
+ }
+ if (record.headers !== undefined && typeof record.headers !== "function") {
+ getOptionalStringRecordProperty(record, "headers", message);
+ }
+}
+
+function readCredentialsStepId(record: Record<string, unknown>): string | undefined {
+ const resolver = record.__eveResolveRemoteAgentCredentials;
+ if (typeof resolver !== "function") {
+ return undefined;
+ }
+ const stepId = (resolver as { readonly stepId?: unknown }).stepId;
+ return typeof stepId === "string" ? stepId : undefined;
+}