The Open Framework for Building Agents
fix(eve): bind enclosing extension config for nested extension mounts (#4100)
prha436187609d0c
diff --git a/.changeset/nested-extension-mount-config.md b/.changeset/nested-extension-mount-config.mdnew file mode 100644index 000000000..b9f266741--- /dev/null+++ b/.changeset/nested-extension-mount-config.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Extensions mounted inside a contributed subagent can now read the enclosing extension's configuration. Previously the nested mount saw an unbound handle, so deriving its configuration from the parent extension failed with `Invalid extension config`.diff --git a/docs/extensions.md b/docs/extensions.mdindex f5db7c2c1..353747bc3 100644--- a/docs/extensions.md+++ b/docs/extensions.md@@ -93,6 +93,17 @@ Author a subagent under `extension/subagents/<id>/` using the same files as a suModules inside the contributed subagent can import the extension handle. For example, a tool under `extension/subagents/reviewer/tools/` can read the configuration bound by the consumer's `agent/extensions/crm.ts` mount.+A contributed subagent can mount another extension under `extension/subagents/<id>/extensions/` and derive that mount's configuration from its own extension's configuration:++```ts+// extension/subagents/reviewer/extensions/search.ts+import search from "@acme/search";++import crm from "../../../extension.js";++export default search({ apiKey: crm.config.searchApiKey });+```+### Build and optionally publishThe scaffold's `package.json` declares separate source and distribution roots:diff --git a/packages/eve/src/compiler/load-binding-namespace.ts b/packages/eve/src/compiler/load-binding-namespace.tsindex a1fb618e0..b4e3c05f5 100644--- a/packages/eve/src/compiler/load-binding-namespace.ts+++ b/packages/eve/src/compiler/load-binding-namespace.ts@@ -19,6 +19,17 @@ export interface ExtensionCompileMount {readonly entry?: NonNullable<AuthoredModuleLoadOptions["extension"]>["entry"];}+/**+ * Filesystem mounts enclosing `mountId`, outermost first. Extension subagents live at+ * `<mountId>/subagents/<id>`, so a nested mount id extends its enclosing mount ids.+ */+function ancestorMountEntries(mounts: ReadonlyMap<string, ExtensionCompileMount>, mountId: string) {+ return [...mounts.values()]+ .filter((mount) => mount.entry !== undefined && mountId.startsWith(`${mount.mountId}/`))+ .sort((left, right) => left.mountId.length - right.mountId.length)+ .map((mount) => ({ ...mount.entry!, mountId: mount.mountId }));+}+/** Loads one node's selected bindings with dependency ordering and per-phase caching. */export function createCompiledBindingNamespaceLoader(input: {readonly bindings?: Readonly<Record<string, AgentModuleBinding>>;@@ -90,6 +101,8 @@ async function loadCompiledBindingNamespace(input: {mountId,evaluationId: input.evaluationId,entry: mount?.entry,+ ancestors:+ input.mounts === undefined ? undefined : ancestorMountEntries(input.mounts, mountId),};return await loadAuthoredModuleNamespace(input.binding.backing.sourcePath, {externalDependencies: input.binding.backing.externalDependencies,diff --git a/packages/eve/src/compiler/mounted-extension.integration.test.ts b/packages/eve/src/compiler/mounted-extension.integration.test.tsindex d1a9403a0..c049b126d 100644--- a/packages/eve/src/compiler/mounted-extension.integration.test.ts+++ b/packages/eve/src/compiler/mounted-extension.integration.test.ts@@ -767,6 +767,130 @@ describe("mounted extension via directory form with override", () => {});});+describe("nested extension mounts", () => {+ it("binds enclosing extension config through nested mounts of a twice-mounted extension", async () => {+ const app = await createAppRoot("eve-nested-extension-config-", {+ files: {+ "agent/agent.mjs": 'export default { model: "openai/gpt-5.4" };',+ "agent/instructions.md": "Work with the available tools.",+ "agent/extensions/outer.mjs":+ 'import outer from "@acme/outer"; export default outer({ label: "from-outer" });',+ "agent/extensions/second.mjs":+ 'import outer from "@acme/outer"; export default outer({ label: "from-second" });',+ "node_modules/@acme/outer/package.json": JSON.stringify({+ name: "@acme/outer",+ type: "module",+ eve: { extension: { source: "source", dist: "extension" } },+ exports: { ".": "./extension/extension.mjs" },+ }),+ "node_modules/@acme/outer/extension/_manifest.json": compatibilityManifest({+ extension: 1,+ subagent: 6,+ config: 1,+ }),+ "node_modules/@acme/outer/extension/extension.mjs": [+ 'import { defineExtension } from "eve/extension";',+ "const config = { '~standard': { version: 1, vendor: 'test', validate: value => typeof value?.label === 'string' ? { value } : { issues: [{ message: 'label is required' }] } } };",+ "export default defineExtension({ config });",+ ].join("\n"),+ "node_modules/@acme/outer/extension/subagents/helper/agent.mjs":+ 'export default { model: "openai/gpt-5.4", description: "Help with labels" };',+ "node_modules/@acme/outer/extension/subagents/helper/extensions/inner.mjs": [+ 'import inner from "@acme/inner";',+ 'import outer from "../../../extension.mjs";',+ "export default inner({ label: outer.config.label });",+ ].join("\n"),+ "node_modules/@acme/inner/package.json": JSON.stringify({+ name: "@acme/inner",+ type: "module",+ eve: { extension: { source: "source", dist: "extension" } },+ exports: { ".": "./extension/extension.mjs" },+ }),+ "node_modules/@acme/inner/extension/_manifest.json": compatibilityManifest({+ extension: 1,+ subagent: 6,+ tool: 1,+ config: 1,+ }),+ "node_modules/@acme/inner/extension/extension.mjs": [+ 'import { defineExtension } from "eve/extension";',+ "const config = { '~standard': { version: 1, vendor: 'test', validate: value => ({ value }) } };",+ "export default defineExtension({ config });",+ ].join("\n"),+ "node_modules/@acme/inner/extension/tools/label.mjs": [+ 'import ext from "@acme/inner";',+ "const label = ext.config.label;",+ "export default { description: label, inputSchema: {}, execute: () => label };",+ ].join("\n"),+ "node_modules/@acme/inner/extension/subagents/deep/agent.mjs":+ 'export default { model: "openai/gpt-5.4", description: "Go deeper" };',+ "node_modules/@acme/inner/extension/subagents/deep/extensions/leaf.mjs": [+ 'import leaf from "@acme/leaf";',+ 'import inner from "../../../extension.mjs";',+ "export default leaf({ label: `${inner.config.label}/leaf` });",+ ].join("\n"),+ "node_modules/@acme/leaf/package.json": JSON.stringify({+ name: "@acme/leaf",+ type: "module",+ eve: { extension: { source: "source", dist: "extension" } },+ exports: { ".": "./extension/extension.mjs" },+ }),+ "node_modules/@acme/leaf/extension/_manifest.json": compatibilityManifest({+ extension: 1,+ tool: 1,+ config: 1,+ }),+ "node_modules/@acme/leaf/extension/extension.mjs": [+ 'import { defineExtension } from "eve/extension";',+ "const config = { '~standard': { version: 1, vendor: 'test', validate: value => typeof value?.label === 'string' ? { value } : { issues: [{ message: 'leaf label is required' }] } } };",+ "export default defineExtension({ config });",+ ].join("\n"),+ "node_modules/@acme/leaf/extension/tools/leaf_label.mjs": [+ 'import ext from "@acme/leaf";',+ "const label = ext.config.label;",+ "export default { description: label, inputSchema: {}, execute: () => label };",+ ].join("\n"),+ },+ });++ const { manifest, moduleMap } = await compileRuntimeGraph(app.appRoot);+ const moduleMapPath = join(app.appRoot, ".eve", "compile", "nested-map.mjs");+ const { code } = await bundleAuthoredModuleMapForGeneration({+ appRoot: app.appRoot,+ manifest,+ moduleMapPath,+ });+ await writeFile(moduleMapPath, code);+ const generated = (await import(`${moduleMapPath}?test=nested-config`)) as {+ default: typeof moduleMap;+ };+ // Each nested mount reads the configuration of the mounts that contributed its subagent,+ // through every level of nesting.+ for (const [mount, label] of [+ ["outer", "from-outer"],+ ["second", "from-second"],+ ] as const) {+ const helper = manifest.subagents.find((node) => node.name === `${mount}__helper`)!;+ const deep = manifest.subagents.find(+ (node) => node.name === "inner__deep" && node.parentNodeId === helper.nodeId,+ )!;+ for (const [node, toolName, expected] of [+ [helper, "inner__label", label],+ [deep, "leaf__leaf_label", `${label}/leaf`],+ ] as const) {+ const tool = node.agent.tools.find((entry) => entry.name === toolName)!;+ expect(tool.description).toBe(expected);+ for (const map of [moduleMap, generated.default]) {+ const definition = map.nodes[node.nodeId]!.modules[tool.sourceId]!.default as {+ execute: () => string;+ };+ expect(definition.execute()).toBe(expected);+ }+ }+ }+ });+});+describe("mounted extension subagent resources", () => {it("materializes extension subagent resources under a Windows-safe directory", async () => {const app = await createAppRoot("eve-mounted-extension-subagent-resources-", {diff --git a/packages/eve/src/internal/authored-module-loader.ts b/packages/eve/src/internal/authored-module-loader.tsindex 58786c07b..f06e1a439 100644--- a/packages/eve/src/internal/authored-module-loader.ts+++ b/packages/eve/src/internal/authored-module-loader.ts@@ -49,17 +49,24 @@ const AUTHORED_MODULE_BUNDLE_DIRECTORY_PATH = join("authored-modules",);+export interface ExtensionMountEntry {+ readonly mountSourcePath: string;+ readonly packageName: string;+ readonly sourceRoot: string;+ readonly specifier: string;+}+export interface AuthoredModuleLoadOptions {readonly externalDependencies?: readonly string[];readonly extension?: {readonly mountId: string;/** Only filesystem mounts need a synthetic entry to bind their configuration. */- readonly entry?: {- readonly mountSourcePath: string;- readonly packageName: string;- readonly sourceRoot: string;- readonly specifier: string;- };+ readonly entry?: ExtensionMountEntry;+ /**+ * Filesystem mounts enclosing `mountId`, outermost first. A mount declared inside another+ * extension may read that extension's configuration, so those mounts bind first.+ */+ readonly ancestors?: readonly (ExtensionMountEntry & { readonly mountId: string })[];readonly evaluationId?: string;};}@@ -156,11 +163,15 @@ export async function bundleAuthoredModuleCode(const packageRoot = resolveAuthoredPackageRoot(modulePath);const mount = options.extension?.entry;const mountId = options.extension?.mountId;+ const mountChain =+ mount === undefined+ ? []+ : [...(options.extension?.ancestors ?? []), { ...mount, mountId: mountId! }];return await buildAuthoredModuleBundle(modulePath, options, {packageBoundaryPlugin: createRuntimeLoaderPackageBoundaryPlugin({externalDependencies: normalizeExternalDependencies(options.externalDependencies),packageRoot,- extensionSpecifier: mount?.specifier,+ extensionSpecifiers: new Set(mountChain.map((entry) => entry.specifier)),}),plugins: [...(mount === undefined@@ -173,16 +184,17 @@ export async function bundleAuthoredModuleCode(},load(id: string) {if (id !== "\0eve-compile-mount-entry") return undefined;- const mountImport = `${mount.mountSourcePath}?eve-mount=${encodeURIComponent(mountId!)}`;+ const mountImports = mountChain.map(+ (entry) =>+ `import ${JSON.stringify(`${entry.mountSourcePath}?eve-mount=${encodeURIComponent(entry.mountId)}`)};`,+ );const contribution = `${modulePath}?eve-mount=${encodeURIComponent(mountId!)}`;- return `import ${JSON.stringify(mountImport)}; export * from ${JSON.stringify(contribution)}; import entry from ${JSON.stringify(contribution)}; export default entry;`;+ return `${mountImports.join(" ")} export * from ${JSON.stringify(contribution)}; import entry from ${JSON.stringify(contribution)}; export default entry;`;},},]),createAuthoredWorkflowDirectivePlugin({ appRoot: packageRoot }),- ...(mount === undefined- ? []- : [createExtensionMountPlugin([{ ...mount, mountId: mountId! }])!]),+ ...(mount === undefined ? [] : [createExtensionMountPlugin(mountChain)!]),],sourcemap: "inline",});diff --git a/packages/eve/src/internal/authored-package-boundary.ts b/packages/eve/src/internal/authored-package-boundary.tsindex 205512f69..9036ef45d 100644--- a/packages/eve/src/internal/authored-package-boundary.ts+++ b/packages/eve/src/internal/authored-package-boundary.ts@@ -95,7 +95,7 @@ export function createGenerationPackageBoundaryPlugin(input: {export function createRuntimeLoaderPackageBoundaryPlugin(input: {readonly externalDependencies: readonly string[];readonly packageRoot: string;- readonly extensionSpecifier?: string;+ readonly extensionSpecifiers?: ReadonlySet<string>;}): Record<string, unknown> {const canonicalPackageRoot = toCanonicalPath(input.packageRoot);@@ -111,7 +111,7 @@ export function createRuntimeLoaderPackageBoundaryPlugin(input: {return undefined;}- if (source === input.extensionSpecifier) return undefined;+ if (input.extensionSpecifiers?.has(source) === true) return undefined;if (isFrameworkRuntimeImport(source, importer)) {return {external: true,diff --git a/packages/eve/src/internal/bundler/extension-mount-plugin.ts b/packages/eve/src/internal/bundler/extension-mount-plugin.tsindex f51471da3..97c2d845f 100644--- a/packages/eve/src/internal/bundler/extension-mount-plugin.ts+++ b/packages/eve/src/internal/bundler/extension-mount-plugin.ts@@ -42,11 +42,15 @@ export function createExtensionMountPlugin(return canonicalPath;};const roots = mounts.map((mount) => ({ ...mount, root: canonical(mount.sourceRoot) }));- const declarationPaths = new Map(- roots- .filter((mount) => mount.mountSourcePath !== undefined)- .map((mount) => [canonical(resolve(mount.mountSourcePath!)), mount]),- );+ // A mount file inside an extension subagent declares one mount per enclosing mount. Extension+ // subagents live at `<mountId>/subagents/<id>`, so a nested mount id extends its enclosing+ // mount ids; the trailing `/` keeps `a` from enclosing `ab/...`.+ const declarationPaths = new Map<string, (typeof roots)[number][]>();+ for (const mount of roots) {+ if (mount.mountSourcePath === undefined) continue;+ const path = canonical(resolve(mount.mountSourcePath));+ declarationPaths.set(path, [...(declarationPaths.get(path) ?? []), mount]);+ }const byId = new Map(roots.map((mount) => [mount.mountId, mount]));const overrideMounts = new Map([...overridePaths].map(([path, id]) => [canonical(path), byId.get(id)]),@@ -76,11 +80,31 @@ export function createExtensionMountPlugin(const cleanSource = query >= 0 ? source.slice(0, query) : source;const cleanImporter = importerQuery >= 0 ? importer!.slice(0, importerQuery) : importer;const importerPath = cleanImporter === undefined ? undefined : canonical(cleanImporter);+ const declarations =+ importerPath === undefined ? [] : (declarationPaths.get(importerPath) ?? []);const declarationMount =- importerPath === undefined ? undefined : declarationPaths.get(importerPath);+ declarations.length === 1+ ? declarations[0]+ : declarations.find(+ (candidate) =>+ inherited !== undefined && candidate.mountId.startsWith(`${inherited}/`),+ );+ // A nested mount file is loaded as its enclosing extension's source, but the extension it+ // mounts must bind that mount's own instance.+ const declaredSource =+ declarationMount !== undefined &&+ (cleanSource === declarationMount.specifier ||+ cleanSource === declarationMount.programmaticImport?.specifier)+ ? declarationMount+ : undefined;const overrideMount =importerPath === undefined ? undefined : overrideMounts.get(importerPath);- const mountId = tagged ?? inherited ?? declarationMount?.mountId ?? overrideMount?.mountId;+ const mountId =+ tagged ??+ declaredSource?.mountId ??+ inherited ??+ declarationMount?.mountId ??+ overrideMount?.mountId;const mount = mountId === undefined ? undefined : byId.get(mountId);if (mountId !== undefined && mount === undefined)throw new Error(`Unknown extension mount "${mountId}".`);@@ -122,9 +146,24 @@ export function createExtensionMountPlugin() {return { id: `${resolved.id}${MOUNT_QUERY}${encodeURIComponent(mountId!)}` };}- if (mount !== undefined) return resolved;- if (importer === undefined || importer.startsWith("\0")) return undefined;+ if (override) return resolved;+ if (mount === undefined && (importer === undefined || importer.startsWith("\0"))) {+ return undefined;+ }const owners = roots.filter((root) => within(path, root.root));+ if (mount !== undefined) {+ // Source owned by another extension keeps that extension's mount identity, so a mount+ // declared inside an extension reads the configuration its enclosing mount bound. When+ // the extension is mounted more than once, the enclosing mount disambiguates.+ const owner =+ owners+ .filter((candidate) => mount.mountId.startsWith(`${candidate.mountId}/`))+ .sort((left, right) => right.mountId.length - left.mountId.length)[0] ??+ (owners.length === 1 ? owners[0] : undefined);+ return owner === undefined+ ? resolved+ : { id: `${resolved.id}${MOUNT_QUERY}${encodeURIComponent(owner.mountId)}` };+ }if (owners.length > 1) {throw new Error(`Import "${source}" from "${importer}" refers to multiple extension mounts (${owners.map((owner) => owner.mountId).join(", ")}). Import it from an owned mount or contribution instead.`,