Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

fix(eve): keep each agent's config when one extension is mounted in several agents (#3780)

roboeve[bot]0ea9308ba594
diff --git a/.changeset/per-agent-extension-config.md b/.changeset/per-agent-extension-config.md
new file mode 100644
index 000000000..aef859972
--- /dev/null
+++ b/.changeset/per-agent-extension-config.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Fix an extension mounted in several agents with different configs, for example at the root and inside a declared subagent, giving every agent the config of whichever mount loaded last. `extension.config` now returns the config of the mount serving the current session's agent, or the root agent's mount in channel requests and schedule runs. Subagents an extension ships inherit the config of the agent that mounts it.
diff --git a/docs/extensions.md b/docs/extensions.md
index fb5dab4a5..f2afdd738 100644
--- a/docs/extensions.md
+++ b/docs/extensions.md
@@ -83,6 +83,8 @@ export default defineTool({
});
```
+Read `extension.config` inside handlers such as `execute`, not at module top level. When the same extension is mounted in several agents with different configs, each session reads the config of its own agent's mount, and a top-level read cannot tell which agent is asking.
+
If no configuration is needed, export `defineExtension()` and let consumers re-export it directly. Config schemas must validate synchronously.
`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.
diff --git a/packages/eve/src/channel/schedule.test.ts b/packages/eve/src/channel/schedule.test.ts
index 596498f43..d0e42ce53 100644
--- a/packages/eve/src/channel/schedule.test.ts
+++ b/packages/eve/src/channel/schedule.test.ts
@@ -12,7 +12,7 @@ import {
ScheduleDispatcher,
} from "#channel/schedule.js";
import { contextStorage } from "#context/container.js";
-import { ScheduleIdKey } from "#context/keys.js";
+import { ExtensionConfigsKey, ScheduleIdKey } from "#context/keys.js";
import type { RunHandle, Runtime, SessionAuthContext } from "#channel/types.js";
import { slackChannel } from "#public/channels/slack/slackChannel.js";
import { isScheduleAuth } from "#public/schedules/index.js";
@@ -20,8 +20,10 @@ import type { ResolvedChannelDefinition } from "#runtime/types.js";
import { defineDynamicSchedules } from "#public/schedules/subscription.js";
import { inMemoryScheduleProvider } from "#public/schedules/providers/in-memory.js";
import { createScheduleCollectionPayload } from "#runtime/schedules/payload.js";
+import "#runtime/extension-mount-configs.js";
import { z } from "#compiled/zod/index.js";
import { defineChannel } from "#public/definitions/channel.js";
+import { defineExtension } from "#public/definitions/extension.js";
function createMockRunHandle(): RunHandle {
return { events: new ReadableStream<MessageStreamEvent>(), sessionId: "mock-session-id" };
@@ -81,6 +83,9 @@ describe("ScheduleDispatcher", () => {
function setup(auth: typeof creator | null = creator) {
const runtime = createMockRuntime();
const targets: string[] = [];
+ const extensionConfigs = new Map([["@acme/crm", { apiKey: "sk-root" }]]);
+ const crm = defineExtension({ config: z.object({ apiKey: z.string() }) }, "@acme/crm");
+ const observedExtensionConfigs: Array<unknown> = [];
const channel = defineChannel<undefined, void, { channelId: string }>({
routes: [],
async receive(input, context) {
@@ -97,6 +102,8 @@ describe("ScheduleDispatcher", () => {
auth: SessionAuthContext;
waitUntil: (task: Promise<unknown>) => void;
}) => {
+ observedExtensionConfigs.push(contextStorage.getStore()?.get(ExtensionConfigsKey));
+ observedExtensionConfigs.push(crm.config);
const channelId =
args.payload.destination === "my-dm" ? `dm-${args.auth.principalId}` : "team-channel";
args.waitUntil(args.to(channel, { channelId }).send(args.payload.task));
@@ -134,6 +141,7 @@ describe("ScheduleDispatcher", () => {
fetch: async () => new Response(),
},
],
+ extensionConfigs,
});
const input = {
collectionId: "requests",
@@ -141,7 +149,15 @@ describe("ScheduleDispatcher", () => {
occurrence,
payload,
};
- return { dispatcher, input, runtime, run, targets };
+ return {
+ dispatcher,
+ input,
+ extensionConfigs,
+ observedExtensionConfigs,
+ runtime,
+ run,
+ targets,
+ };
}
it("derives a destination from payload intent and starts fresh unattended work as the creator", async () => {
@@ -163,6 +179,12 @@ describe("ScheduleDispatcher", () => {
expect(runtime.dispatchContinuation).not.toHaveBeenCalled();
});
+ it("runs occurrence handlers with the root extension configs", async () => {
+ const { dispatcher, input, extensionConfigs, observedExtensionConfigs } = setup();
+ await dispatcher.triggerCollection(input);
+ expect(observedExtensionConfigs).toEqual([extensionConfigs, { apiKey: "sk-root" }]);
+ });
+
it.each([null, { ...creator, principalId: "bob" }])(
"does not invoke authored code when creator resolution fails (%j)",
async (auth) => {
@@ -200,7 +222,11 @@ describe("ScheduleDispatcher", () => {
describe("markdown form", () => {
it("starts a Session via runtime.createSession with the SCHEDULE_ADAPTER", async () => {
const runtime = createMockRuntime();
- const dispatcher = new ScheduleDispatcher({ runtime, channels: [] });
+ const dispatcher = new ScheduleDispatcher({
+ runtime,
+ channels: [],
+ extensionConfigs: new Map(),
+ });
const result = await dispatcher.trigger({
scheduleId: "heartbeat",
markdown: "Run heartbeat task.",
@@ -221,7 +247,7 @@ describe("ScheduleDispatcher", () => {
const runtime = createMockRuntime();
runtime.createSession = vi.fn().mockRejectedValue(new Error("boom"));
await expect(
- new ScheduleDispatcher({ runtime, channels: [] }).trigger({
+ new ScheduleDispatcher({ runtime, channels: [], extensionConfigs: new Map() }).trigger({
scheduleId: "heartbeat",
markdown: "x",
}),
@@ -236,7 +262,11 @@ describe("ScheduleDispatcher", () => {
vi.stubEnv("SLACK_SIGNING_SECRET", "test-secret");
try {
const { definition, resolved } = makeSlackChannelEntry();
- const dispatcher = new ScheduleDispatcher({ runtime, channels: [resolved] });
+ const dispatcher = new ScheduleDispatcher({
+ runtime,
+ channels: [resolved],
+ extensionConfigs: new Map(),
+ });
let observed = false;
const result = await dispatcher.trigger({
scheduleId: "daily-digest",
@@ -262,7 +292,11 @@ describe("ScheduleDispatcher", () => {
});
it("collects waitUntil promises", async () => {
const runtime = createMockRuntime();
- const result = await new ScheduleDispatcher({ runtime, channels: [] }).trigger({
+ const result = await new ScheduleDispatcher({
+ runtime,
+ channels: [],
+ extensionConfigs: new Map(),
+ }).trigger({
scheduleId: "background-job",
async run({ waitUntil }) {
waitUntil(Promise.resolve("done"));
@@ -284,7 +318,11 @@ describe("ScheduleDispatcher", () => {
vi.stubEnv("SLACK_SIGNING_SECRET", "test-secret");
try {
const { definition, resolved } = makeSlackChannelEntry();
- const result = await new ScheduleDispatcher({ runtime, channels: [resolved] }).trigger({
+ const result = await new ScheduleDispatcher({
+ runtime,
+ channels: [resolved],
+ extensionConfigs: new Map(),
+ }).trigger({
scheduleId: "dynamic-tasks",
run({ to, waitUntil }) {
waitUntil(
@@ -315,7 +353,11 @@ describe("ScheduleDispatcher", () => {
adapter: { kind: "x" },
} satisfies CompiledChannel;
await expect(
- new ScheduleDispatcher({ runtime: createMockRuntime(), channels: [] }).trigger({
+ new ScheduleDispatcher({
+ runtime: createMockRuntime(),
+ channels: [],
+ extensionConfigs: new Map(),
+ }).trigger({
scheduleId: "stranger",
async run({ to }) {
await to(stranger, {}).send("x", { auth: null });
@@ -327,7 +369,11 @@ describe("ScheduleDispatcher", () => {
it("isScheduleAuth recognizes the app principal schedules dispatch with, and only it", async () => {
const runtime = createMockRuntime();
- const dispatcher = new ScheduleDispatcher({ runtime, channels: [] });
+ const dispatcher = new ScheduleDispatcher({
+ runtime,
+ channels: [],
+ extensionConfigs: new Map(),
+ });
let appAuth: SessionAuthContext | undefined;
await dispatcher.trigger({ scheduleId: "heartbeat", markdown: "Run heartbeat task." });
@@ -351,9 +397,32 @@ describe("ScheduleDispatcher", () => {
expect(isScheduleAuth(null)).toBe(false);
});
+ it("runs the handler with the root extension configs in scope", async () => {
+ const extensionConfigs = new Map([["@acme/crm", { apiKey: "sk-root" }]]);
+ const dispatcher = new ScheduleDispatcher({
+ runtime: createMockRuntime(),
+ channels: [],
+ extensionConfigs,
+ });
+ let seen: unknown;
+
+ await dispatcher.trigger({
+ scheduleId: "sync",
+ async run() {
+ seen = contextStorage.getStore()?.get(ExtensionConfigsKey);
+ },
+ });
+
+ expect(seen).toBe(extensionConfigs);
+ });
+
it("throws when neither run nor markdown is provided", async () => {
await expect(
- new ScheduleDispatcher({ runtime: createMockRuntime(), channels: [] }).trigger({
+ new ScheduleDispatcher({
+ runtime: createMockRuntime(),
+ channels: [],
+ extensionConfigs: new Map(),
+ }).trigger({
scheduleId: "empty",
}),
).rejects.toThrow(/has neither "run" nor "markdown"/);
diff --git a/packages/eve/src/channel/schedule.ts b/packages/eve/src/channel/schedule.ts
index 9875aa0ad..d84f2f09c 100644
--- a/packages/eve/src/channel/schedule.ts
+++ b/packages/eve/src/channel/schedule.ts
@@ -6,7 +6,13 @@ import { createCrossChannelToFn, toCrossChannelTargets } from "#channel/cross-ch
import { createSession, type Session } from "#channel/session.js";
import type { Runtime } from "#channel/types.js";
import { ContextContainer, contextStorage } from "#context/container.js";
-import { AuthKey, OccurrenceIdKey, ScheduleIdKey, ScheduleInstanceKey } from "#context/keys.js";
+import {
+ AuthKey,
+ ExtensionConfigsKey,
+ OccurrenceIdKey,
+ ScheduleIdKey,
+ ScheduleInstanceKey,
+} from "#context/keys.js";
import { expectFunction } from "#internal/authored-module.js";
import type {
ScheduleDefinition,
@@ -83,17 +89,22 @@ export interface ScheduleCollectionDispatchInput {
export class ScheduleDispatcher {
private readonly runtime: Runtime;
private readonly channels: readonly ResolvedChannelDefinition[];
+ private readonly extensionConfigs: ReadonlyMap<string, Record<string, unknown>>;
constructor(config: {
readonly runtime: Runtime;
readonly channels: readonly ResolvedChannelDefinition[];
+ /** Root extension configs the schedule's `run` reads through `extension.config`. */
+ readonly extensionConfigs: ReadonlyMap<string, Record<string, unknown>>;
}) {
this.runtime = config.runtime;
this.channels = config.channels;
+ this.extensionConfigs = config.extensionConfigs;
}
async trigger(input: ScheduleDispatchInput): Promise<ScheduleDispatchResult> {
const scope = new ContextContainer();
scope.set(ScheduleIdKey, input.scheduleId);
+ scope.setVirtualContext(ExtensionConfigsKey, this.extensionConfigs);
return await contextStorage.run(scope, () => this.triggerInScope(input));
}
@@ -131,6 +142,7 @@ export class ScheduleDispatcher {
const scope = new ContextContainer();
scope.set(ScheduleIdKey, input.collectionId);
scope.set(AuthKey, auth);
+ scope.setVirtualContext(ExtensionConfigsKey, this.extensionConfigs);
scope.set(OccurrenceIdKey, occurrence.executionId);
scope.set(ScheduleInstanceKey, occurrence.name);
return await contextStorage.run(scope, async () => {
diff --git a/packages/eve/src/compiler/mounted-extension.integration.test.ts b/packages/eve/src/compiler/mounted-extension.integration.test.ts
index c049b126d..6f8cac7e6 100644
--- a/packages/eve/src/compiler/mounted-extension.integration.test.ts
+++ b/packages/eve/src/compiler/mounted-extension.integration.test.ts
@@ -5,6 +5,7 @@ import { describe, expect, it } from "vitest";
import { compileAgent } from "#compiler/compile-agent.js";
import { ContextContainer, contextStorage } from "#context/container.js";
+import { ExtensionConfigsKey } from "#context/keys.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";
@@ -13,6 +14,7 @@ import { useTemporaryAppRoots } from "#internal/testing/use-temporary-app-roots.
import { createDiskRuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";
import { loadCompiledManifest } from "#runtime/loaders/manifest.js";
import { resolveRuntimeAgentGraph } from "#runtime/resolve-agent-graph.js";
+import { withExtensionConfigs } from "#runtime/extension-mount-configs.js";
const createAppRoot = useTemporaryAppRoots();
@@ -92,7 +94,7 @@ describe("mounted extension via authored-source loader", () => {
'import ext from "@acme/crm";',
'import prompt from "./prompt.md?raw";',
'import asset from "./badge.svg";',
- "const account = ext.config.account; export default { description: account, inputSchema: {}, execute: () => ({ account, prompt, asset }) };",
+ 'export default { description: "Read account", inputSchema: {}, execute: () => ({ account: ext.config.account, prompt, asset }) };',
].join("\n"),
"node_modules/@acme/crm/extension/tools/prompt.md": "Account prompt",
"node_modules/@acme/crm/extension/tools/badge.svg": "<svg/>",
@@ -104,43 +106,40 @@ describe("mounted extension via authored-source loader", () => {
expect(first.manifest.tools.map((tool) => [tool.name, tool.description])).toEqual(
expect.arrayContaining([
["one__account", "Read overridden account"],
- ["two__account", "two"],
+ ["two__account", "Read account"],
]),
);
- 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),
- });
- const read = (map: typeof first.moduleMap, name: string) => {
- const tool = first.manifest.tools.find((entry) => entry.name === `${name}__account`)!;
- return (
- map.nodes[ROOT_COMPILED_AGENT_NODE_ID]!.modules[tool.sourceId]!.default as {
- execute: () => unknown;
- }
- ).execute();
+ const second = await compileRuntimeGraph(app.appRoot);
+ const read = (
+ compiled: typeof first,
+ name: string,
+ moduleMap: typeof first.moduleMap = compiled.moduleMap,
+ ) => {
+ const tool = compiled.manifest.tools.find((entry) => entry.name === `${name}__account`)!;
+ const execute = () =>
+ (
+ moduleMap.nodes[ROOT_COMPILED_AGENT_NODE_ID]!.modules[tool.sourceId]!.default as {
+ execute: () => unknown;
+ }
+ ).execute();
+ const context = contextStorage.getStore();
+ if (context !== undefined) {
+ context.setVirtualContext(ExtensionConfigsKey, compiled.graph.root.extensionConfigs);
+ return execute();
+ }
+ return withExtensionConfigs(compiled.graph.root.extensionConfigs, execute);
};
const accountResult = {
account: "two",
prompt: "Account prompt",
asset: "data:image/svg+xml;base64,PHN2Zy8+",
};
- expect(read(first.moduleMap, "two")).toEqual(accountResult);
- expect(read(second, "two")).toEqual(accountResult);
+ expect(read(first, "two")).toEqual(accountResult);
+ expect(read(second, "two")).toEqual({ ...accountResult, account: "updated" });
const helper = first.manifest.subagents.find((node) => node.name === "one__helper")!;
const peek = helper.agent.tools.find((tool) => tool.name === "peek")!;
expect(
@@ -152,7 +151,7 @@ describe("mounted extension via authored-source loader", () => {
).toBe("one");
const context = new ContextContainer();
contextStorage.run(context, () => {
- expect(read(first.moduleMap, "one")).toEqual({ account: "one", count: 1 });
+ expect(read(first, "one")).toEqual({ account: "one", count: 1 });
expect(read(second, "one")).toEqual({ account: "one", count: 2 });
});
expect(Object.keys(serializeContext(context))).toContain("override-count");
@@ -170,16 +169,20 @@ describe("mounted extension via authored-source loader", () => {
const generated = (await import(`${moduleMapPath}?test=independent-config`)) as {
default: typeof first.moduleMap;
};
- expect(read(generated.default, "two")).toEqual(accountResult);
+ expect(read(first, "two", generated.default)).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]) {
+ expect(tool.description).toBe("Read account");
+ for (const map of [first.moduleMap, second.moduleMap, 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 });
+ const node = first.graph.nodesByNodeId.get(subagent.nodeId)!;
+ expect(withExtensionConfigs(node.extensionConfigs, () => definition.execute())).toEqual({
+ ...accountResult,
+ account: name,
+ });
}
}
});
@@ -245,7 +248,7 @@ describe("mounted extension via authored-source loader", () => {
'import code from "eve/extensions/code"; export default code({ worker: { model: "openai/gpt-5.4", reasoning: "low" } });',
},
});
- const { manifest, moduleMap } = await compileRuntimeGraph(app.appRoot);
+ const { graph, manifest, moduleMap } = await compileRuntimeGraph(app.appRoot);
const workers = ["one", "two"].map((name) =>
manifest.subagents.find((subagent) => subagent.name === `${name}__worker`)!,
);
@@ -256,7 +259,10 @@ describe("mounted extension via authored-source loader", () => {
const definition = moduleMap.nodes[worker.nodeId]!.modules[configSourceId]!.default as {
model: { events: { "session.started": () => { reasoning: string } } };
};
- return definition.model.events["session.started"]().reasoning;
+ return withExtensionConfigs(
+ graph.nodesByNodeId.get(worker.nodeId)!.extensionConfigs,
+ () => definition.model.events["session.started"]().reasoning,
+ );
});
expect(reasoning).toEqual(["high", "low"]);
const second = await loadCompiledModuleMapFromAuthoredSource({
@@ -268,7 +274,10 @@ describe("mounted extension via authored-source loader", () => {
.default as {
model: { events: { "session.started": () => { reasoning: string } } };
};
- return definition.model.events["session.started"]().reasoning;
+ return withExtensionConfigs(
+ graph.nodesByNodeId.get(worker.nodeId)!.extensionConfigs,
+ () => definition.model.events["session.started"]().reasoning,
+ );
});
expect(secondReasoning).toEqual(["high", "low"]);
});
@@ -495,9 +504,11 @@ describe("mounted extension via authored-source loader", () => {
const tool = graph.root.agent.tools.find((entry) => entry.name === "crm__crm_echo");
expect(tool).toBeDefined();
- await expect(tool?.execute?.({}, { messages: [], toolCallId: "call_1" })).resolves.toEqual({
- apiKey: "sk-authored",
- });
+ await expect(
+ withExtensionConfigs(graph.root.extensionConfigs, () =>
+ tool?.execute?.({}, { messages: [], toolCallId: "call_1" }),
+ ),
+ ).resolves.toEqual({ apiKey: "sk-authored" });
});
});
@@ -668,9 +679,11 @@ describe("mounted extension via directory form with override", () => {
const echo = graph.root.agent.tools.find((entry) => entry.name === "crm__crm_echo");
expect(echo).toBeDefined();
- await expect(echo?.execute?.({}, { messages: [], toolCallId: "call_1" })).resolves.toEqual({
- apiKey: "sk-dir",
- });
+ await expect(
+ withExtensionConfigs(graph.root.extensionConfigs, () =>
+ echo?.execute?.({}, { messages: [], toolCallId: "call_1" }),
+ ),
+ ).resolves.toEqual({ apiKey: "sk-dir" });
const status = graph.root.agent.tools.find((entry) => entry.name === "crm__crm_status");
expect(status).toBeDefined();
diff --git a/packages/eve/src/context/keys.ts b/packages/eve/src/context/keys.ts
index c2101807c..d62dab3ff 100644
--- a/packages/eve/src/context/keys.ts
+++ b/packages/eve/src/context/keys.ts
@@ -105,6 +105,14 @@ export const OccurrenceIdKey = new ContextKey<string>("eve.scheduleOccurrenceId"
/** Authored schedule whose dispatch created this session. */
export const ScheduleIdKey = new ContextKey<string>("eve.scheduleId");
export const ScheduleInstanceKey = new ContextKey<string>("eve.scheduleInstance");
+/**
+ * Extension configs for runtime scopes without a session bundle, such as a
+ * channel request or schedule run. Set as a virtual value, never serialized.
+ */
+export const ExtensionConfigsKey = new ContextKey<ReadonlyMap<string, Record<string, unknown>>>(
+ "eve.extensionConfigs",
+);
+
/** Display title derived from the session's initial input. */
export const SessionTitleKey = new ContextKey<string>("eve.sessionTitle");
export const ChannelDeliveryKey = new ContextKey<ChannelDeliveryMetadata>("eve.channelDelivery");
diff --git a/packages/eve/src/execution/node-step.test.ts b/packages/eve/src/execution/node-step.test.ts
index 295ef9795..a5417dc82 100644
--- a/packages/eve/src/execution/node-step.test.ts
+++ b/packages/eve/src/execution/node-step.test.ts
@@ -160,6 +160,7 @@ function createTestNode(
return {
agent,
channels: [],
+ extensionConfigs: new Map(),
hookRegistry: createRuntimeHookRegistry([]),
nodeId: ROOT_RUNTIME_AGENT_NODE_ID,
sandboxRegistry: createStubSandboxRegistry(),
diff --git a/packages/eve/src/execution/session/turn-connection-approval.integration.test.ts b/packages/eve/src/execution/session/turn-connection-approval.integration.test.ts
index f79246a70..2388295be 100644
--- a/packages/eve/src/execution/session/turn-connection-approval.integration.test.ts
+++ b/packages/eve/src/execution/session/turn-connection-approval.integration.test.ts
@@ -216,6 +216,7 @@ function setup(
sandboxRegistry: sandboxRegistry as CompiledBundle["graph"]["root"]["sandboxRegistry"],
turnAgent,
channels: [],
+ extensionConfigs: new Map(),
hookRegistry: createRuntimeHookRegistry([]),
nodeId: "__root__",
subagentRegistry: {
diff --git a/packages/eve/src/internal/bundler/extension-mount-plugin.ts b/packages/eve/src/internal/bundler/extension-mount-plugin.ts
index 0e8e62c31..db8faa795 100644
--- a/packages/eve/src/internal/bundler/extension-mount-plugin.ts
+++ b/packages/eve/src/internal/bundler/extension-mount-plugin.ts
@@ -2,6 +2,7 @@ import { readFileSync, realpathSync } from "node:fs";
import { dirname, join, resolve, sep } from "node:path";
const MOUNT_QUERY = "?eve-mount=";
+const EXTENSION_HANDLE_PREFIX = "\0eve-extension-handle:";
/** Directory beside an extension distribution's source root that holds its shared chunks. */
export const EXTENSION_CHUNK_DIRECTORY = "_chunks";
@@ -117,6 +118,26 @@ export function createExtensionMountPlugin(
if (mountId !== undefined && mount === undefined)
throw new Error(`Unknown extension mount "${mountId}".`);
+ if (cleanSource === "eve/extension" && importerPath !== undefined) {
+ const owners = roots.filter((root) => isExtensionModule(importerPath, root.root));
+ const owner =
+ mountId === undefined
+ ? owners.length === 1
+ ? owners[0]
+ : undefined
+ : (owners
+ .filter(
+ (candidate) =>
+ mountId === candidate.mountId || mountId.startsWith(`${candidate.mountId}/`),
+ )
+ .sort((left, right) => right.mountId.length - left.mountId.length)[0] ??
+ (owners.length === 1 ? owners[0] : undefined));
+ const mountIdentity = owner?.mountId;
+ if (mountIdentity !== undefined) {
+ return `${EXTENSION_HANDLE_PREFIX}${encodeURIComponent(mountIdentity)}`;
+ }
+ }
+
// An override has mount context for its imports, but remains application-owned:
// its own state and all of its other dependencies keep their ordinary identity.
const override =
@@ -182,6 +203,17 @@ export function createExtensionMountPlugin(
: undefined;
},
load(id: string) {
+ if (id.startsWith(EXTENSION_HANDLE_PREFIX)) {
+ const mountId = decodeURIComponent(id.slice(EXTENSION_HANDLE_PREFIX.length));
+ return {
+ code: [
+ `import { defineExtension as define } from "eve/extension";`,
+ `export const defineExtension = (options) => define(options, ${JSON.stringify(mountId)});`,
+ "",
+ ].join("\n"),
+ moduleType: "js" as const,
+ };
+ }
const query = id.indexOf(MOUNT_QUERY);
if (query < 0) return undefined;
const path = id.slice(0, query);
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 af0d0bded..510666917 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
@@ -83,6 +83,28 @@ describe("extension-scope plugin (bundled)", () => {
};
expect(result.distinct).toBe(true);
});
+
+ it("binds defineExtension to the owning package in a mounted entry", async () => {
+ const { modulePath, sourceRoot } = scratchModule(
+ [
+ 'import { defineExtension } from "eve/extension";',
+ "export default defineExtension();",
+ ].join("\n"),
+ );
+ const code = await bundle(`${modulePath}?eve-mount=extensions%2Fcrm`, [
+ createExtensionMountPlugin([
+ {
+ mountId: "extensions/crm",
+ packageName: "@acme/crm",
+ sourceRoot,
+ specifier: "@acme/crm",
+ },
+ ]),
+ externalizeEvePlugin,
+ ]);
+ expect(code).toContain('defineExtension(options, "extensions/crm")');
+ });
+
it.each(["dual", "import-only"])(
"uses the ESM export for a mounted %s package",
async (shape) => {
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 b038039da..1e5d27e2b 100644
--- a/packages/eve/src/internal/bundler/extension-scope-plugin.test.ts
+++ b/packages/eve/src/internal/bundler/extension-scope-plugin.test.ts
@@ -6,7 +6,12 @@ import {
type ExtensionScopeBundlerPlugin,
} from "#internal/bundler/extension-scope-plugin.js";
-const SCOPES = [{ sourceRoot: "/pkg/crm/extension", mountId: "extensions/crm" }];
+const SCOPES = [
+ {
+ sourceRoot: "/pkg/crm/extension",
+ mountId: "extensions/crm",
+ },
+];
function pathPlugin(): ExtensionScopeBundlerPlugin {
const created = createExtensionScopePlugin(SCOPES);
@@ -55,9 +60,11 @@ describe("createExtensionScopePlugin (path containment)", () => {
).toBe("\0eve-ext-scope:context:subagents%2Fresearch%2Fextensions%2Fcrm");
});
- it("leaves eve/extension unscoped for extension-owned importers", () => {
- const id = pathPlugin().resolveId("eve/extension", "/pkg/crm/extension/config.ts");
- expect(id).toBeUndefined();
+ it("binds eve/extension handles to the mounted identity", () => {
+ const plugin = pathPlugin();
+ const id = plugin.resolveId("eve/extension", "/pkg/crm/extension/config.ts");
+ expect(id).toBe("\0eve-ext-scope:extension:extensions%2Fcrm");
+ expect(plugin.load(id!)?.code).toContain('define(options, "extensions/crm")');
});
it("ignores importers outside every extension source root", () => {
@@ -83,7 +90,9 @@ describe("createFixedMountScopePlugin (dev per-module)", () => {
expect(plugin.resolveId("eve/context", "/anywhere/on/disk/tool.ts")).toBe(
"\0eve-ext-scope:context:extensions%2Fcrm",
);
- expect(plugin.resolveId("eve/extension", "/anywhere/config.ts")).toBeUndefined();
+ expect(plugin.resolveId("eve/extension", "/anywhere/config.ts")).toBe(
+ "\0eve-ext-scope:extension:extensions%2Fcrm",
+ );
});
it("never re-enters through virtual shim importers", () => {
@@ -100,7 +109,7 @@ describe("createFixedMountScopePlugin (dev per-module)", () => {
});
describe("shim baking (shared)", () => {
- it("bakes the namespace into the defineState shim", () => {
+ it("bakes the mount identity into the defineState shim", () => {
const shim = createFixedMountScopePlugin("extensions/crm").load(
"\0eve-ext-scope:context:extensions%2Fcrm",
);
@@ -108,6 +117,13 @@ describe("shim baking (shared)", () => {
expect(shim?.code).toContain(`defineMountedState("extensions/crm", name, initial)`);
});
+ it("bakes the mount identity into the defineExtension shim", () => {
+ const shim = createFixedMountScopePlugin("extensions/crm").load(
+ "\0eve-ext-scope:extension:extensions%2Fcrm",
+ );
+ expect(shim?.code).toContain('define(options, "extensions/crm")');
+ });
+
it("passes through non-shim ids in load", () => {
expect(pathPlugin().load("/pkg/crm/extension/tools/budget.ts")).toBeUndefined();
});
diff --git a/packages/eve/src/internal/bundler/extension-scope-plugin.ts b/packages/eve/src/internal/bundler/extension-scope-plugin.ts
index cfc1f1d23..45a282049 100644
--- a/packages/eve/src/internal/bundler/extension-scope-plugin.ts
+++ b/packages/eve/src/internal/bundler/extension-scope-plugin.ts
@@ -45,6 +45,14 @@ function shimSource(mountId: string): string {
].join("\n");
}
+function extensionShimSource(mountId: string): string {
+ return [
+ `import { defineExtension as define } from "eve/extension";`,
+ `export const defineExtension = (options) => define(options, ${JSON.stringify(mountId)});`,
+ "",
+ ].join("\n");
+}
+
/**
* Builds the resolveId/load hook pair shared by both plugin modes. `mountFor`
* returns the owning mount for an importer, or `undefined` to leave the
@@ -57,12 +65,22 @@ function scopeHooks(
return {
name,
resolveId(source: string, importer: string | undefined) {
- if (source !== "eve/context" || importer === undefined || importer.startsWith("\0")) {
+ if (
+ (source !== "eve/context" && source !== "eve/extension") ||
+ importer === undefined ||
+ importer.startsWith("\0")
+ ) {
return undefined;
}
const mountId = mountFor(importer);
if (mountId === undefined) return undefined;
- return `${VIRTUAL_PREFIX}context:${encodeURIComponent(mountId)}`;
+ if (source === "eve/extension") {
+ return `${VIRTUAL_PREFIX}extension:${encodeURIComponent(mountId)}`;
+ }
+ if (source === "eve/context") {
+ return `${VIRTUAL_PREFIX}context:${encodeURIComponent(mountId)}`;
+ }
+ return undefined;
},
load(id: string) {
if (!id.startsWith(VIRTUAL_PREFIX)) {
@@ -70,9 +88,16 @@ function scopeHooks(
}
const descriptor = id.slice(VIRTUAL_PREFIX.length);
const separatorIndex = descriptor.indexOf(":");
- if (descriptor.slice(0, separatorIndex) !== "context") return undefined;
+ const kind = descriptor.slice(0, separatorIndex);
+ if (kind !== "context" && kind !== "extension") return undefined;
const mountId = decodeURIComponent(descriptor.slice(separatorIndex + 1));
- return { code: shimSource(mountId), moduleType: "js" as const };
+ if (kind === "context") {
+ return { code: shimSource(mountId), moduleType: "js" as const };
+ }
+ if (kind === "extension") {
+ return { code: extensionShimSource(mountId), moduleType: "js" as const };
+ }
+ return undefined;
},
};
}
@@ -80,7 +105,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 mount-owned state shim.
+ * `eve/context` and `eve/extension` imports redirected to mount-owned shims.
*
* 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.
diff --git a/packages/eve/src/internal/nitro/routes/channel-dispatch.test.ts b/packages/eve/src/internal/nitro/routes/channel-dispatch.test.ts
index 3935ea130..dae296251 100644
--- a/packages/eve/src/internal/nitro/routes/channel-dispatch.test.ts
+++ b/packages/eve/src/internal/nitro/routes/channel-dispatch.test.ts
@@ -140,6 +140,7 @@ describe("dispatchChannelRequest", () => {
const currentProjects: Array<Awaited<ReturnType<typeof resolveVercelOidcCurrentProject>>> = [];
mockedResolveNitroChannelRuntimeBundle.mockResolvedValue({
agentName: "test-agent",
+ extensionConfigs: new Map(),
channels: [
{
handler: async (request) => {
@@ -183,6 +184,7 @@ describe("dispatchChannelRequest", () => {
mockedResolveNitroChannelRuntimeBundle.mockResolvedValue({
agentName: "test-agent",
+ extensionConfigs: new Map(),
channels: [
{
fetch: async (_request: Request, ctx: { waitUntil: (t: Promise<unknown>) => void }) => {
@@ -262,6 +264,7 @@ describe("dispatchChannelRequest", () => {
let capturedArgs: RouteHandlerArgs | undefined;
mockedResolveNitroChannelRuntimeBundle.mockResolvedValue({
agentName: "test-agent",
+ extensionConfigs: new Map(),
channels: [
{
handler: async (_req, args) => {
@@ -327,6 +330,7 @@ describe("dispatchChannelRequest", () => {
mockedResolveNitroChannelRuntimeBundle.mockResolvedValue({
agentName: "test-agent",
+ extensionConfigs: new Map(),
channels: [
{
handler: async (_req, args) => {
@@ -374,6 +378,7 @@ describe("dispatchChannelRequest", () => {
mockedResolveNitroChannelRuntimeBundle.mockResolvedValue({
agentName: "test-agent",
+ extensionConfigs: new Map(),
channels: [
{
handler: async (_req, args) => {
@@ -411,6 +416,7 @@ describe("dispatchChannelRequest", () => {
mockedResolveNitroChannelRuntimeBundle.mockResolvedValue({
agentName: "test-agent",
+ extensionConfigs: new Map(),
channels: [
{
handler: async (_req, args) => {
@@ -451,6 +457,7 @@ describe("dispatchChannelRequest", () => {
mockedResolveNitroChannelRuntimeBundle.mockResolvedValue({
agentName: "test-agent",
+ extensionConfigs: new Map(),
channels: [
{
handler: async (_req, args) =>
@@ -496,6 +503,7 @@ describe("dispatchChannelRequest", () => {
mockedResolveNitroChannelRuntimeBundle.mockResolvedValue({
agentName: "test-agent",
+ extensionConfigs: new Map(),
channels: [
{
handler: async (_req, args) =>
@@ -538,6 +546,7 @@ describe("dispatchChannelRequest", () => {
mockedResolveNitroChannelRuntimeBundle.mockResolvedValue({
agentName: "test-agent",
+ extensionConfigs: new Map(),
channels: [
{
handler: async (_req, args) => {
@@ -577,6 +586,7 @@ describe("dispatchChannelRequest", () => {
mockedResolveNitroChannelRuntimeBundle.mockResolvedValue({
agentName: "test-agent",
+ extensionConfigs: new Map(),
channels: [
{
fetch: async () => new Response("not used"),
@@ -622,6 +632,7 @@ describe("dispatchChannelRequest", () => {
it("rejects websocket upgrades when no websocket channel matches", async () => {
mockedResolveNitroChannelRuntimeBundle.mockResolvedValue({
agentName: "test-agent",
+ extensionConfigs: new Map(),
channels: [],
runtime,
});
@@ -646,6 +657,7 @@ describe("dispatchChannelRequest", () => {
const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
mockedResolveNitroChannelRuntimeBundle.mockResolvedValue({
agentName: "test-agent",
+ extensionConfigs: new Map(),
channels: [
{
fetch: async () => {
@@ -690,6 +702,7 @@ describe("dispatchChannelRequest", () => {
mockedResolveNitroChannelRuntimeBundle.mockResolvedValue({
agentName: "test-agent",
+ extensionConfigs: new Map(),
channels: [
{
fetch: async (_req, ctx: { waitUntil: (t: Promise<unknown>) => void }) => {
@@ -730,6 +743,7 @@ describe("dispatchChannelRequest", () => {
mockedResolveNitroChannelRuntimeBundle.mockResolvedValue({
agentName: "test-agent",
+ extensionConfigs: new Map(),
channels: [
{
fetch: async () => new Response("ok"),
@@ -816,6 +830,7 @@ function mockRouteSendRuntime(): Runtime {
});
mockedResolveNitroChannelRuntimeBundle.mockResolvedValue({
agentName: "test-agent",
+ extensionConfigs: new Map(),
channels: [
slackChannel(async () => new Response("unused"), {
adapter: { kind: "channel:slack" },
@@ -859,6 +874,7 @@ describe("dispatchChannelRequest tracing", () => {
it("uses the semantic request name", async () => {
mockedResolveNitroChannelRuntimeBundle.mockResolvedValue({
agentName: "test-agent",
+ extensionConfigs: new Map(),
channels: [slackChannel(async () => new Response("ok"))],
runtime,
});
@@ -877,6 +893,7 @@ describe("dispatchChannelRequest tracing", () => {
let spansDuringHandler = -1;
mockedResolveNitroChannelRuntimeBundle.mockResolvedValue({
agentName: "test-agent",
+ extensionConfigs: new Map(),
channels: [
slackChannel(
async () => {
@@ -930,6 +947,7 @@ describe("dispatchChannelRequest tracing", () => {
mockedResolveNitroChannelRuntimeBundle.mockResolvedValue({
agentName: "test-agent",
+ extensionConfigs: new Map(),
channels: [
slackChannel(async () => new Response("ok"), {
adapter: { kind: "http" },
@@ -948,6 +966,7 @@ describe("dispatchChannelRequest tracing", () => {
it("makes a span created inside the handler a child of the request span", async () => {
mockedResolveNitroChannelRuntimeBundle.mockResolvedValue({
agentName: "test-agent",
+ extensionConfigs: new Map(),
channels: [
slackChannel(async () => {
// Model hook.resume: a nested span opened under the active context.
@@ -1007,6 +1026,7 @@ describe("dispatchChannelRequest tracing", () => {
const parentId = "b7ad6b7169203331";
mockedResolveNitroChannelRuntimeBundle.mockResolvedValue({
agentName: "test-agent",
+ extensionConfigs: new Map(),
channels: [slackChannel(async () => new Response("ok"))],
runtime,
});
@@ -1029,6 +1049,7 @@ describe("dispatchChannelRequest tracing", () => {
const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
mockedResolveNitroChannelRuntimeBundle.mockResolvedValue({
agentName: "test-agent",
+ extensionConfigs: new Map(),
channels: [
slackChannel(async () => {
throw new Error("handler exploded");
@@ -1077,6 +1098,7 @@ describe("dispatchChannelRequest tracing", () => {
it("still emits a 404 span with the route but no channel identity when nothing matches", async () => {
mockedResolveNitroChannelRuntimeBundle.mockResolvedValue({
agentName: "test-agent",
+ extensionConfigs: new Map(),
channels: [],
runtime,
});
@@ -1105,6 +1127,7 @@ describe("dispatchChannelRequest tracing", () => {
mockedResolveNitroChannelRuntimeBundle.mockResolvedValue({
agentName: "test-agent",
+ extensionConfigs: new Map(),
channels: [
{
fetch: async () => new Response("ok"),
@@ -1167,6 +1190,7 @@ describe("dispatchChannelRequest without an OTel provider", () => {
const waitUntil = vi.fn<(task: Promise<unknown>) => void>();
mockedResolveNitroChannelRuntimeBundle.mockResolvedValue({
agentName: "test-agent",
+ extensionConfigs: new Map(),
channels: [slackChannel(async () => new Response("ok"))],
runtime,
});
@@ -1210,6 +1234,7 @@ describe("dispatchChannelRequest with request tracing not enabled", () => {
const waitUntil = vi.fn<(task: Promise<unknown>) => void>();
mockedResolveNitroChannelRuntimeBundle.mockResolvedValue({
agentName: "test-agent",
+ extensionConfigs: new Map(),
channels: [slackChannel(async () => new Response("ok"))],
runtime,
});
diff --git a/packages/eve/src/internal/nitro/routes/channel-dispatch.ts b/packages/eve/src/internal/nitro/routes/channel-dispatch.ts
index 959040936..2fc1831a3 100644
--- a/packages/eve/src/internal/nitro/routes/channel-dispatch.ts
+++ b/packages/eve/src/internal/nitro/routes/channel-dispatch.ts
@@ -33,6 +33,7 @@ import { createRouteInvokeTool } from "#internal/nitro/routes/route-invoke-tool.
import { readVercelProjectLink } from "#internal/vercel/project-link.js";
import { withVercelOidcProjectResolver } from "#channel/auth/vercel-oidc-project.js";
import { withLocalDevRequestScope } from "#runtime/local-dev-capability.js";
+import { withExtensionConfigs } from "#runtime/extension-mount-configs.js";
import { getWorld } from "#internal/workflow/runtime.js";
const log = createLogger("channel.dispatch");
@@ -104,22 +105,27 @@ export async function dispatchChannelRequest(
let response: Response;
try {
- response = await withDevelopmentVercelOidcContext(config, event.req, async () => {
- if (matchedChannel.handler) {
- // Authored CompiledChannel route — build RouteHandlerArgs.
- return await matchedChannel.handler(event.req, routeArgs.args);
- }
-
- // Framework-internal fetch-only channel (e.g. the connection
- // callback route). Build a RouteContext with the agent handle.
- const ctx: RouteContext = {
- waitUntil: routeArgs.args.waitUntil,
- params: routeArgs.args.params,
- requestIp: routeArgs.args.requestIp,
- };
-
- return await matchedChannel.fetch(event.req, ctx);
- });
+ response = await withDevelopmentVercelOidcContext(
+ config,
+ event.req,
+ async () =>
+ await withExtensionConfigs(bundle.extensionConfigs, async () => {
+ if (matchedChannel.handler) {
+ // Authored CompiledChannel route — build RouteHandlerArgs.
+ return await matchedChannel.handler(event.req, routeArgs.args);
+ }
+
+ // Framework-internal fetch-only channel (e.g. the connection
+ // callback route). Build a RouteContext with the agent handle.
+ const ctx: RouteContext = {
+ waitUntil: routeArgs.args.waitUntil,
+ params: routeArgs.args.params,
+ requestIp: routeArgs.args.requestIp,
+ };
+
+ return await matchedChannel.fetch(event.req, ctx);
+ }),
+ );
} catch (error) {
// Without this a handler throw is only Nitro's default 5xx, with no eve
// log. logError records the exception against the active request span,
@@ -177,10 +183,14 @@ export async function dispatchChannelWebSocketRequest(
const hooks = await withDevelopmentVercelOidcContext(
config,
event.req,
- async () => await websocket(event.req, routeArgs.args),
+ async () =>
+ await withExtensionConfigs(
+ bundle.extensionConfigs,
+ async () => await websocket(event.req, routeArgs.args),
+ ),
);
flushBackgroundTasks(event, routeArgs.backgroundTasks, routeKey, matchedChannel.name);
- return hooks;
+ return withScopedWebSocketHooks(hooks, bundle.extensionConfigs);
} catch (error) {
const errorId = logError(log, "channel websocket handler threw", error, {
routeKey,
@@ -194,6 +204,27 @@ export async function dispatchChannelWebSocketRequest(
}
}
+function withScopedWebSocketHooks(
+ hooks: WebSocketRouteHooks,
+ extensionConfigs: ReadonlyMap<string, Record<string, unknown>>,
+): WebSocketRouteHooks {
+ // Hooks may be a class instance relying on its prototype or private fields,
+ // so they run bound to the authored object, not to this wrapper.
+ const scoped =
+ <Args extends unknown[], Result>(callback: (...args: Args) => Result) =>
+ (...args: Args): Result =>
+ withExtensionConfigs(extensionConfigs, () => callback.apply(hooks, args));
+
+ return {
+ ...hooks,
+ close: hooks.close === undefined ? undefined : scoped(hooks.close),
+ error: hooks.error === undefined ? undefined : scoped(hooks.error),
+ message: hooks.message === undefined ? undefined : scoped(hooks.message),
+ open: hooks.open === undefined ? undefined : scoped(hooks.open),
+ upgrade: hooks.upgrade === undefined ? undefined : scoped(hooks.upgrade),
+ };
+}
+
async function withDevelopmentVercelOidcContext<T>(
config: NitroArtifactsConfig,
request: Request,
diff --git a/packages/eve/src/internal/nitro/routes/runtime-stack.ts b/packages/eve/src/internal/nitro/routes/runtime-stack.ts
index 5d99b577c..980392249 100644
--- a/packages/eve/src/internal/nitro/routes/runtime-stack.ts
+++ b/packages/eve/src/internal/nitro/routes/runtime-stack.ts
@@ -21,6 +21,8 @@ import {
interface NitroChannelRuntimeBundle {
readonly agentName: string;
readonly channels: readonly ResolvedChannelDefinition[];
+ /** Root extension configs; channel routes serve the root agent. */
+ readonly extensionConfigs: ReadonlyMap<string, Record<string, unknown>>;
readonly resolveRemoteAgentStreamHeaders?: RemoteAgentStreamHeadersResolver;
readonly runtime: Runtime;
}
@@ -44,6 +46,7 @@ export async function resolveNitroChannelRuntimeBundle(
return {
agentName: bundle.resolvedAgent.config?.name ?? "eve",
channels: bundle.graph.root.channels,
+ extensionConfigs: bundle.graph.root.extensionConfigs,
resolveRemoteAgentStreamHeaders: async (input) =>
await resolveRemoteAgentStreamHeaders({ bundle, ...input }),
runtime,
diff --git a/packages/eve/src/internal/nitro/routes/schedule-task.ts b/packages/eve/src/internal/nitro/routes/schedule-task.ts
index 77bf5287c..dcae0d14b 100644
--- a/packages/eve/src/internal/nitro/routes/schedule-task.ts
+++ b/packages/eve/src/internal/nitro/routes/schedule-task.ts
@@ -41,6 +41,7 @@ export async function dispatchScheduleTaskFromArtifacts(
const dispatcher = new ScheduleDispatcher({
runtime,
channels: bundle.graph.root.channels,
+ extensionConfigs: bundle.graph.root.extensionConfigs,
});
const dispatchInput: {
diff --git a/packages/eve/src/public/definitions/extension.test.ts b/packages/eve/src/public/definitions/extension.test.ts
index 4952bd67a..f9c80edfc 100644
--- a/packages/eve/src/public/definitions/extension.test.ts
+++ b/packages/eve/src/public/definitions/extension.test.ts
@@ -2,7 +2,8 @@ import { describe, expect, it } from "vitest";
import { z } from "zod";
import type { StandardSchemaV1 } from "#compiled/@standard-schema/spec/index.js";
-import { defineExtension } from "#public/definitions/extension.js";
+import { defineExtension, readMountedExtensionConfig } from "#public/definitions/extension.js";
+import { withExtensionConfigs } from "#runtime/extension-mount-configs.js";
describe("defineExtension", () => {
it("exposes the declared schema", () => {
@@ -22,15 +23,18 @@ describe("defineExtension", () => {
const mounted = ext({ apiKey: "sk-456" });
expect(mounted).toBeDefined();
- expect(ext.config).toEqual({ apiKey: "sk-456", baseUrl: "https://api.acme.example" });
+ expect(readMountedExtensionConfig(mounted)).toEqual({
+ apiKey: "sk-456",
+ baseUrl: "https://api.acme.example",
+ });
});
it("lets a bound value override a default", () => {
const ext = defineExtension({
config: z.object({ baseUrl: z.string().default("https://default") }),
});
- ext({ baseUrl: "https://override" });
- expect(ext.config).toEqual({ baseUrl: "https://override" });
+ const mounted = ext({ baseUrl: "https://override" });
+ expect(readMountedExtensionConfig(mounted)).toEqual({ baseUrl: "https://override" });
});
it("applies schema defaults when read before an all-optional mount binds", () => {
@@ -70,16 +74,21 @@ describe("defineExtension", () => {
});
it("types the config reader from the schema", () => {
- const ext = defineExtension({
- config: z.object({ apiKey: z.string(), tier: z.string().default("free") }),
- });
+ const ext = defineExtension(
+ { config: z.object({ apiKey: z.string(), tier: z.string().default("free") }) },
+ "@acme/types",
+ );
ext({ apiKey: "k" });
+ const config = withExtensionConfigs(
+ new Map([["@acme/types", { apiKey: "k", tier: "free" }]]),
+ () => ext.config,
+ );
// Compile-time assertions (checked by `tsc`).
- const apiKey: string = ext.config.apiKey;
- const tier: string = ext.config.tier;
+ const apiKey: string = config.apiKey;
+ const tier: string = config.tier;
// @ts-expect-error apiKey is a string, not a number
- const wrong: number = ext.config.apiKey;
+ const wrong: number = config.apiKey;
void wrong;
expect(apiKey).toBe("k");
diff --git a/packages/eve/src/public/definitions/extension.ts b/packages/eve/src/public/definitions/extension.ts
index 26631afaa..502271a43 100644
--- a/packages/eve/src/public/definitions/extension.ts
+++ b/packages/eve/src/public/definitions/extension.ts
@@ -3,6 +3,43 @@ import type { StandardSchemaV1 } from "#compiled/@standard-schema/spec/index.js"
/** Marker carried by the object an extension handle produces when called. */
const MOUNTED_EXTENSION = Symbol.for("eve.mounted-extension");
+/** The validated config a mount call produced, read back when the agent graph resolves. */
+const MOUNTED_CONFIG = Symbol.for("eve.mounted-extension-config");
+
+/**
+ * Returns the extension configs the active runtime scope (session, channel
+ * request, or schedule run) binds, or `undefined` outside one. Installed by the
+ * runtime.
+ */
+const SCOPED_CONFIGS_RESOLVER = Symbol.for("eve.extension-scoped-configs-resolver");
+
+type ScopedConfigsResolver = () => ReadonlyMap<string, Record<string, unknown>> | undefined;
+
+function scopedConfigs(): ReadonlyMap<string, Record<string, unknown>> | undefined {
+ const resolve = (globalThis as Record<symbol, unknown>)[SCOPED_CONFIGS_RESOLVER];
+ return typeof resolve === "function" ? (resolve as ScopedConfigsResolver)() : undefined;
+}
+
+/**
+ * Returns the config a mount module's default export was called with, or
+ * `undefined` for a bare (no-config) mount.
+ */
+export function readMountedExtensionConfig(value: unknown): Record<string, unknown> | undefined {
+ if (typeof value !== "object" || value === null || !(MOUNTED_CONFIG in value)) {
+ return undefined;
+ }
+ return (value as { readonly [MOUNTED_CONFIG]: Record<string, unknown> })[MOUNTED_CONFIG];
+}
+
+/**
+ * Installs the runtime lookup the handle's `config` consults first, so each
+ * read resolves against the agent node and graph of the active scope instead
+ * of the last mount evaluated. The resolver holds no graph state itself.
+ */
+export function installScopedExtensionConfigsResolver(resolve: ScopedConfigsResolver): void {
+ (globalThis as Record<symbol, unknown>)[SCOPED_CONFIGS_RESOLVER] = resolve;
+}
+
/**
* Marker value an extension handle returns when called. The consumer's mount
* file default-exports it (directly for a no-config extension, or as the result
@@ -23,7 +60,11 @@ export interface MountedExtension {
export interface ExtensionHandle<S extends StandardSchemaV1 = StandardSchemaV1> {
/** Consumer mount factory: validates `values` against the schema and binds them. */
(values: StandardSchemaV1.InferInput<S>): MountedExtension;
- /** The bound configuration, typed from the schema (defaults applied). */
+ /**
+ * The configuration of the mount serving the current agent, typed from the
+ * schema (defaults applied). Read it inside handlers such as a tool's
+ * `execute`; a module top-level read cannot tell which agent is asking.
+ */
readonly config: StandardSchemaV1.InferOutput<S>;
/** The declared config schema; read by `eve extension build`. */
readonly schema: S;
@@ -80,7 +121,8 @@ function validateConfig(
* handle. A consuming agent mounts it, calling the handle to bind config
* (`export default crm({ apiKey })`) or re-exporting it directly when there is no
* config (`export { default } from "@acme/gizmo"`). The extension's own tools,
- * hooks, and connections read the bound config through the handle:
+ * hooks, and connections read the config of the mount serving the current
+ * agent through the handle, inside their handlers:
*
* ```ts
* // extension/extension.ts
@@ -89,12 +131,19 @@ function validateConfig(
* export default defineExtension({ config: z.object({ apiKey: z.string() }) });
*
* // extension/tools/search.ts
+ * import { defineTool } from "eve/tools";
* import extension from "../extension.js";
- * const { apiKey } = extension.config;
+ * export default defineTool({
+ * // ...
+ * async execute() {
+ * const { apiKey } = extension.config;
+ * // ...
+ * },
+ * });
* ```
*
- * The second argument is retained for source compatibility with compiled extension
- * declarations; instance bindings come from the loaded module graph, not its value.
+ * The `namespace` argument is supplied by the bundler shim and is not part of the
+ * authoring surface.
*/
export function defineExtension<const S extends StandardSchemaV1>(
options: { readonly config: S },
@@ -106,20 +155,30 @@ export function defineExtension(
): NoConfigExtensionHandle;
export function defineExtension(
options?: { readonly config?: StandardSchemaV1 },
- _namespace?: string,
+ namespace?: string,
): ExtensionHandle | NoConfigExtensionHandle {
const schema = options?.config;
- let bound: Record<string, unknown> | undefined;
+ const resolvedNamespace = namespace;
+ let boundConfig: Record<string, unknown> | undefined;
+
const handle = ((values?: unknown): MountedExtension => {
- bound = validateConfig(schema, values);
- return { [MOUNTED_EXTENSION]: true };
+ const parsed = validateConfig(schema, values);
+ boundConfig = parsed;
+ return { [MOUNTED_EXTENSION]: true, [MOUNTED_CONFIG]: parsed } as MountedExtension;
}) as ExtensionHandle & NoConfigExtensionHandle;
Object.defineProperty(handle, "schema", { value: schema, enumerable: true });
Object.defineProperty(handle, "config", {
enumerable: true,
get(): Record<string, unknown> {
- return bound ?? validateConfig(schema, {});
+ const scoped = scopedConfigs();
+ if (scoped !== undefined) {
+ return (
+ (resolvedNamespace === undefined ? undefined : scoped.get(resolvedNamespace)) ??
+ validateConfig(schema, {})
+ );
+ }
+ return boundConfig ?? validateConfig(schema, {});
},
});
diff --git a/packages/eve/src/runtime/extension-mount-configs.test.ts b/packages/eve/src/runtime/extension-mount-configs.test.ts
new file mode 100644
index 000000000..cb4ee2c5c
--- /dev/null
+++ b/packages/eve/src/runtime/extension-mount-configs.test.ts
@@ -0,0 +1,110 @@
+import { describe, expect, it } from "vitest";
+
+import { ContextContainer, contextStorage } from "#context/container.js";
+import {
+ type CompiledAgentManifest,
+ type CompiledExtensionMount,
+ ROOT_COMPILED_AGENT_NODE_ID,
+} from "#compiler/manifest.js";
+import type { CompiledModuleMap } from "#compiler/module-map.js";
+import { defineExtension } from "#public/definitions/extension.js";
+import {
+ resolveExtensionMountConfigs,
+ withExtensionConfigs,
+} from "#runtime/extension-mount-configs.js";
+import type { ResolvedRuntimeAgentNode } from "#runtime/graph.js";
+import { BundleKey, type CompiledBundle } from "#runtime/sessions/runtime-context-keys.js";
+
+const regionSchema = {
+ "~standard": {
+ version: 1 as const,
+ vendor: "test",
+ validate: (value: unknown) => ({ value: { region: "us", ...(value as object) } }),
+ },
+};
+
+function crmMount(sourceId: string): CompiledExtensionMount {
+ return {
+ externalDependencies: [],
+ mountLogicalPath: "agent/extensions/crm.ts",
+ mountSourceId: sourceId,
+ namespace: "crm",
+ packageName: "@acme/crm",
+ specifier: "@acme/crm",
+ mountId: sourceId,
+ sourceRoot: "/node_modules/@acme/crm/extension",
+ mountSourcePath: "/app/agent/extensions/crm.ts",
+ };
+}
+
+describe("resolveExtensionMountConfigs", () => {
+ const crm = defineExtension({ config: regionSchema }, "root-crm");
+ const manifest = {
+ extensionMounts: [crmMount("root-crm")],
+ subagents: [
+ {
+ agent: { extensionMounts: [] as CompiledExtensionMount[] },
+ nodeId: "shipped",
+ parentNodeId: ROOT_COMPILED_AGENT_NODE_ID,
+ },
+ {
+ agent: { extensionMounts: [crmMount("bare-crm")] },
+ nodeId: "bare",
+ parentNodeId: ROOT_COMPILED_AGENT_NODE_ID,
+ },
+ ],
+ } as CompiledAgentManifest;
+ const moduleMap: CompiledModuleMap = {
+ nodes: {
+ [ROOT_COMPILED_AGENT_NODE_ID]: {
+ modules: { "root-crm": { default: crm({ region: "eu" }) } },
+ },
+ bare: { modules: { "bare-crm": { default: crm } } },
+ },
+ };
+
+ it("inherits the parent's config for a node without its own mount", () => {
+ const configs = resolveExtensionMountConfigs(manifest, moduleMap);
+
+ expect(configs.get("shipped")?.get("root-crm")).toEqual({ region: "eu" });
+ });
+
+ it("does not inherit the parent's config for a node's own bare mount", () => {
+ const configs = resolveExtensionMountConfigs(manifest, moduleMap);
+
+ expect(configs.get("bare")?.has("bare-crm")).toBe(false);
+ });
+});
+
+/** A session scope whose bundle serves a node with `extensionConfigs`. */
+function sessionScope(extensionConfigs: ResolvedRuntimeAgentNode["extensionConfigs"]) {
+ const ctx = new ContextContainer();
+ ctx.set(BundleKey, {
+ graph: { root: { extensionConfigs } as ResolvedRuntimeAgentNode },
+ } as CompiledBundle);
+ return ctx;
+}
+
+describe("extension config scoping", () => {
+ it("gives a session node without a mount the defaults, not another agent's config", () => {
+ const crm = defineExtension({ config: regionSchema }, "root-crm");
+ crm({ region: "eu" });
+
+ const config = contextStorage.run(sessionScope(new Map()), () => crm.config);
+
+ expect(config).toEqual({ region: "us" });
+ });
+
+ it("reads ingress configs until a session bundle takes over", () => {
+ const crm = defineExtension({ config: regionSchema }, "root-crm");
+ crm({ region: "eu" });
+ const session = sessionScope(new Map([["root-crm", { region: "sa" }]]));
+
+ const seen = withExtensionConfigs(new Map([["root-crm", { region: "ap" }]]), () => ({
+ ingress: crm.config,
+ session: contextStorage.run(session, () => crm.config),
+ }));
+
+ expect(seen).toEqual({ ingress: { region: "ap" }, session: { region: "sa" } });
+ });
+});
diff --git a/packages/eve/src/runtime/extension-mount-configs.ts b/packages/eve/src/runtime/extension-mount-configs.ts
new file mode 100644
index 000000000..3e5ca1a1b
--- /dev/null
+++ b/packages/eve/src/runtime/extension-mount-configs.ts
@@ -0,0 +1,79 @@
+import { ContextContainer, contextStorage } from "#context/container.js";
+import { ExtensionConfigsKey } from "#context/keys.js";
+import { type CompiledAgentManifest, ROOT_COMPILED_AGENT_NODE_ID } from "#compiler/manifest.js";
+import type { CompiledModuleMap } from "#compiler/module-map.js";
+import {
+ installScopedExtensionConfigsResolver,
+ readMountedExtensionConfig,
+} from "#public/definitions/extension.js";
+import { BundleKey } from "#runtime/sessions/runtime-context-keys.js";
+
+type Config = Record<string, unknown>;
+type ExtensionConfigs = ReadonlyMap<string, Config>;
+
+interface MountNode {
+ readonly agent: { readonly extensionMounts: CompiledAgentManifest["extensionMounts"] };
+ readonly parentNodeId?: string;
+}
+
+// A session bundle points `graph.root` at its own node, so its configs win over
+// any ingress configs an enclosing scope set.
+installScopedExtensionConfigsResolver(() => {
+ const ctx = contextStorage.getStore();
+ return ctx?.get(BundleKey)?.graph.root.extensionConfigs ?? ctx?.get(ExtensionConfigsKey);
+});
+
+/**
+ * Resolves every agent node's extension mount configs, keyed by compiled node
+ * id, so one extension mounted in several agents keeps each mount's config. A
+ * node without its own mount of an extension (for example a subagent the
+ * extension ships) inherits its parent's; a node's own bare mount uses the
+ * schema defaults.
+ *
+ * The result belongs to this graph only; the runtime stores it on the resolved
+ * nodes so concurrent or reloaded graphs never share it.
+ */
+export function resolveExtensionMountConfigs(
+ manifest: CompiledAgentManifest,
+ moduleMap: CompiledModuleMap,
+): ReadonlyMap<string, ExtensionConfigs> {
+ const nodesById = new Map<string, MountNode>([
+ [ROOT_COMPILED_AGENT_NODE_ID, { agent: manifest }],
+ ]);
+ for (const subagent of manifest.subagents) {
+ nodesById.set(subagent.nodeId, subagent);
+ }
+ const effectiveByNodeId = new Map<string, ExtensionConfigs>();
+
+ const effectiveConfigs = (nodeId: string): ExtensionConfigs => {
+ const cached = effectiveByNodeId.get(nodeId);
+ if (cached !== undefined) return cached;
+ const node = nodesById.get(nodeId);
+ const configs = new Map(
+ node?.parentNodeId === undefined ? [] : effectiveConfigs(node.parentNodeId),
+ );
+ for (const mount of node?.agent.extensionMounts ?? []) {
+ const config = readMountedExtensionConfig(
+ moduleMap.nodes[nodeId]?.modules[mount.mountSourceId]?.default,
+ );
+ if (config === undefined) configs.delete(mount.mountId);
+ else configs.set(mount.mountId, config);
+ }
+ effectiveByNodeId.set(nodeId, configs);
+ return configs;
+ };
+
+ for (const nodeId of nodesById.keys()) effectiveConfigs(nodeId);
+ return effectiveByNodeId;
+}
+
+/**
+ * Runs `callback` in a fresh ingress scope where extension handles read
+ * `configs`. Used by channel requests and websocket callbacks, which carry no
+ * session bundle. Like every ingress scope, it inherits only the dev-TUI hint.
+ */
+export function withExtensionConfigs<T>(configs: ExtensionConfigs, callback: () => T): T {
+ const scope = new ContextContainer();
+ scope.setVirtualContext(ExtensionConfigsKey, configs);
+ return contextStorage.run(scope, callback);
+}
diff --git a/packages/eve/src/runtime/graph.ts b/packages/eve/src/runtime/graph.ts
index 7e111bc1b..5f39831b7 100644
--- a/packages/eve/src/runtime/graph.ts
+++ b/packages/eve/src/runtime/graph.ts
@@ -22,6 +22,12 @@ export interface ResolvedRuntimeAgentNode {
* combine framework defaults with the resolved-agent's authored channels.
*/
readonly channels: readonly ResolvedChannelDefinition[];
+ /**
+ * Validated config of each extension this node mounts, keyed by package
+ * namespace. Inherited from the parent when the node has no mount of its
+ * own (for example a subagent the extension ships).
+ */
+ readonly extensionConfigs: ReadonlyMap<string, Record<string, unknown>>;
/**
* Per-node hook registry. Stream-event subscribers fan out alongside
* channel adapter event handlers.
diff --git a/packages/eve/src/runtime/resolve-agent-graph.ts b/packages/eve/src/runtime/resolve-agent-graph.ts
index 3fe8e4b63..7b813f770 100644
--- a/packages/eve/src/runtime/resolve-agent-graph.ts
+++ b/packages/eve/src/runtime/resolve-agent-graph.ts
@@ -12,6 +12,7 @@ import { validateCompiledModuleMap } from "#compiler/validate-artifact.js";
import type { HeadersValue } from "#client/types.js";
import { expectObjectRecord } from "#internal/authored-module.js";
import { createResolvedRuntimeTurnAgent } from "#runtime/agent/bootstrap.js";
+import { resolveExtensionMountConfigs } from "#runtime/extension-mount-configs.js";
import { type ResolvedAgentGraphBundle, ROOT_RUNTIME_AGENT_NODE_ID } from "#runtime/graph.js";
import { createRuntimeHookRegistry } from "#runtime/hooks/registry.js";
import { resolveAgent } from "#runtime/resolve-agent.js";
@@ -80,6 +81,7 @@ export async function resolveRuntimeAgentGraph(
input: ResolveRuntimeAgentGraphInput,
): Promise<ResolvedAgentGraphBundle> {
validateCompiledModuleMap(input.manifest, input.moduleMap);
+ const extensionConfigsByNodeId = resolveExtensionMountConfigs(input.manifest, input.moduleMap);
const nodesByNodeId = new Map<string, ResolvedAgentGraphBundle["root"]>();
const childNodeIdsByParentNodeId = createChildNodeIdsByParentNodeId(input.manifest);
const subagentNodesById = new Map(
@@ -87,6 +89,7 @@ export async function resolveRuntimeAgentGraph(
);
const root = await resolveRuntimeAgentNode({
childNodeIdsByParentNodeId,
+ extensionConfigsByNodeId,
manifest: input.manifest,
moduleMap: input.moduleMap,
nodeId: ROOT_COMPILED_AGENT_NODE_ID,
@@ -113,6 +116,10 @@ interface ResolveRuntimeAgentNodeInput {
readonly nodesByNodeId: Map<string, ResolvedAgentGraphBundle["root"]>;
readonly sourceId?: string;
readonly subagentNodesById: ReadonlyMap<string, CompiledSubagentNode>;
+ readonly extensionConfigsByNodeId: ReadonlyMap<
+ string,
+ ReadonlyMap<string, Record<string, unknown>>
+ >;
}
async function resolveRuntimeAgentNode(
@@ -161,11 +168,13 @@ async function resolveRuntimeAgentNode(
nodesByNodeId: input.nodesByNodeId,
parentNodeId: input.nodeId,
subagentNodesById: input.subagentNodesById,
+ extensionConfigsByNodeId: input.extensionConfigsByNodeId,
}),
});
const node: ResolvedAgentGraphBundle["root"] = {
agent,
channels: agent.channels,
+ extensionConfigs: input.extensionConfigsByNodeId.get(input.nodeId) ?? new Map(),
hookRegistry: createRuntimeHookRegistry(agent.hooks),
nodeId,
sandboxRegistry,
@@ -192,6 +201,10 @@ async function resolveRuntimeSubagents(input: {
readonly nodesByNodeId: Map<string, ResolvedAgentGraphBundle["root"]>;
readonly parentNodeId: string;
readonly subagentNodesById: ReadonlyMap<string, CompiledSubagentNode>;
+ readonly extensionConfigsByNodeId: ReadonlyMap<
+ string,
+ ReadonlyMap<string, Record<string, unknown>>
+ >;
}): Promise<readonly ResolvedRuntimeDelegationNode[]> {
const resolvedSubagents: ResolvedRuntimeDelegationNode[] = [];
const childNodeIds = input.childNodeIdsByParentNodeId.get(input.parentNodeId) ?? [];
@@ -216,6 +229,7 @@ async function resolveRuntimeSubagents(input: {
nodesByNodeId: input.nodesByNodeId,
sourceRef,
subagentNodesById: input.subagentNodesById,
+ extensionConfigsByNodeId: input.extensionConfigsByNodeId,
}),
);
}
@@ -239,6 +253,10 @@ async function resolveRuntimeSubagent(input: {
readonly nodesByNodeId: Map<string, ResolvedAgentGraphBundle["root"]>;
readonly sourceRef: CompiledSubagentNode;
readonly subagentNodesById: ReadonlyMap<string, CompiledSubagentNode>;
+ readonly extensionConfigsByNodeId: ReadonlyMap<
+ string,
+ ReadonlyMap<string, Record<string, unknown>>
+ >;
}): Promise<ResolvedRuntimeSubagentNode> {
const variant:
| { readonly description: string; readonly dynamic?: never; readonly tool?: boolean }
@@ -274,6 +292,7 @@ async function resolveRuntimeSubagent(input: {
nodesByNodeId: input.nodesByNodeId,
sourceId: input.sourceRef.sourceId,
subagentNodesById: input.subagentNodesById,
+ extensionConfigsByNodeId: input.extensionConfigsByNodeId,
});
return resolvedSubagent;
diff --git a/packages/eve/src/runtime/schedules/dispatch-occurrence.ts b/packages/eve/src/runtime/schedules/dispatch-occurrence.ts
index af43baf4f..1719ae627 100644
--- a/packages/eve/src/runtime/schedules/dispatch-occurrence.ts
+++ b/packages/eve/src/runtime/schedules/dispatch-occurrence.ts
@@ -26,6 +26,7 @@ export async function dispatchScheduledOccurrence(input: {
compiledArtifactsSource: input.bundle.compiledArtifactsSource,
}),
channels: input.bundle.graph.root.channels,
+ extensionConfigs: input.bundle.graph.root.extensionConfigs,
}).triggerCollection({
collectionId: input.collection,
definition: input.definition,
diff --git a/packages/eve/test/scenarios/mounted-extension-authored-source.scenario.test.ts b/packages/eve/test/scenarios/mounted-extension-authored-source.scenario.test.ts
new file mode 100644
index 000000000..d59d8e6de
--- /dev/null
+++ b/packages/eve/test/scenarios/mounted-extension-authored-source.scenario.test.ts
@@ -0,0 +1,337 @@
+import type { H3Event } from "nitro";
+import { describe, expect, it } from "vitest";
+
+import { compileAgent } from "../../src/compiler/compile-agent.js";
+import {
+ type CompiledAgentManifest,
+ ROOT_COMPILED_AGENT_NODE_ID,
+} from "../../src/compiler/manifest.js";
+import type { CompiledModuleMap } from "../../src/compiler/module-map.js";
+import { ContextContainer, contextStorage } from "../../src/context/container.js";
+import { withExtensionConfigs } from "../../src/runtime/extension-mount-configs.js";
+import { createDiskRuntimeCompiledArtifactsSource } from "../../src/runtime/compiled-artifacts-source.js";
+import { loadCompiledManifest } from "../../src/runtime/loaders/manifest.js";
+import { loadCompiledModuleMapFromAuthoredSource } from "../../src/internal/authored-module-map-loader.js";
+import { loadResolvedModuleExport } from "../../src/runtime/resolve-helpers.js";
+import { createDevelopmentNitroArtifactsConfig } from "../../src/internal/nitro/host/artifacts-config.js";
+import {
+ dispatchChannelRequest,
+ dispatchChannelWebSocketRequest,
+} from "../../src/internal/nitro/routes/channel-dispatch.js";
+import { dispatchScheduleTaskFromArtifacts } from "../../src/internal/nitro/routes/schedule-task.js";
+import { createScheduleRegistrations } from "../../src/runtime/schedules/register.js";
+import { loadResolvedCompiledSchedules } from "../../src/runtime/schedules/resolve-schedule.js";
+import type { ResolvedAgentGraphBundle } from "../../src/runtime/graph.js";
+import { resolveRuntimeAgentGraph } from "../../src/runtime/resolve-agent-graph.js";
+import { BundleKey, type CompiledBundle } from "../../src/runtime/sessions/runtime-context-keys.js";
+import { useScenarioApp } from "../../src/internal/testing/scenario-app.js";
+
+const scenarioApp = useScenarioApp();
+const SCHEDULE_API_KEY_SLOT = "eve.scenario.crm-schedule-api-key";
+const compatibilityManifest = JSON.stringify({
+ kind: "eve-extension",
+ formatVersion: 1,
+ builtWithEve: "0.0.0-test",
+ requires: { extension: 1, tool: 1, config: 1 },
+});
+
+/**
+ * Runs the `eve eval` / `eve dev` path: the module map is hydrated from authored
+ * source, so the extension-scope plugin must bind config across separately-bundled
+ * mount and tool modules. Deterministic guard for the config-binding regression.
+ */
+describe("mounted extension via authored-source loader", () => {
+ it("binds mounted config so a composed tool reads it", async () => {
+ const app = await scenarioApp({
+ name: "mounted-extension-authored-source",
+ installDependencies: true,
+ files: {
+ ...crmExtensionPackageFiles(),
+ "agent/agent.mjs": 'export default { model: "openai/gpt-5.4" };\n',
+ "agent/instructions.md": "You are a precise assistant.\n",
+ "agent/extensions/crm.mjs": [
+ 'import crm from "@acme/crm";',
+ 'export default crm({ apiKey: "sk-authored" });',
+ "",
+ ].join("\n"),
+ },
+ });
+
+ await compileAgent({ startPath: app.appRoot });
+
+ const compiledArtifactsSource = createDiskRuntimeCompiledArtifactsSource(app.appRoot);
+ const [manifest, moduleMap] = await Promise.all([
+ loadCompiledManifest({ compiledArtifactsSource }),
+ loadCompiledModuleMapFromAuthoredSource({ compiledArtifactsSource }),
+ ]);
+ const graph = await resolveRuntimeAgentGraph({ manifest, moduleMap });
+
+ const tool = graph.root.agent.tools.find((entry) => entry.name === "crm__crm_echo");
+ expect(tool).toBeDefined();
+ await expect(
+ withExtensionConfigs(graph.root.extensionConfigs, () =>
+ tool?.execute?.({}, { messages: [], toolCallId: "call_1" }),
+ ),
+ ).resolves.toEqual({ apiKey: "sk-authored" });
+ });
+
+ it("keeps each agent's config when one extension is mounted in several agents", async () => {
+ const { manifest, moduleMap } = await createMultiMountApp(
+ "mounted-extension-authored-source-multi-mount",
+ );
+ const graph = await resolveRuntimeAgentGraph({ manifest, moduleMap });
+ const researcherNodeId = manifest.subagents[0]?.nodeId;
+ expect(researcherNodeId).toBeDefined();
+
+ await expect(echoInSession(graph, undefined)).resolves.toEqual({ apiKey: "sk-root" });
+ await expect(echoInSession(graph, researcherNodeId)).resolves.toEqual({
+ apiKey: "sk-researcher",
+ });
+ });
+
+ it("keeps a session on its own graph's config while another graph loads", async () => {
+ const { manifest, moduleMap } = await createMultiMountApp(
+ "mounted-extension-authored-source-graph-generations",
+ );
+ const graphA = await resolveRuntimeAgentGraph({ manifest, moduleMap });
+ // A second generation of the same app (e.g. a dev reload) with a new root key.
+ const graphB = await resolveRuntimeAgentGraph({
+ manifest,
+ moduleMap: withRootMountConfig(moduleMap, manifest, { apiKey: "sk-root-b" }),
+ });
+
+ await expect(echoInSession(graphA, undefined)).resolves.toEqual({ apiKey: "sk-root" });
+ await expect(echoInSession(graphB, undefined)).resolves.toEqual({ apiKey: "sk-root-b" });
+ });
+
+ it("gives an extension websocket callback the root mount's config", async () => {
+ const { appRoot } = await createMultiMountApp("mounted-extension-authored-source-websocket");
+ const request = new Request("http://localhost/crm/socket");
+ Object.assign(request, { ip: "127.0.0.1" });
+ const event: Pick<H3Event, "context" | "waitUntil"> & { readonly req: Request } = {
+ context: { params: {} },
+ req: request,
+ waitUntil() {},
+ };
+
+ const hooks = await dispatchChannelWebSocketRequest(
+ event as H3Event,
+ "WEBSOCKET /crm/socket",
+ createDevelopmentNitroArtifactsConfig({ configuredWorld: undefined, appRoot }),
+ );
+ const peer = { context: {} };
+
+ await hooks.open?.(peer as never);
+
+ expect(peer.context).toEqual({ apiKey: "sk-root" });
+ });
+
+ it("gives an extension channel request the root mount's config", async () => {
+ const { appRoot } = await createMultiMountApp("mounted-extension-authored-source-channel");
+ const request = new Request("http://localhost/crm/status");
+ Object.assign(request, { ip: "127.0.0.1" });
+ const event: Pick<H3Event, "context" | "waitUntil"> & { readonly req: Request } = {
+ context: { params: {} },
+ req: request,
+ waitUntil() {},
+ };
+
+ const response = await dispatchChannelRequest(
+ event as H3Event,
+ "GET /crm/status",
+ createDevelopmentNitroArtifactsConfig({ configuredWorld: undefined, appRoot }),
+ );
+
+ expect(response.status).toBe(200);
+ await expect(response.text()).resolves.toBe("sk-root");
+ });
+
+ it("gives an extension schedule run the root mount's config", async () => {
+ const { appRoot, manifest, moduleMap } = await createMultiMountApp(
+ "mounted-extension-authored-source-schedule",
+ );
+ const compiledArtifactsSource = createDiskRuntimeCompiledArtifactsSource(appRoot);
+ const schedules = await loadResolvedCompiledSchedules({ compiledArtifactsSource });
+ const sync = createScheduleRegistrations(schedules).find(
+ (registration) => registration.scheduleId === "crm__sync",
+ );
+ expect(sync).toBeDefined();
+
+ const dispatched = await dispatchScheduleTaskFromArtifacts(
+ sync!.taskName,
+ compiledArtifactsSource,
+ );
+ expect(dispatched.scheduleId).toBe("crm__sync");
+
+ const graph = await resolveRuntimeAgentGraph({ manifest, moduleMap });
+ const schedule = manifest.schedules.find((entry) => entry.name === "crm__sync");
+ expect(schedule).toBeDefined();
+ const definition = (await loadResolvedModuleExport({
+ definition: schedule!,
+ kindLabel: "schedule",
+ moduleMap,
+ nodeId: undefined,
+ })) as { run(): Promise<void> | void };
+ delete (globalThis as Record<symbol, unknown>)[Symbol.for(SCHEDULE_API_KEY_SLOT)];
+ await withExtensionConfigs(graph.root.extensionConfigs, () => definition.run());
+ expect((globalThis as Record<symbol, unknown>)[Symbol.for(SCHEDULE_API_KEY_SLOT)]).toBe(
+ "sk-root",
+ );
+ delete (globalThis as Record<symbol, unknown>)[Symbol.for(SCHEDULE_API_KEY_SLOT)];
+ });
+});
+
+/**
+ * Root and a declared subagent both mount `@acme/crm` with different keys. The
+ * subagent's mount evaluates last, so a last-bound lookup returns its key.
+ */
+async function createMultiMountApp(name: string) {
+ const app = await scenarioApp({
+ name,
+ installDependencies: true,
+ files: {
+ ...crmExtensionPackageFiles(),
+ "agent/agent.mjs": 'export default { model: "openai/gpt-5.4" };\n',
+ "agent/instructions.md": "You are a precise assistant.\n",
+ "agent/extensions/crm.mjs": [
+ 'import crm from "@acme/crm";',
+ 'export default crm({ apiKey: "sk-root" });',
+ "",
+ ].join("\n"),
+ "agent/subagents/researcher/agent.mjs": [
+ "export default {",
+ ' model: "openai/gpt-5.4",',
+ ' description: "Research a focused account set.",',
+ "};",
+ "",
+ ].join("\n"),
+ "agent/subagents/researcher/instructions.md": "You research accounts.\n",
+ "agent/subagents/researcher/extensions/crm.mjs": [
+ 'import crm from "@acme/crm";',
+ 'export default crm({ apiKey: "sk-researcher" });',
+ "",
+ ].join("\n"),
+ },
+ });
+
+ await compileAgent({ startPath: app.appRoot });
+
+ const compiledArtifactsSource = createDiskRuntimeCompiledArtifactsSource(app.appRoot);
+ const [manifest, moduleMap] = await Promise.all([
+ loadCompiledManifest({ compiledArtifactsSource }),
+ loadCompiledModuleMapFromAuthoredSource({ compiledArtifactsSource }),
+ ]);
+ return { appRoot: app.appRoot, manifest, moduleMap };
+}
+
+/**
+ * Runs the node's `crm__crm_echo` tool the way a session does: with the node's
+ * bundle in context. Per-node bundles point `graph.root` at their node; the
+ * root bundle carries no node id.
+ */
+async function echoInSession(
+ graph: ResolvedAgentGraphBundle,
+ nodeId: string | undefined,
+): Promise<unknown> {
+ const node = nodeId === undefined ? graph.root : graph.nodesByNodeId.get(nodeId);
+ const execute = node?.agent.tools.find((entry) => entry.name === "crm__crm_echo")?.execute as
+ | ((input: object, options: object) => Promise<unknown>)
+ | undefined;
+ expect(execute).toBeDefined();
+ const ctx = new ContextContainer();
+ ctx.set(BundleKey, {
+ graph: { nodesByNodeId: graph.nodesByNodeId, root: node },
+ nodeId,
+ } as CompiledBundle);
+ return await contextStorage.run(ctx, () => execute!({}, { messages: [], toolCallId: "call_1" }));
+}
+
+/** Copies `moduleMap` with the root `@acme/crm` mount bound to `config`. */
+function withRootMountConfig(
+ moduleMap: CompiledModuleMap,
+ manifest: CompiledAgentManifest,
+ config: Record<string, unknown>,
+): CompiledModuleMap {
+ const mount = manifest.extensionMounts.find((entry) => entry.namespace === "crm");
+ if (mount === undefined) throw new Error("Expected a root crm mount.");
+ const rootNode = moduleMap.nodes[ROOT_COMPILED_AGENT_NODE_ID];
+ if (rootNode === undefined) throw new Error("Expected a root module map node.");
+ const mountModule = rootNode.modules[mount.mountSourceId];
+ return {
+ ...moduleMap,
+ nodes: {
+ ...moduleMap.nodes,
+ [ROOT_COMPILED_AGENT_NODE_ID]: {
+ ...rootNode,
+ modules: {
+ ...rootNode.modules,
+ [mount.mountSourceId]: {
+ ...mountModule,
+ default: {
+ ...(mountModule?.default as object),
+ [Symbol.for("eve.mounted-extension-config")]: config,
+ },
+ },
+ },
+ },
+ },
+ };
+}
+
+function crmExtensionPackageFiles(): Record<string, string> {
+ return {
+ "node_modules/@acme/crm/package.json": `${JSON.stringify({
+ name: "@acme/crm",
+ type: "module",
+ eve: { extension: { source: "source", dist: "extension" } },
+ exports: { ".": "./extension/extension.mjs" },
+ })}\n`,
+ "node_modules/@acme/crm/extension/_manifest.json": compatibilityManifest,
+ "node_modules/@acme/crm/extension/extension.mjs": [
+ 'import { defineExtension } from "eve/extension";',
+ // Minimal pass-through Standard Schema — these scenarios test binding, not validation.
+ "const config = { '~standard': { version: 1, vendor: 'scenario', validate: (value) => ({ value }) } };",
+ "export default defineExtension({ config });",
+ "",
+ ].join("\n"),
+ "node_modules/@acme/crm/extension/channels/status.mjs": [
+ 'import { defineChannel, GET, WS } from "eve/channels";',
+ 'import extension from "../extension.mjs";',
+ // A class instance with a private method: hooks must run bound to it.
+ "class CrmSocket {",
+ " #apiKey() { return extension.config.apiKey; }",
+ " open(peer) { peer.context.apiKey = this.#apiKey(); }",
+ "}",
+ "export default defineChannel({",
+ " routes: [",
+ ' GET("/crm/status", async () => new Response(extension.config.apiKey)),',
+ ' WS("/crm/socket", async () => new CrmSocket()),',
+ " ],",
+ "});",
+ "",
+ ].join("\n"),
+ "node_modules/@acme/crm/extension/schedules/sync.mjs": [
+ 'import { defineSchedule } from "eve/schedules";',
+ 'import extension from "../extension.mjs";',
+ "export default defineSchedule({",
+ ' cron: "0 9 * * *",',
+ " run() {",
+ ` globalThis[Symbol.for(${JSON.stringify(SCHEDULE_API_KEY_SLOT)})] = extension.config.apiKey;`,
+ " },",
+ "});",
+ "",
+ ].join("\n"),
+ "node_modules/@acme/crm/extension/tools/crm_echo.mjs": [
+ 'import { defineTool } from "eve/tools";',
+ 'import extension from "../extension.mjs";',
+ "export default defineTool({",
+ ' description: "Echo the configured API key.",',
+ " inputSchema: { type: 'object', properties: {}, additionalProperties: false },",
+ " async execute() {",
+ " return { apiKey: extension.config.apiKey };",
+ " },",
+ "});",
+ "",
+ ].join("\n"),
+ };
+}
diff --git a/packages/eve/test/scenarios/mounted-extension-installed.scenario.test.ts b/packages/eve/test/scenarios/mounted-extension-installed.scenario.test.ts
index 865610711..303c54459 100644
--- a/packages/eve/test/scenarios/mounted-extension-installed.scenario.test.ts
+++ b/packages/eve/test/scenarios/mounted-extension-installed.scenario.test.ts
@@ -18,6 +18,7 @@ import {
import { createDiskRuntimeCompiledArtifactsSource } from "../../src/runtime/compiled-artifacts-source.js";
import { loadCompiledManifest } from "../../src/runtime/loaders/manifest.js";
import { resolveRuntimeAgentGraph } from "../../src/runtime/resolve-agent-graph.js";
+import { withExtensionConfigs } from "../../src/runtime/extension-mount-configs.js";
import { loadResolvedModuleExport } from "../../src/runtime/resolve-helpers.js";
// Scenario tier: building the extension package spawns tsc for declarations.
@@ -296,14 +297,18 @@ describe("mounted extension installed under node_modules", () => {
const echo = graph.root.agent.tools.find((entry) => entry.name === "crm__echo");
expect(echo).toBeDefined();
- await expect(echo?.execute?.({}, { messages: [], toolCallId: "call_1" })).resolves.toEqual({
- apiKey: "sk-installed",
- });
+ await expect(
+ withExtensionConfigs(graph.root.extensionConfigs, () =>
+ echo?.execute?.({}, { messages: [], toolCallId: "call_1" }),
+ ),
+ ).resolves.toEqual({ apiKey: "sk-installed" });
const shout = graph.root.agent.tools.find((entry) => entry.name === "crm__shout");
- await expect(shout?.execute?.({}, { messages: [], toolCallId: "call_2" })).resolves.toEqual({
- apiKey: "SK-INSTALLED",
- });
+ await expect(
+ withExtensionConfigs(graph.root.extensionConfigs, () =>
+ shout?.execute?.({}, { messages: [], toolCallId: "call_2" }),
+ ),
+ ).resolves.toEqual({ apiKey: "SK-INSTALLED" });
const status = graph.root.agent.channels.find((entry) => entry.name === "crm__status");
expect(status).toMatchObject({
@@ -312,11 +317,13 @@ describe("mounted extension installed under node_modules", () => {
urlPath: "/crm/status",
});
if (status === undefined) throw new Error("Expected the extension channel to resolve.");
- const response = await status.fetch(new Request("https://example.com/crm/status"), {
- params: {},
- requestIp: null,
- waitUntil() {},
- });
+ const response = await withExtensionConfigs(graph.root.extensionConfigs, () =>
+ status.fetch(new Request("https://example.com/crm/status"), {
+ params: {},
+ requestIp: null,
+ waitUntil() {},
+ }),
+ );
await expect(response.text()).resolves.toBe("sk-installed");
const sync = manifest.schedules.find((entry) => entry.name === "crm__sync");
@@ -335,11 +342,13 @@ describe("mounted extension installed under node_modules", () => {
run(input: { waitUntil(task: Promise<unknown>): void }): Promise<void> | void;
};
let scheduledTask: Promise<unknown> | undefined;
- await syncDefinition.run({
- waitUntil(task) {
- scheduledTask = task;
- },
- });
+ await withExtensionConfigs(graph.root.extensionConfigs, () =>
+ syncDefinition.run({
+ waitUntil(task) {
+ scheduledTask = task;
+ },
+ }),
+ );
await expect(scheduledTask).resolves.toBe("sk-installed");
const reviewer = graph.root.subagentRegistry.subagentsByName.get("crm__reviewer");
@@ -349,9 +358,11 @@ describe("mounted extension installed under node_modules", () => {
});
const reviewerNode = graph.nodesByNodeId.get(reviewer!.definition.nodeId);
const key = reviewerNode?.agent.tools.find((entry) => entry.name === "key");
- await expect(key?.execute?.({}, { messages: [], toolCallId: "call_3" })).resolves.toEqual({
- apiKey: "sk-installed",
- });
+ await expect(
+ withExtensionConfigs(reviewerNode!.extensionConfigs, () =>
+ key?.execute?.({}, { messages: [], toolCallId: "call_3" }),
+ ),
+ ).resolves.toEqual({ apiKey: "sk-installed" });
expect(
graph.root.subagentRegistry.subagentsByName.get("crm__weather")?.definition,
).toMatchObject({
@@ -365,9 +376,11 @@ describe("mounted extension installed under node_modules", () => {
const nestedReviewer = managerNode?.subagentRegistry.subagentsByName.get("nested__reviewer");
const nestedReviewerNode = graph.nodesByNodeId.get(nestedReviewer!.definition.nodeId);
const nestedKey = nestedReviewerNode?.agent.tools.find((entry) => entry.name === "key");
- await expect(nestedKey?.execute?.({}, { messages: [], toolCallId: "call_4" })).resolves.toEqual(
- { apiKey: "sk-installed" },
- );
+ await expect(
+ withExtensionConfigs(nestedReviewerNode!.extensionConfigs, () =>
+ nestedKey?.execute?.({}, { messages: [], toolCallId: "call_4" }),
+ ),
+ ).resolves.toEqual({ apiKey: "sk-installed" });
expect(graph.root.agent.skills.map((skill) => skill.name)).toEqual(
expect.arrayContaining(["crm__notes", "crm__research", "crm__guide"]),
@@ -394,10 +407,12 @@ describe("mounted extension installed under node_modules", () => {
const dynamicTools = graph.root.agent.dynamicToolResolvers.find(
(resolver) => resolver.slug === "crm__dynamic",
);
- const producedTools = (await dynamicTools?.events["session.started"]?.({}, {})) as {
- quote: { execute(input: unknown, context: unknown): Promise<unknown> };
- };
- await expect(producedTools.quote.execute({}, {})).resolves.toEqual({ apiKey: "sk-installed" });
+ const producedTools = (await withExtensionConfigs(graph.root.extensionConfigs, () =>
+ dynamicTools?.events["session.started"]?.({}, {}),
+ )) as { quote: { execute(input: unknown, context: unknown): Promise<unknown> } };
+ await expect(
+ withExtensionConfigs(graph.root.extensionConfigs, () => producedTools.quote.execute({}, {})),
+ ).resolves.toEqual({ apiKey: "sk-installed" });
const dynamicSkills = graph.root.agent.dynamicSkillResolvers.find(
(resolver) => resolver.slug === "crm__oncall",
@@ -476,14 +491,18 @@ describe("mounted extension installed under node_modules", () => {
const { graph } = await compileRuntimeGraph(app.appRoot);
const rootEcho = graph.root.agent.tools.find((entry) => entry.name === "crm__echo");
- await expect(rootEcho?.execute?.({}, { messages: [], toolCallId: "call_1" })).resolves.toEqual({
- apiKey: "sk-root",
- });
+ await expect(
+ withExtensionConfigs(graph.root.extensionConfigs, () =>
+ rootEcho?.execute?.({}, { messages: [], toolCallId: "call_1" }),
+ ),
+ ).resolves.toEqual({ apiKey: "sk-root" });
const manager = graph.root.subagentRegistry.subagentsByName.get("manager");
const managerNode = graph.nodesByNodeId.get(manager!.definition.nodeId);
const managerShout = managerNode?.agent.tools.find((entry) => entry.name === "crm__shout");
await expect(
- managerShout?.execute?.({}, { messages: [], toolCallId: "call_2" }),
+ withExtensionConfigs(managerNode!.extensionConfigs, () =>
+ managerShout?.execute?.({}, { messages: [], toolCallId: "call_2" }),
+ ),
).resolves.toEqual({ apiKey: "sk-manager" });
});
});
diff --git a/packages/eve/test/scenarios/schedule-trigger.scenario.test.ts b/packages/eve/test/scenarios/schedule-trigger.scenario.test.ts
index 908ea3a2c..4d43136d1 100644
--- a/packages/eve/test/scenarios/schedule-trigger.scenario.test.ts
+++ b/packages/eve/test/scenarios/schedule-trigger.scenario.test.ts
@@ -148,6 +148,7 @@ describe("schedule trigger end-to-end (channel-less schedules)", () => {
const dispatcher = new ScheduleDispatcher({
runtime: createCapturingRuntime(captured),
channels: bundle.graph.root.channels,
+ extensionConfigs: bundle.graph.root.extensionConfigs,
});
const dispatchInput: { scheduleId: string; markdown?: string } = {
@@ -209,6 +210,7 @@ describe("schedule trigger end-to-end (channel-less schedules)", () => {
const dispatcher = new ScheduleDispatcher({
runtime: createCapturingRuntime(captured),
channels: bundle.graph.root.channels,
+ extensionConfigs: bundle.graph.root.extensionConfigs,
});
const dispatchInput: { scheduleId: string; markdown?: string } = {
@@ -291,6 +293,7 @@ describe("schedule trigger end-to-end (channel-less schedules)", () => {
const dispatcher = new ScheduleDispatcher({
runtime: createCapturingRuntime(captured),
channels: bundle.graph.root.channels,
+ extensionConfigs: bundle.graph.root.extensionConfigs,
});
await dispatcher.trigger({