Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

fix(eve): build - analyze dynamic tool captures from syntax (#1127)

Andrew Barba45ad5d0e83c2
diff --git a/.changeset/quiet-dynamic-captures.md b/.changeset/quiet-dynamic-captures.md
new file mode 100644
index 000000000..e7630891d
--- /dev/null
+++ b/.changeset/quiet-dynamic-captures.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Analyze dynamic tool closure references from the syntax tree so object keys and string contents cannot become invalid runtime captures.
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
new file mode 100644
index 000000000..0650e5c13
--- /dev/null
+++ b/packages/eve/src/internal/workflow-bundle/dynamic-tool-ast-references.ts
@@ -0,0 +1,169 @@
+/** Rolldown AST subset consumed by the dynamic-tool transform. */
+export type DynamicToolAstNode = {
+ argument?: DynamicToolAstNode | null;
+ arguments?: DynamicToolAstNode[];
+ async?: boolean;
+ body?:
+ | DynamicToolAstNode
+ | DynamicToolAstNode[]
+ | { body?: DynamicToolAstNode[]; type?: string; start?: number; end?: number };
+ callee?: DynamicToolAstNode;
+ computed?: boolean;
+ declaration?: DynamicToolAstNode | null;
+ declarations?: DynamicToolAstNode[];
+ end?: number;
+ expression?: DynamicToolAstNode | null;
+ id?: { name?: string; start?: number; end?: number } | null;
+ init?: DynamicToolAstNode | null;
+ key?: DynamicToolAstNode | null;
+ kind?: string;
+ left?: DynamicToolAstNode | null;
+ method?: boolean;
+ name?: string;
+ params?: DynamicToolAstNode[];
+ properties?: DynamicToolAstNode[];
+ right?: DynamicToolAstNode | null;
+ start?: number;
+ type?: string;
+ value?: DynamicToolAstNode | unknown;
+};
+
+type IdentifierContext = "binding" | "reference";
+
+/**
+ * Collects identifiers used as runtime references in a function body AST.
+ */
+export function collectReferencedIdentifierNames(node: DynamicToolAstNode): Set<string> {
+ const names = new Set<string>();
+
+ const visit = (current: DynamicToolAstNode, context: IdentifierContext): void => {
+ if (current.type?.startsWith("TS")) {
+ if (isRuntimeTypeScriptExpression(current) && current.expression) {
+ visit(current.expression, "reference");
+ }
+ return;
+ }
+
+ if (current.type === "Identifier" && current.name && context === "reference") {
+ names.add(current.name);
+ }
+
+ for (const [key, value] of Object.entries(current)) {
+ const childContext = getChildContext(current, key, context);
+ if (!childContext) continue;
+
+ if (Array.isArray(value)) {
+ for (const child of value) {
+ if (isAstNode(child)) {
+ visit(child, childContext);
+ }
+ }
+ } else if (isAstNode(value)) {
+ visit(value, childContext);
+ }
+ }
+ };
+
+ visit(node, "reference");
+ return names;
+}
+
+function getChildContext(
+ parent: DynamicToolAstNode,
+ parentKey: string,
+ context: IdentifierContext,
+): IdentifierContext | null {
+ if (
+ parentKey === "typeAnnotation" ||
+ parentKey === "returnType" ||
+ parentKey === "typeParameters" ||
+ parentKey === "typeArguments"
+ ) {
+ return null;
+ }
+
+ if (parent.type === "VariableDeclarator" && parentKey === "id") {
+ return "binding";
+ }
+
+ if (
+ (parent.type === "FunctionExpression" ||
+ parent.type === "ArrowFunctionExpression" ||
+ parent.type === "FunctionDeclaration") &&
+ (parentKey === "id" || parentKey === "params")
+ ) {
+ return "binding";
+ }
+
+ if (
+ (parent.type === "CatchClause" && parentKey === "param") ||
+ ((parent.type === "ClassDeclaration" || parent.type === "ClassExpression") &&
+ parentKey === "id")
+ ) {
+ return "binding";
+ }
+
+ if (parent.type === "Property" && parentKey === "key") {
+ return parent.computed === true ? "reference" : null;
+ }
+
+ if (parent.type === "Property" && parentKey === "value") {
+ return context;
+ }
+
+ if (parent.type === "AssignmentPattern") {
+ return parentKey === "right" ? "reference" : context;
+ }
+
+ if (
+ (parent.type === "ObjectPattern" ||
+ parent.type === "ArrayPattern" ||
+ parent.type === "RestElement") &&
+ (parentKey === "properties" || parentKey === "elements" || parentKey === "argument")
+ ) {
+ return context;
+ }
+
+ if (
+ (parent.type === "MemberExpression" || parent.type === "OptionalMemberExpression") &&
+ parentKey === "property"
+ ) {
+ return parent.computed === true ? "reference" : null;
+ }
+
+ if (
+ (parent.type === "MethodDefinition" || parent.type === "PropertyDefinition") &&
+ parentKey === "key"
+ ) {
+ return parent.computed === true ? "reference" : null;
+ }
+
+ if (
+ (parent.type === "LabeledStatement" ||
+ parent.type === "BreakStatement" ||
+ parent.type === "ContinueStatement") &&
+ parentKey === "label"
+ ) {
+ return null;
+ }
+
+ return "reference";
+}
+
+function isRuntimeTypeScriptExpression(node: DynamicToolAstNode): boolean {
+ return (
+ node.type === "TSAsExpression" ||
+ node.type === "TSInstantiationExpression" ||
+ node.type === "TSNonNullExpression" ||
+ node.type === "TSSatisfiesExpression" ||
+ node.type === "TSTypeAssertion"
+ );
+}
+
+function isAstNode(value: unknown): value is DynamicToolAstNode {
+ return (
+ value !== null &&
+ typeof value === "object" &&
+ typeof (value as DynamicToolAstNode).type === "string"
+ );
+}
diff --git a/packages/eve/src/internal/workflow-bundle/dynamic-tool-transform.test.ts b/packages/eve/src/internal/workflow-bundle/dynamic-tool-transform.test.ts
index f317f7e49..c87ae56f0 100644
--- a/packages/eve/src/internal/workflow-bundle/dynamic-tool-transform.test.ts
+++ b/packages/eve/src/internal/workflow-bundle/dynamic-tool-transform.test.ts
@@ -271,6 +271,162 @@ export default defineDynamic({
expect(readStepFn).not.toBe(writeStepFn);
});
+ it("does not capture object keys or text from string literals", async () => {
+ const source = `
+import { defineDynamic, defineTool } from "eve/tools";
+
+export default defineDynamic({
+ events: {
+ "session.started": async () => {
+ const tools = {};
+
+ tools.probe_alpha = defineTool({
+ description: "probe alpha",
+ inputSchema: { type: "object" },
+ execute({ q }) {
+ return { url: "/x/" + q, note: "answer from app tools only" };
+ },
+ });
+
+ {
+ const url = "https://example.com";
+ const cred = { a: 1 };
+ tools.probe_beta = defineTool({
+ description: "probe beta",
+ inputSchema: { type: "object" },
+ execute() {
+ return { target: url, cred };
+ },
+ });
+ }
+
+ return tools;
+ },
+ },
+});
+`;
+
+ const { callHandler } = await transformAndEval("tools/reference-analysis.ts", source);
+ const tools = await callHandler();
+ const alpha = tools.probe_alpha as Record<string, unknown>;
+ const beta = tools.probe_beta as Record<string, unknown>;
+
+ expect(alpha.__closureVars).toEqual({});
+ expect((alpha.execute as Function)({ q: "one" })).toEqual({
+ note: "answer from app tools only",
+ url: "/x/one",
+ });
+ expect(beta.__closureVars).toEqual({
+ cred: { a: 1 },
+ url: "https://example.com",
+ });
+ expect((beta.execute as Function)()).toEqual({
+ cred: { a: 1 },
+ target: "https://example.com",
+ });
+ });
+
+ it("captures computed keys and defaults inside binding patterns", async () => {
+ const source = `
+import { defineDynamic, defineTool } from "eve/tools";
+
+export default defineDynamic({
+ events: {
+ "session.started": async () => {
+ const fallback = "missing";
+ const field = "value";
+ return {
+ tool: defineTool({
+ description: "T",
+ inputSchema: { type: "object" },
+ execute(input) {
+ const { [field]: value = fallback } = input;
+ return value;
+ },
+ }),
+ };
+ },
+ },
+});
+`;
+
+ const { callHandler } = await transformAndEval("tools/binding-patterns.ts", source);
+ const tools = await callHandler();
+ const tool = tools.tool as Record<string, unknown>;
+ const execute = tool.execute as Function;
+
+ expect(tool.__closureVars).toEqual({
+ fallback: "missing",
+ field: "value",
+ });
+ expect(execute({})).toBe("missing");
+ expect(execute({ value: "present" })).toBe("present");
+ });
+
+ it("captures a direct identifier in an arrow expression body", async () => {
+ const source = `
+import { defineDynamic, defineTool } from "eve/tools";
+
+export default defineDynamic({
+ events: {
+ "session.started": async () => {
+ const result = "captured";
+ return {
+ tool: defineTool({
+ description: "T",
+ inputSchema: { type: "object" },
+ execute: () => result,
+ }),
+ };
+ },
+ },
+});
+`;
+
+ const { callHandler } = await transformAndEval("tools/identifier-expression.ts", source);
+ const tools = await callHandler();
+ const tool = tools.tool as Record<string, unknown>;
+
+ expect(tool.__closureVars).toEqual({ result: "captured" });
+ expect((tool.execute as Function)()).toBe("captured");
+ });
+
+ it("captures runtime references inside TypeScript expressions", async () => {
+ const source = `
+import { defineDynamic, defineTool } from "eve/tools";
+
+export default defineDynamic({
+ events: {
+ "session.started": async () => {
+ const TypeName = "type-only";
+ const asserted = "asserted";
+ const nonNull = "non-null";
+ const satisfied = "satisfied";
+ return {
+ tool: defineTool({
+ description: "T",
+ inputSchema: { type: "object" },
+ execute() {
+ return [
+ asserted as TypeName,
+ nonNull!,
+ satisfied satisfies TypeName,
+ ];
+ },
+ }),
+ };
+ },
+ },
+});
+`;
+
+ const result = await transformDynamicToolExecute("tools/typescript-expressions.ts", source);
+
+ expect(result).not.toBeNull();
+ expect(result!.code).toContain("const { asserted, nonNull, satisfied } = __vars");
+ expect(result!.code).not.toContain("const { TypeName, asserted, nonNull, satisfied } = __vars");
+ });
+
it("async execute preserves await semantics", async () => {
const source = `
import { defineDynamic, defineTool } from "eve/tools";
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 7da4c8c3d..db1d30493 100644
--- a/packages/eve/src/internal/workflow-bundle/dynamic-tool-transform.ts
+++ b/packages/eve/src/internal/workflow-bundle/dynamic-tool-transform.ts
@@ -26,32 +26,10 @@
*/
import { parseWithNitroRolldownAst } from "#internal/bundler/nitro-rolldown.js";
-
-type AstNode = {
- argument?: AstNode | null;
- arguments?: AstNode[];
- async?: boolean;
- body?: AstNode | AstNode[] | { body?: AstNode[]; type?: string; start?: number; end?: number };
- callee?: AstNode;
- computed?: boolean;
- declaration?: AstNode | null;
- declarations?: AstNode[];
- end?: number;
- expression?: AstNode | null;
- id?: { name?: string; start?: number; end?: number } | null;
- init?: AstNode | null;
- key?: AstNode | null;
- kind?: string;
- left?: AstNode | null;
- method?: boolean;
- name?: string;
- params?: AstNode[];
- properties?: AstNode[];
- right?: AstNode | null;
- start?: number;
- type?: string;
- value?: AstNode | unknown;
-};
+import {
+ collectReferencedIdentifierNames,
+ type DynamicToolAstNode as AstNode,
+} from "#internal/workflow-bundle/dynamic-tool-ast-references.js";
interface HandlerInfo {
/** The handler function AST node */
@@ -80,6 +58,8 @@ interface ExecuteInfo {
params: string;
/** Body source (block statement including braces) */
body: string;
+ /** Function body AST used to identify actual identifier references */
+ bodyNode: AstNode;
/** Scope entries from nested functions between handler and this execute */
nestedScopes: readonly ScopeEntry[];
}
@@ -382,18 +362,22 @@ function walkForExecuteProps(
if (isFn || isMethod) {
const params = extractFnParams(source, fn);
const body = extractFnBody(source, fn);
+ const bodyNode = fn.body as AstNode | undefined;
const isAsync = fn.async === true;
- results.push({
- propStart: prop.start,
- propEnd: prop.end,
- fnSource: source.slice(fn.start, fn.end),
- isAsync,
- params,
- body,
- hoistedName: `__eve_dynamic_exec_${transformCounter++}`,
- nestedScopes,
- });
+ if (bodyNode) {
+ results.push({
+ propStart: prop.start,
+ propEnd: prop.end,
+ fnSource: source.slice(fn.start, fn.end),
+ isAsync,
+ params,
+ body,
+ bodyNode,
+ hoistedName: `__eve_dynamic_exec_${transformCounter++}`,
+ nestedScopes,
+ });
+ }
}
}
}
@@ -494,7 +478,7 @@ function applyTransform(source: string, handlers: HandlerInfo[]): { code: string
// Only capture vars the execute body actually references. This
// avoids TDZ errors when the execute is inside a nested function
// that runs before later handler-level declarations are initialized.
- const bodyText = exec.body;
+ const referencedNames = collectReferencedIdentifierNames(exec.bodyNode);
// Exclude names that collide with the execute function's own
// parameters — the hoisted function already has those as formal
@@ -503,8 +487,7 @@ function applyTransform(source: string, handlers: HandlerInfo[]): { code: string
const execParamNames = extractExecuteParamNames(exec.params);
const allVars = deduped.filter(
- (name) =>
- !execParamNames.has(name) && new RegExp(`\\b${escapeForRegex(name)}\\b`).test(bodyText),
+ (name) => !execParamNames.has(name) && referencedNames.has(name),
);
const varsObj = allVars.length > 0 ? `{ ${allVars.join(", ")} }` : "{}";
@@ -615,10 +598,6 @@ function findProperty(obj: AstNode, name: string): AstNode | undefined {
);
}
-function escapeForRegex(s: string): string {
- return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
-}
-
/**
* Splits a parameter string on top-level commas, respecting nested
* angle brackets (`<>`), parentheses, square brackets, and curly