Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat(eve): scope extension configuration to mounts (#3969)

prha7a33f3703430
diff --git a/.changeset/mount-config-isolation.md b/.changeset/mount-config-isolation.md
new file mode 100644
index 000000000..0517506b8
--- /dev/null
+++ b/.changeset/mount-config-isolation.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Isolate extension module instances and configuration per logical mount, including directory overrides and their subagents, while preserving asset imports and extension-owned dependencies. Durable extension state still uses package-scoped keys.
diff --git a/docs/extensions.md b/docs/extensions.md
index 61096a87c..1386f0a5a 100644
--- a/docs/extensions.md
+++ b/docs/extensions.md
@@ -193,7 +193,9 @@ For an extension with no configuration, mount its default export directly:
export { default } from "@acme/gizmo";
```
-The same mount shape works with an npm package, a workspace dependency, or a linked local package.
+The same mount shape works with an npm package, a workspace dependency, or a linked local package. Each mount binds its own configuration, even when two mounts use the same package. Moving or renaming a mount creates a new instance.
+
+Extension state still uses package-prefixed keys. Two stateful mounts of the same package in one context can share a state slot; application-defined state keys are unchanged.
### Use an extension in a workspace
diff --git a/e2e/fixtures/extensions/agent/extensions/toolkit-alt.ts b/e2e/fixtures/extensions/agent/extensions/toolkit-alt.ts
new file mode 100644
index 000000000..dc34e3bdc
--- /dev/null
+++ b/e2e/fixtures/extensions/agent/extensions/toolkit-alt.ts
@@ -0,0 +1,3 @@
+import toolkit from "toolkit-extension";
+
+export default toolkit({ apiKey: "sk-e2e-toolkit-alt", tier: "enterprise" });
diff --git a/e2e/fixtures/extensions/agent/mock-responder.ts b/e2e/fixtures/extensions/agent/mock-responder.ts
index acc52f4b3..cdff67d40 100644
--- a/e2e/fixtures/extensions/agent/mock-responder.ts
+++ b/e2e/fixtures/extensions/agent/mock-responder.ts
@@ -16,6 +16,19 @@ export function respond(request: MockModelRequest): MockModelResponse | string {
.join(" ");
}
+ if (message.includes("Alice is checking the primary account")) {
+ const lookups = [
+ { name: "toolkit__toolkit_lookup", input: { account: "primary" } },
+ { name: "toolkit-alt__toolkit_lookup", input: { account: "secondary" } },
+ ];
+ const next = lookups.find(
+ (lookup) => !request.toolResults.some((result) => result.name === lookup.name),
+ );
+ return next === undefined
+ ? JSON.stringify(request.toolResults.map((result) => result.output))
+ : { toolCalls: [next] };
+ }
+
if (!message.includes(`Call \`${LAYOUT_TOOL}\``)) {
return `Mock reply: ${message}`;
}
diff --git a/e2e/fixtures/extensions/evals/config-binding.eval.ts b/e2e/fixtures/extensions/evals/config-binding.eval.ts
index 8dc50b303..f84a709e2 100644
--- a/e2e/fixtures/extensions/evals/config-binding.eval.ts
+++ b/e2e/fixtures/extensions/evals/config-binding.eval.ts
@@ -1,16 +1,18 @@
import { defineEval } from "eve/evals";
export default defineEval({
- tags: ["real-model"],
- description: "Mounted extension tool returns the config bound at the mount site.",
+ description: "Two mounts of one extension keep their configured accounts separate.",
async test(t) {
await t.send(
- "Call the `toolkit__toolkit_lookup` tool with account 'acme' and report exactly what it returned.",
+ "Alice is checking the primary account and Bob is checking the secondary account. Use `toolkit__toolkit_lookup` with account 'primary' for Alice, then `toolkit-alt__toolkit_lookup` with account 'secondary' for Bob. Report each lookup result.",
);
t.succeeded();
t.calledTool("toolkit__toolkit_lookup", {
- output: { account: "acme", apiKey: "sk-e2e-toolkit", tier: "pro" },
+ output: { account: "primary", apiKey: "sk-e2e-toolkit", tier: "pro" },
+ });
+ t.calledTool("toolkit-alt__toolkit_lookup", {
+ output: { account: "secondary", apiKey: "sk-e2e-toolkit-alt", tier: "enterprise" },
});
},
});
diff --git a/packages/eve/src/client/agent-info-schema.ts b/packages/eve/src/client/agent-info-schema.ts
index a0a796dd7..7a1223c66 100644
--- a/packages/eve/src/client/agent-info-schema.ts
+++ b/packages/eve/src/client/agent-info-schema.ts
@@ -23,6 +23,7 @@ const moduleBacking = z.discriminatedUnion("kind", [
.strict()
.optional(),
kind: z.literal("filesystem"),
+ mountId: z.string().optional(),
sourcePath: z.string(),
})
.strict(),
@@ -30,6 +31,7 @@ const moduleBacking = z.discriminatedUnion("kind", [
.object({
dependencies: z.record(z.string(), z.string()).optional(),
kind: z.literal("programmatic"),
+ mountId: z.string().optional(),
moduleId: z.string(),
parameters: z.record(z.string(), z.unknown()).optional(),
registryId: z.string(),
diff --git a/packages/eve/src/client/client.test.ts b/packages/eve/src/client/client.test.ts
index c7bedfa65..e48266f2c 100644
--- a/packages/eve/src/client/client.test.ts
+++ b/packages/eve/src/client/client.test.ts
@@ -279,6 +279,45 @@ describe("Client request policy", () => {
},
);
+ it("accepts mount provenance for extension tools and application overrides", async () => {
+ const mountId = "extensions/crm";
+ const owners = [
+ { kind: "extension", mountId, namespace: "crm", packageName: "@acme/crm" },
+ { kind: "application" },
+ ];
+ const tools = owners.map((owner, index) => ({
+ binding: {
+ backing: {
+ kind: "filesystem",
+ sourcePath: `/app/tools/${index}.ts`,
+ externalDependencies: [],
+ mountId,
+ },
+ logicalPath: `tools/${index}.ts`,
+ owner,
+ },
+ description: "Read account",
+ hasAuth: false,
+ hasExecute: true,
+ hasModelOutputProjection: false,
+ hasOutputSchema: false,
+ inputSchema: {},
+ logicalPath: `tools/${index}.ts`,
+ name: `crm__${index}`,
+ owner,
+ requiresApproval: false,
+ sourceId: `tools/${index}.ts`,
+ sourceKind: "module",
+ }));
+ vi.spyOn(globalThis, "fetch").mockResolvedValue(
+ Response.json({ ...AGENT_INFO, tools: { ...AGENT_INFO.tools, static: tools } }),
+ );
+ const info = await new Client({ host: "https://eve.test" }).info();
+ expect(info.tools.static.map((tool) => tool.binding?.backing)).toEqual(
+ tools.map((tool) => tool.binding.backing),
+ );
+ });
+
it("accepts the legacy optional instrumentation field in v4 agent info", async () => {
const owner = { kind: "application" as const };
vi.spyOn(globalThis, "fetch").mockResolvedValue(
diff --git a/packages/eve/src/compiler/bundled-extension.ts b/packages/eve/src/compiler/bundled-extension.ts
index 8c1af6f02..8738f8ab0 100644
--- a/packages/eve/src/compiler/bundled-extension.ts
+++ b/packages/eve/src/compiler/bundled-extension.ts
@@ -1,4 +1,3 @@
-import { packageStateNamespace } from "#discover/extensions.js";
import {
defineProgrammaticExtensionMountDeclaration,
type ProgrammaticAgentSource,
@@ -7,6 +6,9 @@ import { resolveInstalledPackageInfo, resolvePackageRoot } from "#internal/appli
/** The small descriptor used for extensions shipped inside eve. */
export interface BundledExtensionDescriptor {
+ readonly entryPath: string;
+ readonly importSpecifier: string;
+ readonly config: Record<string, unknown>;
readonly loadMount: () => Promise<unknown>;
readonly namespace: string;
readonly sourceDirectory: string;
@@ -14,6 +16,9 @@ export interface BundledExtensionDescriptor {
export interface BundledExtensionMount {
readonly declaration: ProgrammaticAgentSource;
+ readonly entryPath: string;
+ readonly importSpecifier: string;
+ readonly config: Record<string, unknown>;
readonly namespace: string;
readonly packageName: string;
readonly packageRoot: string;
@@ -36,24 +41,16 @@ export function createBundledExtensionMount(
modules: [
{
logicalPath,
- loadNamespace: async () => {
- const container = globalThis as Record<symbol, unknown>;
- const scopeSymbol = Symbol.for("eve.ext-config-scope");
- const previousScope = container[scopeSymbol];
- container[scopeSymbol] = packageStateNamespace(packageName);
- try {
- return { default: await descriptor.loadMount() };
- } finally {
- if (previousScope === undefined) delete container[scopeSymbol];
- else container[scopeSymbol] = previousScope;
- }
- },
+ loadNamespace: async () => ({ default: await descriptor.loadMount() }),
},
],
});
return Object.freeze({
declaration,
+ entryPath: descriptor.entryPath,
+ importSpecifier: descriptor.importSpecifier,
+ config: descriptor.config,
namespace: descriptor.namespace,
packageName,
packageRoot,
diff --git a/packages/eve/src/compiler/development-extensions.integration.test.ts b/packages/eve/src/compiler/development-extensions.integration.test.ts
index aab8f35be..2ad3078d6 100644
--- a/packages/eve/src/compiler/development-extensions.integration.test.ts
+++ b/packages/eve/src/compiler/development-extensions.integration.test.ts
@@ -5,7 +5,10 @@ import {
getDevelopmentExtensionSourceRegistry,
prepareDevelopmentExtensions,
} from "#compiler/development-extensions.js";
-import { createProgrammaticCompiledModuleMap } from "#compiler/module-map.js";
+import {
+ createCompiledModuleMapSource,
+ createProgrammaticCompiledModuleMap,
+} from "#compiler/module-map.js";
import { compileAgentManifest } from "#compiler/normalize-manifest.js";
import { validateCompiledModuleMap } from "#compiler/validate-artifact.js";
import { createAgentSourceManifest } from "#discover/manifest.js";
@@ -54,6 +57,11 @@ describe("development extensions", () => {
getDevelopmentExtensionSourceRegistry(),
]);
expect(() => validateCompiledModuleMap(compiled, moduleMap)).not.toThrow();
+ const generated = createCompiledModuleMapSource({
+ manifest: compiled,
+ moduleMapPath: "/virtual/source-test/.eve/compile/module-map.mjs",
+ });
+ expect(generated).toContain("eve/self-modification?eve-mount=extensions%2Fself-modification");
});
it("does not replace an authored self-modification mount", async () => {
diff --git a/packages/eve/src/compiler/development-extensions.ts b/packages/eve/src/compiler/development-extensions.ts
index 3139d65f1..2f2505da6 100644
--- a/packages/eve/src/compiler/development-extensions.ts
+++ b/packages/eve/src/compiler/development-extensions.ts
@@ -14,11 +14,16 @@ import {
import type { AgentSourceManifest } from "#discover/manifest.js";
import { discoverBundledExtension } from "#discover/bundled-extension.js";
import { mountRefNamespace } from "#discover/extensions.js";
-import { resolvePackageSourceDirectoryPath } from "#internal/application/package.js";
+import {
+ resolvePackageSourceDirectoryPath,
+ resolvePackageSourceFilePath,
+} from "#internal/application/package.js";
// Keep this indirect so extension-contract declaration generation does not follow the dev-only mount.
const SELF_MODIFICATION_EXTENSION_MODULE = "#self-modification/extension/extension.js";
+const SELF_MODIFICATION_CONFIG = { local: { enabled: true } };
+
const DEVELOPMENT_EXTENSION_IDS = ["self-modification"] as const;
export type DevelopmentExtensionId = (typeof DEVELOPMENT_EXTENSION_IDS)[number];
@@ -39,10 +44,13 @@ function getBundledExtensionById(): ReadonlyMap<string, BundledExtensionMount> {
[
{
namespace: "self-modification",
+ importSpecifier: "eve/self-modification",
+ entryPath: resolvePackageSourceFilePath("src/self-modification/extension/extension.ts"),
+ config: SELF_MODIFICATION_CONFIG,
sourceDirectory: resolvePackageSourceDirectoryPath("src/self-modification/extension"),
loadMount: async () => {
const { default: extension } = await import(SELF_MODIFICATION_EXTENSION_MODULE);
- return extension({ local: { enabled: true } });
+ return extension(SELF_MODIFICATION_CONFIG);
},
},
] as const satisfies readonly BundledExtensionDescriptor[]
@@ -124,7 +132,10 @@ export async function prepareDevelopmentExtensions(input: {
nodeId: input.nodeId,
owner: { feature: extension.declaration.id, kind: "framework" },
registration: { applyTo: "root", source: extension.declaration },
- }),
+ }).map((candidate) => ({
+ ...candidate,
+ backing: { ...candidate.backing, mountId: `extensions/${extension.namespace}` },
+ })),
);
}
diff --git a/packages/eve/src/compiler/extension-mount-bindings.ts b/packages/eve/src/compiler/extension-mount-bindings.ts
new file mode 100644
index 000000000..d8305f347
--- /dev/null
+++ b/packages/eve/src/compiler/extension-mount-bindings.ts
@@ -0,0 +1,26 @@
+import type { CompiledAgentManifest } from "#compiler/manifest.js";
+import type { AgentModuleBinding } from "#compiler/source-graph.js";
+
+/** Mount association is independent of ownership: overrides stay application-owned. */
+export function bindingMountId(binding: AgentModuleBinding): string | undefined {
+ return binding.backing.mountId;
+}
+
+export function extensionOverridePaths(
+ manifest: CompiledAgentManifest,
+): ReadonlyMap<string, string> {
+ return new Map(
+ [manifest, ...manifest.subagents.map((node) => node.agent)].flatMap((node) =>
+ [
+ ...Object.values(node.bindings),
+ ...node.remoteAgents.map((remote) => remote.binding),
+ ].flatMap((binding) =>
+ binding.backing.kind === "filesystem" &&
+ binding.owner.kind === "application" &&
+ bindingMountId(binding) !== undefined
+ ? [[binding.backing.sourcePath, bindingMountId(binding)!] as const]
+ : [],
+ ),
+ ),
+ );
+}
diff --git a/packages/eve/src/compiler/extension-mount-evaluation.ts b/packages/eve/src/compiler/extension-mount-evaluation.ts
new file mode 100644
index 000000000..922481618
--- /dev/null
+++ b/packages/eve/src/compiler/extension-mount-evaluation.ts
@@ -0,0 +1,52 @@
+import { posix } from "node:path";
+
+import { bindingMountId } from "#compiler/extension-mount-bindings.js";
+import { NodeModuleEvaluationContext } from "#compiler/module-lifecycle.js";
+import type { NodeCompileInput } from "#compiler/normalize-manifest-types.js";
+import type { AgentSourceRegistry } from "#compiler/source-graph.js";
+import { mountRefNamespace, packageStateNamespace } from "#discover/extensions.js";
+import type { AuthoredModuleLoadOptions } from "#internal/authored-module-loader.js";
+
+export type ExtensionCompileMount = NonNullable<AuthoredModuleLoadOptions["mount"]>;
+
+export function createMountEvaluationContext(input: {
+ readonly node: NodeCompileInput;
+ readonly registries: readonly AgentSourceRegistry[];
+ readonly mounts: Map<string, ExtensionCompileMount>;
+ readonly evaluationId: string;
+}): NodeModuleEvaluationContext {
+ const sourceIds = new Map<string, string>();
+ for (const mount of input.node.manifest.resolvedExtensions) {
+ const mountId = posix.join(input.node.nodePath, "extensions", mount.namespace);
+ const declaration =
+ mount.programmaticDeclaration ??
+ input.node.manifest.extensions.find(
+ (ref) => mountRefNamespace(ref.logicalPath) === mount.namespace,
+ );
+ if (declaration === undefined) continue;
+ sourceIds.set(mountId, declaration.sourceId);
+ input.mounts.set(mountId, {
+ mountId,
+ mountSourcePath: posix.join(input.node.manifest.agentRoot, declaration.logicalPath),
+ packageName: mount.packageName,
+ packageNamespace: packageStateNamespace(mount.packageName),
+ sourceRoot: mount.sourceRoot,
+ specifier: mount.specifier,
+ ...(mount.programmaticDeclaration === undefined
+ ? {}
+ : {
+ programmaticImport: {
+ specifier: mount.programmaticDeclaration.importSpecifier,
+ entryPath: mount.programmaticDeclaration.entryPath,
+ config: mount.programmaticDeclaration.config,
+ },
+ }),
+ });
+ }
+ return new NodeModuleEvaluationContext(
+ input.registries,
+ (binding) => sourceIds.get(bindingMountId(binding) ?? ""),
+ input.mounts,
+ input.evaluationId,
+ );
+}
diff --git a/packages/eve/src/compiler/load-binding-namespace.ts b/packages/eve/src/compiler/load-binding-namespace.ts
index bb32840a3..e12e87fac 100644
--- a/packages/eve/src/compiler/load-binding-namespace.ts
+++ b/packages/eve/src/compiler/load-binding-namespace.ts
@@ -5,6 +5,8 @@ import {
memoizeModuleNamespaceFactories,
type ProgrammaticModuleNamespace,
} from "#compiler/source-graph.js";
+import { bindingMountId } from "#compiler/extension-mount-bindings.js";
+import type { ExtensionCompileMount } from "#compiler/extension-mount-evaluation.js";
import { packageStateNamespace } from "#discover/extensions.js";
import { loadAuthoredModuleNamespace } from "#internal/authored-module-loader.js";
@@ -15,6 +17,9 @@ export type CompiledBindingNamespaceLoader = (
/** Loads one node's selected bindings with dependency ordering and per-phase caching. */
export function createCompiledBindingNamespaceLoader(input: {
readonly bindings?: Readonly<Record<string, AgentModuleBinding>>;
+ readonly mounts?: ReadonlyMap<string, ExtensionCompileMount>;
+ readonly evaluationId?: string;
+ readonly mountSourceId?: (binding: AgentModuleBinding) => string | undefined;
readonly onLoad?: (sourceId: string) => void;
readonly registries: readonly AgentSourceRegistry[];
readonly resolveBinding?: (sourceId: string) => AgentModuleBinding | undefined;
@@ -39,11 +44,19 @@ export function createCompiledBindingNamespaceLoader(input: {
}
input.onLoad?.(sourceId);
const nextLineage = new Set(lineage).add(sourceId);
- const loading = loadCompiledBindingNamespace({
- binding,
- loadDependency: (dependencySourceId) => load(dependencySourceId, nextLineage),
- registries: input.registries,
- }).then(memoizeModuleNamespaceFactories);
+ const mountSourceId = input.mountSourceId?.(binding);
+ const loading = (async () => {
+ if (mountSourceId !== undefined && mountSourceId !== sourceId) {
+ await load(mountSourceId, nextLineage);
+ }
+ return await loadCompiledBindingNamespace({
+ binding,
+ loadDependency: (dependencySourceId) => load(dependencySourceId, nextLineage),
+ registries: input.registries,
+ mounts: input.mounts,
+ evaluationId: input.evaluationId,
+ });
+ })().then(memoizeModuleNamespaceFactories);
cache.set(sourceId, loading);
return loading;
};
@@ -54,12 +67,16 @@ export function createCompiledBindingNamespaceLoader(input: {
async function loadCompiledBindingNamespace(input: {
readonly binding: AgentModuleBinding;
readonly loadDependency: CompiledBindingNamespaceLoader;
+ readonly mounts?: ReadonlyMap<string, ExtensionCompileMount>;
+ readonly evaluationId?: string;
readonly registries: readonly AgentSourceRegistry[];
}): Promise<ProgrammaticModuleNamespace> {
if (input.binding.backing.kind === "filesystem") {
return await loadAuthoredModuleNamespace(input.binding.backing.sourcePath, {
externalDependencies: input.binding.backing.externalDependencies,
extensionScopeNamespace: resolveCompiledModuleExtensionScopeNamespace(input.binding),
+ mount: input.mounts?.get(bindingMountId(input.binding) ?? ""),
+ evaluationId: input.evaluationId,
});
}
const dependencyNamespaces = Object.fromEntries(
@@ -76,7 +93,7 @@ async function loadCompiledBindingNamespace(input: {
});
}
-/** Derives the stable package-owned scope used while loading an extension module. */
+/** Derives the legacy package-owned state scope used while loading an extension module. */
export function resolveCompiledModuleExtensionScopeNamespace(
binding: AgentModuleBinding,
): string | undefined {
diff --git a/packages/eve/src/compiler/manifest.ts b/packages/eve/src/compiler/manifest.ts
index 5b053f939..8d6a3f6a3 100644
--- a/packages/eve/src/compiler/manifest.ts
+++ b/packages/eve/src/compiler/manifest.ts
@@ -58,7 +58,7 @@ export const ROOT_COMPILED_AGENT_NODE_ID = "__root__";
/**
* Current compiled manifest schema version.
*/
-export const COMPILED_AGENT_MANIFEST_VERSION = 53;
+export const COMPILED_AGENT_MANIFEST_VERSION = 54;
/**
* Active compiled channel entry — backed by an authored `Channel` module.
@@ -372,6 +372,7 @@ const filesystemModuleBackingSchema = z
.object({
externalDependencies: z.array(z.string()).readonly(),
extensionScope: z.object({ namespace: z.string(), sourceRoot: z.string() }).strict().optional(),
+ mountId: z.string().optional(),
kind: z.literal("filesystem"),
sourcePath: z.string(),
})
@@ -381,6 +382,7 @@ const programmaticModuleBackingSchema = z
.object({
dependencies: z.record(z.string(), z.string()).readonly().optional(),
kind: z.literal("programmatic"),
+ mountId: z.string().optional(),
moduleId: z.string(),
parameters: jsonObjectSchema.optional(),
registryId: z.string(),
@@ -939,10 +941,20 @@ const compiledExtensionMountSchema: z.ZodType<CompiledExtensionMount> = z
externalDependencies: z.array(z.string()).readonly(),
namespace: z.string(),
packageName: z.string(),
+ specifier: z.string(),
mountId: mountIdSchema,
packageNamespace: z.string(),
sourceRoot: z.string(),
mountSourceId: z.string(),
+ mountSourcePath: z.string(),
+ programmaticImport: z
+ .object({
+ specifier: z.string(),
+ entryPath: z.string(),
+ config: z.record(z.string(), z.unknown()),
+ })
+ .strict()
+ .optional(),
mountLogicalPath: z.string(),
})
.strict();
@@ -1027,29 +1039,29 @@ const compiledSubagentNodeSchema: z.ZodType<CompiledSubagentNode> = z.union([
/**
* One mounted extension recorded on a compiled agent manifest. The runtime
* evaluates {@link mountLogicalPath} at module-map load so the mount's factory
- * call binds the extension's config before any tool runs.
+ * call binds the extension's config on its instance handle before any tool runs.
*/
export interface CompiledExtensionMount {
+ readonly programmaticImport?: {
+ readonly specifier: string;
+ readonly entryPath: string;
+ readonly config: Record<string, unknown>;
+ };
/** Runtime packages this extension requires the consuming application to externalize. */
readonly externalDependencies: readonly string[];
/** Mount-derived namespace that prefixes the extension's tool/skill names. */
readonly namespace: string;
readonly packageName: string;
+ /** Package export imported by the mount declaration. */
+ readonly specifier: string;
/** Canonical path of this mount in the root agent tree. */
readonly mountId: string;
- /**
- * Package-derived namespace that scopes durable state keys and config binding.
- * Unlike the logical consumer path in {@link mountId}, this stays stable when
- * the mount file is renamed, so persisted state is not orphaned.
- */
+ /** Package-derived namespace for durable extension state keys. */
readonly packageNamespace: string;
- /**
- * Absolute path to the extension's source root on disk. The extension-scope
- * bundler plugin treats any module under this root as extension-owned and
- * rewrites its `eve/context`/`eve/extension` imports to bake in the namespace.
- */
+ /** Absolute path to the extension's distributed source root. */
readonly sourceRoot: string;
readonly mountSourceId: string;
+ readonly mountSourcePath: string;
readonly mountLogicalPath: string;
}
diff --git a/packages/eve/src/compiler/module-lifecycle.ts b/packages/eve/src/compiler/module-lifecycle.ts
index 125b06d14..37166ebf5 100644
--- a/packages/eve/src/compiler/module-lifecycle.ts
+++ b/packages/eve/src/compiler/module-lifecycle.ts
@@ -15,8 +15,16 @@ export class NodeModuleEvaluationContext {
readonly #lifecycle = new NodeModuleLifecycle();
readonly loadNamespace: CompiledBindingNamespaceLoader;
- constructor(registries: readonly AgentSourceRegistry[]) {
+ constructor(
+ registries: readonly AgentSourceRegistry[],
+ mountSourceId?: (binding: AgentModuleBinding) => string | undefined,
+ mounts?: Parameters<typeof createCompiledBindingNamespaceLoader>[0]["mounts"],
+ evaluationId?: string,
+ ) {
this.loadNamespace = createCompiledBindingNamespaceLoader({
+ mountSourceId,
+ mounts,
+ evaluationId,
onLoad: (sourceId) => this.#lifecycle.recordCompileLoad(sourceId),
registries,
resolveBinding: (sourceId) => this.#bindings[sourceId],
diff --git a/packages/eve/src/compiler/module-map.ts b/packages/eve/src/compiler/module-map.ts
index 89a1d1c74..e89bdc93b 100644
--- a/packages/eve/src/compiler/module-map.ts
+++ b/packages/eve/src/compiler/module-map.ts
@@ -1,3 +1,4 @@
+import { bindingMountId } from "#compiler/extension-mount-bindings.js";
import { z } from "#compiled/zod/index.js";
import type {
CompiledAgentManifest,
@@ -38,6 +39,7 @@ interface BoundModule {
}
interface BoundNodeScope {
+ readonly mounts: CompiledAgentResources["extensionMounts"];
readonly modules: readonly BoundModule[];
readonly nodeId: string;
}
@@ -61,21 +63,43 @@ export function createCompiledModuleMapSource(input: CreateCompiledModuleMapSour
let index = 0;
let usesProgrammaticLoader = false;
const scopes: RenderedNodeScope[] = collectBoundNodeScopes(input.manifest).map((scope) => {
+ const mounts = new Map(scope.mounts.map((mount) => [mount.mountSourceId, mount]));
+ const mountSourceIds = new Map(
+ scope.mounts.map((mount) => [mount.mountId, mount.mountSourceId]),
+ );
const bindingNames = new Map(
scope.modules.map((module) => [module.sourceId, `module_${index++}`] as const),
);
+ const ordered = orderBoundModules(scope.modules, (binding) =>
+ mountSourceIds.get(bindingMountId(binding) ?? ""),
+ );
return {
- modules: scope.modules.map(({ binding, sourceId }) => {
+ modules: ordered.map(({ binding, sourceId }) => {
const bindingName = bindingNames.get(sourceId)!;
if (binding.backing.kind === "filesystem") {
- return {
- bindingName,
- importSpecifier: createImportSpecifier({
+ const specifier =
+ createImportSpecifier({
fromDirectory: moduleMapDirectory,
importSpecifierStyle,
targetPath: binding.backing.sourcePath,
- }),
- initializer: `memoizeModuleNamespaceFactories(imported_${bindingName})`,
+ }) +
+ (bindingMountId(binding) === undefined
+ ? ""
+ : `?eve-mount=${encodeURIComponent(bindingMountId(binding)!)}`);
+ const contribution = bindingMountId(binding) !== undefined && !mounts.has(sourceId);
+ return {
+ bindingName,
+ importSpecifier: contribution ? undefined : specifier,
+ initializer: `memoizeModuleNamespaceFactories(${contribution ? `await import(${JSON.stringify(specifier)})` : `imported_${bindingName}`})`,
+ sourceId,
+ };
+ }
+ const mount = mounts.get(sourceId);
+ if (mount?.programmaticImport !== undefined) {
+ const specifier = `${mount.programmaticImport.specifier}?eve-mount=${encodeURIComponent(mount.mountId)}`;
+ return {
+ bindingName,
+ initializer: `memoizeModuleNamespaceFactories({ default: (await import(${JSON.stringify(specifier)})).default(${JSON.stringify(mount.programmaticImport.config)}) })`,
sourceId,
};
}
@@ -105,13 +129,13 @@ export function createCompiledModuleMapSource(input: CreateCompiledModuleMapSour
return [
"// Generated by eve. Do not edit by hand.",
- ...(usesProgrammaticLoader || imports.length > 0
+ ...(usesProgrammaticLoader || modules.length > 0
? [
`import { loadFrameworkProgrammaticModule as loadProgrammaticModule, memoizeModuleNamespaceFactories } from ${JSON.stringify(normalizeEsmImportSpecifier(input.programmaticLoaderImportSpecifier ?? "eve/internal/programmatic-source-loader"))};`,
]
: []),
...imports,
- ...(usesProgrammaticLoader || imports.length > 0 ? [""] : []),
+ ...(usesProgrammaticLoader || modules.length > 0 ? [""] : []),
...initializers,
...(initializers.length > 0 ? [""] : []),
`export const moduleMap = ${renderModuleMap(scopes)};`,
@@ -132,7 +156,14 @@ export async function createProgrammaticCompiledModuleMap(
const bindings = Object.fromEntries(
scope.modules.map(({ binding, sourceId }) => [sourceId, binding]),
);
- const loadNamespace = createCompiledBindingNamespaceLoader({ bindings, registries });
+ const mountSourceIds = new Map(
+ scope.mounts.map((mount) => [mount.mountId, mount.mountSourceId]),
+ );
+ const loadNamespace = createCompiledBindingNamespaceLoader({
+ bindings,
+ registries,
+ mountSourceId: (binding) => mountSourceIds.get(bindingMountId(binding) ?? ""),
+ });
for (const { sourceId } of scope.modules) {
modules[sourceId] = await loadNamespace(sourceId);
}
@@ -162,7 +193,10 @@ export function collectRuntimeModuleBindingsForManifest(
);
}
-function orderBoundModules(modules: readonly BoundModule[]): readonly BoundModule[] {
+function orderBoundModules(
+ modules: readonly BoundModule[],
+ mountSourceId?: (binding: CompiledModuleBinding) => string | undefined,
+): readonly BoundModule[] {
const bySourceId = new Map(modules.map((module) => [module.sourceId, module]));
const ordered: BoundModule[] = [];
const visiting = new Set<string>();
@@ -173,6 +207,11 @@ function orderBoundModules(modules: readonly BoundModule[]): readonly BoundModul
throw new Error(`Compiled module dependency cycle includes "${module.sourceId}".`);
}
visiting.add(module.sourceId);
+ const mount = mountSourceId?.(module.binding);
+ if (mount !== undefined && mount !== module.sourceId) {
+ const dependency = bySourceId.get(mount);
+ if (dependency !== undefined) visit(dependency);
+ }
if (module.binding.backing.kind === "programmatic") {
for (const dependencySourceId of Object.values(module.binding.backing.dependencies ?? {})) {
const dependency = bySourceId.get(dependencySourceId);
@@ -207,12 +246,14 @@ function collectBoundNodeScopes(manifest: CompiledAgentManifest): readonly Bound
return [
{
modules: collectRuntimeModuleBindingsForManifest(manifest),
+ mounts: manifest.extensionMounts,
nodeId: ROOT_COMPILED_AGENT_NODE_ID,
},
...[...manifest.subagents]
.sort((left, right) => left.nodeId.localeCompare(right.nodeId))
.map((subagent) => ({
modules: collectRuntimeModuleBindingsForManifest(subagent.agent),
+ mounts: subagent.agent.extensionMounts,
nodeId: subagent.nodeId,
})),
];
diff --git a/packages/eve/src/compiler/mounted-extension.integration.test.ts b/packages/eve/src/compiler/mounted-extension.integration.test.ts
index cb248015d..41e51d7ae 100644
--- a/packages/eve/src/compiler/mounted-extension.integration.test.ts
+++ b/packages/eve/src/compiler/mounted-extension.integration.test.ts
@@ -1,10 +1,14 @@
-import { stat } from "node:fs/promises";
+import { mkdir, readdir, stat, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { compileAgent } from "#compiler/compile-agent.js";
+import { ContextContainer, contextStorage } from "#context/container.js";
+import { serializeContext } from "#context/serialize.js";
+import { ROOT_COMPILED_AGENT_NODE_ID } from "#compiler/manifest.js";
import { loadCompiledModuleMapFromAuthoredSource } from "#internal/authored-module-map-loader.js";
+import { bundleAuthoredModuleMapForGeneration } from "#internal/authored-module-loader.js";
import { useTemporaryAppRoots } from "#internal/testing/use-temporary-app-roots.js";
import { createDiskRuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";
import { loadCompiledManifest } from "#runtime/loaders/manifest.js";
@@ -41,6 +45,257 @@ async function compileRuntimeGraph(appRoot: string) {
* mount and tool modules. Deterministic guard for the config-binding regression.
*/
describe("mounted extension via authored-source loader", () => {
+ it("binds independent config for duplicate mounts and loaded application graphs", async () => {
+ const app = await createAppRoot("eve-independent-extension-config-", {
+ files: {
+ "agent/agent.mjs": 'export default { model: "openai/gpt-5.4" };',
+ "agent/instructions.md": "Work with the available tools.",
+ "agent/extensions/one/extension.mjs":
+ 'import ext from "@acme/crm"; export default ext({ account: "one" });',
+ "agent/extensions/one/tools/account.mjs": [
+ 'import ext from "@acme/crm";',
+ 'import { defineState } from "eve/context";',
+ 'const count = defineState("override-count", () => 0);',
+ 'export default { description: "Read overridden account", inputSchema: {}, execute: () => { count.update(n => n + 1); return { account: ext.config.account, count: count.get() }; } };',
+ ].join("\n"),
+ "agent/extensions/one/subagents/helper/agent.mjs":
+ 'export default { model: "openai/gpt-5.4", description: "Help with accounts" };',
+ "agent/extensions/one/subagents/helper/tools/peek.mjs":
+ 'import ext from "@acme/crm"; export default { description: "Read account", inputSchema: {}, execute: () => ext.config.account };',
+ "agent/extensions/two.mjs":
+ 'import ext from "@acme/crm"; export default ext({ account: "two" });',
+ "node_modules/@acme/crm/package.json": JSON.stringify({
+ name: "@acme/crm",
+ type: "module",
+ eve: { extension: { source: "source", dist: "extension" } },
+ exports: { ".": "./extension/extension.mjs" },
+ }),
+ "node_modules/@acme/crm/extension/_manifest.json": compatibilityManifest({
+ extension: 1,
+ tool: 1,
+ config: 1,
+ }),
+ "node_modules/@acme/crm/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/crm/extension/tools/account.mjs": [
+ 'import ext from "@acme/crm";',
+ 'import prompt from "./prompt.md?raw";',
+ 'import asset from "./badge.svg";',
+ "const account = ext.config.account; export default { description: account, inputSchema: {}, execute: () => ({ account, prompt, asset }) };",
+ ].join("\n"),
+ "node_modules/@acme/crm/extension/tools/prompt.md": "Account prompt",
+ "node_modules/@acme/crm/extension/tools/badge.svg": "<svg/>",
+ },
+ });
+ const first = await compileRuntimeGraph(app.appRoot);
+ expect(first.manifest.tools.find((tool) => tool.name === "two__account")?.description).toBe(
+ "two",
+ );
+ const second = await loadCompiledModuleMapFromAuthoredSource({
+ compiledArtifactsSource: createDiskRuntimeCompiledArtifactsSource(app.appRoot),
+ });
+ const read = (map: typeof first.moduleMap, name: string) => {
+ const tool = first.manifest.tools.find((entry) => entry.name === `${name}__account`)!;
+ return (
+ map.nodes[ROOT_COMPILED_AGENT_NODE_ID]!.modules[tool.sourceId]!.default as {
+ execute: () => unknown;
+ }
+ ).execute();
+ };
+ const accountResult = {
+ account: "two",
+ prompt: "Account prompt",
+ asset: "data:image/svg+xml;base64,PHN2Zy8+",
+ };
+ expect(read(first.moduleMap, "two")).toEqual(accountResult);
+ expect(read(second, "two")).toEqual(accountResult);
+ const helper = first.manifest.subagents.find((node) => node.name === "one__helper")!;
+ const peek = helper.agent.tools.find((tool) => tool.name === "peek")!;
+ expect(
+ (
+ first.moduleMap.nodes[helper.nodeId]!.modules[peek.sourceId]!.default as {
+ execute: () => string;
+ }
+ ).execute(),
+ ).toBe("one");
+ const context = new ContextContainer();
+ contextStorage.run(context, () => {
+ expect(read(first.moduleMap, "one")).toEqual({ account: "one", count: 1 });
+ expect(read(second, "one")).toEqual({ account: "one", count: 2 });
+ });
+ expect(Object.keys(serializeContext(context))).toContain("override-count");
+ expect(first.manifest.bindings["ext-override:one:tools/account.mjs"]?.owner.kind).toBe(
+ "application",
+ );
+
+ const moduleMapPath = join(app.appRoot, ".eve", "compile", "config-map.mjs");
+ const { code } = await bundleAuthoredModuleMapForGeneration({
+ appRoot: app.appRoot,
+ manifest: first.manifest,
+ moduleMapPath,
+ });
+ await writeFile(moduleMapPath, code);
+ const generated = (await import(`${moduleMapPath}?test=independent-config`)) as {
+ default: typeof first.moduleMap;
+ };
+ expect(read(generated.default, "two")).toEqual(accountResult);
+ });
+
+ it("allocates a new authored-source graph on each load", async () => {
+ const app = await createAppRoot("eve-fallback-generation-", {
+ files: {
+ "agent/agent.mjs": 'export default { model: "openai/gpt-5.4" };',
+ "agent/instructions.md": "Work with the available tools.",
+ "agent/extensions/one.mjs": 'import ext from "@acme/crm"; export default ext;',
+ "node_modules/@acme/crm/package.json": JSON.stringify({
+ name: "@acme/crm",
+ type: "module",
+ eve: { extension: { source: "source", dist: "extension" } },
+ exports: { ".": "./extension/extension.mjs" },
+ }),
+ "node_modules/@acme/crm/extension/_manifest.json": compatibilityManifest({ extension: 1 }),
+ "node_modules/@acme/crm/extension/extension.mjs": "export default { instance: {} };",
+ },
+ });
+ await compileAgent({ startPath: app.appRoot });
+ const source = createDiskRuntimeCompiledArtifactsSource(app.appRoot);
+ const maps = await Promise.all(
+ Array.from({ length: 4 }, () =>
+ loadCompiledModuleMapFromAuthoredSource({ compiledArtifactsSource: source }),
+ ),
+ );
+ const manifest = await loadCompiledManifest({ compiledArtifactsSource: source });
+ const id = manifest.extensionMounts[0]!.mountSourceId;
+ const instances = maps.map(
+ (map) => map.nodes[ROOT_COMPILED_AGENT_NODE_ID]!.modules[id]!.default,
+ );
+ expect(new Set(instances).size).toBe(4);
+ expect(
+ (await readdir(join(app.appRoot, ".eve", "compile"))).filter(
+ (name) => name.startsWith("authored-module-map-") && name.endsWith(".mjs"),
+ ),
+ ).toHaveLength(1);
+ });
+
+ it("isolates configured built-in extension mounts", async () => {
+ const app = await createAppRoot("eve-built-in-mounts-", {
+ files: {
+ "agent/agent.mjs": 'export default { model: "openai/gpt-5.4" };',
+ "agent/instructions.md": "Work with the available tools.",
+ "agent/extensions/one.mjs":
+ 'import code from "eve/extensions/code"; export default code({ worker: { model: "openai/gpt-5.4", reasoning: "high" } });',
+ "agent/extensions/two.mjs":
+ 'import code from "eve/extensions/code"; export default code({ worker: { model: "openai/gpt-5.4", reasoning: "low" } });',
+ },
+ });
+ const { manifest, moduleMap } = await compileRuntimeGraph(app.appRoot);
+ const workers = ["one", "two"].map((name) =>
+ manifest.subagents.find((subagent) => subagent.name === `${name}__worker`)!,
+ );
+ expect(workers[0]?.owner).toMatchObject({ mountId: "extensions/one" });
+ const reasoning = workers.map((worker) => {
+ if ("configResolver" in worker) throw new Error("Expected static worker config.");
+ const configSourceId = worker.agent.config.source.sourceId;
+ const definition = moduleMap.nodes[worker.nodeId]!.modules[configSourceId]!.default as {
+ model: { events: { "session.started": () => { reasoning: string } } };
+ };
+ return definition.model.events["session.started"]().reasoning;
+ });
+ expect(reasoning).toEqual(["high", "low"]);
+ const second = await loadCompiledModuleMapFromAuthoredSource({
+ compiledArtifactsSource: createDiskRuntimeCompiledArtifactsSource(app.appRoot),
+ });
+ const secondReasoning = workers.map((worker) => {
+ if ("configResolver" in worker) throw new Error("Expected static worker config.");
+ const definition = second.nodes[worker.nodeId]!.modules[worker.agent.config.source.sourceId]!
+ .default as {
+ model: { events: { "session.started": () => { reasoning: string } } };
+ };
+ return definition.model.events["session.started"]().reasoning;
+ });
+ expect(secondReasoning).toEqual(["high", "low"]);
+ });
+
+ it("keeps module instances distinct across mounts in a generation graph", async () => {
+ const app = await createAppRoot("eve-mount-instances-", {
+ files: {
+ "agent/agent.mjs": 'export default { model: "openai/gpt-5.4" };',
+ "agent/instructions.md": "Work with the available tools.",
+ "agent/extensions/one.mjs": 'import ext from "@acme/crm"; export default ext;',
+ "agent/extensions/two.mjs": 'import ext from "@acme/crm"; export default ext;',
+ "node_modules/@acme/crm/package.json": JSON.stringify({
+ name: "@acme/crm",
+ type: "module",
+ eve: { extension: { source: "source", dist: "extension" } },
+ exports: { ".": "./extension/extension.mjs" },
+ }),
+ "node_modules/@acme/crm/extension/_manifest.json": JSON.stringify({
+ ...JSON.parse(compatibilityManifest({ extension: 1, tool: 1 })),
+ formatVersion: 2,
+ build: { externalDependencies: ["nested-dependency"] },
+ }),
+ "node_modules/@acme/crm/node_modules/nested-dependency/package.json": JSON.stringify({
+ name: "nested-dependency",
+ type: "module",
+ exports: "./index.mjs",
+ }),
+ "node_modules/@acme/crm/node_modules/nested-dependency/index.mjs":
+ "export default 'nested-value';",
+ "node_modules/@acme/crm/extension/extension.mjs": 'export { default } from "./handle.mjs";',
+ "node_modules/@acme/crm/extension/handle.mjs":
+ "import value from 'nested-dependency'; export default { instance: { value } };",
+ "node_modules/@acme/crm/extension/tools/check.mjs":
+ 'import ext from "@acme/crm"; export default { description: "Check instance", inputSchema: {}, execute: () => ext.instance };',
+ },
+ });
+ const { manifest, moduleMap } = await compileRuntimeGraph(app.appRoot);
+ const fallbackModules = moduleMap.nodes[ROOT_COMPILED_AGENT_NODE_ID]!.modules;
+ const fallbackMounts = manifest.extensionMounts.map(
+ (mount) => (fallbackModules[mount.mountSourceId]!.default as { instance: object }).instance,
+ );
+ expect(fallbackMounts[0]).not.toBe(fallbackMounts[1]);
+ expect(fallbackMounts[0]).toEqual({ value: "nested-value" });
+ const nextGraph = await loadCompiledModuleMapFromAuthoredSource({
+ compiledArtifactsSource: createDiskRuntimeCompiledArtifactsSource(app.appRoot),
+ });
+ const nextModules = nextGraph.nodes[ROOT_COMPILED_AGENT_NODE_ID]!.modules;
+ expect(
+ (nextModules[manifest.extensionMounts[0]!.mountSourceId]!.default as { instance: object })
+ .instance,
+ ).not.toBe(fallbackMounts[0]);
+ for (const [index, mount] of manifest.extensionMounts.entries()) {
+ const tool = manifest.tools.find((entry) => entry.name === `${mount.namespace}__check`)!;
+ expect((fallbackModules[tool.sourceId]!.default as { execute: () => object }).execute()).toBe(
+ fallbackMounts[index],
+ );
+ }
+ const moduleMapPath = join(app.appRoot, ".eve", "compile", "mount-map.mjs");
+ const { code } = await bundleAuthoredModuleMapForGeneration({
+ appRoot: app.appRoot,
+ manifest,
+ moduleMapPath,
+ resolveExternalPaths: true,
+ });
+ await mkdir(join(app.appRoot, ".eve", "compile"), { recursive: true });
+ await writeFile(moduleMapPath, code);
+ const map = (await import(`${moduleMapPath}?test=mount-instances`)) as {
+ default: { nodes: Record<string, { modules: Record<string, Record<string, unknown>> }> };
+ };
+ const modules = map.default.nodes[ROOT_COMPILED_AGENT_NODE_ID]!.modules;
+ const mounts = manifest.extensionMounts;
+ const instances = mounts.map(
+ (mount) => (modules[mount.mountSourceId]!.default as { instance: object }).instance,
+ );
+ expect(instances[0]).not.toBe(instances[1]);
+ for (const [index, mount] of mounts.entries()) {
+ const tool = manifest.tools.find((entry) => entry.name === `${mount.namespace}__check`)!;
+ const definition = modules[tool.sourceId]!.default as { execute: () => object };
+ expect(definition.execute()).toBe(instances[index]);
+ }
+ });
it("binds mounted config so a composed tool reads it", async () => {
const app = await createAppRoot("eve-mounted-extension-authored-source-", {
files: {
diff --git a/packages/eve/src/compiler/normalize-manifest-helpers.ts b/packages/eve/src/compiler/normalize-manifest-helpers.ts
index e2e36b156..d64bd03ea 100644
--- a/packages/eve/src/compiler/normalize-manifest-helpers.ts
+++ b/packages/eve/src/compiler/normalize-manifest-helpers.ts
@@ -1,4 +1,7 @@
import { posix } from "node:path";
+import type { NodeModuleEvaluationContext } from "#compiler/module-lifecycle.js";
+import type { ComposedNodeSourceGraph, SelectedNodeConfig } from "#compiler/node-source-state.js";
+import { loadModuleBackedDefinition } from "#compiler/normalize-helpers.js";
import { mountRefNamespace, packageStateNamespace } from "#discover/extensions.js";
import type { AgentSourceManifest, LocalSubagentSourceRef } from "#discover/manifest.js";
@@ -12,7 +15,9 @@ import type { ModuleSourceRef } from "#shared/source-ref.js";
import { normalizeSubagentConfig } from "#compiler/normalize-subagent.js";
import {
canonicalSourceSlot,
+ createAgentModuleBinding,
extensionMountId,
+ isAgentModuleCandidate,
type AgentModuleCandidate,
type AgentSourceOwner,
type AgentSourceRegistry,
@@ -20,6 +25,33 @@ import {
type CompiledModuleBinding,
} from "#compiler/source-graph.js";
+export async function loadSelectedNodeConfig(
+ state: ComposedNodeSourceGraph,
+ evaluation: NodeModuleEvaluationContext,
+): Promise<SelectedNodeConfig> {
+ const candidate = state.composed.selected.get("agent");
+ if (candidate === undefined || !isAgentModuleCandidate(candidate)) {
+ throw new Error("Every local agent node requires a selected module-backed agent.ts source.");
+ }
+ const binding = createAgentModuleBinding(candidate);
+ const projected = state.sourcesBySourceId.get(candidate.sourceId);
+ if (projected?.source.sourceKind !== "module") {
+ throw new Error(`Selected agent config source "${candidate.sourceId}" was not projected.`);
+ }
+ const source = projected.source;
+ return {
+ binding,
+ candidate,
+ definition: await loadModuleBackedDefinition({
+ binding,
+ kind: "agent config",
+ loadNamespace: evaluation.loadNamespace,
+ source,
+ }),
+ source,
+ };
+}
+
export function collectSelectedSourceIds(composed: ComposedAgentModuleCandidates): Set<string> {
return new Set([...composed.selected.values()].map((candidate) => candidate.sourceId));
}
@@ -181,8 +213,19 @@ export function compileExtensionMounts(
externalDependencies: [...mount.externalDependencies],
mountLogicalPath: mountRef.logicalPath,
mountSourceId: mountRef.sourceId,
+ ...(mount.programmaticDeclaration === undefined
+ ? {}
+ : {
+ programmaticImport: {
+ specifier: mount.programmaticDeclaration.importSpecifier,
+ entryPath: mount.programmaticDeclaration.entryPath,
+ config: mount.programmaticDeclaration.config,
+ },
+ }),
+ mountSourcePath: posix.join(manifest.agentRoot, mountRef.logicalPath),
namespace: mount.namespace,
packageName: mount.packageName,
+ specifier: mount.specifier,
mountId: extensionMountId(nodePath, mount.namespace),
packageNamespace: packageStateNamespace(mount.packageName),
sourceRoot: mount.sourceRoot,
diff --git a/packages/eve/src/compiler/normalize-manifest-types.ts b/packages/eve/src/compiler/normalize-manifest-types.ts
index fd705e5ac..c6afeea6e 100644
--- a/packages/eve/src/compiler/normalize-manifest-types.ts
+++ b/packages/eve/src/compiler/normalize-manifest-types.ts
@@ -15,6 +15,7 @@ export interface CompileAgentManifestOptions {
}
export interface NodeCompileInput {
+ readonly mountId?: string;
readonly developmentExtensionCandidates?: readonly AgentModuleCandidate[];
readonly extensionScope?: { readonly namespace: string; readonly sourceRoot: string };
readonly inheritedExternalDependencies: readonly string[];
diff --git a/packages/eve/src/compiler/normalize-manifest.ts b/packages/eve/src/compiler/normalize-manifest.ts
index 0a1d25d16..628aa66df 100644
--- a/packages/eve/src/compiler/normalize-manifest.ts
+++ b/packages/eve/src/compiler/normalize-manifest.ts
@@ -1,3 +1,9 @@
+import { randomUUID } from "node:crypto";
+import {
+ createMountEvaluationContext,
+ type ExtensionCompileMount,
+} from "#compiler/extension-mount-evaluation.js";
+
import type { AgentSourceManifest } from "#discover/manifest.js";
import {
type CompiledAgentDefinition,
@@ -26,10 +32,7 @@ import {
ROOT_COMPILED_AGENT_NODE_ID,
} from "#compiler/manifest.js";
import { createCompiledRuntimeModelCatalogLoader } from "#compiler/model-catalog.js";
-import {
- markConfigRuntimeEntries,
- NodeModuleEvaluationContext,
-} from "#compiler/module-lifecycle.js";
+import { markConfigRuntimeEntries } from "#compiler/module-lifecycle.js";
import { compileAgentConfig } from "#compiler/normalize-agent-config.js";
import { compileChannelDefinition } from "#compiler/normalize-channel.js";
import { compileConnectionDefinition } from "#compiler/normalize-connection.js";
@@ -39,10 +42,7 @@ import {
assertFrameworkToolPolicy,
canDisableToolWithoutSelectedSource,
} from "#compiler/default-tool-policy.js";
-import {
- loadModuleBackedDefinition,
- type ManifestCompileContext,
-} from "#compiler/normalize-helpers.js";
+import type { ManifestCompileContext } from "#compiler/normalize-helpers.js";
import { resolveWorkspaceSubagentDefinition } from "#compiler/resolve-workspace-subagent.js";
import { workspaceSubagentName } from "#public/definitions/workspace-agent.js";
import { compileHookEntry } from "#compiler/normalize-hook.js";
@@ -62,7 +62,6 @@ import {
type ComposedNodeSourceGraph,
type FinalizedNodeSourceState,
type PhaseOneNodeSourceState,
- type SelectedNodeConfig,
} from "#compiler/node-source-state.js";
import {
assertApplicationOverlayCanApplyToAllNodes,
@@ -74,6 +73,7 @@ import {
createCompiledRemoteAgent,
expectSubagentDescription,
mergeExternalDependencies,
+ loadSelectedNodeConfig,
collectSelectedSourceIds,
withDiagnosticsSummary,
withExtensionNamespace,
@@ -154,6 +154,8 @@ class AgentGraphCompiler {
private readonly context: ManifestCompileContext;
private readonly registries: readonly AgentSourceRegistry[];
private readonly diagnostics: CompilerDiagnostic[];
+ private readonly mounts = new Map<string, ExtensionCompileMount>();
+ private readonly evaluationId = randomUUID();
constructor(
context: ManifestCompileContext,
@@ -224,6 +226,7 @@ class AgentGraphCompiler {
const nodeId = createCompiledSubagentNodeId(input.nodeId, source.sourceId);
const childInput: NodeCompileInput = {
extensionScope: projected.extensionScope ?? input.extensionScope,
+ mountId: projected.mountId,
inheritedExternalDependencies,
isRoot: false,
layer: projected.candidate.layer,
@@ -359,6 +362,7 @@ class AgentGraphCompiler {
const projected = projectAgentSources({
externalDependencies,
extensionScope: input.extensionScope,
+ mountId: input.mountId,
layer: input.layer,
manifest: input.manifest,
nodeId: input.nodeId,
@@ -437,7 +441,12 @@ class AgentGraphCompiler {
externalDependencies: readonly string[],
): Promise<PhaseOneNodeSourceState> {
const graph = this.composeNodeSources(input, externalDependencies);
- const evaluation = new NodeModuleEvaluationContext(this.registries);
+ const evaluation = createMountEvaluationContext({
+ node: input,
+ registries: this.registries,
+ mounts: this.mounts,
+ evaluationId: this.evaluationId,
+ });
evaluation.setBindings(
Object.fromEntries(
[...graph.composed.selected.values()]
@@ -448,34 +457,7 @@ class AgentGraphCompiler {
return {
evaluation,
graph,
- selectedConfig: await this.loadSelectedConfig(graph, evaluation),
- };
- }
-
- private async loadSelectedConfig(
- state: ComposedNodeSourceGraph,
- evaluation: NodeModuleEvaluationContext,
- ): Promise<SelectedNodeConfig> {
- const candidate = state.composed.selected.get("agent");
- if (candidate === undefined || !isAgentModuleCandidate(candidate)) {
- throw new Error("Every local agent node requires a selected module-backed agent.ts source.");
- }
- const binding = createAgentModuleBinding(candidate);
- const projected = state.sourcesBySourceId.get(candidate.sourceId);
- if (projected?.source.sourceKind !== "module") {
- throw new Error(`Selected agent config source "${candidate.sourceId}" was not projected.`);
- }
- const source = projected.source;
- return {
- binding,
- candidate,
- definition: await loadModuleBackedDefinition({
- binding,
- kind: "agent config",
- loadNamespace: evaluation.loadNamespace,
- source,
- }),
- source,
+ selectedConfig: await loadSelectedNodeConfig(graph, evaluation),
};
}
diff --git a/packages/eve/src/compiler/project-sources.ts b/packages/eve/src/compiler/project-sources.ts
index 8569c9e6b..7211daa4f 100644
--- a/packages/eve/src/compiler/project-sources.ts
+++ b/packages/eve/src/compiler/project-sources.ts
@@ -9,6 +9,7 @@ import type {
ScheduleSourceRef,
SkillSourceRef,
} from "#discover/manifest.js";
+import { mountRefNamespace } from "#discover/extensions.js";
import { stripLogicalPathExtension } from "#discover/filesystem.js";
import type { ModuleSourceRef } from "#shared/source-ref.js";
import type {
@@ -77,6 +78,7 @@ const MODULE_KIND_BY_SLOT_ROOT: Partial<
};
export interface ProjectedSubagentSource {
+ readonly mountId?: string;
readonly candidate: AgentResourceCandidate;
readonly nodePath: string;
readonly extensionScope?: { readonly namespace: string; readonly sourceRoot: string };
@@ -98,6 +100,7 @@ export function projectAgentSources(input: {
readonly nodeId: string;
readonly nodePath: string;
readonly owner?: AgentSourceOwner;
+ readonly mountId?: string;
}): ProjectedAgentSources {
const owner = input.owner ?? { kind: "application" as const };
const candidates: AgentSourceCandidate[] = [];
@@ -113,6 +116,13 @@ export function projectAgentSources(input: {
nodeId: input.nodeId,
subagentsPath: posix.join(input.nodePath, "subagents"),
owner,
+ mountId: input.mountId,
+ declarationMountIds: new Map(
+ input.manifest.extensions.map((source) => [
+ source.sourceId,
+ posix.join(input.nodePath, "extensions", mountRefNamespace(source.logicalPath)),
+ ]),
+ ),
resources,
subagents,
});
@@ -140,6 +150,7 @@ export function projectAgentSources(input: {
nodeId: input.nodeId,
subagentsPath: posix.join(mountId, "subagents"),
owner: extensionOwner,
+ mountId,
resources,
sourceIdPrefix: `ext:${mount.namespace}:`,
subagents,
@@ -154,6 +165,7 @@ export function projectAgentSources(input: {
nodeId: input.nodeId,
subagentsPath: posix.join(mountId, "subagents"),
owner: { kind: "application" },
+ mountId,
resources,
sourceIdPrefix: `ext-override:${mount.namespace}:`,
subagents,
@@ -190,6 +202,7 @@ function createFilesystemModuleCandidate(input: {
readonly logicalPath: string;
readonly nodeId: string;
readonly owner: AgentSourceOwner;
+ readonly mountId?: string;
readonly source: ModuleSourceRef;
readonly sourceId?: string;
readonly sourceRoot: string;
@@ -200,6 +213,7 @@ function createFilesystemModuleCandidate(input: {
? { extensionScope: input.extensionScope }
: {}),
kind: "filesystem" as const,
+ mountId: input.mountId,
sourcePath: join(input.sourceRoot, input.source.logicalPath),
};
return {
@@ -251,6 +265,7 @@ function createExtensionManifestSourceProjection(
function projectManifest(input: {
readonly candidates: AgentSourceCandidate[];
+ readonly declarationMountIds?: ReadonlyMap<string, string>;
readonly externalDependencies: readonly string[];
readonly projection: ManifestSourceProjection;
readonly layer: AgentSourceLayer;
@@ -258,13 +273,18 @@ function projectManifest(input: {
readonly nodeId: string;
readonly subagentsPath: string;
readonly owner: AgentSourceOwner;
+ readonly mountId?: string;
readonly resources: ProjectedResourceSource[];
readonly sourceIdPrefix?: string;
readonly subagents: ProjectedSubagentSource[];
}): void {
const { projection } = input;
const sourceId = (id: string) => `${input.sourceIdPrefix ?? ""}${id}`;
- const pushModule = (source: ModuleSourceRef, logicalPathOverride?: string) => {
+ const pushModule = (
+ source: ModuleSourceRef,
+ logicalPathOverride?: string,
+ mountId = input.mountId,
+ ) => {
const logicalPath = projection.logicalPath(logicalPathOverride ?? source.logicalPath);
const candidate = createFilesystemModuleCandidate({
externalDependencies: input.externalDependencies,
@@ -275,6 +295,7 @@ function projectManifest(input: {
logicalPath,
nodeId: input.nodeId,
owner: input.owner,
+ mountId,
source,
sourceId: sourceId(source.sourceId),
sourceRoot: input.manifest.agentRoot,
@@ -326,7 +347,9 @@ function projectManifest(input: {
canonicalSourceSlot(logicalPath) === "agent" ? undefined : "agent.ts",
);
}
- for (const source of input.manifest.extensions) pushModule(source);
+ for (const source of input.manifest.extensions) {
+ pushModule(source, undefined, input.declarationMountIds?.get(source.sourceId));
+ }
for (const source of input.manifest.channels) pushModule(source);
for (const source of input.manifest.connections) pushModule(source);
for (const source of input.manifest.hooks) pushModule(source);
@@ -371,6 +394,7 @@ function projectManifest(input: {
input.candidates.push(candidate);
input.subagents.push({
candidate,
+ mountId: input.mountId,
nodePath: posix.join(input.subagentsPath, source.subagentId),
...(projection.extensionScope === undefined
? {}
diff --git a/packages/eve/src/compiler/remote-agent-node.ts b/packages/eve/src/compiler/remote-agent-node.ts
index c08123b07..9f81f0e8e 100644
--- a/packages/eve/src/compiler/remote-agent-node.ts
+++ b/packages/eve/src/compiler/remote-agent-node.ts
@@ -52,12 +52,14 @@ export const compiledRemoteAgentNodeSchema: z.ZodType<CompiledRemoteAgentNode> =
.strict()
.optional(),
kind: z.literal("filesystem"),
+ mountId: z.string().optional(),
sourcePath: z.string(),
})
.strict(),
z
.object({
kind: z.literal("programmatic"),
+ mountId: z.string().optional(),
moduleId: z.string(),
registryId: z.string(),
revision: z.string(),
diff --git a/packages/eve/src/compiler/source-graph.test.ts b/packages/eve/src/compiler/source-graph.test.ts
index dc46fcc5e..e06f65892 100644
--- a/packages/eve/src/compiler/source-graph.test.ts
+++ b/packages/eve/src/compiler/source-graph.test.ts
@@ -47,14 +47,12 @@ function candidate(
describe("bundled extension declarations", () => {
it("registers a configured extension declaration without enumerating contributions", async () => {
- const loadMount = vi.fn(async () => {
- expect((globalThis as Record<symbol, unknown>)[Symbol.for("eve.ext-config-scope")]).toBe(
- "eve",
- );
- return { config: { enabled: true }, mounted: true };
- });
+ const loadMount = vi.fn(async () => ({ config: { enabled: true }, mounted: true }));
const mount = createBundledExtensionMount({
loadMount,
+ entryPath: "/packages/example/extension/extension.ts",
+ importSpecifier: "eve/example",
+ config: {},
namespace: "example",
sourceDirectory: "/packages/example/extension",
});
@@ -79,9 +77,6 @@ describe("bundled extension declarations", () => {
}),
).resolves.toEqual({ default: { config: { enabled: true }, mounted: true } });
expect(loadMount).toHaveBeenCalledOnce();
- expect(
- (globalThis as Record<symbol, unknown>)[Symbol.for("eve.ext-config-scope")],
- ).toBeUndefined();
});
});
diff --git a/packages/eve/src/compiler/source-graph.ts b/packages/eve/src/compiler/source-graph.ts
index 6ca76d1d6..1628db03e 100644
--- a/packages/eve/src/compiler/source-graph.ts
+++ b/packages/eve/src/compiler/source-graph.ts
@@ -151,6 +151,7 @@ export type AgentSourceForm = "derived" | "direct";
export type AgentModuleBacking =
| {
readonly externalDependencies: readonly string[];
+ readonly mountId?: string;
readonly extensionScope?: {
readonly namespace: string;
readonly sourceRoot: string;
@@ -160,6 +161,7 @@ export type AgentModuleBacking =
}
| {
readonly dependencies?: Readonly<Record<string, string>>;
+ readonly mountId?: string;
readonly kind: "programmatic";
readonly moduleId: string;
readonly parameters?: JsonObject;
diff --git a/packages/eve/src/discover/bundled-extension.test.ts b/packages/eve/src/discover/bundled-extension.test.ts
index 0bd21e4c5..2981ffddf 100644
--- a/packages/eve/src/discover/bundled-extension.test.ts
+++ b/packages/eve/src/discover/bundled-extension.test.ts
@@ -8,6 +8,9 @@ describe("discoverBundledExtension", () => {
it("discovers the complete extension tree without declared file entries", async () => {
const mount = createBundledExtensionMount({
loadMount: async () => ({}),
+ entryPath: "/package/extension/extension.ts",
+ importSpecifier: "eve/example",
+ config: {},
namespace: "example",
sourceDirectory: "/package/extension",
});
@@ -31,6 +34,9 @@ describe("discoverBundledExtension", () => {
"tools/nested/second.ts",
]);
expect(result.mount.programmaticDeclaration).toEqual({
+ entryPath: "/package/extension/extension.ts",
+ importSpecifier: "eve/example",
+ config: {},
logicalPath: "extensions/example.ts",
sourceId: `${mount.declaration.id}:extensions/example.ts`,
});
diff --git a/packages/eve/src/discover/bundled-extension.ts b/packages/eve/src/discover/bundled-extension.ts
index 44a369752..b6e7d0059 100644
--- a/packages/eve/src/discover/bundled-extension.ts
+++ b/packages/eve/src/discover/bundled-extension.ts
@@ -32,6 +32,9 @@ export async function discoverBundledExtension(input: {
packageName: input.mount.packageName,
packageRoot: input.mount.packageRoot,
programmaticDeclaration: {
+ importSpecifier: input.mount.importSpecifier,
+ entryPath: input.mount.entryPath,
+ config: input.mount.config,
logicalPath: declaration.logicalPath,
sourceId: `${input.mount.declaration.id}:${declaration.logicalPath}`,
},
diff --git a/packages/eve/src/discover/extensions.ts b/packages/eve/src/discover/extensions.ts
index 20ec3c631..496bec073 100644
--- a/packages/eve/src/discover/extensions.ts
+++ b/packages/eve/src/discover/extensions.ts
@@ -148,10 +148,8 @@ export function mountRefNamespace(logicalPath: string): string {
}
/**
- * Derives the namespace that scopes an extension's durable state keys and config
- * binding from its package name. Unlike the mount namespace, this stays keyed to
- * the package (e.g. `@acme/crm` → `acme-crm`) so renaming the consumer's mount
- * file never orphans persisted state.
+ * Derives the legacy durable state prefix from an extension's package name.
+ * Renaming the consumer's mount file does not change existing state keys.
*/
export function packageStateNamespace(packageName: string): string {
return (
diff --git a/packages/eve/src/discover/manifest.ts b/packages/eve/src/discover/manifest.ts
index 992d71862..f04fe0632 100644
--- a/packages/eve/src/discover/manifest.ts
+++ b/packages/eve/src/discover/manifest.ts
@@ -149,6 +149,9 @@ export type ExtensionSourceRef = ModuleSourceRef;
export interface ResolvedExtensionMount {
/** Programmatic declaration used when the mount does not exist on disk. */
readonly programmaticDeclaration?: {
+ readonly importSpecifier: string;
+ readonly entryPath: string;
+ readonly config: Record<string, unknown>;
readonly logicalPath: string;
readonly sourceId: string;
};
diff --git a/packages/eve/src/internal/authored-module-loader.ts b/packages/eve/src/internal/authored-module-loader.ts
index 09394fc70..0954d8edd 100644
--- a/packages/eve/src/internal/authored-module-loader.ts
+++ b/packages/eve/src/internal/authored-module-loader.ts
@@ -2,9 +2,12 @@ import { createHash } from "node:crypto";
import { existsSync, mkdirSync, realpathSync, writeFileSync } from "node:fs";
import { dirname, join, relative, resolve, sep } from "node:path";
+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 { createExtensionMountPlugin } from "#internal/bundler/extension-mount-plugin.js";
+import { createCompileMountPlugins } from "#internal/bundler/compile-mount-plugin.js";
import { authoredModuleConditions } from "#internal/authored-module-conditions.js";
import { createAuthoredModuleBundleError } from "#internal/authored-module-bundle.js";
import { createAuthoredModuleEvaluationError } from "#internal/authored-module-evaluation-error.js";
@@ -55,6 +58,20 @@ export interface AuthoredModuleLoadOptions {
* dependencies bundled with it) are scoped to this namespace at bundle time.
*/
readonly extensionScopeNamespace?: string;
+ readonly evaluationId?: string;
+ readonly mount?: {
+ readonly mountId: string;
+ readonly mountSourcePath: string;
+ readonly packageName: string;
+ readonly packageNamespace: string;
+ readonly sourceRoot: string;
+ readonly specifier: string;
+ readonly programmaticImport?: {
+ readonly specifier: string;
+ readonly entryPath: string;
+ readonly config: Record<string, unknown>;
+ };
+ };
}
/**
@@ -151,8 +168,12 @@ export async function bundleAuthoredModuleCode(
packageBoundaryPlugin: createRuntimeLoaderPackageBoundaryPlugin({
externalDependencies: normalizeExternalDependencies(options.externalDependencies),
packageRoot,
+ extensionSpecifier: options.mount?.specifier,
}),
- plugins: [createAuthoredWorkflowDirectivePlugin({ appRoot: packageRoot })],
+ plugins: [
+ ...createCompileMountPlugins(modulePath, options),
+ createAuthoredWorkflowDirectivePlugin({ appRoot: packageRoot }),
+ ],
sourcemap: "inline",
});
}
@@ -263,6 +284,7 @@ export interface AuthoredModuleMapBundle {
}
export async function bundleAuthoredModuleMapForGeneration(input: {
+ readonly resolveExternalPaths?: boolean;
readonly appRoot: string;
readonly manifest: CompiledAgentManifest;
readonly moduleMapPath: string;
@@ -288,11 +310,16 @@ export async function bundleAuthoredModuleMapForGeneration(input: {
moduleMapPath: input.moduleMapPath,
programmaticLoaderImportSpecifier,
});
+ const extensionMounts = [
+ input.manifest,
+ ...input.manifest.subagents.map((subagent) => subagent.agent),
+ ].flatMap((node) => node.extensionMounts);
const extensionScopePlugin = createExtensionScopePlugin(
[input.manifest, ...input.manifest.subagents.map((subagent) => subagent.agent)].flatMap(
(node) =>
node.extensionMounts.map((mount) => ({
packageNamespace: mount.packageNamespace,
+ mountId: mount.mountId,
sourceRoot: mount.sourceRoot,
})),
),
@@ -310,6 +337,7 @@ export async function bundleAuthoredModuleMapForGeneration(input: {
workflowFunctions: (id) => workflowSources.workflowFunctions(id),
}),
workflowSources.graphPlugin(),
+ createExtensionMountPlugin(extensionMounts, extensionOverridePaths(input.manifest)),
extensionScopePlugin,
createAuthoredRelativeExtensionResolverPlugin({ extensions: RESOLVE_EXTENSIONS }),
createAuthoredAssetImportPlugin({ packageRoot }),
@@ -318,7 +346,12 @@ export async function bundleAuthoredModuleMapForGeneration(input: {
extensions: RESOLVE_EXTENSIONS,
}),
createNodeEsmCompatBannerPlugin({ includeRequire: true }),
- createGenerationPackageBoundaryPlugin({ externalDependencies, packageRoot }),
+ createGenerationPackageBoundaryPlugin({
+ externalDependencies,
+ packageRoot,
+ extensionSpecifiers: new Set(extensionMounts.map((mount) => mount.specifier)),
+ resolveExternalPaths: input.resolveExternalPaths,
+ }),
].filter((plugin) => plugin !== null);
try {
@@ -475,7 +508,7 @@ async function buildAuthoredModuleBundle(
const tsconfigPath = resolveAuthoredTsConfigPath(packageRoot);
const plugins = [
...configuration.plugins,
- options.extensionScopeNamespace === undefined
+ options.mount !== undefined || options.extensionScopeNamespace === undefined
? null
: createFixedNamespaceScopePlugin(options.extensionScopeNamespace),
createAuthoredRelativeExtensionResolverPlugin({ extensions: RESOLVE_EXTENSIONS }),
@@ -491,7 +524,7 @@ async function buildAuthoredModuleBundle(
try {
const chunk = await buildSingleRolldownChunk(`authored module for "${modulePath}"`, {
cwd: packageRoot,
- input: modulePath,
+ input: options.mount === undefined ? modulePath : "\0eve-compile-mount-entry",
platform: "node",
plugins,
resolve: {
@@ -575,6 +608,8 @@ async function loadBundledAuthoredModule(
.update("\0")
.update(options.extensionScopeNamespace ?? "")
.update("\0")
+ .update(options.mount?.mountId ?? "")
+ .update("\0")
.update(code)
.digest("hex");
const bundleDirectoryPath = join(
@@ -589,7 +624,10 @@ async function loadBundledAuthoredModule(
}
try {
- return await import(`${createFileImportSpecifier(bundlePath)}?v=${bundleHash}`);
+ const instance = options.mount === undefined ? "" : (options.evaluationId ?? "");
+ return await import(
+ `${createFileImportSpecifier(bundlePath)}?v=${bundleHash}&instance=${encodeURIComponent(instance)}`
+ );
} catch (error) {
throw createAuthoredModuleEvaluationError(modulePath, error);
}
@@ -601,7 +639,7 @@ function createInFlightModuleLoadKey(
): string {
const externalDependencies = normalizeExternalDependencies(options.externalDependencies);
- return `${modulePath}\0${externalDependencies.join("\0")}\0${options.extensionScopeNamespace ?? ""}`;
+ return `${modulePath}\0${externalDependencies.join("\0")}\0${options.extensionScopeNamespace ?? ""}\0${options.mount?.mountId ?? ""}\0${options.mount === undefined ? "" : (options.evaluationId ?? "")}`;
}
export function resolveAuthoredTsConfigPath(packageRoot: string): string | false {
diff --git a/packages/eve/src/internal/authored-module-map-loader.ts b/packages/eve/src/internal/authored-module-map-loader.ts
index 4c1c0f800..9d04d456d 100644
--- a/packages/eve/src/internal/authored-module-map-loader.ts
+++ b/packages/eve/src/internal/authored-module-map-loader.ts
@@ -1,3 +1,5 @@
+import { createHash, randomUUID } from "node:crypto";
+import { link, mkdir, unlink, writeFile } from "node:fs/promises";
import { join, relative, resolve } from "node:path";
import { pathToFileURL } from "node:url";
@@ -15,14 +17,15 @@ import {
type CompiledModuleMap,
} from "#compiler/module-map.js";
import { loadFrameworkProgrammaticModule } from "#framework/sources/registry.js";
-import { loadAuthoredModuleNamespace } from "#internal/authored-module-loader.js";
+import {
+ bundleAuthoredModuleMapForGeneration,
+ loadAuthoredModuleNamespace,
+} from "#internal/authored-module-loader.js";
import { readMaterializedAuthoredModuleIndex } from "#internal/materialized-authored-modules.js";
import type { RuntimeDiskCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";
import { loadCompiledManifest } from "#runtime/loaders/manifest.js";
import { formatValidationError } from "#runtime/validation.js";
-const EXT_CONFIG_SCOPE = Symbol.for("eve.ext-config-scope");
-
/** Hydrates the compiled module map from the manifest’s authored bindings. */
export async function loadCompiledModuleMapFromAuthoredSource(input: {
readonly compiledArtifactsSource: RuntimeDiskCompiledArtifactsSource;
@@ -52,6 +55,43 @@ async function hydrateCompiledModuleMapFromManifest(
});
}
+ if (
+ [manifest, ...manifest.subagents.map((subagent) => subagent.agent)].some(
+ (node) => node.extensionMounts.length > 0,
+ )
+ ) {
+ const moduleMapPath = join(runtimeAppRoot, ".eve", "compile", "authored-module-map.mjs");
+ const { code } = await bundleAuthoredModuleMapForGeneration({
+ appRoot: authoredAppRoot,
+ resolveExternalPaths: true,
+ manifest,
+ moduleMapPath,
+ });
+ const hash = createHash("sha256").update(code).digest("hex");
+ const fileName = `authored-module-map-${hash}.mjs`;
+ const outputPath = join(runtimeAppRoot, ".eve", "compile", fileName);
+ await mkdir(join(runtimeAppRoot, ".eve", "compile"), { recursive: true });
+ const temporaryPath = `${outputPath}.${randomUUID()}.tmp`;
+ try {
+ await writeFile(temporaryPath, code, { flag: "wx" });
+ try {
+ await link(temporaryPath, outputPath);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
+ }
+ } finally {
+ await unlink(temporaryPath).catch((error: NodeJS.ErrnoException) => {
+ if (error.code !== "ENOENT") throw error;
+ });
+ }
+ // Independent application loads need fresh mutable extension handles, but share bundle bytes.
+ return await loadMaterializedCompiledModuleMap({
+ moduleMapPath: fileName,
+ runtimeAppRoot,
+ instanceId: randomUUID(),
+ });
+ }
+
const nodes: CompiledModuleMap["nodes"] = {};
const nodeManifests: ReadonlyArray<{
readonly manifest: CompiledAgentNodeManifest | CompiledAgentResources;
@@ -76,45 +116,36 @@ async function hydrateCompiledNodeScope(
manifest: CompiledAgentNodeManifest | CompiledAgentResources,
resolveSourcePath: (sourcePath: string) => string,
): Promise<CompiledModuleMap["nodes"][string]["modules"]> {
- const mountScopes = new Map(
- manifest.extensionMounts.map((mount) => [mount.mountSourceId, mount.packageNamespace]),
- );
- const container = globalThis as Record<symbol, unknown>;
const modules: CompiledModuleMap["nodes"][string]["modules"] = {};
for (const { binding, sourceId } of collectRuntimeModuleBindingsForManifest(manifest)) {
- const mountConfigScope = mountScopes.get(sourceId);
- if (mountConfigScope !== undefined) container[EXT_CONFIG_SCOPE] = mountConfigScope;
- try {
- modules[sourceId] =
- binding.backing.kind === "programmatic"
- ? await loadFrameworkProgrammaticModule(
- binding.backing,
- Object.fromEntries(
- Object.entries(binding.backing.dependencies ?? {}).map(
- ([alias, dependencySourceId]) => [alias, modules[dependencySourceId]!],
- ),
+ modules[sourceId] =
+ binding.backing.kind === "programmatic"
+ ? await loadFrameworkProgrammaticModule(
+ binding.backing,
+ Object.fromEntries(
+ Object.entries(binding.backing.dependencies ?? {}).map(
+ ([alias, dependencySourceId]) => [alias, modules[dependencySourceId]!],
),
- )
- : memoizeModuleNamespaceFactories(
- await loadAuthoredModuleNamespace(resolveSourcePath(binding.backing.sourcePath), {
- externalDependencies: binding.backing.externalDependencies,
- extensionScopeNamespace: resolveCompiledModuleExtensionScopeNamespace(binding),
- }),
- );
- } finally {
- if (mountConfigScope !== undefined) container[EXT_CONFIG_SCOPE] = undefined;
- }
+ ),
+ )
+ : memoizeModuleNamespaceFactories(
+ await loadAuthoredModuleNamespace(resolveSourcePath(binding.backing.sourcePath), {
+ externalDependencies: binding.backing.externalDependencies,
+ extensionScopeNamespace: resolveCompiledModuleExtensionScopeNamespace(binding),
+ }),
+ );
}
return modules;
}
async function loadMaterializedCompiledModuleMap(input: {
+ readonly instanceId?: string;
readonly moduleMapPath: string;
readonly runtimeAppRoot: string;
}): Promise<CompiledModuleMap> {
const moduleMapPath = join(input.runtimeAppRoot, ".eve", "compile", input.moduleMapPath);
const moduleNamespace = (await import(
- `${pathToFileURL(moduleMapPath).href}?generation=${encodeURIComponent(input.moduleMapPath)}`
+ `${pathToFileURL(moduleMapPath).href}?generation=${encodeURIComponent(input.instanceId ?? input.moduleMapPath)}`
)) as { readonly default?: unknown; readonly moduleMap?: unknown };
const parsed = compiledModuleMapSchema.safeParse(
moduleNamespace.moduleMap ?? moduleNamespace.default,
diff --git a/packages/eve/src/internal/authored-package-boundary.ts b/packages/eve/src/internal/authored-package-boundary.ts
index daf1afe0d..2335dd939 100644
--- a/packages/eve/src/internal/authored-package-boundary.ts
+++ b/packages/eve/src/internal/authored-package-boundary.ts
@@ -40,6 +40,8 @@ interface ResolvedAuthoredExternalModule {
export function createGenerationPackageBoundaryPlugin(input: {
readonly externalDependencies: readonly string[];
readonly packageRoot: string;
+ readonly extensionSpecifiers?: ReadonlySet<string>;
+ readonly resolveExternalPaths?: boolean;
}): Record<string, unknown> {
return {
name: "eve-generation-package-boundary",
@@ -54,6 +56,7 @@ export function createGenerationPackageBoundaryPlugin(input: {
}
if (isFrameworkRuntimeImport(source, importer)) {
+ if (input.extensionSpecifiers?.has(source)) return undefined;
return { external: true, id: resolveFrameworkRuntimeImport(source) };
}
@@ -77,12 +80,18 @@ export function createGenerationPackageBoundaryPlugin(input: {
return undefined;
}
- return { external: true, id: source };
+ return {
+ external: true,
+ id: input.resolveExternalPaths
+ ? normalizeEsmImportSpecifier(externalModule.resolvedId)
+ : source,
+ };
},
};
}
export function createRuntimeLoaderPackageBoundaryPlugin(input: {
+ readonly extensionSpecifier?: string;
readonly externalDependencies: readonly string[];
readonly packageRoot: string;
}): Record<string, unknown> {
@@ -100,6 +109,7 @@ export function createRuntimeLoaderPackageBoundaryPlugin(input: {
return undefined;
}
+ if (source === input.extensionSpecifier) return undefined;
if (isFrameworkRuntimeImport(source, importer)) {
return {
external: true,
diff --git a/packages/eve/src/internal/bundler/compile-mount-plugin.ts b/packages/eve/src/internal/bundler/compile-mount-plugin.ts
new file mode 100644
index 000000000..61b4f93be
--- /dev/null
+++ b/packages/eve/src/internal/bundler/compile-mount-plugin.ts
@@ -0,0 +1,37 @@
+import type { AuthoredModuleLoadOptions } from "#internal/authored-module-loader.js";
+import { createExtensionMountPlugin } from "#internal/bundler/extension-mount-plugin.js";
+import { createExtensionScopePlugin } from "#internal/bundler/extension-scope-plugin.js";
+
+/** Compile contributions with their declaration so config and callbacks share one handle. */
+export function createCompileMountPlugins(
+ modulePath: string,
+ options: AuthoredModuleLoadOptions,
+): Record<string, unknown>[] {
+ const mount = options.mount;
+ if (mount === undefined) return [];
+ const tag = `?eve-mount=${encodeURIComponent(mount.mountId)}`;
+ const declaration = mount.programmaticImport;
+ return [
+ {
+ name: "eve-compile-mount-entry",
+ resolveId(id: string) {
+ return id === "\0eve-compile-mount-entry" || id === "\0eve-compile-mount-declaration"
+ ? id
+ : undefined;
+ },
+ load(id: string) {
+ if (id === "\0eve-compile-mount-declaration" && declaration !== undefined) {
+ return `import extension from ${JSON.stringify(declaration.specifier + tag)}; export default extension(${JSON.stringify(declaration.config)});`;
+ }
+ if (id !== "\0eve-compile-mount-entry") return undefined;
+ const mountImport =
+ declaration === undefined
+ ? mount.mountSourcePath + tag
+ : "\0eve-compile-mount-declaration";
+ return `import ${JSON.stringify(mountImport)}; import * as entry from ${JSON.stringify(modulePath + tag)}; export * from ${JSON.stringify(modulePath + tag)}; export default entry.default;`;
+ },
+ },
+ createExtensionMountPlugin([mount], new Map([[modulePath, mount.mountId]]))!,
+ { ...createExtensionScopePlugin([mount])! },
+ ];
+}
diff --git a/packages/eve/src/internal/bundler/extension-mount-plugin.ts b/packages/eve/src/internal/bundler/extension-mount-plugin.ts
new file mode 100644
index 000000000..64ae3e792
--- /dev/null
+++ b/packages/eve/src/internal/bundler/extension-mount-plugin.ts
@@ -0,0 +1,145 @@
+import { readFileSync, realpathSync } from "node:fs";
+import { resolve, sep } from "node:path";
+
+const MOUNT_QUERY = "?eve-mount=";
+
+interface Mount {
+ readonly mountId: string;
+ readonly sourceRoot: string;
+ readonly packageName: string;
+ readonly specifier?: string;
+ readonly mountSourcePath?: string;
+ readonly programmaticImport?: { readonly specifier: string; readonly entryPath: string };
+}
+
+function canonical(path: string): string {
+ try {
+ return realpathSync(path);
+ } catch {
+ return resolve(path);
+ }
+}
+
+function within(path: string, root: string): boolean {
+ return path === root || path.startsWith(`${root}${sep}`);
+}
+
+/** Isolates extension-owned source modules, but leaves ordinary dependencies shared. */
+export function createExtensionMountPlugin(
+ mounts: readonly Mount[],
+ overridePaths: ReadonlyMap<string, string> = new Map(),
+): Record<string, unknown> | null {
+ if (mounts.length === 0) return null;
+ 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]),
+ );
+ const byId = new Map(roots.map((mount) => [mount.mountId, mount]));
+ const overrideMounts = new Map(
+ [...overridePaths].map(([path, id]) => [canonical(path), byId.get(id)]),
+ );
+ return {
+ name: "eve-extension-mount",
+ async resolveId(
+ this: {
+ resolve: (
+ source: string,
+ importer?: string,
+ options?: { skipSelf: boolean; kind?: "import-statement" },
+ ) => Promise<{ id: string; external?: boolean } | null>;
+ },
+ source: string,
+ importer?: string,
+ ) {
+ if (source === "eve/context") return undefined;
+ const query = source.indexOf(MOUNT_QUERY);
+ const tagged =
+ query >= 0 ? decodeURIComponent(source.slice(query + MOUNT_QUERY.length)) : undefined;
+ const importerQuery = importer?.indexOf(MOUNT_QUERY) ?? -1;
+ const inherited =
+ importerQuery >= 0
+ ? decodeURIComponent(importer!.slice(importerQuery + MOUNT_QUERY.length))
+ : undefined;
+ 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 declarationMount =
+ importerPath === undefined ? undefined : declarationPaths.get(importerPath);
+ const overrideMount =
+ importerPath === undefined ? undefined : overrideMounts.get(importerPath);
+ const mountId = tagged ?? 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}".`);
+
+ // An override has mount context for its imports, but remains application-owned:
+ // its own state and all of its other dependencies keep their ordinary identity.
+ const override =
+ mount !== undefined &&
+ importerPath !== undefined &&
+ !within(importerPath, mount.root) &&
+ overrideMounts.get(importerPath) === mount;
+ const sourceMount =
+ mount !== undefined &&
+ (cleanSource === mount.specifier || cleanSource === mount.programmaticImport?.specifier)
+ ? mount
+ : undefined;
+ // Use ESM conditions for authored exports; programmatic mounts supply their entry.
+ const resolved = await this.resolve(
+ sourceMount?.programmaticImport?.entryPath ?? cleanSource,
+ cleanImporter,
+ {
+ skipSelf: true,
+ kind: "import-statement",
+ },
+ );
+ if (resolved === null || resolved.id.startsWith("\0")) return resolved;
+ if (resolved.external) {
+ if (sourceMount === undefined) return resolved;
+ throw new Error(
+ `Extension export "${cleanSource}" for mount "${mountId}" was externalized; it must be bundled to isolate its configuration.`,
+ );
+ }
+ // Assets have no mutable module state. Preserve their loader's query and identity.
+ if (!/\.(?:[cm]?[jt]sx?|json)$/.test(resolved.id)) return resolved;
+ const path = canonical(resolved.id);
+ if (
+ mount !== undefined &&
+ (sourceMount !== undefined || (!override && within(path, mount.root)))
+ ) {
+ return { id: `${resolved.id}${MOUNT_QUERY}${encodeURIComponent(mountId!)}` };
+ }
+ if (mount !== undefined) return resolved;
+ if (importer === undefined || importer.startsWith("\0")) return undefined;
+ const owners = roots.filter((root) => within(path, root.root));
+ 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.`,
+ );
+ }
+ return owners.length === 1
+ ? { id: `${resolved.id}${MOUNT_QUERY}${encodeURIComponent(owners[0]!.mountId)}` }
+ : undefined;
+ },
+ load(id: string) {
+ const query = id.indexOf(MOUNT_QUERY);
+ if (query < 0) return undefined;
+ const path = id.slice(0, query);
+ if (!/\.(?:[cm]?[jt]sx?|json)$/.test(path)) return undefined;
+ const extension = path.slice(path.lastIndexOf(".") + 1);
+ const moduleType =
+ extension === "json"
+ ? "json"
+ : extension === "tsx"
+ ? "tsx"
+ : extension === "jsx"
+ ? "jsx"
+ : ["ts", "mts", "cts"].includes(extension)
+ ? "ts"
+ : "js";
+ return { code: readFileSync(path, "utf8"), moduleType };
+ },
+ };
+}
diff --git a/packages/eve/src/internal/bundler/extension-scope-plugin.integration.test.ts b/packages/eve/src/internal/bundler/extension-scope-plugin.integration.test.ts
index fa2ade260..68a53d575 100644
--- a/packages/eve/src/internal/bundler/extension-scope-plugin.integration.test.ts
+++ b/packages/eve/src/internal/bundler/extension-scope-plugin.integration.test.ts
@@ -5,6 +5,7 @@ import { join } from "node:path";
import { afterAll, describe, expect, it } from "vitest";
import { buildSingleRolldownChunk } from "#internal/bundler/nitro-rolldown.js";
+import { createExtensionMountPlugin } from "#internal/bundler/extension-mount-plugin.js";
import {
createExtensionScopePlugin,
createFixedNamespaceScopePlugin,
@@ -49,6 +50,63 @@ const STATE_MODULE = [
].join("\n");
describe("extension-scope plugin (bundled)", () => {
+ it("evaluates shared extension source once per mount, including relative imports", async () => {
+ const { sourceRoot } = scratchModule('export { instance } from "../shared.ts";');
+ writeFileSync(join(sourceRoot, "shared.ts"), "export const instance = {};");
+ const entry = join(sourceRoot, "entry.ts");
+ writeFileSync(
+ entry,
+ [
+ 'import { instance as research } from "./tools/budget.ts?eve-mount=extensions%2Fresearch";',
+ 'import { instance as support } from "./tools/budget.ts?eve-mount=extensions%2Fsupport";',
+ "export const distinct = research !== support;",
+ ].join("\n"),
+ );
+ const code = await bundle(entry, [
+ createExtensionMountPlugin([
+ {
+ mountId: "extensions/research",
+ sourceRoot,
+ packageName: "@acme/test",
+ specifier: "@acme/test",
+ },
+ {
+ mountId: "extensions/support",
+ sourceRoot,
+ packageName: "@acme/test",
+ specifier: "@acme/test",
+ },
+ ]),
+ ]);
+ const result = (await import(`data:text/javascript,${encodeURIComponent(code)}`)) as {
+ distinct: boolean;
+ };
+ expect(result.distinct).toBe(true);
+ });
+ it("rejects an application import with two possible mount owners", async () => {
+ const { sourceRoot } = scratchModule("export const value = 1;");
+ const entry = join(sourceRoot, "..", "consumer.ts");
+ writeFileSync(entry, 'export { value } from "./extension/tools/budget.ts";');
+ await expect(
+ bundle(entry, [
+ createExtensionMountPlugin([
+ {
+ mountId: "extensions/research",
+ sourceRoot,
+ packageName: "@acme/test",
+ specifier: "@acme/test",
+ },
+ {
+ mountId: "extensions/support",
+ sourceRoot,
+ packageName: "@acme/test",
+ specifier: "@acme/test",
+ },
+ ]),
+ ]),
+ ).rejects.toThrow(/multiple extension mounts/);
+ });
+
afterAll(() => {
// Scratch dirs live under the OS temp root; leaving them is harmless and
// avoids racing the bundler's async file handles on cleanup.
diff --git a/packages/eve/src/internal/bundler/extension-scope-plugin.test.ts b/packages/eve/src/internal/bundler/extension-scope-plugin.test.ts
index 1d6d42dff..2d47bbf36 100644
--- a/packages/eve/src/internal/bundler/extension-scope-plugin.test.ts
+++ b/packages/eve/src/internal/bundler/extension-scope-plugin.test.ts
@@ -26,9 +26,9 @@ describe("createExtensionScopePlugin (path containment)", () => {
expect(id).toBe("\0eve-ext-scope:context:acme-crm");
});
- it("redirects eve/extension to a namespaced shim for extension-owned importers", () => {
+ it("leaves eve/extension unscoped for extension-owned importers", () => {
const id = pathPlugin().resolveId("eve/extension", "/pkg/crm/extension/config.ts");
- expect(id).toBe("\0eve-ext-scope:extension:acme-crm");
+ expect(id).toBeUndefined();
});
it("ignores importers outside every extension source root", () => {
@@ -54,9 +54,7 @@ describe("createFixedNamespaceScopePlugin (dev per-module)", () => {
expect(plugin.resolveId("eve/context", "/anywhere/on/disk/tool.ts")).toBe(
"\0eve-ext-scope:context:acme-crm",
);
- expect(plugin.resolveId("eve/extension", "/anywhere/config.ts")).toBe(
- "\0eve-ext-scope:extension:acme-crm",
- );
+ expect(plugin.resolveId("eve/extension", "/anywhere/config.ts")).toBeUndefined();
});
it("never re-enters through virtual shim importers", () => {
@@ -81,15 +79,6 @@ describe("shim baking (shared)", () => {
expect(shim?.code).toContain(`__eveScopedDefineState("acme-crm" + "." + name, initial)`);
});
- it("bakes the namespace into the defineExtension shim", () => {
- const shim = createFixedNamespaceScopePlugin("acme-crm").load(
- "\0eve-ext-scope:extension:acme-crm",
- );
- expect(shim?.code).toContain(`from "eve/extension"`);
- expect(shim?.code).toContain(`export function defineExtension(options, namespace)`);
- expect(shim?.code).toContain(`namespace === undefined ? "acme-crm" : namespace`);
- });
-
it("passes through non-shim ids in load", () => {
expect(pathPlugin().load("/pkg/crm/extension/tools/budget.ts")).toBeUndefined();
});
diff --git a/packages/eve/src/internal/bundler/extension-scope-plugin.ts b/packages/eve/src/internal/bundler/extension-scope-plugin.ts
index ebb266a09..a69be582f 100644
--- a/packages/eve/src/internal/bundler/extension-scope-plugin.ts
+++ b/packages/eve/src/internal/bundler/extension-scope-plugin.ts
@@ -2,26 +2,18 @@ import { realpathSync } from "node:fs";
import { resolve, sep } from "node:path";
/**
- * One extension's on-disk source root paired with the namespace its durable
- * state keys and config binding must be scoped to.
+ * One extension's on-disk source root paired with its legacy durable state prefix.
*/
interface ExtensionScope {
/** Absolute path to the extension's source root. */
readonly sourceRoot: string;
/** Package-derived namespace (e.g. `acme-crm`). */
readonly packageNamespace: string;
+ readonly mountId?: string;
}
const VIRTUAL_PREFIX = "\0eve-ext-scope:";
-/** Framework module an extension-owned import is redirected through. */
-type ScopedFrameworkModule = "eve/context" | "eve/extension";
-
-const SCOPED_FRAMEWORK_MODULES: Record<ScopedFrameworkModule, "context" | "extension"> = {
- "eve/context": "context",
- "eve/extension": "extension",
-};
-
/** The subset of the rolldown/rollup plugin shape this plugin implements. */
export interface ExtensionScopeBundlerPlugin {
readonly name: string;
@@ -47,27 +39,12 @@ function isUnder(path: string, root: string): boolean {
return path === root || path.startsWith(`${root}${sep}`);
}
-function shimSource(kind: "context" | "extension", namespace: string): string {
- const ns = JSON.stringify(namespace);
- if (kind === "context") {
- // Wrap `defineState` (the only runtime export) so the durable key is
- // prefixed with the namespace baked into the bundle, not read from
- // evaluation-order-sensitive global state.
- return [
- `import { defineState as __eveScopedDefineState } from "eve/context";`,
- `export function defineState(name, initial) {`,
- ` return __eveScopedDefineState(${ns} + "." + name, initial);`,
- `}`,
- "",
- ].join("\n");
- }
- // Wrap `defineExtension` (the only runtime export) so the handle bakes the
- // namespace — both the mount binding and the handle's `config` reader resolve
- // to the same scope from any module in the extension.
+function shimSource(namespace: string): string {
+ // Legacy state keys stay package-prefixed until checkpoint admission changes.
return [
- `import { defineExtension as __eveScopedDefineExtension } from "eve/extension";`,
- `export function defineExtension(options, namespace) {`,
- ` return __eveScopedDefineExtension(options, namespace === undefined ? ${ns} : namespace);`,
+ `import { defineState as __eveScopedDefineState } from "eve/context";`,
+ `export function defineState(name, initial) {`,
+ ` return __eveScopedDefineState(${JSON.stringify(namespace)} + "." + name, initial);`,
`}`,
"",
].join("\n");
@@ -75,7 +52,7 @@ function shimSource(kind: "context" | "extension", namespace: string): string {
/**
* Builds the resolveId/load hook pair shared by both plugin modes. `namespaceFor`
- * returns the scope namespace for a given importer, or `undefined` to leave the
+ * returns the legacy state scope for an importer, or `undefined` to leave the
* import untouched.
*/
function scopeHooks(
@@ -85,15 +62,12 @@ function scopeHooks(
return {
name,
resolveId(source: string, importer: string | undefined) {
- const kind = SCOPED_FRAMEWORK_MODULES[source as ScopedFrameworkModule];
- if (kind === undefined || importer === undefined || importer.startsWith("\0")) {
+ if (source !== "eve/context" || importer === undefined || importer.startsWith("\0")) {
return undefined;
}
const namespace = namespaceFor(importer);
- if (namespace === undefined) {
- return undefined;
- }
- return `${VIRTUAL_PREFIX}${kind}:${namespace}`;
+ if (namespace === undefined) return undefined;
+ return `${VIRTUAL_PREFIX}context:${namespace}`;
},
load(id: string) {
if (!id.startsWith(VIRTUAL_PREFIX)) {
@@ -101,9 +75,9 @@ function scopeHooks(
}
const descriptor = id.slice(VIRTUAL_PREFIX.length);
const separatorIndex = descriptor.indexOf(":");
- const kind = descriptor.slice(0, separatorIndex) as "context" | "extension";
+ if (descriptor.slice(0, separatorIndex) !== "context") return undefined;
const namespace = descriptor.slice(separatorIndex + 1);
- return { code: shimSource(kind, namespace), moduleType: "js" as const };
+ return { code: shimSource(namespace), moduleType: "js" as const };
},
};
}
@@ -111,8 +85,8 @@ function scopeHooks(
/**
* Path-containment scope plugin for the whole-application bundle (the production
* build). Any module physically under an extension's source root has its
- * `eve/context`/`eve/extension` imports redirected to a generated shim that
- * bakes the extension's package namespace into `defineState`/`defineExtension`.
+ * `eve/context` imports redirected to a generated shim that preserves the
+ * legacy package prefix for `defineState`.
*
* Returns `null` when there are no extensions, so consumer-only builds carry no
* extra plugin and their output is byte-identical to a non-extension build.
@@ -126,15 +100,23 @@ export function createExtensionScopePlugin(
const canonicalScopes = scopes.map((scope) => ({
root: canonicalize(scope.sourceRoot),
packageNamespace: scope.packageNamespace,
+ mountId: scope.mountId,
}));
return scopeHooks("eve-extension-scope", (importer) => {
+ const mountQuery = importer.indexOf("?eve-mount=");
+ if (mountQuery >= 0) {
+ const mountId = decodeURIComponent(importer.slice(mountQuery + "?eve-mount=".length));
+ const owned = canonicalScopes.find((scope) => scope.mountId === mountId);
+ if (owned === undefined) throw new Error(`Unknown extension mount "${mountId}".`);
+ return isUnder(importerPath(importer), owned.root) ? owned.packageNamespace : undefined;
+ }
const path = importerPath(importer);
- for (const scope of canonicalScopes) {
- if (isUnder(path, scope.root)) {
- return scope.packageNamespace;
- }
+ const matches = canonicalScopes.filter((scope) => isUnder(path, scope.root));
+ if (matches.length === 0) return undefined;
+ if (new Set(matches.map((scope) => scope.packageNamespace)).size > 1) {
+ throw new Error(`Ambiguous extension scope for "${path}".`);
}
- return undefined;
+ return matches[0]!.packageNamespace;
});
}
diff --git a/packages/eve/src/internal/nitro/host/create-application-nitro.scenario.test.ts b/packages/eve/src/internal/nitro/host/create-application-nitro.scenario.test.ts
index 5c8a779b9..51fa8156a 100644
--- a/packages/eve/src/internal/nitro/host/create-application-nitro.scenario.test.ts
+++ b/packages/eve/src/internal/nitro/host/create-application-nitro.scenario.test.ts
@@ -31,6 +31,8 @@ import { applyWorkflowTransform } from "#internal/workflow-bundle/workflow-build
import { useTemporaryDirectories } from "#internal/testing/use-temporary-app-roots.js";
import { defineChannel, WS } from "#public/definitions/channel.js";
import { defineTool } from "#tools/definition.js";
+import { JustBashSandbox } from "#sandbox/providers/just-bash.js";
+import { defineSandbox } from "#public/definitions/sandbox.js";
import { defineWorkflowTool } from "#tools/workflow-definition.js";
import { attachWorkflowProgramOptions } from "#tools/workflow-program-input.js";
@@ -102,8 +104,15 @@ async function createPreparedHost(
): Promise<PreparedDevelopmentApplicationHost> {
const appRoot = "/tmp/weather-agent";
const paths = resolveCompilerArtifactPaths(appRoot);
- const modules: Array<NonNullable<Parameters<typeof compileFromMemory>[0]["modules"]>[number]> =
- [];
+ const modules: Array<NonNullable<Parameters<typeof compileFromMemory>[0]["modules"]>[number]> = [
+ {
+ logicalPath: "sandbox.ts",
+ loadNamespace: async () => {
+ const environment = JustBashSandbox.environment();
+ return { environment, default: defineSandbox(() => environment.open()) };
+ },
+ },
+ ];
if (input.websocket === true) {
modules.push({
logicalPath: "channels/voice.ts",
@@ -647,8 +656,10 @@ describe("application Nitro creation", () => {
externalDependencies: ["zod", "sharp"],
mountLogicalPath: "extensions/layout.ts",
mountSourceId: "extensions/layout.ts",
+ mountSourcePath: join(sourceRoot, "layout.ts"),
namespace: "layout",
packageName: "layout-extension",
+ specifier: "layout-extension",
mountId: "extensions/layout",
packageNamespace: "layout-extension",
sourceRoot,
@@ -730,7 +741,7 @@ describe("application Nitro creation", () => {
);
});
- it("leaves Nitro to classify unconfigured hosted dependencies", async () => {
+ it("traces only the configured sandbox engine and leaves other dependencies to Nitro", async () => {
const nitroStub = createNitroStub();
createNitroMock.mockResolvedValueOnce(nitroStub.nitro);
@@ -740,7 +751,7 @@ describe("application Nitro creation", () => {
await createProductionApplicationNitro(preparedHost, createProductionOptions(preparedHost));
- expect(createNitroMock.mock.calls[0]?.[0].traceDeps).toEqual([]);
+ expect(createNitroMock.mock.calls[0]?.[0].traceDeps).toEqual(["just-bash"]);
});
it("includes the workflow sandbox runtime plugin only for generated-program tools", async () => {
diff --git a/packages/eve/src/internal/nitro/host/create-application-nitro.ts b/packages/eve/src/internal/nitro/host/create-application-nitro.ts
index fa4b3f5bb..54de25a9b 100644
--- a/packages/eve/src/internal/nitro/host/create-application-nitro.ts
+++ b/packages/eve/src/internal/nitro/host/create-application-nitro.ts
@@ -21,6 +21,8 @@ import { createProductionNitroArtifactsConfig } from "#internal/nitro/host/artif
import { createCompiledSandboxProviderPrunePlugin } from "#internal/nitro/host/compiled-sandbox-provider-prune-plugin.js";
import { createDevelopmentRuntimePrunePlugin } from "#internal/nitro/host/development-runtime-prune-plugin.js";
import { createExtensionScopePlugin } from "#internal/bundler/extension-scope-plugin.js";
+import { extensionOverridePaths } from "#compiler/extension-mount-bindings.js";
+import { createExtensionMountPlugin } from "#internal/bundler/extension-mount-plugin.js";
import {
createExtensionExternalDependencyPlugin,
resolveExtensionExternalDependencyPaths,
@@ -586,6 +588,7 @@ function createApplicationNitroBundlerConfiguration(
node.extensionMounts.map((mount) => ({
sourceRoot: mount.sourceRoot,
packageNamespace: mount.packageNamespace,
+ mountId: mount.mountId,
})),
),
);
@@ -598,6 +601,10 @@ function createApplicationNitroBundlerConfiguration(
compiledSandboxProviderPrunePlugin,
createOptionalEngineDependencyPlugin(unconfiguredOptionalEnginePackages),
createExtensionExternalDependencyPlugin(extensionMounts),
+ createExtensionMountPlugin(
+ extensionMounts,
+ extensionOverridePaths(preparedHost.compileResult.manifest),
+ ),
extensionScopePlugin,
].filter((plugin) => plugin !== null);
const nitroRolldownConfig = {
diff --git a/packages/eve/src/internal/workflow-bundle/dynamic-capability-transform-plugin.ts b/packages/eve/src/internal/workflow-bundle/dynamic-capability-transform-plugin.ts
index eaefbedef..b2a3e3e55 100644
--- a/packages/eve/src/internal/workflow-bundle/dynamic-capability-transform-plugin.ts
+++ b/packages/eve/src/internal/workflow-bundle/dynamic-capability-transform-plugin.ts
@@ -11,7 +11,7 @@ export function createDynamicCapabilityTransformPlugin(
) {
return {
async transform(code: string, id: string) {
- const normalizedId = id.replaceAll("\\", "/");
+ const normalizedId = id.split("?")[0]!.replaceAll("\\", "/");
const transformDynamicTools = options.dynamicTools !== false;
const transformDynamicRemoteAgents =
options.dynamicRemoteAgents !== false && normalizedId.includes("/subagents/");
@@ -23,7 +23,7 @@ export function createDynamicCapabilityTransformPlugin(
let changed = false;
if (transformDynamicTools) {
const result = await transformDynamicToolExecute(
- id,
+ normalizedId,
transformed,
options.workflowFunctions?.(id),
);
@@ -33,7 +33,7 @@ export function createDynamicCapabilityTransformPlugin(
}
}
if (transformDynamicRemoteAgents) {
- const result = await transformDynamicRemoteAgentCredentials(id, transformed);
+ const result = await transformDynamicRemoteAgentCredentials(normalizedId, transformed);
if (result !== null) {
transformed = result.code;
changed = true;
diff --git a/packages/eve/src/public/definitions/extension.test.ts b/packages/eve/src/public/definitions/extension.test.ts
index 596dfcad7..4952bd67a 100644
--- a/packages/eve/src/public/definitions/extension.test.ts
+++ b/packages/eve/src/public/definitions/extension.test.ts
@@ -4,25 +4,20 @@ import { z } from "zod";
import type { StandardSchemaV1 } from "#compiled/@standard-schema/spec/index.js";
import { defineExtension } from "#public/definitions/extension.js";
-// Each test uses a distinct namespace because the config registry is process-global.
-
describe("defineExtension", () => {
it("exposes the declared schema", () => {
const schema = z.object({ apiKey: z.string() });
- const ext = defineExtension({ config: schema }, "schema-test");
+ const ext = defineExtension({ config: schema });
expect(ext.schema).toBe(schema);
});
it("binds values from the mount factory call and reads them with defaults applied", () => {
- const ext = defineExtension(
- {
- config: z.object({
- apiKey: z.string(),
- baseUrl: z.string().default("https://api.acme.example"),
- }),
- },
- "read-factory",
- );
+ const ext = defineExtension({
+ config: z.object({
+ apiKey: z.string(),
+ baseUrl: z.string().default("https://api.acme.example"),
+ }),
+ });
const mounted = ext({ apiKey: "sk-456" });
@@ -31,30 +26,26 @@ describe("defineExtension", () => {
});
it("lets a bound value override a default", () => {
- const ext = defineExtension(
- { config: z.object({ baseUrl: z.string().default("https://default") }) },
- "read-override",
- );
+ const ext = defineExtension({
+ config: z.object({ baseUrl: z.string().default("https://default") }),
+ });
ext({ baseUrl: "https://override" });
expect(ext.config).toEqual({ baseUrl: "https://override" });
});
it("applies schema defaults when read before an all-optional mount binds", () => {
- const ext = defineExtension(
- { config: z.object({ verbose: z.boolean().default(false) }) },
- "read-zero",
- );
+ const ext = defineExtension({ config: z.object({ verbose: z.boolean().default(false) }) });
expect(ext.config).toEqual({ verbose: false });
});
it("rejects a missing required field at bind", () => {
- const ext = defineExtension({ config: z.object({ apiKey: z.string() }) }, "bind-required");
+ const ext = defineExtension({ config: z.object({ apiKey: z.string() }) });
// @ts-expect-error apiKey is required by the schema
expect(() => ext({})).toThrow(/Invalid extension config/);
});
it("rejects a wrong-typed value at bind", () => {
- const ext = defineExtension({ config: z.object({ pageSize: z.number() }) }, "bind-type");
+ const ext = defineExtension({ config: z.object({ pageSize: z.number() }) });
// @ts-expect-error pageSize must be a number
expect(() => ext({ pageSize: "nope" })).toThrow(/Invalid extension config/);
});
@@ -67,22 +58,21 @@ describe("defineExtension", () => {
validate: async (value) => ({ value }),
},
};
- const ext = defineExtension({ config: asyncSchema }, "bind-async");
+ const ext = defineExtension({ config: asyncSchema });
expect(() => ext({})).toThrow(/validate synchronously/);
});
it("has an empty config and undefined schema with no config declared", () => {
- const ext = defineExtension(undefined, "noconfig-test");
+ const ext = defineExtension();
expect(ext.schema).toBeUndefined();
expect(ext()).toBeDefined();
expect(ext.config).toEqual({});
});
it("types the config reader from the schema", () => {
- const ext = defineExtension(
- { config: z.object({ apiKey: z.string(), tier: z.string().default("free") }) },
- "types-test",
- );
+ const ext = defineExtension({
+ config: z.object({ apiKey: z.string(), tier: z.string().default("free") }),
+ });
ext({ apiKey: "k" });
// Compile-time assertions (checked by `tsc`).
diff --git a/packages/eve/src/public/definitions/extension.ts b/packages/eve/src/public/definitions/extension.ts
index 7f23344f2..26631afaa 100644
--- a/packages/eve/src/public/definitions/extension.ts
+++ b/packages/eve/src/public/definitions/extension.ts
@@ -3,32 +3,6 @@ import type { StandardSchemaV1 } from "#compiled/@standard-schema/spec/index.js"
/** Marker carried by the object an extension handle produces when called. */
const MOUNTED_EXTENSION = Symbol.for("eve.mounted-extension");
-const CONFIG_REGISTRY = Symbol.for("eve.extension-config-registry");
-
-/**
- * Ambient namespace set by the dev/eval loader around a mount module's
- * evaluation. A mount loads the handle unbundled (cross-package), so the
- * bundler's scope shim never runs on it; this fallback lets the mount still bind
- * under the package namespace. The shim's explicit argument takes precedence.
- */
-const EXT_CONFIG_SCOPE = Symbol.for("eve.ext-config-scope");
-
-function ambientConfigScope(): string | undefined {
- const scope = (globalThis as Record<symbol, unknown>)[EXT_CONFIG_SCOPE];
- return typeof scope === "string" && scope.length > 0 ? scope : undefined;
-}
-
-/** Process-global map of extension namespace to its bound, validated config. */
-function configRegistry(): Map<string, Record<string, unknown>> {
- const container = globalThis as Record<symbol, unknown>;
- let registry = container[CONFIG_REGISTRY] as Map<string, Record<string, unknown>> | undefined;
- if (registry === undefined) {
- registry = new Map();
- container[CONFIG_REGISTRY] = registry;
- }
- return registry;
-}
-
/**
* Marker value an extension handle returns when called. The consumer's mount
* file default-exports it (directly for a no-config extension, or as the result
@@ -119,8 +93,8 @@ function validateConfig(
* const { apiKey } = extension.config;
* ```
*
- * The `namespace` argument is supplied by the bundler shim and is not part of the
- * authoring surface.
+ * The second argument is retained for source compatibility with compiled extension
+ * declarations; instance bindings come from the loaded module graph, not its value.
*/
export function defineExtension<const S extends StandardSchemaV1>(
options: { readonly config: S },
@@ -132,19 +106,12 @@ export function defineExtension(
): NoConfigExtensionHandle;
export function defineExtension(
options?: { readonly config?: StandardSchemaV1 },
- namespace?: string,
+ _namespace?: string,
): ExtensionHandle | NoConfigExtensionHandle {
const schema = options?.config;
- // The bundler shim passes the namespace explicitly for the extension's own
- // bundled modules; an unshimmed cross-package mount falls back to the ambient
- // scope the loader sets around the mount evaluation.
- const resolvedNamespace = namespace ?? ambientConfigScope();
-
+ let bound: Record<string, unknown> | undefined;
const handle = ((values?: unknown): MountedExtension => {
- const parsed = validateConfig(schema, values);
- if (resolvedNamespace !== undefined && resolvedNamespace.length > 0) {
- configRegistry().set(resolvedNamespace, parsed);
- }
+ bound = validateConfig(schema, values);
return { [MOUNTED_EXTENSION]: true };
}) as ExtensionHandle & NoConfigExtensionHandle;
@@ -152,8 +119,6 @@ export function defineExtension(
Object.defineProperty(handle, "config", {
enumerable: true,
get(): Record<string, unknown> {
- const bound =
- resolvedNamespace === undefined ? undefined : configRegistry().get(resolvedNamespace);
return bound ?? validateConfig(schema, {});
},
});
diff --git a/packages/eve/src/self-modification/package-consumption.scenario.test.ts b/packages/eve/src/self-modification/package-consumption.scenario.test.ts
index f8abfd83e..444c9747b 100644
--- a/packages/eve/src/self-modification/package-consumption.scenario.test.ts
+++ b/packages/eve/src/self-modification/package-consumption.scenario.test.ts
@@ -196,7 +196,7 @@ if (compiled.subagents.length !== 1 || subagent === undefined || !subagent.agent
`,
);
await run("node", ["verify-development-extension.mjs"], appRoot);
- const build = await run("pnpm", ["build"], appRoot);
+ const build = await run("pnpm", ["exec", "eve", "build", "--skip-sandbox-prewarm"], appRoot);
const output = `${build.stdout}\n${build.stderr}`;
if (output.includes("Could not resolve '#shared/")) {
throw new Error(