The Open Framework for Building Agents
fix(eve): compiler - make authored module lifecycle explicit (#2614)
Andrew Barba47b3e4809e6f
diff --git a/.changeset/clean-module-lifecycle.md b/.changeset/clean-module-lifecycle.mdnew file mode 100644index 000000000..bc555b5a7--- /dev/null+++ b/.changeset/clean-module-lifecycle.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Static authored definitions now remain build-only, while runtime entries and their assets use the same bundling semantics in development and production.diff --git a/docs/agent-config.md b/docs/agent-config.mdindex 843b8a28f..cb9c4d7ae 100644--- a/docs/agent-config.md+++ b/docs/agent-config.md@@ -26,6 +26,8 @@ vision-capable model or [route image inputs to GeminiFlash](./guides/dynamic-capabilities#route-image-inputs-to-a-vision-model).When `agent.ts` is present, `model` is required.+A config that selects a static Gateway model is compile-only. A config that contains a dynamic model or a direct-provider `LanguageModel` remains a runtime entry because eve must resolve that authored value while the agent runs. See [Authored module lifecycle](./reference/typescript-api#authored-module-lifecycle).+`model` accepts a gateway model id string, which routes through the [Vercel AI Gateway](https://vercel.com/docs/ai-gateway). To call a provider directly and configure the model in code, pass a provider-authored `LanguageModel`.Provider-specific AI SDK packages are regular project dependencies. A fresh `eve init` app includes the core `ai` package, but it does not install every provider package. Install the provider package you import, then set that provider's API key:diff --git a/docs/guides/dynamic-capabilities.md b/docs/guides/dynamic-capabilities.mdindex 4304e196c..b030aefa4 100644--- a/docs/guides/dynamic-capabilities.md+++ b/docs/guides/dynamic-capabilities.md@@ -5,6 +5,8 @@ description: "Resolve models, subagents, tools, skills, and instructions at runt`defineDynamic` resolves the model, subagents, tools, skills, and instructions at runtime from a session event instead of declaring them up front. Reach for it when the right capability isn't known until the session starts, because it hinges on who the caller is, what tenant they belong to, feature flags, or external data. The [subagents](../subagents), [tools](../tools), [skills](../skills), and [instructions](../instructions) guides each point here for their dynamic form.+eve evaluates a dynamic definition module once during compilation to classify and validate it, then retains that module as a runtime entry so its event handlers can run. Its top-level code therefore runs in both phases; keep caller-specific work inside the handlers. See [Authored module lifecycle](../reference/typescript-api#authored-module-lifecycle).+## Dynamic modelsThe `model` field in `agent.ts` accepts `defineDynamic({ events })`. Resolversdiff --git a/docs/instructions.mdx b/docs/instructions.mdxindex 99aa4583f..90668881e 100644--- a/docs/instructions.mdx+++ b/docs/instructions.mdx@@ -42,7 +42,9 @@ export default defineInstructions({`role` is either `"system"` or `"user"` and defaults to `"system"`. The legacy `{ markdown: string }` form still creates system-role instructions, but is deprecated; do not combine `markdown` with `content` or `role`. Blank content contributes no context.-A module-backed definition runs once at build time. eve stores its resolved content and role in the compiled manifest, so the runtime never reruns the module.+A module-backed definition runs once at build time. eve stores its resolved content and role in the compiled manifest, so the definition is not a runtime entry.++This includes its normal ESM and [asset imports](./reference/typescript-api#asset-imports), such as a top-level prompt imported with `?raw`. See [Authored module lifecycle](./reference/typescript-api#authored-module-lifecycle) for the full compile/runtime contract.## System and user rolesdiff --git a/docs/reference/typescript-api.md b/docs/reference/typescript-api.mdindex 01e6d5756..01291a226 100644--- a/docs/reference/typescript-api.md+++ b/docs/reference/typescript-api.md@@ -59,6 +59,31 @@ Tool-wide authoring helpers such as `defineTool`, `defineDynamic`, and `disableT`defineInstructions` accepts `{ content: string, role?: "system" | "user" }`; omitted `role` means `"system"`. Its `eve/instructions` version of `defineDynamic` accepts only `session.started` and `turn.started` handlers returning `defineInstructions(...)` or `null`. The legacy `{ markdown: string }` definition remains available as a deprecated system-role form.+## Authored module lifecycle++eve evaluates TypeScript definition modules during compilation so it can validate and normalize the agent. Within one agent node, each module namespace loads at most once during that compile. The resolved definition then determines whether the module is also an entry in the runtime bundle:++| Lifecycle | Authored definitions |+| ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| Compile only | Static instructions and skills, prompt-form TypeScript schedules, static Gateway or default agent config, provider-managed web search, `Workflow` configuration, fully shadowed channels, and a child sandbox that selects its parent's sandbox |+| Compile and runtime | Dynamic instructions, skills, tools, models, and subagents; executable tools; effective channels; connections; hooks; memory; handler schedules; direct-provider models; independent sandboxes; and remote subagents |+| Runtime only | Instrumentation modules and extension mount initialization |++A compile-only module is not imported when the deployed runtime starts. For example, eve stores the resolved content from a static `instructions.ts` in the compiled manifest. A compile-and-runtime module is evaluated during compilation and imported again when a runtime process loads the module map. Keep module-top-level work deterministic, and put request- or session-specific work in the definition's runtime callbacks.++The runtime bundler follows the normal ESM graph from every runtime entry. A helper remains runtime code when a tool or other runtime entry imports it, even if static instructions also import that helper. Lifecycle selection applies to definition entries, not as tree-shaking permission for their ordinary dependencies.++### Asset imports++Authored modules may import relative non-code assets from anywhere inside their project package, including outside `agent/`:++```ts title="agent/tools/read_template.ts"+import icon from "../../assets/icon.png";+import template from "../../prompts/template.txt?raw";+```++`?raw` embeds the file as UTF-8 text. Other non-code asset imports produce a data URL with an inferred media type. Compilation, local development, and production builds use the same resolution behavior. Imports that escape the project package are rejected; package those files with the application instead.+## Runtime context (`ctx`)`ctx` is passed to your tool `execute`, hook handlers, channel event handlers, and connection auth/header resolvers. It is live only while authored code is running, so reaching for it at module top level throws. See [Session context](../guides/session-context) for the full model.diff --git a/docs/schedules.mdx b/docs/schedules.mdxindex a464e0609..1ba5abf82 100644--- a/docs/schedules.mdx+++ b/docs/schedules.mdx@@ -27,6 +27,8 @@ interface ScheduleHandlerArgs {`defineSchedule` is a type-level pass-through. The compiler is what enforces the one-of rule.+A TypeScript schedule with `markdown` is compile-only because eve stores the prompt in the manifest. A schedule with `run` remains a runtime entry so the handler can execute. See [Authored module lifecycle](./reference/typescript-api#authored-module-lifecycle).+`cron` is a standard 5-field string (`minute hour day-of-month month day-of-week`) with minute granularity. On Vercel, each schedule becomes a Vercel Cron Job, and Vercel evaluates the expression in UTC, so `"0 9 * * 1-5"` fires at 09:00 UTC on weekdays. `eve dev` never fires schedules on their cron cadence. A built app served with `eve start` does run production scheduled tasks. To trigger one while iterating in dev, use the dispatch route below.## Markdown form (fire-and-forget)diff --git a/docs/skills.mdx b/docs/skills.mdxindex e10857c15..8130e0b7a 100644--- a/docs/skills.mdx+++ b/docs/skills.mdx@@ -59,6 +59,8 @@ export default defineSkill({eve generates `SKILL.md` from `markdown`, and each `files` entry becomes a package-relative sibling. Start with plain markdown and move to `defineSkill` only when you hit its limits.+A static `defineSkill` module is evaluated during compilation and its resolved definition is stored in the manifest; a dynamic skill module is also retained as a runtime entry. See [Authored module lifecycle](./reference/typescript-api#authored-module-lifecycle).+## Find and install community skills`eve registry search` includes [skills.sh](https://skills.sh) as the built-in `@skills` source. Search by task, review the source, then install the returned skill into your project:diff --git a/e2e/fixtures/agent-authored-bundling/agent/agent.ts b/e2e/fixtures/agent-authored-bundling/agent/agent.tsnew file mode 100644index 000000000..bf13305dc--- /dev/null+++ b/e2e/fixtures/agent-authored-bundling/agent/agent.ts@@ -0,0 +1,12 @@+import { e2eAgentConfig } from "@eve-e2e/config";+import { defineAgent } from "eve";+import { mockModel } from "eve/evals";+import { respond } from "./lib/mock-responder";++const base = e2eAgentConfig({ mock: respond });++export default defineAgent({+ ...base,+ model: mockModel(respond),+ modelContextWindowTokens: base.modelContextWindowTokens ?? 1_000_000,+});diff --git a/e2e/fixtures/agent-authored-bundling/agent/authored-assets.d.ts b/e2e/fixtures/agent-authored-bundling/agent/authored-assets.d.tsnew file mode 100644index 000000000..9645d99bb--- /dev/null+++ b/e2e/fixtures/agent-authored-bundling/agent/authored-assets.d.ts@@ -0,0 +1,9 @@+declare module "*?raw" {+ const content: string;+ export default content;+}++declare module "*.bin" {+ const dataUrl: string;+ export default dataUrl;+}diff --git a/e2e/fixtures/agent-authored-bundling/agent/instructions.ts b/e2e/fixtures/agent-authored-bundling/agent/instructions.tsnew file mode 100644index 000000000..edcd66071--- /dev/null+++ b/e2e/fixtures/agent-authored-bundling/agent/instructions.ts@@ -0,0 +1,18 @@+import { readFileSync } from "node:fs";+import { resolve } from "node:path";++import { defineInstructions } from "eve/instructions";++import prompt from "../authored-assets/prompt.md?raw";+import { SHARED_MODULE_MARKER } from "../authored-assets/shared";++// This source-only read is a cold-start tripwire: static instructions may run+// during compilation, but a deployed runtime entry could not resolve this file.+const compileOnlyMarker = readFileSync(+ resolve(process.cwd(), "authored-assets/compile-only.txt"),+ "utf8",+).trim();++export default defineInstructions({+ content: [prompt.trim(), SHARED_MODULE_MARKER, compileOnlyMarker].join("\n"),+});diff --git a/e2e/fixtures/agent-authored-bundling/agent/instrumentation.ts b/e2e/fixtures/agent-authored-bundling/agent/instrumentation.tsnew file mode 100644index 000000000..9a42dc0a6--- /dev/null+++ b/e2e/fixtures/agent-authored-bundling/agent/instrumentation.ts@@ -0,0 +1,13 @@+import { defineInstrumentation } from "eve/instrumentation";++import marker from "../authored-assets/instrumentation.txt?raw";++const INSTRUMENTATION_MARKER = "authored-instrumentation-asset";++if (marker.trim() !== INSTRUMENTATION_MARKER) {+ throw new Error("Authored instrumentation asset did not preserve its contents.");+}++export default defineInstrumentation({+ functionId: INSTRUMENTATION_MARKER,+});diff --git a/e2e/fixtures/agent-authored-bundling/agent/lib/mock-responder.ts b/e2e/fixtures/agent-authored-bundling/agent/lib/mock-responder.tsnew file mode 100644index 000000000..600f73a07--- /dev/null+++ b/e2e/fixtures/agent-authored-bundling/agent/lib/mock-responder.ts@@ -0,0 +1,18 @@+import type { MockModelRequest, MockModelResponse } from "eve/evals";++const PROBE_DIRECTIVE = "AUTHORED-BUNDLING-PROBE";+const PROBE_TOOL = "bundle_probe";++export function respond(request: MockModelRequest): MockModelResponse | string {+ const message = request.lastUserMessage ?? "";+ if (!message.includes(PROBE_DIRECTIVE)) {+ return `Mock reply: ${message}`;+ }++ const result = [...request.toolResults].reverse().find((entry) => entry.name === PROBE_TOOL);+ if (result === undefined) {+ return { toolCalls: [{ name: PROBE_TOOL }] };+ }++ return `${PROBE_DIRECTIVE}-COMPLETE`;+}diff --git a/e2e/fixtures/agent-authored-bundling/agent/tools/bundle_probe.ts b/e2e/fixtures/agent-authored-bundling/agent/tools/bundle_probe.tsnew file mode 100644index 000000000..a5ffc69a8--- /dev/null+++ b/e2e/fixtures/agent-authored-bundling/agent/tools/bundle_probe.ts@@ -0,0 +1,18 @@+import { defineTool } from "eve/tools";+import { z } from "zod";++import binaryAsset from "../../authored-assets/runtime.bin";+import rawText from "../../authored-assets/runtime.txt?raw";+import { SHARED_MODULE_MARKER } from "../../authored-assets/shared";++export default defineTool({+ description: "E2E bundling probe. Call only when the user sends AUTHORED-BUNDLING-PROBE.",+ inputSchema: z.object({}),+ execute() {+ return {+ binaryAsset,+ rawText,+ sharedModule: SHARED_MODULE_MARKER,+ };+ },+});diff --git a/e2e/fixtures/agent-authored-bundling/authored-assets/compile-only.txt b/e2e/fixtures/agent-authored-bundling/authored-assets/compile-only.txtnew file mode 100644index 000000000..158f59eea--- /dev/null+++ b/e2e/fixtures/agent-authored-bundling/authored-assets/compile-only.txt@@ -0,0 +1 @@+compile-only-instructionsdiff --git a/e2e/fixtures/agent-authored-bundling/authored-assets/instrumentation.txt b/e2e/fixtures/agent-authored-bundling/authored-assets/instrumentation.txtnew file mode 100644index 000000000..a9908cd9f--- /dev/null+++ b/e2e/fixtures/agent-authored-bundling/authored-assets/instrumentation.txt@@ -0,0 +1 @@+authored-instrumentation-assetdiff --git a/e2e/fixtures/agent-authored-bundling/authored-assets/prompt.md b/e2e/fixtures/agent-authored-bundling/authored-assets/prompt.mdnew file mode 100644index 000000000..bce87b044--- /dev/null+++ b/e2e/fixtures/agent-authored-bundling/authored-assets/prompt.md@@ -0,0 +1,3 @@+# Identity++You are a helpful assistant.diff --git a/e2e/fixtures/agent-authored-bundling/authored-assets/runtime.bin b/e2e/fixtures/agent-authored-bundling/authored-assets/runtime.binnew file mode 100644index 000000000..1be2c92d1--- /dev/null+++ b/e2e/fixtures/agent-authored-bundling/authored-assets/runtime.bin@@ -0,0 +1 @@+EVE-BINARY-ASSETdiff --git a/e2e/fixtures/agent-authored-bundling/authored-assets/runtime.txt b/e2e/fixtures/agent-authored-bundling/authored-assets/runtime.txtnew file mode 100644index 000000000..21f118c89--- /dev/null+++ b/e2e/fixtures/agent-authored-bundling/authored-assets/runtime.txt@@ -0,0 +1 @@+authored runtime textdiff --git a/e2e/fixtures/agent-authored-bundling/authored-assets/shared.ts b/e2e/fixtures/agent-authored-bundling/authored-assets/shared.tsnew file mode 100644index 000000000..2ebf61596--- /dev/null+++ b/e2e/fixtures/agent-authored-bundling/authored-assets/shared.ts@@ -0,0 +1 @@+export const SHARED_MODULE_MARKER = "shared-authored-typescript-module";diff --git a/e2e/fixtures/agent-authored-bundling/evals/authored-bundling.eval.ts b/e2e/fixtures/agent-authored-bundling/evals/authored-bundling.eval.tsnew file mode 100644index 000000000..eaf232768--- /dev/null+++ b/e2e/fixtures/agent-authored-bundling/evals/authored-bundling.eval.ts@@ -0,0 +1,21 @@+import { defineEval } from "eve/evals";++const PROBE_DIRECTIVE = "AUTHORED-BUNDLING-PROBE";++export default defineEval({+ description:+ "Static and runtime authored modules preserve their lifecycle and bundled asset semantics.",+ async test(t) {+ await t.send(PROBE_DIRECTIVE);++ t.succeeded();+ t.calledTool("bundle_probe", {+ output: {+ binaryAsset: "data:application/octet-stream;base64,RVZFLUJJTkFSWS1BU1NFVAo=",+ rawText: "authored runtime text\n",+ sharedModule: "shared-authored-typescript-module",+ },+ });+ t.messageIncludes(`${PROBE_DIRECTIVE}-COMPLETE`);+ },+});diff --git a/e2e/fixtures/agent-authored-bundling/evals/evals.config.ts b/e2e/fixtures/agent-authored-bundling/evals/evals.config.tsnew file mode 100644index 000000000..7a61a5b55--- /dev/null+++ b/e2e/fixtures/agent-authored-bundling/evals/evals.config.ts@@ -0,0 +1,6 @@+import { e2eJudgeModel } from "@eve-e2e/config";+import { defineEvalConfig } from "eve/evals";++export default defineEvalConfig({+ judge: { model: e2eJudgeModel() },+});diff --git a/e2e/fixtures/agent-authored-bundling/package.json b/e2e/fixtures/agent-authored-bundling/package.jsonnew file mode 100644index 000000000..bbf2f07c2--- /dev/null+++ b/e2e/fixtures/agent-authored-bundling/package.json@@ -0,0 +1,23 @@+{+ "name": "agent-authored-bundling",+ "version": "0.0.0",+ "private": true,+ "type": "module",+ "scripts": {+ "build": "eve build",+ "dev": "eve dev",+ "start": "eve start",+ "typecheck": "eve build && tsc",+ "test:e2e": "eve eval --strict"+ },+ "dependencies": {+ "@eve-e2e/config": "workspace:*",+ "@workflow/world-postgres": "catalog:",+ "eve": "workspace:*",+ "zod": "catalog:"+ },+ "devDependencies": {+ "@types/node": "catalog:",+ "typescript": "catalog:"+ }+}diff --git a/e2e/fixtures/agent-authored-bundling/tsconfig.json b/e2e/fixtures/agent-authored-bundling/tsconfig.jsonnew file mode 100644index 000000000..7e570d043--- /dev/null+++ b/e2e/fixtures/agent-authored-bundling/tsconfig.json@@ -0,0 +1,17 @@+{+ "compilerOptions": {+ "target": "ES2022",+ "module": "esnext",+ "moduleResolution": "bundler",+ "outDir": "dist",+ "rootDir": ".",+ "strict": true,+ "esModuleInterop": true,+ "skipLibCheck": true,+ "forceConsistentCasingInFileNames": true,+ "declaration": false,+ "noEmit": true,+ "types": ["node"]+ },+ "include": ["agent/**/*.ts", "evals/**/*.ts"]+}diff --git a/packages/eve/src/cli/commands/channel-add-conflicts.ts b/packages/eve/src/cli/commands/channel-add-conflicts.tsindex 98dd7bf56..05025cf67 100644--- a/packages/eve/src/cli/commands/channel-add-conflicts.ts+++ b/packages/eve/src/cli/commands/channel-add-conflicts.ts@@ -5,7 +5,7 @@ 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 type { AgentModuleBinding } from "#compiler/source-graph.js";import { discoverAgent } from "#discover/discover-agent.js";import { EVE_SESSION_ROUTE_PATH } from "#protocol/routes.js";@@ -35,7 +35,7 @@ export async function inspectExistingChannelRegistrations(const slackOwners = new Set<string>();for (const source of manifest.channels) {- const binding: CompiledModuleBinding = {+ const binding: AgentModuleBinding = {backing: {externalDependencies: [],kind: "filesystem",diff --git a/packages/eve/src/compiler/channel-route-plan.ts b/packages/eve/src/compiler/channel-route-plan.tsindex dc68946a7..b13a688dc 100644--- a/packages/eve/src/compiler/channel-route-plan.ts+++ b/packages/eve/src/compiler/channel-route-plan.ts@@ -4,7 +4,7 @@ import type {CompiledChannelRoutePlan,CompiledShadowedChannelRoute,} from "#compiler/manifest.js";-import type { AgentSourceDescriptor, CompiledModuleBinding } from "#compiler/source-graph.js";+import type { AgentModuleBinding, AgentSourceDescriptor } from "#compiler/source-graph.js";import {createChannelRouteShadowedDiagnostic,type CompilerDiagnostic,@@ -12,7 +12,7 @@ import {import { HOST_HTTP_INVENTORY } from "#framework/host-inventory.js";export function createCompiledChannelRoutePlan(input: {- readonly bindings: Readonly<Record<string, CompiledModuleBinding>>;+ readonly bindings: Readonly<Record<string, AgentModuleBinding>>;readonly channels: readonly CompiledChannelDefinition[];readonly diagnostics?: CompilerDiagnostic[];readonly nodeId: string;diff --git a/packages/eve/src/compiler/compile-from-memory.test.ts b/packages/eve/src/compiler/compile-from-memory.test.tsindex 6b1bdc66a..a14eb672b 100644--- a/packages/eve/src/compiler/compile-from-memory.test.ts+++ b/packages/eve/src/compiler/compile-from-memory.test.ts@@ -29,6 +29,14 @@ describe("compileFromMemory", () => {expect(manifest.bindings[manifest.config.source.sourceId]?.owner).toEqual({kind: "application",});+ expect(manifest.bindings[manifest.config.source.sourceId]?.usage).toEqual({+ compile: true,+ runtimeEntry: false,+ });+ expect(manifest.bindings[manifest.sandbox.sourceId]?.usage).toEqual({+ compile: true,+ runtimeEntry: true,+ });expect(manifest.sourceComposition.entries).toContainEqual(expect.objectContaining({kind: "shadowed",@@ -81,7 +89,7 @@ describe("compileFromMemory", () => {expect(manifest.bindings[skill!.sourceId]?.owner).toEqual({ kind: "application" });});- it("preserves roots and passes the serialized v43 schema", async () => {+ it("preserves roots and passes the serialized v44 schema", async () => {const { manifest } = await compileFromMemory({agentRoot: "/app/agent",appRoot: "/app",@@ -119,6 +127,7 @@ describe("compileFromMemory", () => {expect(manifest.bindings[sourceId]).toMatchObject({backing: { kind: "programmatic", moduleId: "instrumentation.ts" },owner: { kind: "application" },+ usage: { compile: false, runtimeEntry: true },});expect(moduleMap.nodes[ROOT_COMPILED_AGENT_NODE_ID]?.modules[sourceId]?.default).toBe(instrumentation,diff --git a/packages/eve/src/compiler/instrumentation-layout-config.ts b/packages/eve/src/compiler/instrumentation-layout-config.tsnew file mode 100644index 000000000..2927ea169--- /dev/null+++ b/packages/eve/src/compiler/instrumentation-layout-config.ts@@ -0,0 +1,16 @@+import type { CompiledAgentDefinition } from "#compiler/manifest.js";+import type { FinalizedNodeSourceState } from "#compiler/node-source-state.js";++export function assertInstrumentationLayoutConfig(+ config: CompiledAgentDefinition,+ state: FinalizedNodeSourceState,+): void {+ if (+ config.experimental?.instrumentationProviders === true &&+ state.composed.selected.has("instrumentation")+ ) {+ throw new Error(+ "A selected instrumentation.ts source cannot be used with experimental.instrumentationProviders. Move the declaration into the instrumentation/ provider directory.",+ );+ }+}diff --git a/packages/eve/src/compiler/load-binding-namespace.test.ts b/packages/eve/src/compiler/load-binding-namespace.test.tsindex a411a1002..0511f9d1d 100644--- a/packages/eve/src/compiler/load-binding-namespace.test.ts+++ b/packages/eve/src/compiler/load-binding-namespace.test.ts@@ -4,7 +4,7 @@ import { createCompiledBindingNamespaceLoader } from "#compiler/load-binding-namimport {createAgentSourceRegistry,defineProgrammaticAgentSource,- type CompiledModuleBinding,+ type AgentModuleBinding,} from "#compiler/source-graph.js";const mocks = vi.hoisted(() => ({@@ -24,7 +24,7 @@ describe("compiled binding namespace loader", () => {revision: "test:template:v1",});const registry = createAgentSourceRegistry([], { templates: [template] });- const bindings: Record<string, CompiledModuleBinding> = {+ const bindings: Record<string, AgentModuleBinding> = {dependency: {backing: {externalDependencies: [],@@ -73,7 +73,7 @@ describe("compiled binding namespace loader", () => {revision: "test:cyclic-template:v1",});const registry = createAgentSourceRegistry([], { templates: [template] });- const programmatic = (dependency: string): CompiledModuleBinding => ({+ const programmatic = (dependency: string): AgentModuleBinding => ({backing: {dependencies: { source: dependency },kind: "programmatic",diff --git a/packages/eve/src/compiler/load-binding-namespace.ts b/packages/eve/src/compiler/load-binding-namespace.tsindex 6adb069a4..bb32840a3 100644--- a/packages/eve/src/compiler/load-binding-namespace.ts+++ b/packages/eve/src/compiler/load-binding-namespace.ts@@ -1,6 +1,6 @@import {+ type AgentModuleBinding,type AgentSourceRegistry,- type CompiledModuleBinding,loadProgrammaticModuleNamespace,memoizeModuleNamespaceFactories,type ProgrammaticModuleNamespace,@@ -14,9 +14,14 @@ export type CompiledBindingNamespaceLoader = (/** Loads one node's selected bindings with dependency ordering and per-phase caching. */export function createCompiledBindingNamespaceLoader(input: {- readonly bindings: Readonly<Record<string, CompiledModuleBinding>>;+ readonly bindings?: Readonly<Record<string, AgentModuleBinding>>;+ readonly onLoad?: (sourceId: string) => void;readonly registries: readonly AgentSourceRegistry[];+ readonly resolveBinding?: (sourceId: string) => AgentModuleBinding | undefined;}): CompiledBindingNamespaceLoader {+ if (input.bindings === undefined && input.resolveBinding === undefined) {+ throw new Error("Compiled binding namespace loader requires a binding source.");+ }const cache = new Map<string, Promise<ProgrammaticModuleNamespace>>();const load = (@@ -28,10 +33,11 @@ export function createCompiledBindingNamespaceLoader(input: {}const cached = cache.get(sourceId);if (cached !== undefined) return cached;- const binding = input.bindings[sourceId];+ const binding = input.resolveBinding?.(sourceId) ?? input.bindings?.[sourceId];if (binding === undefined) {throw new Error(`Compiled binding dependency "${sourceId}" is missing.`);}+ input.onLoad?.(sourceId);const nextLineage = new Set(lineage).add(sourceId);const loading = loadCompiledBindingNamespace({binding,@@ -46,7 +52,7 @@ export function createCompiledBindingNamespaceLoader(input: {}async function loadCompiledBindingNamespace(input: {- readonly binding: CompiledModuleBinding;+ readonly binding: AgentModuleBinding;readonly loadDependency: CompiledBindingNamespaceLoader;readonly registries: readonly AgentSourceRegistry[];}): Promise<ProgrammaticModuleNamespace> {@@ -72,7 +78,7 @@ async function loadCompiledBindingNamespace(input: {/** Derives the stable package-owned scope used while loading an extension module. */export function resolveCompiledModuleExtensionScopeNamespace(- binding: CompiledModuleBinding,+ binding: AgentModuleBinding,): string | undefined {return binding.owner.kind === "extension"? packageStateNamespace(binding.owner.packageName)diff --git a/packages/eve/src/compiler/manifest.test.ts b/packages/eve/src/compiler/manifest.test.tsindex d1fb3b053..df60495f1 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 v43", () => {+describe("compiled agent manifest v44", () => {it("round-trips a real compiled graph through the serialized schema", async () => {const { manifest } = await compileFromMemory({model: "openai/gpt-5.4",@@ -37,6 +37,25 @@ describe("compiled agent manifest v43", () => {);});+ it("requires strict lifecycle usage on every serialized binding", async () => {+ const { manifest } = await compileFromMemory({ model: "openai/gpt-5.4" });+ const serialized = JSON.parse(JSON.stringify(manifest)) as typeof manifest;+ const sourceId = serialized.config.source.sourceId;+ const binding = serialized.bindings[sourceId]!;++ const { usage: _usage, ...withoutUsage } = binding;+ serialized.bindings[sourceId] = withoutUsage as typeof binding;+ expect(compiledAgentManifestSchema.safeParse(serialized).success).toBe(false);++ serialized.bindings[sourceId] = {+ ...manifest.bindings[sourceId]!,+ usage: { compile: false, runtimeEntry: false },+ };+ expect(() => validateCompiledAgentManifest(serialized)).toThrow(+ `compiled binding "${sourceId}" has no compile or runtime usage`,+ );+ });+it("rejects unreferenced bindings and invalid route provenance", async () => {const { manifest } = await compileFromMemory({ model: "openai/gpt-5.4" });const configBinding = manifest.bindings[manifest.config.source.sourceId]!;@@ -73,7 +92,7 @@ describe("compiled agent manifest v43", () => {).toThrow("dangling winner");});- it("rejects module maps whose keys diverge from total bindings", async () => {+ it("rejects module maps whose keys diverge from runtime entries", async () => {const { manifest, moduleMap } = await compileFromMemory({ model: "openai/gpt-5.4" });const root = moduleMap.nodes.__root__!;diff --git a/packages/eve/src/compiler/manifest.ts b/packages/eve/src/compiler/manifest.tsindex 70077cc45..f46ca795f 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 = 43;+export const COMPILED_AGENT_MANIFEST_VERSION = 44;/*** Compiled channel entry preserved in the compiled manifest.@@ -396,6 +396,12 @@ const compiledModuleBindingSchema: z.ZodType<CompiledModuleBinding> = zbacking: agentModuleBackingSchema,logicalPath: z.string(),owner: agentSourceOwnerSchema,+ usage: z+ .object({+ compile: z.boolean(),+ runtimeEntry: z.boolean(),+ })+ .strict(),}).strict();diff --git a/packages/eve/src/compiler/module-lifecycle.scenario.test.ts b/packages/eve/src/compiler/module-lifecycle.scenario.test.tsnew file mode 100644index 000000000..f35fd02aa--- /dev/null+++ b/packages/eve/src/compiler/module-lifecycle.scenario.test.ts@@ -0,0 +1,110 @@+import { join } from "node:path";++import { describe, expect, it } from "vitest";++import { compileAgentManifest } from "#compiler/normalize-manifest.js";+import { discoverAgent } from "#discover/discover-agent.js";+import { useScenarioApp } from "#internal/testing/scenario-app.js";++describe("authored module lifecycle", () => {+ const scenarioApp = useScenarioApp();++ it("classifies static, dynamic, direct-model, and remote subagent configs", async () => {+ const app = await scenarioApp({+ files: {+ "agent/agent.mjs": 'export default { model: "openai/gpt-5.4" };\n',+ "agent/subagents/direct-model/agent.mjs": [+ "const model = {",+ ' specificationVersion: "v3",',+ ' provider: "test-provider",',+ ' modelId: "direct-model",',+ " async doGenerate() { return {}; },",+ " async doStream() { return {}; },",+ "};",+ "export default {",+ ' description: "Uses a direct provider model.",',+ " model,",+ " modelContextWindowTokens: 8192,",+ "};",+ "",+ ].join("\n"),+ "agent/subagents/dynamic-model/agent.mjs": [+ "export default {",+ ' description: "Chooses a model at runtime.",',+ " model: {",+ ' kind: "eve:dynamic",',+ ' events: { "session.started": () => "openai/gpt-5.4" },',+ " },",+ "};",+ "",+ ].join("\n"),+ "agent/subagents/dynamic/agent.mjs": [+ "export default {",+ ' kind: "eve:dynamic",',+ " events: {",+ ' "session.started": () => ({',+ ' description: "Dynamically available.",',+ ' model: "openai/gpt-5.4",',+ " }),",+ " },",+ "};",+ "",+ ].join("\n"),+ "agent/subagents/remote.mjs": [+ "export default {",+ ' description: "Calls a remote deployment.",',+ ' kind: "remote",',+ ' path: "/eve/v1/session",',+ ' url: "https://remote.example.com",',+ "};",+ "",+ ].join("\n"),+ "agent/subagents/static/agent.mjs": [+ "export default {",+ ' description: "Always available.",',+ ' model: "openai/gpt-5.4",',+ "};",+ "",+ ].join("\n"),+ },+ name: "module-lifecycle-subagents",+ });+ const discovered = await discoverAgent({+ agentRoot: join(app.appRoot, "agent"),+ appRoot: app.appRoot,+ });+ const manifest = await compileAgentManifest(discovered.manifest);++ expect(manifest.bindings[manifest.config.source.sourceId]?.usage).toEqual({+ compile: true,+ runtimeEntry: false,+ });++ const staticNode = manifest.subagents.find((node) => node.name === "static")!;+ expect(staticNode.configResolver).toBeUndefined();+ if (!("config" in staticNode.agent)) throw new Error("Expected a static subagent config.");+ expect(staticNode.agent.bindings[staticNode.agent.config.source.sourceId]?.usage).toEqual({+ compile: true,+ runtimeEntry: false,+ });++ const dynamicNode = manifest.subagents.find((node) => node.name === "dynamic")!;+ expect(dynamicNode.configResolver).toBeDefined();+ expect(dynamicNode.agent.bindings[dynamicNode.configResolver!.sourceId]?.usage).toEqual({+ compile: true,+ runtimeEntry: true,+ });++ for (const name of ["dynamic-model", "direct-model"]) {+ const node = manifest.subagents.find((candidate) => candidate.name === name)!;+ if (!("config" in node.agent)) throw new Error(`Expected a static config for ${name}.`);+ expect(node.agent.bindings[node.agent.config.source.sourceId]?.usage).toEqual({+ compile: true,+ runtimeEntry: true,+ });+ }++ const remote = manifest.remoteAgents.find((agent) => agent.name === "remote")!;+ expect(remote.binding.usage).toEqual({ compile: true, runtimeEntry: true });+ });+});diff --git a/packages/eve/src/compiler/module-lifecycle.test.ts b/packages/eve/src/compiler/module-lifecycle.test.tsnew file mode 100644index 000000000..f5057e023--- /dev/null+++ b/packages/eve/src/compiler/module-lifecycle.test.ts@@ -0,0 +1,101 @@+import { describe, expect, it, vi } from "vitest";++import { NodeModuleEvaluationContext } from "#compiler/module-lifecycle.js";+import {+ createAgentSourceRegistry,+ defineProgrammaticAgentSource,+ type AgentModuleBinding,+} from "#compiler/source-graph.js";++const owner = { kind: "application" as const };++function programmaticBinding(+ moduleId: string,+ dependencies?: Readonly<Record<string, string>>,+): AgentModuleBinding {+ return {+ backing: {+ dependencies,+ kind: "programmatic",+ moduleId,+ registryId: "lifecycle-test",+ revision: "v1",+ },+ logicalPath: moduleId,+ owner,+ };+}++describe("node module lifecycle", () => {+ it("loads each namespace once across config and resource compilation", async () => {+ const loadConfig = vi.fn(async () => ({ default: { model: "openai/gpt-5.4" } }));+ const loadTool = vi.fn(async () => ({ default: { execute: () => null } }));+ const source = defineProgrammaticAgentSource({+ id: "lifecycle-test",+ modules: [+ { loadNamespace: loadConfig, logicalPath: "agent.ts" },+ { loadNamespace: loadTool, logicalPath: "tools/runtime.ts" },+ ],+ revision: "v1",+ });+ const context = new NodeModuleEvaluationContext([+ createAgentSourceRegistry([{ applyTo: "root", source }]),+ ]);+ const config = programmaticBinding("agent.ts");+ const tool = programmaticBinding("tools/runtime.ts");++ context.setBindings({ config });+ const firstConfig = await context.loadNamespace("config");+ context.setBindings({ config, tool });+ const secondConfig = await context.loadNamespace("config");+ await context.loadNamespace("tool");+ context.requireRuntimeEntry("tool");++ expect(firstConfig).toBe(secondConfig);+ expect(loadConfig).toHaveBeenCalledTimes(1);+ expect(loadTool).toHaveBeenCalledTimes(1);+ expect(context.finalizeBindings()).toMatchObject({+ config: { usage: { compile: true, runtimeEntry: false } },+ tool: { usage: { compile: true, runtimeEntry: true } },+ });+ });++ it("links transitive programmatic dependencies into runtime entries", () => {+ const context = new NodeModuleEvaluationContext([]);+ context.setBindings({+ dependency: programmaticBinding("dependency.ts"),+ root: programmaticBinding("root.ts", { dependency: "dependency" }),+ });+ context.requireRuntimeEntry("root");++ expect(context.finalizeBindings()).toMatchObject({+ dependency: { usage: { compile: false, runtimeEntry: true } },+ root: { usage: { compile: false, runtimeEntry: true } },+ });+ });++ it("rejects missing dependencies, cycles, and unused selected bindings", () => {+ const missing = new NodeModuleEvaluationContext([]);+ missing.setBindings({ root: programmaticBinding("root.ts", { dependency: "missing" }) });+ missing.requireRuntimeEntry("root");+ expect(() => missing.finalizeBindings()).toThrow(+ 'Runtime module entry "missing" has no selected binding.',+ );++ const cyclic = new NodeModuleEvaluationContext([]);+ cyclic.setBindings({+ left: programmaticBinding("left.ts", { right: "right" }),+ right: programmaticBinding("right.ts", { left: "left" }),+ });+ cyclic.requireRuntimeEntry("left");+ expect(() => cyclic.finalizeBindings()).toThrow(+ 'Compiled module dependency cycle includes "left".',+ );++ const unused = new NodeModuleEvaluationContext([]);+ unused.setBindings({ unused: programmaticBinding("unused.ts") });+ expect(() => unused.finalizeBindings()).toThrow(+ 'Selected module binding "unused" has no compile or runtime usage.',+ );+ });+});diff --git a/packages/eve/src/compiler/module-lifecycle.ts b/packages/eve/src/compiler/module-lifecycle.tsnew file mode 100644index 000000000..125b06d14--- /dev/null+++ b/packages/eve/src/compiler/module-lifecycle.ts@@ -0,0 +1,112 @@+import type {+ AgentModuleBinding,+ AgentSourceRegistry,+ CompiledModuleBinding,+} from "#compiler/source-graph.js";+import type { CompiledAgentDefinition } from "#compiler/manifest.js";+import {+ createCompiledBindingNamespaceLoader,+ type CompiledBindingNamespaceLoader,+} from "#compiler/load-binding-namespace.js";++/** Owns namespace loading and lifecycle decisions for one node compilation. */+export class NodeModuleEvaluationContext {+ #bindings: Readonly<Record<string, AgentModuleBinding>> = {};+ readonly #lifecycle = new NodeModuleLifecycle();+ readonly loadNamespace: CompiledBindingNamespaceLoader;++ constructor(registries: readonly AgentSourceRegistry[]) {+ this.loadNamespace = createCompiledBindingNamespaceLoader({+ onLoad: (sourceId) => this.#lifecycle.recordCompileLoad(sourceId),+ registries,+ resolveBinding: (sourceId) => this.#bindings[sourceId],+ });+ }++ setBindings(bindings: Readonly<Record<string, AgentModuleBinding>>): void {+ this.#bindings = bindings;+ }++ requireRuntimeEntry(sourceId: string): void {+ this.#lifecycle.requireRuntimeEntry(sourceId);+ }++ finalizeBindings(): Record<string, CompiledModuleBinding> {+ return this.#lifecycle.finalize(this.#bindings);+ }+}++/** Marks authored config namespaces whose values must be resolved by the runtime. */+export function markConfigRuntimeEntries(+ config: CompiledAgentDefinition,+ evaluation: NodeModuleEvaluationContext,+): void {+ const sources = [config.dynamicModel, config.model?.source, config.compaction?.model?.source];+ for (const source of sources) {+ if (source !== undefined) evaluation.requireRuntimeEntry(source.sourceId);+ }+}++/** Tracks one selected node's module namespace usage across compilation and runtime linking. */+class NodeModuleLifecycle {+ readonly #compileLoads = new Set<string>();+ readonly #runtimeRoots = new Set<string>();++ recordCompileLoad(sourceId: string): void {+ this.#compileLoads.add(sourceId);+ }++ requireRuntimeEntry(sourceId: string): void {+ this.#runtimeRoots.add(sourceId);+ }++ finalize(+ bindings: Readonly<Record<string, AgentModuleBinding>>,+ ): Record<string, CompiledModuleBinding> {+ const runtimeEntries = collectRuntimeEntryClosure(bindings, this.#runtimeRoots);+ const compiled: Record<string, CompiledModuleBinding> = {};++ for (const [sourceId, binding] of Object.entries(bindings)) {+ const usage = {+ compile: this.#compileLoads.has(sourceId),+ runtimeEntry: runtimeEntries.has(sourceId),+ };+ if (!usage.compile && !usage.runtimeEntry) {+ throw new Error(`Selected module binding "${sourceId}" has no compile or runtime usage.`);+ }+ compiled[sourceId] = Object.freeze({ ...binding, usage: Object.freeze(usage) });+ }++ return compiled;+ }+}++function collectRuntimeEntryClosure(+ bindings: Readonly<Record<string, AgentModuleBinding>>,+ roots: ReadonlySet<string>,+): Set<string> {+ const runtimeEntries = new Set<string>();+ const visiting = new Set<string>();++ const visit = (sourceId: string): void => {+ if (runtimeEntries.has(sourceId)) return;+ if (visiting.has(sourceId)) {+ throw new Error(`Compiled module dependency cycle includes "${sourceId}".`);+ }+ const binding = bindings[sourceId];+ if (binding === undefined) {+ throw new Error(`Runtime module entry "${sourceId}" has no selected binding.`);+ }+ visiting.add(sourceId);+ if (binding.backing.kind === "programmatic") {+ for (const dependencySourceId of Object.values(binding.backing.dependencies ?? {})) {+ visit(dependencySourceId);+ }+ }+ visiting.delete(sourceId);+ runtimeEntries.add(sourceId);+ };++ for (const sourceId of roots) visit(sourceId);+ return runtimeEntries;+}diff --git a/packages/eve/src/compiler/module-map.test.ts b/packages/eve/src/compiler/module-map.test.tsindex 9426ea963..dd8572021 100644--- a/packages/eve/src/compiler/module-map.test.ts+++ b/packages/eve/src/compiler/module-map.test.ts@@ -2,7 +2,7 @@ import { describe, expect, it, vi } from "vitest";import { compileFromMemory } from "#compiler/compile-from-memory.js";import {- collectModuleBindingsForManifest,+ collectRuntimeModuleBindingsForManifest,createCompiledModuleMapSource,createProgrammaticCompiledModuleMap,} from "#compiler/module-map.js";@@ -25,7 +25,7 @@ vi.mock("#internal/authored-module-loader.js", () => ({}));describe("compiled module maps", () => {- it("renders every selected binding and no shadowed source", async () => {+ it("renders every runtime binding and no compile-only or shadowed source", async () => {const { manifest } = await compileFromMemory({model: "openai/gpt-5.4",tools: [{ name: "weather" }],@@ -35,8 +35,9 @@ describe("compiled module maps", () => {moduleMapPath: "/app/.eve/compile/module-map.mjs",});- for (const sourceId of Object.keys(manifest.bindings)) {- expect(source).toContain(JSON.stringify(sourceId));+ for (const [sourceId, binding] of Object.entries(manifest.bindings)) {+ if (binding.usage.runtimeEntry) expect(source).toContain(JSON.stringify(sourceId));+ else expect(source).not.toContain(JSON.stringify(sourceId));}for (const entry of manifest.sourceComposition.entries) {if (entry.kind === "shadowed") {@@ -47,14 +48,19 @@ describe("compiled module maps", () => {expect(source).toContain("memoizeModuleNamespaceFactories");});- it("collects exactly the node binding table plus explicit remote bindings", async () => {+ it("collects exactly the runtime node bindings plus explicit remote bindings", async () => {const { manifest } = await compileFromMemory({model: "openai/gpt-5.4",tools: [{ name: "weather" }, { name: "echo" }],});- expect(collectModuleBindingsForManifest(manifest).map((entry) => entry.sourceId)).toEqual(- Object.keys(manifest.bindings).sort(),+ expect(+ collectRuntimeModuleBindingsForManifest(manifest).map((entry) => entry.sourceId),+ ).toEqual(+ Object.entries(manifest.bindings)+ .filter(([, binding]) => binding.usage.runtimeEntry)+ .map(([sourceId]) => sourceId)+ .sort(),);});@@ -86,6 +92,7 @@ describe("compiled module maps", () => {},logicalPath: "tools/renamed-mount__tool.ts",owner: { kind: "extension", namespace: "renamed-mount", packageName: "@acme/crm" },+ usage: { compile: true, runtimeEntry: true },};for (const sourceId of applicationSourceIds) {manifest.bindings[sourceId] = {@@ -96,6 +103,7 @@ describe("compiled module maps", () => {},logicalPath: manifest.bindings[sourceId]!.logicalPath,owner: { kind: "application" },+ usage: manifest.bindings[sourceId]!.usage,};}mocks.loadAuthoredModuleNamespace.mockClear();@@ -132,8 +140,14 @@ describe("compiled module maps", () => {parameters: { role: "derived" },},};+ manifest.bindings[configSourceId] = {+ ...manifest.bindings[configSourceId]!,+ usage: { ...manifest.bindings[configSourceId]!.usage, runtimeEntry: true },+ };- const ordered = collectModuleBindingsForManifest(manifest).map((entry) => entry.sourceId);+ const ordered = collectRuntimeModuleBindingsForManifest(manifest).map(+ (entry) => entry.sourceId,+ );const source = createCompiledModuleMapSource({manifest,moduleMapPath: "/app/.eve/compile/module-map.mjs",diff --git a/packages/eve/src/compiler/module-map.ts b/packages/eve/src/compiler/module-map.tsindex 61fb9b34f..444800061 100644--- a/packages/eve/src/compiler/module-map.ts+++ b/packages/eve/src/compiler/module-map.ts@@ -142,12 +142,15 @@ export async function createProgrammaticCompiledModuleMap(return { nodes };}-/** Returns every binding owned by one compiled node, including remote config modules. */-export function collectModuleBindingsForManifest(+/** Returns one compiled node's finalized runtime entries, including remote config modules. */+export function collectRuntimeModuleBindingsForManifest(manifest: CompiledAgentNodeManifest | CompiledAgentResources,): readonly BoundModule[] {- const modules = new Map<string, CompiledModuleBinding>(Object.entries(manifest.bindings));+ const modules = new Map<string, CompiledModuleBinding>(+ Object.entries(manifest.bindings).filter(([, binding]) => binding.usage.runtimeEntry),+ );for (const remote of manifest.remoteAgents) {+ if (!remote.binding.usage.runtimeEntry) continue;if (modules.has(remote.sourceId)) {throw new Error(`Remote agent binding "${remote.sourceId}" collides with a node binding.`);}@@ -204,13 +207,13 @@ function renderProgrammaticDependencies(function collectBoundNodeScopes(manifest: CompiledAgentManifest): readonly BoundNodeScope[] {return [{- modules: collectModuleBindingsForManifest(manifest),+ modules: collectRuntimeModuleBindingsForManifest(manifest),nodeId: ROOT_COMPILED_AGENT_NODE_ID,},...[...manifest.subagents].sort((left, right) => left.nodeId.localeCompare(right.nodeId)).map((subagent) => ({- modules: collectModuleBindingsForManifest(subagent.agent),+ modules: collectRuntimeModuleBindingsForManifest(subagent.agent),nodeId: subagent.nodeId,})),];diff --git a/packages/eve/src/compiler/node-source-state.ts b/packages/eve/src/compiler/node-source-state.tsindex 49d44ae11..441e931b7 100644--- a/packages/eve/src/compiler/node-source-state.ts+++ b/packages/eve/src/compiler/node-source-state.ts@@ -9,14 +9,15 @@ import type {ProjectedSubagentSource,} from "#compiler/project-sources.js";import {- createCompiledModuleBinding,+ createAgentModuleBinding,+ type AgentModuleBinding,type AgentModuleCandidate,type AgentSourceBacking,type AgentSourceCandidate,type AgentSourceDescriptor,type ComposedAgentModuleCandidates,- type CompiledModuleBinding,} from "#compiler/source-graph.js";+import type { NodeModuleEvaluationContext } from "#compiler/module-lifecycle.js";export interface ComposedNodeSourceGraph {composed: ComposedAgentModuleCandidates;@@ -27,19 +28,21 @@ export interface ComposedNodeSourceGraph {}export interface SelectedNodeConfig {- readonly binding: CompiledModuleBinding;+ readonly binding: AgentModuleBinding;readonly candidate: AgentModuleCandidate;readonly definition: unknown;readonly source: ModuleSourceRef;}export interface PhaseOneNodeSourceState {+ readonly evaluation: NodeModuleEvaluationContext;readonly graph: ComposedNodeSourceGraph;readonly selectedConfig: SelectedNodeConfig;}export interface FinalizedNodeSourceState extends ComposedNodeSourceGraph {- readonly bindings: Record<string, CompiledModuleBinding>;+ readonly bindings: Record<string, AgentModuleBinding>;+ readonly evaluation: NodeModuleEvaluationContext;}export function finalizeNodeSourceState(@@ -89,8 +92,9 @@ export function finalizeNodeSourceState((candidate): candidate is AgentModuleCandidate =>selectedSourceIds.has(candidate.sourceId) && candidate.backing.kind !== "resource",)- .map((candidate) => [candidate.sourceId, createCompiledModuleBinding(candidate)]),+ .map((candidate) => [candidate.sourceId, createAgentModuleBinding(candidate)]),);+ phaseOne.evaluation.setBindings(bindings);return {bindings,composed,@@ -105,6 +109,7 @@ export function finalizeNodeSourceState(subagentsBySourceId: new Map(projected.subagents.map((entry) => [entry.candidate.sourceId, entry]),),+ evaluation: phaseOne.evaluation,};}diff --git a/packages/eve/src/compiler/normalize-agent-config.ts b/packages/eve/src/compiler/normalize-agent-config.tsindex 691113f14..213d341fd 100644--- a/packages/eve/src/compiler/normalize-agent-config.ts+++ b/packages/eve/src/compiler/normalize-agent-config.ts@@ -21,7 +21,7 @@ import {loadModuleBackedDefinition,type ManifestCompileContext,} from "#compiler/normalize-helpers.js";-import type { CompiledModuleBinding } from "#compiler/source-graph.js";+import type { AgentModuleBinding } from "#compiler/source-graph.js";import { createCompiledBindingNamespaceLoader } from "#compiler/load-binding-namespace.js";type Mutable<T> = { -readonly [K in keyof T]: T[K] };@@ -34,7 +34,7 @@ export async function compileAgentConfig(manifest: AgentSourceManifest,context: ManifestCompileContext,options: {- readonly binding: CompiledModuleBinding;+ readonly binding: AgentModuleBinding;readonly definition?: unknown;readonly source: ModuleSourceRef;},@@ -292,7 +292,7 @@ async function normalizeAuthoredModelReference(input: {function formatAgentConfigModulePath(manifest: AgentSourceManifest,configModule: ModuleSourceRef,- binding: CompiledModuleBinding,+ binding: AgentModuleBinding,): string {if (binding.backing.kind === "programmatic") return configModule.logicalPath;return normalizeLogicalPath(diff --git a/packages/eve/src/compiler/normalize-helpers.ts b/packages/eve/src/compiler/normalize-helpers.tsindex 8a286001b..66bd316a7 100644--- a/packages/eve/src/compiler/normalize-helpers.ts+++ b/packages/eve/src/compiler/normalize-helpers.ts@@ -6,8 +6,8 @@ import { toErrorMessage } from "#shared/errors.js";import type { ModuleSourceRef } from "#shared/source-ref.js";import type { CompiledRuntimeModelCatalogLoader } from "#compiler/model-catalog.js";import {+ type AgentModuleBinding,type AgentSourceRegistry,- type CompiledModuleBinding,type AgentSourceOwner,type ProgrammaticModuleNamespace,} from "#compiler/source-graph.js";@@ -29,12 +29,12 @@ export interface ManifestCompileContext {}export interface ModuleBackedDefinitionLoadOptions {- readonly binding: CompiledModuleBinding;+ readonly binding: AgentModuleBinding;readonly loadNamespace: CompiledBindingNamespaceLoader;}export interface SourceDefinitionCompileOptions {- readonly binding?: CompiledModuleBinding;+ readonly binding?: AgentModuleBinding;readonly loadNamespace?: CompiledBindingNamespaceLoader;readonly owner: AgentSourceOwner;}@@ -59,7 +59,7 @@ export function requireModuleBackedDefinitionLoadOptions(* authored file failed.*/export async function loadModuleBackedDefinition(input: {- readonly binding: CompiledModuleBinding;+ readonly binding: AgentModuleBinding;readonly dependencyNamespaces?: Readonly<Record<string, ProgrammaticModuleNamespace>>;readonly displayPath?: string;readonly kind: string;diff --git a/packages/eve/src/compiler/normalize-manifest-helpers.ts b/packages/eve/src/compiler/normalize-manifest-helpers.tsindex 3593df167..39c2a9fbc 100644--- a/packages/eve/src/compiler/normalize-manifest-helpers.ts+++ b/packages/eve/src/compiler/normalize-manifest-helpers.ts@@ -140,6 +140,7 @@ export function createCompiledRemoteAgent(input: {backing: input.binding.backing,logicalPath,owner: input.owner,+ usage: input.binding.usage,};const node = {backing: { kind: "resource" as const, sourcePath: input.source.entryPath },diff --git a/packages/eve/src/compiler/normalize-manifest.test.ts b/packages/eve/src/compiler/normalize-manifest.test.tsindex 30e0474d3..02aa06fa7 100644--- a/packages/eve/src/compiler/normalize-manifest.test.ts+++ b/packages/eve/src/compiler/normalize-manifest.test.ts@@ -17,10 +17,17 @@ import { validateCompiledModuleMap } from "#compiler/validate-artifact.js";import { frameworkAgentSourceRegistry } from "#framework/sources/registry.js";import { defineAgent } from "#public/definitions/agent.js";import { defineChannel, GET, POST } from "#public/definitions/channel.js";+import { defineMcpClientConnection } from "#public/definitions/connections/mcp.js";import { defineHook } from "#public/definitions/hook.js";+import { defineInstructions } from "#public/definitions/instructions.js";+import { defineSchedule } from "#public/definitions/schedule.js";+import { defineSkill } from "#public/definitions/skill.js";import { resolveAgent } from "#runtime/resolve-agent.js";import { defineTool, disableTool } from "#tools/definition.js";import { defineMemory } from "#public/memory/index.js";+import { defineDynamic } from "#dynamic/definition.js";+import { experimental_workflow } from "#tools/workflow.js";+import { webSearch } from "#tools/provided/web-search.js";function manifest() {return createAgentSourceManifest({@@ -132,6 +139,123 @@ describe("compileAgentManifest source graph", () => {expect(order).toContain("tool");});+ it("classifies compile and runtime usage from normalized authored semantics", async () => {+ const sourceRegistry = registry([+ {+ logicalPath: "agent.ts",+ loadNamespace: async () => ({+ default: defineAgent({ model: "openai/gpt-5.4" }),+ }),+ },+ {+ logicalPath: "instructions/static.ts",+ loadNamespace: async () => ({+ default: defineInstructions({ content: "Static instructions." }),+ }),+ },+ {+ logicalPath: "instructions/dynamic.ts",+ loadNamespace: async () => ({+ default: defineDynamic({+ events: { "session.started": () => ({ content: "Dynamic instructions." }) },+ }),+ }),+ },+ {+ logicalPath: "skills/static.ts",+ loadNamespace: async () => ({+ default: defineSkill({ description: "Static skill.", markdown: "# Static\n" }),+ }),+ },+ {+ logicalPath: "skills/dynamic.ts",+ loadNamespace: async () => ({+ default: defineDynamic({+ events: {+ "session.started": () =>+ defineSkill({ description: "Dynamic skill.", markdown: "# Dynamic\n" }),+ },+ }),+ }),+ },+ {+ logicalPath: "schedules/prompt.ts",+ loadNamespace: async () => ({+ default: defineSchedule({ cron: "0 9 * * *", markdown: "Run the prompt." }),+ }),+ },+ {+ logicalPath: "schedules/handler.ts",+ loadNamespace: async () => ({+ default: defineSchedule({ cron: "0 10 * * *", run: async () => {} }),+ }),+ },+ {+ logicalPath: "tools/executable.ts",+ loadNamespace: async () => ({+ default: defineTool({ description: "Execute.", execute: () => null, inputSchema: {} }),+ }),+ },+ {+ logicalPath: "tools/dynamic.ts",+ loadNamespace: async () => ({+ default: defineDynamic({+ events: {+ "session.started": () =>+ defineTool({ description: "Dynamic.", execute: () => null, inputSchema: {} }),+ },+ }),+ }),+ },+ {+ logicalPath: "tools/workflow.ts",+ loadNamespace: async () => ({ default: experimental_workflow() }),+ },+ {+ logicalPath: "tools/web_search.ts",+ loadNamespace: async () => ({ default: webSearch({ provider: "parallel" }) }),+ },+ {+ logicalPath: "connections/linear.ts",+ loadNamespace: async () => ({+ default: defineMcpClientConnection({+ description: "Linear.",+ url: "https://mcp.linear.example",+ }),+ }),+ },+ {+ logicalPath: "hooks/audit.ts",+ loadNamespace: async () => ({+ default: defineHook({ events: { "session.started": async () => {} } }),+ }),+ },+ ]);++ const compiled = await compileAgentManifest(manifest(), {+ sourceRegistries: [sourceRegistry],+ });+ const usageByLogicalPath = Object.fromEntries(+ Object.values(compiled.bindings).map((binding) => [binding.logicalPath, binding.usage]),+ );++ expect(usageByLogicalPath).toMatchObject({+ "agent.ts": { compile: true, runtimeEntry: false },+ "connections/linear.ts": { compile: true, runtimeEntry: true },+ "hooks/audit.ts": { compile: true, runtimeEntry: true },+ "instructions/dynamic.ts": { compile: true, runtimeEntry: true },+ "instructions/static.ts": { compile: true, runtimeEntry: false },+ "schedules/handler.ts": { compile: true, runtimeEntry: true },+ "schedules/prompt.ts": { compile: true, runtimeEntry: false },+ "skills/dynamic.ts": { compile: true, runtimeEntry: true },+ "skills/static.ts": { compile: true, runtimeEntry: false },+ "tools/dynamic.ts": { compile: true, runtimeEntry: true },+ "tools/executable.ts": { compile: true, runtimeEntry: true },+ "tools/web_search.ts": { compile: true, runtimeEntry: false },+ "tools/workflow.ts": { compile: true, runtimeEntry: false },+ });+ });+it("projects the root node once and finalizes its filesystem bindings after config", async () => {let toolSourceIterations = 0;const discovered = manifest();@@ -163,6 +287,93 @@ describe("compileAgentManifest source graph", () => {externalDependencies: ["sharp"],kind: "filesystem",});+ expect(compiled.bindings["instrumentation.ts"]?.usage).toEqual({+ compile: false,+ runtimeEntry: true,+ });+ });++ it("classifies dynamic and source-backed model configs as runtime entries", async () => {+ const dynamicRegistry = registry([+ {+ logicalPath: "agent.ts",+ loadNamespace: async () => ({+ default: defineAgent({+ model: defineDynamic({+ events: { "session.started": () => "openai/gpt-5.4" },+ }),+ }),+ }),+ },+ ]);+ const dynamic = await compileAgentManifest(manifest(), {+ sourceRegistries: [dynamicRegistry],+ });+ expect(dynamic.bindings[dynamic.config.source.sourceId]?.usage).toEqual({+ compile: true,+ runtimeEntry: true,+ });++ const directModel = {+ doGenerate: async () => ({}),+ doStream: async () => ({}),+ modelId: "direct-model",+ provider: "test-provider",+ specificationVersion: "v3",+ } as never;+ const directRegistry = registry([+ {+ logicalPath: "agent.ts",+ loadNamespace: async () => ({+ default: defineAgent({ model: directModel, modelContextWindowTokens: 8_192 }),+ }),+ },+ ]);+ const direct = await compileAgentManifest(manifest(), {+ sourceRegistries: [directRegistry],+ });+ expect(direct.config.model?.source?.sourceId).toBe(direct.config.source.sourceId);+ expect(direct.bindings[direct.config.source.sourceId]?.usage).toEqual({+ compile: true,+ runtimeEntry: true,+ });+ });++ it("classifies extension mount initialization as runtime-only", async () => {+ const discovered = manifest();+ const extensionManifest = createAgentSourceManifest({+ agentId: "crm-extension",+ agentRoot: "/virtual/crm-extension/extension",+ appRoot: "/virtual/crm-extension",+ });+ discovered.extensions.push(createModuleSourceRef({ logicalPath: "extensions/crm.ts" }));+ discovered.resolvedExtensions.push({+ externalDependencies: [],+ manifest: extensionManifest,+ namespace: "crm",+ packageName: "@acme/crm",+ packageRoot: "/virtual/crm-extension",+ sourceRoot: extensionManifest.agentRoot,+ specifier: "@acme/crm/extension",+ });+ const sourceRegistry = registry([+ {+ logicalPath: "agent.ts",+ loadNamespace: async () => ({+ default: defineAgent({ model: "openai/gpt-5.4" }),+ }),+ },+ ]);++ const compiled = await compileAgentManifest(discovered, {+ sourceRegistries: [sourceRegistry],+ });+ const mount = compiled.extensionMounts[0]!;++ expect(compiled.bindings[mount.mountSourceId]?.usage).toEqual({+ compile: false,+ runtimeEntry: true,+ });});it("projects a local subagent node once", async () => {@@ -261,6 +472,14 @@ describe("compileAgentManifest source graph", () => {},urlPath: "/same/[name]",});+ expect(compiled.bindings[compiled.channelRoutes.effective[0]!.sourceId]?.usage).toEqual({+ compile: true,+ runtimeEntry: true,+ });+ expect(compiled.bindings[compiled.channelRoutes.shadowed[0]!.source.sourceId]?.usage).toEqual({+ compile: true,+ runtimeEntry: false,+ });expect(diagnostics).toContainEqual(expect.objectContaining({ code: "compile/channel-route-shadowed", severity: "warning" }),);@@ -429,6 +648,14 @@ describe("compileAgentManifest source graph", () => {slot: "profile",},});+ expect(compiled.bindings[memory.sourceId]?.usage).toEqual({+ compile: true,+ runtimeEntry: true,+ });+ expect(compiled.bindings[wrapper.sourceId]?.usage).toEqual({+ compile: true,+ runtimeEntry: true,+ });const moduleMap = await createProgrammaticCompiledModuleMap(compiled, [frameworkAgentSourceRegistry,@@ -518,23 +745,40 @@ describe("compileAgentManifest source graph", () => {});it("rejects stale programmatic revisions before loading a namespace", async () => {- const loader = vi.fn(async () => ({ default: defineAgent({ model: "openai/gpt-5.4" }) }));+ const configLoader = vi.fn(async () => ({+ default: defineAgent({ model: "openai/gpt-5.4" }),+ }));+ const loader = vi.fn(async () => ({+ default: defineTool({+ description: "Runtime entry.",+ execute: () => null,+ inputSchema: { type: "object" },+ }),+ }));const source = defineProgrammaticAgentSource({id: "revision-test",- modules: [{ loadNamespace: loader, logicalPath: "agent.ts" }],+ modules: [+ { loadNamespace: configLoader, logicalPath: "agent.ts" },+ { loadNamespace: loader, logicalPath: "tools/runtime.ts" },+ ],revision: "v1",});const sourceRegistry = createAgentSourceRegistry([{ applyTo: "root", source }]);const compiled = await compileAgentManifest(manifest(), {sourceRegistries: [sourceRegistry],});- const binding = compiled.bindings[compiled.config.source.sourceId]!;+ const binding = Object.values(compiled.bindings).find(+ (candidate) => candidate.logicalPath === "tools/runtime.ts",+ )!;const staleRegistry = createAgentSourceRegistry([{applyTo: "root",source: defineProgrammaticAgentSource({id: "revision-test",- modules: [{ loadNamespace: loader, logicalPath: "agent.ts" }],+ modules: [+ { loadNamespace: configLoader, logicalPath: "agent.ts" },+ { loadNamespace: loader, logicalPath: "tools/runtime.ts" },+ ],revision: "v2",}),},diff --git a/packages/eve/src/compiler/normalize-manifest.ts b/packages/eve/src/compiler/normalize-manifest.tsindex 49a3bb6bd..4c4bacecd 100644--- a/packages/eve/src/compiler/normalize-manifest.ts+++ b/packages/eve/src/compiler/normalize-manifest.ts@@ -28,7 +28,11 @@ 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 {+ markConfigRuntimeEntries,+ NodeModuleEvaluationContext,+} from "#compiler/module-lifecycle.js";+import { assertInstrumentationLayoutConfig } from "#compiler/instrumentation-layout-config.js";import { compileAgentConfig } from "#compiler/normalize-agent-config.js";import { compileChannelDefinition } from "#compiler/normalize-channel.js";import { compileConnectionDefinition } from "#compiler/normalize-connection.js";@@ -73,11 +77,12 @@ import { summarizeCompilerDiagnostics, type CompilerDiagnostic } from "#compilerimport { projectAgentSources, projectSelectedSources } from "#compiler/project-sources.js";import {composeAgentModuleCandidates,- createCompiledModuleBinding,+ createAgentModuleBinding,createProgrammaticModuleCandidates,describeAgentSourceCandidate,disableComposedCandidate,instantiateProgrammaticTemplate,+ isAgentModuleCandidate,type AgentModuleCandidate,type AgentSourceCandidate,type AgentSourceLayer,@@ -201,6 +206,7 @@ class AgentGraphCompiler {};}const state = finalizeNodeSourceState(phaseOne, externalDependencies);+ markConfigRuntimeEntries(config, state.evaluation);assertInstrumentationLayoutConfig(config, state);const resources = await this.compileResources(input, state);const children = await this.compileChildren(input, state, externalDependencies);@@ -254,9 +260,16 @@ class AgentGraphCompiler {if (normalized.kind === "remote") {assertRemoteAgentDefinitionHasNoLocalPackageEntries(source);+ const sourceId = phaseOne.selectedConfig.source.sourceId;+ phaseOne.evaluation.setBindings({ [sourceId]: phaseOne.selectedConfig.binding });+ phaseOne.evaluation.requireRuntimeEntry(sourceId);+ const binding = phaseOne.evaluation.finalizeBindings()[sourceId];+ if (binding === undefined) {+ throw new Error(`Remote subagent "${nodeId}" has no finalized config binding.`);+ }remoteAgents.push(createCompiledRemoteAgent({- binding: phaseOne.selectedConfig.binding,+ binding,definition: normalized,nodeId,owner: projected.owner,@@ -290,6 +303,11 @@ class AgentGraphCompiler {config = { ...config, build: { ...config.build, externalDependencies } };}const finalState = finalizeNodeSourceState(phaseOne, externalDependencies);+ if (config === undefined) {+ finalState.evaluation.requireRuntimeEntry(phaseOne.selectedConfig.source.sourceId);+ } else {+ markConfigRuntimeEntries(config, finalState.evaluation);+ }if (config !== undefined) assertInstrumentationLayoutConfig(config, finalState);const resources = await this.compileResources(childInput, finalState);const children = await this.compileChildren(childInput, finalState, externalDependencies);@@ -422,34 +440,42 @@ class AgentGraphCompiler {externalDependencies: readonly string[],): Promise<PhaseOneNodeSourceState> {const graph = this.composeNodeSources(input, externalDependencies);+ const evaluation = new NodeModuleEvaluationContext(this.registries);+ evaluation.setBindings(+ Object.fromEntries(+ [...graph.composed.selected.values()]+ .filter(isAgentModuleCandidate)+ .map((candidate) => [candidate.sourceId, createAgentModuleBinding(candidate)]),+ ),+ );return {+ evaluation,graph,- selectedConfig: await this.loadSelectedConfig(graph),+ selectedConfig: await this.loadSelectedConfig(graph, evaluation),};}- private async loadSelectedConfig(state: ComposedNodeSourceGraph): Promise<SelectedNodeConfig> {+ private async loadSelectedConfig(+ state: ComposedNodeSourceGraph,+ evaluation: NodeModuleEvaluationContext,+ ): Promise<SelectedNodeConfig> {const candidate = state.composed.selected.get("agent");- if (candidate === undefined || !isModuleCandidate(candidate)) {+ if (candidate === undefined || !isAgentModuleCandidate(candidate)) {throw new Error("Every local agent node requires a selected module-backed agent.ts source.");}- const binding = createCompiledModuleBinding(candidate);+ const binding = createAgentModuleBinding(candidate);const projected = state.sourcesBySourceId.get(candidate.sourceId);if (projected?.source.sourceKind !== "module") {throw new Error(`Selected agent config source "${candidate.sourceId}" was not projected.`);}const source = projected.source;- const loadNamespace = createCompiledBindingNamespaceLoader({- bindings: { [candidate.sourceId]: binding },- registries: this.registries,- });return {binding,candidate,definition: await loadModuleBackedDefinition({binding,kind: "agent config",- loadNamespace,+ loadNamespace: evaluation.loadNamespace,source,}),source,@@ -476,10 +502,7 @@ class AgentGraphCompiler {let workflowTool: CompiledWorkflowToolDefinition | undefined;let webSearchProvider: WebSearchProvider | undefined;const selectedSourceIds = collectSelectedSourceIds(state.composed);- const loadNamespace = createCompiledBindingNamespaceLoader({- bindings: state.bindings,- registries: this.registries,- });+ const loadNamespace = state.evaluation.loadNamespace;for (const candidate of state.orderedCandidates) {if (!selectedSourceIds.has(candidate.sourceId)) continue;@@ -514,6 +537,7 @@ class AgentGraphCompiler {loadNamespace,}),);+ state.evaluation.requireRuntimeEntry(candidate.sourceId);break;case "hook":hooks.push(@@ -522,6 +546,7 @@ class AgentGraphCompiler {loadNamespace,}),);+ state.evaluation.requireRuntimeEntry(candidate.sourceId);break;case "instructions": {const result = await compileInstructionsEntry(@@ -530,11 +555,15 @@ class AgentGraphCompiler {options,);if (result.kind === "instructions") instructions.push(result.definition);- else dynamicInstructions.push(result.definition);+ else {+ dynamicInstructions.push(result.definition);+ state.evaluation.requireRuntimeEntry(candidate.sourceId);+ }break;}case "instrumentation":instrumentation = entry.source;+ state.evaluation.requireRuntimeEntry(candidate.sourceId);break;case "memory":memories.push(@@ -543,22 +572,36 @@ class AgentGraphCompiler {loadNamespace,}),);+ state.evaluation.requireRuntimeEntry(candidate.sourceId);break;case "sandbox":sandbox = await compileSandboxDefinition(input.manifest.agentRoot, entry.source, {binding: binding!,loadNamespace,});+ if (!sandbox.inheritsParent) {+ state.evaluation.requireRuntimeEntry(candidate.sourceId);+ }break;- case "schedule":- schedules.push(- await compileScheduleDefinition(input.manifest.agentRoot, entry.source, options),+ case "schedule": {+ const schedule = await compileScheduleDefinition(+ input.manifest.agentRoot,+ entry.source,+ options,);+ schedules.push(schedule);+ if (schedule.sourceKind === "module" && schedule.hasRun) {+ state.evaluation.requireRuntimeEntry(candidate.sourceId);+ }break;+ }case "skill": {const result = await compileSkillSource(input.manifest.agentRoot, entry.source, options);if (result.kind === "skill") skills.push(result.definition);- else dynamicSkills.push(withExtensionNamespace(result.definition, candidate.owner));+ else {+ dynamicSkills.push(withExtensionNamespace(result.definition, candidate.owner));+ state.evaluation.requireRuntimeEntry(candidate.sourceId);+ }break;}case "tool": {@@ -570,9 +613,12 @@ class AgentGraphCompiler {state.composed = disableComposedCandidate({ candidate, composed: state.composed });delete state.bindings[candidate.sourceId];selectedSourceIds.delete(candidate.sourceId);- } else if (result.kind === "tool") tools.push(result.definition);- else if (result.kind === "dynamic-tool") {+ } else if (result.kind === "tool") {+ tools.push(result.definition);+ state.evaluation.requireRuntimeEntry(candidate.sourceId);+ } else if (result.kind === "dynamic-tool") {dynamicTools.push(withExtensionNamespace(result.definition, candidate.owner));+ state.evaluation.requireRuntimeEntry(candidate.sourceId);} else if (result.kind === "workflow-tool") {assertRootOwnedSpecialTool(candidate as AgentModuleCandidate, "Workflow");workflowTool = { ...entry.source, maxSubagents: result.maxSubagents };@@ -606,17 +652,25 @@ class AgentGraphCompiler {]),),});+ for (const channel of channelRoutes.effective) {+ state.evaluation.requireRuntimeEntry(channel.sourceId);+ }+ const extensionMounts = compileExtensionMounts(input.manifest, state.composed);+ for (const mount of extensionMounts) {+ state.evaluation.requireRuntimeEntry(mount.mountSourceId);+ }+ const bindings = state.evaluation.finalizeBindings();return createCompiledAgentResources({agentRoot: input.manifest.agentRoot,appRoot: input.manifest.appRoot,- bindings: state.bindings,+ bindings,channelRoutes,connections,diagnosticsSummary: summarizeCompilerDiagnostics(this.diagnostics),dynamicInstructions,dynamicSkills,dynamicTools,- extensionMounts: compileExtensionMounts(input.manifest, state.composed),+ extensionMounts,hooks,memories,instructions,@@ -637,21 +691,3 @@ class AgentGraphCompiler {});}}--function isModuleCandidate(candidate: AgentSourceCandidate): candidate is AgentModuleCandidate {- return candidate.backing.kind !== "resource";-}--function assertInstrumentationLayoutConfig(- config: CompiledAgentDefinition,- state: FinalizedNodeSourceState,-): void {- if (- config.experimental?.instrumentationProviders === true &&- state.composed.selected.has("instrumentation")- ) {- throw new Error(- "A selected instrumentation.ts source cannot be used with experimental.instrumentationProviders. Move the declaration into the instrumentation/ provider directory.",- );- }-}diff --git a/packages/eve/src/compiler/normalize-sandbox.scenario.test.ts b/packages/eve/src/compiler/normalize-sandbox.scenario.test.tsindex 9d4a10797..8f68e5968 100644--- a/packages/eve/src/compiler/normalize-sandbox.scenario.test.ts+++ b/packages/eve/src/compiler/normalize-sandbox.scenario.test.ts@@ -51,9 +51,14 @@ describe("sandbox compilation", () => {appRoot: app.appRoot,});const manifest = await compileAgentManifest(discovered.manifest);- expect(manifest.subagents[0]?.agent).toMatchObject({+ const child = manifest.subagents[0]!.agent;+ expect(child).toMatchObject({sandbox: { inheritsParent: true },workspaceResourceRoot: { rootEntries: ["bar.txt"] },});+ expect(child.bindings[child.sandbox.sourceId]?.usage).toEqual({+ compile: true,+ runtimeEntry: false,+ });});});diff --git a/packages/eve/src/compiler/remote-agent-node.ts b/packages/eve/src/compiler/remote-agent-node.tsindex c6a24fe32..582efb1a4 100644--- a/packages/eve/src/compiler/remote-agent-node.ts+++ b/packages/eve/src/compiler/remote-agent-node.ts@@ -78,6 +78,7 @@ export const compiledRemoteAgentNodeSchema: z.ZodType<CompiledRemoteAgentNode> =}).strict(),]),+ usage: z.object({ compile: z.boolean(), runtimeEntry: z.boolean() }).strict(),}).strict(),description: z.string(),diff --git a/packages/eve/src/compiler/source-graph.ts b/packages/eve/src/compiler/source-graph.tsindex e79fc2b3e..3a0944807 100644--- a/packages/eve/src/compiler/source-graph.ts+++ b/packages/eve/src/compiler/source-graph.ts@@ -178,12 +178,22 @@ export interface AgentModuleCandidate {readonly sourceId: string;}-export interface CompiledModuleBinding {+export interface AgentModuleBinding {readonly backing: AgentModuleBacking;readonly logicalPath: string;readonly owner: AgentSourceOwner;}+export interface CompiledModuleBinding extends AgentModuleBinding {+ /** Compiler-owned namespace usage for this selected binding. */+ readonly usage: {+ /** The compiler evaluated this namespace while normalizing the node. */+ readonly compile: boolean;+ /** The namespace is an entry in the runtime module map. */+ readonly runtimeEntry: boolean;+ };+}+export interface AgentSourceDescriptor {readonly backing: AgentSourceBacking;readonly form: AgentSourceForm;@@ -205,6 +215,12 @@ export interface AgentResourceCandidate {export type AgentSourceCandidate = AgentModuleCandidate | AgentResourceCandidate;+export function isAgentModuleCandidate(+ candidate: AgentSourceCandidate,+): candidate is AgentModuleCandidate {+ return candidate.backing.kind !== "resource";+}+export type AgentSourceCompositionEntry =| {readonly kind: "shadowed";@@ -484,9 +500,7 @@ export function disableComposedCandidate(input: {};}-export function createCompiledModuleBinding(- candidate: AgentModuleCandidate,-): CompiledModuleBinding {+export function createAgentModuleBinding(candidate: AgentModuleCandidate): AgentModuleBinding {return Object.freeze({backing: candidate.backing,logicalPath: candidate.logicalPath,diff --git a/packages/eve/src/compiler/validate-artifact.ts b/packages/eve/src/compiler/validate-artifact.tsindex d6c2068fe..01be414d4 100644--- a/packages/eve/src/compiler/validate-artifact.ts+++ b/packages/eve/src/compiler/validate-artifact.ts@@ -8,7 +8,7 @@ import type {import { ROOT_COMPILED_AGENT_NODE_ID } from "#compiler/manifest.js";import type { CompiledModuleBinding } from "#compiler/source-graph.js";import type { CompiledModuleMap } from "#compiler/module-map.js";-import { collectModuleBindingsForManifest } from "#compiler/module-map.js";+import { collectRuntimeModuleBindingsForManifest } from "#compiler/module-map.js";import { HOST_HTTP_INVENTORY } from "#framework/host-inventory.js";type CompiledNode = CompiledAgentNodeManifest | CompiledAgentResources;@@ -89,14 +89,16 @@ export function validateCompiledModuleMap(const expected = new Map<string, Set<string>>([["__root__",- new Set(collectModuleBindingsForManifest(manifest).map((binding) => binding.sourceId)),+ new Set(collectRuntimeModuleBindingsForManifest(manifest).map((binding) => binding.sourceId)),],...manifest.subagents.map((subagent) =>[subagent.nodeId,new Set(- collectModuleBindingsForManifest(subagent.agent).map((binding) => binding.sourceId),+ collectRuntimeModuleBindingsForManifest(subagent.agent).map(+ (binding) => binding.sourceId,+ ),),] as const,),@@ -250,6 +252,9 @@ function validateBinding(logicalPath: string,binding: CompiledModuleBinding,): void {+ if (!binding.usage.compile && !binding.usage.runtimeEntry) {+ fail(`compiled binding "${sourceId}" has no compile or runtime usage`);+ }if (binding.logicalPath !== logicalPath) {fail(`compiled binding "${sourceId}" targets "${binding.logicalPath}", not "${logicalPath}"`);}@@ -287,6 +292,14 @@ function validateProgrammaticBindingDependencies(`programmatic binding "${sourceId}" depends on missing binding "${dependencySourceId}"`,);}+ if (+ binding.usage.runtimeEntry &&+ bindings[dependencySourceId]?.usage.runtimeEntry !== true+ ) {+ fail(+ `runtime binding "${sourceId}" depends on non-runtime binding "${dependencySourceId}"`,+ );+ }visit(dependencySourceId);}}diff --git a/packages/eve/src/execution/tasks/parent/tool-execution.integration.test.ts b/packages/eve/src/execution/tasks/parent/tool-execution.integration.test.tsindex 2f907e8c1..b6362c4d0 100644--- a/packages/eve/src/execution/tasks/parent/tool-execution.integration.test.ts+++ b/packages/eve/src/execution/tasks/parent/tool-execution.integration.test.ts@@ -62,6 +62,7 @@ describe("background subagent tool execution", () => {},logicalPath: "subagents/reviewer.ts",owner: { kind: "application" },+ usage: { compile: true, runtimeEntry: true },},description: "Remote reviewer",entryPath: "/virtual/eve-memory-app/agent/subagents/reviewer.ts",diff --git a/packages/eve/src/framework/sources/registry.ts b/packages/eve/src/framework/sources/registry.tsindex d205bd1fa..8cc16aef9 100644--- a/packages/eve/src/framework/sources/registry.ts+++ b/packages/eve/src/framework/sources/registry.ts@@ -9,7 +9,7 @@ import {type ProgrammaticModuleNamespace,} from "#compiler/source-graph.js";-const revision = `eve@${resolveInstalledPackageInfo().version}:compiled-manifest-v43`;+const revision = `eve@${resolveInstalledPackageInfo().version}:compiled-manifest-v44`;const localDefaults = defineProgrammaticAgentSource({id: "eve:defaults",diff --git a/packages/eve/src/internal/application/compiled-artifacts.ts b/packages/eve/src/internal/application/compiled-artifacts.tsindex 91c34ed15..2a8940479 100644--- a/packages/eve/src/internal/application/compiled-artifacts.ts+++ b/packages/eve/src/internal/application/compiled-artifacts.ts@@ -3,7 +3,6 @@ import { join } from "node:path";import type { CompileMetadata } from "#compiler/artifacts.js";import type { CompileAgentResult } from "#compiler/compile-agent.js";-import { createCompiledModuleMapSource } from "#compiler/module-map.js";import { stringifyEsmImportSpecifier } from "#internal/application/import-specifier.js";import {resolvePackageCompiledFilePath,@@ -11,14 +10,15 @@ import {} from "#internal/application/package.js";import { buildPackageUserAgent } from "#internal/user-agent.js";import type { AgentWorkflowWorldDefinition } from "#shared/agent-definition.js";+import {+ prepareAuthoredRuntimeModules,+ type PreparedAuthoredRuntimeModules,+} from "#internal/authored-runtime-modules.js";import {readMaterializedAuthoredModuleIndex,type MaterializedInstrumentation,} from "#internal/materialized-authored-modules.js";-import {- resolveInstrumentationLayout,- type InstrumentationLayout,-} from "#internal/instrumentation-layout.js";+import { type InstrumentationLayout } from "#internal/instrumentation-layout.js";import { usesParentDevelopmentWorkflowWorld } from "#internal/workflow/development-world-protocol.js";import { resolveWorkflowWorldImport } from "#internal/workflow/world-target.js";@@ -49,16 +49,16 @@ export interface GeneratedCompiledArtifactsFiles {/** Nitro plugin that installs the selected vendored Workflow world. */workflowWorldPluginPath: string;/**- * Optional Nitro plugin that imports the authored instrumentation modules- * from the application when present.+ * Optional Nitro plugin that imports prepared instrumentation runtime+ * entries when present.*/instrumentationPluginPath?: string;/** Layout identity used by dev plugin selection and structural fingerprinting. */instrumentationLayout?: GeneratedInstrumentationLayout;/**- * Absolute paths to the authored instrumentation modules when present — one- * for the file layout, one per provider in the directory layout. Nitro uses these- * to preserve each module's side effects during bundling.+ * Absolute paths to prepared instrumentation modules when present — one for+ * the file layout, one per provider in the directory layout. Nitro uses these+ * to preserve each module's side effects during packaging.*/instrumentationSourcePaths?: readonly string[];}@@ -76,25 +76,23 @@ export async function writeCompiledArtifactsFiles(input: {outDir: string;}): Promise<GeneratedCompiledArtifactsFiles> {const bootstrapPath = join(input.outDir, "compiled-artifacts-bootstrap.mjs");+ const moduleMapPath = join(input.outDir, "compiled-artifacts-module-map.mjs");const instrumentationPluginPath = join(input.outDir, "compiled-artifacts-instrumentation.mjs");const workflowWorldPluginPath = join(input.outDir, "compiled-artifacts-workflow-world.mjs");- const providersEnabled =- input.compileResult.manifest.config.experimental?.instrumentationProviders ?? false;- const providerLayout = providersEnabled- ? resolveInstrumentationLayout({- agentRoot: input.compileResult.manifest.agentRoot,- providersEnabled: true,- })- : undefined;+ const prepared = await prepareAuthoredRuntimeModules({+ manifest: input.compileResult.manifest,+ moduleMapPath: input.compileResult.paths.moduleMapPath,+ });await mkdir(input.outDir, { recursive: true });+ await writeFile(moduleMapPath, prepared.moduleMapCode);await writeFile(bootstrapPath,- await createCompiledArtifactsBootstrapSource({+ createCompiledArtifactsBootstrapSource({compileResult: input.compileResult,installModulePath: resolvePackageSourceFilePath("src/runtime/loaders/bundled-artifacts.ts"),- moduleMapPath: bootstrapPath,metadata: input.compileResult.metadata,+ moduleMapImportPath: moduleMapPath,}),);await writeFile(@@ -117,16 +115,17 @@ export async function writeCompiledArtifactsFiles(input: {instrumentationPluginPath,createInstrumentationPluginSource({agentName: input.compileResult.manifest.config.name,- layout: { kind: "module-map", moduleMapPath: bootstrapPath, sourceId },+ layout: { kind: "module-map", moduleMapPath, sourceId },}),);generatedArtifacts.instrumentationPluginPath = instrumentationPluginPath;generatedArtifacts.instrumentationLayout = { kind: "file" };- const binding = input.compileResult.manifest.bindings[sourceId];- if (binding?.backing.kind === "filesystem") {- generatedArtifacts.instrumentationSourcePaths = [binding.backing.sourcePath];- }- } else if (providerLayout !== undefined) {+ generatedArtifacts.instrumentationSourcePaths = [moduleMapPath];+ } else if (prepared.instrumentation !== undefined) {+ const providerLayout = await writePreparedInstrumentation({+ instrumentation: prepared.instrumentation,+ outDir: input.outDir,+ });await writeFile(instrumentationPluginPath,createInstrumentationPluginSource({@@ -142,6 +141,23 @@ export async function writeCompiledArtifactsFiles(input: {return generatedArtifacts;}+async function writePreparedInstrumentation(input: {+ readonly instrumentation: NonNullable<PreparedAuthoredRuntimeModules["instrumentation"]>;+ readonly outDir: string;+}): Promise<InstrumentationLayout> {+ const writeOne = async (sourceId: string, code: string): Promise<string> => {+ const path = join(input.outDir, `compiled-artifacts-instrumentation-${sourceId}.mjs`);+ await writeFile(path, code);+ return path;+ };++ const modulePathsBySlot: Record<string, string> = {};+ for (const [slot, code] of Object.entries(input.instrumentation.moduleCodeBySlot)) {+ modulePathsBySlot[slot] = await writeOne(slot, code);+ }+ return { kind: "directory", modulePathsBySlot };+}+function instrumentationSourcePathsOf(layout: InstrumentationLayout): readonly string[] {return layout.kind === "file" ? [layout.modulePath] : Object.values(layout.modulePathsBySlot);}@@ -273,41 +289,28 @@ function createDevelopmentCompiledArtifactsBootstrapSource(agentName: string): s].join("\n");}-function stripCompiledModuleMapDefaultExport(source: string): string {- return source.replace(/\nexport default moduleMap;\n?$/, "\n");-}--export async function createCompiledArtifactsBootstrapSource(input: {+export function createCompiledArtifactsBootstrapSource(input: {compileResult: CompileAgentResult;installModulePath: string;metadata: CompileMetadata;- moduleMapPath: string;-}): Promise<string> {+ moduleMapImportPath: string;+}): string {const agentName = input.compileResult.manifest.config.name;- const moduleMapSource = stripCompiledModuleMapDefaultExport(- createCompiledModuleMapSource({- importSpecifierStyle: "absolute",- manifest: input.compileResult.manifest,- moduleMapPath: input.moduleMapPath,- programmaticLoaderImportSpecifier: resolvePackageSourceFilePath(- "src/internal/programmatic-source-loader.ts",- ),- }),- ).trim();return ["// Generated by eve. Do not edit by hand.",+ `import moduleMap from ${stringifyEsmImportSpecifier(input.moduleMapImportPath)};`,`import { installBundledCompiledArtifacts } from ${stringifyEsmImportSpecifier(input.installModulePath)};`,`import { installEveWorkflowQueueNamespace } from ${stringifyEsmImportSpecifier(resolvePackageSourceFilePath("src/internal/workflow/queue-namespace.ts"))};`,"",`installEveWorkflowQueueNamespace(${JSON.stringify(agentName)});`,"",- moduleMapSource,- "",`const metadata = ${JSON.stringify(input.metadata, null, 2)};`,"",`const manifest = ${JSON.stringify(input.compileResult.manifest, null, 2)};`,"",+ "export { moduleMap };",+ "","export function installCompiledArtifactsBootstrap() {"," installBundledCompiledArtifacts({"," manifest,",diff --git a/packages/eve/src/internal/authored-asset-import-plugin.ts b/packages/eve/src/internal/authored-asset-import-plugin.tsindex 63f7bc83d..bb7a9705f 100644--- a/packages/eve/src/internal/authored-asset-import-plugin.ts+++ b/packages/eve/src/internal/authored-asset-import-plugin.ts@@ -1,5 +1,6 @@+import { realpathSync } from "node:fs";import { readFile } from "node:fs/promises";-import { dirname, extname, isAbsolute, resolve } from "node:path";+import { dirname, extname, isAbsolute, relative, resolve } from "node:path";const AUTHORED_ASSET_CODE_EXTENSIONS = [".ts",@@ -15,9 +16,14 @@ const AUTHORED_ASSET_CODE_EXTENSIONS = [/*** Creates the Rollup-compatible plugin that gives authored modules a small- * asset-module surface for non-code relative imports.+ * asset-module surface for non-code relative imports inside the authored+ * package. Assets may sit outside the agent directory, but not outside the+ * package that owns it.*/-export function createAuthoredAssetImportPlugin(): Record<string, unknown> {+export function createAuthoredAssetImportPlugin(input: {+ readonly packageRoot: string;+}): Record<string, unknown> {+ const packageRoot = toCanonicalPath(input.packageRoot);return {name: "eve-authored-asset-import",resolveId(source: string, importer: string | undefined) {@@ -27,8 +33,14 @@ export function createAuthoredAssetImportPlugin(): Record<string, unknown> {const { path, suffix } = splitImportSuffix(source);const resolvedPath = isAbsolute(path) ? path : resolve(dirname(importer), path);+ const canonicalPath = toCanonicalPath(resolvedPath);+ if (!isPathInsideOrEqual(canonicalPath, packageRoot)) {+ throw new Error(+ `Authored asset import "${source}" from "${importer}" resolves outside package root "${packageRoot}".`,+ );+ }- return `${resolvedPath}${suffix}`;+ return `${canonicalPath}${suffix}`;},async load(id: string) {const { path, suffix } = splitImportSuffix(id);@@ -64,6 +76,20 @@ export function createAuthoredAssetImportPlugin(): Record<string, unknown> {};}+function isPathInsideOrEqual(path: string, directory: string): boolean {+ const relativePath = relative(directory, resolve(path));+ return relativePath === "" || (!relativePath.startsWith("..") && !isAbsolute(relativePath));+}++function toCanonicalPath(path: string): string {+ const absolutePath = resolve(path);+ try {+ return realpathSync.native(absolutePath);+ } catch {+ return absolutePath;+ }+}+async function readAssetText(path: string): Promise<string | undefined> {try {return await readFile(path, "utf8");diff --git a/packages/eve/src/internal/authored-module-loader.scenario.test.ts b/packages/eve/src/internal/authored-module-loader.scenario.test.tsindex 2ab04383e..d9c048774 100644--- a/packages/eve/src/internal/authored-module-loader.scenario.test.ts+++ b/packages/eve/src/internal/authored-module-loader.scenario.test.ts@@ -1,6 +1,6 @@import { mkdir, mkdtemp, realpath, rm, symlink, writeFile } from "node:fs/promises";import { tmpdir } from "node:os";-import { join } from "node:path";+import { basename, join } from "node:path";import { describe, expect, it } from "vitest";@@ -1222,6 +1222,34 @@ describe("loadAuthoredModuleNamespace", () => {});});+ it("rejects asset imports outside the authored package", async () => {+ const app = await scenarioApp({+ files: {+ "agent/tools/outside_asset.ts": "export default {};\n",+ },+ name: "outside-asset-import",+ });+ const outsideFileName = `${basename(app.appRoot)}.txt`;+ const outsidePath = join(app.appRoot, "..", outsideFileName);+ const modulePath = join(app.appRoot, "agent", "tools", "outside_asset.ts");++ try {+ await Promise.all([+ writeFile(outsidePath, "outside\n"),+ writeFile(+ modulePath,+ `import value from "../../../${outsideFileName}?raw";\nexport default value;\n`,+ ),+ ]);++ await expect(loadAuthoredModuleNamespace(modulePath)).rejects.toThrow(+ /resolves outside package root/,+ );+ } finally {+ await rm(outsidePath, { force: true });+ }+ });+it("recovers in the same process once a missing package is installed", async () => {// Regression: bundling used to emit unresolvable package imports as// bare externals, so the loader handed Node an import that could notdiff --git a/packages/eve/src/internal/authored-module-loader.ts b/packages/eve/src/internal/authored-module-loader.tsindex c442cb49f..3695a6d51 100644--- a/packages/eve/src/internal/authored-module-loader.ts+++ b/packages/eve/src/internal/authored-module-loader.ts@@ -25,6 +25,8 @@ import {type RolldownResolveContext,} from "#internal/authored-package-boundary.js";import { expectObjectRecord } from "#internal/authored-module.js";+import { normalizeEsmImportSpecifier } from "#internal/application/import-specifier.js";+import { resolvePackageSourceFilePath } from "#internal/application/package.js";import {buildSingleRolldownChunk,buildWithNitroRolldown,@@ -204,7 +206,7 @@ export async function bundleExtensionDistributionGraph(input: {const plugins = [createAuthoredDirectiveGuardPlugin(),createAuthoredRelativeExtensionResolverPlugin({ extensions: RESOLVE_EXTENSIONS }),- createAuthoredAssetImportPlugin(),+ createAuthoredAssetImportPlugin({ packageRoot: input.packageRoot }),createAuthoredPackageTsConfigPathsPlugin({appPackageRoot: input.packageRoot,extensions: RESOLVE_EXTENSIONS,@@ -259,6 +261,9 @@ export async function bundleAuthoredModuleMapForGeneration(input: {readonly moduleMapPath: string;}): Promise<string> {const packageRoot = resolveAuthoredPackageRoot(input.manifest.agentRoot);+ const programmaticLoaderImportSpecifier = resolvePackageSourceFilePath(+ "src/internal/programmatic-source-loader.ts",+ );const externalDependencies = normalizeExternalDependencies([...(input.manifest.config.build?.externalDependencies ?? []),...input.manifest.subagents.flatMap((subagent) =>@@ -270,6 +275,7 @@ export async function bundleAuthoredModuleMapForGeneration(input: {const moduleMapSource = createCompiledModuleMapSource({manifest: input.manifest,moduleMapPath: input.moduleMapPath,+ programmaticLoaderImportSpecifier,});const extensionScopePlugin = createExtensionScopePlugin([input.manifest, ...input.manifest.subagents.map((subagent) => subagent.agent)].flatMap(@@ -285,11 +291,12 @@ export async function bundleAuthoredModuleMapForGeneration(input: {id: input.moduleMapPath,source: moduleMapSource,}),+ createExternalRuntimeImportPlugin(programmaticLoaderImportSpecifier),createDynamicCapabilityTransformPlugin(),createAuthoredDirectiveGuardPlugin(),extensionScopePlugin,createAuthoredRelativeExtensionResolverPlugin({ extensions: RESOLVE_EXTENSIONS }),- createAuthoredAssetImportPlugin(),+ createAuthoredAssetImportPlugin({ packageRoot }),createAuthoredPackageTsConfigPathsPlugin({appPackageRoot: packageRoot,extensions: RESOLVE_EXTENSIONS,@@ -321,6 +328,18 @@ export async function bundleAuthoredModuleMapForGeneration(input: {}}+function createExternalRuntimeImportPlugin(importSpecifier: string): Record<string, unknown> {+ const normalizedImportSpecifier = normalizeEsmImportSpecifier(importSpecifier);+ return {+ name: "eve-external-runtime-import",+ resolveId(id: string) {+ return id === normalizedImportSpecifier+ ? { external: true, id: normalizedImportSpecifier }+ : undefined;+ },+ };+}+function createVirtualGenerationModuleMapPlugin(input: {readonly id: string;readonly source: string;@@ -403,7 +422,7 @@ async function buildAuthoredModuleBundle(? null: createFixedNamespaceScopePlugin(options.extensionScopeNamespace),createAuthoredRelativeExtensionResolverPlugin({ extensions: RESOLVE_EXTENSIONS }),- createAuthoredAssetImportPlugin(),+ createAuthoredAssetImportPlugin({ packageRoot }),createAuthoredPackageTsConfigPathsPlugin({appPackageRoot: packageRoot,extensions: RESOLVE_EXTENSIONS,diff --git a/packages/eve/src/internal/authored-module-map-loader.ts b/packages/eve/src/internal/authored-module-map-loader.tsindex 0e4d72144..d2bdee5a9 100644--- a/packages/eve/src/internal/authored-module-map-loader.ts+++ b/packages/eve/src/internal/authored-module-map-loader.ts@@ -9,7 +9,7 @@ import type {import { ROOT_COMPILED_AGENT_NODE_ID } from "#compiler/manifest.js";import { memoizeModuleNamespaceFactories } from "#compiler/source-graph.js";import {- collectModuleBindingsForManifest,+ collectRuntimeModuleBindingsForManifest,compiledModuleMapSchema,resolveCompiledModuleExtensionScopeNamespace,type CompiledModuleMap,@@ -74,7 +74,7 @@ async function hydrateCompiledNodeScope();const container = globalThis as Record<symbol, unknown>;const modules: CompiledModuleMap["nodes"][string]["modules"] = {};- for (const { binding, sourceId } of collectModuleBindingsForManifest(manifest)) {+ for (const { binding, sourceId } of collectRuntimeModuleBindingsForManifest(manifest)) {const mountConfigScope = mountScopes.get(sourceId);if (mountConfigScope !== undefined) container[EXT_CONFIG_SCOPE] = mountConfigScope;try {diff --git a/packages/eve/src/internal/authored-runtime-modules.ts b/packages/eve/src/internal/authored-runtime-modules.tsnew file mode 100644index 000000000..d349eb3b4--- /dev/null+++ b/packages/eve/src/internal/authored-runtime-modules.ts@@ -0,0 +1,42 @@+import type { CompiledAgentManifest } from "#compiler/manifest.js";+import {+ bundleAuthoredModuleForGeneration,+ bundleAuthoredModuleMapForGeneration,+} from "#internal/authored-module-loader.js";+import { resolveInstrumentationLayout } from "#internal/instrumentation-layout.js";++interface PreparedAuthoredRuntimeInstrumentation {+ readonly kind: "directory";+ readonly moduleCodeBySlot: Readonly<Record<string, string>>;+}++export interface PreparedAuthoredRuntimeModules {+ readonly instrumentation?: PreparedAuthoredRuntimeInstrumentation;+ readonly moduleMapCode: string;+}++/** Builds the authored runtime graph before a development or production host packages it. */+export async function prepareAuthoredRuntimeModules(input: {+ readonly manifest: CompiledAgentManifest;+ readonly moduleMapPath: string;+}): Promise<PreparedAuthoredRuntimeModules> {+ const moduleMapCode = await bundleAuthoredModuleMapForGeneration(input);+ const providersEnabled = input.manifest.config.experimental?.instrumentationProviders ?? false;+ const layout = providersEnabled+ ? resolveInstrumentationLayout({ agentRoot: input.manifest.agentRoot, providersEnabled: true })+ : undefined;+ const externalDependencies = input.manifest.config.build?.externalDependencies ?? [];+ const bundleInstrumentationModule = async (sourcePath: string): Promise<string> =>+ await bundleAuthoredModuleForGeneration(sourcePath, { externalDependencies });+ let instrumentation: PreparedAuthoredRuntimeInstrumentation | undefined;++ if (layout?.kind === "directory") {+ const moduleCodeBySlot: Record<string, string> = {};+ for (const [slot, sourcePath] of Object.entries(layout.modulePathsBySlot)) {+ moduleCodeBySlot[slot] = await bundleInstrumentationModule(sourcePath);+ }+ instrumentation = { kind: "directory", moduleCodeBySlot };+ }++ return instrumentation === undefined ? { moduleMapCode } : { instrumentation, moduleMapCode };+}diff --git a/packages/eve/src/internal/materialized-authored-modules.ts b/packages/eve/src/internal/materialized-authored-modules.tsindex e228b6e1f..1987bbee1 100644--- a/packages/eve/src/internal/materialized-authored-modules.ts+++ b/packages/eve/src/internal/materialized-authored-modules.ts@@ -5,12 +5,8 @@ import { join, relative, sep } from "node:path";import type { CompiledAgentManifest } from "#compiler/manifest.js";import { COMPILED_AGENT_MANIFEST_KIND, ROOT_COMPILED_AGENT_NODE_ID } from "#compiler/manifest.js";-import {- bundleAuthoredModuleForGeneration,- bundleAuthoredModuleMapForGeneration,-} from "#internal/authored-module-loader.js";+import type { PreparedAuthoredRuntimeModules } from "#internal/authored-runtime-modules.js";import { serializeCompiledManifestForFingerprint } from "#internal/compiled-manifest-fingerprint.js";-import { resolveInstrumentationLayout } from "#internal/instrumentation-layout.js";const MATERIALIZED_MODULES_DIRECTORY = "authored-modules";const MATERIALIZED_MODULES_INDEX = "authored-modules.json";@@ -30,45 +26,8 @@ export interface MaterializedAuthoredModuleIndex {readonly version: 3;}-type PreparedMaterializedInstrumentation =- | { readonly kind: "file"; readonly moduleCode: string }- | {- readonly kind: "directory";- readonly moduleCodeBySlot: Readonly<Record<string, string>>;- };--export interface PreparedMaterializedAuthoredModules {- readonly instrumentation?: PreparedMaterializedInstrumentation;- readonly moduleMapCode: string;-}--export async function prepareMaterializedAuthoredModules(input: {- readonly manifest: CompiledAgentManifest;- readonly moduleMapPath: string;-}): Promise<PreparedMaterializedAuthoredModules> {- const moduleMapCode = await bundleAuthoredModuleMapForGeneration(input);- const providersEnabled = input.manifest.config.experimental?.instrumentationProviders ?? false;- const layout = providersEnabled- ? resolveInstrumentationLayout({ agentRoot: input.manifest.agentRoot, providersEnabled: true })- : undefined;- const externalDependencies = input.manifest.config.build?.externalDependencies ?? [];- const bundleInstrumentationModule = async (sourcePath: string): Promise<string> =>- await bundleAuthoredModuleForGeneration(sourcePath, { externalDependencies });- let instrumentation: PreparedMaterializedInstrumentation | undefined;-- if (layout?.kind === "directory") {- const moduleCodeBySlot: Record<string, string> = {};- for (const [slot, sourcePath] of Object.entries(layout.modulePathsBySlot)) {- moduleCodeBySlot[slot] = await bundleInstrumentationModule(sourcePath);- }- instrumentation = { kind: "directory", moduleCodeBySlot };- }-- return instrumentation === undefined ? { moduleMapCode } : { instrumentation, moduleMapCode };-}-export async function writeMaterializedAuthoredModules(input: {- readonly prepared: PreparedMaterializedAuthoredModules;+ readonly prepared: PreparedAuthoredRuntimeModules;readonly runtimeAppRoot: string;}): Promise<MaterializedAuthoredModuleIndex> {const compileRoot = join(input.runtimeAppRoot, ".eve", "compile");@@ -113,15 +72,7 @@ export async function writeMaterializedAuthoredModules(input: {let instrumentation: MaterializedInstrumentation | undefined;- if (input.prepared.instrumentation?.kind === "file") {- instrumentation = {- kind: "file",- modulePath: await materializeInstrumentationModule(- "file",- input.prepared.instrumentation.moduleCode,- ),- };- } else if (input.prepared.instrumentation?.kind === "directory") {+ if (input.prepared.instrumentation !== undefined) {const modulePathsBySlot: Record<string, string> = {};for (const [slot, code] of Object.entries(input.prepared.instrumentation.moduleCodeBySlot)) {modulePathsBySlot[slot] = await materializeInstrumentationModule(slot, code);diff --git a/packages/eve/src/internal/nitro/dev-runtime-artifacts.integration.test.ts b/packages/eve/src/internal/nitro/dev-runtime-artifacts.integration.test.tsindex fa6e62492..5f460a158 100644--- a/packages/eve/src/internal/nitro/dev-runtime-artifacts.integration.test.ts+++ b/packages/eve/src/internal/nitro/dev-runtime-artifacts.integration.test.ts@@ -58,6 +58,7 @@ async function createNextStyleImportSnapshotFixture(): Promise<{ readonly appRooconst moduleMapPath = join(compileDirectoryPath, "module-map.mjs");await mkdir(agentRoot, { recursive: true });+ await mkdir(join(agentRoot, "tools"), { recursive: true });await mkdir(join(appRoot, "node_modules"), { recursive: true });await mkdir(join(appRoot, "src", "features", "editor", "eve"), { recursive: true });await mkdir(compileDirectoryPath, { recursive: true });@@ -80,14 +81,7 @@ async function createNextStyleImportSnapshotFixture(): Promise<{ readonly appRoo);await writeFile(join(agentRoot, "agent.ts"),- [- 'import { createEveModelRouter } from "./model-router";',- 'import { authSessionAuth } from "@/features/editor/eve/auth-session";',- "",- 'export default { model: "openai/gpt-5.4-mini" };',- "export const routed = createEveModelRouter(authSessionAuth);",- "",- ].join("\n"),+ ['export default { model: "openai/gpt-5.4-mini" };', ""].join("\n"),);await writeFile(join(agentRoot, "model-router.ts"),@@ -102,6 +96,23 @@ async function createNextStyleImportSnapshotFixture(): Promise<{ readonly appRoojoin(appRoot, "src", "features", "editor", "eve", "auth-session.ts"),'export const authSessionAuth = "session-auth";\n',);+ await writeFile(+ join(agentRoot, "tools", "routed.ts"),+ [+ 'import { defineTool } from "eve/tools";',+ 'import { createEveModelRouter } from "../model-router";',+ 'import { authSessionAuth } from "@/features/editor/eve/auth-session";',+ "",+ "export const routed = createEveModelRouter(authSessionAuth);",+ "",+ "export default defineTool({",+ ' description: "Return the routed session auth value.",',+ ' inputSchema: { type: "object", properties: {}, additionalProperties: false },',+ " async execute() { return routed; },",+ "});",+ "",+ ].join("\n"),+ );await writeFile(join(agentRoot, "instructions.md"), "Use the routed model.\n");const compileResult = await compileAgent({ startPath: appRoot });@@ -744,9 +755,10 @@ describe("development runtime artifact snapshots", () => {createDevelopmentNitroArtifactsConfig({ appRoot }),),});- const agentModule = bundle.moduleMap.nodes[ROOT_COMPILED_AGENT_NODE_ID]?.modules["agent.ts"];+ const routedToolModule =+ bundle.moduleMap.nodes[ROOT_COMPILED_AGENT_NODE_ID]?.modules["tools/routed.ts"];- expect(agentModule).toMatchObject({+ expect(routedToolModule).toMatchObject({routed: "router:session-auth",});});@@ -764,9 +776,10 @@ describe("development runtime artifact snapshots", () => {const bundle = await getCompiledRuntimeAgentBundle({compiledArtifactsSource: createDiskRuntimeCompiledArtifactsSource(runtimeAppRoot!),});- const agentModule = bundle.moduleMap.nodes[ROOT_COMPILED_AGENT_NODE_ID]?.modules["agent.ts"];+ const routedToolModule =+ bundle.moduleMap.nodes[ROOT_COMPILED_AGENT_NODE_ID]?.modules["tools/routed.ts"];- expect(agentModule).toMatchObject({+ expect(routedToolModule).toMatchObject({routed: "router:session-auth",});});diff --git a/packages/eve/src/internal/nitro/development-generation.ts b/packages/eve/src/internal/nitro/development-generation.tsindex a465d5155..2f8d1cca2 100644--- a/packages/eve/src/internal/nitro/development-generation.ts+++ b/packages/eve/src/internal/nitro/development-generation.ts@@ -1,10 +1,8 @@import { rm } from "node:fs/promises";import type { CompileAgentResult } from "#compiler/compile-agent.js";-import {- prepareMaterializedAuthoredModules,- writeMaterializedAuthoredModules,-} from "#internal/materialized-authored-modules.js";+import { prepareAuthoredRuntimeModules } from "#internal/authored-runtime-modules.js";+import { writeMaterializedAuthoredModules } from "#internal/materialized-authored-modules.js";import {activateDevelopmentRuntimeArtifactsSnapshotTransaction,pruneDevelopmentRuntimeArtifactsSnapshots,@@ -27,7 +25,7 @@ const developmentGenerationPruneStates = new Map<string, DevelopmentGenerationPrexport async function stageDevelopmentGeneration(compileResult: CompileAgentResult,): Promise<DevelopmentGeneration> {- const prepared = await prepareMaterializedAuthoredModules({+ const prepared = await prepareAuthoredRuntimeModules({manifest: compileResult.manifest,moduleMapPath: compileResult.paths.moduleMapPath,});diff --git a/packages/eve/src/internal/nitro/host/authored-runtime-artifacts.scenario.test.ts b/packages/eve/src/internal/nitro/host/authored-runtime-artifacts.scenario.test.tsnew file mode 100644index 000000000..ae933450c--- /dev/null+++ b/packages/eve/src/internal/nitro/host/authored-runtime-artifacts.scenario.test.ts@@ -0,0 +1,220 @@+import { mkdtemp, readFile, rm } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { pathToFileURL } from "node:url";++import { describe, expect, it } from "vitest";++import type { CompiledModuleMap } from "#compiler/module-map.js";+import {+ createApplicationBuildWorkspace,+ removeApplicationBuildWorkspace,+} from "#internal/application/build-workspace.js";+import { createAuthoredSourceRuntimeCompiledArtifactsSource } from "#internal/application/runtime-compiled-artifacts-source.js";+import { loadCompiledModuleMapFromAuthoredSource } from "#internal/authored-module-map-loader.js";+import type { MaterializedInstrumentation } from "#internal/materialized-authored-modules.js";+import {+ discardDevelopmentGeneration,+ stageDevelopmentGeneration,+} from "#internal/nitro/development-generation.js";+import { prepareProductionApplicationHost } from "#internal/nitro/host/prepare-application-host.js";+import { useScenarioApp } from "#internal/testing/scenario-app.js";++describe("authored runtime artifacts", () => {+ const scenarioApp = useScenarioApp();++ it("keeps compile-only asset imports out of equivalent development and production maps", async () => {+ const app = await scenarioApp({+ files: {+ "assets/runtime.bin": "BINARY",+ "assets/runtime.txt": "runtime text\n",+ "agent/agent.ts": 'export default { model: "openai/gpt-5.4" };\n',+ "agent/instructions.ts": [+ 'import { appendFileSync } from "node:fs";',+ 'import prompt from "../prompts/cse.md?raw";',+ "const logPath = process.env.EVE_TEST_INSTRUCTIONS_LOG;",+ 'if (logPath == null) throw new Error("missing instructions log path");',+ 'appendFileSync(logPath, "evaluated\\n");',+ "export default { content: prompt };",+ "",+ ].join("\n"),+ "agent/instrumentation.ts": [+ 'import marker from "../assets/runtime.txt?raw";',+ "export default { marker };",+ "",+ ].join("\n"),+ "agent/tools/read_assets.ts": [+ 'import binary from "../../assets/runtime.bin";',+ 'import text from "../../assets/runtime.txt?raw";',+ "export default {",+ ' description: "Read bundled assets.",',+ " execute: () => ({ binary, text }),",+ "};",+ "",+ ].join("\n"),+ "prompts/cse.md": "CSE system prompt\n",+ },+ installDependencies: true,+ name: "authored-runtime-assets",+ });+ const lifecycleLogPath = join(app.appRoot, "instructions-evaluations.log");+ const workspace = await createApplicationBuildWorkspace(app.appRoot);+ const foreignCwd = await mkdtemp(join(tmpdir(), "eve-foreign-cwd-"));+ const previousCwd = process.cwd();+ const previousLogPath = process.env.EVE_TEST_INSTRUCTIONS_LOG;+ process.env.EVE_TEST_INSTRUCTIONS_LOG = lifecycleLogPath;+ let developmentGeneration: Awaited<ReturnType<typeof stageDevelopmentGeneration>> | undefined;++ try {+ const productionHost = await prepareProductionApplicationHost(workspace);+ const manifest = productionHost.compileResult.manifest;+ const instructions = manifest.instructions.find(+ (entry) => entry.logicalPath === "instructions.ts",+ )!;+ const tool = manifest.tools.find((entry) => entry.name === "read_assets")!;+ const instrumentationSourceId = manifest.instrumentation!.sourceId;++ expect(manifest.bindings[instructions.sourceId]?.usage).toEqual({+ compile: true,+ runtimeEntry: false,+ });+ expect(await readFile(lifecycleLogPath, "utf8")).toBe("evaluated\n");++ developmentGeneration = await stageDevelopmentGeneration(productionHost.compileResult);+ const developmentMap = await loadCompiledModuleMapFromAuthoredSource({+ compiledArtifactsSource: createAuthoredSourceRuntimeCompiledArtifactsSource(+ developmentGeneration.runtimeAppRoot,+ ),+ });++ process.chdir(foreignCwd);+ const productionModulePath = join(+ workspace.host.artifactsDir,+ "compiled-artifacts-module-map.mjs",+ );+ const productionNamespace = (await import(+ `${pathToFileURL(productionModulePath).href}?scenario=foreign-cwd`+ )) as { readonly default: CompiledModuleMap };+ const productionMap = productionNamespace.default;+ const productionRoot = productionMap.nodes.__root__;+ const developmentRoot = developmentMap.nodes.__root__;+ if (productionRoot === undefined || developmentRoot === undefined) {+ throw new Error("Expected root module-map scopes.");+ }++ expect(moduleKeys(productionMap)).toEqual(moduleKeys(developmentMap));+ expect(productionRoot.modules[instructions.sourceId]).toBeUndefined();+ expect(developmentRoot.modules[instructions.sourceId]).toBeUndefined();+ expect(+ (+ productionRoot.modules[instrumentationSourceId] as {+ readonly default: { readonly marker: string };+ }+ ).default.marker,+ ).toBe("runtime text\n");+ expect(+ (+ developmentRoot.modules[instrumentationSourceId] as {+ readonly default: { readonly marker: string };+ }+ ).default.marker,+ ).toBe("runtime text\n");+ expect(await executeAssetTool(productionMap, tool.sourceId)).toEqual({+ binary: "data:application/octet-stream;base64,QklOQVJZ",+ text: "runtime text\n",+ });+ expect(await executeAssetTool(developmentMap, tool.sourceId)).toEqual(+ await executeAssetTool(productionMap, tool.sourceId),+ );+ expect(await readFile(lifecycleLogPath, "utf8")).toBe("evaluated\n");+ } finally {+ process.chdir(previousCwd);+ if (previousLogPath === undefined) delete process.env.EVE_TEST_INSTRUCTIONS_LOG;+ else process.env.EVE_TEST_INSTRUCTIONS_LOG = previousLogPath;+ if (developmentGeneration !== undefined) {+ await discardDevelopmentGeneration(developmentGeneration);+ }+ await Promise.all([+ removeApplicationBuildWorkspace(workspace),+ rm(foreignCwd, { force: true, recursive: true }),+ ]);+ }+ });++ it("prepares provider-directory instrumentation identically for development and production", async () => {+ const app = await scenarioApp({+ files: {+ "agent/agent.ts": [+ "export default {",+ ' model: "openai/gpt-5.4",',+ " experimental: { instrumentationProviders: true },",+ "};",+ "",+ ].join("\n"),+ "agent/instrumentation/otel.ts": [+ 'import marker from "../../assets/provider.txt?raw";',+ "export default { marker };",+ "",+ ].join("\n"),+ "agent/instructions.md": "Use the configured model.\n",+ "assets/provider.txt": "provider asset\n",+ },+ name: "provider-runtime-assets",+ });+ const workspace = await createApplicationBuildWorkspace(app.appRoot);+ let developmentGeneration: Awaited<ReturnType<typeof stageDevelopmentGeneration>> | undefined;++ try {+ const productionHost = await prepareProductionApplicationHost(workspace);+ const productionProviderPath =+ productionHost.compiledArtifacts.instrumentationSourcePaths?.[0];+ expect(productionProviderPath).toBe(+ join(workspace.host.artifactsDir, "compiled-artifacts-instrumentation-otel.mjs"),+ );+ expect(productionProviderPath).not.toContain(join(app.appRoot, "agent", "instrumentation"));++ developmentGeneration = await stageDevelopmentGeneration(productionHost.compileResult);+ const compileRoot = join(developmentGeneration.runtimeAppRoot, ".eve", "compile");+ const index = JSON.parse(+ await readFile(join(compileRoot, "authored-modules.json"), "utf8"),+ ) as { readonly instrumentation?: MaterializedInstrumentation };+ expect(index.instrumentation?.kind).toBe("directory");+ if (index.instrumentation?.kind !== "directory") {+ throw new Error("Expected provider-directory instrumentation.");+ }+ const developmentProviderPath = join(+ compileRoot,+ index.instrumentation.modulePathsBySlot.otel!,+ );+ const [productionProvider, developmentProvider] = await Promise.all([+ import(`${pathToFileURL(productionProviderPath!).href}?target=production`),+ import(`${pathToFileURL(developmentProviderPath).href}?target=development`),+ ]);++ expect(productionProvider.default.marker).toBe("provider asset\n");+ expect(developmentProvider.default.marker).toBe(productionProvider.default.marker);+ } finally {+ if (developmentGeneration !== undefined) {+ await discardDevelopmentGeneration(developmentGeneration);+ }+ await removeApplicationBuildWorkspace(workspace);+ }+ });+});++function moduleKeys(moduleMap: CompiledModuleMap): Record<string, string[]> {+ return Object.fromEntries(+ Object.entries(moduleMap.nodes).map(([nodeId, node]) => [+ nodeId,+ Object.keys(node.modules).sort(),+ ]),+ );+}++async function executeAssetTool(moduleMap: CompiledModuleMap, sourceId: string): Promise<unknown> {+ const namespace = moduleMap.nodes.__root__?.modules[sourceId] as+ | { readonly default?: { readonly execute?: () => unknown } }+ | undefined;+ if (namespace?.default?.execute === undefined) throw new Error("Asset tool is not executable.");+ return await namespace.default.execute();+}diff --git a/packages/eve/src/internal/nitro/routes/agent-info/build-agent-info-response.test.ts b/packages/eve/src/internal/nitro/routes/agent-info/build-agent-info-response.test.tsindex cc1af264d..c3b6c37c5 100644--- a/packages/eve/src/internal/nitro/routes/agent-info/build-agent-info-response.test.ts+++ b/packages/eve/src/internal/nitro/routes/agent-info/build-agent-info-response.test.ts@@ -109,6 +109,8 @@ describe("buildAgentInfoResponse", () => {slug: "profile",}),);+ expect(response.agent.config.binding).not.toHaveProperty("usage");+ expect(response.memories[0]?.binding).not.toHaveProperty("usage");expect(() => AgentInfoResultSchema.parse(response)).not.toThrow();});diff --git a/packages/eve/src/internal/nitro/routes/agent-info/build-agent-info-response.ts b/packages/eve/src/internal/nitro/routes/agent-info/build-agent-info-response.tsindex 222e9cbc8..c7fbe4b25 100644--- a/packages/eve/src/internal/nitro/routes/agent-info/build-agent-info-response.ts+++ b/packages/eve/src/internal/nitro/routes/agent-info/build-agent-info-response.ts@@ -273,10 +273,18 @@ function sourceProjection(sourceId: source.sourceId,sourceKind: toAgentInfoSourceKind(source.sourceKind),};+ const publicBinding =+ binding === undefined+ ? undefined+ : {+ backing: binding.backing,+ logicalPath: binding.logicalPath,+ owner: binding.owner,+ };if (binding !== undefined && source.exportName !== undefined) {- return { ...projected, binding, exportName: source.exportName };+ return { ...projected, binding: publicBinding!, exportName: source.exportName };}- if (binding !== undefined) return { ...projected, binding };+ if (binding !== undefined) return { ...projected, binding: publicBinding! };if (source.exportName !== undefined) return { ...projected, exportName: source.exportName };return projected;}diff --git a/packages/eve/src/setup/channel-add-conflicts.ts b/packages/eve/src/setup/channel-add-conflicts.tsindex 6383ee4e9..65ac1086d 100644--- a/packages/eve/src/setup/channel-add-conflicts.ts+++ b/packages/eve/src/setup/channel-add-conflicts.ts@@ -5,7 +5,7 @@ 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 type { AgentModuleBinding } from "#compiler/source-graph.js";import { discoverAgent } from "#discover/discover-agent.js";import { EVE_SESSION_ROUTE_PATH } from "#protocol/routes.js";@@ -45,7 +45,7 @@ export async function inspectExistingChannelRegistrations(const slackOwners = new Set<string>();for (const source of manifest.channels) {- const binding: CompiledModuleBinding = {+ const binding: AgentModuleBinding = {backing: {externalDependencies: [],kind: "filesystem",diff --git a/packages/eve/test/scenarios/app-runtime-dependencies.scenario.test.ts b/packages/eve/test/scenarios/app-runtime-dependencies.scenario.test.tsindex 53dd38c92..1af9428ca 100644--- a/packages/eve/test/scenarios/app-runtime-dependencies.scenario.test.ts+++ b/packages/eve/test/scenarios/app-runtime-dependencies.scenario.test.ts@@ -166,7 +166,6 @@ describe("app runtime dependency tracing", () => {)).join("\n");- expect(serverModuleEntries.some((entry) => entry.includes("fixture-runtime-dep"))).toBe(true);expect(tracedServerPackageJson.dependencies).not.toHaveProperty("fixture-runtime-dep");expect(tracedServerPackageJson.dependencies).not.toHaveProperty(EVE_PACKAGE_INFO.name);await expect(@@ -292,8 +291,6 @@ describe("app runtime dependency tracing", () => {).rejects.toMatchObject({code: "ENOENT",});- expect(bundledDependencyModule.source).toContain("const __dirname = __eveDirname(__filename);");-await import(pathToFileURL(bundledDependencyModule.modulePath).href);}, 30_000);@@ -969,7 +966,6 @@ describe("app runtime dependency tracing", () => {recursive: true,});- expect(serverEntries.some((entry) => entry.includes("fixture-instrumentation-dep"))).toBe(true);const instrumentationModulePath = (await Promise.all(serverEntriesdiff --git a/packages/eve/test/scenarios/compile-agent.scenario.test.ts b/packages/eve/test/scenarios/compile-agent.scenario.test.tsindex 9fbae3420..256f30076 100644--- a/packages/eve/test/scenarios/compile-agent.scenario.test.ts+++ b/packages/eve/test/scenarios/compile-agent.scenario.test.ts@@ -382,7 +382,8 @@ describe("compiler artifacts", () => {});expect(moduleMapText).toContain('"nodes": Object.freeze({');expect(moduleMapText).toContain(`"${ROOT_COMPILED_AGENT_NODE_ID}": Object.freeze({`);- expect(moduleMapText).toContain('"agent.mjs": module_0');+ expect(moduleMapText).toMatch(/"channels\/support\.mjs": module_\d+/);+ expect(moduleMapText).not.toContain('"agent.mjs":');expect(moduleMapText).not.toContain('"subagents": Object.freeze({');});@@ -502,13 +503,15 @@ describe("compiler artifacts", () => {const normalizedModuleMapText = normalizeArtifactValue(moduleMapText.trimEnd(), appRoot);- // Every selected module-backed source retains a total binding, including- // modules whose normalized content is serialized into the manifest.- expect(normalizedModuleMapText).toContain('from "../../agent/agent.mjs";');- expect(normalizedModuleMapText).toContain('from "../../agent/instructions.mjs";');+ // The manifest retains the total binding graph, while the runtime map+ // contains only executable entries.+ expect(normalizedModuleMapText).not.toContain('from "../../agent/agent.mjs";');+ expect(normalizedModuleMapText).not.toContain('from "../../agent/instructions.mjs";');expect(normalizedModuleMapText).toContain('from "../../agent/tools/get_weather.mjs";');- expect(normalizedModuleMapText).toContain('from "../../agent/subagents/reviewer/agent.mjs";');- expect(normalizedModuleMapText).toContain(+ expect(normalizedModuleMapText).not.toContain(+ 'from "../../agent/subagents/reviewer/agent.mjs";',+ );+ expect(normalizedModuleMapText).not.toContain('from "../../agent/subagents/reviewer/instructions.mjs";',);expect(normalizedModuleMapText).toContain(@@ -516,10 +519,9 @@ describe("compiler artifacts", () => {);expect(normalizedModuleMapText).toContain('"nodes": Object.freeze({');expect(normalizedModuleMapText).toContain(`"${ROOT_COMPILED_AGENT_NODE_ID}": Object.freeze({`);- expect(normalizedModuleMapText).toMatch(/"agent\.mjs": module_\d+/);+ expect(normalizedModuleMapText).not.toContain('"agent.mjs":');expect(normalizedModuleMapText).toMatch(/"tools\/get_weather\.mjs": module_\d+/);expect(normalizedModuleMapText).toContain('"subagents/reviewer": Object.freeze({');- expect(normalizedModuleMapText).toMatch(/"agent\.mjs": module_\d+/);expect(normalizedModuleMapText).toMatch(/"tools\/review\.mjs": module_\d+/);});@@ -747,7 +749,7 @@ describe("compileAgent", () => {sourceId: "sandbox/sandbox.cjs",sourceKind: "module",});- expect(normalizeArtifactValue(moduleMapText, app.appRoot)).toMatch(/"agent\.cjs": module_\d+/);+ expect(normalizeArtifactValue(moduleMapText, app.appRoot)).not.toContain('"agent.cjs":');expect(normalizeArtifactValue(moduleMapText, app.appRoot)).toMatch(/"sandbox\/sandbox\.cjs": module_\d+/,);@@ -1410,8 +1412,10 @@ describe("compileAgent", () => {nodeId: "subagents/researcher",sourceId: "subagents/researcher",});- expect(normalizedModuleMapText).toContain('from "../../agent/agent.mjs";');- expect(normalizedModuleMapText).toContain('from "../../agent/subagents/researcher/agent.mjs";');+ expect(normalizedModuleMapText).not.toContain('from "../../agent/agent.mjs";');+ expect(normalizedModuleMapText).not.toContain(+ 'from "../../agent/subagents/researcher/agent.mjs";',+ );expect(normalizedModuleMapText).toContain('from "../../agent/subagents/researcher/sandbox/sandbox.mjs";',);diff --git a/packages/eve/test/scenarios/compiled-artifacts-bootstrap.scenario.test.ts b/packages/eve/test/scenarios/compiled-artifacts-bootstrap.scenario.test.tsindex 99c278a05..dc54ade9c 100644--- a/packages/eve/test/scenarios/compiled-artifacts-bootstrap.scenario.test.ts+++ b/packages/eve/test/scenarios/compiled-artifacts-bootstrap.scenario.test.ts@@ -99,7 +99,7 @@ describe("writeCompiledArtifactsFiles", () => {const instrumentationPluginSource = await readFile(instrumentationPluginPath, "utf8");expect(instrumentationPluginSource).toContain(- generatedArtifacts.bootstrapPath.replaceAll("\\", "/"),+ join(outDir, "compiled-artifacts-module-map.mjs").replaceAll("\\", "/"),);expect(instrumentationPluginSource).toContain(`moduleMap.nodes["__root__"].modules["instrumentation.ts"]`,@@ -172,8 +172,8 @@ describe("writeCompiledArtifactsFiles", () => {}expect(generatedArtifacts.instrumentationSourcePaths).toEqual([- join(agentRoot, "instrumentation", "local.ts"),- join(agentRoot, "instrumentation", "otel.ts"),+ join(outDir, "compiled-artifacts-instrumentation-local.mjs"),+ join(outDir, "compiled-artifacts-instrumentation-otel.mjs"),]);const instrumentationPluginSource = await readFile(instrumentationPluginPath, "utf8");diff --git a/packages/eve/test/scenarios/dev-server-connections.scenario.test.ts b/packages/eve/test/scenarios/dev-server-connections.scenario.test.tsindex 567ec3891..d4d0e9a43 100644--- a/packages/eve/test/scenarios/dev-server-connections.scenario.test.ts+++ b/packages/eve/test/scenarios/dev-server-connections.scenario.test.ts@@ -251,7 +251,7 @@ describe("eve dev server live connections", () => {join(app.appRoot, "agent", "instrumentation.ts"),createInstrumentationSource("keep-alive-two"),);- await forceDevelopmentRebuild(server.url);+ await forceDevelopmentRebuild(server.url, agent);await waitForCondition(async () => (await fetchText(server.url, "/instrumentation-marker")) === "keep-alive-two",`Timed out waiting for the structural replacement.\n\nstdout:\n${server.stdout()}\n\nstderr:\n${server.stderr()}`,diff --git a/packages/eve/test/scenarios/dev-server-harness.ts b/packages/eve/test/scenarios/dev-server-harness.tsindex 235f07e74..36f294e6c 100644--- a/packages/eve/test/scenarios/dev-server-harness.ts+++ b/packages/eve/test/scenarios/dev-server-harness.ts@@ -351,9 +351,16 @@ export async function fetchAgentInfo(serverUrl: string): Promise<AgentInfoResponreturn (await response.json()) as AgentInfoResponse;}-export async function forceDevelopmentRebuild(serverUrl: string): Promise<void> {+export async function forceDevelopmentRebuild(serverUrl: string, agent?: Agent): Promise<void> {const rebuildUrl = new URL(EVE_DEV_RUNTIME_ARTIFACTS_REBUILD_ROUTE_PATH, serverUrl);rebuildUrl.searchParams.set("force", "1");+ if (agent !== undefined) {+ const response = await requestWithAgent(rebuildUrl.href, agent);+ if (response.statusCode < 200 || response.statusCode >= 300) {+ throw new Error(`Development rebuild failed with status ${String(response.statusCode)}.`);+ }+ return;+ }const response = await fetch(rebuildUrl);if (!response.ok) {throw new Error(`Development rebuild failed with status ${String(response.status)}.`);@@ -494,7 +501,11 @@ async function waitForServerUrl(input: {export async function requestWithAgent(url: string,agent: Agent,-): Promise<{ readonly body: string; readonly localPort: number | undefined }> {+): Promise<{+ readonly body: string;+ readonly localPort: number | undefined;+ readonly statusCode: number;+}> {return await new Promise((resolve, reject) => {const target = new URL(url);const request = requestHttp(@@ -507,9 +518,10 @@ export async function requestWithAgent((response) => {const chunks: Buffer[] = [];const localPort = response.socket.localPort;+ const statusCode = response.statusCode ?? 0;response.on("data", (chunk: Buffer) => chunks.push(chunk));response.on("end", () => {- resolve({ body: Buffer.concat(chunks).toString("utf8"), localPort });+ resolve({ body: Buffer.concat(chunks).toString("utf8"), localPort, statusCode });});},);diff --git a/packages/eve/test/scenarios/runtime-loaders.scenario.test.ts b/packages/eve/test/scenarios/runtime-loaders.scenario.test.tsindex 20569cc50..b341ff2cb 100644--- a/packages/eve/test/scenarios/runtime-loaders.scenario.test.ts+++ b/packages/eve/test/scenarios/runtime-loaders.scenario.test.ts@@ -415,15 +415,11 @@ describe("runtime compiled artifact loaders", () => {expect(resolvedChannel.urlPath).toBe("/slack");expect(typeof resolvedChannel.fetch).toBe("function");expect(resolvedAgent.channels.filter((channel) => channel.name === "slack")).toHaveLength(1);- // The canonical module map retains every source node that participates in- // compilation while excluding implementation-only imports such as `lib/`.+ // The runtime module map excludes compile-only config, instructions,+ // skills, and prompt schedules while retaining executable entries.const rootModuleIds = Object.keys(moduleMap.nodes[ROOT_COMPILED_AGENT_NODE_ID]?.modules ?? {});expect(rootModuleIds.filter((moduleId) => !moduleId.startsWith("eve:"))).toEqual([- "agent.mjs","channels/slack.mjs",- "instructions.mjs",- "schedules/daily-digest.mjs",- "skills/route-weather.mjs","tools/get_weather.mjs",]);expect(rootModuleIds.some((moduleId) => moduleId.startsWith("eve:"))).toBe(true);@@ -549,7 +545,7 @@ describe("runtime compiled artifact loaders", () => {]);const researcherModuleIds = Object.keys(moduleMap.nodes["subagents/researcher"]?.modules ?? {});expect(researcherModuleIds.filter((moduleId) => !moduleId.startsWith("eve:defaults:"))).toEqual(- ["agent.mjs", "sandbox/sandbox.mjs", "tools/search.mjs"],+ ["sandbox/sandbox.mjs", "tools/search.mjs"],);expect(researcherModuleIds.some((moduleId) => moduleId.startsWith("eve:defaults:"))).toBe(true);expect(researcherNode?.agent.instructions).toEqual([diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 1e13e1ff9..33a5fd288 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -573,6 +573,28 @@ importers:specifier: 'catalog:'version: 4.1.10(@edge-runtime/[email protected])(@opentelemetry/[email protected])(@types/[email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ e2e/fixtures/agent-authored-bundling:+ dependencies:+ '@eve-e2e/config':+ specifier: workspace:*+ version: link:../e2e-config+ '@workflow/world-postgres':+ specifier: 'catalog:'+ version: 5.0.0-beta.35(@opentelemetry/[email protected])(@types/[email protected])(@upstash/[email protected])([email protected])([email protected])([email protected])+ eve:+ specifier: workspace:*+ version: link:../../../packages/eve+ zod:+ specifier: 'catalog:'+ version: 4.4.3+ devDependencies:+ '@types/node':+ specifier: 'catalog:'+ version: 25.9.1+ typescript:+ specifier: 'catalog:'+ version: 7.0.2+e2e/fixtures/agent-background-tools:dependencies:'@eve-e2e/config':