Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

fix(eve): initialize instrumentation before server imports (#3806)

Matan Kushnere7d205773d76
diff --git a/.changeset/early-instrumentation-startup.md b/.changeset/early-instrumentation-startup.md
new file mode 100644
index 000000000..982d13d61
--- /dev/null
+++ b/.changeset/early-instrumentation-startup.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Await instrumentation setup before loading server dependencies in development and production, so OpenTelemetry can instrument external packages such as `pg`.
diff --git a/docs/guides/instrumentation/instrumentation.mdx b/docs/guides/instrumentation/instrumentation.mdx
index db1624b2c..77588745b 100644
--- a/docs/guides/instrumentation/instrumentation.mdx
+++ b/docs/guides/instrumentation/instrumentation.mdx
@@ -51,6 +51,11 @@ export default defineInstrumentation({
`ctx.state` is JSON storage scoped to this file and operation. It survives
durable suspension and is released after the terminal event.
+Use `setup` for asynchronous initialization. In `eve dev` and built servers,
+eve awaits every provider's setup before loading the server entry. A setup
+failure stops startup. Modules imported by an instrumentation file load before
+setup, so keep dependencies that need initialization out of those imports.
+
## Control inputs and outputs
Each lifecycle file created with `defineInstrumentation(...)` has an
diff --git a/docs/guides/instrumentation/otel.mdx b/docs/guides/instrumentation/otel.mdx
index 5336e03be..9a4f3a3e3 100644
--- a/docs/guides/instrumentation/otel.mdx
+++ b/docs/guides/instrumentation/otel.mdx
@@ -38,6 +38,36 @@ does not affect lifecycle instrumentation created with `defineInstrumentation()`
See [Audience](../channels/overview#audience) for how channels classify the
conversation passed to this policy.
+## Instrument Node.js dependencies
+
+Pass OpenTelemetry instrumentation instances to `otel({ instrumentations })`.
+For example, install the PostgreSQL instrumentation alongside `pg`:
+
+```bash
+pnpm add pg @opentelemetry/instrumentation-pg
+```
+
+```ts title="agent/instrumentation/otel.ts"
+import { PgInstrumentation } from "@opentelemetry/instrumentation-pg";
+import { otel } from "eve/instrumentation/otel";
+
+export default otel({
+ instrumentations: [new PgInstrumentation()],
+});
+```
+
+Keep the instrumented package external so Node.js module hooks can intercept
+it. Add `pg` to your agent's [build configuration](/docs/agent-config#other-defineagent-fields):
+
+```ts title="agent/agent.ts"
+import { defineAgent } from "eve";
+
+export default defineAgent({
+ model: "openai/gpt-5.4-mini",
+ build: { externalDependencies: ["pg"] },
+});
+```
+
## Add an OpenTelemetry destination
Use this section when sending traces to a third-party destination. Install
diff --git a/e2e/fixtures/agent-authored-bundling/agent/instrumentation/bundling.ts b/e2e/fixtures/agent-authored-bundling/agent/instrumentation/bundling.ts
index ca57831ca..ad70f7348 100644
--- a/e2e/fixtures/agent-authored-bundling/agent/instrumentation/bundling.ts
+++ b/e2e/fixtures/agent-authored-bundling/agent/instrumentation/bundling.ts
@@ -1,7 +1,14 @@
+import { setImmediate } from "node:timers/promises";
+
import { defineInstrumentation } from "eve/instrumentation";
import marker from "../../authored-assets/instrumentation.txt?raw";
+// Instrumentation and tools are bundled separately, so the test needs process-wide state.
+declare global {
+ var eveE2eInstrumentationReady: boolean | undefined;
+}
+
const INSTRUMENTATION_MARKER = "authored-instrumentation-asset";
if (marker.trim() !== INSTRUMENTATION_MARKER) {
@@ -9,7 +16,8 @@ if (marker.trim() !== INSTRUMENTATION_MARKER) {
}
export default defineInstrumentation({
- setup: () => {
- void INSTRUMENTATION_MARKER;
+ async setup() {
+ await setImmediate();
+ globalThis.eveE2eInstrumentationReady = true;
},
});
diff --git a/e2e/fixtures/agent-authored-bundling/agent/tools/bundle_probe.ts b/e2e/fixtures/agent-authored-bundling/agent/tools/bundle_probe.ts
index a5ffc69a8..6665fa6be 100644
--- a/e2e/fixtures/agent-authored-bundling/agent/tools/bundle_probe.ts
+++ b/e2e/fixtures/agent-authored-bundling/agent/tools/bundle_probe.ts
@@ -5,12 +5,15 @@ import binaryAsset from "../../authored-assets/runtime.bin";
import rawText from "../../authored-assets/runtime.txt?raw";
import { SHARED_MODULE_MARKER } from "../../authored-assets/shared";
+const instrumentationReadyAtImport = globalThis.eveE2eInstrumentationReady === true;
+
export default defineTool({
description: "E2E bundling probe. Call only when the user sends AUTHORED-BUNDLING-PROBE.",
inputSchema: z.object({}),
execute() {
return {
binaryAsset,
+ instrumentationReadyAtImport,
rawText,
sharedModule: SHARED_MODULE_MARKER,
};
diff --git a/e2e/fixtures/agent-authored-bundling/evals/authored-bundling.eval.ts b/e2e/fixtures/agent-authored-bundling/evals/authored-bundling.eval.ts
index eaf232768..ba457cfb8 100644
--- a/e2e/fixtures/agent-authored-bundling/evals/authored-bundling.eval.ts
+++ b/e2e/fixtures/agent-authored-bundling/evals/authored-bundling.eval.ts
@@ -12,6 +12,7 @@ export default defineEval({
t.calledTool("bundle_probe", {
output: {
binaryAsset: "data:application/octet-stream;base64,RVZFLUJJTkFSWS1BU1NFVAo=",
+ instrumentationReadyAtImport: true,
rawText: "authored runtime text\n",
sharedModule: "shared-authored-typescript-module",
},
diff --git a/packages/eve/src/internal/nitro/host/create-application-nitro.scenario.test.ts b/packages/eve/src/internal/nitro/host/create-application-nitro.scenario.test.ts
index 12031e41f..e45db02a1 100644
--- a/packages/eve/src/internal/nitro/host/create-application-nitro.scenario.test.ts
+++ b/packages/eve/src/internal/nitro/host/create-application-nitro.scenario.test.ts
@@ -86,6 +86,7 @@ function createNitroStub(input: { buildDir?: string; dev?: boolean } = {}): Nitr
handlers: [],
publicAssets: [],
rootDir: "/tmp/weather-agent",
+ virtual: {},
},
routing: {
sync() {},
diff --git a/packages/eve/src/internal/nitro/host/create-application-nitro.ts b/packages/eve/src/internal/nitro/host/create-application-nitro.ts
index 95f995eb3..fa4b3f5bb 100644
--- a/packages/eve/src/internal/nitro/host/create-application-nitro.ts
+++ b/packages/eve/src/internal/nitro/host/create-application-nitro.ts
@@ -5,6 +5,7 @@ import { fileURLToPath } from "node:url";
import { resolveAuthoredTsConfigPath } from "#internal/authored-module-loader.js";
import { createNitro } from "nitro/builder";
import type { Nitro } from "nitro/types";
+import { configureInstrumentationEntry } from "#internal/nitro/host/instrumentation-entry.js";
import { EVE_PACKAGE_NAME } from "#internal/package-name.js";
import {
resolvePackageRoot,
@@ -639,6 +640,9 @@ function configureSharedApplicationNitro(
nitro: Nitro,
preparedHost: PreparedApplicationHost,
): void {
+ if (preparedHost.compiledArtifacts.instrumentationPluginPath !== undefined) {
+ configureInstrumentationEntry(nitro, preparedHost.compiledArtifacts.instrumentationPluginPath);
+ }
addNitroRoutingImportSpecifierPlugin(nitro);
const workflowAliases = resolveWorkflowAliases();
for (const [specifier, resolvedPath] of Object.entries(workflowAliases)) {
diff --git a/packages/eve/src/internal/nitro/host/instrumentation-entry.scenario.test.ts b/packages/eve/src/internal/nitro/host/instrumentation-entry.scenario.test.ts
new file mode 100644
index 000000000..125d273ea
--- /dev/null
+++ b/packages/eve/src/internal/nitro/host/instrumentation-entry.scenario.test.ts
@@ -0,0 +1,191 @@
+import { execFile } from "node:child_process";
+import { mkdir, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+import { pathToFileURL } from "node:url";
+import { promisify } from "node:util";
+
+import { build, createNitro, prepare } from "nitro/builder";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import {
+ useTemporaryAppRoots,
+ useTemporaryDirectories,
+} from "#internal/testing/use-temporary-app-roots.js";
+import { configureInstrumentationEntry } from "#internal/nitro/host/instrumentation-entry.js";
+import { buildApplication } from "#internal/nitro/host.js";
+
+vi.mock("#internal/nitro/host/vercel-build-prewarm.js", () => ({
+ runVercelBuildPrewarm: async () => true,
+}));
+
+const execFileAsync = promisify(execFile);
+const createDirectory = useTemporaryDirectories();
+const createAppRoot = useTemporaryAppRoots();
+
+afterEach(() => vi.unstubAllEnvs());
+
+describe("instrumentation before the Nitro entry", () => {
+ it.each(["vercel-web", "vercel-node", "node-server", "development", "setup-failure"])(
+ "awaits asynchronous setup before application imports with %s",
+ async (target) => {
+ const root = await createDirectory("eve-instrumentation-entry-");
+ const driverDirectory = join(root, "node_modules", "fixture-driver");
+ await mkdir(driverDirectory, { recursive: true });
+ await writeFile(
+ join(driverDirectory, "package.json"),
+ JSON.stringify({ name: "fixture-driver", version: "1.0.0", main: "index.cjs" }),
+ );
+ await writeFile(
+ join(driverDirectory, "index.cjs"),
+ "globalThis.startup.push(`driver:${globalThis.instrumentationReady === true}`);",
+ );
+ const instrumentationPath = join(root, "instrumentation.mjs");
+ await writeFile(
+ instrumentationPath,
+ [
+ 'import { setImmediate } from "node:timers/promises";',
+ "await setImmediate();",
+ ...(target === "setup-failure"
+ ? ["throw new Error('Instrumentation setup failed');"]
+ : []),
+ "globalThis.instrumentationReady = true;",
+ "globalThis.startup.push('instrumentation');",
+ "export default app => {",
+ " app.hooks.hook('close', () => globalThis.startup.push('shutdown'));",
+ " globalThis.closeNitro = () => app.hooks.callHook('close');",
+ "};",
+ ].join("\n"),
+ );
+ const applicationPath = join(root, "application.mjs");
+ await writeFile(applicationPath, 'import "fixture-driver"; export default () => {};');
+ const nitro = await createNitro({
+ rootDir: root,
+ dev: target === "development",
+ preset: target === "node-server" ? "node-server" : "vercel",
+ vercel: { entryFormat: target === "vercel-node" ? "node" : "web" },
+ logLevel: 0,
+ plugins: [applicationPath, instrumentationPath],
+ traceDeps: ["fixture-driver"],
+ rollupConfig: { external: ["fixture-driver"] },
+ });
+ configureInstrumentationEntry(nitro, instrumentationPath);
+
+ try {
+ await prepare(nitro);
+ const compiled = new Promise<void>((resolve) =>
+ nitro.hooks.hookOnce("compiled", () => resolve()),
+ );
+ await build(nitro);
+ await compiled;
+ const entry = pathToFileURL(join(nitro.options.output.serverDir, "index.mjs")).href;
+ const { stdout } = await execFileAsync(
+ process.execPath,
+ [
+ "--input-type=module",
+ "-e",
+ `globalThis.startup = [];
+ try {
+ const { default: server } = await import(${JSON.stringify(entry)});
+ await import(${JSON.stringify(entry)});
+ if (${JSON.stringify(target)} === 'vercel-web' && typeof server.fetch !== 'function') throw new Error('Missing Vercel fetch handler');
+ if (${JSON.stringify(target)} === 'vercel-node' && typeof server !== 'function') throw new Error('Missing Vercel Node handler');
+ if (${JSON.stringify(target)} === 'development' && typeof server.ipc.onClose !== 'function') throw new Error('Missing development close handler');
+ await globalThis.closeNitro();
+ } catch (error) {
+ globalThis.startup.push(error.message);
+ }
+ console.log('RESULT ' + JSON.stringify(globalThis.startup));
+ process.exit(0);`,
+ ],
+ {
+ cwd: root,
+ env: { ...process.env, NITRO_PORT: "0", NITRO_HOST: "127.0.0.1" },
+ timeout: 10_000,
+ },
+ );
+ const result = stdout.split("\n").find((line) => line.startsWith("RESULT "));
+ expect(JSON.parse(result!.slice("RESULT ".length))).toEqual(
+ target === "setup-failure"
+ ? ["Instrumentation setup failed"]
+ : ["instrumentation", "driver:true", "shutdown"],
+ );
+ } finally {
+ await nitro.close();
+ }
+ },
+ );
+
+ it("registers the authored OTel pipeline before eve's external tool dependencies load", async () => {
+ vi.stubEnv("VERCEL", "1");
+ vi.stubEnv("VERCEL_DEPLOYMENT_ID", "");
+ const { appRoot } = await createAppRoot("eve-instrumentation-tool-dependency-", {
+ files: {
+ "package.json": JSON.stringify({
+ name: "instrumentation-tool-dependency",
+ type: "module",
+ dependencies: { "fixture-driver": "1.0.0" },
+ }),
+ "agent/agent.mjs":
+ 'export default { model: "openai/gpt-5.4-mini", build: { externalDependencies: ["fixture-driver"] } };',
+ "agent/instructions.md": "Help Alice check her database.",
+ "agent/tools/check.mjs": [
+ 'import { defineTool } from "eve/tools";',
+ 'import driver from "fixture-driver";',
+ 'export default defineTool({ description: "Check the database.", inputSchema: {}, execute: () => driver });',
+ ].join("\n"),
+ "agent/instrumentation/audit.mjs": [
+ 'import { setImmediate } from "node:timers/promises";',
+ 'import { defineInstrumentation } from "eve/instrumentation";',
+ "export default defineInstrumentation({ async setup() {",
+ " await setImmediate();",
+ " globalThis.startup.push('setup');",
+ "} });",
+ ].join("\n"),
+ "agent/instrumentation/otel.mjs": [
+ 'import { otel } from "eve/instrumentation/otel";',
+ "export default otel({ instrumentations: [{",
+ " getConfig: () => ({ enabled: false }),",
+ " setTracerProvider() {}, setMeterProvider() {}, disable() {},",
+ " enable() { globalThis.instrumentationReady = true; globalThis.startup.push('instrumentation'); },",
+ "}] });",
+ ].join("\n"),
+ "node_modules/fixture-driver/package.json": JSON.stringify({
+ name: "fixture-driver",
+ version: "1.0.0",
+ main: "index.cjs",
+ }),
+ "node_modules/fixture-driver/index.cjs": [
+ "const ready = globalThis.instrumentationReady === true;",
+ "(globalThis.startup ??= []).push(`driver:${ready}`);",
+ "module.exports = { ready };",
+ ].join("\n"),
+ },
+ });
+ const output = await buildApplication(appRoot, { skipSandboxPrewarm: false });
+ for (const functionPath of ["__server.func", ".well-known/workflow/v1/flow.func"]) {
+ const entry = pathToFileURL(join(output, "functions", functionPath, "index.mjs")).href;
+ const { stdout } = await execFileAsync(
+ process.execPath,
+ [
+ "--input-type=module",
+ "-e",
+ `globalThis.startup = [];
+ const { default: server } = await import(${JSON.stringify(entry)});
+ const response = await server.fetch(new Request('http://localhost/eve/v1/health'), { waitUntil() {} });
+ if (response.status !== 200) throw new Error(await response.text());
+ console.log(JSON.stringify({ status: response.status, startup: globalThis.startup }));
+ process.exit(0);`,
+ ],
+ {
+ cwd: appRoot,
+ env: { ...process.env, VERCEL_DEPLOYMENT_ID: "dpl_instrumentation_entry_test" },
+ timeout: 10_000,
+ },
+ );
+ expect(JSON.parse(stdout.trim())).toEqual({
+ status: 200,
+ startup: ["setup", "instrumentation", "driver:true"],
+ });
+ }
+ });
+});
diff --git a/packages/eve/src/internal/nitro/host/instrumentation-entry.ts b/packages/eve/src/internal/nitro/host/instrumentation-entry.ts
new file mode 100644
index 000000000..6d4baefc8
--- /dev/null
+++ b/packages/eve/src/internal/nitro/host/instrumentation-entry.ts
@@ -0,0 +1,22 @@
+import type { Nitro } from "nitro/types";
+
+import { stringifyEsmImportSpecifier } from "#internal/application/import-specifier.js";
+
+const INSTRUMENTATION_ENTRY = "#eve/instrumentation-entry";
+
+/** Awaits instrumentation before importing the preset's server dependency graph. */
+export function configureInstrumentationEntry(nitro: Nitro, instrumentationPath: string): void {
+ // Nitro's development preset otherwise collapses both startup phases into one module.
+ nitro.options.inlineDynamicImports = false;
+ nitro.options.virtual[INSTRUMENTATION_ENTRY] = () =>
+ [
+ `await import(${stringifyEsmImportSpecifier(instrumentationPath)});`,
+ `const { default: server } = await import(${stringifyEsmImportSpecifier(nitro.options.entry)});`,
+ "export default server;",
+ ].join("\n");
+
+ // Presets finish selecting their runtime entry in build:before.
+ nitro.hooks.hook("rollup:before", (_nitro, config) => {
+ config.input = INSTRUMENTATION_ENTRY;
+ });
+}
diff --git a/packages/eve/src/tracing/otel-declaration.ts b/packages/eve/src/tracing/otel-declaration.ts
index 03504e14f..008042860 100644
--- a/packages/eve/src/tracing/otel-declaration.ts
+++ b/packages/eve/src/tracing/otel-declaration.ts
@@ -37,10 +37,6 @@ export type {
* set. Destinations are the plural half and live in `otelIntegration()`.
*
* `contextManager` is deliberately absent: eve's span nesting depends on it.
- * `instrumentations` is accepted so providers can opt into Node auto-
- * instrumentations (e.g. `@opentelemetry/auto-instrumentations-node`); the
- * packages patch modules eve already imported, so their effects are limited
- * to code loaded after registration.
*/
export interface OtelOptions {
/**
@@ -87,11 +83,10 @@ export interface OtelOptions {
readonly propagators?: readonly PropagatorOrName[];
/**
* OpenTelemetry `Instrumentation` instances passed through to
- * `registerOTel`. Use them to patch Node.js built-ins (HTTP, DNS, fs, etc.)
- * for automatic spans around outbound work. Disabled by default because eve
- * already imports the model SDK before registration, so patching cannot
- * reach it — but code loaded after registration (tool modules, connection
- * clients) will be instrumented.
+ * `registerOTel` before the server entry loads. Disabled by default.
+ * Keep packages that rely on Node.js module hooks in
+ * `build.externalDependencies` and out of instrumentation modules' import
+ * graphs so they load after registration.
*/
readonly instrumentations?: readonly unknown[];
}