The Open Framework for Building Agents
Improve authored dependency load diagnostics (#1097)
prha64dbe2b2803d
diff --git a/.changeset/tidy-authored-load-errors.md b/.changeset/tidy-authored-load-errors.mdnew file mode 100644index 000000000..c7f4e7fd8--- /dev/null+++ b/.changeset/tidy-authored-load-errors.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Add actionable authored-module evaluation errors that identify installed packages and distinguish extensionless ESM from missing package output while preserving the original failure as the cause.diff --git a/packages/eve/src/internal/authored-module-evaluation-error.ts b/packages/eve/src/internal/authored-module-evaluation-error.tsnew file mode 100644index 000000000..3c7c04910--- /dev/null+++ b/packages/eve/src/internal/authored-module-evaluation-error.ts@@ -0,0 +1,115 @@+import { existsSync, readFileSync, statSync } from "node:fs";+import { dirname, extname, join, relative, resolve } from "node:path";+import { fileURLToPath } from "node:url";++interface ModuleLoadError extends Error {+ readonly code?: unknown;+ readonly url?: unknown;+}++interface InstalledPackageLocation {+ readonly name: string;+ readonly root: string;+}++/** Adds authored-module and installed-package context to Node evaluation failures. */+export function createAuthoredModuleEvaluationError(modulePath: string, cause: unknown): Error {+ const details = describeInstalledPackageLoadFailure(cause);++ return new Error(+ [+ "Failed to evaluate authored module:",+ ` ${modulePath}`,+ ...(details === undefined ? [] : ["", details]),+ ].join("\n"),+ { cause },+ );+}++function describeInstalledPackageLoadFailure(cause: unknown): string | undefined {+ if (!(cause instanceof Error)) return undefined;++ const error = cause as ModuleLoadError;+ if (error.code !== "ERR_MODULE_NOT_FOUND" || typeof error.url !== "string") {+ return undefined;+ }++ const missingPath = filePathFromUrl(error.url);+ if (missingPath === undefined || extname(missingPath) !== "") {+ return undefined;+ }++ const installedPackage = findInstalledPackage(missingPath);+ if (installedPackage === undefined) return undefined;++ const packageRelativePath = toPackageRelativePath(installedPackage.root, missingPath);+ if (findExistingModulePath(missingPath) !== undefined) {+ return [+ "Failed to load an installed package:",+ ` Package: ${installedPackage.name} (loaded outside the authored bundle)`,+ ` Import: ${packageRelativePath}`,+ " Reason: Node's ESM loader does not infer file extensions for relative imports.",+ " Hint: Use a Node-compatible package or entrypoint, or report the extensionless import to the package publisher.",+ ].join("\n");+ }++ return [+ "Failed to load an installed package:",+ ` Package: ${installedPackage.name} (loaded outside the authored bundle)`,+ ` Missing: ${packageRelativePath}`,+ " Reason: Package output may be incomplete, incorrectly installed, or incompatible with a standalone Node runtime.",+ " Hint: Verify the installed package version and output, use a Node-compatible entrypoint, or report the missing module to the package publisher.",+ ].join("\n");+}++function findExistingModulePath(path: string): string | undefined {+ for (const extension of [".js", ".mjs", ".cjs"]) {+ const candidate = `${path}${extension}`;+ try {+ if (statSync(candidate).isFile()) return candidate;+ } catch {+ // Try the next Node JavaScript extension.+ }+ }++ return undefined;+}++function toPackageRelativePath(packageRoot: string, path: string): string {+ return relative(packageRoot, path).replaceAll("\\", "/");+}++function filePathFromUrl(value: string): string | undefined {+ try {+ const url = new URL(value);+ return url.protocol === "file:" ? fileURLToPath(url) : undefined;+ } catch {+ return undefined;+ }+}++function findInstalledPackage(filePath: string): InstalledPackageLocation | undefined {+ let currentDirectory = dirname(resolve(filePath));++ while (true) {+ const manifestPath = join(currentDirectory, "package.json");+ if (existsSync(manifestPath) && isNodeModulesPath(manifestPath)) {+ try {+ const manifest = JSON.parse(readFileSync(manifestPath, "utf8")) as { name?: unknown };+ if (typeof manifest.name === "string" && manifest.name.length > 0) {+ return { name: manifest.name, root: currentDirectory };+ }+ } catch {+ return undefined;+ }+ }++ const parentDirectory = dirname(currentDirectory);+ if (parentDirectory === currentDirectory) return undefined;+ currentDirectory = parentDirectory;+ }+}++function isNodeModulesPath(filePath: string): boolean {+ return filePath.replaceAll("\\", "/").includes("/node_modules/");+}diff --git a/packages/eve/src/internal/authored-module-loader.scenario.test.ts b/packages/eve/src/internal/authored-module-loader.scenario.test.tsindex 4a7f6b15d..ad3993797 100644--- a/packages/eve/src/internal/authored-module-loader.scenario.test.ts+++ b/packages/eve/src/internal/authored-module-loader.scenario.test.ts@@ -57,6 +57,113 @@ describe("loadAuthoredModuleNamespace", () => {}});+ it("explains when an installed package contains Node-incompatible extensionless ESM", async () => {+ const app = await scenarioApp({+ files: {+ "agent/channels/eve.ts": [+ 'import { matchRoute } from "compiler-oriented-sdk/server";',+ "",+ 'export const result = matchRoute("/");',+ "",+ ].join("\n"),+ "node_modules/compiler-oriented-sdk/dist/server/index.js":+ 'export { matchRoute } from "./routeMatcher";\n',+ "node_modules/compiler-oriented-sdk/dist/server/routeMatcher.js":+ "export const matchRoute = () => true;\n",+ "node_modules/compiler-oriented-sdk/package.json": JSON.stringify({+ exports: { "./server": "./dist/server/index.js" },+ name: "compiler-oriented-sdk",+ type: "module",+ }),+ },+ name: "compiler-oriented-external-package",+ });+ const modulePath = join(app.appRoot, "agent", "channels", "eve.ts");++ let thrown: unknown;+ try {+ await loadAuthoredModuleNamespace(modulePath);+ } catch (error) {+ thrown = error;+ }++ expect(thrown).toBeInstanceOf(Error);+ const error = thrown as Error;+ expect(error.message).toContain(`Failed to evaluate authored module:\n ${modulePath}`);+ expect(error.message).toContain("Failed to load an installed package:");+ expect(error.message).toContain(+ " Package: compiler-oriented-sdk (loaded outside the authored bundle)",+ );+ expect(error.message).toContain(" Import: dist/server/routeMatcher");+ expect(error.message).not.toContain("routeMatcher.js");+ expect(error.message).toContain(+ " Reason: Node's ESM loader does not infer file extensions for relative imports.",+ );+ expect(error.message).toContain(" Hint: Use a Node-compatible package or entrypoint");+ expect(error.cause).toBeInstanceOf(Error);+ expect((error.cause as NodeJS.ErrnoException).code).toBe("ERR_MODULE_NOT_FOUND");+ });++ it("does not infer a compiler requirement when package output is simply missing", async () => {+ const app = await scenarioApp({+ files: {+ "agent/tools/use_sdk.ts": 'import "incomplete-sdk";\nexport const result = true;\n',+ "node_modules/incomplete-sdk/index.js": 'import "./generated";\n',+ "node_modules/incomplete-sdk/package.json": JSON.stringify({+ exports: "./index.js",+ name: "incomplete-sdk",+ type: "module",+ }),+ },+ name: "incomplete-external-package",+ });+ const modulePath = join(app.appRoot, "agent", "tools", "use_sdk.ts");++ let thrown: unknown;+ try {+ await loadAuthoredModuleNamespace(modulePath);+ } catch (error) {+ thrown = error;+ }++ expect(thrown).toBeInstanceOf(Error);+ const error = thrown as Error;+ expect(error.message).toContain("Failed to load an installed package:");+ expect(error.message).toContain(+ " Package: incomplete-sdk (loaded outside the authored bundle)",+ );+ expect(error.message).toContain(" Missing: generated");+ expect(error.message).toContain(+ " Reason: Package output may be incomplete, incorrectly installed",+ );+ expect(error.message).not.toContain("ESM loader does not infer");+ expect(error.cause).toMatchObject({ code: "ERR_MODULE_NOT_FOUND" });+ });++ it("preserves an authored module initialization failure as the evaluation cause", async () => {+ const app = await scenarioApp({+ files: {+ "agent/tools/throws.ts": 'throw new Error("authored initialization failed");\n',+ },+ name: "authored-initialization-failure",+ });+ const modulePath = join(app.appRoot, "agent", "tools", "throws.ts");++ let thrown: unknown;+ try {+ await loadAuthoredModuleNamespace(modulePath);+ } catch (error) {+ thrown = error;+ }++ expect(thrown).toBeInstanceOf(Error);+ const error = thrown as Error;+ expect(error.message).toContain(`Failed to evaluate authored module:\n ${modulePath}`);+ expect(error.message).not.toContain("Failed to load an installed package:");+ expect(error.message).not.toContain("Package:");+ expect(error.cause).toMatchObject({ message: "authored initialization failed" });+ });+it("resolves extensionless relative imports with dotted TypeScript basenames", async () => {const app = await scenarioApp({files: {diff --git a/packages/eve/src/internal/authored-module-loader.ts b/packages/eve/src/internal/authored-module-loader.tsindex 250b20a85..9dfb17ae4 100644--- a/packages/eve/src/internal/authored-module-loader.ts+++ b/packages/eve/src/internal/authored-module-loader.ts@@ -7,6 +7,7 @@ import { createCompiledModuleMapSource } from "#compiler/module-map.js";import { createAuthoredAssetImportPlugin } from "#internal/authored-asset-import-plugin.js";import { assertNoWorkflowDirectivePrologue } from "#internal/authored-directive-prologue.js";import { createAuthoredModuleBundleError } from "#internal/authored-module-bundle.js";+import { createAuthoredModuleEvaluationError } from "#internal/authored-module-evaluation-error.js";import { createAuthoredPackageTsConfigPathsPlugin } from "#internal/authored-package-tsconfig-paths.js";import {createExtensionScopePlugin,@@ -472,7 +473,11 @@ async function loadBundledAuthoredModule(writeFileSync(bundlePath, code);}- return await import(`${createFileImportSpecifier(bundlePath)}?v=${bundleHash}`);+ try {+ return await import(`${createFileImportSpecifier(bundlePath)}?v=${bundleHash}`);+ } catch (error) {+ throw createAuthoredModuleEvaluationError(modulePath, error);+ }}function createAuthoredRelativeExtensionResolverPlugin(input: {