Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat(eve): sources - derive modules from selected slots (#2539)

Andrew Barbafc527969de45
diff --git a/.changeset/derived-programmatic-sources.md b/.changeset/derived-programmatic-sources.md
new file mode 100644
index 000000000..2bec1cacb
--- /dev/null
+++ b/.changeset/derived-programmatic-sources.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Allow framework features to derive ordinary source slots from other selected modules through dependency-aware programmatic templates, with consistent composition and module-map hydration.
diff --git a/packages/eve/src/cli/commands/channel-add-conflicts.ts b/packages/eve/src/cli/commands/channel-add-conflicts.ts
index 498d73883..98dd7bf56 100644
--- a/packages/eve/src/cli/commands/channel-add-conflicts.ts
+++ b/packages/eve/src/cli/commands/channel-add-conflicts.ts
@@ -4,6 +4,7 @@ import type { ChannelKind } from "#setup/scaffold/index.js";
import type { DisabledChannelReasons } from "#setup/cli/index.js";
import { compileChannelDefinition } from "#compiler/normalize-channel.js";
+import { createCompiledBindingNamespaceLoader } from "#compiler/load-binding-namespace.js";
import type { CompiledModuleBinding } from "#compiler/source-graph.js";
import { discoverAgent } from "#discover/discover-agent.js";
import { EVE_SESSION_ROUTE_PATH } from "#protocol/routes.js";
@@ -45,7 +46,10 @@ export async function inspectExistingChannelRegistrations(
};
const compiled = await compileChannelDefinition(agentRoot, source, {
binding,
- registries: [],
+ loadNamespace: createCompiledBindingNamespaceLoader({
+ bindings: { [source.sourceId]: binding },
+ registries: [],
+ }),
});
if (compiled.kind !== "channel") continue;
for (const definition of compiled.definitions) {
diff --git a/packages/eve/src/compiler/load-binding-namespace.test.ts b/packages/eve/src/compiler/load-binding-namespace.test.ts
new file mode 100644
index 000000000..a411a1002
--- /dev/null
+++ b/packages/eve/src/compiler/load-binding-namespace.test.ts
@@ -0,0 +1,97 @@
+import { describe, expect, it, vi } from "vitest";
+
+import { createCompiledBindingNamespaceLoader } from "#compiler/load-binding-namespace.js";
+import {
+ createAgentSourceRegistry,
+ defineProgrammaticAgentSource,
+ type CompiledModuleBinding,
+} from "#compiler/source-graph.js";
+
+const mocks = vi.hoisted(() => ({
+ loadAuthoredModuleNamespace: vi.fn(async () => ({ default: "dependency" })),
+}));
+
+vi.mock("#internal/authored-module-loader.js", () => ({
+ loadAuthoredModuleNamespace: mocks.loadAuthoredModuleNamespace,
+}));
+
+describe("compiled binding namespace loader", () => {
+ it("loads dependencies once and passes aliases and parameters to a template", async () => {
+ const loadTemplate = vi.fn(async (context) => ({ default: context }));
+ const template = defineProgrammaticAgentSource({
+ id: "test:template",
+ modules: [{ loadNamespace: loadTemplate, logicalPath: "tools/template.ts" }],
+ revision: "test:template:v1",
+ });
+ const registry = createAgentSourceRegistry([], { templates: [template] });
+ const bindings: Record<string, CompiledModuleBinding> = {
+ dependency: {
+ backing: {
+ externalDependencies: [],
+ kind: "filesystem",
+ sourcePath: "/virtual/dependency.ts",
+ },
+ logicalPath: "tools/dependency.ts",
+ owner: { kind: "application" },
+ },
+ derived: {
+ backing: {
+ dependencies: { source: "dependency" },
+ kind: "programmatic",
+ moduleId: "tools/template.ts",
+ parameters: { slot: "derived" },
+ registryId: template.id,
+ revision: template.revision,
+ },
+ logicalPath: "tools/derived.ts",
+ owner: { feature: "test", kind: "framework" },
+ },
+ };
+ const loadNamespace = createCompiledBindingNamespaceLoader({
+ bindings,
+ registries: [registry],
+ });
+
+ const first = await loadNamespace("derived");
+ const second = await loadNamespace("derived");
+ await loadNamespace("dependency");
+
+ expect(first).toBe(second);
+ expect(mocks.loadAuthoredModuleNamespace).toHaveBeenCalledTimes(1);
+ expect(loadTemplate).toHaveBeenCalledTimes(1);
+ expect(loadTemplate).toHaveBeenCalledWith({
+ dependencies: { source: { default: "dependency" } },
+ parameters: { slot: "derived" },
+ });
+ });
+
+ it("rejects dependency cycles before evaluating a template", async () => {
+ const loadTemplate = vi.fn(async () => ({}));
+ const template = defineProgrammaticAgentSource({
+ id: "test:cyclic-template",
+ modules: [{ loadNamespace: loadTemplate, logicalPath: "tools/template.ts" }],
+ revision: "test:cyclic-template:v1",
+ });
+ const registry = createAgentSourceRegistry([], { templates: [template] });
+ const programmatic = (dependency: string): CompiledModuleBinding => ({
+ backing: {
+ dependencies: { source: dependency },
+ kind: "programmatic",
+ moduleId: "tools/template.ts",
+ registryId: template.id,
+ revision: template.revision,
+ },
+ logicalPath: `tools/${dependency}.ts`,
+ owner: { feature: "test", kind: "framework" },
+ });
+ const loadNamespace = createCompiledBindingNamespaceLoader({
+ bindings: { first: programmatic("second"), second: programmatic("first") },
+ registries: [registry],
+ });
+
+ await expect(loadNamespace("first")).rejects.toThrow(
+ 'Compiled binding dependency cycle includes "first".',
+ );
+ expect(loadTemplate).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/eve/src/compiler/load-binding-namespace.ts b/packages/eve/src/compiler/load-binding-namespace.ts
new file mode 100644
index 000000000..116c1c530
--- /dev/null
+++ b/packages/eve/src/compiler/load-binding-namespace.ts
@@ -0,0 +1,79 @@
+import {
+ type AgentSourceRegistry,
+ type CompiledModuleBinding,
+ loadProgrammaticModuleNamespace,
+ type ProgrammaticModuleNamespace,
+} from "#compiler/source-graph.js";
+import { packageStateNamespace } from "#discover/extensions.js";
+import { loadAuthoredModuleNamespace } from "#internal/authored-module-loader.js";
+
+export type CompiledBindingNamespaceLoader = (
+ sourceId: string,
+) => Promise<ProgrammaticModuleNamespace>;
+
+/** Loads one node's selected bindings with dependency ordering and per-phase caching. */
+export function createCompiledBindingNamespaceLoader(input: {
+ readonly bindings: Readonly<Record<string, CompiledModuleBinding>>;
+ readonly registries: readonly AgentSourceRegistry[];
+}): CompiledBindingNamespaceLoader {
+ const cache = new Map<string, Promise<ProgrammaticModuleNamespace>>();
+
+ const load = (
+ sourceId: string,
+ lineage: ReadonlySet<string> = new Set(),
+ ): Promise<ProgrammaticModuleNamespace> => {
+ if (lineage.has(sourceId)) {
+ throw new Error(`Compiled binding dependency cycle includes "${sourceId}".`);
+ }
+ const cached = cache.get(sourceId);
+ if (cached !== undefined) return cached;
+ const binding = input.bindings[sourceId];
+ if (binding === undefined) {
+ throw new Error(`Compiled binding dependency "${sourceId}" is missing.`);
+ }
+ const nextLineage = new Set(lineage).add(sourceId);
+ const loading = loadCompiledBindingNamespace({
+ binding,
+ loadDependency: (dependencySourceId) => load(dependencySourceId, nextLineage),
+ registries: input.registries,
+ });
+ cache.set(sourceId, loading);
+ return loading;
+ };
+
+ return load;
+}
+
+async function loadCompiledBindingNamespace(input: {
+ readonly binding: CompiledModuleBinding;
+ readonly loadDependency: CompiledBindingNamespaceLoader;
+ readonly registries: readonly AgentSourceRegistry[];
+}): Promise<ProgrammaticModuleNamespace> {
+ if (input.binding.backing.kind === "filesystem") {
+ return await loadAuthoredModuleNamespace(input.binding.backing.sourcePath, {
+ externalDependencies: input.binding.backing.externalDependencies,
+ extensionScopeNamespace: resolveCompiledModuleExtensionScopeNamespace(input.binding),
+ });
+ }
+ const dependencyNamespaces = Object.fromEntries(
+ await Promise.all(
+ Object.entries(input.binding.backing.dependencies ?? {}).map(
+ async ([alias, sourceId]) => [alias, await input.loadDependency(sourceId)] as const,
+ ),
+ ),
+ );
+ return await loadProgrammaticModuleNamespace({
+ backing: input.binding.backing,
+ dependencyNamespaces,
+ registries: input.registries,
+ });
+}
+
+/** Derives the stable package-owned scope used while loading an extension module. */
+export function resolveCompiledModuleExtensionScopeNamespace(
+ binding: CompiledModuleBinding,
+): string | undefined {
+ return binding.owner.kind === "extension"
+ ? packageStateNamespace(binding.owner.packageName)
+ : undefined;
+}
diff --git a/packages/eve/src/compiler/manifest.test.ts b/packages/eve/src/compiler/manifest.test.ts
index 6f566db51..9dc710c81 100644
--- a/packages/eve/src/compiler/manifest.test.ts
+++ b/packages/eve/src/compiler/manifest.test.ts
@@ -11,7 +11,7 @@ import {
validateCompiledModuleMap,
} from "#compiler/validate-artifact.js";
-describe("compiled agent manifest v42", () => {
+describe("compiled agent manifest v43", () => {
it("round-trips a real compiled graph through the serialized schema", async () => {
const { manifest } = await compileFromMemory({
model: "openai/gpt-5.4",
@@ -58,6 +58,7 @@ describe("compiled agent manifest v42", () => {
method: "GET",
source: {
backing: { kind: "resource", sourcePath: "/virtual/channels/loser.ts" },
+ form: "direct",
layer: "application",
logicalPath: "channels/loser.ts",
owner: { kind: "application" },
diff --git a/packages/eve/src/compiler/manifest.ts b/packages/eve/src/compiler/manifest.ts
index 0d4be076e..ae7c471f9 100644
--- a/packages/eve/src/compiler/manifest.ts
+++ b/packages/eve/src/compiler/manifest.ts
@@ -54,7 +54,7 @@ export const ROOT_COMPILED_AGENT_NODE_ID = "__root__";
/**
* Current compiled manifest schema version.
*/
-export const COMPILED_AGENT_MANIFEST_VERSION = 42;
+export const COMPILED_AGENT_MANIFEST_VERSION = 43;
/**
* Compiled channel entry preserved in the compiled manifest.
@@ -365,8 +365,10 @@ const filesystemModuleBackingSchema = z
const programmaticModuleBackingSchema = z
.object({
+ dependencies: z.record(z.string(), z.string()).readonly().optional(),
kind: z.literal("programmatic"),
moduleId: z.string(),
+ parameters: jsonObjectSchema.optional(),
registryId: z.string(),
revision: z.string(),
semanticRevision: z.string().optional(),
@@ -397,6 +399,7 @@ const agentSourceDescriptorSchema: z.ZodType<AgentSourceDescriptor> = z
programmaticModuleBackingSchema,
resourceSourceBackingSchema,
]),
+ form: z.enum(["derived", "direct"]),
layer: z.enum(["framework-default", "extension-package", "extension-override", "application"]),
logicalPath: z.string(),
owner: agentSourceOwnerSchema,
diff --git a/packages/eve/src/compiler/module-map.test.ts b/packages/eve/src/compiler/module-map.test.ts
index f47b1fe89..6cd0eaea7 100644
--- a/packages/eve/src/compiler/module-map.test.ts
+++ b/packages/eve/src/compiler/module-map.test.ts
@@ -6,6 +6,7 @@ import {
createCompiledModuleMapSource,
createProgrammaticCompiledModuleMap,
} from "#compiler/module-map.js";
+import { validateCompiledAgentManifest } from "#compiler/validate-artifact.js";
const mocks = vi.hoisted(() => ({
loadAuthoredModuleNamespace: vi.fn(
@@ -110,4 +111,60 @@ describe("compiled module maps", () => {
.every(([, options]) => options.extensionScopeNamespace === undefined),
).toBe(true);
});
+
+ it("orders and renders programmatic dependencies in generated maps", async () => {
+ const { manifest } = await compileFromMemory({
+ model: "openai/gpt-5.4",
+ tools: [{ name: "weather" }],
+ });
+ const tool = manifest.tools.find((candidate) => candidate.name === "weather")!;
+ const configSourceId = manifest.config.source.sourceId;
+ const binding = manifest.bindings[tool.sourceId]!;
+ if (binding.backing.kind !== "programmatic") {
+ throw new Error("Expected a programmatic tool binding.");
+ }
+ manifest.bindings[tool.sourceId] = {
+ ...binding,
+ backing: {
+ ...binding.backing,
+ dependencies: { config: configSourceId },
+ parameters: { role: "derived" },
+ },
+ };
+
+ const ordered = collectModuleBindingsForManifest(manifest).map((entry) => entry.sourceId);
+ const source = createCompiledModuleMapSource({
+ manifest,
+ moduleMapPath: "/app/.eve/compile/module-map.mjs",
+ });
+
+ expect(ordered.indexOf(configSourceId)).toBeLessThan(ordered.indexOf(tool.sourceId));
+ expect(source).toContain('"parameters":{"role":"derived"}');
+ expect(source).toMatch(/Object\.freeze\(\{ "config": module_\d+ \}\)/);
+ });
+
+ it("rejects missing and cyclic programmatic binding dependencies", async () => {
+ const { manifest } = await compileFromMemory({ model: "openai/gpt-5.4" });
+ const sourceId = manifest.config.source.sourceId;
+ const binding = manifest.bindings[sourceId]!;
+ if (binding.backing.kind !== "programmatic") {
+ throw new Error("Expected a programmatic config binding.");
+ }
+
+ manifest.bindings[sourceId] = {
+ ...binding,
+ backing: { ...binding.backing, dependencies: { missing: "missing-source" } },
+ };
+ expect(() => validateCompiledAgentManifest(manifest)).toThrow(
+ `programmatic binding "${sourceId}" depends on missing binding "missing-source"`,
+ );
+
+ manifest.bindings[sourceId] = {
+ ...binding,
+ backing: { ...binding.backing, dependencies: { self: sourceId } },
+ };
+ expect(() => validateCompiledAgentManifest(manifest)).toThrow(
+ `programmatic binding dependency cycle includes "${sourceId}"`,
+ );
+ });
});
diff --git a/packages/eve/src/compiler/module-map.ts b/packages/eve/src/compiler/module-map.ts
index 5929cf224..c0a397615 100644
--- a/packages/eve/src/compiler/module-map.ts
+++ b/packages/eve/src/compiler/module-map.ts
@@ -5,15 +5,15 @@ import type {
CompiledAgentResources,
} from "#compiler/manifest.js";
import { ROOT_COMPILED_AGENT_NODE_ID } from "#compiler/manifest.js";
-import { packageStateNamespace } from "#discover/extensions.js";
import {
- loadProgrammaticModuleNamespace,
type AgentSourceRegistry,
type CompiledModuleBinding,
type ProgrammaticModuleNamespace,
} from "#compiler/source-graph.js";
+import { createCompiledBindingNamespaceLoader } from "#compiler/load-binding-namespace.js";
import { normalizeEsmImportSpecifier } from "#internal/application/import-specifier.js";
-import { loadAuthoredModuleNamespace } from "#internal/authored-module-loader.js";
+
+export { resolveCompiledModuleExtensionScopeNamespace } from "#compiler/load-binding-namespace.js";
export type CompiledModuleNodeScope = z.infer<typeof compiledModuleNodeScopeSchema>;
export type CompiledModuleMap = z.infer<typeof compiledModuleMapSchema>;
@@ -61,29 +61,34 @@ export function createCompiledModuleMapSource(input: CreateCompiledModuleMapSour
const importSpecifierStyle = input.importSpecifierStyle ?? "relative";
let index = 0;
let usesProgrammaticLoader = false;
- const scopes: RenderedNodeScope[] = collectBoundNodeScopes(input.manifest).map((scope) => ({
- modules: scope.modules.map(({ binding, sourceId }) => {
- const bindingName = `module_${index++}`;
- if (binding.backing.kind === "filesystem") {
+ const scopes: RenderedNodeScope[] = collectBoundNodeScopes(input.manifest).map((scope) => {
+ const bindingNames = new Map(
+ scope.modules.map((module) => [module.sourceId, `module_${index++}`] as const),
+ );
+ return {
+ modules: scope.modules.map(({ binding, sourceId }) => {
+ const bindingName = bindingNames.get(sourceId)!;
+ if (binding.backing.kind === "filesystem") {
+ return {
+ bindingName,
+ importSpecifier: createImportSpecifier({
+ fromDirectory: moduleMapDirectory,
+ importSpecifierStyle,
+ targetPath: binding.backing.sourcePath,
+ }),
+ sourceId,
+ };
+ }
+ usesProgrammaticLoader = true;
return {
bindingName,
- importSpecifier: createImportSpecifier({
- fromDirectory: moduleMapDirectory,
- importSpecifierStyle,
- targetPath: binding.backing.sourcePath,
- }),
+ initializer: `await loadProgrammaticModule(${JSON.stringify(binding.backing)}, ${renderProgrammaticDependencies(binding.backing.dependencies, bindingNames)})`,
sourceId,
};
- }
- usesProgrammaticLoader = true;
- return {
- bindingName,
- initializer: `await loadProgrammaticModule(${JSON.stringify(binding.backing)})`,
- sourceId,
- };
- }),
- nodeId: scope.nodeId,
- }));
+ }),
+ nodeId: scope.nodeId,
+ };
+ });
const modules = scopes.flatMap((scope) => scope.modules);
const imports = modules.flatMap((module) =>
module.importSpecifier === undefined
@@ -122,29 +127,18 @@ export async function createProgrammaticCompiledModuleMap(
const nodes: CompiledModuleMap["nodes"] = {};
for (const scope of collectBoundNodeScopes(manifest)) {
const modules: Record<string, ProgrammaticModuleNamespace> = {};
- for (const { binding, sourceId } of scope.modules) {
- modules[sourceId] =
- binding.backing.kind === "filesystem"
- ? await loadAuthoredModuleNamespace(binding.backing.sourcePath, {
- externalDependencies: binding.backing.externalDependencies,
- extensionScopeNamespace: resolveCompiledModuleExtensionScopeNamespace(binding),
- })
- : await loadProgrammaticModuleNamespace({ backing: binding.backing, registries });
+ const bindings = Object.fromEntries(
+ scope.modules.map(({ binding, sourceId }) => [sourceId, binding]),
+ );
+ const loadNamespace = createCompiledBindingNamespaceLoader({ bindings, registries });
+ for (const { sourceId } of scope.modules) {
+ modules[sourceId] = await loadNamespace(sourceId);
}
nodes[scope.nodeId] = { modules };
}
return { nodes };
}
-/** Derives the stable package-owned scope used while loading an extension module. */
-export function resolveCompiledModuleExtensionScopeNamespace(
- binding: CompiledModuleBinding,
-): string | undefined {
- return binding.owner.kind === "extension"
- ? packageStateNamespace(binding.owner.packageName)
- : undefined;
-}
-
/** Returns every binding owned by one compiled node, including remote config modules. */
export function collectModuleBindingsForManifest(
manifest: CompiledAgentNodeManifest | CompiledAgentResources,
@@ -156,9 +150,52 @@ export function collectModuleBindingsForManifest(
}
modules.set(remote.sourceId, remote.binding);
}
- return [...modules]
- .sort(([left], [right]) => left.localeCompare(right))
- .map(([sourceId, binding]) => ({ binding, sourceId }));
+ return orderBoundModules(
+ [...modules]
+ .sort(([left], [right]) => left.localeCompare(right))
+ .map(([sourceId, binding]) => ({ binding, sourceId })),
+ );
+}
+
+function orderBoundModules(modules: readonly BoundModule[]): readonly BoundModule[] {
+ const bySourceId = new Map(modules.map((module) => [module.sourceId, module]));
+ const ordered: BoundModule[] = [];
+ const visiting = new Set<string>();
+ const visited = new Set<string>();
+ const visit = (module: BoundModule): void => {
+ if (visited.has(module.sourceId)) return;
+ if (visiting.has(module.sourceId)) {
+ throw new Error(`Compiled module dependency cycle includes "${module.sourceId}".`);
+ }
+ visiting.add(module.sourceId);
+ if (module.binding.backing.kind === "programmatic") {
+ for (const dependencySourceId of Object.values(module.binding.backing.dependencies ?? {})) {
+ const dependency = bySourceId.get(dependencySourceId);
+ if (dependency === undefined) {
+ throw new Error(
+ `Programmatic binding "${module.sourceId}" depends on missing binding "${dependencySourceId}".`,
+ );
+ }
+ visit(dependency);
+ }
+ }
+ visiting.delete(module.sourceId);
+ visited.add(module.sourceId);
+ ordered.push(module);
+ };
+ for (const module of modules) visit(module);
+ return ordered;
+}
+
+function renderProgrammaticDependencies(
+ dependencies: Readonly<Record<string, string>> | undefined,
+ bindingNames: ReadonlyMap<string, string>,
+): string {
+ const entries = Object.entries(dependencies ?? {});
+ if (entries.length === 0) return "Object.freeze({})";
+ return `Object.freeze({ ${entries
+ .map(([alias, sourceId]) => `${JSON.stringify(alias)}: ${bindingNames.get(sourceId)!}`)
+ .join(", ")} })`;
}
function collectBoundNodeScopes(manifest: CompiledAgentManifest): readonly BoundNodeScope[] {
diff --git a/packages/eve/src/compiler/normalize-agent-config.ts b/packages/eve/src/compiler/normalize-agent-config.ts
index df496ccb4..dfe44f4f4 100644
--- a/packages/eve/src/compiler/normalize-agent-config.ts
+++ b/packages/eve/src/compiler/normalize-agent-config.ts
@@ -22,6 +22,7 @@ import {
type ManifestCompileContext,
} from "#compiler/normalize-helpers.js";
import type { CompiledModuleBinding } from "#compiler/source-graph.js";
+import { createCompiledBindingNamespaceLoader } from "#compiler/load-binding-namespace.js";
type Mutable<T> = { -readonly [K in keyof T]: T[K] };
@@ -47,7 +48,10 @@ export async function compileAgentConfig(
binding: options.binding,
displayPath: configModulePath,
kind: "agent config",
- registries: context.registries,
+ loadNamespace: createCompiledBindingNamespaceLoader({
+ bindings: { [configModule.sourceId]: options.binding },
+ registries: context.registries,
+ }),
source: configModule,
}),
`Expected the agent config export "${configModule.exportName ?? "default"}" from "${configModulePath}" to match the public eve shape.`,
diff --git a/packages/eve/src/compiler/normalize-channel.ts b/packages/eve/src/compiler/normalize-channel.ts
index ce9296cd2..ce00a9277 100644
--- a/packages/eve/src/compiler/normalize-channel.ts
+++ b/packages/eve/src/compiler/normalize-channel.ts
@@ -32,7 +32,7 @@ export async function compileChannelDefinition(
const rawValue = await loadModuleBackedDefinition({
binding: options.binding,
kind: "channel",
- registries: options.registries,
+ loadNamespace: options.loadNamespace,
source,
});
diff --git a/packages/eve/src/compiler/normalize-connection.ts b/packages/eve/src/compiler/normalize-connection.ts
index efc3bf6a0..7bd87d2c5 100644
--- a/packages/eve/src/compiler/normalize-connection.ts
+++ b/packages/eve/src/compiler/normalize-connection.ts
@@ -36,7 +36,7 @@ export async function compileConnectionDefinition(
const loaded = await loadModuleBackedDefinition({
binding: options.binding,
kind: "connection",
- registries: options.registries,
+ loadNamespace: options.loadNamespace,
source,
});
const protocol = readConnectionProtocol(loaded);
diff --git a/packages/eve/src/compiler/normalize-helpers.ts b/packages/eve/src/compiler/normalize-helpers.ts
index bf3178d39..13b357f1c 100644
--- a/packages/eve/src/compiler/normalize-helpers.ts
+++ b/packages/eve/src/compiler/normalize-helpers.ts
@@ -2,16 +2,15 @@ import {
getAuthoredModuleExport,
materializeAuthoredModuleExport,
} from "#internal/authored-module.js";
-import { loadAuthoredModuleNamespace } from "#internal/authored-module-loader.js";
import { toErrorMessage } from "#shared/errors.js";
import type { ModuleSourceRef } from "#shared/source-ref.js";
import type { CompiledRuntimeModelCatalogLoader } from "#compiler/model-catalog.js";
import {
- loadProgrammaticModuleNamespace,
type AgentSourceRegistry,
type CompiledModuleBinding,
type AgentSourceOwner,
} from "#compiler/source-graph.js";
+import type { CompiledBindingNamespaceLoader } from "#compiler/load-binding-namespace.js";
const SANDBOX_PARENT_DEFINITION_MARKER = Symbol.for("eve.sandbox-parent-definition");
@@ -30,23 +29,23 @@ export interface ManifestCompileContext {
export interface ModuleBackedDefinitionLoadOptions {
readonly binding: CompiledModuleBinding;
- readonly registries: readonly AgentSourceRegistry[];
+ readonly loadNamespace: CompiledBindingNamespaceLoader;
}
export interface SourceDefinitionCompileOptions {
readonly binding?: CompiledModuleBinding;
+ readonly loadNamespace?: CompiledBindingNamespaceLoader;
readonly owner: AgentSourceOwner;
- readonly registries?: readonly AgentSourceRegistry[];
}
export function requireModuleBackedDefinitionLoadOptions(
options: SourceDefinitionCompileOptions,
logicalPath: string,
): ModuleBackedDefinitionLoadOptions {
- if (options.binding === undefined || options.registries === undefined) {
+ if (options.binding === undefined || options.loadNamespace === undefined) {
throw new Error(`Module-backed source "${logicalPath}" requires a compiled binding.`);
}
- return { binding: options.binding, registries: options.registries };
+ return { binding: options.binding, loadNamespace: options.loadNamespace };
}
/**
@@ -62,7 +61,7 @@ export async function loadModuleBackedDefinition(input: {
readonly binding: CompiledModuleBinding;
readonly displayPath?: string;
readonly kind: string;
- readonly registries: readonly AgentSourceRegistry[];
+ readonly loadNamespace: CompiledBindingNamespaceLoader;
readonly source: ModuleSourceRef;
}): Promise<unknown> {
if (input.binding.logicalPath !== input.source.logicalPath) {
@@ -70,15 +69,7 @@ export async function loadModuleBackedDefinition(input: {
`Compiled binding "${input.source.sourceId}" targets "${input.binding.logicalPath}", not "${input.source.logicalPath}".`,
);
}
- const moduleNamespace =
- input.binding.backing.kind === "filesystem"
- ? await loadAuthoredModuleNamespace(input.binding.backing.sourcePath, {
- externalDependencies: input.binding.backing.externalDependencies,
- })
- : await loadProgrammaticModuleNamespace({
- backing: input.binding.backing,
- registries: input.registries,
- });
+ const moduleNamespace = await input.loadNamespace(input.source.sourceId);
const exportValue = getAuthoredModuleExport(moduleNamespace, input.source);
// defineSandbox marks parent selectors so they remain distinguishable from
diff --git a/packages/eve/src/compiler/normalize-hook.ts b/packages/eve/src/compiler/normalize-hook.ts
index 00b9c95a6..07bb80fe8 100644
--- a/packages/eve/src/compiler/normalize-hook.ts
+++ b/packages/eve/src/compiler/normalize-hook.ts
@@ -16,7 +16,7 @@ export async function compileHookEntry(
await loadModuleBackedDefinition({
binding: options.binding,
kind: "hook",
- registries: options.registries,
+ loadNamespace: options.loadNamespace,
source,
}),
`Expected the hook export "${source.exportName ?? "default"}" from "${source.logicalPath}" to return an object.`,
diff --git a/packages/eve/src/compiler/normalize-instructions.ts b/packages/eve/src/compiler/normalize-instructions.ts
index d528e72ec..6a14ab598 100644
--- a/packages/eve/src/compiler/normalize-instructions.ts
+++ b/packages/eve/src/compiler/normalize-instructions.ts
@@ -72,7 +72,7 @@ export async function compileInstructionsEntry(
const exportValue = await loadModuleBackedDefinition({
binding: loadOptions.binding,
kind: "instructions",
- registries: loadOptions.registries,
+ loadNamespace: loadOptions.loadNamespace,
source,
});
diff --git a/packages/eve/src/compiler/normalize-manifest.ts b/packages/eve/src/compiler/normalize-manifest.ts
index 9bcadb785..55609aa62 100644
--- a/packages/eve/src/compiler/normalize-manifest.ts
+++ b/packages/eve/src/compiler/normalize-manifest.ts
@@ -27,6 +27,7 @@ import {
ROOT_COMPILED_AGENT_NODE_ID,
} from "#compiler/manifest.js";
import { createCompiledRuntimeModelCatalogLoader } from "#compiler/model-catalog.js";
+import { createCompiledBindingNamespaceLoader } from "#compiler/load-binding-namespace.js";
import { compileAgentConfig } from "#compiler/normalize-agent-config.js";
import { compileChannelDefinition } from "#compiler/normalize-channel.js";
import { compileConnectionDefinition } from "#compiler/normalize-connection.js";
@@ -408,13 +409,17 @@ class AgentGraphCompiler {
throw new Error(`Selected agent config source "${candidate.sourceId}" was not projected.`);
}
const source = projected.source;
+ const loadNamespace = createCompiledBindingNamespaceLoader({
+ bindings: { [candidate.sourceId]: binding },
+ registries: this.registries,
+ });
return {
binding,
candidate,
definition: await loadModuleBackedDefinition({
binding,
kind: "agent config",
- registries: this.registries,
+ loadNamespace,
source,
}),
source,
@@ -440,6 +445,10 @@ class AgentGraphCompiler {
let workflowTool: CompiledWorkflowToolDefinition | undefined;
let webSearchProvider: WebSearchProvider | undefined;
const selectedSourceIds = collectSelectedSourceIds(state.composed);
+ const loadNamespace = createCompiledBindingNamespaceLoader({
+ bindings: state.bindings,
+ registries: this.registries,
+ });
for (const candidate of state.orderedCandidates) {
if (!selectedSourceIds.has(candidate.sourceId)) continue;
@@ -448,8 +457,8 @@ class AgentGraphCompiler {
const binding = state.bindings[candidate.sourceId];
const options = {
binding,
+ loadNamespace,
owner: candidate.owner,
- registries: this.registries,
};
switch (entry.kind) {
case "config":
@@ -458,7 +467,7 @@ class AgentGraphCompiler {
case "channel": {
const result = await compileChannelDefinition(input.manifest.agentRoot, entry.source, {
binding: binding!,
- registries: this.registries,
+ loadNamespace,
});
if (result.kind === "disabled") {
state.composed = disableComposedCandidate({ candidate, composed: state.composed });
@@ -471,7 +480,7 @@ class AgentGraphCompiler {
connections.push(
await compileConnectionDefinition(input.manifest.agentRoot, entry.source, {
binding: binding!,
- registries: this.registries,
+ loadNamespace,
}),
);
break;
@@ -479,7 +488,7 @@ class AgentGraphCompiler {
hooks.push(
await compileHookEntry(entry.source, {
binding: binding!,
- registries: this.registries,
+ loadNamespace,
}),
);
break;
@@ -499,7 +508,7 @@ class AgentGraphCompiler {
case "sandbox":
sandbox = await compileSandboxDefinition(input.manifest.agentRoot, entry.source, {
binding: binding!,
- registries: this.registries,
+ loadNamespace,
});
break;
case "schedule":
@@ -516,7 +525,7 @@ class AgentGraphCompiler {
case "tool": {
const result = await compileToolEntry(input.manifest.agentRoot, entry.source, {
binding: binding!,
- registries: this.registries,
+ loadNamespace,
});
if (result.kind === "disabled") {
state.composed = disableComposedCandidate({ candidate, composed: state.composed });
diff --git a/packages/eve/src/compiler/normalize-sandbox.ts b/packages/eve/src/compiler/normalize-sandbox.ts
index 5f3737153..a06fae222 100644
--- a/packages/eve/src/compiler/normalize-sandbox.ts
+++ b/packages/eve/src/compiler/normalize-sandbox.ts
@@ -23,7 +23,7 @@ export async function compileSandboxDefinition(
const loaded = await loadModuleBackedDefinition({
binding: options.binding,
kind: "sandbox",
- registries: options.registries,
+ loadNamespace: options.loadNamespace,
source,
});
const inheritsParent = await resolveParentSandboxSelector(loaded, message);
diff --git a/packages/eve/src/compiler/normalize-schedule.ts b/packages/eve/src/compiler/normalize-schedule.ts
index 79b1cc9fb..177809ca3 100644
--- a/packages/eve/src/compiler/normalize-schedule.ts
+++ b/packages/eve/src/compiler/normalize-schedule.ts
@@ -33,10 +33,8 @@ export async function compileScheduleDefinition(
)
: normalizeScheduleDefinition(
await loadModuleBackedDefinition({
- binding: requireModuleBackedDefinitionLoadOptions(options, source.logicalPath).binding,
+ ...requireModuleBackedDefinitionLoadOptions(options, source.logicalPath),
kind: "schedule",
- registries: requireModuleBackedDefinitionLoadOptions(options, source.logicalPath)
- .registries,
source,
}),
`Expected the schedule export "${source.exportName ?? "default"}" from "${source.logicalPath}" to match the public eve shape.`,
diff --git a/packages/eve/src/compiler/normalize-skill.ts b/packages/eve/src/compiler/normalize-skill.ts
index 19cdfce99..967dfec8b 100644
--- a/packages/eve/src/compiler/normalize-skill.ts
+++ b/packages/eve/src/compiler/normalize-skill.ts
@@ -74,7 +74,7 @@ export async function compileSkillSource(
const exportValue = await loadModuleBackedDefinition({
binding: loadOptions.binding,
kind: "skill",
- registries: loadOptions.registries,
+ loadNamespace: loadOptions.loadNamespace,
source,
});
diff --git a/packages/eve/src/compiler/normalize-tool.ts b/packages/eve/src/compiler/normalize-tool.ts
index ee7f78507..df6bb3f9e 100644
--- a/packages/eve/src/compiler/normalize-tool.ts
+++ b/packages/eve/src/compiler/normalize-tool.ts
@@ -46,7 +46,7 @@ export async function compileToolEntry(
await loadModuleBackedDefinition({
binding: options.binding,
kind: "tool",
- registries: options.registries,
+ loadNamespace: options.loadNamespace,
source,
}),
`Expected the tool export "${source.exportName ?? "default"}" from "${source.logicalPath}" to match the public eve shape.`,
diff --git a/packages/eve/src/compiler/project-sources.ts b/packages/eve/src/compiler/project-sources.ts
index 4f7b11076..876ff1c99 100644
--- a/packages/eve/src/compiler/project-sources.ts
+++ b/packages/eve/src/compiler/project-sources.ts
@@ -204,6 +204,7 @@ export function createFilesystemModuleCandidate(input: {
return {
backing,
exportName: input.source.exportName,
+ form: "direct",
layer: input.layer,
logicalPath: input.logicalPath,
nodeId: input.nodeId,
@@ -272,6 +273,7 @@ function projectManifest(input: {
? source.skillFilePath
: join(input.manifest.agentRoot, source.logicalPath),
},
+ form: "direct",
layer: input.layer,
logicalPath,
nodeId: input.nodeId,
@@ -333,6 +335,7 @@ function projectManifest(input: {
};
const candidate: AgentResourceCandidate = {
backing: { kind: "resource", sourcePath: source.entryPath },
+ form: "direct",
layer: input.layer,
logicalPath,
nodeId: input.nodeId,
diff --git a/packages/eve/src/compiler/source-graph.test.ts b/packages/eve/src/compiler/source-graph.test.ts
new file mode 100644
index 000000000..e35de4870
--- /dev/null
+++ b/packages/eve/src/compiler/source-graph.test.ts
@@ -0,0 +1,246 @@
+import { describe, expect, it, vi } from "vitest";
+
+import {
+ composeAgentModuleCandidates,
+ createAgentSourceRegistry,
+ createProgrammaticModuleCandidates,
+ defineProgrammaticAgentSource,
+ instantiateProgrammaticTemplate,
+ loadProgrammaticModuleNamespace,
+ type AgentModuleBacking,
+ type AgentModuleCandidate,
+ type AgentSourceLayer,
+ type AgentSourceOwner,
+ type AgentSourceRegistration,
+ type ProgrammaticAgentModule,
+ type ProgrammaticAgentSource,
+ type ProgrammaticModuleLoadContext,
+} from "#compiler/source-graph.js";
+
+function source(
+ id: string,
+ logicalPath: string,
+ loadNamespace: ProgrammaticAgentModule["loadNamespace"] = async () => ({}),
+): ProgrammaticAgentSource {
+ return defineProgrammaticAgentSource({
+ id,
+ modules: [{ loadNamespace, logicalPath }],
+ revision: `${id}:v1`,
+ });
+}
+
+function candidate(
+ registration: AgentSourceRegistration,
+ layer: AgentSourceLayer,
+ owner: AgentSourceOwner = { kind: "application" },
+) {
+ return createProgrammaticModuleCandidates({
+ layer,
+ nodeId: "node",
+ owner,
+ registration,
+ })[0]!;
+}
+
+describe("derived programmatic sources", () => {
+ it("loads registered templates with selected dependencies and serialized parameters", async () => {
+ const dependencyNamespace = { default: { description: "GitHub connection" } };
+ const loadTemplate = vi.fn(async (context: ProgrammaticModuleLoadContext) => ({
+ default: context,
+ }));
+ const dependencySource = source(
+ "test:connection",
+ "connections/github.ts",
+ async () => dependencyNamespace,
+ );
+ const templateSource = source(
+ "test:connection-tool-template",
+ "tools/connection-tool-template.ts",
+ loadTemplate,
+ );
+ const registry = createAgentSourceRegistry([{ applyTo: "root", source: dependencySource }], {
+ templates: [templateSource],
+ });
+ const [dependencyRegistration] = registry.registrations;
+ const registeredTemplate = registry.templates.get(templateSource.id);
+ if (dependencyRegistration === undefined || registeredTemplate === undefined) {
+ throw new Error("Expected registered source and template.");
+ }
+ const dependency = candidate(dependencyRegistration, "application");
+ const derived = instantiateProgrammaticTemplate({
+ anchor: dependency,
+ dependencies: { connection: dependency },
+ logicalPath: "tools/github.ts",
+ owner: { feature: "connection-tools", kind: "framework" },
+ parameters: { connection: "github" },
+ template: registeredTemplate,
+ });
+
+ expect(registry.registrations).toHaveLength(1);
+ expect(registry.templates.has(templateSource.id)).toBe(true);
+ expect(derived).toMatchObject({
+ form: "derived",
+ layer: "application",
+ nodeId: "node",
+ sourceId:
+ "test:connection-tool-template:tools/github.ts:from:test:connection:connections/github.ts",
+ });
+ expect(composeAgentModuleCandidates([dependency, derived]).selected.get("tools/github")).toBe(
+ derived,
+ );
+
+ const namespace = await loadProgrammaticModuleNamespace({
+ backing: derived.backing as Extract<AgentModuleBacking, { kind: "programmatic" }>,
+ dependencyNamespaces: { connection: dependencyNamespace },
+ registries: [registry],
+ });
+ expect(namespace.default).toMatchObject({ parameters: { connection: "github" } });
+ expect(loadTemplate).toHaveBeenCalledWith({
+ dependencies: { connection: dependencyNamespace },
+ parameters: { connection: "github" },
+ });
+ });
+
+ it("inherits its anchor layer and yields to a direct target in that layer", () => {
+ const templateSource = source(
+ "test:connection-tool-template",
+ "tools/connection-tool-template.ts",
+ );
+ const registry = createAgentSourceRegistry([], { templates: [templateSource] });
+ const template = registry.templates.get(templateSource.id)!;
+ const extensionOwner = {
+ kind: "extension" as const,
+ namespace: "github",
+ packageName: "@acme/github",
+ };
+ const extensionConnection = candidate(
+ { applyTo: "root", source: source("test:extension-connection", "connections/github.ts") },
+ "extension-package",
+ extensionOwner,
+ );
+ const applicationConnection = candidate(
+ { applyTo: "root", source: source("test:application-connection", "connections/github.ts") },
+ "application",
+ );
+ const directApplicationTool = candidate(
+ { applyTo: "root", source: source("test:direct-tool", "tools/github.ts") },
+ "application",
+ );
+ const derive = (anchor: AgentModuleCandidate) =>
+ instantiateProgrammaticTemplate({
+ anchor,
+ dependencies: { connection: anchor },
+ logicalPath: "tools/github.ts",
+ owner: { feature: "connection-tools", kind: "framework" },
+ template,
+ });
+ const extensionDerived = derive(extensionConnection);
+ const applicationDerived = derive(applicationConnection);
+
+ expect(extensionDerived.layer).toBe("extension-package");
+ expect(applicationDerived.layer).toBe("application");
+ expect(
+ composeAgentModuleCandidates([
+ extensionConnection,
+ applicationConnection,
+ extensionDerived,
+ applicationDerived,
+ ]).selected.get("tools/github"),
+ ).toBe(applicationDerived);
+
+ const composed = composeAgentModuleCandidates([
+ extensionConnection,
+ applicationConnection,
+ extensionDerived,
+ applicationDerived,
+ directApplicationTool,
+ ]);
+ expect(composed.selected.get("tools/github")).toBe(directApplicationTool);
+ expect(composed.composition.entries).toContainEqual(
+ expect.objectContaining({
+ kind: "shadowed",
+ source: expect.objectContaining({ form: "derived", sourceId: applicationDerived.sourceId }),
+ winnerSourceId: directApplicationTool.sourceId,
+ }),
+ );
+ });
+
+ it("rejects a selected derived source when its dependency was shadowed", () => {
+ const dependencySource = source("test:dependency", "tools/input.ts");
+ const replacementSource = source("test:dependency-replacement", "tools/input.ts");
+ const templateSource = source("test:derived-template", "tools/template.ts");
+ const registry = createAgentSourceRegistry([], { templates: [templateSource] });
+ const template = registry.templates.get(templateSource.id)!;
+ const dependency = candidate(
+ { applyTo: "root", source: dependencySource },
+ "extension-package",
+ { kind: "extension", namespace: "example", packageName: "@acme/example" },
+ );
+ const replacement = candidate({ applyTo: "root", source: replacementSource }, "application");
+ const derived = instantiateProgrammaticTemplate({
+ anchor: dependency,
+ dependencies: { input: dependency },
+ logicalPath: "tools/output.ts",
+ owner: { feature: "example", kind: "framework" },
+ template,
+ });
+
+ expect(() => composeAgentModuleCandidates([dependency, replacement, derived])).toThrow(
+ `Derived programmatic source "${derived.sourceId}" depends on unselected source "${dependency.sourceId}".`,
+ );
+ });
+
+ it("rejects unregistered templates and invalid anchor dependencies", () => {
+ const anchor = candidate(
+ { applyTo: "root", source: source("test:anchor", "connections/input.ts") },
+ "application",
+ );
+ const rawTemplateSource = source("test:raw-template", "tools/template.ts");
+ const input = {
+ anchor,
+ dependencies: { input: anchor },
+ logicalPath: "tools/output.ts",
+ owner: { feature: "example", kind: "framework" } as const,
+ };
+
+ expect(() =>
+ instantiateProgrammaticTemplate({
+ ...input,
+ template: { module: rawTemplateSource.modules[0]!, source: rawTemplateSource },
+ }),
+ ).toThrow("Derived programmatic modules require a registered template.");
+ expect(() =>
+ createAgentSourceRegistry([], {
+ templates: [
+ defineProgrammaticAgentSource({
+ id: "test:multi-module-template",
+ modules: [
+ { loadNamespace: async () => ({}), logicalPath: "tools/first.ts" },
+ { loadNamespace: async () => ({}), logicalPath: "tools/second.ts" },
+ ],
+ revision: "test:multi-module-template:v1",
+ }),
+ ],
+ }),
+ ).toThrow(
+ 'Programmatic template source "test:multi-module-template" must register exactly one module.',
+ );
+
+ const registry = createAgentSourceRegistry([], { templates: [rawTemplateSource] });
+ const template = registry.templates.get(rawTemplateSource.id)!;
+ const other = candidate(
+ { applyTo: "root", source: source("test:other", "connections/other.ts") },
+ "application",
+ );
+ expect(() =>
+ instantiateProgrammaticTemplate({ ...input, dependencies: { other }, template }),
+ ).toThrow("must include its anchor source as a dependency");
+ expect(() =>
+ instantiateProgrammaticTemplate({
+ ...input,
+ dependencies: { input: anchor, other: { ...other, nodeId: "other-node" } },
+ template,
+ }),
+ ).toThrow(`cannot depend on source "${other.sourceId}" from another node`);
+ });
+});
diff --git a/packages/eve/src/compiler/source-graph.ts b/packages/eve/src/compiler/source-graph.ts
index d748f93e8..331aa8480 100644
--- a/packages/eve/src/compiler/source-graph.ts
+++ b/packages/eve/src/compiler/source-graph.ts
@@ -5,12 +5,20 @@ import {
normalizeLogicalPath,
stripLogicalPathExtension,
} from "#discover/filesystem.js";
+import { parseJsonObject, type JsonObject } from "#shared/json.js";
export type ProgrammaticModuleNamespace = Readonly<Record<string, unknown>>;
+export interface ProgrammaticModuleLoadContext {
+ readonly dependencies: Readonly<Record<string, ProgrammaticModuleNamespace>>;
+ readonly parameters: JsonObject;
+}
+
export interface ProgrammaticAgentModule {
readonly exportName?: string;
- readonly loadNamespace: () => Promise<ProgrammaticModuleNamespace>;
+ readonly loadNamespace: (
+ context: ProgrammaticModuleLoadContext,
+ ) => Promise<ProgrammaticModuleNamespace>;
readonly logicalPath: string;
readonly semanticRevision?: string;
}
@@ -26,15 +34,25 @@ export interface AgentSourceRegistration {
readonly source: ProgrammaticAgentSource;
}
+export interface AgentSourceRegistryOptions {
+ readonly templates?: readonly ProgrammaticAgentSource[];
+}
+
+export interface RegisteredProgrammaticTemplate {
+ readonly module: ProgrammaticAgentModule;
+ readonly source: ProgrammaticAgentSource;
+}
+
export interface AgentSourceRegistry {
readonly registrations: readonly AgentSourceRegistration[];
readonly sources: ReadonlyMap<string, ProgrammaticAgentSource>;
+ readonly templates: ReadonlyMap<string, RegisteredProgrammaticTemplate>;
}
-class ImmutableProgrammaticSourceMap implements ReadonlyMap<string, ProgrammaticAgentSource> {
- readonly #values: ReadonlyMap<string, ProgrammaticAgentSource>;
+class ImmutableProgrammaticSourceMap<T> implements ReadonlyMap<string, T> {
+ readonly #values: ReadonlyMap<string, T>;
- constructor(values: ReadonlyMap<string, ProgrammaticAgentSource>) {
+ constructor(values: ReadonlyMap<string, T>) {
this.#values = new Map(values);
Object.freeze(this);
}
@@ -47,26 +65,22 @@ class ImmutableProgrammaticSourceMap implements ReadonlyMap<string, Programmatic
return "ImmutableProgrammaticSourceMap";
}
- [Symbol.iterator](): MapIterator<[string, ProgrammaticAgentSource]> {
+ [Symbol.iterator](): MapIterator<[string, T]> {
return this.#values[Symbol.iterator]();
}
- entries(): MapIterator<[string, ProgrammaticAgentSource]> {
+ entries(): MapIterator<[string, T]> {
return this.#values.entries();
}
forEach(
- callbackfn: (
- value: ProgrammaticAgentSource,
- key: string,
- map: ReadonlyMap<string, ProgrammaticAgentSource>,
- ) => void,
+ callbackfn: (value: T, key: string, map: ReadonlyMap<string, T>) => void,
thisArg?: unknown,
): void {
this.#values.forEach((value, key) => callbackfn.call(thisArg, value, key, this));
}
- get(key: string): ProgrammaticAgentSource | undefined {
+ get(key: string): T | undefined {
return this.#values.get(key);
}
@@ -78,7 +92,7 @@ class ImmutableProgrammaticSourceMap implements ReadonlyMap<string, Programmatic
return this.#values.keys();
}
- values(): MapIterator<ProgrammaticAgentSource> {
+ values(): MapIterator<T> {
return this.#values.values();
}
}
@@ -98,6 +112,8 @@ export type AgentSourceLayer =
| "extension-override"
| "application";
+export type AgentSourceForm = "derived" | "direct";
+
export type AgentModuleBacking =
| {
readonly externalDependencies: readonly string[];
@@ -109,8 +125,10 @@ export type AgentModuleBacking =
readonly sourcePath: string;
}
| {
+ readonly dependencies?: Readonly<Record<string, string>>;
readonly kind: "programmatic";
readonly moduleId: string;
+ readonly parameters?: JsonObject;
readonly registryId: string;
readonly revision: string;
readonly semanticRevision?: string;
@@ -126,6 +144,7 @@ export type AgentSourceBacking =
export interface AgentModuleCandidate {
readonly backing: AgentModuleBacking;
readonly exportName?: string;
+ readonly form: AgentSourceForm;
readonly layer: AgentSourceLayer;
readonly logicalPath: string;
readonly nodeId: string;
@@ -141,6 +160,7 @@ export interface CompiledModuleBinding {
export interface AgentSourceDescriptor {
readonly backing: AgentSourceBacking;
+ readonly form: AgentSourceForm;
readonly layer: AgentSourceLayer;
readonly logicalPath: string;
readonly owner: AgentSourceOwner;
@@ -149,6 +169,7 @@ export interface AgentSourceDescriptor {
export interface AgentResourceCandidate {
readonly backing: Extract<AgentSourceBacking, { readonly kind: "resource" }>;
+ readonly form: AgentSourceForm;
readonly layer: AgentSourceLayer;
readonly logicalPath: string;
readonly nodeId: string;
@@ -185,6 +206,13 @@ const LAYER_PRECEDENCE: Readonly<Record<AgentSourceLayer, number>> = {
application: 3,
};
+const FORM_PRECEDENCE: Readonly<Record<AgentSourceForm, number>> = {
+ derived: 0,
+ direct: 1,
+};
+
+const registeredProgrammaticTemplates = new WeakSet<RegisteredProgrammaticTemplate>();
+
export function defineProgrammaticAgentSource(
input: ProgrammaticAgentSource,
): ProgrammaticAgentSource {
@@ -219,21 +247,38 @@ export function defineProgrammaticAgentSource(
export function createAgentSourceRegistry(
registrations: readonly AgentSourceRegistration[],
+ options: AgentSourceRegistryOptions = {},
): AgentSourceRegistry {
const sources = new Map<string, ProgrammaticAgentSource>();
- const frozenRegistrations = registrations.map((registration) => {
- const source = defineProgrammaticAgentSource(registration.source);
- const existing = sources.get(source.id);
- if (existing !== undefined) {
+ const templates = new Map<string, RegisteredProgrammaticTemplate>();
+ const addSource = (inputSource: ProgrammaticAgentSource): ProgrammaticAgentSource => {
+ const source = defineProgrammaticAgentSource(inputSource);
+ if (sources.has(source.id)) {
throw new Error(`Programmatic agent source id "${source.id}" is registered more than once.`);
}
sources.set(source.id, source);
+ return source;
+ };
+ const frozenRegistrations = registrations.map((registration) => {
+ const source = addSource(registration.source);
return Object.freeze({ applyTo: registration.applyTo, source });
});
+ for (const inputTemplate of options.templates ?? []) {
+ const source = addSource(inputTemplate);
+ if (source.modules.length !== 1) {
+ throw new Error(
+ `Programmatic template source "${source.id}" must register exactly one module.`,
+ );
+ }
+ const template = Object.freeze({ module: source.modules[0]!, source });
+ registeredProgrammaticTemplates.add(template);
+ templates.set(source.id, template);
+ }
return Object.freeze({
registrations: Object.freeze(frozenRegistrations),
sources: new ImmutableProgrammaticSourceMap(sources),
+ templates: new ImmutableProgrammaticSourceMap(templates),
});
}
@@ -254,6 +299,7 @@ export function createProgrammaticModuleCandidates(input: {
semanticRevision: module.semanticRevision,
}),
exportName: module.exportName,
+ form: "direct" as const,
layer: input.layer,
logicalPath: module.logicalPath,
nodeId: input.nodeId,
@@ -263,6 +309,65 @@ export function createProgrammaticModuleCandidates(input: {
});
}
+export function instantiateProgrammaticTemplate(input: {
+ readonly anchor: AgentModuleCandidate;
+ readonly dependencies: Readonly<Record<string, AgentModuleCandidate>>;
+ readonly logicalPath: string;
+ readonly owner: AgentSourceOwner;
+ readonly parameters?: JsonObject;
+ readonly template: RegisteredProgrammaticTemplate;
+}): AgentModuleCandidate {
+ if (!registeredProgrammaticTemplates.has(input.template)) {
+ throw new Error("Derived programmatic modules require a registered template.");
+ }
+ const logicalPath = validateProgrammaticLogicalPath(input.logicalPath);
+ const anchorSourceId = expectNonEmpty(
+ input.anchor.sourceId,
+ "Derived programmatic module anchor source id",
+ );
+ const sourceId = `${input.template.source.id}:${logicalPath}:from:${anchorSourceId}`;
+ const dependencyCandidates = Object.values(input.dependencies);
+ if (!dependencyCandidates.some((candidate) => candidate.sourceId === anchorSourceId)) {
+ throw new Error(
+ `Derived programmatic module "${sourceId}" must include its anchor source as a dependency.`,
+ );
+ }
+ const dependencies = Object.freeze(
+ Object.fromEntries(
+ Object.entries(input.dependencies)
+ .sort(([left], [right]) => left.localeCompare(right))
+ .map(([alias, candidate]) => {
+ expectNonEmpty(alias, "Derived programmatic module dependency alias");
+ if (candidate.nodeId !== input.anchor.nodeId) {
+ throw new Error(
+ `Derived programmatic module "${sourceId}" cannot depend on source "${candidate.sourceId}" from another node.`,
+ );
+ }
+ return [alias, candidate.sourceId];
+ }),
+ ),
+ );
+ const parameters = Object.freeze(parseJsonObject(input.parameters ?? {}));
+ return Object.freeze({
+ backing: Object.freeze({
+ dependencies,
+ kind: "programmatic" as const,
+ moduleId: input.template.module.logicalPath,
+ parameters,
+ registryId: input.template.source.id,
+ revision: input.template.source.revision,
+ semanticRevision: input.template.module.semanticRevision,
+ }),
+ exportName: input.template.module.exportName,
+ form: "derived" as const,
+ layer: input.anchor.layer,
+ logicalPath,
+ nodeId: input.anchor.nodeId,
+ owner: input.owner,
+ sourceId,
+ });
+}
+
export function composeAgentModuleCandidates(
candidates: readonly AgentSourceCandidate[],
): ComposedAgentModuleCandidates {
@@ -288,18 +393,21 @@ export function composeAgentModuleCandidates(
for (const [slot, slotCandidates] of [...candidatesBySlot].sort(([left], [right]) =>
left.localeCompare(right),
)) {
- const seenLayers = new Set<AgentSourceLayer>();
+ const seenPrecedence = new Set<string>();
for (const candidate of slotCandidates) {
- if (seenLayers.has(candidate.layer)) {
+ const precedence = `${candidate.layer}:${candidate.form}`;
+ if (seenPrecedence.has(precedence)) {
throw new Error(
- `Agent source slot "${slot}" has more than one ${candidate.layer} candidate.`,
+ `Agent source slot "${slot}" has more than one ${candidate.layer} ${candidate.form} candidate.`,
);
}
- seenLayers.add(candidate.layer);
+ seenPrecedence.add(precedence);
}
const ordered = [...slotCandidates].sort(
- (left, right) => LAYER_PRECEDENCE[right.layer] - LAYER_PRECEDENCE[left.layer],
+ (left, right) =>
+ LAYER_PRECEDENCE[right.layer] - LAYER_PRECEDENCE[left.layer] ||
+ FORM_PRECEDENCE[right.form] - FORM_PRECEDENCE[left.form],
);
const winner = ordered[0]!;
selected.set(slot, winner);
@@ -313,6 +421,8 @@ export function composeAgentModuleCandidates(
}
}
+ validateSelectedCandidateDependencies(selected);
+
return {
composition: { entries: Object.freeze(entries) },
selected,
@@ -360,6 +470,7 @@ export function createCompiledModuleBinding(
export async function loadProgrammaticModuleNamespace(input: {
readonly backing: Extract<AgentModuleBacking, { readonly kind: "programmatic" }>;
+ readonly dependencyNamespaces?: Readonly<Record<string, ProgrammaticModuleNamespace>>;
readonly registries: readonly AgentSourceRegistry[];
}): Promise<ProgrammaticModuleNamespace> {
const matchingSources = input.registries
@@ -389,7 +500,21 @@ export async function loadProgrammaticModuleNamespace(input: {
`Programmatic module "${source.id}:${module.logicalPath}" semantic revision does not match the compiled binding.`,
);
}
- const namespace = await module.loadNamespace();
+ const dependencies = Object.fromEntries(
+ Object.entries(input.backing.dependencies ?? {}).map(([alias, sourceId]) => {
+ const namespace = input.dependencyNamespaces?.[alias];
+ if (namespace === undefined) {
+ throw new Error(
+ `Programmatic module "${source.id}:${module.logicalPath}" requires unresolved binding "${sourceId}" as dependency "${alias}".`,
+ );
+ }
+ return [alias, namespace];
+ }),
+ );
+ const namespace = await module.loadNamespace({
+ dependencies: Object.freeze(dependencies),
+ parameters: Object.freeze(input.backing.parameters ?? {}),
+ });
if (namespace === null || typeof namespace !== "object") {
throw new Error(
`Programmatic module "${source.id}:${module.logicalPath}" loader must return a module namespace object.`,
@@ -476,6 +601,7 @@ export function describeAgentSourceCandidate(
): AgentSourceDescriptor {
return Object.freeze({
backing: candidate.backing,
+ form: candidate.form,
layer: candidate.layer,
logicalPath: candidate.logicalPath,
owner: candidate.owner,
@@ -483,6 +609,22 @@ export function describeAgentSourceCandidate(
});
}
+function validateSelectedCandidateDependencies(
+ selected: ReadonlyMap<string, AgentSourceCandidate>,
+): void {
+ const selectedSourceIds = new Set([...selected.values()].map((candidate) => candidate.sourceId));
+ for (const candidate of selected.values()) {
+ if (candidate.backing.kind !== "programmatic") continue;
+ for (const sourceId of Object.values(candidate.backing.dependencies ?? {})) {
+ if (!selectedSourceIds.has(sourceId)) {
+ throw new Error(
+ `Derived programmatic source "${candidate.sourceId}" depends on unselected source "${sourceId}".`,
+ );
+ }
+ }
+ }
+}
+
function expectNonEmpty(value: string, label: string): string {
if (value.trim().length === 0) throw new Error(`${label} must be non-empty.`);
return value;
diff --git a/packages/eve/src/compiler/validate-artifact.ts b/packages/eve/src/compiler/validate-artifact.ts
index 9bfd434a0..2467b300c 100644
--- a/packages/eve/src/compiler/validate-artifact.ts
+++ b/packages/eve/src/compiler/validate-artifact.ts
@@ -186,6 +186,7 @@ export function validateCompiledAgentResources(
fail(`compiled binding "${sourceId}" is not referenced by its node manifest`);
}
}
+ validateProgrammaticBindingDependencies(node.bindings);
const activeSourceIds = new Set([
...referencedModuleSources.keys(),
@@ -257,6 +258,40 @@ function validateBinding(
}
}
+function validateProgrammaticBindingDependencies(
+ bindings: Readonly<Record<string, CompiledModuleBinding>>,
+): void {
+ const visiting = new Set<string>();
+ const visited = new Set<string>();
+ const visit = (sourceId: string): void => {
+ if (visited.has(sourceId)) return;
+ if (visiting.has(sourceId)) {
+ fail(`programmatic binding dependency cycle includes "${sourceId}"`);
+ }
+ const binding = bindings[sourceId];
+ if (binding === undefined) fail(`programmatic binding dependency "${sourceId}" is missing`);
+ visiting.add(sourceId);
+ if (binding.backing.kind === "programmatic") {
+ for (const [alias, dependencySourceId] of Object.entries(
+ binding.backing.dependencies ?? {},
+ )) {
+ if (alias.trim().length === 0) {
+ fail(`programmatic binding "${sourceId}" has an empty dependency alias`);
+ }
+ if (bindings[dependencySourceId] === undefined) {
+ fail(
+ `programmatic binding "${sourceId}" depends on missing binding "${dependencySourceId}"`,
+ );
+ }
+ visit(dependencySourceId);
+ }
+ }
+ visiting.delete(sourceId);
+ visited.add(sourceId);
+ };
+ for (const sourceId of Object.keys(bindings)) visit(sourceId);
+}
+
function collectReferencedModuleSources(
node: CompiledNode,
): Map<string, { readonly logicalPath: string }> {
diff --git a/packages/eve/src/framework/sources/registry.ts b/packages/eve/src/framework/sources/registry.ts
index 5e6f02f11..495c838a8 100644
--- a/packages/eve/src/framework/sources/registry.ts
+++ b/packages/eve/src/framework/sources/registry.ts
@@ -8,7 +8,7 @@ import {
type ProgrammaticModuleNamespace,
} from "#compiler/source-graph.js";
-const revision = `eve@${resolveInstalledPackageInfo().version}:compiled-manifest-v42`;
+const revision = `eve@${resolveInstalledPackageInfo().version}:compiled-manifest-v43`;
const localDefaults = defineProgrammaticAgentSource({
id: "eve:defaults",
@@ -93,9 +93,11 @@ export const frameworkAgentSourceRegistry: AgentSourceRegistry = createAgentSour
export async function loadFrameworkProgrammaticModule(
backing: Extract<AgentModuleBacking, { readonly kind: "programmatic" }>,
+ dependencyNamespaces?: Readonly<Record<string, ProgrammaticModuleNamespace>>,
): Promise<ProgrammaticModuleNamespace> {
return await loadProgrammaticModuleNamespace({
backing,
+ dependencyNamespaces,
registries: [frameworkAgentSourceRegistry],
});
}
diff --git a/packages/eve/src/internal/authored-module-map-loader.ts b/packages/eve/src/internal/authored-module-map-loader.ts
index 896626b9c..a0298b345 100644
--- a/packages/eve/src/internal/authored-module-map-loader.ts
+++ b/packages/eve/src/internal/authored-module-map-loader.ts
@@ -79,7 +79,14 @@ async function hydrateCompiledNodeScope(
try {
modules[sourceId] =
binding.backing.kind === "programmatic"
- ? await loadFrameworkProgrammaticModule(binding.backing)
+ ? await loadFrameworkProgrammaticModule(
+ binding.backing,
+ Object.fromEntries(
+ Object.entries(binding.backing.dependencies ?? {}).map(
+ ([alias, dependencySourceId]) => [alias, modules[dependencySourceId]!],
+ ),
+ ),
+ )
: await loadAuthoredModuleNamespace(binding.backing.sourcePath, {
externalDependencies: binding.backing.externalDependencies,
extensionScopeNamespace: resolveCompiledModuleExtensionScopeNamespace(binding),
diff --git a/packages/eve/src/internal/nitro/host/extension-capability-requirements.ts b/packages/eve/src/internal/nitro/host/extension-capability-requirements.ts
index 366e25576..62130d124 100644
--- a/packages/eve/src/internal/nitro/host/extension-capability-requirements.ts
+++ b/packages/eve/src/internal/nitro/host/extension-capability-requirements.ts
@@ -13,6 +13,7 @@ import { loadAuthoredModuleNamespace } from "#internal/authored-module-loader.js
import { extensionUsesState } from "#internal/nitro/host/extension-state-usage.js";
import type { ModuleSourceRef } from "#shared/source-ref.js";
import type { SourceDefinitionCompileOptions } from "#compiler/normalize-helpers.js";
+import { createCompiledBindingNamespaceLoader } from "#compiler/load-binding-namespace.js";
/** Derives only the extension-facing contracts used by one authored tree. */
export async function deriveExtensionCapabilityRequirements(input: {
@@ -103,30 +104,34 @@ function createLoadOptions(
readonly shortName: string;
readonly sourceRoot: string;
},
- source: { readonly logicalPath: string },
+ source: { readonly logicalPath: string; readonly sourceId: string },
moduleRoot: string,
): SourceDefinitionCompileOptions & {
readonly binding: NonNullable<SourceDefinitionCompileOptions["binding"]>;
- readonly registries: readonly [];
+ readonly loadNamespace: NonNullable<SourceDefinitionCompileOptions["loadNamespace"]>;
} {
const owner = {
kind: "extension" as const,
namespace: input.shortName,
packageName: input.packageName,
};
- return {
- binding: {
- backing: {
- externalDependencies: input.runtimeDependencies,
- extensionScope: { namespace: input.shortName, sourceRoot: input.sourceRoot },
- kind: "filesystem",
- sourcePath: join(moduleRoot, source.logicalPath),
- },
- logicalPath: source.logicalPath,
- owner,
+ const binding = {
+ backing: {
+ externalDependencies: input.runtimeDependencies,
+ extensionScope: { namespace: input.shortName, sourceRoot: input.sourceRoot },
+ kind: "filesystem" as const,
+ sourcePath: join(moduleRoot, source.logicalPath),
},
+ logicalPath: source.logicalPath,
+ owner,
+ };
+ return {
+ binding,
+ loadNamespace: createCompiledBindingNamespaceLoader({
+ bindings: { [source.sourceId]: binding },
+ registries: [],
+ }),
owner,
- registries: [],
};
}
diff --git a/packages/eve/src/setup/channel-add-conflicts.ts b/packages/eve/src/setup/channel-add-conflicts.ts
index 77d9b22db..6383ee4e9 100644
--- a/packages/eve/src/setup/channel-add-conflicts.ts
+++ b/packages/eve/src/setup/channel-add-conflicts.ts
@@ -4,6 +4,7 @@ import { isNextJsProject, type ChannelKind } from "#setup/scaffold/index.js";
import type { DisabledChannelReasons } from "#setup/cli/index.js";
import { compileChannelDefinition } from "#compiler/normalize-channel.js";
+import { createCompiledBindingNamespaceLoader } from "#compiler/load-binding-namespace.js";
import type { CompiledModuleBinding } from "#compiler/source-graph.js";
import { discoverAgent } from "#discover/discover-agent.js";
import { EVE_SESSION_ROUTE_PATH } from "#protocol/routes.js";
@@ -55,7 +56,10 @@ export async function inspectExistingChannelRegistrations(
};
const compiled = await compileChannelDefinition(agentRoot, source, {
binding,
- registries: [],
+ loadNamespace: createCompiledBindingNamespaceLoader({
+ bindings: { [source.sourceId]: binding },
+ registries: [],
+ }),
});
if (compiled.kind !== "channel") continue;
for (const definition of compiled.definitions) {
diff --git a/research/programmatic-agent-sources.md b/research/programmatic-agent-sources.md
index f5d1765af..b13ec98b4 100644
--- a/research/programmatic-agent-sources.md
+++ b/research/programmatic-agent-sources.md
@@ -1,7 +1,7 @@
---
issue: https://github.com/vercel/eve/issues/2347
status: in-progress
-last_updated: "2026-08-24"
+last_updated: "2026-08-25"
---
# Programmatic agent sources
@@ -150,9 +150,16 @@ virtual agent-relative paths:
```ts
type ProgrammaticModuleNamespace = Readonly<Record<string, unknown>>;
+interface ProgrammaticModuleLoadContext {
+ readonly dependencies: Readonly<Record<string, ProgrammaticModuleNamespace>>;
+ readonly parameters: JsonObject;
+}
+
interface ProgrammaticAgentModule {
readonly exportName?: string;
- readonly loadNamespace: () => Promise<ProgrammaticModuleNamespace>;
+ readonly loadNamespace: (
+ context: ProgrammaticModuleLoadContext,
+ ) => Promise<ProgrammaticModuleNamespace>;
readonly logicalPath: string;
readonly semanticRevision?: string;
}
@@ -170,8 +177,24 @@ interface AgentSourceRegistration {
readonly source: ProgrammaticAgentSource;
}
+interface AgentSourceRegistryOptions {
+ readonly templates?: readonly ProgrammaticAgentSource[];
+}
+
+interface RegisteredProgrammaticTemplate {
+ readonly module: ProgrammaticAgentModule;
+ readonly source: ProgrammaticAgentSource;
+}
+
+interface AgentSourceRegistry {
+ readonly registrations: readonly AgentSourceRegistration[];
+ readonly sources: ReadonlyMap<string, ProgrammaticAgentSource>;
+ readonly templates: ReadonlyMap<string, RegisteredProgrammaticTemplate>;
+}
+
function createAgentSourceRegistry(
registrations: readonly AgentSourceRegistration[],
+ options?: AgentSourceRegistryOptions,
): AgentSourceRegistry;
```
@@ -181,10 +204,12 @@ select only module-backed slots. The path derives identity; there is no `name`,
slug, kind, protocol, or precedence field.
The selected export follows existing ESM semantics and may be a zero-argument
-sync or async factory. Construction shallow-copies and freezes source and
-module metadata without invoking `loadNamespace`. The loader returns the exact
-namespace and preserves brands, symbols, functions, and durable callback
-metadata. Programmatic source IDs derive deterministically as
+sync or async factory. A namespace loader may ignore its context when it is an
+ordinary overlay; a derived module receives selected dependency namespaces and
+serialized parameters through that context. Construction shallow-copies and
+freezes source and module data without invoking `loadNamespace`. The loader
+returns the exact namespace and preserves brands, symbols, functions, and
+durable callback metadata. Programmatic source IDs derive deterministically as
`<source.id>:<logicalPath>` and must be unique within each node.
Each source also declares a non-empty immutable `revision`. The revision
@@ -205,14 +230,17 @@ default sandbox uses an explicit stable token so unrelated eve source changes
do not discard durable sandbox state.
Registries are explicitly assembled, statically imported, and immutable before
-compilation. They are not global, side-effect-populated, or mutable runtime
-registries. `root` applies only to the application root. `all-local-nodes` is a
-finite overlay applied after filesystem and extension nodes are discovered; it
-rejects `agent.ts`, `subagents/**`, `channels/**`, `schedules/**`, and
-`extensions/**`. A closed internal framework registration is the narrow
-exception that may provide the default `agent.ts` for every already-discovered
-local node. Arbitrary programmatic sources cannot use config to expand the
-graph recursively.
+compilation. Registrations are source overlays; each template is a single
+loadable module implementation used only by derived candidates and never
+injects a candidate on its own. Registration returns an opaque template handle,
+so candidate construction cannot accept an arbitrary unregistered source.
+Registries are not global, side-effect-populated, or mutable at runtime. `root`
+applies only to the application root. `all-local-nodes` is a finite overlay
+applied after filesystem and extension nodes are discovered; it rejects
+`agent.ts`, `subagents/**`, `channels/**`, `schedules/**`, and `extensions/**`.
+A closed internal framework registration is the narrow exception that may
+provide the default `agent.ts` for every already-discovered local node.
+Arbitrary programmatic sources cannot use config to expand the graph recursively.
Framework registry modules contain literal dynamic imports inside namespace
loaders. They do not statically import or evaluate definition modules while
@@ -238,6 +266,8 @@ type AgentSourceOwner =
type AgentSourceLayer =
"framework-default" | "extension-package" | "extension-override" | "application";
+type AgentSourceForm = "derived" | "direct";
+
interface AgentModuleCandidate {
readonly backing:
| {
@@ -250,12 +280,15 @@ interface AgentModuleCandidate {
readonly sourcePath: string;
}
| {
+ readonly dependencies?: Readonly<Record<string, string>>;
readonly kind: "programmatic";
readonly moduleId: string;
+ readonly parameters?: JsonObject;
readonly registryId: string;
readonly revision: string;
readonly semanticRevision?: string;
};
+ readonly form: AgentSourceForm;
readonly layer: AgentSourceLayer;
readonly logicalPath: string;
readonly nodeId: string;
@@ -264,6 +297,9 @@ interface AgentModuleCandidate {
}
```
+`direct` means contributed to a slot without derivation; it does not imply a
+filesystem-authored or application-owned source.
+
`logicalPath` is never used as an import path. Filesystem loading uses
`sourcePath` plus its external-dependency and extension scope. Programmatic
loading uses the exact registry/module/revision tuple. Missing or
@@ -275,6 +311,50 @@ Raw filesystem resources retain their physical source paths and participate in
the same slot composition, but they do not gain a programmatic backing in this
version.
+### Derived slot composition
+
+A selected module may induce an ordinary candidate in another logical slot by
+instantiating a registered programmatic template:
+
+```text
+selected memory/profile.ts ──dependency "memory"──> derived tools/profile.ts
+ │
+ ordinary slot composition and binding
+```
+
+```ts
+function instantiateProgrammaticTemplate(input: {
+ readonly anchor: AgentModuleCandidate;
+ readonly dependencies: Readonly<Record<string, AgentModuleCandidate>>;
+ readonly logicalPath: string;
+ readonly owner: AgentSourceOwner;
+ readonly parameters?: JsonObject;
+ readonly template: RegisteredProgrammaticTemplate;
+}): AgentModuleCandidate;
+```
+
+`instantiateProgrammaticTemplate` requires a registry-issued template and an
+anchor candidate. It inherits the anchor's node and layer, derives stable
+provenance from the template, target path, and anchor source ID, and records
+dependency aliases as selected source IDs plus behavior-critical JSON
+`parameters` in the programmatic backing. The anchor must be one of those
+dependencies, every dependency must belong to its node, and all dependencies
+must remain selected after composition. The constructor does not evaluate any
+module. A direct candidate wins over a derived candidate within the same source
+layer. Normal cross-layer precedence still applies, so an application-derived
+capability can replace an extension contribution while a direct application
+source can replace or disable the derived capability.
+
+Templates are not an open projection callback or a mutable registry. A closed
+compiler feature decides when to instantiate one from the already-discovered
+source graph, then the ordinary composer, binding table, normalizers, and
+module maps take over. Compiled dependency graphs reject missing bindings and
+cycles. Compilation, in-memory hydration, and generated module maps resolve
+dependencies in order and cache each selected namespace once per phase.
+Namespace caching does not cache materialized zero-argument definition exports;
+a feature that requires one shared definition instance across multiple slots
+must provide a separate per-phase materialization boundary.
+
### Required compiled bindings
Bindings are load-critical data and must not live only in optional compile
@@ -360,6 +440,7 @@ definitions. Precedence is:
```text
framework default < extension package < extension override < application
+derived < direct within one layer
```
For each slot it:
@@ -970,14 +1051,14 @@ executes a caller-owned definition instead of the selected installed tool.
## Downstream memory integration
-The wrapper-namespace path — an authored memory slot compiled to a
-programmatic binding whose virtual `tools/<slot>.ts` exports `defineDynamic`,
-producing an ordinary compiled resolver and qualified provider tools — is the
-intended mechanism for a future first-class memory integration. Proving that
-path, including cold-start namespace reconstruction and resuming a parked
-provider-tool call, is an acceptance item for the future memory research doc,
-which must use this same source graph and binding table rather than a
-memory-only registry or runtime contributor seam.
+The wrapper-namespace path uses derived slot composition: a selected authored
+memory slot instantiates a registered template whose virtual
+`tools/<slot>.ts` exports `defineDynamic`, depends on the selected memory
+binding, and carries the slot as serialized parameters. The result is an
+ordinary compiled resolver producing qualified provider tools. The memory
+implementation must prove cold-start namespace reconstruction and resuming a
+parked provider-tool call through this source graph and binding table rather
+than a memory-only registry or runtime contributor seam.
## Delivery
@@ -1019,8 +1100,7 @@ and v3 inspection metadata. The compiler diagnostic artifact moves from
version 1 to version 2 in the same PR. Disk and bundled loaders reject
earlier serialized shapes rather than repairing them. The complete version 42
schema, its single semantic validator, and serialization fixtures land first
-inside the PR, and the serialized shape does not change again within it; the
-same rule applies to version 43 in PR 2. Kernel preparation
+inside the PR, and the serialized shape does not change again within it. Kernel preparation
switches from catalog membership to slot survival: a capability prepares only
when its canonical source survived composition, and agent-info v3 derives its
prepared kernel entries from that survival plus the static kind mapping.
@@ -1039,6 +1119,14 @@ the health and info routes into the replaceable eve channel, and replaces the
and updates tool, config, channel, health, sandbox, and agent-info
documentation.
+### Follow-up — derived slot composition
+
+Programmatic templates, derived-vs-direct precedence within a layer, binding
+dependencies, serialized parameters, and dependency-aware namespace loading
+land as one focused source-graph extension before memory builds on the graph.
+`COMPILED_AGENT_MANIFEST_VERSION` moves from 42 to 43. This follow-up carries a
+`patch` changeset because it changes only internal compiler capabilities.
+
### PR 2 — kernel effects
Dispatch becomes declared effects, and the seam is deleted:
@@ -1051,7 +1139,7 @@ Dispatch becomes declared effects, and the seam is deleted:
4. deletion of the complete magic-string dispatch layer listed in the
deletion ledger's kernel row.
-`COMPILED_AGENT_MANIFEST_VERSION` moves from 42 to 43 with the serialized
+`COMPILED_AGENT_MANIFEST_VERSION` moves from 43 to 44 with the serialized
kernel effect plan. PR 2 is `patch` when externally observable behavior is
preserved, and updates the dynamic capability documentation.
@@ -1186,8 +1274,9 @@ The implementation is complete only when:
per-primitive precedence, disable implementation, or separate subagent
composer.
- Required compiled bindings are the only authority for namespace loading.
- Optional metadata, inferred physical paths, and virtual disk fallback cannot
- affect behavior.
+ Inferred physical paths, diagnostic metadata, and virtual disk fallback
+ cannot affect behavior; derived module dependencies and parameters are
+ required backing data because they do affect behavior.
- Programmatic construction is explicit, immutable, statically reachable, and
lazy. There is no global registry, runtime graph mutation, function
serialization, generated temporary source, or unselected namespace