The Open Framework for Building Agents
fix(eve): evaluate shared authored modules once per compile (#4115)
roboeve[bot]e40d7d73f847
diff --git a/.changeset/shared-compile-module-graph.md b/.changeset/shared-compile-module-graph.mdnew file mode 100644index 000000000..f56c92959--- /dev/null+++ b/.changeset/shared-compile-module-graph.md@@ -0,0 +1,5 @@+---+"eve": patch+---++`eve build` and `eve dev` now evaluate a module shared by several tools, channels, or other authored files once per compile instead of once per importing file. Compile memory now grows with the code an agent actually has, not with the number of files that import it, so agents with many tools over a shared SDK or workspace package no longer run out of memory on smaller build machines. Authored modules transpiled to CommonJS with an `__esModule` marker, such as a `tools/*.cjs` file with `exports.default = …`, now also compile and run correctly instead of resolving to the whole `exports` object. On Windows, CommonJS authored modules can now `require()` eve and other external packages.diff --git a/packages/eve/src/compiler/load-binding-namespace.ts b/packages/eve/src/compiler/load-binding-namespace.tsindex 6d0018101..488eb2fc0 100644--- a/packages/eve/src/compiler/load-binding-namespace.ts+++ b/packages/eve/src/compiler/load-binding-namespace.ts@@ -9,6 +9,7 @@ import {loadAuthoredModuleNamespace,type AuthoredModuleLoadOptions,} from "#internal/authored-module-loader.js";+import type { AuthoredModuleGraph } from "#internal/authored-module-graph.js";export type CompiledBindingNamespaceLoader = (sourceId: string,@@ -38,6 +39,7 @@ export function createCompiledBindingNamespaceLoader(input: {*/readonly appRoot: string | undefined;readonly bindings?: Readonly<Record<string, AgentModuleBinding>>;+ readonly graph?: AuthoredModuleGraph;readonly mounts?: ReadonlyMap<string, ExtensionCompileMount>;readonly evaluationId?: string;readonly mountSourceId?: (binding: AgentModuleBinding) => string | undefined;@@ -73,6 +75,7 @@ export function createCompiledBindingNamespaceLoader(input: {return await loadCompiledBindingNamespace({appRoot: input.appRoot,binding,+ graph: input.graph,loadDependency: (dependencySourceId) => load(dependencySourceId, nextLineage),registries: input.registries,mounts: input.mounts,@@ -89,6 +92,7 @@ export function createCompiledBindingNamespaceLoader(input: {async function loadCompiledBindingNamespace(input: {readonly appRoot: string | undefined;readonly binding: AgentModuleBinding;+ readonly graph?: AuthoredModuleGraph;readonly loadDependency: CompiledBindingNamespaceLoader;readonly mounts?: ReadonlyMap<string, ExtensionCompileMount>;readonly evaluationId?: string;@@ -115,6 +119,7 @@ async function loadCompiledBindingNamespace(input: {appRoot: input.binding.owner.kind === "application" ? input.appRoot : undefined,externalDependencies: input.binding.backing.externalDependencies,extension,+ graph: input.graph,});}const dependencyNamespaces = Object.fromEntries(diff --git a/packages/eve/src/compiler/module-lifecycle.ts b/packages/eve/src/compiler/module-lifecycle.tsindex 88a1af333..7ca31a5c8 100644--- a/packages/eve/src/compiler/module-lifecycle.ts+++ b/packages/eve/src/compiler/module-lifecycle.ts@@ -21,9 +21,11 @@ export class NodeModuleEvaluationContext {mounts?: Parameters<typeof createCompiledBindingNamespaceLoader>[0]["mounts"],evaluationId?: string,appRoot?: string,+ graph?: Parameters<typeof createCompiledBindingNamespaceLoader>[0]["graph"],) {this.loadNamespace = createCompiledBindingNamespaceLoader({appRoot,+ graph,mountSourceId,mounts,evaluationId,diff --git a/packages/eve/src/compiler/module-map.ts b/packages/eve/src/compiler/module-map.tsindex db6d0ebf8..f261ab40d 100644--- a/packages/eve/src/compiler/module-map.ts+++ b/packages/eve/src/compiler/module-map.ts@@ -90,7 +90,7 @@ export function createCompiledModuleMapSource(input: CreateCompiledModuleMapSourreturn {bindingName,importSpecifier: contribution ? undefined : specifier,- initializer: `memoizeModuleNamespaceFactories(${contribution ? `await import(${JSON.stringify(specifier)})` : `imported_${bindingName}`})`,+ initializer: `memoizeModuleNamespaceFactories(interopAuthoredModuleNamespace(${contribution ? `await import(${JSON.stringify(specifier)})` : `imported_${bindingName}`}))`,sourceId,};}@@ -131,7 +131,7 @@ export function createCompiledModuleMapSource(input: CreateCompiledModuleMapSour"// Generated by eve. Do not edit by hand.",...(usesProgrammaticLoader || modules.length > 0? [- `import { loadFrameworkProgrammaticModule as loadProgrammaticModule, memoizeModuleNamespaceFactories } from ${JSON.stringify(normalizeEsmImportSpecifier(input.programmaticLoaderImportSpecifier ?? "eve/internal/programmatic-source-loader"))};`,+ `import { interopAuthoredModuleNamespace, loadFrameworkProgrammaticModule as loadProgrammaticModule, memoizeModuleNamespaceFactories } from ${JSON.stringify(normalizeEsmImportSpecifier(input.programmaticLoaderImportSpecifier ?? "eve/internal/programmatic-source-loader"))};`,]: []),...imports,diff --git a/packages/eve/src/compiler/normalize-manifest.test.ts b/packages/eve/src/compiler/normalize-manifest.test.tsindex 8607c67ce..6c49cd002 100644--- a/packages/eve/src/compiler/normalize-manifest.test.ts+++ b/packages/eve/src/compiler/normalize-manifest.test.ts@@ -656,7 +656,8 @@ describe("compileAgentManifest source graph", () => {sourceRegistries: [sourceRegistry],});- expect(toolSourceIterations).toBe(1);+ // One read lists the module graph's entries; the other is the projection.+ expect(toolSourceIterations).toBe(2);expect(compiled.config.build?.externalDependencies).toEqual(["sharp"]);});@@ -1008,7 +1009,8 @@ describe("compileAgentManifest source graph", () => {}),).rejects.toThrow('Subagent "subagents/child" must define a non-empty description.');- expect(toolSourceIterations).toBe(1);+ // One read lists the module graph's entries; the other is the projection.+ expect(toolSourceIterations).toBe(2);});it("disables a lower-precedence framework slot without retaining a binding", async () => {diff --git a/packages/eve/src/compiler/normalize-manifest.ts b/packages/eve/src/compiler/normalize-manifest.tsindex 3204d0d07..e15be2cfa 100644--- a/packages/eve/src/compiler/normalize-manifest.ts+++ b/packages/eve/src/compiler/normalize-manifest.ts@@ -2,6 +2,10 @@ import { randomUUID } from "node:crypto";import type { ExtensionCompileMount } from "#compiler/load-binding-namespace.js";import { NodeModuleEvaluationContext } from "#compiler/module-lifecycle.js";import { assertStaticConnectionOwnership } from "#compiler/connection-ownership.js";+import {+ createAuthoredModuleGraph,+ type AuthoredModuleGraph,+} from "#internal/authored-module-graph.js";import { bindingMountId } from "#compiler/extension-mount-bindings.js";import type { AgentSourceManifest } from "#discover/manifest.js";@@ -87,7 +91,11 @@ import {withExtensionNamespace,} from "#compiler/normalize-manifest-helpers.js";import { summarizeCompilerDiagnostics, type CompilerDiagnostic } from "#compiler/diagnostics.js";-import { projectAgentSources, projectSelectedSources } from "#compiler/project-sources.js";+import {+ listApplicationModulePaths,+ projectAgentSources,+ projectSelectedSources,+} from "#compiler/project-sources.js";import {composeAgentModuleCandidates,createAgentModuleBinding,@@ -131,7 +139,14 @@ export async function compileAgentManifest(nodeId: ROOT_COMPILED_AGENT_NODE_ID,selection: options.developmentExtensions ?? noDevelopmentExtensions(),});- const compiler = new AgentGraphCompiler(context, registries, diagnostics);+ const compiler = new AgentGraphCompiler(+ context,+ registries,+ diagnostics,+ createAuthoredModuleGraph(listApplicationModulePaths(developmentExtensions.manifest), {+ appRoot: manifest.appRoot,+ }),+ );const root = await compiler.compileStaticNode({developmentExtensionCandidates: developmentExtensions.candidates,inheritedExternalDependencies: [],@@ -158,15 +173,18 @@ class AgentGraphCompiler {private readonly diagnostics: CompilerDiagnostic[];private readonly mounts = new Map<string, ExtensionCompileMount>();private readonly evaluationId = randomUUID();+ private readonly moduleGraph: AuthoredModuleGraph;constructor(context: ManifestCompileContext,registries: readonly AgentSourceRegistry[],diagnostics: CompilerDiagnostic[],+ moduleGraph: AuthoredModuleGraph,) {this.context = context;this.registries = registries;this.diagnostics = diagnostics;+ this.moduleGraph = moduleGraph;}async compileStaticNode(input: NodeCompileInput): Promise<CompiledLocalNodeResult> {@@ -433,6 +451,7 @@ class AgentGraphCompiler {this.mounts,this.evaluationId,input.manifest.appRoot,+ this.moduleGraph,);evaluation.setBindings(Object.fromEntries(diff --git a/packages/eve/src/compiler/project-sources.ts b/packages/eve/src/compiler/project-sources.tsindex 860d8bc50..fd8cde1eb 100644--- a/packages/eve/src/compiler/project-sources.ts+++ b/packages/eve/src/compiler/project-sources.ts@@ -176,6 +176,32 @@ export function projectAgentSources(input: {return { candidates, resources, subagents };}+/**+ * Lists the application module files a compile may evaluate, across local+ * subagents, so they can be bundled as one shared graph. Extension mounts load+ * with their own scope and are left out.+ */+export function listApplicationModulePaths(manifest: AgentSourceManifest): string[] {+ const sources: readonly { readonly logicalPath: string; readonly sourceKind: string }[] = [+ ...(manifest.configModule === undefined ? [] : [manifest.configModule]),+ ...(manifest.sandbox === null ? [] : [manifest.sandbox]),+ ...manifest.channels,+ ...manifest.connections,+ ...manifest.hooks,+ ...manifest.memories,+ ...manifest.tools,+ ...manifest.instructions,+ ...manifest.schedules,+ ...manifest.skills,+ ];+ return [+ ...sources.flatMap((source) =>+ source.sourceKind === "module" ? [join(manifest.agentRoot, source.logicalPath)] : [],+ ),+ ...manifest.subagents.flatMap((subagent) => listApplicationModulePaths(subagent.manifest)),+ ];+}+export function projectSelectedSources(input: {readonly candidates: Iterable<AgentSourceCandidate>;readonly resources: readonly ProjectedResourceSource[];diff --git a/packages/eve/src/internal/authored-module-build-options.ts b/packages/eve/src/internal/authored-module-build-options.tsnew file mode 100644index 000000000..33a282b1d--- /dev/null+++ b/packages/eve/src/internal/authored-module-build-options.ts@@ -0,0 +1,48 @@+import { existsSync } from "node:fs";+import { join } from "node:path";++import { createAuthoredAssetImportPlugin } from "#internal/authored-asset-import-plugin.js";+import { authoredModuleConditions } from "#internal/authored-module-conditions.js";+import { RESOLVE_EXTENSIONS } from "#internal/authored-package-boundary.js";+import { createAuthoredPackageTsConfigPathsPlugin } from "#internal/authored-package-tsconfig-paths.js";+import { createAuthoredRelativeExtensionResolverPlugin } from "#internal/authored-relative-extension-resolver.js";+import { createNodeEsmCompatBannerPlugin } from "#internal/node-esm-compat-banner.js";++/** Rolldown options shared by every authored module bundle of one package. */+export function createAuthoredModuleBuildOptions(input: {+ readonly packageBoundaryPlugin: Record<string, unknown>;+ readonly packageRoot: string;+ readonly plugins: readonly (object | null)[];+}): Record<string, unknown> {+ return {+ cwd: input.packageRoot,+ platform: "node",+ plugins: [+ ...input.plugins,+ createAuthoredRelativeExtensionResolverPlugin({ extensions: RESOLVE_EXTENSIONS }),+ createAuthoredAssetImportPlugin({ packageRoot: input.packageRoot }),+ createAuthoredPackageTsConfigPathsPlugin({+ appPackageRoot: input.packageRoot,+ extensions: RESOLVE_EXTENSIONS,+ }),+ createNodeEsmCompatBannerPlugin({ includeRequire: true }),+ input.packageBoundaryPlugin,+ ].filter((plugin) => plugin !== null),+ resolve: {+ conditionNames: authoredModuleConditions(),+ extensions: [...RESOLVE_EXTENSIONS],+ },+ tsconfig: resolveAuthoredTsConfigPath(input.packageRoot),+ };+}++export function resolveAuthoredTsConfigPath(packageRoot: string): string | false {+ for (const fileName of ["tsconfig.json", "jsconfig.json"]) {+ const path = join(packageRoot, fileName);+ if (existsSync(path)) {+ return path;+ }+ }++ return false;+}diff --git a/packages/eve/src/internal/authored-module-graph.ts b/packages/eve/src/internal/authored-module-graph.tsnew file mode 100644index 000000000..ebcd5bf5a--- /dev/null+++ b/packages/eve/src/internal/authored-module-graph.ts@@ -0,0 +1,102 @@+import { existsSync, mkdirSync, writeFileSync } from "node:fs";+import { join, resolve } from "node:path";++import { createAuthoredModuleBuildOptions } from "#internal/authored-module-build-options.js";+import {+ AUTHORED_BUNDLED_MODULE_EXTENSION,+ AUTHORED_MODULE_BUNDLE_DIRECTORY_PATH,+ createAuthoredWorkflowDirectivePlugin,+ resolveAuthoredPackageRoot,+} from "#internal/authored-module-loader.js";+import {+ createRuntimeLoaderPackageBoundaryPlugin,+ normalizeExternalDependencies,+} from "#internal/authored-package-boundary.js";+import { buildWithNitroRolldown } from "#internal/bundler/nitro-rolldown.js";++/**+ * Bundles a compile's application modules as one code-split graph per set of+ * external dependencies, so a module they share is evaluated once, as in the+ * runtime module map. A module bundled on its own evaluates a private copy of+ * everything it imports.+ */+export interface AuthoredModuleGraph {+ /** Returns the graph entry file for `modulePath`, or `undefined` to bundle it alone. */+ entryPath(+ modulePath: string,+ externalDependencies: readonly string[],+ ): Promise<string | undefined>;+}++export function createAuthoredModuleGraph(+ modulePaths: readonly string[],+ options: { readonly appRoot?: string } = {},+): AuthoredModuleGraph {+ const entries = [...new Set(modulePaths.map((modulePath) => resolve(modulePath)))].filter(+ (modulePath) => AUTHORED_BUNDLED_MODULE_EXTENSION.test(modulePath),+ );+ const builds = new Map<string, Promise<ReadonlyMap<string, string> | undefined>>();+ return {+ async entryPath(modulePath, externalDependencies) {+ const externals = normalizeExternalDependencies(externalDependencies);+ const key = externals.join("\0");+ let build = builds.get(key);+ if (build === undefined) {+ // Modules fall back to their own bundle, which reports any bundling error.+ build = writeAuthoredModuleGraph(entries, externals, options.appRoot).catch(+ () => undefined,+ );+ builds.set(key, build);+ }+ return (await build)?.get(resolve(modulePath));+ },+ };+}++async function writeAuthoredModuleGraph(+ modulePaths: readonly string[],+ externalDependencies: readonly string[],+ appRoot: string | undefined,+): Promise<ReadonlyMap<string, string>> {+ const entryPaths = new Map<string, string>();+ if (modulePaths.length === 0) return entryPaths;+ const packageRoot = resolveAuthoredPackageRoot(modulePaths[0]!);+ const inputs = new Map(+ modulePaths+ .filter((modulePath) => resolveAuthoredPackageRoot(modulePath) === packageRoot)+ .map((modulePath, index) => [`entry-${index}`, modulePath]),+ );+ const result = await buildWithNitroRolldown({+ ...createAuthoredModuleBuildOptions({+ packageBoundaryPlugin: createRuntimeLoaderPackageBoundaryPlugin({+ externalDependencies: [...externalDependencies],+ packageRoot,+ }),+ packageRoot,+ plugins: [createAuthoredWorkflowDirectivePlugin({ appRoot: appRoot ?? packageRoot })],+ }),+ input: Object.fromEntries(inputs),+ // Each entry chunk must expose exactly its module's exports.+ preserveEntrySignatures: "strict",+ write: false,+ output: {+ chunkFileNames: "[name]-[hash].mjs",+ codeSplitting: true,+ comments: false,+ entryFileNames: "[name]-[hash].mjs",+ format: "esm",+ sourcemap: "inline",+ },+ });+ const directoryPath = join(packageRoot, AUTHORED_MODULE_BUNDLE_DIRECTORY_PATH);+ mkdirSync(directoryPath, { recursive: true });+ for (const item of result.output) {+ if (item.type !== "chunk") continue;+ // File names carry a content hash, so an existing file already has this content.+ const filePath = join(directoryPath, item.fileName);+ if (!existsSync(filePath)) writeFileSync(filePath, item.code);+ const modulePath = item.isEntry ? inputs.get(item.name) : undefined;+ if (modulePath !== undefined) entryPaths.set(modulePath, filePath);+ }+ return entryPaths;+}diff --git a/packages/eve/src/internal/authored-module-loader.integration.test.ts b/packages/eve/src/internal/authored-module-loader.integration.test.tsindex 1270025a6..8c62d4bdb 100644--- a/packages/eve/src/internal/authored-module-loader.integration.test.ts+++ b/packages/eve/src/internal/authored-module-loader.integration.test.ts@@ -1,9 +1,12 @@import { mkdir, mkdtemp, rm, symlink, writeFile } from "node:fs/promises";import { tmpdir } from "node:os";import { basename, join } from "node:path";+import { pathToFileURL } from "node:url";import { describe, expect, it } from "vitest";+import { compileAgent } from "#compiler/compile-agent.js";+import type { CompiledModuleMap } from "#compiler/module-map.js";import { compileAgentManifest } from "#compiler/normalize-manifest.js";import { discoverAgent } from "#discover/discover-agent.js";import { resolveDiscoveryProject } from "#discover/project.js";@@ -13,7 +16,10 @@ import {bundleAuthoredModuleMapForGeneration,loadAuthoredModuleNamespace,} from "#internal/authored-module-loader.js";+import { loadCompiledModuleMapFromAuthoredSource } from "#internal/authored-module-map-loader.js";import { useTemporaryAppRoots } from "#internal/testing/use-temporary-app-roots.js";+import { createDiskRuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";+import { resolveRuntimeAgentGraph } from "#runtime/resolve-agent-graph.js";describe("loadAuthoredModuleNamespace", () => {const createAppRoot = useTemporaryAppRoots();@@ -1355,7 +1361,87 @@ export default defineWorkflowTool({ description: "Probe", inputSchema: { type: "}});- it.fails("evaluates a module shared by authored tools once per compilation", async () => {+ it.each([+ [+ "transpiled CommonJS",+ 'Object.defineProperty(exports, "__esModule", { value: true }); exports.default = tool;',+ ],+ ["CommonJS", "module.exports = tool;"],+ ])("compiles %s authored tool exports", async (_kind, exportStatement) => {+ const app = await createApp({+ files: {+ "agent/agent.ts": 'export default { model: "openai/gpt-5.4" };',+ "agent/tools/legacy.cjs": [+ 'const tool = { description: "Legacy tool.", execute() { return "ok"; } };',+ exportStatement,+ "",+ ].join("\n"),+ },+ name: "commonjs-authored-tool",+ });+ const discovered = await discoverAgent({+ agentRoot: join(app.appRoot, "agent"),+ appRoot: app.appRoot,+ });++ const compiled = await compileAgentManifest(discovered.manifest);++ expect(compiled.tools.find((tool) => tool.logicalPath === "tools/legacy.cjs")).toMatchObject({+ description: "Legacy tool.",+ hasExecute: true,+ });+ });++ it("resolves transpiled CommonJS authored modules from the runtime module map", async () => {+ const esModuleFlag = 'Object.defineProperty(exports, "__esModule", { value: true });';+ const app = await createApp({+ files: {+ "agent/agent.ts": 'export default { model: "openai/gpt-5.4" };',+ "agent/instructions.md": "Use the legacy tool.",+ "agent/sandbox/sandbox.cjs": [+ 'const { DefaultSandbox, defineSandbox } = require("eve/sandbox");',+ esModuleFlag,+ "const environment = DefaultSandbox.environment();",+ "exports.environment = environment;",+ "exports.default = defineSandbox(async () => await environment.open());",+ "",+ ].join("\n"),+ "agent/tools/legacy.cjs": [+ esModuleFlag,+ 'exports.default = { description: "Legacy tool.", execute() { return "ok"; } };',+ "",+ ].join("\n"),+ },+ name: "commonjs-runtime-module-map",+ });+ const { manifest } = await compileAgent({ startPath: app.appRoot });+ const moduleMapPath = join(app.appRoot, ".eve", "compile", "generation-module-map.mjs");+ const { code } = await bundleAuthoredModuleMapForGeneration({+ appRoot: app.appRoot,+ manifest,+ moduleMapPath,+ });+ await writeFile(moduleMapPath, code);+ const moduleMaps = {+ // What `eve build` output and the `eve dev` host import.+ generation: (+ (await import(pathToFileURL(moduleMapPath).href)) as { default: CompiledModuleMap }+ ).default,+ // What `eve eval`, sandbox prewarm, and the compiled-agent cache hydrate from source.+ authoredSource: await loadCompiledModuleMapFromAuthoredSource({+ compiledArtifactsSource: createDiskRuntimeCompiledArtifactsSource(app.appRoot),+ }),+ };++ for (const [path, moduleMap] of Object.entries(moduleMaps)) {+ const { root } = await resolveRuntimeAgentGraph({ manifest, moduleMap });+ const tool = root.agent.tools.find((entry) => entry.logicalPath === "tools/legacy.cjs");+ expect(await tool?.execute?.({}, {} as never), path).toBe("ok");+ expect(root.agent.sandbox, path).toMatchObject({ logicalPath: "sandbox/sandbox.cjs" });+ }+ });++ it("evaluates a module shared by authored tools once per compilation", async () => {const evaluationsKey = "__eveSharedAuthoredModuleEvaluations";const tool = (sharedImport: string) =>[diff --git a/packages/eve/src/internal/authored-module-loader.ts b/packages/eve/src/internal/authored-module-loader.tsindex db566ee4a..9b1391991 100644--- a/packages/eve/src/internal/authored-module-loader.ts+++ b/packages/eve/src/internal/authored-module-loader.ts@@ -6,6 +6,11 @@ import { extensionOverridePaths } from "#compiler/extension-mount-bindings.js";import type { CompiledAgentManifest } from "#compiler/manifest.js";import { createCompiledModuleMapSource } from "#compiler/module-map.js";import { createAuthoredAssetImportPlugin } from "#internal/authored-asset-import-plugin.js";+import {+ createAuthoredModuleBuildOptions,+ resolveAuthoredTsConfigPath,+} from "#internal/authored-module-build-options.js";+import type { AuthoredModuleGraph } from "#internal/authored-module-graph.js";import {createExtensionMountPlugin,EXTENSION_CHUNK_DIRECTORY,@@ -27,7 +32,7 @@ import {isNodeModulesPath,normalizeExternalDependencies,} from "#internal/authored-package-boundary.js";-import { expectObjectRecord } from "#internal/authored-module.js";+import { expectObjectRecord, interopAuthoredModuleNamespace } from "#internal/authored-module.js";import { normalizeEsmImportSpecifier } from "#internal/application/import-specifier.js";import { resolvePackageSourceFilePath } from "#internal/application/package.js";import {@@ -44,8 +49,8 @@ import {type WorkflowManifest,} from "#internal/workflow-bundle/workflow-builders.js";-const AUTHORED_BUNDLED_MODULE_EXTENSION = /\.[cm]?[jt]sx?$/;-const AUTHORED_MODULE_BUNDLE_DIRECTORY_PATH = join(+export const AUTHORED_BUNDLED_MODULE_EXTENSION = /\.[cm]?[jt]sx?$/;+export const AUTHORED_MODULE_BUNDLE_DIRECTORY_PATH = join("node_modules",".cache","eve",@@ -77,6 +82,8 @@ export interface AuthoredModuleLoadOptions {readonly ancestors?: readonly (ExtensionMountEntry & { readonly mountId: string })[];readonly evaluationId?: string;};+ /** Shares one evaluated module graph across the loads of one compilation. */+ readonly graph?: AuthoredModuleGraph;}/**@@ -141,7 +148,7 @@ async function doLoadAuthoredModuleNamespace(: await import(createFileImportSpecifier(modulePath));return expectObjectRecord(- loadedModule,+ interopAuthoredModuleNamespace(loadedModule),`Expected "${modulePath}" to export a module namespace object.`,);}@@ -541,31 +548,19 @@ async function buildAuthoredModuleBundle(},): Promise<string> {const packageRoot = resolveAuthoredPackageRoot(modulePath);- const tsconfigPath = resolveAuthoredTsConfigPath(packageRoot);- const plugins = [- ...configuration.plugins,- options.extension === undefined ? null : createFixedMountScopePlugin(options.extension.mountId),- createAuthoredRelativeExtensionResolverPlugin({ extensions: RESOLVE_EXTENSIONS }),- createAuthoredAssetImportPlugin({ packageRoot }),- createAuthoredPackageTsConfigPathsPlugin({- appPackageRoot: packageRoot,- extensions: RESOLVE_EXTENSIONS,- }),- createNodeEsmCompatBannerPlugin({ includeRequire: true }),- configuration.packageBoundaryPlugin,- ].filter((plugin) => plugin !== null);-try {const chunk = await buildSingleRolldownChunk(`authored module for "${modulePath}"`, {- cwd: packageRoot,+ ...createAuthoredModuleBuildOptions({+ packageBoundaryPlugin: configuration.packageBoundaryPlugin,+ packageRoot,+ plugins: [+ ...configuration.plugins,+ options.extension === undefined+ ? null+ : createFixedMountScopePlugin(options.extension.mountId),+ ],+ }),input: options.extension?.entry === undefined ? modulePath : "\0eve-compile-mount-entry",- platform: "node",- plugins,- resolve: {- conditionNames: authoredModuleConditions(),- extensions: [...RESOLVE_EXTENSIONS],- },- tsconfig: tsconfigPath,output: {comments: false,format: "esm",@@ -600,7 +595,7 @@ function createAuthoredDirectiveGuardPlugin(): Record<string, unknown> {// Client mode: steps keep their bodies, workflows become references. Step// registration happens once, in the host's step entrypoint.-function createAuthoredWorkflowDirectivePlugin(input: {+export function createAuthoredWorkflowDirectivePlugin(input: {readonly appRoot: string;readonly recorder?: AuthoredWorkflowSourceRecorder;}): Record<string, unknown> {@@ -632,6 +627,25 @@ async function loadBundledAuthoredModule(modulePath: string,options: AuthoredModuleLoadOptions,): Promise<unknown> {+ const graphEntryPath =+ options.extension === undefined+ ? await options.graph?.entryPath(modulePath, options.externalDependencies ?? [])+ : undefined;+ const specifier =+ graphEntryPath === undefined+ ? await writeAuthoredModuleBundle(modulePath, options)+ : createFileImportSpecifier(graphEntryPath);+ try {+ return await import(specifier);+ } catch (error) {+ throw createAuthoredModuleEvaluationError(modulePath, error);+ }+}++async function writeAuthoredModuleBundle(+ modulePath: string,+ options: AuthoredModuleLoadOptions,+): Promise<string> {const code = await bundleAuthoredModuleCode(modulePath, options);const externalDependencies = normalizeExternalDependencies(options.externalDependencies);@@ -655,14 +669,8 @@ async function loadBundledAuthoredModule(writeFileSync(bundlePath, code);}- try {- const instance = options.extension?.evaluationId ?? "";- return await import(- `${createFileImportSpecifier(bundlePath)}?v=${bundleHash}&instance=${encodeURIComponent(instance)}`- );- } catch (error) {- throw createAuthoredModuleEvaluationError(modulePath, error);- }+ const instance = options.extension?.evaluationId ?? "";+ return `${createFileImportSpecifier(bundlePath)}?v=${bundleHash}&instance=${encodeURIComponent(instance)}`;}function createInFlightModuleLoadKey(@@ -674,17 +682,6 @@ function createInFlightModuleLoadKey(return `${modulePath}\0${externalDependencies.join("\0")}\0${options.extension?.mountId ?? ""}\0${options.extension?.evaluationId ?? ""}\0${options.appRoot ?? ""}`;}-export function resolveAuthoredTsConfigPath(packageRoot: string): string | false {- for (const fileName of ["tsconfig.json", "jsconfig.json"]) {- const path = join(packageRoot, fileName);- if (existsSync(path)) {- return path;- }- }-- return false;-}-export function resolveAuthoredPackageRoot(modulePath: string): string {let currentDirectory = dirname(modulePath);diff --git a/packages/eve/src/internal/authored-module.ts b/packages/eve/src/internal/authored-module.tsindex 8f0663c23..633952bb9 100644--- a/packages/eve/src/internal/authored-module.ts+++ b/packages/eve/src/internal/authored-module.ts@@ -3,6 +3,22 @@ import type { JsonObject } from "#shared/json.js";import type { ModuleSourceRef } from "#shared/source-ref.js";import type { AgentModelOptionsDefinition, AgentToolExposure } from "#shared/agent-definition.js";+/**+ * Returns the exports of transpiled CommonJS as its module namespace. Bundlers+ * expose a CommonJS module's whole `exports` object as the ESM default, so a+ * module marked `__esModule` would otherwise read its namespace as+ * `{ default: { default, ...named } }`.+ */+export function interopAuthoredModuleNamespace(namespace: unknown): unknown {+ if (typeof namespace !== "object" || namespace === null) return namespace;+ const exports: unknown = Reflect.get(namespace, "default");+ return typeof exports === "object" &&+ exports !== null &&+ Reflect.get(exports, "__esModule") === true+ ? exports+ : namespace;+}+/*** Returns the selected authored module export from one namespace.*/diff --git a/packages/eve/src/internal/authored-package-boundary.ts b/packages/eve/src/internal/authored-package-boundary.tsindex 198a696a8..42902a36a 100644--- a/packages/eve/src/internal/authored-package-boundary.ts+++ b/packages/eve/src/internal/authored-package-boundary.ts@@ -1,6 +1,7 @@import { existsSync, readFileSync, realpathSync } from "node:fs";import { createRequire, isBuiltin } from "node:module";import { dirname, join, resolve, sep } from "node:path";+import { fileURLToPath } from "node:url";import { normalizeEsmImportSpecifier } from "#internal/application/import-specifier.js";import {@@ -59,7 +60,10 @@ export function createGenerationPackageBoundaryPlugin(input: {if (input.extensionSpecifiers?.has(source)) return undefined;if (isFrameworkRuntimeImport(source, importer)) {if (input.extensionSpecifiers?.has(source)) return undefined;- return { external: true, id: resolveFrameworkRuntimeImport(source) };+ return {+ external: true,+ id: toExternalModuleId(resolveFrameworkRuntimeImport(source), options.kind),+ };}// Package-private imports must be resolved before this bundle is moved@@ -85,7 +89,7 @@ export function createGenerationPackageBoundaryPlugin(input: {return {external: true,id: input.resolveExternalPaths- ? normalizeEsmImportSpecifier(externalModule.resolvedId)+ ? toExternalModuleId(normalizeEsmImportSpecifier(externalModule.resolvedId), options.kind): source,};},@@ -115,7 +119,7 @@ export function createRuntimeLoaderPackageBoundaryPlugin(input: {if (isFrameworkRuntimeImport(source, importer)) {return {external: true,- id: resolveRuntimeLoaderFrameworkImport(source),+ id: toExternalModuleId(resolveRuntimeLoaderFrameworkImport(source), options.kind),};}@@ -129,7 +133,13 @@ export function createRuntimeLoaderPackageBoundaryPlugin(input: {const resolvedPackageImport = resolvePackageImport(source, importer, input.packageRoot);if (resolvedPackageImport !== undefined) {return isFrameworkPackagePath(resolvedPackageImport)- ? { external: true, id: normalizeEsmImportSpecifier(resolvedPackageImport) }+ ? {+ external: true,+ id: toExternalModuleId(+ normalizeEsmImportSpecifier(resolvedPackageImport),+ options.kind,+ ),+ }: { id: resolvedPackageImport };}}@@ -147,7 +157,7 @@ export function createRuntimeLoaderPackageBoundaryPlugin(input: {return {external: true,- id: normalizeEsmImportSpecifier(resolvedId),+ id: toExternalModuleId(normalizeEsmImportSpecifier(resolvedId), options.kind),};}@@ -379,6 +389,14 @@ function isFrameworkPackagePath(path: string): boolean {return nearestPackageRoot(path) === canonicalFrameworkPackageRoot;}+/**+ * ESM imports need `file:` URLs for Windows absolute paths, but CommonJS+ * `require()` rejects URLs, so a `require()` of an external keeps its path.+ */+function toExternalModuleId(id: string, kind: string): string {+ return kind === "require-call" && id.startsWith("file:") ? fileURLToPath(id) : id;+}+function resolveExistingExternalFilePath(id: string): string | undefined {if (existsSync(id)) {return id;diff --git a/packages/eve/src/internal/bundler/nitro-rolldown.ts b/packages/eve/src/internal/bundler/nitro-rolldown.tsindex a1bc59a42..0bcfcdfa3 100644--- a/packages/eve/src/internal/bundler/nitro-rolldown.ts+++ b/packages/eve/src/internal/bundler/nitro-rolldown.ts@@ -12,6 +12,8 @@ export type RolldownOutputChunk = {readonly fileName: string;readonly imports: readonly string[];readonly dynamicImports: readonly string[];+ readonly isEntry: boolean;+ readonly name: string;};export type RolldownOutputAsset = {diff --git a/packages/eve/src/internal/development-programmatic-source-loader.ts b/packages/eve/src/internal/development-programmatic-source-loader.tsindex 33183ecff..8ef247a9b 100644--- a/packages/eve/src/internal/development-programmatic-source-loader.ts+++ b/packages/eve/src/internal/development-programmatic-source-loader.ts@@ -22,3 +22,4 @@ export async function loadFrameworkProgrammaticModule(}export { memoizeModuleNamespaceFactories } from "#compiler/source-graph.js";+export { interopAuthoredModuleNamespace } from "#internal/authored-module.js";diff --git a/packages/eve/src/internal/nitro/host/create-application-nitro.ts b/packages/eve/src/internal/nitro/host/create-application-nitro.tsindex c07c2609c..bfe6a93b5 100644--- a/packages/eve/src/internal/nitro/host/create-application-nitro.ts+++ b/packages/eve/src/internal/nitro/host/create-application-nitro.ts@@ -2,7 +2,7 @@ import { readFile } from "node:fs/promises";import { dirname, isAbsolute, join, relative, resolve } from "node:path";import { fileURLToPath } from "node:url";-import { resolveAuthoredTsConfigPath } from "#internal/authored-module-loader.js";+import { resolveAuthoredTsConfigPath } from "#internal/authored-module-build-options.js";import { createNitro } from "nitro/builder";import type { Nitro } from "nitro/types";import {diff --git a/packages/eve/src/internal/nitro/host/external-dependency-output-check-plugin.integration.test.ts b/packages/eve/src/internal/nitro/host/external-dependency-output-check-plugin.integration.test.tsindex 258d23709..f266c04f8 100644--- a/packages/eve/src/internal/nitro/host/external-dependency-output-check-plugin.integration.test.ts+++ b/packages/eve/src/internal/nitro/host/external-dependency-output-check-plugin.integration.test.ts@@ -55,6 +55,8 @@ async function checkOutput(input: {dynamicImports: [],fileName: "_chunks/db.mjs",imports: ["pg/lib/client"],+ isEntry: false,+ name: "chunk",type: "chunk",},"index.mjs": {@@ -62,6 +64,8 @@ async function checkOutput(input: {dynamicImports: ["pg"],fileName: "index.mjs",imports: ["_chunks/db.mjs", "zod"],+ isEntry: false,+ name: "chunk",type: "chunk",},},@@ -89,6 +93,8 @@ async function checkInstalledPackage(files: Readonly<Record<string, string>>) {dynamicImports: [],fileName: "index.mjs",imports: ["pg"],+ isEntry: false,+ name: "chunk",type: "chunk",},},diff --git a/packages/eve/src/internal/programmatic-source-loader.ts b/packages/eve/src/internal/programmatic-source-loader.tsindex 0466045c8..3be36ab89 100644--- a/packages/eve/src/internal/programmatic-source-loader.ts+++ b/packages/eve/src/internal/programmatic-source-loader.ts@@ -1,2 +1,3 @@export { loadFrameworkProgrammaticModule } from "#framework/sources/registry.js";export { memoizeModuleNamespaceFactories } from "#compiler/source-graph.js";+export { interopAuthoredModuleNamespace } from "#internal/authored-module.js";