Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

fix(eve): fail the build when dynamic remote credentials capture handler values (#4127)

Andrew Barbaac77188ad0bd
diff --git a/.changeset/dynamic-remote-credentials-build-error.md b/.changeset/dynamic-remote-credentials-build-error.md
new file mode 100644
index 000000000..defe942f1
--- /dev/null
+++ b/.changeset/dynamic-remote-credentials-build-error.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+The build now fails when a dynamic remote agent's `auth` or `headers` uses a value declared inside the event handler. Before, eve moved the credentials to module scope anyway, so they threw at request time or silently read a same-named module value. Dynamic remote agents imported through an alias or `import * as eve` now compile their credentials too.
diff --git a/docs/guides/remote-agents.md b/docs/guides/remote-agents.md
index 5ff72fc41..491882e2c 100644
--- a/docs/guides/remote-agents.md
+++ b/docs/guides/remote-agents.md
@@ -59,9 +59,16 @@ 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.
+and keep their functions self-contained with module imports, module-level
+constants, or environment variables. They are rehydrated outside the event
+handler, so they cannot close over `_event`, `ctx`, or handler-local values. The
+build fails with an error that names the handler-local value when they do.
+
+eve compiles only `auth` and `headers` written directly in the
+`defineRemoteAgent({ ... })` object in the subagent file. When they arrive
+through a spread, a variable passed as the argument, or a definition built in
+another module, eve rejects the definition at runtime, logs the error, and runs
+the agent without that subagent.
## Runtime URLs
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
index e74fa0d24..9103ca6b2 100644
--- 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
@@ -131,6 +131,80 @@ export default defineDynamic({
expect(credentials.headers!()).toEqual({ "x-runtime": "fresh" });
});
+ it("hoists credentials from aliased and namespace imports", async () => {
+ for (const source of [
+ `import { defineDynamic, defineRemoteAgent as remote } from "eve";
+export default defineDynamic({ events: { "session.started": () => remote({ description: "Research", url: "https://example.com", headers: () => ({ "x-runtime": "fresh" }) }) } });`,
+ `import * as eve from "eve";
+export default eve.defineDynamic({ events: { "session.started": () => eve.defineRemoteAgent({ description: "Research", url: "https://example.com", headers: () => ({ "x-runtime": "fresh" }) }) } });`,
+ ]) {
+ expect(await transformSource(source)).toContain("__eveResolveRemoteAgentCredentials");
+ }
+ });
+
+ // Each module also declares "env", which the hoisted copy would silently read.
+ it.each([
+ {
+ name: "handler-local const",
+ handler: `const env = "PRODUCTION";
+ return defineRemoteAgent({ description: "Research", url: "https://example.com", headers: () => ({ "x-env": env }) });`,
+ },
+ {
+ name: "handler-local function declaration",
+ handler: `function env() { return "PRODUCTION"; }
+ return defineRemoteAgent({ description: "Research", url: "https://example.com", headers: () => ({ "x-env": env() }) });`,
+ },
+ {
+ name: "catch parameter",
+ handler: `try { throw "PRODUCTION"; } catch (env) {
+ return defineRemoteAgent({ description: "Research", url: "https://example.com", headers: () => ({ "x-env": env }) });
+ }`,
+ },
+ {
+ name: "const next to a same-named nested parameter",
+ handler: `const env = "PRODUCTION";
+ return defineRemoteAgent({ description: "Research", url: "https://example.com", headers: () => ({ "x-env": env, all: ["a"].map((env) => env) }) });`,
+ },
+ ])("fails the build when credentials capture a $name", async ({ handler }) => {
+ const source = `
+import { defineDynamic, defineRemoteAgent } from "eve";
+
+const env = "STAGING";
+export default defineDynamic({ events: { "session.started": () => {
+ ${handler}
+} } });
+`;
+ await expect(transformSource(source)).rejects.toThrow(
+ /Dynamic remote agent "headers" in subagents\/research\.ts references "env", declared outside module scope/,
+ );
+ });
+
+ it("allows credentials that use module bindings and their own locals", async () => {
+ const source = `
+import { defineDynamic, defineRemoteAgent } from "eve";
+
+const ENV = "PRODUCTION";
+export default defineDynamic({
+ events: {
+ "session.started": (_event, ctx) => {
+ if (ctx) {
+ const ENV = "BLOCK";
+ }
+ return defineRemoteAgent({
+ async auth(request) {
+ const ctx = { token: ENV };
+ return { headers: { authorization: ctx.token, url: request?.url } };
+ },
+ description: "Remote research.",
+ url: "https://research.example.com",
+ });
+ },
+ },
+});
+`;
+ expect(await transformSource(source)).toContain("__eveResolveRemoteAgentCredentials");
+ });
+
it("does not transform public remote definitions without credentials", async () => {
await expect(
transformDynamicRemoteAgentCredentials(
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
index f22e3594d..6eac53a5e 100644
--- a/packages/eve/src/internal/workflow-bundle/dynamic-remote-agent-transform.ts
+++ b/packages/eve/src/internal/workflow-bundle/dynamic-remote-agent-transform.ts
@@ -2,9 +2,11 @@ import { createHash } from "node:crypto";
import { parseWithNitroRolldownAst } from "#internal/bundler/nitro-rolldown.js";
import {
+ collectFreeVariables,
+ findEveImportAliases,
findProperty,
type DynamicToolAstNode as AstNode,
- walkNode,
+ walkDefinerCalls,
} from "#internal/workflow-bundle/dynamic-tool-ast-references.js";
import { stableModuleId } from "#internal/workflow-bundle/stable-module-id.js";
@@ -45,48 +47,69 @@ function findCredentialsFactories(
): CredentialsFactoryInfo[] {
const factories: CredentialsFactoryInfo[] = [];
const moduleId = stableModuleId(filename);
+ // The bare name also covers re-exports through authored modules.
+ const definers = new Set([
+ "defineRemoteAgent",
+ ...findEveImportAliases(ast, ["defineRemoteAgent"]),
+ ]);
- 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;
- }
+ walkDefinerCalls(ast, definers, (call, argument, enclosingBindings) => {
const auth = findProperty(argument, "auth");
const headers = findProperty(argument, "headers");
- if (auth === undefined && headers === undefined) {
- return false;
+ if (
+ (auth === undefined && headers === undefined) ||
+ call.start === undefined ||
+ call.end === undefined
+ ) {
+ return;
}
+ assertModuleScoped(filename, [auth, headers], enclosingBindings);
// Content-addressed so the id survives rebuilds and never collides across
// modules or transform order; editing the factory itself invalidates it.
- const callSource = source.slice(node.start, node.end);
+ const callSource = source.slice(call.start, call.end);
const hash = createHash("sha256")
.update(`${moduleId}//${callSource}`)
.digest("hex")
.slice(0, 16);
factories.push({
authPropertySource: sliceNode(source, auth),
- callEnd: node.end,
+ callEnd: call.end,
callSource,
- callStart: node.start,
+ callStart: call.start,
headersPropertySource: sliceNode(source, headers),
hoistedName: `__eve_dynamic_remote_credentials_${hash}`,
});
- return false;
});
return factories;
}
+/**
+ * Hoisted credentials run at module scope, so a reference to a binding from an
+ * enclosing function or block would throw or, when a module binding shares its
+ * name, silently resolve to the wrong value.
+ */
+function assertModuleScoped(
+ filename: string,
+ properties: ReadonlyArray<AstNode | undefined>,
+ enclosingBindings: ReadonlySet<string>,
+): void {
+ for (const property of properties) {
+ const value = property?.value as AstNode | undefined;
+ if (value === undefined) continue;
+ const captured = [...collectFreeVariables(value)].filter((name) => enclosingBindings.has(name));
+ if (captured.length > 0) {
+ const key = String(property!.key?.name ?? property!.key?.value);
+ const names = captured.map((name) => `"${name}"`).join(", ");
+ throw new Error(
+ `Dynamic remote agent "${key}" in ${filename} references ${names}, declared outside module scope. ` +
+ `eve moves dynamic remote auth and headers to module scope so credentials stay out of durable workflow state. ` +
+ `Declare ${names} at module scope or inside "${key}" itself.`,
+ );
+ }
+ }
+}
+
function applyTransform(
source: string,
factories: readonly CredentialsFactoryInfo[],
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 c6c31f50f..6ff2f7645 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
@@ -1,4 +1,4 @@
-/** Rolldown AST subset consumed by the dynamic-tool transform. */
+/** Rolldown AST subset consumed by the dynamic tool and remote agent transforms. */
export type DynamicToolAstNode = {
argument?: DynamicToolAstNode | null;
arguments?: DynamicToolAstNode[];
@@ -8,7 +8,9 @@ export type DynamicToolAstNode = {
| DynamicToolAstNode[]
| { body?: DynamicToolAstNode[]; type?: string; start?: number; end?: number };
callee?: DynamicToolAstNode;
+ cases?: DynamicToolAstNode[];
computed?: boolean;
+ consequent?: DynamicToolAstNode | DynamicToolAstNode[] | null;
declaration?: DynamicToolAstNode | null;
declarations?: DynamicToolAstNode[];
directive?: string;
@@ -25,6 +27,7 @@ export type DynamicToolAstNode = {
method?: boolean;
name?: string;
object?: DynamicToolAstNode | null;
+ param?: DynamicToolAstNode | null;
params?: DynamicToolAstNode[];
properties?: DynamicToolAstNode[];
property?: DynamicToolAstNode | null;
@@ -37,6 +40,8 @@ export type DynamicToolAstNode = {
elements?: Array<DynamicToolAstNode | null>;
};
+type AstNode = DynamicToolAstNode;
+
type IdentifierContext = "binding" | "reference";
export function findProperty(
@@ -200,10 +205,225 @@ function isRuntimeTypeScriptExpression(node: DynamicToolAstNode): boolean {
);
}
-function isAstNode(value: unknown): value is DynamicToolAstNode {
+export function isAstNode(value: unknown): value is DynamicToolAstNode {
return (
value !== null &&
typeof value === "object" &&
typeof (value as DynamicToolAstNode).type === "string"
);
}
+
+/**
+ * Local names (`alias` or `namespace.name`) that refer to the given exports of
+ * an `eve` or `eve/*` import.
+ */
+export function findEveImportAliases(ast: AstNode, names: readonly string[]): ReadonlySet<string> {
+ const aliases = new Set<string>();
+ walkNode(ast, (node) => {
+ if (node.type !== "ImportDeclaration") return true;
+ const source = node.source?.value;
+ if (typeof source !== "string" || (source !== "eve" && !source.startsWith("eve/"))) {
+ return false;
+ }
+ for (const specifier of node.specifiers ?? []) {
+ if (specifier.type === "ImportNamespaceSpecifier" && specifier.local?.name) {
+ for (const name of names) aliases.add(`${specifier.local.name}.${name}`);
+ }
+ if (
+ specifier.type === "ImportSpecifier" &&
+ names.includes(String(specifier.imported?.name ?? specifier.imported?.value)) &&
+ specifier.local?.name
+ ) {
+ aliases.add(specifier.local.name);
+ }
+ }
+ return false;
+ });
+ return aliases;
+}
+
+export function readDefinerName(callee: AstNode | undefined): string | undefined {
+ if (callee?.type === "Identifier") return callee.name;
+ if (callee?.type !== "MemberExpression" || callee.object?.type !== "Identifier") return undefined;
+ const property = callee.computed ? callee.property?.value : callee.property?.name;
+ return typeof property === "string" ? `${callee.object.name}.${property}` : undefined;
+}
+
+export function collectPatternNames(pattern: AstNode | null, names: string[]): void {
+ if (!pattern) return;
+ if (pattern.type === "Identifier" && pattern.name) {
+ names.push(pattern.name);
+ return;
+ }
+ if (pattern.type === "ObjectPattern") {
+ for (const property of pattern.properties ?? []) {
+ collectPatternNames(
+ property.type === "RestElement"
+ ? (property.argument as AstNode | null)
+ : (property.value as AstNode | null),
+ names,
+ );
+ }
+ }
+ if (pattern.type === "ArrayPattern") {
+ for (const element of pattern.elements ?? []) collectPatternNames(element, names);
+ }
+ if (pattern.type === "AssignmentPattern") {
+ collectPatternNames(pattern.left as AstNode | null, names);
+ }
+}
+
+export function extractParamNames(fn: AstNode): string[] {
+ const names: string[] = [];
+ for (const parameter of fn.params ?? []) collectPatternNames(parameter, names);
+ return names;
+}
+
+export function isFunction(node: AstNode): boolean {
+ return (
+ node.type === "ArrowFunctionExpression" ||
+ node.type === "FunctionDeclaration" ||
+ node.type === "FunctionExpression"
+ );
+}
+
+/**
+ * Visits each call to one of `definers` that takes a single object literal,
+ * with the names bound by its enclosing function, block, catch, loop, and class
+ * scopes. Module-scope bindings are excluded.
+ */
+export function walkDefinerCalls(
+ ast: AstNode,
+ definers: ReadonlySet<string>,
+ visit: (call: AstNode, argument: AstNode, enclosingBindings: ReadonlySet<string>) => void,
+): void {
+ const walk = (node: AstNode, bindings: ReadonlySet<string>): void => {
+ const argument = node.arguments?.[0];
+ if (
+ node.type === "CallExpression" &&
+ definers.has(readDefinerName(node.callee) ?? "") &&
+ node.arguments?.length === 1 &&
+ argument?.type === "ObjectExpression"
+ ) {
+ visit(node, argument, bindings);
+ return;
+ }
+ const scoped = node.type === "Program" ? bindings : withScopeBindings(node, bindings);
+ for (const value of Object.values(node)) {
+ for (const child of Array.isArray(value) ? value : [value]) {
+ if (isAstNode(child)) walk(child, scoped);
+ }
+ }
+ };
+ walk(ast, new Set());
+}
+
+/**
+ * Names `node` references at runtime without binding them in a scope that
+ * encloses the reference.
+ */
+export function collectFreeVariables(node: AstNode): Set<string> {
+ const free = new Set<string>();
+
+ const visit = (
+ current: AstNode,
+ context: IdentifierContext,
+ bindings: ReadonlySet<string>,
+ ): void => {
+ if (current.type?.startsWith("TS")) {
+ if (isRuntimeTypeScriptExpression(current) && current.expression) {
+ visit(current.expression, "reference", bindings);
+ }
+ return;
+ }
+ if (
+ current.type === "Identifier" &&
+ current.name &&
+ context === "reference" &&
+ !bindings.has(current.name)
+ ) {
+ free.add(current.name);
+ }
+
+ const scoped = withScopeBindings(current, bindings);
+ for (const [key, value] of Object.entries(current)) {
+ const childContext = getChildContext(current, key, context);
+ if (!childContext) continue;
+ for (const child of Array.isArray(value) ? value : [value]) {
+ if (isAstNode(child)) visit(child, childContext, scoped);
+ }
+ }
+ };
+
+ visit(node, "reference", new Set());
+ return free;
+}
+
+function withScopeBindings(node: AstNode, bindings: ReadonlySet<string>): ReadonlySet<string> {
+ const names = scopeBindings(node);
+ return names.length === 0 ? bindings : new Set([...bindings, ...names]);
+}
+
+function scopeBindings(node: AstNode): string[] {
+ const names: string[] = [];
+ if (isFunction(node)) {
+ if (node.type === "FunctionExpression" && node.id?.name) names.push(node.id.name);
+ for (const parameter of node.params ?? []) collectPatternNames(parameter, names);
+ if (isAstNode(node.body)) collectVarNames(node.body, names);
+ } else if (node.type === "BlockStatement" || node.type === "StaticBlock") {
+ collectLexicalNames(node.body, names);
+ } else if (node.type === "SwitchStatement") {
+ for (const switchCase of node.cases ?? []) collectLexicalNames(switchCase.consequent, names);
+ } else if (
+ node.type === "ForStatement" ||
+ node.type === "ForInStatement" ||
+ node.type === "ForOfStatement"
+ ) {
+ const declaration = node.type === "ForStatement" ? node.init : node.left;
+ if (declaration?.type === "VariableDeclaration" && declaration.kind !== "var") {
+ for (const declarator of declaration.declarations ?? []) {
+ collectPatternNames(declarator.id as AstNode | null, names);
+ }
+ }
+ } else if (node.type === "CatchClause") {
+ collectPatternNames(node.param ?? null, names);
+ } else if (node.type === "ClassExpression" && node.id?.name) {
+ names.push(node.id.name);
+ }
+ return names;
+}
+
+/** `var` declarations hoist to the nearest function, across nested blocks. */
+function collectVarNames(body: AstNode, names: string[]): void {
+ walkNode(body, (node) => {
+ if (isFunction(node)) return false;
+ if (node.type === "VariableDeclaration" && node.kind === "var") {
+ for (const declarator of node.declarations ?? []) {
+ collectPatternNames(declarator.id as AstNode | null, names);
+ }
+ }
+ return true;
+ });
+}
+
+/** Module code is strict, so function and class declarations are block-scoped. */
+function collectLexicalNames(
+ statements: AstNode["body"] | AstNode["consequent"],
+ names: string[],
+): void {
+ if (!Array.isArray(statements)) return;
+ for (const statement of statements) {
+ if (statement.type === "VariableDeclaration" && statement.kind !== "var") {
+ for (const declarator of statement.declarations ?? []) {
+ collectPatternNames(declarator.id as AstNode | null, names);
+ }
+ } else if (
+ (statement.type === "FunctionDeclaration" ||
+ statement.type === "ClassDeclaration" ||
+ statement.type === "TSEnumDeclaration") &&
+ statement.id?.name
+ ) {
+ names.push(statement.id.name);
+ }
+ }
+}
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 519ff8bf9..f8c13d509 100644
--- a/packages/eve/src/internal/workflow-bundle/dynamic-tool-transform.ts
+++ b/packages/eve/src/internal/workflow-bundle/dynamic-tool-transform.ts
@@ -7,8 +7,14 @@
import { parseWithNitroRolldownAst } from "#internal/bundler/nitro-rolldown.js";
import {
+ collectPatternNames,
collectReferencedIdentifierNames,
+ extractParamNames,
+ findEveImportAliases,
findProperty,
+ isAstNode,
+ isFunction,
+ readDefinerName,
type DynamicToolAstNode as AstNode,
walkNode,
} from "#internal/workflow-bundle/dynamic-tool-ast-references.js";
@@ -70,14 +76,14 @@ export async function transformDynamicToolExecute(
if (!source.includes("defineTool") && !source.includes("defineWorkflowTool")) return null;
const ast = (await parseWithNitroRolldownAst(filename, source)) as AstNode;
- const defineToolAliases = findDefineToolAliases(ast);
+ const defineToolAliases = findEveImportAliases(ast, ["defineTool", "defineWorkflowTool"]);
if (defineToolAliases.size === 0) return null;
const callbacks: CallbackInfo[] = [];
walkForCallbacks(source, ast, callbacks, [], {
defineToolAliases,
workflowFunctions,
- durableSchemaAliases: findDefineToolAliases(ast, ["defineDurableSchema"]),
+ durableSchemaAliases: findEveImportAliases(ast, ["defineDurableSchema"]),
});
return callbacks.length === 0 ? null : applyTransform(source, callbacks);
}
@@ -95,41 +101,6 @@ interface WalkContext {
readonly workflowFunctions: ReadonlySet<string>;
}
-function findDefineToolAliases(
- ast: AstNode,
- names: readonly string[] = ["defineTool", "defineWorkflowTool"],
-): ReadonlySet<string> {
- const aliases = new Set<string>();
- walkNode(ast, (node) => {
- if (node.type !== "ImportDeclaration") return true;
- const source = node.source?.value;
- if (typeof source !== "string" || (source !== "eve" && !source.startsWith("eve/"))) {
- return false;
- }
- for (const specifier of node.specifiers ?? []) {
- if (specifier.type === "ImportNamespaceSpecifier" && specifier.local?.name) {
- for (const name of names) aliases.add(`${specifier.local.name}.${name}`);
- }
- if (
- specifier.type === "ImportSpecifier" &&
- names.includes(String(specifier.imported?.name ?? specifier.imported?.value)) &&
- specifier.local?.name
- ) {
- aliases.add(specifier.local.name);
- }
- }
- return false;
- });
- return aliases;
-}
-
-function readDefinerName(callee: AstNode | undefined): string | undefined {
- if (callee?.type === "Identifier") return callee.name;
- if (callee?.type !== "MemberExpression" || callee.object?.type !== "Identifier") return undefined;
- const property = callee.computed ? callee.property?.value : callee.property?.name;
- return typeof property === "string" ? `${callee.object.name}.${property}` : undefined;
-}
-
function walkForCallbacks(
source: string,
node: AstNode | null | undefined,
@@ -448,36 +419,6 @@ function collectScopeVarDeclarations(bodyNode: AstNode): string[] {
return names;
}
-function collectPatternNames(pattern: AstNode | null, names: string[]): void {
- if (!pattern) return;
- if (pattern.type === "Identifier" && pattern.name) {
- names.push(pattern.name);
- return;
- }
- if (pattern.type === "ObjectPattern") {
- for (const property of pattern.properties ?? []) {
- collectPatternNames(
- property.type === "RestElement"
- ? (property.argument as AstNode | null)
- : (property.value as AstNode | null),
- names,
- );
- }
- }
- if (pattern.type === "ArrayPattern") {
- for (const element of pattern.elements ?? []) collectPatternNames(element, names);
- }
- if (pattern.type === "AssignmentPattern") {
- collectPatternNames(pattern.left as AstNode | null, names);
- }
-}
-
-function extractParamNames(fn: AstNode): string[] {
- const names: string[] = [];
- for (const parameter of fn.params ?? []) collectPatternNames(parameter, names);
- return names;
-}
-
function extractFnParams(source: string, fn: AstNode): string {
if (!fn.params || fn.params.length === 0) return "";
const first = fn.params[0]!;
@@ -541,15 +482,3 @@ function extractCallbackParamNames(params: string): Set<string> {
}
return new Set(names);
}
-
-function isFunction(node: AstNode): boolean {
- return (
- node.type === "ArrowFunctionExpression" ||
- node.type === "FunctionDeclaration" ||
- node.type === "FunctionExpression"
- );
-}
-
-function isAstNode(value: unknown): value is AstNode {
- return value !== null && typeof value === "object" && typeof (value as AstNode).type === "string";
-}