Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat(eve): scope durable extension state to mounts (#3970)

prhab34bab8eb397
diff --git a/.changeset/per-mount-extension-config.md b/.changeset/per-mount-extension-config.md
new file mode 100644
index 000000000..1d8f270ad
--- /dev/null
+++ b/.changeset/per-mount-extension-config.md
@@ -0,0 +1,5 @@
+---
+"eve": minor
+---
+
+Extension configuration and durable state now belong to each logical mount, so duplicate mounts can use independent config and state. Session handoffs across this upgrade boundary are rejected in both directions, including for agents without extensions; keep each session's owning deployment available until it finishes, or start a new session on the deployment you want to use.
diff --git a/docs/extensions.md b/docs/extensions.md
index 1386f0a5a..f5db7c2c1 100644
--- a/docs/extensions.md
+++ b/docs/extensions.md
@@ -85,7 +85,7 @@ export default defineTool({
If no configuration is needed, export `defineExtension()` and let consumers re-export it directly. Config schemas must validate synchronously.
-`defineState` is automatically scoped to the extension package, so the same state name does not collide with the consumer or another extension.
+`defineState` uses a durable key scoped to the logical mount path and the authored state name. Two mounts of the same package can use the same state name without sharing a slot in one context. Contributed subagents use their parent extension's mount identity, but retain their own runtime contexts.
### Add a subagent
@@ -195,7 +195,14 @@ export { default } from "@acme/gizmo";
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.
+Extension state belongs to the logical mount path (for example, `extensions/crm` or `subagents/research/extensions/crm`). A flat `crm.ts` mount and a directory `crm/extension.ts` mount have the same identity; moving or renaming the mount changes its state keys. Application-defined state keys are unchanged.
+
+### Upgrade from package-scoped extension state
+
+Deployments before this release stored extension state under package-prefixed keys. eve does not migrate that state to mount-owned keys or reset it during restore.
+
+- Session handoffs across this upgrade boundary are rejected in both directions, including for agents without extensions. Keep each session's owning deployment available until the session finishes, or start a new session on the deployment you want to use.
+- Local context snapshots use a separate state-layout check. Older snapshots for agents with extensions are incompatible; snapshots for agents without extensions can restore if they contain no unrecognized state keys.
### Use an extension in a workspace
diff --git a/e2e/fixtures/extensions/agent/mock-responder.ts b/e2e/fixtures/extensions/agent/mock-responder.ts
index cdff67d40..37616e45e 100644
--- a/e2e/fixtures/extensions/agent/mock-responder.ts
+++ b/e2e/fixtures/extensions/agent/mock-responder.ts
@@ -29,6 +29,37 @@ export function respond(request: MockModelRequest): MockModelResponse | string {
: { toolCalls: [next] };
}
+ if (message.includes("Call toolkit__toolkit_lookup")) {
+ const calls = [
+ "toolkit__toolkit_lookup",
+ "toolkit-alt__toolkit_lookup",
+ "toolkit__toolkit_budget",
+ "toolkit__toolkit_budget",
+ "toolkit-alt__toolkit_budget",
+ ];
+ const completed = request.toolResults;
+ const next = calls.find((name, index) => {
+ if (name.endsWith("_budget")) {
+ const previousBudgetCalls = calls.slice(0, index).filter((call) => call === name).length;
+ const completedBudgetCalls = completed.filter((entry) => entry.name === name).length;
+ return completedBudgetCalls <= previousBudgetCalls;
+ }
+ return !completed.some((entry) => entry.name === name);
+ });
+ return next === undefined
+ ? "Both mounts kept their own configuration and budget."
+ : {
+ toolCalls: [
+ {
+ name: next,
+ input: next.endsWith("_lookup")
+ ? { account: next.startsWith("toolkit-alt") ? "secondary" : "primary" }
+ : {},
+ },
+ ],
+ };
+ }
+
if (!message.includes(`Call \`${LAYOUT_TOOL}\``)) {
return `Mock reply: ${message}`;
}
diff --git a/e2e/fixtures/extensions/evals/duplicate-mounts.eval.ts b/e2e/fixtures/extensions/evals/duplicate-mounts.eval.ts
new file mode 100644
index 000000000..00859539e
--- /dev/null
+++ b/e2e/fixtures/extensions/evals/duplicate-mounts.eval.ts
@@ -0,0 +1,20 @@
+import { defineEval } from "eve/evals";
+
+export default defineEval({
+ description: "Two mounts of one extension keep separate config and durable state.",
+ async test(t) {
+ await t.send(
+ "Call toolkit__toolkit_lookup with account 'primary', then toolkit-alt__toolkit_lookup with account 'secondary'. Bump toolkit's budget twice and toolkit-alt's budget once. Report the lookup configuration and each budget count.",
+ );
+
+ t.succeeded();
+ t.calledTool("toolkit__toolkit_lookup", {
+ 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" },
+ });
+ t.calledTool("toolkit__toolkit_budget", { output: { scope: "toolkit", count: 2 } });
+ t.calledTool("toolkit-alt__toolkit_budget", { output: { scope: "toolkit", count: 1 } });
+ },
+});
diff --git a/packages/eve/package.json b/packages/eve/package.json
index a76dc9b0f..40b2d1c3d 100644
--- a/packages/eve/package.json
+++ b/packages/eve/package.json
@@ -316,6 +316,12 @@
"import": "./dist/src/internal/programmatic-source-loader.js",
"default": "./dist/src/internal/programmatic-source-loader.js"
},
+ "./internal/mount-state": {
+ "eve-source": "./src/internal/mount-state.ts",
+ "types": "./dist/src/internal/mount-state.d.ts",
+ "import": "./dist/src/internal/mount-state.js",
+ "default": "./dist/src/internal/mount-state.js"
+ },
"./local-dev": {
"types": "./dist/src/public/local-dev.d.ts",
"import": "./dist/src/public/local-dev.js",
diff --git a/packages/eve/src/client/agent-info-schema.ts b/packages/eve/src/client/agent-info-schema.ts
index 7a1223c66..374a728c2 100644
--- a/packages/eve/src/client/agent-info-schema.ts
+++ b/packages/eve/src/client/agent-info-schema.ts
@@ -7,7 +7,7 @@ const owner = z.discriminatedUnion("kind", [
z
.object({
kind: z.literal("extension"),
- mountId: mountIdSchema,
+ mountId: mountIdSchema.optional(),
namespace: z.string(),
packageName: z.string(),
})
diff --git a/packages/eve/src/compiler/bundled-extension.ts b/packages/eve/src/compiler/bundled-extension.ts
index 8738f8ab0..7ccb6b808 100644
--- a/packages/eve/src/compiler/bundled-extension.ts
+++ b/packages/eve/src/compiler/bundled-extension.ts
@@ -3,13 +3,13 @@ import {
type ProgrammaticAgentSource,
} from "#compiler/source-graph.js";
import { resolveInstalledPackageInfo, resolvePackageRoot } from "#internal/application/package.js";
+import { parseJsonObject, type JsonObject } from "#shared/json.js";
/** 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 config: JsonObject;
readonly namespace: string;
readonly sourceDirectory: string;
}
@@ -18,7 +18,7 @@ export interface BundledExtensionMount {
readonly declaration: ProgrammaticAgentSource;
readonly entryPath: string;
readonly importSpecifier: string;
- readonly config: Record<string, unknown>;
+ readonly config: JsonObject;
readonly namespace: string;
readonly packageName: string;
readonly packageRoot: string;
@@ -35,13 +35,17 @@ export function createBundledExtensionMount(
const packageRoot = resolvePackageRoot();
const revision = `eve@${packageInfo.version}:development-extensions-v1`;
const logicalPath = `extensions/${descriptor.namespace}.ts`;
+ const config = parseJsonObject(descriptor.config);
const declaration = defineProgrammaticExtensionMountDeclaration({
id: `eve:development-extension:${descriptor.namespace}`,
revision,
modules: [
{
logicalPath,
- loadNamespace: async () => ({ default: await descriptor.loadMount() }),
+ loadNamespace: async () => {
+ const { default: extension } = await import(descriptor.importSpecifier);
+ return { default: extension(config) };
+ },
},
],
});
@@ -50,7 +54,7 @@ export function createBundledExtensionMount(
declaration,
entryPath: descriptor.entryPath,
importSpecifier: descriptor.importSpecifier,
- config: descriptor.config,
+ config,
namespace: descriptor.namespace,
packageName,
packageRoot,
diff --git a/packages/eve/src/compiler/development-extensions.ts b/packages/eve/src/compiler/development-extensions.ts
index 2f2505da6..a943fa67f 100644
--- a/packages/eve/src/compiler/development-extensions.ts
+++ b/packages/eve/src/compiler/development-extensions.ts
@@ -19,9 +19,6 @@ import {
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;
@@ -48,10 +45,6 @@ function getBundledExtensionById(): ReadonlyMap<string, BundledExtensionMount> {
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(SELF_MODIFICATION_CONFIG);
- },
},
] as const satisfies readonly BundledExtensionDescriptor[]
)
diff --git a/packages/eve/src/compiler/extension-mount-evaluation.ts b/packages/eve/src/compiler/extension-mount-evaluation.ts
deleted file mode 100644
index 922481618..000000000
--- a/packages/eve/src/compiler/extension-mount-evaluation.ts
+++ /dev/null
@@ -1,52 +0,0 @@
-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 e12e87fac..a1fb618e0 100644
--- a/packages/eve/src/compiler/load-binding-namespace.ts
+++ b/packages/eve/src/compiler/load-binding-namespace.ts
@@ -5,15 +5,20 @@ 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";
+import {
+ loadAuthoredModuleNamespace,
+ type AuthoredModuleLoadOptions,
+} from "#internal/authored-module-loader.js";
export type CompiledBindingNamespaceLoader = (
sourceId: string,
) => Promise<ProgrammaticModuleNamespace>;
+export interface ExtensionCompileMount {
+ readonly mountId: string;
+ readonly entry?: NonNullable<AuthoredModuleLoadOptions["extension"]>["entry"];
+}
+
/** Loads one node's selected bindings with dependency ordering and per-phase caching. */
export function createCompiledBindingNamespaceLoader(input: {
readonly bindings?: Readonly<Record<string, AgentModuleBinding>>;
@@ -72,11 +77,23 @@ async function loadCompiledBindingNamespace(input: {
readonly registries: readonly AgentSourceRegistry[];
}): Promise<ProgrammaticModuleNamespace> {
if (input.binding.backing.kind === "filesystem") {
+ const mountId =
+ input.binding.owner.kind === "extension" ? input.binding.owner.mountId : undefined;
+ const mount = mountId === undefined ? undefined : input.mounts?.get(mountId);
+ if (mountId !== undefined && input.mounts !== undefined && mount === undefined) {
+ throw new Error(`Missing mount "${mountId}" for extension contribution.`);
+ }
+ const extension: AuthoredModuleLoadOptions["extension"] =
+ mountId === undefined
+ ? undefined
+ : {
+ mountId,
+ evaluationId: input.evaluationId,
+ entry: mount?.entry,
+ };
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,
+ extension,
});
}
const dependencyNamespaces = Object.fromEntries(
@@ -93,11 +110,7 @@ async function loadCompiledBindingNamespace(input: {
});
}
-/** Derives the legacy package-owned state scope used while loading an extension module. */
-export function resolveCompiledModuleExtensionScopeNamespace(
- binding: AgentModuleBinding,
-): string | undefined {
- return binding.owner.kind === "extension"
- ? packageStateNamespace(binding.owner.packageName)
- : undefined;
+/** Derives the owning mount for state handles in an extension module. */
+export function resolveExtensionBindingMountId(binding: AgentModuleBinding): string | undefined {
+ return binding.owner.kind === "extension" ? binding.owner.mountId : undefined;
}
diff --git a/packages/eve/src/compiler/manifest.ts b/packages/eve/src/compiler/manifest.ts
index 8d6a3f6a3..d383d5186 100644
--- a/packages/eve/src/compiler/manifest.ts
+++ b/packages/eve/src/compiler/manifest.ts
@@ -943,19 +943,18 @@ const compiledExtensionMountSchema: z.ZodType<CompiledExtensionMount> = z
packageName: z.string(),
specifier: z.string(),
mountId: mountIdSchema,
- packageNamespace: z.string(),
sourceRoot: z.string(),
mountSourceId: z.string(),
mountSourcePath: z.string(),
+ mountLogicalPath: z.string(),
programmaticImport: z
.object({
specifier: z.string(),
entryPath: z.string(),
- config: z.record(z.string(), z.unknown()),
+ config: jsonObjectSchema,
})
.strict()
.optional(),
- mountLogicalPath: z.string(),
})
.strict();
@@ -1042,11 +1041,6 @@ const compiledSubagentNodeSchema: z.ZodType<CompiledSubagentNode> = z.union([
* 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. */
@@ -1056,13 +1050,16 @@ export interface CompiledExtensionMount {
readonly specifier: string;
/** Canonical path of this mount in the root agent tree. */
readonly mountId: string;
- /** Package-derived namespace for durable extension state keys. */
- readonly packageNamespace: string;
/** Absolute path to the extension's distributed source root. */
readonly sourceRoot: string;
readonly mountSourceId: string;
readonly mountSourcePath: string;
readonly mountLogicalPath: string;
+ readonly programmaticImport?: {
+ readonly specifier: string;
+ readonly entryPath: string;
+ readonly config: JsonObject;
+ };
}
/**
diff --git a/packages/eve/src/compiler/module-map.test.ts b/packages/eve/src/compiler/module-map.test.ts
index 2a3032cdd..50917693f 100644
--- a/packages/eve/src/compiler/module-map.test.ts
+++ b/packages/eve/src/compiler/module-map.test.ts
@@ -14,7 +14,7 @@ const mocks = vi.hoisted(() => ({
_sourcePath: string,
_options: {
readonly externalDependencies: readonly string[];
- readonly extensionScopeNamespace?: string;
+ readonly extension?: { readonly mountId: string };
},
) => ({}),
),
@@ -79,7 +79,7 @@ describe("compiled module maps", () => {
expect(source).toContain("eve:default-sandbox:v1");
});
- it("loads extension bindings with their stable package namespace", async () => {
+ it("loads extension bindings with their logical mount identity", async () => {
const { manifest } = await compileFromMemory({ model: "openai/gpt-5.4" });
const [extensionSourceId, ...applicationSourceIds] = Object.keys(manifest.bindings).sort();
if (extensionSourceId === undefined) throw new Error("Expected at least one module binding.");
@@ -117,12 +117,12 @@ describe("compiled module maps", () => {
expect(mocks.loadAuthoredModuleNamespace).toHaveBeenCalledWith("/extension/tool.ts", {
externalDependencies: [],
- extensionScopeNamespace: "acme-crm",
+ extension: { mountId: "extensions/renamed-mount" },
});
expect(
mocks.loadAuthoredModuleNamespace.mock.calls
.filter(([sourcePath]) => sourcePath.startsWith("/application/"))
- .every(([, options]) => options.extensionScopeNamespace === undefined),
+ .every(([, options]) => options.extension === undefined),
).toBe(true);
});
diff --git a/packages/eve/src/compiler/module-map.ts b/packages/eve/src/compiler/module-map.ts
index e89bdc93b..f0fd40497 100644
--- a/packages/eve/src/compiler/module-map.ts
+++ b/packages/eve/src/compiler/module-map.ts
@@ -14,7 +14,7 @@ import {
import { createCompiledBindingNamespaceLoader } from "#compiler/load-binding-namespace.js";
import { normalizeEsmImportSpecifier } from "#internal/application/import-specifier.js";
-export { resolveCompiledModuleExtensionScopeNamespace } from "#compiler/load-binding-namespace.js";
+export { resolveExtensionBindingMountId } from "#compiler/load-binding-namespace.js";
export type CompiledModuleMap = z.infer<typeof compiledModuleMapSchema>;
diff --git a/packages/eve/src/compiler/mounted-extension.integration.test.ts b/packages/eve/src/compiler/mounted-extension.integration.test.ts
index 41e51d7ae..d1a9403a0 100644
--- a/packages/eve/src/compiler/mounted-extension.integration.test.ts
+++ b/packages/eve/src/compiler/mounted-extension.integration.test.ts
@@ -5,7 +5,7 @@ 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 { deserializeContext, 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";
@@ -45,7 +45,7 @@ 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 () => {
+ it("binds independent config for duplicate mounts, authored subagents, and loaded application graphs", async () => {
const app = await createAppRoot("eve-independent-extension-config-", {
files: {
"agent/agent.mjs": 'export default { model: "openai/gpt-5.4" };',
@@ -64,6 +64,14 @@ describe("mounted extension via authored-source loader", () => {
'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" });',
+ "agent/subagents/research/agent.mjs":
+ 'export default { model: "openai/gpt-5.4", description: "Research accounts" };',
+ "agent/subagents/research/extensions/crm.mjs":
+ 'import ext from "@acme/crm"; export default ext({ account: "research" });',
+ "agent/subagents/support/agent.mjs":
+ 'export default { model: "openai/gpt-5.4", description: "Support accounts" };',
+ "agent/subagents/support/extensions/crm.mjs":
+ 'import ext from "@acme/crm"; export default ext({ account: "support" });',
"node_modules/@acme/crm/package.json": JSON.stringify({
name: "@acme/crm",
type: "module",
@@ -91,8 +99,29 @@ describe("mounted extension via authored-source loader", () => {
},
});
const first = await compileRuntimeGraph(app.appRoot);
- expect(first.manifest.tools.find((tool) => tool.name === "two__account")?.description).toBe(
- "two",
+ const firstMounts = first.manifest.extensionMounts.map((mount) => mount.mountId);
+ expect(firstMounts).toEqual(expect.arrayContaining(["extensions/one", "extensions/two"]));
+ expect(first.manifest.tools.map((tool) => [tool.name, tool.description])).toEqual(
+ expect.arrayContaining([
+ ["one__account", "Read overridden account"],
+ ["two__account", "two"],
+ ]),
+ );
+ const otherCompilation = await compileAgent({ startPath: app.appRoot });
+ expect(
+ otherCompilation.manifest.tools.find((tool) => tool.name === "two__account")?.description,
+ ).toBe("two");
+ await writeFile(
+ join(app.appRoot, "agent/extensions/two.mjs"),
+ 'import ext from "@acme/crm"; export default ext({ account: "updated" });',
+ );
+ const refreshed = await compileAgent({ startPath: app.appRoot });
+ expect(refreshed.manifest.tools.find((tool) => tool.name === "two__account")?.description).toBe(
+ "updated",
+ );
+ await writeFile(
+ join(app.appRoot, "agent/extensions/two.mjs"),
+ 'import ext from "@acme/crm"; export default ext({ account: "two" });',
);
const second = await loadCompiledModuleMapFromAuthoredSource({
compiledArtifactsSource: createDiskRuntimeCompiledArtifactsSource(app.appRoot),
@@ -142,6 +171,17 @@ describe("mounted extension via authored-source loader", () => {
default: typeof first.moduleMap;
};
expect(read(generated.default, "two")).toEqual(accountResult);
+ for (const name of ["research", "support"]) {
+ const subagent = first.manifest.subagents.find((entry) => entry.name === name)!;
+ const tool = subagent.agent.tools.find((entry) => entry.name === "crm__account")!;
+ expect(tool.description).toBe(name);
+ for (const map of [first.moduleMap, second, generated.default]) {
+ const definition = map.nodes[subagent.nodeId]!.modules[tool.sourceId]!.default as {
+ execute: () => { account: string; asset: string; prompt: string };
+ };
+ expect(definition.execute()).toEqual({ ...accountResult, account: name });
+ }
+ }
});
it("allocates a new authored-source graph on each load", async () => {
@@ -173,11 +213,25 @@ describe("mounted extension via authored-source loader", () => {
(map) => map.nodes[ROOT_COMPILED_AGENT_NODE_ID]!.modules[id]!.default,
);
expect(new Set(instances).size).toBe(4);
+ const generatedMaps = (await readdir(join(app.appRoot, ".eve", "compile"))).filter((name) =>
+ /^authored-module-map-[a-f0-9]{64}\.mjs$/.test(name),
+ );
+ expect(generatedMaps).toHaveLength(1);
+ await writeFile(
+ join(app.appRoot, "node_modules/@acme/crm/extension/extension.mjs"),
+ "export default { instance: {}, revision: 2 };",
+ );
+ const updated = await loadCompiledModuleMapFromAuthoredSource({
+ compiledArtifactsSource: source,
+ });
+ expect(updated.nodes[ROOT_COMPILED_AGENT_NODE_ID]!.modules[id]!.default).toMatchObject({
+ revision: 2,
+ });
expect(
- (await readdir(join(app.appRoot, ".eve", "compile"))).filter(
- (name) => name.startsWith("authored-module-map-") && name.endsWith(".mjs"),
+ (await readdir(join(app.appRoot, ".eve", "compile"))).filter((name) =>
+ /^authored-module-map-[a-f0-9]{64}\.mjs$/.test(name),
),
- ).toHaveLength(1);
+ ).toHaveLength(2);
});
it("isolates configured built-in extension mounts", async () => {
@@ -219,6 +273,104 @@ describe("mounted extension via authored-source loader", () => {
expect(secondReasoning).toEqual(["high", "low"]);
});
+ it("keeps state independent across mounts and context restoration", async () => {
+ const app = await createAppRoot("eve-mount-state-", {
+ 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": compatibilityManifest({
+ extension: 1,
+ tool: 1,
+ }),
+ "node_modules/@acme/crm/extension/extension.mjs": "export default {};",
+ "node_modules/@acme/crm/extension/tools/count.mjs": [
+ 'import { defineState } from "eve/context";',
+ 'const count = defineState("requests", () => 0);',
+ 'export default { description: "Count", inputSchema: {}, execute: () => { count.update(n => n + 1); return count.get(); } };',
+ ].join("\n"),
+ },
+ });
+ const { manifest, moduleMap } = await compileRuntimeGraph(app.appRoot);
+ const execute = (map: typeof moduleMap, mount: string) => {
+ const tool = manifest.tools.find((entry) => entry.name === `${mount}__count`)!;
+ return (
+ map.nodes[ROOT_COMPILED_AGENT_NODE_ID]!.modules[tool.sourceId]!.default as {
+ execute: () => number;
+ }
+ ).execute();
+ };
+ const ctx = new ContextContainer();
+ contextStorage.run(ctx, () => {
+ expect(execute(moduleMap, "one")).toBe(1);
+ expect(execute(moduleMap, "one")).toBe(2);
+ expect(execute(moduleMap, "two")).toBe(1);
+ });
+ const saved = serializeContext(ctx);
+ expect(Object.keys(saved).filter((name) => name.startsWith("eve:mount.v1:"))).toHaveLength(2);
+ const restored = await deserializeContext(saved);
+ contextStorage.run(restored, () => {
+ expect(execute(moduleMap, "one")).toBe(3);
+ expect(execute(moduleMap, "two")).toBe(2);
+ });
+
+ const moduleMapPath = join(app.appRoot, ".eve", "compile", "state-map.mjs");
+ const { code } = await bundleAuthoredModuleMapForGeneration({
+ appRoot: app.appRoot,
+ manifest,
+ moduleMapPath,
+ });
+ await writeFile(moduleMapPath, code);
+ const generated = (await import(`${moduleMapPath}?test=mount-state`)) as {
+ default: typeof moduleMap;
+ };
+ contextStorage.run(restored, () => {
+ expect(execute(generated.default, "one")).toBe(4);
+ expect(execute(generated.default, "two")).toBe(3);
+ });
+ });
+
+ it("rejects application state using a generated mount key", async () => {
+ const app = await createAppRoot("eve-mount-state-collision-", {
+ files: {
+ "agent/agent.mjs": 'export default { model: "openai/gpt-5.4" };',
+ "agent/instructions.md": "Work with the available tools.",
+ "agent/extensions/crm.mjs": 'export { default } from "@acme/crm";',
+ "agent/tools/intrude.mjs": [
+ 'import { defineState } from "eve/context";',
+ 'defineState("eve:mount.v1:extensions%2Fcrm:requests", () => 0);',
+ 'export default { description: "Read state", inputSchema: {}, execute: () => 0 };',
+ ].join("\n"),
+ "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,
+ }),
+ "node_modules/@acme/crm/extension/extension.mjs": "export default {};",
+ "node_modules/@acme/crm/extension/tools/count.mjs": [
+ 'import { defineState } from "eve/context";',
+ 'const count = defineState("requests", () => 0);',
+ 'export default { description: "Count", inputSchema: {}, execute: () => count.get() };',
+ ].join("\n"),
+ },
+ });
+ await expect(compileAgent({ startPath: app.appRoot })).rejects.toMatchObject({
+ cause: expect.objectContaining({ message: expect.stringMatching(/reserved "eve:mount\."/) }),
+ });
+ });
+
it("keeps module instances distinct across mounts in a generation graph", async () => {
const app = await createAppRoot("eve-mount-instances-", {
files: {
diff --git a/packages/eve/src/compiler/normalize-manifest-helpers.ts b/packages/eve/src/compiler/normalize-manifest-helpers.ts
index d64bd03ea..bee53aa99 100644
--- a/packages/eve/src/compiler/normalize-manifest-helpers.ts
+++ b/packages/eve/src/compiler/normalize-manifest-helpers.ts
@@ -3,7 +3,7 @@ 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 { mountRefNamespace } from "#discover/extensions.js";
import type { AgentSourceManifest, LocalSubagentSourceRef } from "#discover/manifest.js";
import type {
CompiledAgentDefinition,
@@ -12,6 +12,11 @@ import type {
CompiledSubagentNode,
} from "#compiler/manifest.js";
import type { ModuleSourceRef } from "#shared/source-ref.js";
+import type { ExtensionCompileMount } from "#compiler/load-binding-namespace.js";
+import { createCompiledChannelRoutePlan } from "#compiler/channel-route-plan.js";
+import { describeAgentSourceCandidate } from "#compiler/source-graph.js";
+import type { FinalizedNodeSourceState } from "#compiler/node-source-state.js";
+import type { CompilerDiagnostic } from "#compiler/diagnostics.js";
import { normalizeSubagentConfig } from "#compiler/normalize-subagent.js";
import {
canonicalSourceSlot,
@@ -197,6 +202,76 @@ export function createCompiledRemoteAgent(input: {
return node;
}
+export function compileChannelRoutes(
+ state: FinalizedNodeSourceState,
+ channels: readonly import("#compiler/manifest.js").CompiledChannelDefinition[],
+ diagnostics: CompilerDiagnostic[],
+ nodeId: string,
+) {
+ const channelRoutes = createCompiledChannelRoutePlan({
+ bindings: state.bindings,
+ channels,
+ diagnostics,
+ nodeId,
+ sources: Object.fromEntries(
+ state.orderedCandidates.map((candidate) => [
+ candidate.sourceId,
+ describeAgentSourceCandidate(candidate),
+ ]),
+ ),
+ });
+ for (const channel of channelRoutes.effective) {
+ state.evaluation.requireRuntimeEntry(channel.sourceId);
+ }
+ return channelRoutes;
+}
+
+export function resolveExtensionMountSource(
+ manifest: AgentSourceManifest,
+ mount: AgentSourceManifest["resolvedExtensions"][number],
+ nodePath: string,
+) {
+ const mountRef =
+ mount.programmaticDeclaration ??
+ manifest.extensions.find((entry) => mountRefNamespace(entry.logicalPath) === mount.namespace);
+ if (mountRef === undefined) return undefined;
+ return {
+ mountId: extensionMountId(nodePath, mount.namespace),
+ logicalPath: mountRef.logicalPath,
+ mountSourceId: mountRef.sourceId,
+ mountSourcePath: posix.join(manifest.agentRoot, mountRef.logicalPath),
+ };
+}
+
+export function createExtensionCompileMounts(
+ manifest: AgentSourceManifest,
+ nodePath: string,
+): {
+ mounts: Map<string, ExtensionCompileMount>;
+ sourceIds: Map<string, string>;
+} {
+ const mounts = new Map<string, ExtensionCompileMount>();
+ const sourceIds = new Map<string, string>();
+ for (const mount of manifest.resolvedExtensions) {
+ const source = resolveExtensionMountSource(manifest, mount, nodePath);
+ if (source === undefined) continue;
+ sourceIds.set(source.mountId, source.mountSourceId);
+ mounts.set(source.mountId, {
+ mountId: source.mountId,
+ entry:
+ mount.programmaticDeclaration === undefined
+ ? {
+ mountSourcePath: source.mountSourcePath,
+ packageName: mount.packageName,
+ sourceRoot: mount.sourceRoot,
+ specifier: mount.specifier,
+ }
+ : undefined,
+ });
+ }
+ return { mounts, sourceIds };
+}
+
export function compileExtensionMounts(
manifest: AgentSourceManifest,
composed: ComposedAgentModuleCandidates,
@@ -204,15 +279,13 @@ export function compileExtensionMounts(
): CompiledExtensionMount[] {
const selected = collectSelectedSourceIds(composed);
return manifest.resolvedExtensions.flatMap((mount) => {
- const mountRef =
- mount.programmaticDeclaration ??
- manifest.extensions.find((entry) => mountRefNamespace(entry.logicalPath) === mount.namespace);
- if (mountRef === undefined || !selected.has(mountRef.sourceId)) return [];
+ const source = resolveExtensionMountSource(manifest, mount, nodePath);
+ if (source === undefined || !selected.has(source.mountSourceId)) return [];
return [
{
externalDependencies: [...mount.externalDependencies],
- mountLogicalPath: mountRef.logicalPath,
- mountSourceId: mountRef.sourceId,
+ mountLogicalPath: source.logicalPath,
+ mountSourceId: source.mountSourceId,
...(mount.programmaticDeclaration === undefined
? {}
: {
@@ -222,12 +295,11 @@ export function compileExtensionMounts(
config: mount.programmaticDeclaration.config,
},
}),
- mountSourcePath: posix.join(manifest.agentRoot, mountRef.logicalPath),
+ mountSourcePath: source.mountSourcePath,
namespace: mount.namespace,
packageName: mount.packageName,
specifier: mount.specifier,
- mountId: extensionMountId(nodePath, mount.namespace),
- packageNamespace: packageStateNamespace(mount.packageName),
+ mountId: source.mountId,
sourceRoot: mount.sourceRoot,
},
];
diff --git a/packages/eve/src/compiler/normalize-manifest.ts b/packages/eve/src/compiler/normalize-manifest.ts
index 628aa66df..165dc0a4a 100644
--- a/packages/eve/src/compiler/normalize-manifest.ts
+++ b/packages/eve/src/compiler/normalize-manifest.ts
@@ -1,8 +1,7 @@
import { randomUUID } from "node:crypto";
-import {
- createMountEvaluationContext,
- type ExtensionCompileMount,
-} from "#compiler/extension-mount-evaluation.js";
+import type { ExtensionCompileMount } from "#compiler/load-binding-namespace.js";
+import { NodeModuleEvaluationContext } from "#compiler/module-lifecycle.js";
+import { bindingMountId } from "#compiler/extension-mount-bindings.js";
import type { AgentSourceManifest } from "#discover/manifest.js";
import {
@@ -56,7 +55,6 @@ import {
normalizeSubagentConfig,
} from "#compiler/normalize-subagent.js";
import { compileToolEntry } from "#compiler/normalize-tool.js";
-import { createCompiledChannelRoutePlan } from "#compiler/channel-route-plan.js";
import {
finalizeNodeSourceState,
type ComposedNodeSourceGraph,
@@ -70,6 +68,8 @@ import {
assertUniqueBy,
assertUniqueRegistryIds,
compileExtensionMounts,
+ compileChannelRoutes,
+ createExtensionCompileMounts,
createCompiledRemoteAgent,
expectSubagentDescription,
mergeExternalDependencies,
@@ -84,7 +84,6 @@ import {
composeAgentModuleCandidates,
createAgentModuleBinding,
createProgrammaticModuleCandidates,
- describeAgentSourceCandidate,
disableComposedCandidate,
instantiateProgrammaticTemplate,
isAgentModuleCandidate,
@@ -441,12 +440,14 @@ class AgentGraphCompiler {
externalDependencies: readonly string[],
): Promise<PhaseOneNodeSourceState> {
const graph = this.composeNodeSources(input, externalDependencies);
- const evaluation = createMountEvaluationContext({
- node: input,
- registries: this.registries,
- mounts: this.mounts,
- evaluationId: this.evaluationId,
- });
+ const { mounts, sourceIds } = createExtensionCompileMounts(input.manifest, input.nodePath);
+ for (const [mountId, mount] of mounts) this.mounts.set(mountId, mount);
+ const evaluation = new NodeModuleEvaluationContext(
+ this.registries,
+ (binding) => sourceIds.get(bindingMountId(binding) ?? ""),
+ this.mounts,
+ this.evaluationId,
+ );
evaluation.setBindings(
Object.fromEntries(
[...graph.composed.selected.values()]
@@ -620,21 +621,7 @@ class AgentGraphCompiler {
assertUniqueBy(dynamicConnections, (connection) => connection.slug, "dynamic connection slug");
assertUniqueBy(skills, (skill) => skill.name, "skill name");
- const channelRoutes = createCompiledChannelRoutePlan({
- bindings: state.bindings,
- channels,
- diagnostics: this.diagnostics,
- nodeId: input.nodeId,
- sources: Object.fromEntries(
- state.orderedCandidates.map((candidate) => [
- candidate.sourceId,
- describeAgentSourceCandidate(candidate),
- ]),
- ),
- });
- for (const channel of channelRoutes.effective) {
- state.evaluation.requireRuntimeEntry(channel.sourceId);
- }
+ const channelRoutes = compileChannelRoutes(state, channels, this.diagnostics, input.nodeId);
const extensionMounts = compileExtensionMounts(input.manifest, state.composed, input.nodePath);
for (const mount of extensionMounts) {
state.evaluation.requireRuntimeEntry(mount.mountSourceId);
diff --git a/packages/eve/src/compiler/source-graph.test.ts b/packages/eve/src/compiler/source-graph.test.ts
index e06f65892..4780cc0ec 100644
--- a/packages/eve/src/compiler/source-graph.test.ts
+++ b/packages/eve/src/compiler/source-graph.test.ts
@@ -17,7 +17,6 @@ import {
type ProgrammaticAgentSource,
type ProgrammaticModuleLoadContext,
} from "#compiler/source-graph.js";
-import { createBundledExtensionMount } from "#compiler/bundled-extension.js";
import { materializeAuthoredModuleExport } from "#internal/authored-module.js";
function source(
@@ -45,41 +44,6 @@ function candidate(
})[0]!;
}
-describe("bundled extension declarations", () => {
- it("registers a configured extension declaration without enumerating contributions", async () => {
- 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",
- });
- const registry = createAgentSourceRegistry([], {
- extensionDeclarations: [mount.declaration],
- });
- const declaration = mount.declaration.modules[0]!;
-
- expect(declaration.logicalPath).toBe("extensions/example.ts");
- expect(registry.sources.get(mount.declaration.id)).toMatchObject({
- id: mount.declaration.id,
- });
- await expect(
- loadProgrammaticModuleNamespace({
- backing: {
- kind: "programmatic",
- moduleId: declaration.logicalPath,
- registryId: mount.declaration.id,
- revision: mount.declaration.revision,
- },
- registries: [registry],
- }),
- ).resolves.toEqual({ default: { config: { enabled: true }, mounted: true } });
- expect(loadMount).toHaveBeenCalledOnce();
- });
-});
-
describe("derived programmatic sources", () => {
it("memoizes definition factories within one module namespace", async () => {
const factory = vi.fn(() => ({ instance: Symbol("definition") }));
diff --git a/packages/eve/src/compiler/source-graph.ts b/packages/eve/src/compiler/source-graph.ts
index 1628db03e..1250ad9ad 100644
--- a/packages/eve/src/compiler/source-graph.ts
+++ b/packages/eve/src/compiler/source-graph.ts
@@ -188,6 +188,14 @@ export interface AgentModuleCandidate {
readonly sourceId: string;
}
+export function bindingMountId(binding: AgentModuleBinding): string | undefined {
+ return binding.backing.kind === "filesystem" && binding.backing.mountId !== undefined
+ ? binding.backing.mountId
+ : binding.owner.kind === "extension"
+ ? binding.owner.mountId
+ : undefined;
+}
+
export interface AgentModuleBinding {
readonly backing: AgentModuleBacking;
readonly logicalPath: string;
diff --git a/packages/eve/src/context/serialize.test.ts b/packages/eve/src/context/serialize.test.ts
index 4598300e7..0d1758382 100644
--- a/packages/eve/src/context/serialize.test.ts
+++ b/packages/eve/src/context/serialize.test.ts
@@ -1,11 +1,14 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { createRuntimeAdapterRegistry } from "#runtime/channels/registry.js";
+import { compileFromMemory } from "#internal/testing/compile-from-memory.js";
import { ContextContainer } from "#context/container.js";
import { ContextKey } from "#context/key.js";
+import { defineState } from "#public/definitions/state.js";
import type { CompiledBundle } from "#runtime/sessions/runtime-context-keys.js";
import { BundleKey, ChannelKey } from "#runtime/sessions/runtime-context-keys.js";
import { deserializeContext, serializeContext } from "#context/serialize.js";
+import * as manifestLoader from "#runtime/loaders/manifest.js";
const BaseKey = new ContextKey<string>("test.deserialize.base");
const DerivedKey = new ContextKey<string>("test.deserialize.derived", {
@@ -31,6 +34,136 @@ describe("deserializeContext", () => {
});
});
+describe("state layout admission", () => {
+ it("rejects unmarked legacy keys before dropping their values", async () => {
+ const { manifest } = await compileFromMemory({ model: "openai/gpt-5.4" });
+ const bundle = { compiledArtifactsSource: { kind: "bundled" } } as CompiledBundle;
+ const deserialize = vi.spyOn(BundleKey.codec!, "deserialize").mockResolvedValue(bundle);
+ const loadManifest = vi
+ .spyOn(manifestLoader, "loadCompiledManifest")
+ .mockResolvedValue(manifest);
+ try {
+ await expect(
+ deserializeContext({ "eve.bundle": {}, "acme-crm.requests": 4 }),
+ ).rejects.toThrow("Incompatible context state layout");
+ // Registration in a previous graph must not turn a reserved legacy authored name
+ // into proof that it belongs to the new layout.
+ new ContextKey("eve:mount.v1:extensions%2Fcrm:requests");
+ await expect(
+ deserializeContext({
+ "eve.bundle": {},
+ "eve:mount.v1:extensions%2Fcrm:requests": 4,
+ }),
+ ).rejects.toThrow("Incompatible context state layout");
+ } finally {
+ deserialize.mockRestore();
+ loadManifest.mockRestore();
+ }
+ });
+
+ it("admits an unmarked checkpoint only when its graph has no mounts", async () => {
+ const { manifest } = await compileFromMemory({ model: "openai/gpt-5.4" });
+ const bundle = { compiledArtifactsSource: { kind: "bundled" } } as CompiledBundle;
+ const deserialize = vi.spyOn(BundleKey.codec!, "deserialize").mockResolvedValue(bundle);
+ const loadManifest = vi
+ .spyOn(manifestLoader, "loadCompiledManifest")
+ .mockResolvedValue(manifest);
+ try {
+ const restored = await deserializeContext({ "eve.bundle": {} });
+ expect(restored.get(BundleKey)).toBe(bundle);
+ loadManifest.mockResolvedValue({
+ ...manifest,
+ extensionMounts: [
+ { mountId: "extensions/crm" } as (typeof manifest.extensionMounts)[number],
+ ],
+ });
+ await expect(deserializeContext({ "eve.bundle": {} })).rejects.toThrow(
+ "Incompatible context state layout",
+ );
+ } finally {
+ deserialize.mockRestore();
+ loadManifest.mockRestore();
+ }
+ });
+
+ it("preserves unchanged application state regardless of prior module registrations", async () => {
+ const { manifest } = await compileFromMemory({ model: "openai/gpt-5.4" });
+ const bundle = { compiledArtifactsSource: { kind: "bundled" } } as CompiledBundle;
+ const name = "test.legacy.app-owned";
+ const deserialize = vi.spyOn(BundleKey.codec!, "deserialize").mockImplementation(async () => {
+ defineState(name, () => 0);
+ return bundle;
+ });
+ const loadManifest = vi
+ .spyOn(manifestLoader, "loadCompiledManifest")
+ .mockResolvedValue(manifest);
+ try {
+ const restored = await deserializeContext({ "eve.bundle": {}, [name]: 4 });
+ expect(restored.get(BundleKey)).toBe(bundle);
+ // The registered key is retained; an unregistered name still refuses the restore.
+ expect([...restored.entries()].map(([key]) => key.name)).toContain(name);
+ await expect(
+ deserializeContext({ "eve.bundle": {}, "test.legacy.unknown": 4 }),
+ ).rejects.toThrow("Incompatible context state layout");
+ } finally {
+ deserialize.mockRestore();
+ loadManifest.mockRestore();
+ }
+ });
+
+ it("drops an unknown application key in a current-layout checkpoint", async () => {
+ const bundle = { compiledArtifactsSource: { kind: "bundled" } } as CompiledBundle;
+ const deserialize = vi.spyOn(BundleKey.codec!, "deserialize").mockResolvedValue(bundle);
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ try {
+ const restored = await deserializeContext({
+ "eve.bundle": {},
+ "eve.stateLayout": 1,
+ "test.renamed.app-owned": 4,
+ });
+ expect(restored.get(BundleKey)).toBe(bundle);
+ expect([...restored.entries()]).toHaveLength(1);
+ expect(warn).toHaveBeenCalledWith(
+ expect.stringContaining("dropping unknown context key"),
+ expect.objectContaining({ key: "test.renamed.app-owned" }),
+ );
+ } finally {
+ deserialize.mockRestore();
+ warn.mockRestore();
+ }
+ });
+
+ it("rejects unmarked reserved state even when the declaration has been removed", async () => {
+ const savedName = "eve:mount.v1:extensions%2Fremoved:requests";
+ new ContextKey(savedName);
+ await expect(deserializeContext({ [savedName]: 4 })).rejects.toThrow(
+ "Incompatible context state layout",
+ );
+ });
+
+ it("keeps marked mount state in a context without a bundle", async () => {
+ const name = "eve:mount.v1:extensions%2Fcrm:requests";
+ const key = new ContextKey<number>(name);
+ const original = new ContextContainer();
+ original.set(key, 4);
+ const saved = serializeContext(original);
+ expect(saved["eve.stateLayout"]).toBe(1);
+ expect((await deserializeContext(saved)).get(key)).toBe(4);
+ });
+
+ it("rejects an unsupported explicit layout", async () => {
+ await expect(deserializeContext({ "eve.bundle": {}, "eve.stateLayout": 2 })).rejects.toThrow(
+ "Incompatible context state layout",
+ );
+ });
+
+ it("stamps bundle-backed context snapshots with the current layout", () => {
+ const ctx = new ContextContainer();
+ ctx.set(BundleKey, { compiledArtifactsSource: {} } as CompiledBundle);
+ expect(serializeContext(ctx)["eve.stateLayout"]).toBe(1);
+ });
+});
+
describe("serialize/deserialize error logging", () => {
let warnSpy: ReturnType<typeof vi.spyOn>;
let errorSpy: ReturnType<typeof vi.spyOn>;
diff --git a/packages/eve/src/context/serialize.ts b/packages/eve/src/context/serialize.ts
index 74db747b4..a19f8da39 100644
--- a/packages/eve/src/context/serialize.ts
+++ b/packages/eve/src/context/serialize.ts
@@ -1,9 +1,12 @@
import { type AlsContext, ContextContainer } from "#context/container.js";
import { resolveKey } from "#context/key.js";
import { createLogger, logError } from "#internal/logging.js";
+import { loadCompiledManifest } from "#runtime/loaders/manifest.js";
import { BundleKey } from "#runtime/sessions/runtime-context-keys.js";
const log = createLogger("context.serialize");
+const STATE_LAYOUT_KEY = "eve.stateLayout";
+const STATE_LAYOUT_VERSION = 1;
/**
* Serializes every value in the context to a plain JSON record.
@@ -22,6 +25,12 @@ export function serializeContext(ctx: AlsContext): Record<string, unknown> {
throw error;
}
}
+ if (
+ data[BundleKey.name] !== undefined ||
+ Object.keys(data).some((name) => name.startsWith("eve:mount."))
+ ) {
+ data[STATE_LAYOUT_KEY] = STATE_LAYOUT_VERSION;
+ }
return data;
}
@@ -35,17 +44,51 @@ export async function deserializeContext(data: Record<string, unknown>): Promise
const ctx = new ContextContainer();
const serializedBundle = data[BundleKey.name];
+ if (data[STATE_LAYOUT_KEY] !== undefined && data[STATE_LAYOUT_KEY] !== STATE_LAYOUT_VERSION) {
+ throw incompatibleStateLayout();
+ }
+ if (
+ data[STATE_LAYOUT_KEY] === undefined &&
+ Object.keys(data).some((name) => data[name] !== undefined && name.startsWith("eve:mount."))
+ ) {
+ throw incompatibleStateLayout();
+ }
if (serializedBundle !== undefined) {
const codec = BundleKey.codec;
if (codec === undefined) {
throw new Error('Context key "eve.bundle" is missing a codec.');
}
- ctx.set(BundleKey, await codec.deserialize(serializedBundle, ctx));
+ const bundle = await codec.deserialize(serializedBundle, ctx);
+ if (data[STATE_LAYOUT_KEY] === undefined) {
+ const manifest = await loadCompiledManifest({
+ compiledArtifactsSource: bundle.compiledArtifactsSource,
+ });
+ if (
+ [manifest, ...manifest.subagents.map((subagent) => subagent.agent)].some(
+ (node) => node.extensionMounts.length > 0,
+ )
+ ) {
+ throw incompatibleStateLayout();
+ }
+ }
+ if (
+ data[STATE_LAYOUT_KEY] === undefined &&
+ Object.keys(data).some(
+ (name) =>
+ name !== BundleKey.name &&
+ name !== STATE_LAYOUT_KEY &&
+ data[name] !== undefined &&
+ resolveKey(name) === undefined,
+ )
+ ) {
+ throw incompatibleStateLayout();
+ }
+ ctx.set(BundleKey, bundle);
}
for (const [name, raw] of Object.entries(data)) {
if (raw === undefined) continue;
- if (name === BundleKey.name) continue;
+ if (name === BundleKey.name || name === STATE_LAYOUT_KEY) continue;
const key = resolveKey(name);
if (key === undefined) {
// Unregistered key (e.g. renamed): dropping it silently loses data, so warn.
@@ -61,3 +104,9 @@ export async function deserializeContext(data: Record<string, unknown>): Promise
}
return ctx;
}
+
+function incompatibleStateLayout(): Error {
+ return new Error(
+ "Incompatible context state layout. Restore this session with its original deployment or start a new session; legacy extension state cannot be assigned to mounts automatically.",
+ );
+}
diff --git a/packages/eve/src/discover/bundled-extension.test.ts b/packages/eve/src/discover/bundled-extension.test.ts
index 2981ffddf..2ffd77c2b 100644
--- a/packages/eve/src/discover/bundled-extension.test.ts
+++ b/packages/eve/src/discover/bundled-extension.test.ts
@@ -7,7 +7,6 @@ import { createMemoryProjectSource } from "#discover/project-source.js";
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: {},
diff --git a/packages/eve/src/discover/bundled-extension.ts b/packages/eve/src/discover/bundled-extension.ts
index b6e7d0059..2447122da 100644
--- a/packages/eve/src/discover/bundled-extension.ts
+++ b/packages/eve/src/discover/bundled-extension.ts
@@ -32,11 +32,11 @@ export async function discoverBundledExtension(input: {
packageName: input.mount.packageName,
packageRoot: input.mount.packageRoot,
programmaticDeclaration: {
+ logicalPath: declaration.logicalPath,
+ sourceId: `${input.mount.declaration.id}:${declaration.logicalPath}`,
importSpecifier: input.mount.importSpecifier,
entryPath: input.mount.entryPath,
config: input.mount.config,
- logicalPath: declaration.logicalPath,
- sourceId: `${input.mount.declaration.id}:${declaration.logicalPath}`,
},
sourceRoot: input.mount.sourceRoot,
specifier: input.mount.specifier,
diff --git a/packages/eve/src/discover/extensions.test.ts b/packages/eve/src/discover/extensions.test.ts
index 81da8fc52..1422dfb69 100644
--- a/packages/eve/src/discover/extensions.test.ts
+++ b/packages/eve/src/discover/extensions.test.ts
@@ -4,7 +4,6 @@ import {
locateExtensionMount,
locateExtensionMountPackage,
mountNamespace,
- packageStateNamespace,
} from "#discover/extensions.js";
import { createModuleSourceRef } from "#discover/manifest.js";
import { createMemoryProjectSource } from "#discover/project-source.js";
@@ -16,24 +15,6 @@ describe("mountNamespace", () => {
});
});
-describe("packageStateNamespace", () => {
- it("keeps a plain package name", () => {
- expect(packageStateNamespace("toolkit-extension")).toBe("toolkit-extension");
- });
-
- it("flattens a scoped package name", () => {
- expect(packageStateNamespace("@acme/crm")).toBe("acme-crm");
- });
-
- it("replaces characters that are unsafe in a key segment", () => {
- expect(packageStateNamespace("@acme/crm.tools")).toBe("acme-crm.tools");
- });
-
- it("falls back to a stable token for a degenerate name", () => {
- expect(packageStateNamespace("@")).toBe("extension");
- });
-});
-
describe("locateExtensionMountPackage", () => {
it("resolves a package-local built-in extension without a compatibility manifest", async () => {
const appRoot = "/repo/apps/agent";
diff --git a/packages/eve/src/discover/extensions.ts b/packages/eve/src/discover/extensions.ts
index 496bec073..318d17ff5 100644
--- a/packages/eve/src/discover/extensions.ts
+++ b/packages/eve/src/discover/extensions.ts
@@ -147,19 +147,6 @@ export function mountRefNamespace(logicalPath: string): string {
return mountNamespace(logicalPath);
}
-/**
- * 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 (
- packageName
- .replace(/^@/, "")
- .replace(/[^a-zA-Z0-9._-]+/g, "-")
- .replace(/^-+|-+$/g, "") || "extension"
- );
-}
-
/**
* Resolves one extension mount to its package and agent-shaped source root
* without importing the mount module. Reads the mount source text to extract
diff --git a/packages/eve/src/discover/manifest.ts b/packages/eve/src/discover/manifest.ts
index f04fe0632..eaf8902b2 100644
--- a/packages/eve/src/discover/manifest.ts
+++ b/packages/eve/src/discover/manifest.ts
@@ -1,4 +1,5 @@
import { basename, relative, resolve } from "node:path";
+import type { JsonObject } from "#shared/json.js";
import type {
MarkdownSourceRef,
ModuleSourceRef,
@@ -149,11 +150,11 @@ 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;
+ readonly importSpecifier: string;
+ readonly entryPath: string;
+ readonly config: JsonObject;
};
/** Mount namespace derived from the mount filename (e.g. `crm`). */
readonly namespace: string;
diff --git a/packages/eve/src/execution/file-memory.integration.test.ts b/packages/eve/src/execution/file-memory.integration.test.ts
index bc0967071..bf8f35311 100644
--- a/packages/eve/src/execution/file-memory.integration.test.ts
+++ b/packages/eve/src/execution/file-memory.integration.test.ts
@@ -91,6 +91,7 @@ async function runTurn(input: { readonly message: string; readonly principalId:
principalType: "user",
},
"eve.bundle": { source: createBundledRuntimeCompiledArtifactsSource() },
+ "eve.stateLayout": 1,
"eve.channel": { kind: "http", state: {} },
"eve.continuationToken": `http:file-memory:${input.principalId}:${crypto.randomUUID()}`,
},
diff --git a/packages/eve/src/execution/legacy-session/import.integration.test.ts b/packages/eve/src/execution/legacy-session/import.integration.test.ts
index 4a46ae8d7..043dc3f4b 100644
--- a/packages/eve/src/execution/legacy-session/import.integration.test.ts
+++ b/packages/eve/src/execution/legacy-session/import.integration.test.ts
@@ -38,6 +38,7 @@ describe("legacy session import", () => {
serializedContext: {
"eve.auth": null,
"eve.bundle": { source: createBundledRuntimeCompiledArtifactsSource() },
+ "eve.stateLayout": 1,
"eve.channel": { kind: "http", state: {} },
},
},
@@ -249,6 +250,7 @@ function legacyContext() {
return {
"eve.auth": null,
"eve.bundle": { source: createBundledRuntimeCompiledArtifactsSource() },
+ "eve.stateLayout": 1,
"eve.channel": { kind: "http", state: {} },
};
}
diff --git a/packages/eve/src/execution/session-limit-cancellation.integration.test.ts b/packages/eve/src/execution/session-limit-cancellation.integration.test.ts
index a9211423b..552acd5ee 100644
--- a/packages/eve/src/execution/session-limit-cancellation.integration.test.ts
+++ b/packages/eve/src/execution/session-limit-cancellation.integration.test.ts
@@ -30,6 +30,7 @@ function buildSerializedContext(overrides: {
return {
"eve.auth": null,
"eve.bundle": { source: createBundledRuntimeCompiledArtifactsSource() },
+ "eve.stateLayout": 1,
"eve.capabilities": { requestInput: true },
"eve.channel": { kind: overrides.channelKind, state: {} },
"eve.continuationToken": overrides.continuationToken,
diff --git a/packages/eve/src/execution/session/handoff-steps.test.ts b/packages/eve/src/execution/session/handoff-steps.test.ts
index e75d21220..13ea14545 100644
--- a/packages/eve/src/execution/session/handoff-steps.test.ts
+++ b/packages/eve/src/execution/session/handoff-steps.test.ts
@@ -1,7 +1,7 @@
import { createTestSessionState } from "#internal/testing/session-state.js";
import { beforeEach, describe, expect, it, vi } from "vitest";
-import type { SessionCheckpoint } from "#execution/session/handoff.js";
+import { SESSION_CHECKPOINT_VERSION, type SessionCheckpoint } from "#execution/session/handoff.js";
import { validateSessionCheckpointStep } from "#execution/session/handoff-steps.js";
import { BundleKey } from "#runtime/sessions/runtime-context-keys.js";
@@ -55,7 +55,7 @@ describe("validateSessionCheckpointStep", () => {
);
});
- it.each([5, 6, 7, 8, 10])(
+ it.each([5, 6, 7, 8, 9, 11])(
"rejects checkpoint version %s before reading nested state",
async (version) => {
const checkpoint = createCheckpoint();
@@ -84,7 +84,7 @@ describe("validateSessionCheckpointStep", () => {
function createCheckpoint(): SessionCheckpoint {
return {
- version: 9,
+ version: SESSION_CHECKPOINT_VERSION,
sessionTimeoutMs: false,
serializedContext: {},
sessionState: createTestSessionState({
diff --git a/packages/eve/src/execution/session/handoff-steps.ts b/packages/eve/src/execution/session/handoff-steps.ts
index 4eb9a66ca..724e8cff8 100644
--- a/packages/eve/src/execution/session/handoff-steps.ts
+++ b/packages/eve/src/execution/session/handoff-steps.ts
@@ -55,7 +55,7 @@ export async function validateSessionCheckpointStep(input: {
const { checkpoint } = input;
if (checkpoint.version !== SESSION_CHECKPOINT_VERSION) {
throw new Error(
- `Unsupported session checkpoint version ${JSON.stringify(checkpoint.version)}; this deployment reads version ${SESSION_CHECKPOINT_VERSION}. Start a new session on this deployment.`,
+ `Unsupported session checkpoint version ${JSON.stringify(checkpoint.version)}; this deployment reads version ${SESSION_CHECKPOINT_VERSION}. Keep the session on its original deployment or start a new session here.`,
);
}
const timeout = checkpoint.sessionTimeoutMs;
diff --git a/packages/eve/src/execution/session/handoff.test.ts b/packages/eve/src/execution/session/handoff.test.ts
index 97b8ca6a8..7e2bc7813 100644
--- a/packages/eve/src/execution/session/handoff.test.ts
+++ b/packages/eve/src/execution/session/handoff.test.ts
@@ -43,7 +43,7 @@ describe("SessionHandoff", () => {
anchorRunId: "session-1",
checkpoint: expect.objectContaining({
sessionTimeoutMs: 60_000,
- version: 9,
+ version: 10,
}),
delivery: trigger.delivery,
targetDeploymentId: "deployment-b",
diff --git a/packages/eve/src/execution/session/handoff.ts b/packages/eve/src/execution/session/handoff.ts
index f36d03f30..eb916820f 100644
--- a/packages/eve/src/execution/session/handoff.ts
+++ b/packages/eve/src/execution/session/handoff.ts
@@ -17,9 +17,10 @@ import type { AgentWorkflowRetentionDefinition } from "#shared/agent-definition.
* Cross-deployment checkpoint contract. The successor may run a different eve
* build than the owner that produced it; bump when any field changes shape so
* an incompatible successor rejects the handoff instead of misreading state.
- * Dynamic skill manifests retain instruction bodies and package revisions.
+ * Mount-owned state requires a new version so older readers reject it rather
+ * than dropping unrecognized state keys during reverse handoff.
*/
-export const SESSION_CHECKPOINT_VERSION = 9;
+export const SESSION_CHECKPOINT_VERSION = 10;
/** Everything a successor needs to continue an idle session. Hooks are derived from the state. */
export interface SessionCheckpoint {
diff --git a/packages/eve/src/execution/turn-cancellation.integration.test.ts b/packages/eve/src/execution/turn-cancellation.integration.test.ts
index 9ae4ded1b..24758626a 100644
--- a/packages/eve/src/execution/turn-cancellation.integration.test.ts
+++ b/packages/eve/src/execution/turn-cancellation.integration.test.ts
@@ -47,6 +47,7 @@ function buildSerializedContext(overrides: {
return {
"eve.auth": null,
"eve.bundle": { source: createBundledRuntimeCompiledArtifactsSource() },
+ "eve.stateLayout": 1,
"eve.channel": { kind: overrides.channelKind, state: {} },
"eve.continuationToken": overrides.continuationToken,
};
diff --git a/packages/eve/src/execution/workflow-runtime.test.ts b/packages/eve/src/execution/workflow-runtime.test.ts
index 76b1fd9c8..a2b54d4bc 100644
--- a/packages/eve/src/execution/workflow-runtime.test.ts
+++ b/packages/eve/src/execution/workflow-runtime.test.ts
@@ -161,7 +161,7 @@ describe("session owner starts", () => {
getRunMock.mockReturnValue({ getWritable: () => sessionWritable });
startMock.mockResolvedValue({ runId: "owner-2" });
const checkpoint = {
- version: 9,
+ version: 10,
serializedContext: {},
sessionState: { continuationToken: "continuation-1", sessionId: "session-1" },
sessionTimeoutMs: 60_000,
@@ -592,6 +592,7 @@ describe("createWorkflowRuntime#createSession", () => {
input: { message: "hello" },
serializedContext: expect.objectContaining({
"eve.bundle": { source: compiledArtifactsSource },
+ "eve.stateLayout": 1,
"eve.channel": expect.objectContaining({ kind: "http", state: {} }),
"eve.otelTraceEnabled": false,
}),
diff --git a/packages/eve/src/internal/authored-module-loader.ts b/packages/eve/src/internal/authored-module-loader.ts
index 0954d8edd..58786c07b 100644
--- a/packages/eve/src/internal/authored-module-loader.ts
+++ b/packages/eve/src/internal/authored-module-loader.ts
@@ -7,7 +7,6 @@ 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";
@@ -15,7 +14,7 @@ import { createAuthoredPackageTsConfigPathsPlugin } from "#internal/authored-pac
import { createAuthoredRelativeExtensionResolverPlugin } from "#internal/authored-relative-extension-resolver.js";
import {
createExtensionScopePlugin,
- createFixedNamespaceScopePlugin,
+ createFixedMountScopePlugin,
} from "#internal/bundler/extension-scope-plugin.js";
import {
RESOLVE_EXTENSIONS,
@@ -52,25 +51,16 @@ const AUTHORED_MODULE_BUNDLE_DIRECTORY_PATH = join(
export interface AuthoredModuleLoadOptions {
readonly externalDependencies?: readonly string[];
- /**
- * When set, the module being loaded is extension-owned: its
- * `defineState`/`defineExtension` calls (and those of its same-package
- * dependencies bundled with it) are scoped to this namespace at bundle time.
- */
- readonly extensionScopeNamespace?: string;
- readonly evaluationId?: string;
- readonly mount?: {
+ readonly extension?: {
readonly mountId: string;
- readonly mountSourcePath: string;
- readonly packageName: string;
- readonly packageNamespace: string;
- readonly sourceRoot: string;
- readonly specifier: string;
- readonly programmaticImport?: {
+ /** Only filesystem mounts need a synthetic entry to bind their configuration. */
+ readonly entry?: {
+ readonly mountSourcePath: string;
+ readonly packageName: string;
+ readonly sourceRoot: string;
readonly specifier: string;
- readonly entryPath: string;
- readonly config: Record<string, unknown>;
};
+ readonly evaluationId?: string;
};
}
@@ -164,15 +154,35 @@ export async function bundleAuthoredModuleCode(
options: AuthoredModuleLoadOptions = {},
): Promise<string> {
const packageRoot = resolveAuthoredPackageRoot(modulePath);
+ const mount = options.extension?.entry;
+ const mountId = options.extension?.mountId;
return await buildAuthoredModuleBundle(modulePath, options, {
packageBoundaryPlugin: createRuntimeLoaderPackageBoundaryPlugin({
externalDependencies: normalizeExternalDependencies(options.externalDependencies),
packageRoot,
- extensionSpecifier: options.mount?.specifier,
+ extensionSpecifier: mount?.specifier,
}),
plugins: [
- ...createCompileMountPlugins(modulePath, options),
+ ...(mount === undefined
+ ? []
+ : [
+ {
+ name: "eve-compile-mount-entry",
+ resolveId(id: string) {
+ return id === "\0eve-compile-mount-entry" ? id : undefined;
+ },
+ load(id: string) {
+ if (id !== "\0eve-compile-mount-entry") return undefined;
+ const mountImport = `${mount.mountSourcePath}?eve-mount=${encodeURIComponent(mountId!)}`;
+ const contribution = `${modulePath}?eve-mount=${encodeURIComponent(mountId!)}`;
+ return `import ${JSON.stringify(mountImport)}; export * from ${JSON.stringify(contribution)}; import entry from ${JSON.stringify(contribution)}; export default entry;`;
+ },
+ },
+ ]),
createAuthoredWorkflowDirectivePlugin({ appRoot: packageRoot }),
+ ...(mount === undefined
+ ? []
+ : [createExtensionMountPlugin([{ ...mount, mountId: mountId! }])!]),
],
sourcemap: "inline",
});
@@ -284,10 +294,10 @@ export interface AuthoredModuleMapBundle {
}
export async function bundleAuthoredModuleMapForGeneration(input: {
- readonly resolveExternalPaths?: boolean;
readonly appRoot: string;
readonly manifest: CompiledAgentManifest;
readonly moduleMapPath: string;
+ readonly resolveExternalPaths?: boolean;
}): Promise<AuthoredModuleMapBundle> {
// The package root owns dependency resolution, while the selected app root
// owns authored workflow IDs and must match the workflow driver.
@@ -318,7 +328,6 @@ export async function bundleAuthoredModuleMapForGeneration(input: {
[input.manifest, ...input.manifest.subagents.map((subagent) => subagent.agent)].flatMap(
(node) =>
node.extensionMounts.map((mount) => ({
- packageNamespace: mount.packageNamespace,
mountId: mount.mountId,
sourceRoot: mount.sourceRoot,
})),
@@ -508,9 +517,7 @@ async function buildAuthoredModuleBundle(
const tsconfigPath = resolveAuthoredTsConfigPath(packageRoot);
const plugins = [
...configuration.plugins,
- options.mount !== undefined || options.extensionScopeNamespace === undefined
- ? null
- : createFixedNamespaceScopePlugin(options.extensionScopeNamespace),
+ options.extension === undefined ? null : createFixedMountScopePlugin(options.extension.mountId),
createAuthoredRelativeExtensionResolverPlugin({ extensions: RESOLVE_EXTENSIONS }),
createAuthoredAssetImportPlugin({ packageRoot }),
createAuthoredPackageTsConfigPathsPlugin({
@@ -524,7 +531,7 @@ async function buildAuthoredModuleBundle(
try {
const chunk = await buildSingleRolldownChunk(`authored module for "${modulePath}"`, {
cwd: packageRoot,
- input: options.mount === undefined ? modulePath : "\0eve-compile-mount-entry",
+ input: options.extension?.entry === undefined ? modulePath : "\0eve-compile-mount-entry",
platform: "node",
plugins,
resolve: {
@@ -606,9 +613,7 @@ async function loadBundledAuthoredModule(
.update("\0")
.update(externalDependencies.join("\0"))
.update("\0")
- .update(options.extensionScopeNamespace ?? "")
- .update("\0")
- .update(options.mount?.mountId ?? "")
+ .update(options.extension?.mountId ?? "")
.update("\0")
.update(code)
.digest("hex");
@@ -624,7 +629,7 @@ async function loadBundledAuthoredModule(
}
try {
- const instance = options.mount === undefined ? "" : (options.evaluationId ?? "");
+ const instance = options.extension?.evaluationId ?? "";
return await import(
`${createFileImportSpecifier(bundlePath)}?v=${bundleHash}&instance=${encodeURIComponent(instance)}`
);
@@ -639,7 +644,7 @@ function createInFlightModuleLoadKey(
): string {
const externalDependencies = normalizeExternalDependencies(options.externalDependencies);
- return `${modulePath}\0${externalDependencies.join("\0")}\0${options.extensionScopeNamespace ?? ""}\0${options.mount?.mountId ?? ""}\0${options.mount === undefined ? "" : (options.evaluationId ?? "")}`;
+ return `${modulePath}\0${externalDependencies.join("\0")}\0${options.extension?.mountId ?? ""}\0${options.extension?.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 9d04d456d..d58a99640 100644
--- a/packages/eve/src/internal/authored-module-map-loader.ts
+++ b/packages/eve/src/internal/authored-module-map-loader.ts
@@ -13,7 +13,7 @@ import { memoizeModuleNamespaceFactories } from "#compiler/source-graph.js";
import {
collectRuntimeModuleBindingsForManifest,
compiledModuleMapSchema,
- resolveCompiledModuleExtensionScopeNamespace,
+ resolveExtensionBindingMountId,
type CompiledModuleMap,
} from "#compiler/module-map.js";
import { loadFrameworkProgrammaticModule } from "#framework/sources/registry.js";
@@ -63,9 +63,9 @@ async function hydrateCompiledModuleMapFromManifest(
const moduleMapPath = join(runtimeAppRoot, ".eve", "compile", "authored-module-map.mjs");
const { code } = await bundleAuthoredModuleMapForGeneration({
appRoot: authoredAppRoot,
- resolveExternalPaths: true,
manifest,
moduleMapPath,
+ resolveExternalPaths: true,
});
const hash = createHash("sha256").update(code).digest("hex");
const fileName = `authored-module-map-${hash}.mjs`;
@@ -131,7 +131,10 @@ async function hydrateCompiledNodeScope(
: memoizeModuleNamespaceFactories(
await loadAuthoredModuleNamespace(resolveSourcePath(binding.backing.sourcePath), {
externalDependencies: binding.backing.externalDependencies,
- extensionScopeNamespace: resolveCompiledModuleExtensionScopeNamespace(binding),
+ extension: (() => {
+ const mountId = resolveExtensionBindingMountId(binding);
+ return mountId === undefined ? undefined : { mountId };
+ })(),
}),
);
}
diff --git a/packages/eve/src/internal/authored-package-boundary.ts b/packages/eve/src/internal/authored-package-boundary.ts
index 2335dd939..a97b1c09c 100644
--- a/packages/eve/src/internal/authored-package-boundary.ts
+++ b/packages/eve/src/internal/authored-package-boundary.ts
@@ -55,6 +55,7 @@ export function createGenerationPackageBoundaryPlugin(input: {
return undefined;
}
+ if (input.extensionSpecifiers?.has(source)) return undefined;
if (isFrameworkRuntimeImport(source, importer)) {
if (input.extensionSpecifiers?.has(source)) return undefined;
return { external: true, id: resolveFrameworkRuntimeImport(source) };
@@ -91,9 +92,9 @@ export function createGenerationPackageBoundaryPlugin(input: {
}
export function createRuntimeLoaderPackageBoundaryPlugin(input: {
- readonly extensionSpecifier?: string;
readonly externalDependencies: readonly string[];
readonly packageRoot: string;
+ readonly extensionSpecifier?: string;
}): Record<string, unknown> {
const canonicalPackageRoot = toCanonicalPath(input.packageRoot);
diff --git a/packages/eve/src/internal/bundler/compile-mount-plugin.ts b/packages/eve/src/internal/bundler/compile-mount-plugin.ts
deleted file mode 100644
index 61b4f93be..000000000
--- a/packages/eve/src/internal/bundler/compile-mount-plugin.ts
+++ /dev/null
@@ -1,37 +0,0 @@
-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-scope-plugin.integration.test.ts b/packages/eve/src/internal/bundler/extension-scope-plugin.integration.test.ts
index 68a53d575..af0d0bded 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
@@ -8,7 +8,7 @@ import { buildSingleRolldownChunk } from "#internal/bundler/nitro-rolldown.js";
import { createExtensionMountPlugin } from "#internal/bundler/extension-mount-plugin.js";
import {
createExtensionScopePlugin,
- createFixedNamespaceScopePlugin,
+ createFixedMountScopePlugin,
} from "#internal/bundler/extension-scope-plugin.js";
// Externalizes the framework barrels so the temp module bundles without eve
@@ -83,6 +83,43 @@ describe("extension-scope plugin (bundled)", () => {
};
expect(result.distinct).toBe(true);
});
+ it.each(["dual", "import-only"])(
+ "uses the ESM export for a mounted %s package",
+ async (shape) => {
+ const { sourceRoot } = scratchModule("export const value = 1;");
+ const dir = join(sourceRoot, "..");
+ const packageRoot = join(dir, "node_modules", "test-extension");
+ mkdirSync(packageRoot, { recursive: true });
+ writeFileSync(
+ join(packageRoot, "package.json"),
+ JSON.stringify({
+ name: "test-extension",
+ exports: {
+ ".":
+ shape === "dual"
+ ? { import: "./entry.mjs", require: "./entry.cjs" }
+ : { import: "./entry.mjs" },
+ },
+ }),
+ );
+ writeFileSync(join(packageRoot, "entry.mjs"), 'export const format = "esm";');
+ writeFileSync(join(packageRoot, "entry.cjs"), 'exports.format = "cjs";');
+ const entry = join(dir, "consumer.ts");
+ writeFileSync(entry, 'export { format } from "test-extension?eve-mount=extensions%2Ftest";');
+ const code = await bundle(entry, [
+ createExtensionMountPlugin([
+ {
+ mountId: "extensions/test",
+ sourceRoot: packageRoot,
+ packageName: "test-extension",
+ specifier: "test-extension",
+ },
+ ]),
+ ]);
+ expect((await import(`data:text/javascript,${encodeURIComponent(code)}`)).format).toBe("esm");
+ },
+ );
+
it("rejects an application import with two possible mount owners", async () => {
const { sourceRoot } = scratchModule("export const value = 1;");
const entry = join(sourceRoot, "..", "consumer.ts");
@@ -115,11 +152,11 @@ describe("extension-scope plugin (bundled)", () => {
it("bakes the package namespace into an extension-owned module's defineState", async () => {
const { modulePath, sourceRoot } = scratchModule(STATE_MODULE);
const code = await bundle(modulePath, [
- createExtensionScopePlugin([{ sourceRoot, packageNamespace: "acme-crm" }]),
+ createExtensionScopePlugin([{ sourceRoot, mountId: "extensions/crm" }]),
externalizeEvePlugin,
]);
- expect(code).toContain("acme-crm");
- expect(code).toContain("eve/context");
+ expect(code).toContain('defineMountedState("extensions/crm", name, initial)');
+ expect(code).toContain("eve/internal/mount-state");
});
it("leaves a module outside every extension source root unscoped", async () => {
@@ -128,12 +165,12 @@ describe("extension-scope plugin (bundled)", () => {
createExtensionScopePlugin([
{
sourceRoot: join(tmpdir(), "some-other-extension", "extension"),
- packageNamespace: "acme-crm",
+ mountId: "extensions/crm",
},
]),
externalizeEvePlugin,
]);
- expect(code).not.toContain("acme-crm");
+ expect(code).not.toContain("eve/internal/mount-state");
});
it("does not scope when there are no extensions", async () => {
@@ -143,7 +180,7 @@ describe("extension-scope plugin (bundled)", () => {
(plugin) => plugin !== null,
);
const code = await bundle(modulePath, plugins);
- expect(code).not.toContain("acme-crm");
+ expect(code).not.toContain("eve/internal/mount-state");
void sourceRoot;
});
@@ -152,9 +189,9 @@ describe("extension-scope plugin (bundled)", () => {
// filesystem matching (which is unreliable under workspace symlinks).
const { modulePath } = scratchModule(STATE_MODULE);
const code = await bundle(modulePath, [
- createFixedNamespaceScopePlugin("acme-crm"),
+ createFixedMountScopePlugin("extensions/crm"),
externalizeEvePlugin,
]);
- expect(code).toContain("acme-crm");
+ expect(code).toContain('defineMountedState("extensions/crm", name, initial)');
});
});
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 2d47bbf36..f878cd070 100644
--- a/packages/eve/src/internal/bundler/extension-scope-plugin.test.ts
+++ b/packages/eve/src/internal/bundler/extension-scope-plugin.test.ts
@@ -2,11 +2,11 @@ import { describe, expect, it } from "vitest";
import {
createExtensionScopePlugin,
- createFixedNamespaceScopePlugin,
+ createFixedMountScopePlugin,
type ExtensionScopeBundlerPlugin,
} from "#internal/bundler/extension-scope-plugin.js";
-const SCOPES = [{ sourceRoot: "/pkg/crm/extension", packageNamespace: "acme-crm" }];
+const SCOPES = [{ sourceRoot: "/pkg/crm/extension", mountId: "extensions/crm" }];
function pathPlugin(): ExtensionScopeBundlerPlugin {
const created = createExtensionScopePlugin(SCOPES);
@@ -23,7 +23,23 @@ describe("createExtensionScopePlugin (path containment)", () => {
it("redirects eve/context to a namespaced shim for extension-owned importers", () => {
const id = pathPlugin().resolveId("eve/context", "/pkg/crm/extension/tools/budget.ts");
- expect(id).toBe("\0eve-ext-scope:context:acme-crm");
+ expect(id).toBe("\0eve-ext-scope:context:extensions%2Fcrm");
+ });
+
+ it("uses the tagged mount when two instances share a source root", () => {
+ const plugin = createExtensionScopePlugin([
+ ...SCOPES,
+ { ...SCOPES[0]!, mountId: "subagents/research/extensions/crm" },
+ ])!;
+ expect(
+ plugin.resolveId(
+ "eve/context",
+ "/pkg/crm/extension/tools/budget.ts?eve-mount=subagents%2Fresearch%2Fextensions%2Fcrm",
+ ),
+ ).toBe("\0eve-ext-scope:context:subagents%2Fresearch%2Fextensions%2Fcrm");
+ expect(() => plugin.resolveId("eve/context", "/pkg/crm/extension/tools/budget.ts")).toThrow(
+ "Ambiguous extension scope",
+ );
});
it("leaves eve/extension unscoped for extension-owned importers", () => {
@@ -47,36 +63,36 @@ describe("createExtensionScopePlugin (path containment)", () => {
});
});
-describe("createFixedNamespaceScopePlugin (dev per-module)", () => {
+describe("createFixedMountScopePlugin (dev per-module)", () => {
it("scopes every non-virtual importer to the fixed namespace", () => {
- const plugin = createFixedNamespaceScopePlugin("acme-crm");
+ const plugin = createFixedMountScopePlugin("extensions/crm");
// The importer path is irrelevant in fixed mode.
expect(plugin.resolveId("eve/context", "/anywhere/on/disk/tool.ts")).toBe(
- "\0eve-ext-scope:context:acme-crm",
+ "\0eve-ext-scope:context:extensions%2Fcrm",
);
expect(plugin.resolveId("eve/extension", "/anywhere/config.ts")).toBeUndefined();
});
it("never re-enters through virtual shim importers", () => {
- const plugin = createFixedNamespaceScopePlugin("acme-crm");
- expect(plugin.resolveId("eve/context", "\0eve-ext-scope:context:acme-crm")).toBeUndefined();
+ const plugin = createFixedMountScopePlugin("extensions/crm");
+ expect(
+ plugin.resolveId("eve/context", "\0eve-ext-scope:context:extensions%2Fcrm"),
+ ).toBeUndefined();
});
it("only intercepts the scoped framework modules", () => {
- const plugin = createFixedNamespaceScopePlugin("acme-crm");
+ const plugin = createFixedMountScopePlugin("extensions/crm");
expect(plugin.resolveId("eve/tools", "/anywhere/tool.ts")).toBeUndefined();
});
});
describe("shim baking (shared)", () => {
it("bakes the namespace into the defineState shim", () => {
- const shim = createFixedNamespaceScopePlugin("acme-crm").load(
- "\0eve-ext-scope:context:acme-crm",
- );
- expect(shim?.code).toContain(
- `import { defineState as __eveScopedDefineState } from "eve/context"`,
+ const shim = createFixedMountScopePlugin("extensions/crm").load(
+ "\0eve-ext-scope:context:extensions%2Fcrm",
);
- expect(shim?.code).toContain(`__eveScopedDefineState("acme-crm" + "." + name, initial)`);
+ expect(shim?.code).toContain(`import { defineMountedState } from "eve/internal/mount-state"`);
+ expect(shim?.code).toContain(`defineMountedState("extensions/crm", name, initial)`);
});
it("passes through non-shim ids in load", () => {
diff --git a/packages/eve/src/internal/bundler/extension-scope-plugin.ts b/packages/eve/src/internal/bundler/extension-scope-plugin.ts
index a69be582f..7e840016f 100644
--- a/packages/eve/src/internal/bundler/extension-scope-plugin.ts
+++ b/packages/eve/src/internal/bundler/extension-scope-plugin.ts
@@ -2,14 +2,12 @@ import { realpathSync } from "node:fs";
import { resolve, sep } from "node:path";
/**
- * One extension's on-disk source root paired with its legacy durable state prefix.
+ * One extension's on-disk source root paired with its logical mount identity.
*/
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;
+ readonly mountId: string;
}
const VIRTUAL_PREFIX = "\0eve-ext-scope:";
@@ -39,25 +37,24 @@ function isUnder(path: string, root: string): boolean {
return path === root || path.startsWith(`${root}${sep}`);
}
-function shimSource(namespace: string): string {
- // Legacy state keys stay package-prefixed until checkpoint admission changes.
+function shimSource(mountId: string): string {
return [
- `import { defineState as __eveScopedDefineState } from "eve/context";`,
+ `import { defineMountedState } from "eve/internal/mount-state";`,
`export function defineState(name, initial) {`,
- ` return __eveScopedDefineState(${JSON.stringify(namespace)} + "." + name, initial);`,
+ ` return defineMountedState(${JSON.stringify(mountId)}, name, initial);`,
`}`,
"",
].join("\n");
}
/**
- * Builds the resolveId/load hook pair shared by both plugin modes. `namespaceFor`
- * returns the legacy state scope for an importer, or `undefined` to leave the
+ * Builds the resolveId/load hook pair shared by both plugin modes. `mountFor`
+ * returns the owning mount for an importer, or `undefined` to leave the
* import untouched.
*/
function scopeHooks(
name: string,
- namespaceFor: (importer: string) => string | undefined,
+ mountFor: (importer: string) => string | undefined,
): ExtensionScopeBundlerPlugin {
return {
name,
@@ -65,9 +62,9 @@ function scopeHooks(
if (source !== "eve/context" || importer === undefined || importer.startsWith("\0")) {
return undefined;
}
- const namespace = namespaceFor(importer);
- if (namespace === undefined) return undefined;
- return `${VIRTUAL_PREFIX}context:${namespace}`;
+ const mountId = mountFor(importer);
+ if (mountId === undefined) return undefined;
+ return `${VIRTUAL_PREFIX}context:${encodeURIComponent(mountId)}`;
},
load(id: string) {
if (!id.startsWith(VIRTUAL_PREFIX)) {
@@ -76,8 +73,8 @@ function scopeHooks(
const descriptor = id.slice(VIRTUAL_PREFIX.length);
const separatorIndex = descriptor.indexOf(":");
if (descriptor.slice(0, separatorIndex) !== "context") return undefined;
- const namespace = descriptor.slice(separatorIndex + 1);
- return { code: shimSource(namespace), moduleType: "js" as const };
+ const mountId = decodeURIComponent(descriptor.slice(separatorIndex + 1));
+ return { code: shimSource(mountId), moduleType: "js" as const };
},
};
}
@@ -85,8 +82,7 @@ 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` imports redirected to a generated shim that preserves the
- * legacy package prefix for `defineState`.
+ * `eve/context` imports redirected to a mount-owned state shim.
*
* 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.
@@ -99,7 +95,6 @@ export function createExtensionScopePlugin(
}
const canonicalScopes = scopes.map((scope) => ({
root: canonicalize(scope.sourceRoot),
- packageNamespace: scope.packageNamespace,
mountId: scope.mountId,
}));
return scopeHooks("eve-extension-scope", (importer) => {
@@ -108,25 +103,25 @@ export function createExtensionScopePlugin(
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;
+ return isUnder(importerPath(importer), owned.root) ? owned.mountId : undefined;
}
const path = importerPath(importer);
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) {
+ if (matches.length > 1) {
throw new Error(`Ambiguous extension scope for "${path}".`);
}
- return matches[0]!.packageNamespace;
+ return matches[0]!.mountId;
});
}
/**
- * Fixed-namespace scope plugin for a single extension-owned module bundle (the
- * dev/eval per-module loader). The compiler already knows the loaded module is
- * extension-owned and under which namespace, so every module in the bundle —
- * the entry plus its same-package dependencies — is scoped, with no reliance on
+ * Fixed-mount scope plugin for a single extension-owned module bundle (the
+ * dev/eval per-module loader). The compiler already knows the owning mount,
+ * so every module in the bundle — the entry plus its same-package dependencies —
+ * is scoped, with no reliance on
* filesystem path matching (which is unreliable under workspace symlinks).
*/
-export function createFixedNamespaceScopePlugin(namespace: string): ExtensionScopeBundlerPlugin {
- return scopeHooks("eve-extension-scope-fixed", () => namespace);
+export function createFixedMountScopePlugin(mountId: string): ExtensionScopeBundlerPlugin {
+ return scopeHooks("eve-extension-scope-fixed", () => mountId);
}
diff --git a/packages/eve/src/internal/mount-state.ts b/packages/eve/src/internal/mount-state.ts
new file mode 100644
index 000000000..5e08990d5
--- /dev/null
+++ b/packages/eve/src/internal/mount-state.ts
@@ -0,0 +1 @@
+export { defineMountedState } from "#public/definitions/state.js";
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 51fa8156a..62f513869 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
@@ -661,7 +661,6 @@ describe("application Nitro creation", () => {
packageName: "layout-extension",
specifier: "layout-extension",
mountId: "extensions/layout",
- packageNamespace: "layout-extension",
sourceRoot,
},
];
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 54de25a9b..8b280c1cd 100644
--- a/packages/eve/src/internal/nitro/host/create-application-nitro.ts
+++ b/packages/eve/src/internal/nitro/host/create-application-nitro.ts
@@ -587,7 +587,6 @@ function createApplicationNitroBundlerConfiguration(
].flatMap((node) =>
node.extensionMounts.map((mount) => ({
sourceRoot: mount.sourceRoot,
- packageNamespace: mount.packageNamespace,
mountId: mount.mountId,
})),
),
diff --git a/packages/eve/src/internal/nitro/host/dev-host-fingerprint.ts b/packages/eve/src/internal/nitro/host/dev-host-fingerprint.ts
index 503c9e3aa..1b5243124 100644
--- a/packages/eve/src/internal/nitro/host/dev-host-fingerprint.ts
+++ b/packages/eve/src/internal/nitro/host/dev-host-fingerprint.ts
@@ -26,10 +26,10 @@ export async function computeDevelopmentHostFingerprint(
extensionScopes: agentNodes
.flatMap((node) => node.extensionMounts)
.map((mount) => ({
- packageNamespace: mount.packageNamespace,
+ mountId: mount.mountId,
sourceRoot: mount.sourceRoot,
}))
- .sort((left, right) => left.sourceRoot.localeCompare(right.sourceRoot)),
+ .sort((left, right) => left.mountId.localeCompare(right.mountId)),
sandboxProviders: [
...new Set(
agentNodes
diff --git a/packages/eve/src/internal/testing/app-harness.integration.test.ts b/packages/eve/src/internal/testing/app-harness.integration.test.ts
index 979ab66ad..07c418541 100644
--- a/packages/eve/src/internal/testing/app-harness.integration.test.ts
+++ b/packages/eve/src/internal/testing/app-harness.integration.test.ts
@@ -14,6 +14,7 @@ function buildSerializedContext(overrides: {
return {
"eve.auth": null,
"eve.bundle": { source: createBundledRuntimeCompiledArtifactsSource() },
+ "eve.stateLayout": 1,
"eve.channel": { kind: overrides.channelKind, state: {} },
"eve.continuationToken": overrides.continuationToken,
};
diff --git a/packages/eve/src/internal/testing/entry-test-helpers.ts b/packages/eve/src/internal/testing/entry-test-helpers.ts
index 4659ce5a2..7683ac1f9 100644
--- a/packages/eve/src/internal/testing/entry-test-helpers.ts
+++ b/packages/eve/src/internal/testing/entry-test-helpers.ts
@@ -30,6 +30,7 @@ export function buildSerializedContext(overrides: {
const context: Record<string, unknown> = {
"eve.auth": overrides.auth ?? null,
"eve.bundle": { source: createBundledRuntimeCompiledArtifactsSource() },
+ "eve.stateLayout": 1,
"eve.channel": channel,
};
if (overrides.audience !== undefined) {
diff --git a/packages/eve/src/internal/testing/workflow-tool-run-harness.ts b/packages/eve/src/internal/testing/workflow-tool-run-harness.ts
index c9b31fd42..f96fd9bd1 100644
--- a/packages/eve/src/internal/testing/workflow-tool-run-harness.ts
+++ b/packages/eve/src/internal/testing/workflow-tool-run-harness.ts
@@ -23,6 +23,7 @@ export function buildWorkflowToolSerializedContext(input: {
return {
"eve.auth": null,
"eve.bundle": { source: createBundledRuntimeCompiledArtifactsSource() },
+ "eve.stateLayout": 1,
"eve.capabilities": { requestInput: input.requestInput ?? false },
"eve.channel": { kind: "http", state: {} },
...(input.acceptedDeploymentId === undefined
diff --git a/packages/eve/src/public/definitions/state.test.ts b/packages/eve/src/public/definitions/state.test.ts
index 3ee39aa4e..c79dc2ed3 100644
--- a/packages/eve/src/public/definitions/state.test.ts
+++ b/packages/eve/src/public/definitions/state.test.ts
@@ -20,6 +20,9 @@ describe("defineState", () => {
// silently corrupt context serialization.
expect(() => defineState("eve.channel", () => null)).toThrow(/reserved/);
expect(() => defineState("eve.budget", () => ({ count: 0 }))).toThrow(/reserved/);
+ expect(() => defineState("eve:mount.v1:extensions%2Fcrm:requests", () => 0)).toThrow(
+ /reserved/,
+ );
});
it("get() returns initial() on first read inside ALS", () => {
diff --git a/packages/eve/src/public/definitions/state.ts b/packages/eve/src/public/definitions/state.ts
index a0a5db9d7..dbf6c7355 100644
--- a/packages/eve/src/public/definitions/state.ts
+++ b/packages/eve/src/public/definitions/state.ts
@@ -15,14 +15,14 @@ export interface StateHandle<T> {
update(fn: (current: T) => T): void;
}
-const RESERVED_STATE_NAME_PREFIX = "eve.";
+const RESERVED_STATE_NAME_PREFIXES = ["eve.", "eve:mount."] as const;
/**
* Creates a typed, named state slot backed by a durable `ContextKey`.
* `initial()` produces the value on first access within a context.
*
- * The name must not start with the reserved `"eve."` prefix (reserved
- * for framework context keys); doing so throws.
+ * Names starting with `"eve."` or `"eve:mount."` are reserved for framework
+ * context keys; using either prefix throws.
*
* All operations require an active eve context. Calling `get()` or
* `update()` outside of tools, hooks, or other framework-managed code
@@ -41,12 +41,28 @@ const RESERVED_STATE_NAME_PREFIX = "eve.";
* ```
*/
export function defineState<T>(name: string, initial: () => T): StateHandle<T> {
- if (name.startsWith(RESERVED_STATE_NAME_PREFIX)) {
+ const reserved = RESERVED_STATE_NAME_PREFIXES.find((prefix) => name.startsWith(prefix));
+ if (reserved !== undefined) {
throw new Error(
- `defineState() name "${name}" uses the reserved "${RESERVED_STATE_NAME_PREFIX}" prefix, which eve reserves for its own framework context keys (e.g. "eve.channel", "eve.bundle"). Colliding with one silently corrupts context serialization. Use your own namespace, e.g. "my-agent.${name.slice(RESERVED_STATE_NAME_PREFIX.length)}".`,
+ `defineState() name "${name}" uses the reserved "${reserved}" prefix. Use an application-owned namespace instead.`,
);
}
+ return createStateHandle(name, initial);
+}
+
+/** Internal registration of generated, mount-owned keys. */
+export function defineMountedState<T>(
+ mountId: string,
+ name: string,
+ initial: () => T,
+): StateHandle<T> {
+ return createStateHandle(
+ `eve:mount.v1:${encodeURIComponent(mountId)}:${encodeURIComponent(name)}`,
+ initial,
+ );
+}
+function createStateHandle<T>(name: string, initial: () => T): StateHandle<T> {
const key = new ContextKey<T>(name);
return {