The Open Framework for Building Agents
feat(eve): make instrumentation directory canonical (#3516)
Chad Hietalafcb3ba2fae64
diff --git a/.changeset/instrumentation-providers-main.md b/.changeset/instrumentation-providers-main.mdnew file mode 100644index 000000000..8c05f77f7--- /dev/null+++ b/.changeset/instrumentation-providers-main.md@@ -0,0 +1,5 @@+---+"eve": minor+---++Make path-named files under `agent/instrumentation/` the supported instrumentation API. Existing `agent/instrumentation.ts` configurations must be split into lifecycle instrumentation, OpenTelemetry destinations, and shared `otel()` settings; extensions that contribute subagents must be rebuilt for the new contract epoch.diff --git a/apps/docs/app/[lang]/integrations/page.tsx b/apps/docs/app/[lang]/integrations/page.tsxindex 86a020f1d..2a345f48d 100644--- a/apps/docs/app/[lang]/integrations/page.tsx+++ b/apps/docs/app/[lang]/integrations/page.tsx@@ -9,7 +9,7 @@ import { Gallery, type GalleryFilter } from "./components/gallery";const title = "Integrations";const description =- "Browse the channels, connections, extensions, memory providers, and instrumentation providers available to an eve agent, each with install, quick start, and configuration steps.";+ "Browse the channels, connections, extensions, memory providers, and observability integrations available to an eve agent, each with install, quick start, and configuration steps.";const titleMetadata = pageTitleMetadata(title);export const metadata: Metadata = {@@ -56,7 +56,7 @@ const IntegrationsPage = ({ searchParams }: PageProps<"/[lang]/integrations">) =<p className="mt-5 max-w-2xl text-gray-900 text-lg">Add the channels where people reach your agent, connections to external services,extensions that package reusable capabilities, memory providers that retain context across- sessions, and instrumentation providers that receive traces.+ sessions, and observability integrations that receive traces.</p></section><Suspense fallback={<Gallery filter="all" integrations={integrations} />}>diff --git a/apps/docs/components/geistdocs/agent-runtime-diagram.tsx b/apps/docs/components/geistdocs/agent-runtime-diagram.tsxindex 049b07e1d..024a2070d 100644--- a/apps/docs/components/geistdocs/agent-runtime-diagram.tsx+++ b/apps/docs/components/geistdocs/agent-runtime-diagram.tsx@@ -103,7 +103,7 @@ export function AgentRuntimeDiagram(): JSX.Element {paths={["agent/tools/**","agent/hooks/**",- "agent/instrumentation.ts",+ "agent/instrumentation/**","agent/connections/**",]}/>diff --git a/apps/docs/lib/geistdocs/llms-index.ts b/apps/docs/lib/geistdocs/llms-index.tsindex cc82dadf8..857ad55a9 100644--- a/apps/docs/lib/geistdocs/llms-index.ts+++ b/apps/docs/lib/geistdocs/llms-index.ts@@ -64,7 +64,7 @@ Documentation links below point directly to Markdown. Remove the \`.md\` suffix- [Deploy to Vercel](${EVE_ORIGIN}/docs/guides/deployment/vercel.md): Build and deploy with Vercel Workflow and Vercel Sandbox.- [Self-Hosting](${EVE_ORIGIN}/docs/guides/deployment/self-hosting.md): Run eve as a Node service or container.- [Authentication](${EVE_ORIGIN}/docs/guides/auth-and-route-protection.md): Secure an agent's HTTP routes and establish caller identity.-- [Instrumentation](${EVE_ORIGIN}/docs/observability/instrumentation.md): Trace agents with OpenTelemetry and inspect workflow metadata.+- [Instrumentation](${EVE_ORIGIN}/docs/observability/instrumentation.md): Configure lifecycle instrumentation and OpenTelemetry destinations.- [Terminal UI](${EVE_ORIGIN}/docs/guides/dev-tui.md): Work with a local or deployed agent from the interactive terminal UI.## Tutorial@@ -91,7 +91,7 @@ Documentation links below point directly to Markdown. Remove the \`.md\` suffix## Optional- [Changelog](${EVE_ORIGIN}/changelog.md): Read eve release notes, including breaking changes and fixes. Follow the next-page links for older releases.-- [Integrations](${EVE_ORIGIN}/integrations): Browse official channels, connections, extensions, and instrumentation providers.+- [Integrations](${EVE_ORIGIN}/integrations): Browse official channels, connections, extensions, and observability integrations.- [Templates](${EVE_ORIGIN}/templates): Browse complete example projects and their source.- [Official eve Skill](https://github.com/vercel/eve/blob/main/skills/eve/SKILL.md): Install or inspect the coding-agent skill; its guidance defers to version-matched bundled docs.- [Source Repository](https://github.com/vercel/eve): Read source, releases, issues, and contribution guidance.diff --git a/apps/docs/lib/geistdocs/redirects.ts b/apps/docs/lib/geistdocs/redirects.tsindex f41b8cf3c..71ad50f15 100644--- a/apps/docs/lib/geistdocs/redirects.ts+++ b/apps/docs/lib/geistdocs/redirects.ts@@ -71,9 +71,10 @@ export const docsRedirects: DocsRedirect[] = [...createDocsRedirects("/deployment/self-hosting", "/guides/deployment/self-hosting"),...createDocsRedirects("/self-hosting", "/guides/deployment/self-hosting"),...createDocsRedirects("/guides/instrumentation", "/observability/instrumentation"),+ ...createDocsRedirects("/guides/instrumentation-providers", "/observability/instrumentation"),...createDocsRedirects(- "/guides/instrumentation-providers","/observability/instrumentation-providers",+ "/observability/instrumentation",),...createDocsRedirects("/guides/instrumentation-otel", "/observability/otel"),...createDocsRedirects("/observability/instrumentation-otel", "/observability/otel"),diff --git a/apps/docs/lib/integrations/data.ts b/apps/docs/lib/integrations/data.tsindex 2d1c16ca3..7f6b1d1bf 100644--- a/apps/docs/lib/integrations/data.ts+++ b/apps/docs/lib/integrations/data.ts@@ -2297,7 +2297,7 @@ See Shopify's [agent profile documentation](https://shopify.dev/docs/agents/prof/*** Instrumentation overlay: presentation plus hand-authored setup markdown.- * Instrumentation providers use hand-authored setup files, so they follow the+ * Instrumentation entries use hand-authored setup files, so they follow the* channel shape (markdown) rather than the generated connection shape.*/type InstrumentationPresentation = ChannelPresentation;@@ -2313,47 +2313,29 @@ const instrumentationPresentations: Record<string, InstrumentationPresentation>eve add instrumentation/braintrust\`\`\``,- quickStart: `eve installs a hook that traces agent activity and an instrumentation file that initializes the Braintrust logger:+ quickStart: `eve installs Braintrust instrumentation:\`\`\`ts-// agent/hooks/braintrust.ts-import { braintrustEveHook } from "braintrust";-import { defineState } from "eve/context";-import { defineHook } from "eve/hooks";--export default defineHook(- braintrustEveHook({- defineState,- metadata: {- app: "my-eve-agent", // Replace with your app name- },- }) as Parameters<typeof defineHook>[0],-);-\`\`\`--\`\`\`ts-// agent/instrumentation.ts+// agent/instrumentation/braintrust.tsimport { braintrustEveInstrumentation, initLogger } from "braintrust";-import { defineState } from "eve/context";-import { defineInstrumentation } from "eve/instrumentation";--export default defineInstrumentation(- braintrustEveInstrumentation({- defineState,- setup: ({ agentName }) => {- initLogger({- projectName: agentName,- apiKey: process.env.BRAINTRUST_API_KEY,- });- },- }) as Parameters<typeof defineInstrumentation>[0],-);++export default braintrustEveInstrumentation({+ metadata: {+ app: "my-eve-agent", // Replace with your app name+ },+ setup: ({ agentName }) => {+ initLogger({+ projectName: agentName,+ apiKey: process.env.BRAINTRUST_API_KEY,+ });+ },+});\`\`\``,- configure: `Create an API key in the Braintrust dashboard and expose it as \`BRAINTRUST_API_KEY\`. Replace the hook's \`app\` metadata with your app name. Spans land in the Braintrust project named after your agent. See the [instrumentation guide](/docs/observability/instrumentation) for the trace hierarchy and the \`recordInputs\`/\`recordOutputs\` controls.`,+ configure: `Create an API key in the Braintrust dashboard and expose it as \`BRAINTRUST_API_KEY\`. Replace the \`app\` metadata with your app name. Do not wrap the result in \`defineInstrumentation\`, pass \`defineState\`, or add \`braintrustEveHook\`; the instrumentation handles eve lifecycle events directly. See [Instrumentation](/docs/observability/instrumentation) for content policy and event handling.`,},"posthog-instrumentation": {logo: "posthog",- docsHref: "/docs/observability/instrumentation",+ docsHref: "/docs/observability/otel",keywords: ["otel", "opentelemetry", "tracing", "observability", "generations", "analytics"],install: `Add PostHog AI Observability from eve's registry:@@ -2361,48 +2343,37 @@ export default defineInstrumentation(eve add instrumentation/posthog\`\`\``,- quickStart: `eve installs \`agent/instrumentation.ts\` with PostHog's trace exporter. It also links spans to the user who initiated the session when an authenticated principal is available:+ quickStart: `eve installs \`agent/instrumentation/posthog.ts\` with PostHog's trace exporter. It also links spans to the user who initiated the session when an authenticated principal is available:\`\`\`ts-// agent/instrumentation.ts-import { trace } from "@opentelemetry/api";+// agent/instrumentation/posthog.tsimport { SimpleSpanProcessor } from "@opentelemetry/sdk-trace-base";import { PostHogTraceExporter } from "@posthog/ai/otel";-import { registerOTel } from "@vercel/otel";-import { defineInstrumentation } from "eve/instrumentation";--export default defineInstrumentation({- setup: ({ agentName }) =>- registerOTel({- serviceName: agentName,- spanProcessors: [- new SimpleSpanProcessor(- new PostHogTraceExporter({- projectToken: process.env.POSTHOG_PROJECT_TOKEN!,- host: process.env.POSTHOG_HOST,- }),- ),- ],- }),- events: {- "step.started"(input) {- const distinctId =- input.session.auth.initiator?.principalId ??- input.session.auth.current?.principalId;-- if (!distinctId) return undefined;+import { otelIntegration } from "eve/instrumentation/otel";++export default otelIntegration({+ spanProcessors: [+ new SimpleSpanProcessor(+ new PostHogTraceExporter({+ projectToken: process.env.POSTHOG_PROJECT_TOKEN!,+ host: process.env.POSTHOG_HOST,+ }),+ ),+ ],+ runtimeContext(input) {+ const distinctId =+ input.session.auth.initiator?.principalId ??+ input.session.auth.current?.principalId;- trace.getActiveSpan()?.setAttribute("posthog.distinct_id", distinctId);- return { runtimeContext: { posthog_distinct_id: distinctId } };- },+ return distinctId ? { "posthog.distinct_id": distinctId } : undefined;},});\`\`\``,- configure: `Copy your project token and client API host from PostHog's project settings and expose them as \`POSTHOG_PROJECT_TOKEN\` and \`POSTHOG_HOST\`. Remove the \`events\` handler to capture generations anonymously. PostHog groups turns using \`eve.session.id\` and preserves eve's trace hierarchy. See [PostHog's eve installation guide](https://posthog.com/docs/ai-observability/installation/eve) for verification steps and the [instrumentation guide](/docs/observability/instrumentation) for input and output capture controls.`,+ configure: `Copy your project token and client API host from PostHog's project settings and expose them as \`POSTHOG_PROJECT_TOKEN\` and \`POSTHOG_HOST\`. Remove \`runtimeContext\` to capture generations anonymously. PostHog groups turns using \`eve.session.id\` and preserves eve's trace hierarchy. See [PostHog's eve installation guide](https://posthog.com/docs/ai-observability/installation/eve) for verification steps and the [OpenTelemetry guide](/docs/observability/otel) for content policy.`,},"sentry-instrumentation": {logo: "sentry",- docsHref: "/docs/observability/instrumentation",+ docsHref: "/docs/observability/otel",keywords: ["otel", "opentelemetry", "tracing", "observability", "otlp", "errors"],install: `Add Sentry instrumentation from eve's registry. Sentry ingests OTLP directly, so no Sentry SDK is required:@@ -2410,61 +2381,53 @@ export default defineInstrumentation({eve add instrumentation/sentry\`\`\``,- quickStart: `Create \`agent/instrumentation.ts\` and point the OTLP exporter at your project's Sentry traces endpoint:+ quickStart: `Create \`agent/instrumentation/sentry.ts\` and point the OTLP exporter at your project's Sentry traces endpoint:\`\`\`ts-// agent/instrumentation.ts-import { defineInstrumentation } from "eve/instrumentation";-import { OTLPHttpProtoTraceExporter, registerOTel } from "@vercel/otel";--export default defineInstrumentation({- setup: ({ agentName }) =>- registerOTel({- serviceName: agentName,- traceExporter: new OTLPHttpProtoTraceExporter({- url: process.env.SENTRY_OTLP_TRACES_ENDPOINT!,- headers: {- "x-sentry-auth": \`sentry sentry_key=\${process.env.SENTRY_PUBLIC_KEY}\`,- },- }),- }),+// agent/instrumentation/sentry.ts+import { OTLPHttpProtoTraceExporter } from "@vercel/otel";+import { otelIntegration } from "eve/instrumentation/otel";++export default otelIntegration({+ traceExporter: new OTLPHttpProtoTraceExporter({+ url: process.env.SENTRY_OTLP_TRACES_ENDPOINT!,+ headers: {+ "x-sentry-auth": \`sentry sentry_key=\${process.env.SENTRY_PUBLIC_KEY}\`,+ },+ }),});\`\`\``,- configure: `Copy the OTLP traces endpoint and public key from your Sentry project under **Settings → Client Keys (DSN)** and expose them as environment variables. Sentry's OTLP intake accepts traces only, and span events are dropped at ingestion. See the [instrumentation guide](/docs/observability/instrumentation) for the trace hierarchy and the \`recordInputs\`/\`recordOutputs\` controls.`,+ configure: `Copy the OTLP traces endpoint and public key from your Sentry project under **Settings → Client Keys (DSN)** and expose them as environment variables. Sentry's OTLP intake accepts traces only, and span events are dropped at ingestion. See the [OpenTelemetry guide](/docs/observability/otel) for trace topology and content policy.`,},"datadog-instrumentation": {logo: "datadog",- docsHref: "/docs/observability/instrumentation",+ docsHref: "/docs/observability/otel",keywords: ["otel", "opentelemetry", "tracing", "observability", "apm", "otlp"],install: `Add Datadog instrumentation from eve's registry:\`\`\`basheve add instrumentation/datadog\`\`\``,- quickStart: `Create \`agent/instrumentation.ts\` and point the OTLP exporter at Datadog's intake for your site, authenticated with your API key:+ quickStart: `Create \`agent/instrumentation/datadog.ts\` and point the OTLP exporter at Datadog's intake for your site, authenticated with your API key:\`\`\`ts-// agent/instrumentation.ts-import { defineInstrumentation } from "eve/instrumentation";-import { OTLPHttpProtoTraceExporter, registerOTel } from "@vercel/otel";--export default defineInstrumentation({- setup: ({ agentName }) =>- registerOTel({- serviceName: agentName,- traceExporter: new OTLPHttpProtoTraceExporter({- url: process.env.DATADOG_OTLP_TRACES_ENDPOINT!,- headers: { "dd-api-key": process.env.DD_API_KEY! },- }),- }),+// agent/instrumentation/datadog.ts+import { OTLPHttpProtoTraceExporter } from "@vercel/otel";+import { otelIntegration } from "eve/instrumentation/otel";++export default otelIntegration({+ traceExporter: new OTLPHttpProtoTraceExporter({+ url: process.env.DATADOG_OTLP_TRACES_ENDPOINT!,+ headers: { "dd-api-key": process.env.DD_API_KEY! },+ }),});\`\`\``,- configure: `Datadog's direct OTLP trace intake is site-specific (for example \`datadoghq.com\` vs \`datadoghq.eu\`) and currently in Preview; look up the endpoint for your site in Datadog's OTLP intake docs. For production, Datadog recommends routing through an OpenTelemetry Collector with the Datadog exporter instead. See the [instrumentation guide](/docs/observability/instrumentation) for the trace hierarchy and the \`recordInputs\`/\`recordOutputs\` controls.`,+ configure: `Datadog's direct OTLP trace intake is site-specific (for example \`datadoghq.com\` vs \`datadoghq.eu\`) and currently in Preview; look up the endpoint for your site in Datadog's OTLP intake docs. For production, Datadog recommends routing through an OpenTelemetry Collector with the Datadog exporter instead. See the [OpenTelemetry guide](/docs/observability/otel) for trace topology and content policy.`,relatedResources: [incidentResponseGuide],},"honeycomb-instrumentation": {logo: "honeycomb",- docsHref: "/docs/observability/instrumentation",+ docsHref: "/docs/observability/otel",keywords: ["otel", "opentelemetry", "tracing", "observability", "queries", "otlp"],install: `Add Honeycomb instrumentation from eve's registry. Honeycomb ingests OTLP directly:@@ -2472,29 +2435,25 @@ export default defineInstrumentation({eve add instrumentation/honeycomb\`\`\``,- quickStart: `Create \`agent/instrumentation.ts\` and send traces to Honeycomb's OTLP endpoint with your ingest key:+ quickStart: `Create \`agent/instrumentation/honeycomb.ts\` and send traces to Honeycomb's OTLP endpoint with your ingest key:\`\`\`ts-// agent/instrumentation.ts-import { defineInstrumentation } from "eve/instrumentation";-import { OTLPHttpProtoTraceExporter, registerOTel } from "@vercel/otel";--export default defineInstrumentation({- setup: ({ agentName }) =>- registerOTel({- serviceName: agentName,- traceExporter: new OTLPHttpProtoTraceExporter({- url: "https://api.honeycomb.io/v1/traces",- headers: { "x-honeycomb-team": process.env.HONEYCOMB_API_KEY! },- }),- }),+// agent/instrumentation/honeycomb.ts+import { OTLPHttpProtoTraceExporter } from "@vercel/otel";+import { otelIntegration } from "eve/instrumentation/otel";++export default otelIntegration({+ traceExporter: new OTLPHttpProtoTraceExporter({+ url: "https://api.honeycomb.io/v1/traces",+ headers: { "x-honeycomb-team": process.env.HONEYCOMB_API_KEY! },+ }),});\`\`\``,- configure: `Create an ingest key under your Honeycomb environment settings and expose it as \`HONEYCOMB_API_KEY\`. Spans arrive in a dataset named after your agent (the OTel service name). EU teams use \`https://api.eu1.honeycomb.io/v1/traces\`. See the [instrumentation guide](/docs/observability/instrumentation) for the trace hierarchy and the \`recordInputs\`/\`recordOutputs\` controls.`,+ configure: `Create an ingest key under your Honeycomb environment settings and expose it as \`HONEYCOMB_API_KEY\`. Spans arrive in a dataset named after your agent (the OTel service name). EU teams use \`https://api.eu1.honeycomb.io/v1/traces\`. See the [OpenTelemetry guide](/docs/observability/otel) for trace topology and content policy.`,},arize: {logo: "arize",- docsHref: "/docs/observability/instrumentation",+ docsHref: "/docs/observability/otel",keywords: ["otel", "opentelemetry", "tracing", "llm observability", "evaluation", "otlp"],install: `Add Arize instrumentation from eve's registry. Arize AX ingests OTLP directly:@@ -2502,33 +2461,28 @@ export default defineInstrumentation({eve add instrumentation/arize\`\`\``,- quickStart: `Create \`agent/instrumentation.ts\` and send traces to Arize's OTLP endpoint with your space ID and API key:+ quickStart: `Create \`agent/instrumentation/arize.ts\` and send traces to Arize's OTLP endpoint with your space ID and API key:\`\`\`ts-// agent/instrumentation.ts-import { defineInstrumentation } from "eve/instrumentation";-import { OTLPHttpProtoTraceExporter, registerOTel } from "@vercel/otel";--export default defineInstrumentation({- setup: ({ agentName }) =>- registerOTel({- serviceName: agentName,- attributes: { "openinference.project.name": agentName },- traceExporter: new OTLPHttpProtoTraceExporter({- url: "https://otlp.arize.com/v1/traces",- headers: {- space_id: process.env.ARIZE_SPACE_ID!,- api_key: process.env.ARIZE_API_KEY!,- },- }),- }),+// agent/instrumentation/arize.ts+import { OTLPHttpProtoTraceExporter } from "@vercel/otel";+import { otelIntegration } from "eve/instrumentation/otel";++export default otelIntegration({+ traceExporter: new OTLPHttpProtoTraceExporter({+ url: "https://otlp.arize.com/v1/traces",+ headers: {+ space_id: process.env.ARIZE_SPACE_ID!,+ api_key: process.env.ARIZE_API_KEY!,+ },+ }),});\`\`\``,- configure: `Copy the space ID and API key from your Arize AX space settings and expose them as \`ARIZE_SPACE_ID\` and \`ARIZE_API_KEY\`. The \`openinference.project.name\` resource attribute routes spans to a project named after your agent. See the [instrumentation guide](/docs/observability/instrumentation) for the trace hierarchy and the \`recordInputs\`/\`recordOutputs\` controls.`,+ configure: `Copy the space ID and API key from your Arize AX space settings and expose them as \`ARIZE_SPACE_ID\` and \`ARIZE_API_KEY\`. See the [OpenTelemetry guide](/docs/observability/otel) for trace topology, resource attributes, and content policy.`,},raindrop: {logo: "raindrop",- docsHref: "/docs/observability/instrumentation",+ docsHref: "/docs/observability/otel",keywords: ["otel", "opentelemetry", "tracing", "observability", "ai issues", "otlp"],install: `Add Raindrop instrumentation from eve's registry. Raindrop ingests OTLP directly:@@ -2536,52 +2490,44 @@ export default defineInstrumentation({eve add instrumentation/raindrop\`\`\``,- quickStart: `Create \`agent/instrumentation.ts\` and send traces to Raindrop's OTLP endpoint with your write key:+ quickStart: `Create \`agent/instrumentation/raindrop.ts\` and send traces to Raindrop's OTLP endpoint with your write key:\`\`\`ts-// agent/instrumentation.ts-import { defineInstrumentation } from "eve/instrumentation";-import { OTLPHttpProtoTraceExporter, registerOTel } from "@vercel/otel";--export default defineInstrumentation({- setup: ({ agentName }) =>- registerOTel({- serviceName: agentName,- traceExporter: new OTLPHttpProtoTraceExporter({- url: "https://api.raindrop.ai/v1/traces",- headers: {- Authorization: \`Bearer \${process.env.RAINDROP_WRITE_KEY}\`,- },- }),- }),+// agent/instrumentation/raindrop.ts+import { OTLPHttpProtoTraceExporter } from "@vercel/otel";+import { otelIntegration } from "eve/instrumentation/otel";++export default otelIntegration({+ traceExporter: new OTLPHttpProtoTraceExporter({+ url: "https://api.raindrop.ai/v1/traces",+ headers: {+ Authorization: \`Bearer \${process.env.RAINDROP_WRITE_KEY}\`,+ },+ }),});\`\`\``,- configure: `Create a write key in the Raindrop dashboard and expose it as \`RAINDROP_WRITE_KEY\`. Raindrop's Vercel AI SDK integration picks up the AI SDK spans eve emits on every turn. See the [instrumentation guide](/docs/observability/instrumentation) for the trace hierarchy and the \`recordInputs\`/\`recordOutputs\` controls.`,+ configure: `Create a write key in the Raindrop dashboard and expose it as \`RAINDROP_WRITE_KEY\`. Raindrop's Vercel AI SDK integration picks up the AI SDK spans eve emits on every turn. See the [OpenTelemetry guide](/docs/observability/otel) for trace topology and content policy.`,},jaeger: {logo: "jaeger",- docsHref: "/docs/observability/instrumentation",+ docsHref: "/docs/observability/otel",keywords: ["otel", "opentelemetry", "tracing", "observability", "local", "self-hosted"],install: `Add Jaeger instrumentation from eve's registry:\`\`\`basheve add instrumentation/jaeger\`\`\``,- quickStart: `Create \`agent/instrumentation.ts\` and point the OTLP exporter at your Jaeger collector:+ quickStart: `Create \`agent/instrumentation/jaeger.ts\` and point the OTLP exporter at your Jaeger collector:\`\`\`ts-// agent/instrumentation.ts-import { defineInstrumentation } from "eve/instrumentation";-import { OTLPHttpProtoTraceExporter, registerOTel } from "@vercel/otel";--export default defineInstrumentation({- setup: ({ agentName }) =>- registerOTel({- serviceName: agentName,- traceExporter: new OTLPHttpProtoTraceExporter({- url: "http://localhost:4318/v1/traces",- }),- }),+// agent/instrumentation/jaeger.ts+import { OTLPHttpProtoTraceExporter } from "@vercel/otel";+import { otelIntegration } from "eve/instrumentation/otel";++export default otelIntegration({+ traceExporter: new OTLPHttpProtoTraceExporter({+ url: "http://localhost:4318/v1/traces",+ }),});\`\`\``,configure: `Run Jaeger locally with Docker and open the UI at \`http://localhost:16686\`:@@ -2590,7 +2536,7 @@ export default defineInstrumentation({docker run --rm -p 16686:16686 -p 4318:4318 jaegertracing/jaeger:latest\`\`\`-Point the exporter at your collector's OTLP HTTP endpoint when self-hosting. See the [instrumentation guide](/docs/observability/instrumentation) for the trace hierarchy and the \`recordInputs\`/\`recordOutputs\` controls.`,+Point the exporter at your collector's OTLP HTTP endpoint when self-hosting. See the [OpenTelemetry guide](/docs/observability/otel) for trace topology and content policy.`,},};@@ -2700,7 +2646,7 @@ function buildInstrumentation(entry: IntegrationEntry): Integration {const presentation = instrumentationPresentations[entry.slug];if (presentation === undefined) {throw new Error(- `Instrumentation provider "${entry.slug}" is in the catalog gallery but has no docs presentation.`,+ `Instrumentation entry "${entry.slug}" is in the catalog gallery but has no docs presentation.`,);}return {diff --git a/apps/docs/lib/integrations/discovery.test.ts b/apps/docs/lib/integrations/discovery.test.tsindex 3c6169d31..40b854d3c 100644--- a/apps/docs/lib/integrations/discovery.test.ts+++ b/apps/docs/lib/integrations/discovery.test.ts@@ -291,13 +291,15 @@ describe("integration discovery", () => {expect(markdown).not.toContain("### MCP ·");});- it("renders instrumentation providers with registry installation", () => {+ it("renders instrumentation integrations with registry installation", () => {const braintrust = getIntegration("braintrust");expect(braintrust).toBeDefined();const markdown = integrationMarkdown(braintrust!);expect(markdown).toContain("eve add instrumentation/braintrust");- expect(markdown).toContain("agent/instrumentation.ts");+ expect(markdown).toContain("agent/instrumentation/braintrust.ts");+ expect(markdown).toContain("braintrustEveInstrumentation");+ expect(markdown).not.toContain("// agent/hooks/braintrust.ts");expect(markdown).toContain("BRAINTRUST_API_KEY");const posthog = getIntegration("posthog-instrumentation");diff --git a/apps/docs/package.json b/apps/docs/package.jsonindex 17cd8981e..5f1a6b6fc 100644--- a/apps/docs/package.json+++ b/apps/docs/package.json@@ -93,7 +93,7 @@"@vgpu/adapter-node": "0.0.7","@webgpu/types": "^0.1.69","@zernio/chat-sdk-adapter": "0.5.0",- "braintrust": "3.24.0",+ "braintrust": "3.29.0","chat": "4.41.0","chat-adapter-sendblue": "0.2.0","eve": "workspace:*",diff --git a/apps/docs/registry.json b/apps/docs/registry.jsonindex aac5ddbb8..fdeeb6911 100644--- a/apps/docs/registry.json+++ b/apps/docs/registry.json@@ -2512,7 +2512,7 @@"type": "registry:item","title": "Braintrust","description": "Trace eve agent sessions in Braintrust, including turns, steps, tool calls, and subagent interactions.",- "dependencies": ["braintrust"],+ "dependencies": ["braintrust@^3.29.0"],"envVars": {"BRAINTRUST_API_KEY": ""},@@ -2520,12 +2520,7 @@{"path": "registry/instrumentation/braintrust.ts","type": "registry:file",- "target": "agent/instrumentation.ts"- },- {- "path": "registry/instrumentation/braintrust-hook.ts",- "type": "registry:file",- "target": "agent/hooks/braintrust.ts"+ "target": "agent/instrumentation/braintrust.ts"}]},@@ -2549,7 +2544,7 @@{"path": "registry/instrumentation/posthog.ts","type": "registry:file",- "target": "agent/instrumentation.ts"+ "target": "agent/instrumentation/posthog.ts"}]},@@ -2567,7 +2562,7 @@{"path": "registry/instrumentation/sentry.ts","type": "registry:file",- "target": "agent/instrumentation.ts"+ "target": "agent/instrumentation/sentry.ts"}]},@@ -2585,7 +2580,7 @@{"path": "registry/instrumentation/datadog.ts","type": "registry:file",- "target": "agent/instrumentation.ts"+ "target": "agent/instrumentation/datadog.ts"}]},@@ -2602,7 +2597,7 @@{"path": "registry/instrumentation/honeycomb.ts","type": "registry:file",- "target": "agent/instrumentation.ts"+ "target": "agent/instrumentation/honeycomb.ts"}]},@@ -2620,7 +2615,7 @@{"path": "registry/instrumentation/arize.ts","type": "registry:file",- "target": "agent/instrumentation.ts"+ "target": "agent/instrumentation/arize.ts"}]},@@ -2637,7 +2632,7 @@{"path": "registry/instrumentation/raindrop.ts","type": "registry:file",- "target": "agent/instrumentation.ts"+ "target": "agent/instrumentation/raindrop.ts"}]},@@ -2651,7 +2646,7 @@{"path": "registry/instrumentation/jaeger.ts","type": "registry:file",- "target": "agent/instrumentation.ts"+ "target": "agent/instrumentation/jaeger.ts"}]}diff --git a/apps/docs/registry/instrumentation/arize.ts b/apps/docs/registry/instrumentation/arize.tsindex b1edd2972..1f1b8f7cd 100644--- a/apps/docs/registry/instrumentation/arize.ts+++ b/apps/docs/registry/instrumentation/arize.ts@@ -1,17 +1,15 @@-import { OTLPHttpProtoTraceExporter, registerOTel } from "@vercel/otel";-import { defineInstrumentation } from "eve/instrumentation";+import { OTLPHttpProtoTraceExporter } from "@vercel/otel";+import { otelIntegration } from "eve/instrumentation/otel";-export default defineInstrumentation({- setup: ({ agentName }) =>- registerOTel({- serviceName: agentName,- attributes: { "openinference.project.name": agentName },- traceExporter: new OTLPHttpProtoTraceExporter({- url: "https://otlp.arize.com/v1/traces",- headers: {- space_id: process.env.ARIZE_SPACE_ID!,- api_key: process.env.ARIZE_API_KEY!,- },- }),- }),+export default otelIntegration({+ exportPolicy: {+ span: () => ({ redact: true, inputs: true, outputs: true }),+ },+ traceExporter: new OTLPHttpProtoTraceExporter({+ url: "https://otlp.arize.com/v1/traces",+ headers: {+ space_id: process.env.ARIZE_SPACE_ID!,+ api_key: process.env.ARIZE_API_KEY!,+ },+ }),});diff --git a/apps/docs/registry/instrumentation/braintrust-hook.ts b/apps/docs/registry/instrumentation/braintrust-hook.tsdeleted file mode 100644index 715d4ae9f..000000000--- a/apps/docs/registry/instrumentation/braintrust-hook.ts+++ /dev/null@@ -1,12 +0,0 @@-import { braintrustEveHook } from "braintrust";-import { defineState } from "eve/context";-import { defineHook } from "eve/hooks";--export default defineHook(- braintrustEveHook({- defineState,- metadata: {- app: "my-eve-agent", // Replace with your app name- },- }) as Parameters<typeof defineHook>[0],-);diff --git a/apps/docs/registry/instrumentation/braintrust.ts b/apps/docs/registry/instrumentation/braintrust.tsindex 1d4180ab6..d180ed294 100644--- a/apps/docs/registry/instrumentation/braintrust.ts+++ b/apps/docs/registry/instrumentation/braintrust.ts@@ -1,15 +1,13 @@import { braintrustEveInstrumentation, initLogger } from "braintrust";-import { defineState } from "eve/context";-import { defineInstrumentation } from "eve/instrumentation";-export default defineInstrumentation(- braintrustEveInstrumentation({- defineState,- setup: ({ agentName }) => {- initLogger({- projectName: agentName,- apiKey: process.env.BRAINTRUST_API_KEY,- });- },- }) as Parameters<typeof defineInstrumentation>[0],-);+export default braintrustEveInstrumentation({+ metadata: {+ app: "my-eve-agent", // Replace with your app name+ },+ setup: ({ agentName }) => {+ initLogger({+ projectName: agentName,+ apiKey: process.env.BRAINTRUST_API_KEY,+ });+ },+});diff --git a/apps/docs/registry/instrumentation/datadog.ts b/apps/docs/registry/instrumentation/datadog.tsindex f90b70260..49a5ad4e9 100644--- a/apps/docs/registry/instrumentation/datadog.ts+++ b/apps/docs/registry/instrumentation/datadog.ts@@ -1,13 +1,12 @@-import { OTLPHttpProtoTraceExporter, registerOTel } from "@vercel/otel";-import { defineInstrumentation } from "eve/instrumentation";+import { OTLPHttpProtoTraceExporter } from "@vercel/otel";+import { otelIntegration } from "eve/instrumentation/otel";-export default defineInstrumentation({- setup: ({ agentName }) =>- registerOTel({- serviceName: agentName,- traceExporter: new OTLPHttpProtoTraceExporter({- url: process.env.DATADOG_OTLP_TRACES_ENDPOINT!,- headers: { "dd-api-key": process.env.DD_API_KEY! },- }),- }),+export default otelIntegration({+ exportPolicy: {+ span: () => ({ redact: true, inputs: true, outputs: true }),+ },+ traceExporter: new OTLPHttpProtoTraceExporter({+ url: process.env.DATADOG_OTLP_TRACES_ENDPOINT!,+ headers: { "dd-api-key": process.env.DD_API_KEY! },+ }),});diff --git a/apps/docs/registry/instrumentation/honeycomb.ts b/apps/docs/registry/instrumentation/honeycomb.tsindex b2c8767b0..641f3b5a8 100644--- a/apps/docs/registry/instrumentation/honeycomb.ts+++ b/apps/docs/registry/instrumentation/honeycomb.ts@@ -1,13 +1,12 @@-import { OTLPHttpProtoTraceExporter, registerOTel } from "@vercel/otel";-import { defineInstrumentation } from "eve/instrumentation";+import { OTLPHttpProtoTraceExporter } from "@vercel/otel";+import { otelIntegration } from "eve/instrumentation/otel";-export default defineInstrumentation({- setup: ({ agentName }) =>- registerOTel({- serviceName: agentName,- traceExporter: new OTLPHttpProtoTraceExporter({- url: "https://api.honeycomb.io/v1/traces",- headers: { "x-honeycomb-team": process.env.HONEYCOMB_API_KEY! },- }),- }),+export default otelIntegration({+ exportPolicy: {+ span: () => ({ redact: true, inputs: true, outputs: true }),+ },+ traceExporter: new OTLPHttpProtoTraceExporter({+ url: "https://api.honeycomb.io/v1/traces",+ headers: { "x-honeycomb-team": process.env.HONEYCOMB_API_KEY! },+ }),});diff --git a/apps/docs/registry/instrumentation/jaeger.ts b/apps/docs/registry/instrumentation/jaeger.tsindex effc4225f..3b171749e 100644--- a/apps/docs/registry/instrumentation/jaeger.ts+++ b/apps/docs/registry/instrumentation/jaeger.ts@@ -1,12 +1,11 @@-import { OTLPHttpProtoTraceExporter, registerOTel } from "@vercel/otel";-import { defineInstrumentation } from "eve/instrumentation";+import { OTLPHttpProtoTraceExporter } from "@vercel/otel";+import { otelIntegration } from "eve/instrumentation/otel";-export default defineInstrumentation({- setup: ({ agentName }) =>- registerOTel({- serviceName: agentName,- traceExporter: new OTLPHttpProtoTraceExporter({- url: "http://localhost:4318/v1/traces",- }),- }),+export default otelIntegration({+ exportPolicy: {+ span: () => ({ redact: true, inputs: true, outputs: true }),+ },+ traceExporter: new OTLPHttpProtoTraceExporter({+ url: "http://localhost:4318/v1/traces",+ }),});diff --git a/apps/docs/registry/instrumentation/posthog.ts b/apps/docs/registry/instrumentation/posthog.tsindex 1fec479dc..62f90f188 100644--- a/apps/docs/registry/instrumentation/posthog.ts+++ b/apps/docs/registry/instrumentation/posthog.ts@@ -1,31 +1,23 @@-import { trace } from "@opentelemetry/api";import { SimpleSpanProcessor } from "@opentelemetry/sdk-trace-base";import { PostHogTraceExporter } from "@posthog/ai/otel";-import { registerOTel } from "@vercel/otel";-import { defineInstrumentation } from "eve/instrumentation";+import { otelIntegration } from "eve/instrumentation/otel";-export default defineInstrumentation({- setup: ({ agentName }) =>- registerOTel({- serviceName: agentName,- spanProcessors: [- new SimpleSpanProcessor(- new PostHogTraceExporter({- projectToken: process.env.POSTHOG_PROJECT_TOKEN!,- host: process.env.POSTHOG_HOST,- }),- ),- ],- }),- events: {- "step.started"(input) {- const distinctId =- input.session.auth.initiator?.principalId ?? input.session.auth.current?.principalId;-- if (!distinctId) return undefined;+export default otelIntegration({+ exportPolicy: {+ span: () => ({ redact: true, inputs: true, outputs: true }),+ },+ spanProcessors: [+ new SimpleSpanProcessor(+ new PostHogTraceExporter({+ projectToken: process.env.POSTHOG_PROJECT_TOKEN!,+ host: process.env.POSTHOG_HOST,+ }),+ ),+ ],+ runtimeContext(input) {+ const distinctId =+ input.session.auth.initiator?.principalId ?? input.session.auth.current?.principalId;- trace.getActiveSpan()?.setAttribute("posthog.distinct_id", distinctId);- return { runtimeContext: { posthog_distinct_id: distinctId } };- },+ return distinctId ? { "posthog.distinct_id": distinctId } : undefined;},});diff --git a/apps/docs/registry/instrumentation/raindrop.ts b/apps/docs/registry/instrumentation/raindrop.tsindex de7d2ac53..a8d18813a 100644--- a/apps/docs/registry/instrumentation/raindrop.ts+++ b/apps/docs/registry/instrumentation/raindrop.ts@@ -1,15 +1,14 @@-import { OTLPHttpProtoTraceExporter, registerOTel } from "@vercel/otel";-import { defineInstrumentation } from "eve/instrumentation";+import { OTLPHttpProtoTraceExporter } from "@vercel/otel";+import { otelIntegration } from "eve/instrumentation/otel";-export default defineInstrumentation({- setup: ({ agentName }) =>- registerOTel({- serviceName: agentName,- traceExporter: new OTLPHttpProtoTraceExporter({- url: "https://api.raindrop.ai/v1/traces",- headers: {- Authorization: `Bearer ${process.env.RAINDROP_WRITE_KEY}`,- },- }),- }),+export default otelIntegration({+ exportPolicy: {+ span: () => ({ redact: true, inputs: true, outputs: true }),+ },+ traceExporter: new OTLPHttpProtoTraceExporter({+ url: "https://api.raindrop.ai/v1/traces",+ headers: {+ Authorization: `Bearer ${process.env.RAINDROP_WRITE_KEY}`,+ },+ }),});diff --git a/apps/docs/registry/instrumentation/sentry.ts b/apps/docs/registry/instrumentation/sentry.tsindex 779c6ee50..4981c90dc 100644--- a/apps/docs/registry/instrumentation/sentry.ts+++ b/apps/docs/registry/instrumentation/sentry.ts@@ -1,15 +1,14 @@-import { OTLPHttpProtoTraceExporter, registerOTel } from "@vercel/otel";-import { defineInstrumentation } from "eve/instrumentation";+import { OTLPHttpProtoTraceExporter } from "@vercel/otel";+import { otelIntegration } from "eve/instrumentation/otel";-export default defineInstrumentation({- setup: ({ agentName }) =>- registerOTel({- serviceName: agentName,- traceExporter: new OTLPHttpProtoTraceExporter({- url: process.env.SENTRY_OTLP_TRACES_ENDPOINT!,- headers: {- "x-sentry-auth": `sentry sentry_key=${process.env.SENTRY_PUBLIC_KEY}`,- },- }),- }),+export default otelIntegration({+ exportPolicy: {+ span: () => ({ redact: true, inputs: true, outputs: true }),+ },+ traceExporter: new OTLPHttpProtoTraceExporter({+ url: process.env.SENTRY_OTLP_TRACES_ENDPOINT!,+ headers: {+ "x-sentry-auth": `sentry sentry_key=${process.env.SENTRY_PUBLIC_KEY}`,+ },+ }),});diff --git a/apps/docs/scripts/validate-instrumentation-registry.ts b/apps/docs/scripts/validate-instrumentation-registry.tsindex 433ab7f62..aaac65595 100644--- a/apps/docs/scripts/validate-instrumentation-registry.ts+++ b/apps/docs/scripts/validate-instrumentation-registry.ts@@ -37,7 +37,7 @@ const expectedSlugs = instrumentationEntries()const actualSlugs = items.map((item) => item.name.slice("instrumentation/".length));if (expectedSlugs.some((slug) => slug === undefined)) {- throw new Error("Every catalog instrumentation provider needs a registry slug mapping.");+ throw new Error("Every catalog instrumentation entry needs a registry slug mapping.");}if (JSON.stringify(actualSlugs) !== JSON.stringify(expectedSlugs)) {throw new Error(@@ -51,16 +51,8 @@ for (const item of items) {const expectedFiles: RegistryFile[] = [{path: expectedPath,- target: "agent/instrumentation.ts",+ target: `agent/instrumentation/${slug}.ts`,},- ...(slug === "braintrust"- ? [- {- path: "registry/instrumentation/braintrust-hook.ts",- target: "agent/hooks/braintrust.ts",- },- ]- : []),];const actualFiles = item.files?.map(({ path, target }) => ({ path, target }));if (JSON.stringify(actualFiles) !== JSON.stringify(expectedFiles)) {@@ -69,4 +61,16 @@ for (const item of items) {for (const file of expectedFiles) {await access(join(docsRoot, file.path));}+ if (slug !== "braintrust") {+ const source = await readFile(join(docsRoot, expectedPath), "utf8");+ if (+ !source.includes("redact: true") ||+ !source.includes("inputs: true") ||+ !source.includes("outputs: true")+ ) {+ throw new Error(+ `Registry item "${item.name}" must preserve metadata-only export with an explicit redaction policy.`,+ );+ }+ }}diff --git a/docs/agent-config.md b/docs/agent-config.mdindex abd868faa..443610f6e 100644--- a/docs/agent-config.md+++ b/docs/agent-config.md@@ -350,7 +350,7 @@ During `eve dev`, ordinary dependencies are bundled into each retained runtime g| Per-tool approval (HITL) | `agent/tools/*.ts`, [Tools](./tools) || Inbound auth & network policy | the channel layer, [Auth & route protection](./guides/auth-and-route-protection) || Sandbox / workspace | `agent/sandbox/`, [Sandbox](./sandbox) |-| Telemetry & debugging | `agent/instrumentation.ts`, [Instrumentation](./observability/instrumentation) |+| Telemetry & debugging | `agent/instrumentation/`, [Instrumentation](./observability/instrumentation) |## What to read nextdiff --git a/docs/concepts/security-model.md b/docs/concepts/security-model.mdindex 4ab58960b..6f14cd023 100644--- a/docs/concepts/security-model.md+++ b/docs/concepts/security-model.md@@ -42,7 +42,10 @@ eve sends data where your agent configuration and runtime choices send it:- Model inputs and outputs flow to the model or routing path selected in `agent.ts`, such as a Vercel AI Gateway model id or a provider-authored `LanguageModel`.- Tool and connection calls flow to the external services, MCP servers, OpenAPI endpoints, and channels you configure.- Sandbox commands can reach network destinations allowed by the sandbox network policy.-- Telemetry and eval data flows to the exporters and providers you configure in `instrumentation.ts` or eval settings.+- Telemetry flows to destinations configured under `agent/instrumentation/`.+ eve also records local traces during `eve dev` and exports to Vercel Agent+ Runs in preview and production by default. Eval data flows to the reporters+ configured in eval settings.eve stores durable session and workflow state needed to resume conversations, stream events, replay completed steps, and show run observability. You are responsible for deciding whether the selected channels, model providers, connected services, sandbox egress destinations, telemetry exporters, retention settings, and deletion controls are appropriate for your data and use case.diff --git a/docs/guides/dev-tui.md b/docs/guides/dev-tui.mdindex d01050cdc..38cf6f183 100644--- a/docs/guides/dev-tui.md+++ b/docs/guides/dev-tui.md@@ -102,7 +102,7 @@ By default, the UI shows `stderr` logs. Use `/loglevel <all|stderr|sandbox|none>Every `eve dev` process writes diagnostic logs to `.eve/logs/`, regardless of the display mode. Read them with [`eve logs`](../reference/cli#eve-logs).-Use `/traces` to inspect traces recorded during local development. See [Instrumentation](../observability/instrumentation#local-traces) for trace capture and retention settings.+Use `/traces` to inspect traces recorded during local development. See [Local traces](../observability/otel#local-traces) for trace capture and retention settings.## Display optionsdiff --git a/docs/guides/hooks.md b/docs/guides/hooks.mdindex 48d780ca3..070cdf06b 100644--- a/docs/guides/hooks.md+++ b/docs/guides/hooks.md@@ -50,7 +50,7 @@ export default githubChannel({A GitHub channel event handler cannot fire for a Slack-owned session, so platform-specific side effects do not depend on an early-return guard. On a built-in channel, an authored handler replaces that channel's default handler for the same event key. Check the channel page before overriding events that deliver replies, progress, errors, or human-input prompts.-Use `ctx.channel.kind` inside a global hook only when the operation is otherwise agent-wide and conditional handling is intentional. For typed channel metadata in dynamic resolvers or instrumentation, import the channel definition and narrow with `isChannel`; see [Add runtime context](../observability/instrumentation#add-runtime-context).+Use `ctx.channel.kind` inside a global hook only when the operation is otherwise agent-wide and conditional handling is intentional. For typed channel metadata in dynamic resolvers or instrumentation, import the channel definition and narrow with `isChannel`; see [OpenTelemetry runtime context](../observability/otel#add-runtime-context).## Hook structure and contextdiff --git a/docs/guides/instrumentation/providers.mdx b/docs/guides/instrumentation/instrumentation.mdxsimilarity index 58%rename from docs/guides/instrumentation/providers.mdxrename to docs/guides/instrumentation/instrumentation.mdxindex cc7042233..707bfc980 100644--- a/docs/guides/instrumentation/providers.mdx+++ b/docs/guides/instrumentation/instrumentation.mdx@@ -1,42 +1,30 @@----title: "Instrumentation Providers"-description: "Configure experimental instrumentation providers, handle lifecycle events, and control the content each provider receives."-url: "/observability/instrumentation-providers"+title: "Instrumentation"+description: "Configure lifecycle instrumentation, handle runtime events, and control the content each destination receives."+url: "/observability/instrumentation"----<Callout type="warning" title="Experimental">- This API is experimental and may change without a deprecation period.-</Callout>+Add lifecycle instrumentation as files under `agent/instrumentation/`. Each+file handles eve runtime events independently. Configure trace exporters and+shared span settings with the [built-in OpenTelemetry APIs](./otel).-Instrumentation providers split observability into files under `agent/instrumentation/`. Each provider handles eve lifecycle events without owning the rest of the telemetry pipeline. Configure OpenTelemetry destinations with the [built-in OpenTelemetry APIs](./otel).+The instrumentation directory replaces `agent/instrumentation.ts`. See+[Migrate instrumentation](/docs/observability/instrumentation-migration) when+upgrading from `eve < 0.62.0`.-Enable it explicitly in `agent.ts`:+## Add instrumentation-```ts title="agent/agent.ts"-import { defineAgent } from "eve";--export default defineAgent({- model: "anthropic/claude-sonnet-5",- experimental: {- instrumentationProviders: true,- },-});-```--The provider directory replaces `agent/instrumentation.ts`; the two layouts cannot be used together. See [Instrumentation](../observability/instrumentation) for the current single-file API.--## Add a provider--The filename identifies the provider slot. A lifecycle-event provider file-must default-export `defineInstrumentation(...)` or `disableInstrumentation()`.+The filename identifies the instrumentation slot. A lifecycle-event file must+default-export `defineInstrumentation(...)` or `disableInstrumentation()`.See [OpenTelemetry](./otel) for the supported OTel declarations.```textagent/instrumentation/- audit.ts lifecycle event provider+ audit.ts lifecycle instrumentation```-This provider records action timing and identity without receiving tool arguments or results:+This instrumentation records action timing and identity without receiving tool+arguments or results:```ts title="agent/instrumentation/audit.ts"import { defineInstrumentation } from "eve/instrumentation";@@ -60,12 +48,15 @@ export default defineInstrumentation({});```-`ctx.state` is JSON storage scoped to this provider and operation. It survives durable suspension and is released after the terminal event.+`ctx.state` is JSON storage scoped to this file and operation. It survives+durable suspension and is released after the terminal event.## Control inputs and outputs-Each provider has an independent `tracePolicy`. It decides whether the provider-receives a trace and whether its events include input or output content.+Each lifecycle file created with `defineInstrumentation(...)` has an+independent `tracePolicy`. It decides whether that file receives a trace and+whether its events include input or output content. OpenTelemetry destinations+share the process-wide policy declared by `otel(...)`.```ts title="agent/instrumentation/audit.ts"import { defineInstrumentation } from "eve/instrumentation";@@ -92,8 +83,8 @@ The function receives `agentName`, `channel`, `audience`, `mode`,`"unknown"`; `environment` is `"development"`, `"preview"`, or`"production"`.-Without a policy, or when it returns `true`, eve sends the provider metadata-for every trace. It includes input and output content in these cases:+Without a policy, or when it returns `true`, eve sends metadata for every+trace. It includes input and output content in these cases:| Environment | Audience | Content || --------------------- | ---------------------- | ------------------ |@@ -101,20 +92,21 @@ for every trace. It includes input and output content in these cases:| Preview or production | `public` | Inputs and outputs || Preview or production | `private` or `unknown` | Metadata only |-Return `{ emit: false }` to not sample the trace for this provider. Return+Return `{ emit: false }` to not sample the trace for this file. Return`{ emit: true, recordInputs, recordOutputs }` to choose the two contentdirections explicitly. Inputs include model prompts, tool arguments, channelinput, and user responses. Outputs include model responses, tool results,-requests for user input, provider metadata, and error details. Omitted content-fields are unavailable to the handler.+requests for user input, model provider metadata, and error details. Omitted+content fields are unavailable to the handler.The channel assigns the audience once when it creates the session. It controlscontent capture, not access. See [Audience](../channels/overview#audience) forhow the channel derives `public`, `private`, and `unknown`.-## Redact fields in a custom provider+## Redact fields-Lifecycle events are immutable snapshots. Copy the fields you need into a destination-specific payload and redact that copy before sending it:+Lifecycle events are immutable snapshots. Copy the fields you need into a+destination-specific payload and redact that copy before sending it:```ts title="agent/instrumentation/audit.ts"import { defineInstrumentation } from "eve/instrumentation";@@ -145,7 +137,7 @@ function redactApiKey(value: unknown): unknown {}async function sendAuditRecord(record: unknown): Promise<void> {- // Send the sanitized record to your provider.+ // Send the sanitized record to your destination.void record;}```@@ -154,15 +146,19 @@ Prefer `recordInputs: false` or `recordOutputs: false` when the destination does## Lifecycle events-Providers can handle session, channel delivery, turn, model attempt, model call, action, input request, and tool call events. Start and terminal events share an `idempotencyKey`, which can serve as a destination row ID.+Instrumentation can handle session, channel delivery, turn, model attempt,+model call, action, input request, and tool call events. Start and terminal+events share an `idempotencyKey`, which can serve as a destination row ID.An ordinary tool emits both `action.*` and `tool.call.*` events. Use `action.*` for eve's durable dispatch lifecycle, including tools, skills, subagents, and remote agents. Use `tool.call.*` only when you need the AI SDK's in-process tool execution boundary.-Handlers for different providers run concurrently and are failure-isolated. Do not depend on provider execution order. Use `flush` to drain buffered records and `shutdown` to release resources.+Handlers from different files run concurrently and are failure-isolated. Do+not depend on execution order. Use `flush` to drain buffered records and+`shutdown` to release resources.## What to read next-- [Instrumentation](../observability/instrumentation): configure the current single-file API-- [OpenTelemetry](./otel): configure OTel destinations and managed exports.+- [Migrate instrumentation](/docs/observability/instrumentation-migration): replace `agent/instrumentation.ts`.+- [OpenTelemetry](/docs/observability/otel): configure OTel destinations and managed exports.- [Local development](../guides/dev-tui): inspect local traces in the TUI-- [Hooks](../guides/hooks): react to runtime events outside the instrumentation provider API+- [Hooks](../guides/hooks): react to runtime events outside the instrumentation lifecyclediff --git a/docs/guides/instrumentation/meta.json b/docs/guides/instrumentation/meta.jsonindex 37c328157..432f06d41 100644--- a/docs/guides/instrumentation/meta.json+++ b/docs/guides/instrumentation/meta.json@@ -1,5 +1,5 @@{"title": "Observability","defaultOpen": false,- "pages": ["overview", "providers", "otel"]+ "pages": ["instrumentation", "otel", "migration"]}diff --git a/docs/guides/instrumentation/migration.md b/docs/guides/instrumentation/migration.mdnew file mode 100644index 000000000..2f9639e92--- /dev/null+++ b/docs/guides/instrumentation/migration.md@@ -0,0 +1,97 @@+---+title: "Migrate Instrumentation"+description: "Move a single instrumentation.ts configuration into lifecycle instrumentation and OpenTelemetry destinations."+url: "/observability/instrumentation-migration"+---++Replace `agent/instrumentation.ts` with path-named files under+`agent/instrumentation/`. Remove+`experimental.instrumentationProviders` from `agent.ts`; instrumentation+discovery is now always enabled.++## Preserve metadata-only capture++In the removed API, omitted `recordInputs` and `recordOutputs` settings both+defaulted to `false`. Once an OpenTelemetry destination is present, the new+default includes content during development and for public conversations.++Add `agent/instrumentation/otel.ts` with an explicit metadata-only policy+before moving exporters:++```ts title="agent/instrumentation/otel.ts"+import { otel } from "eve/instrumentation/otel";++export default otel({+ functionId: "support-agent",+ traceChannelRequests: true,+ tracePolicy: () => ({+ emit: true,+ recordInputs: false,+ recordOutputs: false,+ }),+});+```++After verifying each destination's retention and access controls, widen+`recordInputs` or `recordOutputs` deliberately if needed.++## Move an OpenTelemetry exporter++Move each exporter into its own destination file and replace startup+`registerOTel(...)` calls with `otelIntegration(...)`. Install `@vercel/otel`+if the exporter comes from that package:++```bash+pnpm add @vercel/otel+```++```ts title="agent/instrumentation/honeycomb.ts"+import { OTLPHttpProtoTraceExporter } from "@vercel/otel";+import { otelIntegration } from "eve/instrumentation/otel";++export default otelIntegration({+ exportPolicy: {+ span: () => ({ redact: true, inputs: true, outputs: true }),+ },+ traceExporter: new OTLPHttpProtoTraceExporter({+ url: "https://api.honeycomb.io/v1/traces",+ headers: {+ "x-honeycomb-team": process.env.HONEYCOMB_API_KEY!,+ },+ }),+});+```++The destination policy preserves metadata-only export even if the shared+OpenTelemetry policy is widened later. Add another file for each additional+destination; eve combines them into one pipeline.++## Move runtime context and lifecycle events++Use this mapping when splitting the old definition:++| `agent/instrumentation.ts` field | New location |+| -------------------------------- | -------------------------------------------- |+| `setup` with `registerOTel` | One `otelIntegration()` file per destination |+| `functionId` | `otel({ functionId })` |+| `recordInputs`, `recordOutputs` | `otel({ tracePolicy })` |+| `traceChannelRequests` | `otel({ traceChannelRequests })` |+| `events["step.started"]` | `otelIntegration({ runtimeContext })` |++Move `events["step.started"]` to the destination that needs those attributes;+see [Add runtime context](/docs/observability/otel#add-runtime-context). For+eve lifecycle events, create a separate file with `defineInstrumentation(...)`;+see+[Instrumentation](/docs/observability/instrumentation).++## Verify the migration++Run `eve build`. A remaining `agent/instrumentation.ts` fails the build with a+message directing you to the instrumentation directory.++Before verifying a Vercel deployment, configure trace sampling. A deployed eve+project needs at least one sampling rule with a rate above 0%; we recommend+setting the rate to 100%. See+[Enable tracing on Vercel](/docs/observability/otel#enable-tracing-on-vercel).++Then run the agent and verify each destination independently.diff --git a/docs/guides/instrumentation/otel.mdx b/docs/guides/instrumentation/otel.mdxindex 18a8e5714..48d4da8cd 100644--- a/docs/guides/instrumentation/otel.mdx+++ b/docs/guides/instrumentation/otel.mdx@@ -1,25 +1,22 @@---title: "OpenTelemetry"-description: "Configure OpenTelemetry destinations, content capture, and managed exports with Instrumentation Providers."+description: "Configure OpenTelemetry destinations, content capture, and managed exports."url: "/observability/otel"----<Callout type="warning" title="Experimental">- This API is experimental and may change without a deprecation period.-</Callout>--Use the built-in APIs from `eve/instrumentation/otel` to configure eve's-OpenTelemetry pipeline. This page requires the experimental-[Instrumentation Providers](./instrumentation-providers) layout.+eve configures its built-in OpenTelemetry destinations automatically.+`eve dev` records local traces, and preview and production deployments export+to Vercel Agent Runs by default. You do not need `otel()` or+`otelIntegration()` to use these defaults.## Configure OpenTelemetry-OpenTelemetry configuration has two parts:+`otel()` and `otelIntegration()` are optional:-- `otel()` declares process-wide settings such as the resource, sampler,- propagators, and trace capture policy. Declare it at most once.-- `otelIntegration()` adds one destination. Declare one file per exporter or- processor chain.+- Use `otel()` only when you need process-wide settings such as the resource,+ sampler, propagators, or trace capture policy. Declare it at most once.+- Use `otelIntegration()` only when adding a third-party OpenTelemetry+ destination. Declare one file per exporter or processor chain.Add `agent/instrumentation/otel.ts` when you need process-wide settings orwant to control the content eve writes to OpenTelemetry spans:@@ -39,26 +36,67 @@ export default otel({The OpenTelemetry `tracePolicy` is a capture ceiling shared by every OTeldestination. A destination cannot restore content excluded by this policy. It-does not affect lifecycle-event providers created with `defineInstrumentation()`.+does not affect lifecycle instrumentation created with `defineInstrumentation()`.See [Audience](../channels/overview#audience) for how channels classify theconversation passed to this policy.## Add an OpenTelemetry destination-Most agents only need a destination:+Use this section when sending traces to a third-party destination. Install+`@vercel/otel` before using its exporters:++```bash+pnpm add @vercel/otel+```-```ts title="agent/instrumentation/braintrust.ts"-import { BraintrustExporter } from "@braintrust/otel";+```ts title="agent/instrumentation/honeycomb.ts"+import { OTLPHttpProtoTraceExporter } from "@vercel/otel";import { otelIntegration } from "eve/instrumentation/otel";export default otelIntegration({- traceExporter: new BraintrustExporter({ filterAISpans: true }),+ exportPolicy: {+ span: () => ({ redact: true, inputs: true, outputs: true }),+ },+ traceExporter: new OTLPHttpProtoTraceExporter({+ url: "https://api.honeycomb.io/v1/traces",+ headers: {+ "x-honeycomb-team": process.env.HONEYCOMB_API_KEY!,+ },+ }),});```Pass `spanProcessors` to `otelIntegration()` when a custom destination needs-filtering or transformation. `exportPolicy` is for the built-in-`localTraces()` and `agentRuns()` destinations below.+filtering or transformation. The example's `exportPolicy` preserves span+metadata while removing inputs and outputs from this destination.++## Add runtime context++Use `runtimeContext` to add JSON values to AI SDK spans for each model attempt.+For typed channel metadata, import the channel definition and narrow with+`isChannel`:++```ts title="agent/instrumentation/support.ts"+import { isChannel } from "eve/instrumentation";+import { otelIntegration } from "eve/instrumentation/otel";++import supportChannel from "../channels/support";++export default otelIntegration({+ runtimeContext(input) {+ if (!isChannel(input.channel, supportChannel)) return undefined;++ return {+ "support.channel_id": input.channel.metadata.channelId ?? "",+ "support.user_id": input.channel.metadata.triggeringUserId ?? "",+ };+ },+});+```++The resolver receives the channel, session, final model input, step, and turn.+Keys beginning with `eve.` are reserved. Content excluded by+`otel({ tracePolicy })` is not available to the resolver.## Trace topology@@ -82,15 +120,13 @@ destination's span-search surface.## Manage built-in destinations-The provider layout has two environment-specific defaults:+Instrumentation has two environment-specific defaults.-- `local` records local traces during `eve dev`.-- `agent-runs` exports to Vercel Agent Runs in preview and production- deployments.+### Local traces-Omitting these files preserves the defaults. Reconfigure a destination by-exporting `localTraces()` or `agentRuns()` from the matching file. Disable one-explicitly:+`eve dev` records local traces by default. Omitting+`agent/instrumentation/local.ts` preserves that default. Export+`localTraces(...)` from that file to reconfigure it, or disable it explicitly:```ts title="agent/instrumentation/local.ts"import { disableInstrumentation } from "eve/instrumentation";@@ -98,11 +134,37 @@ import { disableInstrumentation } from "eve/instrumentation";export default disableInstrumentation();```-## Filter a managed destination+### Vercel Agent Runs++Preview and production deployments export to Vercel Agent Runs by default.+Omitting `agent/instrumentation/agent-runs.ts` preserves that default. Export+`agentRuns(...)` from that file to reconfigure it, or export+`disableInstrumentation()` to disable it.++## Enable tracing on Vercel++A deployed eve project needs at least one+[sampling rule with a rate above 0%](https://vercel.com/docs/tracing/always-on-tracing#enable-always-on-tracing)+before Vercel collects traces. We recommend setting the rate to **100%** for+eve projects so every matching request is traced.++Select your team and project, then open+[**Settings → Tracing**](https://vercel.com/d?to=%2F%5Bteam%5D%2F%5Bproject%5D%2Fsettings%2Ftracing&title=Go+to+Tracing+settings):++1. Select **Add Sampling Rule**.+2. Choose **All Environments**, **Production**, or **Preview**.+3. Set **Rate** to `100%`.+4. Select **Save**.++Tracing starts as soon as you save the rule. You can also manage sampling+rules with [`vercel traces config`](https://vercel.com/docs/cli/traces#manage-trace-sampling-rules).+The CLI accepts rates from 1 to 100%; add a 0% rule from the dashboard.++## Filter a destination-`localTraces()` and `agentRuns()` accept one `exportPolicy` object or an array-applied in order. Each policy filters spans and attributes before that-destination's processors receive them:+`otelIntegration()`, `localTraces()`, and `agentRuns()` accept one+`exportPolicy` object or an array applied in order. Each policy filters spans+and attributes before that destination's processors receive them:```ts title="agent/instrumentation/agent-runs.ts"import { agentRuns } from "eve/instrumentation/otel";@@ -153,6 +215,6 @@ before it.## What to read next-- [Instrumentation Providers](./instrumentation-providers): add lifecycle-event providers.-- [Instrumentation](../observability/instrumentation): configure the current single-file API.+- [Instrumentation](/docs/observability/instrumentation): handle eve lifecycle events.+- [Migrate instrumentation](/docs/observability/instrumentation-migration): replace `agent/instrumentation.ts`.- [Local development](../guides/dev-tui): inspect local traces in the TUI.diff --git a/docs/guides/instrumentation/overview.md b/docs/guides/instrumentation/overview.mddeleted file mode 100644index dafc18821..000000000--- a/docs/guides/instrumentation/overview.md+++ /dev/null@@ -1,199 +0,0 @@-----title: "Instrumentation"-description: "Trace an agent with OpenTelemetry in instrumentation.ts, read the workflow run tags eve emits, and debug discovery with eve info and the common-failures table."-url: "/observability/instrumentation"------Use `agent/instrumentation.ts` to configure OpenTelemetry for an eve agent.-eve discovers this file and runs it at server startup before agent code.--## Configure OpenTelemetry--Export `defineInstrumentation(...)` as the default export from-`agent/instrumentation.ts`. eve discovers the file and runs its `setup`-callback at server startup, before agent code runs.--```ts title="agent/instrumentation.ts"-import { BraintrustExporter } from "@braintrust/otel";-import { defineInstrumentation } from "eve/instrumentation";-import { registerOTel } from "@vercel/otel";--export default defineInstrumentation({- setup: ({ agentName }) =>- registerOTel({- serviceName: agentName,- traceExporter: new BraintrustExporter({- parent: `project_name:${agentName}`,- filterAISpans: true,- }),- }),-});-```--Use `setup` to register your OTel provider. eve supplies the resolved agent-name, so you do not need to hard-code a service name. Any OTel-compatible-backend works; install and configure the exporter it requires.--eve records metadata without model, tool, or memory-record content by default.-After reviewing the exporter's destination and retention path, opt in to the-content you need:--- `recordInputs` records message history and recalled memory records. It- defaults to `false`.-- `recordOutputs` records model outputs. It defaults to `false`.-- `functionId` overrides the function name on spans. It defaults to the agent- name.--The session's channel audience is a second gate on content capture. In-Vercel's preview and production deployments, eve records inputs and outputs-only for `public` sessions. During local development, local tracing retains all-content. See [Local traces](#local-traces) to learn more.--For the default eve HTTP channel, the audience is:--| Session creator | Audience |-| ---------------------------------------------------- | --------- |-| Anonymous caller | `unknown` |-| Authenticated `user`, `service`, or `runtime` caller | `private` |-| Any other principal type | `unknown` |--Set `audience: "public"` only for intentionally public traffic. Other-built-in channels classify their own conversations. See-[Audience](../channels/eve#audience) for the `eve` channel or-[Conversation audience](../channels/custom#conversation-audience) for a-custom channel.--## Add runtime context--Use `events["step.started"]` to add values to the AI SDK runtime context for a-model attempt. The AI SDK carries the returned values onto the model-call span-and its children.--```ts title="agent/instrumentation.ts"-import { defineInstrumentation, isChannel } from "eve/instrumentation";-import supportChannel from "./channels/support";--export default defineInstrumentation({- events: {- "step.started"(input) {- if (!isChannel(input.channel, supportChannel)) return undefined;-- return {- runtimeContext: {- "support.channel_id": input.channel.metadata.channelId ?? "",- "support.user_id": input.channel.metadata.triggeringUserId ?? "",- },- };- },- },-});-```--The callback receives the session, turn, step, channel, and final model input.-For an authored channel, import its definition and use `isChannel` before-accessing its typed metadata. Runtime instrumentation receives only the-metadata a channel explicitly exposes; it never falls back to raw channel-state.--## Trace topology--When `agent/instrumentation.ts` registers an OTel provider, each turn produces-this hierarchy:--```text-ai.eve.turn {eve.session.id}- +-- invoke_agent <model> gen_ai.operation.name=invoke_agent- +-- step 1 gen_ai.operation.name=agent_step- | +-- chat <model> gen_ai.operation.name=chat- | +-- execute_tool search gen_ai.operation.name=execute_tool- +-- step 2- | +-- chat <model>- | +-- execute_tool read- +-- step 3 (final text)- +-- chat <model>-```--eve creates the `ai.eve.turn` parent span and passes telemetry to the-[AI SDK](https://ai-sdk.dev/docs/ai-sdk-core/telemetry), which traces model-calls and tool executions. The AI SDK names those spans according to the-OpenTelemetry GenAI semantic conventions.--Set `traceChannelRequests: true` to create one OTel `SERVER` span for each-inbound channel HTTP request. The span parents the turn tree and any-`hook.resume` or outgoing HTTP spans. It defaults to `false`.--```text-POST /eve/v1/session/:sessionId- └── hook.resume- ├── GET hooks/by-token- └── POST hook_received-```--The request span uses a route template in `http.route` and the method in-`http.request.method`; it does not record concrete URLs, session IDs, tokens,-headers, bodies, or query parameters. It adopts an incoming `traceparent` when-present.--## Local traces--Without `agent/instrumentation.ts`, `eve dev` records one bounded trace per-turn under `.eve/traces/`. View traces with-[`/traces`](../guides/dev-tui#logs-and-traces) in the dev TUI or-[`eve traces`](../reference/cli#eve-traces) after `eve dev` exits.--Local traces retain model, tool, and memory-record content by default. Set-`EVE_TRACES_CONTENT=off` in `.env.local` to omit it. Writing-`agent/instrumentation.ts` replaces local tracing; its `recordInputs` and-`recordOutputs` settings control content in the OTel provider you register.--## Workflow run tags--Separately from OpenTelemetry, eve tags every Workflow run with reserved-`$eve.*` attributes. These framework-owned attributes are queryable in the-Workflow dashboard, not on OTel spans. eve emits them for every session, turn,-and subagent run, whether or not `agent/instrumentation.ts` exists.--Structural tags describe a run's place in its tree:--- `$eve.type`: `"session"`, `"turn"`, or `"subagent"`.-- `$eve.parent`: the immediate parent session ID.-- `$eve.root`: the root session ID for the tree.-- `$eve.subagent`: the compiled graph node ID for a subagent run.-- `$eve.trigger`: the channel kind that started the run.-- `$eve.schedule`: the schedule that created the session.-- `$eve.title`: a truncated title from the first user message.-- `$eve.trace_id`: a sampled trace seed. Use it as a trace link, not a- conversation-wide identity.--Each turn also accumulates `$eve.model`, `$eve.input_tokens`,-`$eve.output_tokens`, `$eve.cache_read_tokens`, and `$eve.tool_count`. These-tags power the **Agent Runs** tab in Vercel's **Observability** view. See-[Deploy to Vercel](../guides/deployment/vercel#inspect-agent-runs) for-enablement.--## Debug discovery--Run `eve info` to see the instrumentation eve discovered and any diagnostics.-eve also writes these inspectable artifacts under `.eve/`:--| Artifact | Tells you |-| ------------------------------- | ----------------------------------- |-| `agent-discovery-manifest.json` | What eve found on disk. |-| `diagnostics.json` | Authored-shape errors and warnings. |-| `compiled-agent-manifest.json` | The surface eve loads at runtime. |-| `module-map.mjs` | Compiled module entry points. |--### Common failures--| Symptom | Next action |-| ------------------------------------- | ------------------------------------------------------------------------------------------------- |-| Instrumentation is not discovered. | Run `eve info`, confirm the file is in the expected slot, and read `.eve/diagnostics.json`. |-| A tool is not discovered. | Confirm it is under `agent/tools/`, default-exports `defineTool(...)`, and appears in `eve info`. |-| `eve build` reports discovery errors. | Read the printed diagnostics and `.eve/diagnostics.json`. |--## Instrumentation Providers--[Instrumentation Providers](./instrumentation-providers) is an experimental-multi-file alternative. It cannot be used with `agent/instrumentation.ts`.-Use it when you need independent lifecycle-event providers, OpenTelemetry-destinations, directional content capture, or per-destination redaction.diff --git a/docs/install-integrations.mdx b/docs/install-integrations.mdxindex c669a147f..3c0c8edd4 100644--- a/docs/install-integrations.mdx+++ b/docs/install-integrations.mdx@@ -23,7 +23,7 @@ Web Chat installs a project-level Next.js application. It cannot be added to anIf you do not know an item name yet, run `eve add` without an argument. Its help output shows how to search the registry with `eve registry search <query>`.-Extensions may create a mount under `agent/extensions/`. Connections write their initial definition under `agent/connections/` and install `@vercel/connect` when required. Instrumentation providers write `agent/instrumentation.ts`; because an agent has one instrumentation file, compose multiple exporters there by hand. Configure generated files and required environment variables before running your agent.+Extensions may create a mount under `agent/extensions/`. Connections write their initial definition under `agent/connections/` and install `@vercel/connect` when required. Instrumentation integrations write one destination file under `agent/instrumentation/`, so you can install and configure multiple exporters independently. Configure generated files and required environment variables before running your agent.When an official item declares an interactive setup flow or flows, eve asks whether to run them after installation and runs multiple flows in declaration order. Run the printed `eve add <item> --skip-install` command to resume a skipped or cancelled setup later; it reruns the item's declared flows from the beginning.diff --git a/docs/reference/agent-files.md b/docs/reference/agent-files.mdindex e9b03670c..4e89f969e 100644--- a/docs/reference/agent-files.md+++ b/docs/reference/agent-files.md@@ -13,7 +13,7 @@ In a single-agent project, the agent directory is `agent/`. In an eve agent workagent/├── agent.ts├── instructions.md-├── instrumentation.ts+├── instrumentation/├── channels/├── connections/├── extensions/@@ -50,7 +50,7 @@ Paths below are relative to the agent directory. Root agents can use every path;| ------------------------------------------------------- | ----------------------------------------- | ---------------------- | --------------------------------------------------------------------------------------------------------------------------------------- || `agent.ts` | Runtime config | Yes | Model, model options, compaction, build, and experimental settings. See [Agents](/docs/agent-config). || `instructions.md` / `instructions.ts` / `instructions/` | Base system prompt | Yes | A flat file or directory of `.md` and `.ts` files. Required on the root, optional on subagents. See [Instructions](/docs/instructions). |-| `instrumentation.ts` | Telemetry config | No | Auto-discovered and run before agent code. See [Instrumentation](/docs/observability/instrumentation). |+| `instrumentation/` | Telemetry providers and destinations | No | One path-named provider per file. See [Instrumentation](/docs/observability/instrumentation). || `channels/` | HTTP and messaging entry points | No | See [Channels](/docs/channels/overview). || `connections/` | External MCP and OpenAPI services | Yes | Static files define path-named connections; dynamic sources can resolve caller-specific connections. || `extensions/` | Mounted reusable capabilities | Yes | File or directory mounts. See [Extensions](/docs/extensions). |diff --git a/docs/reference/cli.md b/docs/reference/cli.mdindex bdbd91b22..7ea6abed7 100644--- a/docs/reference/cli.md+++ b/docs/reference/cli.md@@ -272,7 +272,7 @@ Local dev records the last ready URL per resolved app root in `.eve/dev-server-sLocal dev keeps immutable runtime generations under `.eve/dev-runtime/snapshots/` so in-flight turns hold a consistent code revision while new turns pick up rebuilds. Each generation contains the compiled authored module graph and runtime resources rather than a recursive copy of the app or workspace. The terminal REPL keeps its logical session across successful rebuilds, so the next turn continues the conversation on the latest generation; `/new` terminally retires that session before clearing the transcript, and the next prompt starts a fresh session with a new session-scoped sandbox on first sandbox use. After a generation is superseded, `eve dev` retains it for at least 30 minutes and also retains the five most recently superseded generations, regardless of the configured Workflow World. The active generation is never pruned. Old runtime snapshots and local sandbox templates are pruned in the background. For manual cleanup, stop `eve dev` before deleting `.eve/dev-runtime/snapshots/` or `.eve/sandbox-cache/local/templates/`. A turn that remains unfinished beyond the automatic retention window can no longer resume after its generation is pruned.-When no authored `agent/instrumentation.ts` exists, local dev also records traces under `.eve/traces/`, and bounds that store by age, size, and a keep-newest floor. Configure it with `EVE_TRACES*` in `.env.local`; see [`eve traces`](#retention) for the rules and defaults.+Local development records traces under `.eve/traces/` by default and bounds that store by age, size, and a keep-newest floor. Configure it with `EVE_TRACES*` in `.env.local`, or disable the destination with `agent/instrumentation/local.ts`; see [`eve traces`](#retention) for the rules and defaults.## `eve logs`diff --git a/docs/reference/typescript-api.md b/docs/reference/typescript-api.mdindex 5b4c7f4a9..efb30cbe4 100644--- a/docs/reference/typescript-api.md+++ b/docs/reference/typescript-api.md@@ -49,7 +49,8 @@ export default defineTool({| `defineSchedule` | `eve/schedules` | `agent/schedules/<name>.ts` | [Schedules](../schedules) || `defineState` | `eve/context` | tools, hooks, lifecycle | [Session context](../guides/session-context) || `defineSandbox` | `eve/sandbox` | `agent/sandbox.ts` | [Sandbox](../sandbox) |-| `defineInstrumentation` | `eve/instrumentation` | `agent/instrumentation.ts` | [Instrumentation](../observability/instrumentation) |+| `defineInstrumentation` | `eve/instrumentation` | `agent/instrumentation/<name>.ts` | [Instrumentation](../observability/instrumentation) |+| `otel`, `otelIntegration` | `eve/instrumentation/otel` | `agent/instrumentation/<destination>.ts` | [OpenTelemetry](../observability/otel) || `defineRemoteAgent` | `eve` | `agent/subagents/<id>/agent.ts` | [Remote agents](../guides/remote-agents) || `defineEval` | `eve/evals` | `evals/*.eval.ts` | [Evals](../evals/overview) || `defineEvalConfig` | `eve/evals` | `evals/evals.config.ts` | [Evals](../evals/overview) |@@ -136,7 +137,8 @@ Tool definitions accept `availableInSubagents: false` to restrict the tool to to| `eve/memory/file/vercel` | `vercelBlob` and Vercel Blob backend options || `eve/context` | `defineState`, session and state types || `eve/sandbox` | `defineSandbox`, backends |-| `eve/instrumentation` | `defineInstrumentation`, `isChannel` |+| `eve/instrumentation` | `defineInstrumentation`, `disableInstrumentation`, `isChannel`, lifecycle provider types |+| `eve/instrumentation/otel` | `otel`, `otelIntegration`, `localTraces`, `agentRuns`, OpenTelemetry policy types || `eve/local-dev` | `getLocalDevCapability`, `LocalDevCapability` || [`eve/models`](../guides/evaluate) | Automatic model selection with `auto` || `eve/models/openai` | `openai`, `chatgpt`, deprecated `experimental_chatgpt` |diff --git a/e2e/fixtures/agent-authored-bundling/agent/instrumentation.ts b/e2e/fixtures/agent-authored-bundling/agent/instrumentation/bundling.tssimilarity index 71%rename from e2e/fixtures/agent-authored-bundling/agent/instrumentation.tsrename to e2e/fixtures/agent-authored-bundling/agent/instrumentation/bundling.tsindex 9a42dc0a6..ca57831ca 100644--- a/e2e/fixtures/agent-authored-bundling/agent/instrumentation.ts+++ b/e2e/fixtures/agent-authored-bundling/agent/instrumentation/bundling.ts@@ -1,6 +1,6 @@import { defineInstrumentation } from "eve/instrumentation";-import marker from "../authored-assets/instrumentation.txt?raw";+import marker from "../../authored-assets/instrumentation.txt?raw";const INSTRUMENTATION_MARKER = "authored-instrumentation-asset";@@ -9,5 +9,7 @@ if (marker.trim() !== INSTRUMENTATION_MARKER) {}export default defineInstrumentation({- functionId: INSTRUMENTATION_MARKER,+ setup: () => {+ void INSTRUMENTATION_MARKER;+ },});diff --git a/e2e/fixtures/agent-basic-runtime/agent/agent.ts b/e2e/fixtures/agent-basic-runtime/agent/agent.tsindex 788b3241a..d097e7868 100644--- a/e2e/fixtures/agent-basic-runtime/agent/agent.ts+++ b/e2e/fixtures/agent-basic-runtime/agent/agent.ts@@ -75,6 +75,6 @@ export default defineAgent({},},}),- experimental: { ...config.experimental, instrumentationProviders: true },+ experimental: config.experimental,reasoning: "high",});diff --git a/e2e/fixtures/agent-workflow-stress/agent/instrumentation.ts b/e2e/fixtures/agent-workflow-stress/agent/instrumentation/e2e.tssimilarity index 100%rename from e2e/fixtures/agent-workflow-stress/agent/instrumentation.tsrename to e2e/fixtures/agent-workflow-stress/agent/instrumentation/e2e.tsdiff --git a/e2e/fixtures/agent-workflow-stress/agent/instrumentation/otel.ts b/e2e/fixtures/agent-workflow-stress/agent/instrumentation/otel.tsnew file mode 100644index 000000000..e22fd5eab--- /dev/null+++ b/e2e/fixtures/agent-workflow-stress/agent/instrumentation/otel.ts@@ -0,0 +1 @@+export { default } from "@eve-e2e/config/instrumentation-otel";diff --git a/e2e/fixtures/e2e-config/package.json b/e2e/fixtures/e2e-config/package.jsonindex 6508942cd..c1398a659 100644--- a/e2e/fixtures/e2e-config/package.json+++ b/e2e/fixtures/e2e-config/package.json@@ -5,7 +5,8 @@"type": "module","exports": {".": "./src/index.ts",- "./instrumentation": "./src/instrumentation.ts"+ "./instrumentation": "./src/instrumentation.ts",+ "./instrumentation-otel": "./src/instrumentation-otel.ts"},"scripts": {"typecheck": "tsc --noEmit"diff --git a/e2e/fixtures/e2e-config/src/instrumentation-otel.ts b/e2e/fixtures/e2e-config/src/instrumentation-otel.tsnew file mode 100644index 000000000..9e5898e85--- /dev/null+++ b/e2e/fixtures/e2e-config/src/instrumentation-otel.ts@@ -0,0 +1,10 @@+import { otel } from "eve/instrumentation/otel";++export default otel({+ traceChannelRequests: true,+ tracePolicy: () => ({+ emit: true,+ recordInputs: false,+ recordOutputs: false,+ }),+});diff --git a/e2e/fixtures/e2e-config/src/instrumentation.ts b/e2e/fixtures/e2e-config/src/instrumentation.tsindex 8c5006f3c..c927d9e7f 100644--- a/e2e/fixtures/e2e-config/src/instrumentation.ts+++ b/e2e/fixtures/e2e-config/src/instrumentation.ts@@ -1,34 +1,23 @@-import { OTLPHttpJsonTraceExporter, registerOTel } from "@vercel/otel";-import { defineInstrumentation } from "eve/instrumentation";+import { OTLPHttpJsonTraceExporter } from "@vercel/otel";+import { otelIntegration } from "eve/instrumentation/otel";/*** Shared instrumentation for e2e fixtures that export traces to Datadog.* Environments without `DD_API_KEY` keep telemetry enabled but do not* register an exporter.*/-export default defineInstrumentation({- recordInputs: false,- recordOutputs: false,- traceChannelRequests: true,- events: {- "step.started": () => ({- runtimeContext: {- "vercel.env": process.env.VERCEL_ENV ?? "",- },- }),- },- setup({ agentName }) {- const datadogApiKey = process.env.DD_API_KEY?.trim();- if (!datadogApiKey) {- return;- }+const datadogApiKey = process.env.DD_API_KEY?.trim();- registerOTel({- serviceName: agentName,- traceExporter: new OTLPHttpJsonTraceExporter({- url: "https://vercel.integrations.otlp.datadoghq.com/v1/traces",- headers: { "DD-API-KEY": datadogApiKey },- }),- });- },+export default otelIntegration({+ ...(datadogApiKey+ ? {+ traceExporter: new OTLPHttpJsonTraceExporter({+ url: "https://vercel.integrations.otlp.datadoghq.com/v1/traces",+ headers: { "DD-API-KEY": datadogApiKey },+ }),+ }+ : {}),+ runtimeContext: () => ({+ "vercel.env": process.env.VERCEL_ENV ?? "",+ }),});diff --git a/packages/eve/extension-contracts/reports/subagent/v19.json b/packages/eve/extension-contracts/reports/subagent/v19.jsonnew file mode 100644index 000000000..2fdc7a0c1--- /dev/null+++ b/packages/eve/extension-contracts/reports/subagent/v19.json@@ -0,0 +1,23 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "subagent",+ "epoch": 19,+ "sha256": "d907fd891fc4bee918d7544283f7b1bacdbc66e13fa8e39178050b9a4dedcbf7",+ "exports": [+ "AgentCompactionDefinition",+ "AgentDefinition",+ "AgentModelDefinition",+ "AgentStaticModelDefinition",+ "DefinedAgent",+ "DynamicLocalSubagentDefinition",+ "DynamicSubagentDefinition",+ "RemoteAgentDefinition",+ "RemoteAgentDefinitionInput",+ "WorkspaceAgentDefinition",+ "WorkspaceAgentTransport",+ "defineAgent",+ "defineDynamic",+ "defineRemoteAgent",+ "defineWorkspaceAgent"+ ]+}diff --git a/packages/eve/src/client/client.test.ts b/packages/eve/src/client/client.test.tsindex 3c1209893..8c4ad455d 100644--- a/packages/eve/src/client/client.test.ts+++ b/packages/eve/src/client/client.test.ts@@ -244,6 +244,27 @@ describe("Client request policy", () => {expect(info.tools.static[0]).not.toHaveProperty("outputSchema");});+ it("accepts the legacy optional instrumentation field in v4 agent info", async () => {+ const owner = { kind: "application" as const };+ vi.spyOn(globalThis, "fetch").mockResolvedValue(+ Response.json({+ ...AGENT_INFO,+ instrumentation: {+ binding: testBinding("instrumentation.ts", owner),+ logicalPath: "instrumentation.ts",+ owner,+ sourceId: "instrumentation.ts",+ sourceKind: "module",+ },+ }),+ );+ const client = new Client({ host: "https://eve.test" });++ const info = await client.info();++ expect(info.instrumentation?.logicalPath).toBe("instrumentation.ts");+ });+it("rejects unknown fields in the agent info payload", async () => {vi.spyOn(globalThis, "fetch").mockResolvedValue(Response.json({ ...AGENT_INFO, ignoredByClient: true }),diff --git a/packages/eve/src/compiler/compile-from-memory.test.ts b/packages/eve/src/compiler/compile-from-memory.test.tsindex 47420464f..2bb18981c 100644--- a/packages/eve/src/compiler/compile-from-memory.test.ts+++ b/packages/eve/src/compiler/compile-from-memory.test.ts@@ -8,7 +8,6 @@ import {ROOT_COMPILED_AGENT_NODE_ID,} from "#compiler/manifest.js";import { validateCompiledModuleMap } from "#compiler/validate-artifact.js";-import { defineInstrumentation } from "#public/instrumentation/index.js";describe("compileFromMemory", () => {it("uses the ordinary source compiler for defaults and authored config", async () => {@@ -106,31 +105,4 @@ describe("compileFromMemory", () => {compiledAgentManifestSchema.safeParse(JSON.parse(JSON.stringify(manifest))).success,).toBe(true);});-- it("binds instrumentation as an ordinary programmatic module slot", async () => {- const instrumentation = defineInstrumentation({ recordInputs: true });- const { manifest, moduleMap } = await compileFromMemory({- model: "openai/gpt-5.4",- modules: [- {- loadNamespace: async () => ({ default: instrumentation }),- logicalPath: "instrumentation.ts",- },- ],- });-- expect(manifest.instrumentation).toMatchObject({- logicalPath: "instrumentation.ts",- sourceKind: "module",- });- const sourceId = manifest.instrumentation!.sourceId;- 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/extension-compatibility.ts b/packages/eve/src/compiler/extension-compatibility.tsindex 8aca75dbb..f4207675e 100644--- a/packages/eve/src/compiler/extension-compatibility.ts+++ b/packages/eve/src/compiler/extension-compatibility.ts@@ -102,12 +102,14 @@ const EXTENSION_CAPABILITY_CONTRACTS = {},},subagent: {- current: 18,- supported: [3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18],+ current: 19,+ supported: [3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 19],dropped: {1: "Persistent subagent sessions are now the default and the experimental opt-in was removed",2: "Persistent subagent sessions are now the default and the experimental opt-in was removed",5: "Message and reasoning append events now expose deltas instead of cumulative snapshots.",+ 17: "Removed experimental.instrumentationProviders; instrumentation is now always enabled for root agents.",+ 18: "Removed experimental.instrumentationProviders; instrumentation is now always enabled for root agents.",},},connection: {diff --git a/packages/eve/src/compiler/instrumentation-layout-config.ts b/packages/eve/src/compiler/instrumentation-layout-config.tsdeleted file mode 100644index 2927ea169..000000000--- a/packages/eve/src/compiler/instrumentation-layout-config.ts+++ /dev/null@@ -1,16 +0,0 @@-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/manifest.ts b/packages/eve/src/compiler/manifest.tsindex 28ced0ae6..306509330 100644--- a/packages/eve/src/compiler/manifest.ts+++ b/packages/eve/src/compiler/manifest.ts@@ -599,7 +599,6 @@ const compiledAgentConfigBaseFields = {description: z.string().optional(),experimental: z.object({- instrumentationProviders: z.boolean().optional(),workflow: compiledAgentWorkflowDefinitionSchema.optional(),}).strict()@@ -976,7 +975,6 @@ const compiledAgentResourceFields = {remoteAgents: z.array(compiledRemoteAgentNodeSchema),skills: z.array(compiledSkillSourceSchema).readonly(),instructions: z.array(compiledInstructionsSchema).readonly().default([]),- instrumentation: moduleSourceRefSchema.optional(),tools: z.array(compiledToolDefinitionSchema),workspaceResourceRoot: compiledWorkspaceResourceRootSchema,};@@ -1085,7 +1083,6 @@ export const compiledAgentManifestSchema = zskills: z.array(compiledSkillSourceSchema).readonly(),subagents: z.array(compiledSubagentNodeSchema),instructions: z.array(compiledInstructionsSchema).readonly().default([]),- instrumentation: moduleSourceRefSchema.optional(),tools: z.array(compiledToolDefinitionSchema),version: z.literal(COMPILED_AGENT_MANIFEST_VERSION),workspaceResourceRoot: compiledWorkspaceResourceRootSchema,@@ -1113,7 +1110,6 @@ export interface CreateCompiledAgentResourcesInput {readonly schedules?: readonly CompiledScheduleDefinition[];readonly skills?: readonly CompiledSkillDefinition[];readonly instructions?: readonly CompiledInstructionsDefinition[];- readonly instrumentation?: ModuleSourceRef;readonly tools?: readonly CompiledToolDefinition[];readonly workspaceResourceRoot?: CompiledWorkspaceResourceRoot;}@@ -1147,7 +1143,6 @@ export function createCompiledAgentResources(hooks: [...(input.hooks ?? [])],memories: [...(input.memories ?? [])],instructions: [...(input.instructions ?? [])],- instrumentation: input.instrumentation === undefined ? undefined : { ...input.instrumentation },remoteAgents: [...(input.remoteAgents ?? [])],sandbox: input.sandbox,sandboxWorkspaces: [...(input.sandboxWorkspaces ?? [])],@@ -1202,7 +1197,6 @@ function cloneCompiledAgentDefinition(config: CompiledAgentDefinition): Compiledconfig.experimental === undefined? undefined: {- instrumentationProviders: config.experimental.instrumentationProviders,workflow:config.experimental.workflow === undefined? undefined@@ -1300,7 +1294,6 @@ export function createCompiledAgentManifest(input: {readonly skills?: readonly CompiledSkillDefinition[];readonly subagents?: readonly CompiledSubagentNode[];readonly instructions?: readonly CompiledInstructionsDefinition[];- readonly instrumentation?: ModuleSourceRef;readonly tools?: readonly CompiledToolDefinition[];readonly extensionMounts?: readonly CompiledExtensionMount[];readonly workspaceResourceRoot?: CompiledWorkspaceResourceRoot;diff --git a/packages/eve/src/compiler/normalize-agent-config.ts b/packages/eve/src/compiler/normalize-agent-config.tsindex daa87b153..552ad0395 100644--- a/packages/eve/src/compiler/normalize-agent-config.ts+++ b/packages/eve/src/compiler/normalize-agent-config.ts@@ -187,10 +187,6 @@ function normalizeExperimentalDefinition(const compiledExperimental: Mutable<NonNullable<CompiledAgentDefinition["experimental"]>> = {};- if (experimental.instrumentationProviders !== undefined) {- compiledExperimental.instrumentationProviders = experimental.instrumentationProviders;- }-if (experimental.workflow !== undefined) {compiledExperimental.workflow = {modelCallsPerStep: experimental.workflow.modelCallsPerStep,diff --git a/packages/eve/src/compiler/normalize-manifest.test.ts b/packages/eve/src/compiler/normalize-manifest.test.tsindex 7a2cbec45..2fc899a30 100644--- a/packages/eve/src/compiler/normalize-manifest.test.ts+++ b/packages/eve/src/compiler/normalize-manifest.test.ts@@ -597,7 +597,6 @@ describe("compileAgentManifest source graph", () => {it("projects the root node once and finalizes its filesystem bindings after config", async () => {let toolSourceIterations = 0;const discovered = manifest();- discovered.instrumentation = createModuleSourceRef({ logicalPath: "instrumentation.ts" });discovered.tools = new Proxy(discovered.tools, {get(target, property, receiver) {if (property === Symbol.iterator) toolSourceIterations += 1;@@ -621,14 +620,7 @@ describe("compileAgentManifest source graph", () => {});expect(toolSourceIterations).toBe(1);- expect(compiled.bindings["instrumentation.ts"]?.backing).toMatchObject({- externalDependencies: ["sharp"],- kind: "filesystem",- });- expect(compiled.bindings["instrumentation.ts"]?.usage).toEqual({- compile: false,- runtimeEntry: true,- });+ expect(compiled.config.build?.externalDependencies).toEqual(["sharp"]);});it("classifies dynamic and source-backed model configs as runtime entries", async () => {diff --git a/packages/eve/src/compiler/normalize-manifest.ts b/packages/eve/src/compiler/normalize-manifest.tsindex 6df79db52..62a78a0fb 100644--- a/packages/eve/src/compiler/normalize-manifest.ts+++ b/packages/eve/src/compiler/normalize-manifest.ts@@ -1,5 +1,4 @@import type { AgentSourceManifest } from "#discover/manifest.js";-import type { ModuleSourceRef } from "#shared/source-ref.js";import {type CompiledAgentDefinition,type CompiledAgentManifest,@@ -31,7 +30,6 @@ 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";@@ -196,7 +194,6 @@ 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);const manifest = createCompiledAgentNodeManifest({@@ -309,7 +306,6 @@ class AgentGraphCompiler {} 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);const base = {@@ -500,7 +496,6 @@ class AgentGraphCompiler {const schedules: CompiledScheduleDefinition[] = [];const channels: CompiledChannelDefinition[] = [];let sandbox: CompiledSandboxDefinition | undefined;- let instrumentation: ModuleSourceRef | undefined;const selectedSourceIds = collectSelectedSourceIds(state.composed);const loadNamespace = state.evaluation.loadNamespace;@@ -564,10 +559,6 @@ class AgentGraphCompiler {}break;}- case "instrumentation":- instrumentation = entry.source;- state.evaluation.requireRuntimeEntry(candidate.sourceId);- break;case "memory":memories.push(await compileMemoryDefinition(entry.source, {@@ -682,7 +673,6 @@ class AgentGraphCompiler {hooks,memories,instructions,- instrumentation,sandbox,sandboxWorkspaces: input.manifest.sandboxWorkspaces.map((workspace) => ({logicalPath: workspace.logicalPath,diff --git a/packages/eve/src/compiler/project-sources.test.ts b/packages/eve/src/compiler/project-sources.test.tsindex e40c937ea..25836ffb0 100644--- a/packages/eve/src/compiler/project-sources.test.ts+++ b/packages/eve/src/compiler/project-sources.test.ts@@ -21,7 +21,7 @@ describe("qualifyExtensionContributionLogicalPath", () => {expect(qualifyExtensionContributionLogicalPath(logicalPath, "crm")).toBe(expected);});- it.each(["agent.ts", "instrumentation.ts", "memory.ts", "sandbox.ts", "lib/http.ts"])(+ it.each(["agent.ts", "instrumentation/otel.ts", "memory.ts", "sandbox.ts", "lib/http.ts"])("rejects unscopable slot %s",(logicalPath) => {expect(() => qualifyExtensionContributionLogicalPath(logicalPath, "crm")).toThrow(diff --git a/packages/eve/src/compiler/project-sources.ts b/packages/eve/src/compiler/project-sources.tsindex a9f4fd0ce..cf6533995 100644--- a/packages/eve/src/compiler/project-sources.ts+++ b/packages/eve/src/compiler/project-sources.ts@@ -34,7 +34,6 @@ export type ProjectedModuleSource =| "extension"| "hook"| "instructions"- | "instrumentation"| "memory"| "sandbox"| "schedule"@@ -70,7 +69,6 @@ const MODULE_KIND_BY_SLOT_ROOT: Partial<extensions: "extension",hooks: "hook",instructions: "instructions",- instrumentation: "instrumentation",memory: "memory",sandbox: "sandbox",schedules: "schedule",@@ -320,9 +318,6 @@ function projectManifest(input: {canonicalSourceSlot(logicalPath) === "agent" ? undefined : "agent.ts",);}- if (input.manifest.instrumentation !== undefined) {- pushModule(input.manifest.instrumentation);- }for (const source of input.manifest.extensions) pushModule(source);for (const source of input.manifest.channels) pushModule(source);for (const source of input.manifest.connections) pushModule(source);diff --git a/packages/eve/src/compiler/source-graph.ts b/packages/eve/src/compiler/source-graph.tsindex 793eecf3f..3ff2fcb20 100644--- a/packages/eve/src/compiler/source-graph.ts+++ b/packages/eve/src/compiler/source-graph.ts@@ -621,8 +621,7 @@ export function validateProgrammaticLogicalPath(input: string): string {const root = segments[0];const extensionless = stripLogicalPathExtension(logicalPath);const supported =- (segments.length === 1 &&- ["agent", "memory", "sandbox", "instrumentation"].includes(extensionless)) ||+ (segments.length === 1 && ["agent", "memory", "sandbox"].includes(extensionless)) ||(root === "sandbox" &&segments.length === 2 &&getSupportedModuleBaseName(fileName) === "sandbox") ||diff --git a/packages/eve/src/compiler/validate-artifact.ts b/packages/eve/src/compiler/validate-artifact.tsindex 8a116ecb5..0e408f08a 100644--- a/packages/eve/src/compiler/validate-artifact.ts+++ b/packages/eve/src/compiler/validate-artifact.ts@@ -348,7 +348,6 @@ function collectReferencedModuleSources(for (const value of node.hooks) add(value);for (const value of node.memories) add(value);for (const value of node.instructions) if (value.sourceKind === "module") add(value);- if (node.instrumentation !== undefined) add(node.instrumentation);for (const value of node.skills) if (value.sourceKind === "module") add(value);for (const value of node.schedules) if (value.sourceKind === "module") add(value);add(node.sandbox);diff --git a/packages/eve/src/discover/agent.integration.test.ts b/packages/eve/src/discover/agent.integration.test.tsindex 0c692a78c..a794dd6dc 100644--- a/packages/eve/src/discover/agent.integration.test.ts+++ b/packages/eve/src/discover/agent.integration.test.ts@@ -607,29 +607,6 @@ describe("discoverAgent (memory)", () => {expect(result.diagnostics).toEqual([]);});- it("discovers single-file instrumentation as a module source", async () => {- const project = buildMemoryAgentProject({- agentFiles: {- "instrumentation.mjs":- 'throw new Error("instrumentation modules should not execute during discovery");\n',- "instructions.md": "You are a precise assistant.",- },- });-- const result = await discoverAgent({- agentRoot: project.agentRoot,- appRoot: project.appRoot,- source: project.source,- });-- expect(result.diagnostics).toEqual([]);- expect(result.manifest.instrumentation).toEqual({- logicalPath: "instrumentation.mjs",- sourceId: "instrumentation.mjs",- sourceKind: "module",- });- });-it("rejects authored tool filenames that violate the tool-name charset", async () => {const project = buildMemoryAgentProject({agentFiles: {@@ -973,7 +950,7 @@ describe("discoverAgent (memory)", () => {eve: { extension: { source: "source", dist: "extension" } },}),"node_modules/@acme/crm/extension/_manifest.json": EXTENSION_COMPATIBILITY_MANIFEST,- "node_modules/@acme/crm/extension/instrumentation.ts": "export default {};",+ "node_modules/@acme/crm/extension/instrumentation/audit.ts": "export default {};",},agentFiles: {"extensions/crm.ts": 'export { default } from "@acme/crm";\n',@@ -990,7 +967,6 @@ describe("discoverAgent (memory)", () => {expect(result.diagnostics.map((diagnostic) => diagnostic.code)).toContain(DISCOVER_EXTENSION_INSTRUMENTATION_UNSUPPORTED,);- expect(result.manifest.resolvedExtensions[0]?.manifest.instrumentation).toBeUndefined();});it("rejects memory declared by a mounted extension", async () => {diff --git a/packages/eve/src/discover/discover-agent.ts b/packages/eve/src/discover/discover-agent.tsindex 39c816fde..b08ae3e63 100644--- a/packages/eve/src/discover/discover-agent.ts+++ b/packages/eve/src/discover/discover-agent.ts@@ -184,13 +184,22 @@ export async function discoverAgent(input: DiscoverAgentInput): Promise<Discover}),);}- if (instrumentationModuleResult.module !== undefined) {+ const instrumentationDirectory = rootEntries.find(+ (entry) => entry.name === "instrumentation" && entry.isDirectory(),+ );+ if (+ instrumentationModuleResult.module !== undefined ||+ instrumentationDirectory !== undefined+ ) {diagnostics.push(createDiscoverErrorDiagnostic({code: DISCOVER_EXTENSION_INSTRUMENTATION_UNSUPPORTED,message:- "An extension may not declare instrumentation — it is a singleton owned by the consuming agent.",- sourcePath: join(agentRoot, instrumentationModuleResult.module.logicalPath),+ "An extension may not declare instrumentation providers — process-wide observability belongs to the consuming agent.",+ sourcePath:+ instrumentationModuleResult.module === undefined+ ? join(agentRoot, instrumentationDirectory!.name)+ : join(agentRoot, instrumentationModuleResult.module.logicalPath),}),);}@@ -326,10 +335,6 @@ export async function discoverAgent(input: DiscoverAgentInput): Promise<Discoverif (role !== "extension" && configModuleResult.module !== undefined) {manifestInput.configModule = configModuleResult.module;}- if (role !== "extension" && instrumentationModuleResult.module !== undefined) {- manifestInput.instrumentation = instrumentationModuleResult.module;- }-const manifest = createAgentSourceManifest(manifestInput);return {diff --git a/packages/eve/src/discover/manifest.ts b/packages/eve/src/discover/manifest.tsindex ebc99c66d..0cacc1d27 100644--- a/packages/eve/src/discover/manifest.ts+++ b/packages/eve/src/discover/manifest.ts@@ -220,8 +220,6 @@ export interface AgentSourceManifest {* Empty when no instructions are authored.*/instructions: InstructionsSourceRef[];- /** Authored single-file instrumentation module, when present. */- instrumentation?: ModuleSourceRef;/*** Authored sandbox module discovered for this agent, or `null` when* the agent does not declare one. Every agent owns at most one@@ -265,7 +263,6 @@ export interface CreateAgentSourceManifestInput {*/packageName?: string;instructions?: readonly InstructionsSourceRef[];- instrumentation?: ModuleSourceRef;sandbox?: SandboxSourceRef | null;sandboxWorkspaces?: readonly SandboxWorkspaceFolderSourceRef[];schedules?: readonly ScheduleSourceRef[];@@ -348,10 +345,6 @@ export function createAgentSourceManifest(if (input.configModule !== undefined) {manifest.configModule = input.configModule;}- if (input.instrumentation !== undefined) {- manifest.instrumentation = input.instrumentation;- }-return manifest;}diff --git a/packages/eve/src/harness/tool-loop.test.ts b/packages/eve/src/harness/tool-loop.test.tsindex b9386a785..67af3c4bf 100644--- a/packages/eve/src/harness/tool-loop.test.ts+++ b/packages/eve/src/harness/tool-loop.test.ts@@ -42,10 +42,7 @@ import { decodeSandboxRef, isSandboxRefUrl } from "#internal/attachments/sandboximport { attachClientContext } from "#internal/client-context.js";import { mockSandbox } from "#internal/testing/mocks/mock-sandbox.js";import type { UnstampedMessageStreamEvent } from "#protocol/message.js";-import type {- InstrumentationEvents,- InstrumentationStepStartedEventInput,-} from "#public/instrumentation/index.js";+import type { InstrumentationStepStartedEventInput } from "#public/instrumentation/index.js";import { defineInstructions } from "#public/definitions/instructions.js";import type { ResolvedDynamicInstructionsResolver } from "#runtime/types.js";import { createPreparedRuntimeSubagentTool } from "#runtime/subagents/registry.js";@@ -107,6 +104,7 @@ import {type InstrumentationRuntime,type SessionInstrumentation,} from "#instrumentation/runtime.js";+import type { RuntimeContextResolver } from "#tracing/otel-declaration.js";import {CONDITIONAL_DELIVERY_INSTRUCTION,EMPTY_DELIVERY_SENTINEL,@@ -196,7 +194,9 @@ function setConversationContext(function declareTelemetry(config:- | (Readonly<Record<string, unknown>> & { readonly events?: InstrumentationEvents })+ | (Readonly<Record<string, unknown>> & {+ readonly runtimeContext?: RuntimeContextResolver;+ })| undefined,decision?: InstrumentationDecision,audience: ChannelAudience = "unknown",@@ -217,9 +217,10 @@ function declareTelemetry(recordOutputs: config.recordOutputs === true,traceChannelRequests: config["traceChannelRequests"] === true,},+ runtimeContextResolvers:+ config.runtimeContext === undefined ? undefined : [config.runtimeContext],runInContext: (_operation, execute) => execute(),shutdown: async () => undefined,- stepStartedRuntimeContextResolver: config.events?.["step.started"] ?? (() => undefined),};declaredInstrumentation = bindInstrumentationRuntime(declaredRuntime,@@ -247,9 +248,6 @@ function bindHookInstrumentation(: undefined,runInContext,shutdown: async () => undefined,- stepStartedRuntimeContextResolver: useDeclaredRuntime- ? declaredRuntime?.stepStartedRuntimeContextResolver- : undefined,},createInstrumentationContext(useDeclaredRuntime ? declaredDecision : undefined,@@ -5460,15 +5458,11 @@ describe("createToolLoopHarness", () => {it("retries with the offending tool dropped and a one-shot system note", async () => {const resolveRuntimeContext = vi.fn((input: InstrumentationStepStartedEventInput) => ({- runtimeContext: {- "test.attempt": typeof input.modelInput.instructions === "string" ? "original" : "retry",- },+ "test.attempt": typeof input.modelInput.instructions === "string" ? "original" : "retry",}));declareTelemetry({- events: {- "step.started": resolveRuntimeContext,- },+ runtimeContext: resolveRuntimeContext,},undefined,"public",@@ -11923,7 +11917,7 @@ describe("createToolLoopHarness", () => {}});- it("injects eve.version alongside session context into runtimeContext when telemetry is enabled", async () => {+ it("injects eve.version alongside session context when runtimeContext is configured", async () => {setupMockAgent({finishReason: "stop",response: { messages: [{ content: "Hello!", role: "assistant" }] },@@ -11932,7 +11926,7 @@ describe("createToolLoopHarness", () => {toolResults: [],});- declareTelemetry({ tracePolicy: () => true });+ declareTelemetry({ runtimeContext: () => undefined, tracePolicy: () => true });const config = createTestConfig("conversation");const runStep = createToolLoopHarness(config);await runStep(createTestSession(), { message: "hi" });@@ -12160,7 +12154,7 @@ describe("createToolLoopHarness", () => {});});- it("merges step-started runtime context before emitting step.started", async () => {+ it("merges runtime context before emitting step.started", async () => {setupMockAgent({finishReason: "stop",response: { messages: [{ content: "Hello!", role: "assistant" }] },@@ -12176,26 +12170,22 @@ describe("createToolLoopHarness", () => {events.push(event);};const resolveRuntimeContext = vi.fn((input: InstrumentationStepStartedEventInput) => {- order.push('events["step.started"]');+ order.push("runtimeContext");if (input.channel.kind !== "channel:support") {throw new Error("expected support channel metadata");}return {- runtimeContext: {- "eve.session.id": "user-override",- "slack.user_id":- typeof input.channel.metadata["triggeringUserId"] === "string"- ? input.channel.metadata["triggeringUserId"]- : "",- "turn.id": input.turn.id,- },+ "eve.session.id": "user-override",+ "slack.user_id":+ typeof input.channel.metadata["triggeringUserId"] === "string"+ ? input.channel.metadata["triggeringUserId"]+ : "",+ "turn.id": input.turn.id,};});declareTelemetry({- events: {- "step.started": resolveRuntimeContext,- },+ runtimeContext: resolveRuntimeContext,},undefined,"public",@@ -12253,12 +12243,12 @@ describe("createToolLoopHarness", () => {expect(agentCall?.telemetry?.includeRuntimeContext).toEqual(Object.fromEntries(Object.keys(agentCall?.runtimeContext ?? {}).map((key) => [key, true])),);- expect(order.indexOf("turn.started")).toBeLessThan(order.indexOf('events["step.started"]'));- expect(order.indexOf("step.started")).toBeLessThan(order.indexOf('events["step.started"]'));+ expect(order.indexOf("turn.started")).toBeLessThan(order.indexOf("runtimeContext"));+ expect(order.indexOf("step.started")).toBeLessThan(order.indexOf("runtimeContext"));expect(getCompatibilityEventTypes(events)).toContain("step.started");});- it("continues the normal turn flow when step-started runtime context throws", async () => {+ it("continues the normal turn flow when runtime context throws", async () => {setupMockAgent({finishReason: "stop",response: { messages: [{ content: "Hello!", role: "assistant" }] },@@ -12268,10 +12258,8 @@ describe("createToolLoopHarness", () => {});declareTelemetry({- events: {- "step.started": () => {- throw new Error("runtime context resolver failed");- },+ runtimeContext: () => {+ throw new Error("runtime context resolver failed");},});@@ -12299,16 +12287,12 @@ describe("createToolLoopHarness", () => {});});- it("resolves step-started runtime context for each step and turn coordinate", async () => {+ it("resolves runtime context for each step and turn coordinate", async () => {const resolveRuntimeContext = vi.fn((input: InstrumentationStepStartedEventInput) => ({- runtimeContext: {- "test.step": `${input.turn.id}:${input.step.index}`,- },+ "test.step": `${input.turn.id}:${input.step.index}`,}));declareTelemetry({- events: {- "step.started": resolveRuntimeContext,- },+ runtimeContext: resolveRuntimeContext,});const { emit } = createEventCollector();diff --git a/packages/eve/src/harness/tool-loop.ts b/packages/eve/src/harness/tool-loop.tsindex d4e7deb61..0da3ba8d8 100644--- a/packages/eve/src/harness/tool-loop.ts+++ b/packages/eve/src/harness/tool-loop.ts@@ -252,8 +252,8 @@ import {/*** Builds the `telemetry` value for the AI SDK from authored settings.*- * Custom context (authored `InstrumentationDefinition.events` plus- * eve-specific identifiers such as `eve.session.id`) is flowed through+ * Destination runtime context and eve-specific identifiers such as+ * `eve.session.id` are flowed through.* Bound instrumentation supplies custom context because AI SDK v7 surfaces* per-call attributes via `runtimeContext`, not a dedicated metadata field on* `TelemetryOptions`.diff --git a/packages/eve/src/instrumentation/config.test.ts b/packages/eve/src/instrumentation/config.test.tsdeleted file mode 100644index 3d71c9819..000000000--- a/packages/eve/src/instrumentation/config.test.ts+++ /dev/null@@ -1,107 +0,0 @@-import { beforeEach, describe, expect, it, vi } from "vitest";--import type { InstrumentationSetupContext } from "#public/instrumentation/index.js";--const RUNTIME_GLOBAL_KEY = Symbol.for("eve.instrumentation-runtime");--beforeEach(() => {- delete (globalThis as Record<symbol, unknown>)[RUNTIME_GLOBAL_KEY];-});--describe("instrumentation config runtime registration", () => {- it("exposes a resolver registered in one module evaluation through the shared runtime", async () => {- vi.resetModules();- const moduleA = await import("#instrumentation/config.js");- const resolver = vi.fn(() => ({ runtimeContext: { team: "platform" } }));- await moduleA.registerInstrumentationConfig(- { events: { "step.started": resolver } },- { agentName: "test-agent" },- );-- vi.resetModules();- const moduleB = await import("#instrumentation/runtime.js");-- expect(- moduleB.getInstrumentationRuntime()?.stepStartedRuntimeContextResolver?.({} as never),- ).toEqual({ runtimeContext: { team: "platform" } });- expect(resolver).toHaveBeenCalledOnce();- });-- it("replaces the resolver when the authored config reloads", async () => {- const { registerInstrumentationConfig } = await import("#instrumentation/config.js");- const { getInstrumentationRuntime } = await import("#instrumentation/runtime.js");- const first = vi.fn(() => ({ runtimeContext: { version: 1 } }));- const second = vi.fn(() => ({ runtimeContext: { version: 2 } }));-- await registerInstrumentationConfig(- { events: { "step.started": first } },- { agentName: "test-agent" },- );- await registerInstrumentationConfig(- { events: { "step.started": second } },- { agentName: "test-agent" },- );-- expect(getInstrumentationRuntime()?.stepStartedRuntimeContextResolver?.({} as never)).toEqual({- runtimeContext: { version: 2 },- });- expect(first).not.toHaveBeenCalled();- expect(second).toHaveBeenCalledOnce();- });-- it("installs harness telemetry settings on the instrumentation runtime", async () => {- const { registerInstrumentationConfig } = await import("#instrumentation/config.js");- const { getInstrumentationRuntime } = await import("#instrumentation/runtime.js");-- await registerInstrumentationConfig(- {- functionId: "weather",- recordInputs: true,- recordOutputs: false,- traceChannelRequests: true,- },- { agentName: "test-agent" },- );-- expect(getInstrumentationRuntime()?.otelSettings).toEqual({- functionId: "weather",- recordInputs: true,- recordOutputs: false,- traceChannelRequests: true,- });- });-- it("disables input and output recording by default", async () => {- const { registerInstrumentationConfig } = await import("#instrumentation/config.js");- const { getInstrumentationRuntime } = await import("#instrumentation/runtime.js");-- await registerInstrumentationConfig({}, { agentName: "test-agent" });-- expect(getInstrumentationRuntime()?.otelSettings).toEqual({- functionId: undefined,- recordInputs: false,- recordOutputs: false,- traceChannelRequests: false,- });- });-- it("awaits the setup callback with the resolved context", async () => {- vi.resetModules();- const { registerInstrumentationConfig } = await import("#instrumentation/config.js");-- const contexts: InstrumentationSetupContext[] = [];- await registerInstrumentationConfig(- {- setup: (context) => {- contexts.push(context);- },- },- { agentName: "weather-agent" },- );-- expect(contexts).toHaveLength(1);- expect(contexts[0]?.agentName).toBe("weather-agent");- expect(contexts[0]?.environment).toMatch(/^(development|production)$/);- expect(contexts[0]?.frameworkVersion).toEqual(expect.any(String));- });-});diff --git a/packages/eve/src/instrumentation/config.ts b/packages/eve/src/instrumentation/config.tsdeleted file mode 100644index afdd8ac72..000000000--- a/packages/eve/src/instrumentation/config.ts+++ /dev/null@@ -1,35 +0,0 @@-import { createInstrumentationHooks } from "#instrumentation/lifecycle.js";-import { registerInstrumentationRuntime } from "#instrumentation/runtime.js";-import { createInstrumentationSetupContext } from "#instrumentation/setup-context.js";-import type { InstrumentationDefinition } from "#public/instrumentation/index.js";--/**- * Registers the authored instrumentation config and awaits its `setup`- * callback.- *- * Called once by the generated instrumentation Nitro plugin at server- * startup. Subsequent calls overwrite the previous value.- *- * @internal — not part of the public API.- */-export async function registerInstrumentationConfig(- config: InstrumentationDefinition,- input: { readonly agentName: string },-): Promise<void> {- // This legacy layout leaves `registerOTel` to `setup`, so install only the- // runtime projection consumed by the harness.- const runtime = registerInstrumentationRuntime({- forceFlush: async () => undefined,- hooks: createInstrumentationHooks([]),- otelSettings: {- functionId: config.functionId,- recordInputs: config.recordInputs === true,- recordOutputs: config.recordOutputs === true,- traceChannelRequests: config.traceChannelRequests === true,- },- runInContext: (_operation, execute) => execute(),- shutdown: async () => undefined,- });- runtime.stepStartedRuntimeContextResolver = (event) => config.events?.["step.started"]?.(event);- await config.setup?.(createInstrumentationSetupContext(input.agentName));-}diff --git a/packages/eve/src/instrumentation/provider.ts b/packages/eve/src/instrumentation/provider.tsindex e710579d2..446814b43 100644--- a/packages/eve/src/instrumentation/provider.ts+++ b/packages/eve/src/instrumentation/provider.ts@@ -1,8 +1,7 @@/*** The provider contract authored under `agent/instrumentation/`.*- * Reachable only with `experimental.instrumentationProviders` on. With the flag- * off nothing discovers that directory, so these types compile but never run.+ * Each file in the directory declares one independently configured provider.*/// Type-only, so nothing couples the provider definition to the harness at@@ -84,12 +83,7 @@ export type {* Marks a value as having come from `defineInstrumentation` or a built-in* factory.*- * It does not say which layout the value belongs to: a provider and a legacy- * config both carry `events` and `setup`, so no value-level check separates- * them. The layout decides — `agent/instrumentation.ts` is read as a config and- * `agent/instrumentation/*.ts` as providers, and the two are mutually exclusive- * builds. The brand's job is only to catch a default export that never went- * through eve at all.+ * The brand catches a default export that never went through eve.*/export const PROVIDER = Symbol.for("eve.instrumentation.provider");@@ -111,13 +105,11 @@ export interface EvaluationRef {export interface ProviderSetupContext {/** The agent name declared by `defineAgent`. */readonly agentName: string;- /** Always supplied at runtime; optional for legacy setup-context compatibility. */- readonly environment?: InstrumentationEnvironment;+ readonly environment: InstrumentationEnvironment;/** Present only when this server was started for a local `eve eval` run. */readonly evaluation?: EvaluationRef;/** The eve version running the agent. */- /** Always supplied at runtime; optional for legacy setup-context compatibility. */- readonly frameworkVersion?: string;+ readonly frameworkVersion: string;}export interface ProviderState {@@ -184,6 +176,11 @@ export interface ProviderDefinition {readonly shutdown?: () => void | PromiseLike<void>;}+/** Declares one instrumentation provider. */+export function defineInstrumentation(definition: ProviderDefinition): InstrumentationProvider {+ return { ...definition, [PROVIDER]: true };+}+/** A {@link ProviderDefinition} that has been through `defineInstrumentation`. */export type InstrumentationProvider = ProviderDefinition & {readonly [PROVIDER]: true;diff --git a/packages/eve/src/instrumentation/providers.test.ts b/packages/eve/src/instrumentation/providers.test.tsindex a8d58d4e2..110224be5 100644--- a/packages/eve/src/instrumentation/providers.test.ts+++ b/packages/eve/src/instrumentation/providers.test.ts@@ -228,7 +228,6 @@ describe("finalizeInstrumentationProviders", () => {const runtime = finalizeInstrumentationProviders({ serviceName: "weather-agent" });await runtime.hooks.forTrace!(traceContext("unknown")).publish(turnStarted);- expect(runtime.instrumentationProviders).toBe(true);expect(started).toHaveBeenCalledOnce();expect(started.mock.calls[0]?.[0]).toMatchObject({ turnId: "turn-1" });});diff --git a/packages/eve/src/instrumentation/providers.ts b/packages/eve/src/instrumentation/providers.tsindex 2ee3294cd..c25b1e0b1 100644--- a/packages/eve/src/instrumentation/providers.ts+++ b/packages/eve/src/instrumentation/providers.ts@@ -19,10 +19,9 @@ import {* Process-global registry of the providers authored under* `agent/instrumentation/`.*- * Rooted on `globalThis` for the same reason the single-config store is: the- * generated Nitro plugin stays external by `file://` URL while the harness- * chunk is inlined, so the two resolve to distinct ESM module instances and- * need one shared source of truth.+ * Rooted on `globalThis` because the generated Nitro plugin stays external by+ * `file://` URL while the harness chunk is inlined, so the two resolve to+ * distinct ESM module instances and need one shared source of truth.*/const INSTRUMENTATION_PROVIDERS_GLOBAL_KEY = Symbol.for("eve.harness-instrumentation-providers");@@ -122,7 +121,6 @@ export function finalizeInstrumentationProviders(input: {return installInstrumentationRuntime({collected,frameworkVersion: resolveInstalledPackageInfo().version,- instrumentationProviders: true,providers: providerDefinitions,runtimeContextResolvers: collected.runtimeContextResolvers,serviceName: input.serviceName,diff --git a/packages/eve/src/instrumentation/runtime-context.test.ts b/packages/eve/src/instrumentation/runtime-context.test.tsindex 6c20d14a8..98169d4e6 100644--- a/packages/eve/src/instrumentation/runtime-context.test.ts+++ b/packages/eve/src/instrumentation/runtime-context.test.ts@@ -1,5 +1,5 @@import type { ModelMessage } from "ai";-import { describe, expect, it, vi } from "vitest";+import { describe, expect, it } from "vitest";import { ContextContainer, contextStorage } from "#context/container.js";import { AuthKey, ChannelInstrumentationKey } from "#context/keys.js";@@ -10,10 +10,7 @@ import {} from "#instrumentation/runtime-context.js";import type { RuntimeContextResolver } from "#tracing/otel-declaration.js";import type { HarnessSession } from "#harness/types.js";-import type {- InstrumentationStepStartedEventInput,- InstrumentationStepStartedEventResult,-} from "#public/instrumentation/index.js";+import type { InstrumentationStepStartedEventInput } from "#public/instrumentation/index.js";const session: HarnessSession = {agent: {@@ -55,93 +52,32 @@ function build(emissionState,environment: "test",modelInput: { instructions: undefined, messages },+ providerResolvers: [() => undefined],session,- stepStartedResolver: () => undefined,...overrides,});}describe("buildTelemetryRuntimeContext", () => {it("returns undefined when no instrumentation is authored", () => {- expect(build({ stepStartedResolver: undefined })).toBeUndefined();+ expect(build({ providerResolvers: undefined })).toBeUndefined();});it("emits framework identifiers when no resolver is configured", () => {expect(build()).toEqual(FRAMEWORK_KEYS);});- it("merges authored step.started runtime context beneath framework keys", () => {- const runtimeContext = build({- stepStartedResolver: () => ({ runtimeContext: { team: "platform" } }),- });-- expect(runtimeContext).toEqual({ ...FRAMEWORK_KEYS, team: "platform" });- });-- it("drops reserved eve.* keys from authored runtime context", () => {- const runtimeContext = build({- stepStartedResolver: () =>- ({- runtimeContext: {- "eve.session.id": "user-override",- count: 1,- nested: { ok: true },- team: "platform",- },- }) as never,- });-- expect(runtimeContext).toEqual({- ...FRAMEWORK_KEYS,- count: 1,- nested: { ok: true },- team: "platform",- });- });-- it("keeps framework context authoritative when authored runtime context throws", () => {- const runtimeContext = build({- stepStartedResolver: () => {- throw new Error("runtime context resolver failed");- },- });-- expect(runtimeContext).toEqual(FRAMEWORK_KEYS);- });-- it("ignores authored runtime context that returns a Promise", () => {- const runtimeContext = build({- stepStartedResolver: () => Promise.resolve({ runtimeContext: { team: "platform" } }) as never,- });-- expect(runtimeContext).toEqual(FRAMEWORK_KEYS);- });-- it("ignores authored event results without runtimeContext", () => {- const runtimeContext = build({- stepStartedResolver: () => ({}) as never,- });-- expect(runtimeContext).toEqual(FRAMEWORK_KEYS);- });-- it("treats undefined event results as no-op without warning", () => {- const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});-- try {- const runtimeContext = build({- stepStartedResolver: () => undefined,- });-- expect(runtimeContext).toEqual(FRAMEWORK_KEYS);- expect(warnSpy).not.toHaveBeenCalled();- } finally {- warnSpy.mockRestore();- }- });-it("reflects the active channel kind and exposes channel metadata to the resolver", () => {const ctx = new ContextContainer();+ const resolver: RuntimeContextResolver = (input) => {+ if (input.channel.kind !== "channel:support") return undefined;+ return {+ "slack.user_id":+ typeof input.channel.metadata["triggeringUserId"] === "string"+ ? input.channel.metadata["triggeringUserId"]+ : "",+ };+ };ctx.set(ChannelInstrumentationKey, {kind: "channel:support",metadata: { triggeringUserId: "U999" },@@ -149,19 +85,7 @@ describe("buildTelemetryRuntimeContext", () => {const runtimeContext = contextStorage.run(ctx, () =>build({- stepStartedResolver: (- input: InstrumentationStepStartedEventInput,- ): InstrumentationStepStartedEventResult =>- input.channel.kind === "channel:support"- ? {- runtimeContext: {- "slack.user_id":- typeof input.channel.metadata["triggeringUserId"] === "string"- ? input.channel.metadata["triggeringUserId"]- : "",- },- }- : { runtimeContext: {} },+ providerResolvers: [resolver],}),);@@ -175,10 +99,12 @@ describe("buildTelemetryRuntimeContext", () => {let captured: InstrumentationStepStartedEventInput | undefined;build({- stepStartedResolver: (input: InstrumentationStepStartedEventInput) => {- captured = input;- return { runtimeContext: {} };- },+ providerResolvers: [+ (input: InstrumentationStepStartedEventInput) => {+ captured = input;+ return {};+ },+ ],});expect(captured?.modelInput).toEqual({ instructions: undefined, messages: [] });@@ -195,10 +121,12 @@ describe("buildTelemetryRuntimeContext", () => {contextStorage.run(ctx, () =>build({capturesContent: true,- stepStartedResolver: (input: InstrumentationStepStartedEventInput) => {- captured = input;- return { runtimeContext: {} };- },+ providerResolvers: [+ (input: InstrumentationStepStartedEventInput) => {+ captured = input;+ return {};+ },+ ],}),);@@ -223,10 +151,12 @@ describe("buildTelemetryRuntimeContext", () => {let captured: InstrumentationStepStartedEventInput | undefined;contextStorage.run(ctx, () =>build({- stepStartedResolver: (input: InstrumentationStepStartedEventInput) => {- captured = input;- return { runtimeContext: {} };- },+ providerResolvers: [+ (input: InstrumentationStepStartedEventInput) => {+ captured = input;+ return {};+ },+ ],}),);@@ -240,77 +170,54 @@ describe("buildTelemetryRuntimeContext", () => {expect(captured.channel.metadata).toMatchObject({ nested: { value: "original" } });});- describe("provider runtimeContext resolvers", () => {- it("emits framework keys when a provider resolver returns undefined", () => {+ describe("runtimeContext resolvers", () => {+ it("emits framework keys when a resolver returns undefined", () => {const resolver: RuntimeContextResolver = () => undefined;- const runtimeContext = build({- providerResolvers: [resolver],- stepStartedResolver: undefined,- });+ const runtimeContext = build({ providerResolvers: [resolver] });expect(runtimeContext).toEqual(FRAMEWORK_KEYS);});- it("merges a single provider resolver beneath framework keys", () => {+ it("merges a single resolver beneath framework keys", () => {const resolver: RuntimeContextResolver = () => ({ team: "platform" });- const runtimeContext = build({- providerResolvers: [resolver],- stepStartedResolver: undefined,- });+ const runtimeContext = build({ providerResolvers: [resolver] });expect(runtimeContext).toEqual({ ...FRAMEWORK_KEYS, team: "platform" });});- it("merges multiple provider resolvers, later ones overriding earlier", () => {+ it("merges multiple resolvers, later ones overriding earlier", () => {const first: RuntimeContextResolver = () => ({ env: "prod", team: "a" });const second: RuntimeContextResolver = () => ({ team: "b" });const runtimeContext = build({providerResolvers: [first, second],- stepStartedResolver: undefined,});expect(runtimeContext).toEqual({ ...FRAMEWORK_KEYS, env: "prod", team: "b" });});- it("drops reserved eve.* keys from provider resolver results", () => {+ it("drops reserved eve.* keys from resolver results", () => {const resolver: RuntimeContextResolver = () =>({ "eve.session.id": "override", team: "platform" }) as never;- const runtimeContext = build({- providerResolvers: [resolver],- stepStartedResolver: undefined,- });+ const runtimeContext = build({ providerResolvers: [resolver] });expect(runtimeContext).toEqual({ ...FRAMEWORK_KEYS, team: "platform" });});- it("continues when a provider resolver throws", () => {+ it("continues when a resolver throws", () => {const failing: RuntimeContextResolver = () => {throw new Error("boom");};const healthy: RuntimeContextResolver = () => ({ team: "platform" });const runtimeContext = build({providerResolvers: [failing, healthy],- stepStartedResolver: undefined,});expect(runtimeContext).toEqual({ ...FRAMEWORK_KEYS, team: "platform" });});- it("returns undefined when no authored config and no provider resolvers", () => {- expect(- build({ providerResolvers: undefined, stepStartedResolver: undefined }),- ).toBeUndefined();- expect(build({ providerResolvers: [], stepStartedResolver: undefined })).toBeUndefined();- });-- it("merges provider resolver results alongside the legacy step.started hook", () => {- const resolver: RuntimeContextResolver = () => ({ source: "provider" });- const runtimeContext = build({- providerResolvers: [resolver],- stepStartedResolver: () => ({ runtimeContext: { source: "legacy" } }),- });-- expect(runtimeContext).toEqual({ ...FRAMEWORK_KEYS, source: "provider" });+ it("returns undefined when no resolvers are configured", () => {+ expect(build({ providerResolvers: undefined })).toBeUndefined();+ expect(build({ providerResolvers: [] })).toBeUndefined();});});});diff --git a/packages/eve/src/instrumentation/runtime-context.ts b/packages/eve/src/instrumentation/runtime-context.tsindex a793511e2..4d8b47121 100644--- a/packages/eve/src/instrumentation/runtime-context.ts+++ b/packages/eve/src/instrumentation/runtime-context.ts@@ -23,11 +23,10 @@ import {import { createLogger, formatError } from "#internal/logging.js";import type {InstrumentationChannel,- InstrumentationEvents,InstrumentationRuntimeContext,InstrumentationStepStartedEventInput,} from "#public/instrumentation/index.js";-import { parseJsonObject, parseJsonValue, type JsonObject, type JsonValue } from "#shared/json.js";+import { parseJsonValue, type JsonObject, type JsonValue } from "#shared/json.js";const log = createLogger("harness.instrumentation-runtime-context");@@ -43,7 +42,6 @@ export interface BuildTelemetryRuntimeContextInput {};readonly providerResolvers?: readonly RuntimeContextResolver[];readonly session: HarnessSession;- readonly stepStartedResolver: InstrumentationEvents["step.started"];}export interface InstrumentationRuntimeContextSnapshot {@@ -75,27 +73,23 @@ export function snapshotInstrumentationRuntimeContext(/*** Builds per-model-call runtime context for AI SDK telemetry spans.*- * Authored runtime context is parsed defensively. Invalid event results,- * reserved `eve.*` keys, and callback failures are warning-only so- * instrumentation cannot compromise the normal turn flow.+ * Runtime context is parsed defensively. Invalid results, reserved `eve.*`+ * keys, and callback failures are warning-only.*/export function buildTelemetryRuntimeContext(input: BuildTelemetryRuntimeContextInput,): Record<string, unknown> | undefined {- const hasStepStartedResolver = input.stepStartedResolver !== undefined;const hasProviderResolvers =input.providerResolvers !== undefined && input.providerResolvers.length > 0;- if (!hasStepStartedResolver && !hasProviderResolvers) {+ if (!hasProviderResolvers) {return undefined;}- const authoredRuntimeContext = resolveStepStartedRuntimeContext(input);const providerRuntimeContext = resolveProviderRuntimeContext(input);const context = input.context ?? snapshotInstrumentationRuntimeContext(contextStorage.getStore());const projection = context.channel;return {- ...authoredRuntimeContext,...providerRuntimeContext,"eve.channel.kind": normalizeInstrumentationChannelKind(projection?.kind),"eve.environment": input.environment,@@ -108,10 +102,7 @@ export function buildTelemetryRuntimeContext(}function buildInstrumentationStepStartedInput(- input: Omit<- BuildTelemetryRuntimeContextInput,- "eveVersion" | "environment" | "stepStartedResolver"- >,+ input: Omit<BuildTelemetryRuntimeContextInput, "eveVersion" | "environment">,): InstrumentationStepStartedEventInput {const context = input.context ?? snapshotInstrumentationRuntimeContext(contextStorage.getStore());const projection = context.channel;@@ -163,52 +154,11 @@ function filterAuthoredRuntimeContext(return Object.keys(runtimeContext).length > 0 ? runtimeContext : undefined;}-function resolveStepStartedRuntimeContext(- input: BuildTelemetryRuntimeContextInput,-): InstrumentationRuntimeContext | undefined {- const resolver = input.stepStartedResolver;- if (resolver === undefined) {- return undefined;- }-- const source = 'events["step.started"]';- const invoke = () => {- const stepStartedInput = buildInstrumentationStepStartedInput(input);- return resolver(stepStartedInput);- };- const result = resolveInstrumentationProjection({- invoke,- log,- source,- });- if (result === undefined) {- return undefined;- }-- if (!("runtimeContext" in result)) {- log.warn("ignoring instrumentation event result because runtimeContext is missing", { source });- return undefined;- }-- let runtimeContext: JsonObject;- try {- runtimeContext = parseJsonObject(result.runtimeContext);- } catch (error) {- log.warn("ignoring instrumentation event result because runtimeContext is invalid", {- error: formatError(error),- source,- });- return undefined;- }-- return filterAuthoredRuntimeContext(runtimeContext, source);-}-/*** Collects `runtimeContext` contributions from every provider resolver,- * invoking each with a snapshot of the same input the legacy `step.started`- * hook receives. Failures are warning-only so one provider cannot break the- * turn. Later providers override earlier ones on key collision.+ * invoking each with a snapshot of the model attempt. Failures are warning-only+ * so one destination cannot break the turn. Later destinations override earlier+ * ones on key collision.*/function resolveProviderRuntimeContext(input: BuildTelemetryRuntimeContextInput,diff --git a/packages/eve/src/instrumentation/runtime-global.ts b/packages/eve/src/instrumentation/runtime-global.tsindex 4db1d2d8f..ea69b6bc8 100644--- a/packages/eve/src/instrumentation/runtime-global.ts+++ b/packages/eve/src/instrumentation/runtime-global.ts@@ -14,7 +14,7 @@ export function registerInstrumentationRuntime(): InstrumentationRuntime {const existing = globalRuntime[INSTRUMENTATION_RUNTIME_KEY];if (existing !== undefined) {- // A legacy config may reload without taking ownership from the installed runtime.+ // Keep ownership stable when initialization is attempted more than once.existing.otelSettings = runtime.otelSettings;return existing;}diff --git a/packages/eve/src/instrumentation/runtime.test.ts b/packages/eve/src/instrumentation/runtime.test.tsindex 454c05c86..ccbb88afd 100644--- a/packages/eve/src/instrumentation/runtime.test.ts+++ b/packages/eve/src/instrumentation/runtime.test.ts@@ -225,14 +225,14 @@ describe("initializeSessionInstrumentation", () => {it("redacts runtime-context model input when the forwarded ceiling denies inputs", async () => {const ctx = createContext("public");- const runtime = createRuntime({ capturesContent: true, publish: vi.fn() }, () => ({- emit: true,- recordInputs: true,- recordOutputs: true,- }));- runtime.stepStartedRuntimeContextResolver = (event) => ({- runtimeContext: { messageCount: event.modelInput.messages.length },- });+ const runtime: InstrumentationRuntime = {+ ...createRuntime({ capturesContent: true, publish: vi.fn() }, () => ({+ emit: true,+ recordInputs: true,+ recordOutputs: true,+ })),+ runtimeContextResolvers: [(event) => ({ messageCount: event.modelInput.messages.length })],+ };registerInstrumentationRuntime({...runtime,idGenerator: new AgentSpanIdGenerator(),@@ -693,10 +693,10 @@ describe("bindInstrumentationRuntime", () => {it("isolates concurrent step decisions and audiences", async () => {const ctx = createContext("private");- const runtime = createRuntime({ capturesContent: true, publish: vi.fn() });- runtime.stepStartedRuntimeContextResolver = (event) => ({- runtimeContext: { messageCount: event.modelInput.messages.length },- });+ const runtime: InstrumentationRuntime = {+ ...createRuntime({ capturesContent: true, publish: vi.fn() }),+ runtimeContextResolvers: [(event) => ({ messageCount: event.modelInput.messages.length })],+ };const instrumentation = bindInstrumentationRuntime(runtime,ctx,diff --git a/packages/eve/src/instrumentation/runtime.ts b/packages/eve/src/instrumentation/runtime.tsindex 2c7b83820..25e0ee308 100644--- a/packages/eve/src/instrumentation/runtime.ts+++ b/packages/eve/src/instrumentation/runtime.ts@@ -1,7 +1,6 @@import type { Telemetry, TelemetryOptions } from "ai";import { context as otelContext, trace } from "#compiled/@opentelemetry/api/index.js";-import type { InstrumentationEvents } from "#public/instrumentation/index.js";import type { InstrumentationDecision } from "#shared/instrumentation-decision.js";import { shouldCaptureInstrumentationContent } from "#shared/instrumentation-content.js";import type {@@ -114,7 +113,7 @@ export interface InstrumentationStepScope<TSession> {readonly resolveRuntimeContext: (input: Omit<BuildTelemetryRuntimeContextInput,- "capturesContent" | "context" | "providerResolvers" | "stepStartedResolver"+ "capturesContent" | "context" | "providerResolvers">,) => Record<string, unknown> | undefined;readonly session: TSession;@@ -145,7 +144,6 @@ export interface InstrumentationRuntime {readonly forceFlush: () => Promise<void>;readonly hooks: InstrumentationHooks;readonly idGenerator?: AgentSpanIdGenerator;- readonly instrumentationProviders?: boolean;readonly memoryOperations?: boolean;readonly ownsAgentSpans?: boolean;readonly prepareSessionTrace?: (@@ -160,7 +158,6 @@ export interface InstrumentationRuntime {/** Whether the installed OTel sampler would record a trace with this id. */readonly samplesTrace?: (traceId: string, operation?: AgentSamplingOperation) => boolean;readonly shutdown: () => Promise<void>;- stepStartedRuntimeContextResolver?: InstrumentationEvents["step.started"];}/** Worker-bound instrumentation operations consumed by one session execution. */@@ -223,7 +220,6 @@ export function bindInstrumentationRuntime(ownsAgentSpans,otelSettings,runtimeContextResolvers: runtime.runtimeContextResolvers,- stepStartedRuntimeContextResolver: runtime.stepStartedRuntimeContextResolver,tracer: otelSettings === undefined ? undefined : trace.getTracer("eve"),};};@@ -458,7 +454,6 @@ export function bindInstrumentationRuntime(capturesContent: capturesRuntimeContextInput,context: runtimeContextSnapshot,providerResolvers: executionRuntime.runtimeContextResolvers,- stepStartedResolver: executionRuntime.stepStartedRuntimeContextResolver,});},session,diff --git a/packages/eve/src/instrumentation/setup-context.ts b/packages/eve/src/instrumentation/setup-context.tsindex 34247c404..0260b0c15 100644--- a/packages/eve/src/instrumentation/setup-context.ts+++ b/packages/eve/src/instrumentation/setup-context.ts@@ -8,11 +8,6 @@ import type { ProviderSetupContext } from "#public/instrumentation/provider.js";/*** Builds the context handed to an authored `setup` at server startup.*- * Shared by both layouts so the two cannot drift: a divergent context type- * would leave `defineInstrumentation`'s union without a contextual signature- * for `setup`, silently making every authored `setup(context)` parameter an- * implicit `any`.- ** @internal — not part of the public API.*/export function createInstrumentationSetupContext(agentName: string): ProviderSetupContext {diff --git a/packages/eve/src/internal/application/compiled-artifacts.ts b/packages/eve/src/internal/application/compiled-artifacts.tsindex 300d05dd4..3f3732466 100644--- a/packages/eve/src/internal/application/compiled-artifacts.ts+++ b/packages/eve/src/internal/application/compiled-artifacts.ts@@ -25,17 +25,10 @@ import { resolveWorkflowWorldImport } from "#internal/workflow/world-target.js";export type BuiltInWorkflowWorldTarget = "local" | "vercel";-export type GeneratedInstrumentationLayout =- | { readonly kind: "file" }- | { readonly kind: "directory"; readonly slots: readonly string[] };--type InstrumentationPluginLayout =- | InstrumentationLayout- | {- readonly kind: "module-map";- readonly moduleMapPath: string;- readonly sourceId: string;- };+export interface GeneratedInstrumentationLayout {+ readonly kind: "directory";+ readonly slots: readonly string[];+}/*** Paths to the generated compiled-artifacts files shared by Nitro and the@@ -58,9 +51,8 @@ export interface GeneratedCompiledArtifactsFiles {/** Layout identity used by dev plugin selection and structural fingerprinting. */instrumentationLayout?: GeneratedInstrumentationLayout;/**- * 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.+ * Absolute paths to prepared provider modules. Nitro uses these to preserve+ * each module's side effects during packaging.*/instrumentationSourcePaths?: readonly string[];}@@ -112,40 +104,27 @@ export async function writeCompiledArtifactsFiles(input: {workflowWorldPluginPath,};- if (input.compileResult.manifest.instrumentation !== undefined) {- const sourceId = input.compileResult.manifest.instrumentation.sourceId;- await writeFile(- instrumentationPluginPath,- createInstrumentationPluginSource({- agentName: input.compileResult.manifest.config.name,- layout: { kind: "module-map", moduleMapPath, sourceId },- }),- );- generatedArtifacts.instrumentationPluginPath = instrumentationPluginPath;- generatedArtifacts.instrumentationLayout = { kind: "file" };- generatedArtifacts.instrumentationSourcePaths = [moduleMapPath];- } else if (prepared.instrumentation !== undefined) {- const providerLayout = await writePreparedInstrumentation({- instrumentation: prepared.instrumentation,- outDir: input.outDir,- });- await writeFile(- instrumentationPluginPath,- createInstrumentationPluginSource({- agentName: input.compileResult.manifest.config.name,- layout: providerLayout,- }),- );- generatedArtifacts.instrumentationPluginPath = instrumentationPluginPath;- generatedArtifacts.instrumentationLayout = generatedInstrumentationLayout(providerLayout);- generatedArtifacts.instrumentationSourcePaths = instrumentationSourcePathsOf(providerLayout);- }+ const instrumentationLayout = await writePreparedInstrumentation({+ instrumentation: prepared.instrumentation,+ outDir: input.outDir,+ });+ await writeFile(+ instrumentationPluginPath,+ createInstrumentationPluginSource({+ agentName: input.compileResult.manifest.config.name,+ layout: instrumentationLayout,+ }),+ );+ generatedArtifacts.instrumentationPluginPath = instrumentationPluginPath;+ generatedArtifacts.instrumentationLayout = generatedInstrumentationLayout(instrumentationLayout);+ generatedArtifacts.instrumentationSourcePaths =+ instrumentationSourcePathsOf(instrumentationLayout);return generatedArtifacts;}async function writePreparedInstrumentation(input: {- readonly instrumentation: NonNullable<PreparedAuthoredRuntimeModules["instrumentation"]>;+ readonly instrumentation: PreparedAuthoredRuntimeModules["instrumentation"];readonly outDir: string;}): Promise<InstrumentationLayout> {const writeOne = async (sourceId: string, code: string): Promise<string> => {@@ -162,7 +141,7 @@ async function writePreparedInstrumentation(input: {}function instrumentationSourcePathsOf(layout: InstrumentationLayout): readonly string[] {- return layout.kind === "file" ? [layout.modulePath] : Object.values(layout.modulePathsBySlot);+ return Object.values(layout.modulePathsBySlot);}// The dev host's Nitro inputs outlive any single generation, so nothing@@ -203,25 +182,7 @@ export async function writeDevelopmentCompiledArtifactsFiles(input: {workflowWorldPluginPath,};- if (input.compileResult.manifest.instrumentation !== undefined) {- const compileRoot = join(input.runtimeAppRoot, ".eve", "compile");- const moduleMapPath = join(input.outDir, "compiled-artifacts-instrumentation-source.mjs");- await copyFile(join(compileRoot, materializedIndex.moduleMap), moduleMapPath);- await writeFile(- instrumentationPluginPath,- createInstrumentationPluginSource({- agentName: input.compileResult.manifest.config.name,- layout: {- kind: "module-map",- moduleMapPath,- sourceId: input.compileResult.manifest.instrumentation.sourceId,- },- }),- );- generatedArtifacts.instrumentationPluginPath = instrumentationPluginPath;- generatedArtifacts.instrumentationLayout = { kind: "file" };- generatedArtifacts.instrumentationSourcePaths = [moduleMapPath];- } else if (materializedIndex.instrumentation !== undefined) {+ if (materializedIndex.instrumentation !== undefined) {const layout = await copyMaterializedInstrumentation({instrumentation: materializedIndex.instrumentation,outDir: input.outDir,@@ -246,9 +207,7 @@ export async function writeDevelopmentCompiledArtifactsFiles(input: {function generatedInstrumentationLayout(layout: InstrumentationLayout,): GeneratedInstrumentationLayout {- return layout.kind === "file"- ? { kind: "file" }- : { kind: "directory", slots: Object.keys(layout.modulePathsBySlot) };+ return { kind: "directory", slots: Object.keys(layout.modulePathsBySlot) };}/**@@ -268,13 +227,6 @@ async function copyMaterializedInstrumentation(input: {return destination;};- if (input.instrumentation.kind === "file") {- return {- kind: "file",- modulePath: await copyOne("source", input.instrumentation.modulePath),- };- }-const modulePathsBySlot: Record<string, string> = {};for (const [slot, modulePath] of Object.entries(input.instrumentation.modulePathsBySlot)) {modulePathsBySlot[slot] = await copyOne(slot, modulePath);@@ -485,52 +437,16 @@ export function createDevelopmentWorkflowWorldPluginSource(input: {/*** Generates the Nitro plugin that registers the authored instrumentation.*- * The file layout registers one default export; the directory layout- * registers one per file, in slot order, awaiting each `setup` so a provider- * cannot miss an event published while it is still starting up, then builds the- * one OpenTelemetry pipeline their declarations add up to.+ * Registers one provider per file in slot order, awaiting each `setup` so a+ * provider cannot miss an event published while it is still starting up, then+ * builds the one OpenTelemetry pipeline their declarations add up to.*/function createInstrumentationPluginSource(input: {agentName: string;- layout: InstrumentationPluginLayout;+ layout: InstrumentationLayout;}): string {const agentName = JSON.stringify(input.agentName);- if (input.layout.kind === "module-map") {- const registerConfigPath = resolvePackageSourceFilePath("src/instrumentation/config.ts");- return [- "// Generated by eve. Do not edit by hand.",- `import { moduleMap } from ${stringifyEsmImportSpecifier(input.layout.moduleMapPath)};`,- `import { registerInstrumentationConfig } from ${stringifyEsmImportSpecifier(registerConfigPath)};`,- "",- `const instrumentationModule = moduleMap.nodes["__root__"].modules[${JSON.stringify(input.layout.sourceId)}];`,- "if (instrumentationModule.default != null) {",- ` await registerInstrumentationConfig(instrumentationModule.default, { agentName: ${agentName} });`,- "}",- "",- "export default function installInstrumentationPlugin() {}",- "",- ].join("\n");- }-- if (input.layout.kind === "file") {- const registerConfigPath = resolvePackageSourceFilePath("src/instrumentation/config.ts");- return [- "// Generated by eve. Do not edit by hand.",- `import * as instrumentationModule from ${stringifyEsmImportSpecifier(input.layout.modulePath)};`,- `import { registerInstrumentationConfig } from ${stringifyEsmImportSpecifier(registerConfigPath)};`,- "",- "if (instrumentationModule.default != null) {",- ` await registerInstrumentationConfig(instrumentationModule.default, { agentName: ${agentName} });`,- "}",- "",- "// Default export satisfies the Nitro plugin contract so this file",- "// can be used directly as a Nitro plugin without a separate wrapper.",- "export default function installInstrumentationPlugin() {}",- "",- ].join("\n");- }-const registerProviderPath = resolvePackageSourceFilePath("src/instrumentation/providers.ts");const slots = Object.entries(input.layout.modulePathsBySlot);diff --git a/packages/eve/src/internal/authored-definition/core.ts b/packages/eve/src/internal/authored-definition/core.tsindex e0f7ed1f2..8c4cbc278 100644--- a/packages/eve/src/internal/authored-definition/core.ts+++ b/packages/eve/src/internal/authored-definition/core.ts@@ -311,16 +311,9 @@ function normalizeAgentExperimentalDefinition(message: string,): NonNullable<NormalizedAgentDefinition["experimental"]> {const record = expectObjectRecord(value, message);- expectOnlyKnownKeys(record, ["instrumentationProviders", "workflow"], message);+ expectOnlyKnownKeys(record, ["workflow"], message);const normalizedDefinition: Mutable<NonNullable<NormalizedAgentDefinition["experimental"]>> = {};- if (record.instrumentationProviders !== undefined) {- if (typeof record.instrumentationProviders !== "boolean") {- throw new Error(`${message} "experimental.instrumentationProviders" must be a boolean.`);- }- normalizedDefinition.instrumentationProviders = record.instrumentationProviders;- }-if (record.workflow !== undefined) {normalizedDefinition.workflow = normalizeAgentWorkflowDefinition(record.workflow, message);}diff --git a/packages/eve/src/internal/authored-runtime-modules.ts b/packages/eve/src/internal/authored-runtime-modules.tsindex 370b1ca62..2eee0f2ea 100644--- a/packages/eve/src/internal/authored-runtime-modules.ts+++ b/packages/eve/src/internal/authored-runtime-modules.ts@@ -14,7 +14,7 @@ interface PreparedAuthoredRuntimeInstrumentation {export interface PreparedAuthoredRuntimeModules {readonly authoredWorkflowModules: AuthoredWorkflowModules;- readonly instrumentation?: PreparedAuthoredRuntimeInstrumentation;+ readonly instrumentation: PreparedAuthoredRuntimeInstrumentation;readonly moduleMapCode: string;/** Identity of authored sources shared by the workflow driver and step registrations. */readonly workflowSourceFingerprint: string | undefined;@@ -30,26 +30,17 @@ export async function prepareAuthoredRuntimeModules(input: {code: moduleMapCode,workflowSourceFingerprint,} = await bundleAuthoredModuleMapForGeneration(input);- const providersEnabled = input.manifest.config.experimental?.instrumentationProviders ?? false;- const layout = providersEnabled- ? resolveInstrumentationLayout({ agentRoot: input.manifest.agentRoot, providersEnabled: true })- : undefined;+ const layout = resolveInstrumentationLayout({ agentRoot: input.manifest.agentRoot });const externalDependencies = input.manifest.config.build?.externalDependencies ?? [];const bundleInstrumentationModule = async (sourcePath: string): Promise<string> =>await bundleAuthoredModuleForGeneration(sourcePath, { externalDependencies });- let instrumentation: PreparedAuthoredRuntimeInstrumentation | undefined;+ const moduleCodeBySlot = Object.fromEntries(+ await mapConcurrent(Object.entries(layout.modulePathsBySlot), async ([slot, sourcePath]) => [+ slot,+ await bundleInstrumentationModule(sourcePath),+ ]),+ );+ const instrumentation = { kind: "directory", moduleCodeBySlot } as const;- if (layout?.kind === "directory") {- const moduleCodeBySlot = Object.fromEntries(- await mapConcurrent(Object.entries(layout.modulePathsBySlot), async ([slot, sourcePath]) => [- slot,- await bundleInstrumentationModule(sourcePath),- ]),- );- instrumentation = { kind: "directory", moduleCodeBySlot };- }-- return instrumentation === undefined- ? { authoredWorkflowModules, moduleMapCode, workflowSourceFingerprint }- : { authoredWorkflowModules, instrumentation, moduleMapCode, workflowSourceFingerprint };+ return { authoredWorkflowModules, instrumentation, moduleMapCode, workflowSourceFingerprint };}diff --git a/packages/eve/src/internal/instrumentation-layout.integration.test.ts b/packages/eve/src/internal/instrumentation-layout.integration.test.tsindex eca880b2b..f8b636584 100644--- a/packages/eve/src/internal/instrumentation-layout.integration.test.ts+++ b/packages/eve/src/internal/instrumentation-layout.integration.test.ts@@ -11,10 +11,8 @@ beforeEach(() => {agentRoot = mkdtempSync(join(tmpdir(), "eve-instrumentation-layout-"));});-function writeInstrumentationFile(extension = ".ts"): string {- const path = join(agentRoot, `instrumentation${extension}`);- writeFileSync(path, "export default {};\n");- return path;+function writeInstrumentationFile(extension = ".ts"): void {+ writeFileSync(join(agentRoot, `instrumentation${extension}`), "export default {};\n");}function writeInstrumentationProvider(fileName: string): string {@@ -25,102 +23,49 @@ function writeInstrumentationProvider(fileName: string): string {return path;}-describe("resolveInstrumentationLayout with providers off", () => {- it("returns nothing when the agent authored no instrumentation", () => {- expect(resolveInstrumentationLayout({ agentRoot, providersEnabled: false })).toBeUndefined();- });-- it("resolves the single instrumentation file", () => {- const modulePath = writeInstrumentationFile();-- expect(resolveInstrumentationLayout({ agentRoot, providersEnabled: false })).toEqual({- kind: "file",- modulePath,- });- });-- it.each([[".mts"], [".js"], [".mjs"]])("resolves a %s instrumentation file", (extension) => {- const modulePath = writeInstrumentationFile(extension);-- expect(resolveInstrumentationLayout({ agentRoot, providersEnabled: false })).toEqual({- kind: "file",- modulePath,- });- });-- it("ignores a providers directory", () => {- writeInstrumentationProvider("otel.ts");-- expect(resolveInstrumentationLayout({ agentRoot, providersEnabled: false })).toBeUndefined();- });-});--describe("resolveInstrumentationLayout with providers on", () => {+describe("resolveInstrumentationLayout", () => {it("returns an empty directory layout for eve's built-in destinations", () => {- expect(resolveInstrumentationLayout({ agentRoot, providersEnabled: true })).toEqual({+ expect(resolveInstrumentationLayout({ agentRoot })).toEqual({kind: "directory",modulePathsBySlot: {},});});- it("keys each file by the slot its name derives", () => {+ it("keys files by path-derived slot in stable order", () => {const otel = writeInstrumentationProvider("otel.ts");const local = writeInstrumentationProvider("local.mts");+ const agentRuns = writeInstrumentationProvider("agent-runs.mjs");- expect(resolveInstrumentationLayout({ agentRoot, providersEnabled: true })).toEqual({+ expect(resolveInstrumentationLayout({ agentRoot })).toEqual({kind: "directory",- modulePathsBySlot: { local, otel },+ modulePathsBySlot: { "agent-runs": agentRuns, local, otel },});});- it("orders slots independently of directory enumeration", () => {- writeInstrumentationProvider("otel.ts");- writeInstrumentationProvider("agent-runs.ts");- writeInstrumentationProvider("local.ts");-- const layout = resolveInstrumentationLayout({ agentRoot, providersEnabled: true });-- expect(Object.keys(layout?.kind === "directory" ? layout.modulePathsBySlot : {})).toEqual([- "agent-runs",- "local",- "otel",- ]);- });-it("ignores files that are not instrumentation modules", () => {- writeInstrumentationProvider("otel.ts");+ const otel = writeInstrumentationProvider("otel.ts");writeInstrumentationProvider("README.md");- const layout = resolveInstrumentationLayout({ agentRoot, providersEnabled: true });-- expect(Object.keys(layout?.kind === "directory" ? layout.modulePathsBySlot : {})).toEqual([- "otel",- ]);+ expect(resolveInstrumentationLayout({ agentRoot }).modulePathsBySlot).toEqual({ otel });});it("rejects two files claiming one slot", () => {writeInstrumentationProvider("otel.ts");writeInstrumentationProvider("otel.js");- expect(() => resolveInstrumentationLayout({ agentRoot, providersEnabled: true })).toThrow(+ expect(() => resolveInstrumentationLayout({ agentRoot })).toThrow(/Two files declare the "otel" instrumentation provider/,);});- it("rejects a single instrumentation file, naming the flag", () => {- writeInstrumentationFile();-- expect(() => resolveInstrumentationLayout({ agentRoot, providersEnabled: true })).toThrow(- /experimental\.instrumentationProviders/,- );- });-- it("prefers the file error when both layouts are present", () => {- writeInstrumentationFile();- writeInstrumentationProvider("otel.ts");+ it.each([".ts", ".mts", ".js", ".mjs"])(+ "rejects the removed single-file layout for %s",+ (extension) => {+ writeInstrumentationFile(extension);- expect(() => resolveInstrumentationLayout({ agentRoot, providersEnabled: true })).toThrow(- /Move it into the "instrumentation\/" directory/,- );- });+ expect(() => resolveInstrumentationLayout({ agentRoot })).toThrow(+ /Move it into the "instrumentation\/" directory/,+ );+ },+ );});diff --git a/packages/eve/src/internal/instrumentation-layout.ts b/packages/eve/src/internal/instrumentation-layout.tsindex 6c46082d7..f39fa87ff 100644--- a/packages/eve/src/internal/instrumentation-layout.ts+++ b/packages/eve/src/internal/instrumentation-layout.ts@@ -1,58 +1,32 @@import { existsSync, readdirSync, statSync } from "node:fs";import { join } from "node:path";-import { createLogger } from "#internal/logging.js";-const INSTRUMENTATION_EXTENSIONS = [".ts", ".mts", ".js", ".mjs"] as const;const INSTRUMENTATION_DIRECTORY = "instrumentation";-const PROVIDERS_FLAG = "experimental.instrumentationProviders";-const log = createLogger("internal.instrumentation-layout");--/**- * How instrumentation is authored for one agent.- *- * `file` is the single `agent/instrumentation.ts` default export. `directory`- * contains one provider per file, keyed by the slot name the- * file derives (`instrumentation/otel.ts` → `otel`). Which one an agent may use- * is decided by `experimental.instrumentationProviders`, never by what happens- * to be on disk.- */-export type InstrumentationLayout =- | { readonly kind: "file"; readonly modulePath: string }- | { readonly kind: "directory"; readonly modulePathsBySlot: Readonly<Record<string, string>> };+/** Instrumentation providers keyed by their path-derived slot name. */+export interface InstrumentationLayout {+ readonly kind: "directory";+ readonly modulePathsBySlot: Readonly<Record<string, string>>;+}/*** Resolves the instrumentation layout for one agent root.*- * With providers on, an empty directory layout still installs eve's built-in- * destinations. Throws when the layout on disk is not the one the flag selects:- * the wrong layout would otherwise be skipped silently, and telemetry that- * quietly does nothing is the failure this whole surface exists to prevent.+ * An empty directory layout still installs eve's built-in destinations.+ * The removed single-file layout is rejected with a migration-oriented error.*/export function resolveInstrumentationLayout(input: {readonly agentRoot: string;- readonly providersEnabled: boolean;-}): InstrumentationLayout | undefined {+}): InstrumentationLayout {const filePath = resolveInstrumentationFile(input.agentRoot);const directoryPath = join(input.agentRoot, INSTRUMENTATION_DIRECTORY);const hasDirectory = existsSync(directoryPath) && statSync(directoryPath).isDirectory();- if (!input.providersEnabled) {- if (hasDirectory) {- log.warn("ignoring instrumentation provider directory because providers are off", {- agentRoot: input.agentRoot,- flag: PROVIDERS_FLAG,- });- }-- return filePath === undefined ? undefined : { kind: "file", modulePath: filePath };- }-if (filePath !== undefined) {throw new Error(- `Found "${filePath}", but \`${PROVIDERS_FLAG}\` is on. Move it into the "${INSTRUMENTATION_DIRECTORY}/" directory as one file per provider.`,+ `Found removed instrumentation file "${filePath}". Move it into the "${INSTRUMENTATION_DIRECTORY}/" directory as one file per provider. See the instrumentation migration guide.`,);}@@ -104,8 +78,7 @@ function collectInstrumentationProviderModules(}/**- * Resolves the single `agent/instrumentation` module, ignoring any directory of- * the same name.+ * Resolves the removed single `agent/instrumentation` module.*/function resolveInstrumentationFile(agentRoot: string): string | undefined {for (const extension of INSTRUMENTATION_EXTENSIONS) {diff --git a/packages/eve/src/internal/materialized-authored-modules.ts b/packages/eve/src/internal/materialized-authored-modules.tsindex 1987bbee1..df4b1673e 100644--- a/packages/eve/src/internal/materialized-authored-modules.ts+++ b/packages/eve/src/internal/materialized-authored-modules.ts@@ -15,9 +15,10 @@ const MATERIALIZED_MODULES_INDEX = "authored-modules.json";* The materialized instrumentation modules, mirroring the layout they were* authored in. Paths are relative to `.eve/compile`.*/-export type MaterializedInstrumentation =- | { readonly kind: "file"; readonly modulePath: string }- | { readonly kind: "directory"; readonly modulePathsBySlot: Readonly<Record<string, string>> };+export interface MaterializedInstrumentation {+ readonly kind: "directory";+ readonly modulePathsBySlot: Readonly<Record<string, string>>;+}export interface MaterializedAuthoredModuleIndex {readonly fingerprint: string;@@ -70,15 +71,11 @@ export async function writeMaterializedAuthoredModules(input: {return join(MATERIALIZED_MODULES_DIRECTORY, fileName);};- let instrumentation: MaterializedInstrumentation | undefined;-- 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);- }- instrumentation = { kind: "directory", modulePathsBySlot };+ const modulePathsBySlot: Record<string, string> = {};+ for (const [slot, code] of Object.entries(input.prepared.instrumentation.moduleCodeBySlot)) {+ modulePathsBySlot[slot] = await materializeInstrumentationModule(slot, code);}+ const instrumentation: MaterializedInstrumentation = { kind: "directory", modulePathsBySlot };await hashDirectoryIfPresent({fingerprint,@@ -95,9 +92,7 @@ export async function writeMaterializedAuthoredModules(input: {moduleMap: moduleMapPath,version: 3,};- if (instrumentation !== undefined) {- index.instrumentation = instrumentation;- }+ index.instrumentation = instrumentation;await writeFile(join(compileRoot, MATERIALIZED_MODULES_INDEX), `${JSON.stringify(index)}\n`);return index;}@@ -132,9 +127,6 @@ function isMaterializedInstrumentation(value: unknown): boolean {if (typeof value !== "object" || value === null) return false;const candidate = value as Partial<MaterializedInstrumentation>;- if (candidate.kind === "file") {- return typeof (candidate as { modulePath?: unknown }).modulePath === "string";- }if (candidate.kind === "directory") {const paths = (candidate as { modulePathsBySlot?: unknown }).modulePathsBySlot;return (diff --git a/packages/eve/src/internal/nitro/dev-generation-artifacts.scenario.test.ts b/packages/eve/src/internal/nitro/dev-generation-artifacts.scenario.test.tsindex ad14eb905..516625adc 100644--- a/packages/eve/src/internal/nitro/dev-generation-artifacts.scenario.test.ts+++ b/packages/eve/src/internal/nitro/dev-generation-artifacts.scenario.test.ts@@ -479,7 +479,16 @@ describe("development generation artifacts", () => {const app = await scenarioApp({files: {"agent/agent.mjs": 'export default { model: "openai/gpt-5.4" };\n',- "agent/instrumentation.mjs": 'export default { marker: "one" };\n',+ "agent/instrumentation/audit.mjs": [+ 'import { defineInstrumentation } from "eve/instrumentation";',+ 'const marker = "one";',+ "export default defineInstrumentation({",+ " setup() {",+ " globalThis.__EVE_PROVIDER_FINGERPRINT__ = marker;",+ " },",+ "});",+ "",+ ].join("\n"),"agent/instructions.md": "Use the configured model.","agent/skills/guide.md": ["---",@@ -501,7 +510,10 @@ describe("development generation artifacts", () => {"utf8",),) as { readonly instrumentation?: MaterializedInstrumentation; readonly moduleMap: string };- expect(firstIndex.instrumentation).toBeUndefined();+ expect(firstIndex.instrumentation).toMatchObject({+ kind: "directory",+ modulePathsBySlot: { audit: expect.any(String) },+ });const materializedModuleMap = await readFile(join(first.runtimeAppRoot, ".eve", "compile", firstIndex.moduleMap),"utf8",@@ -526,16 +538,22 @@ describe("development generation artifacts", () => {expect(restoredInstructions.fingerprint).toBe(first.fingerprint);await writeFile(- join(app.appRoot, "agent", "instrumentation.mjs"),- 'export default { marker: "two" };\n',+ join(app.appRoot, "agent", "instrumentation", "audit.mjs"),+ [+ 'import { defineInstrumentation } from "eve/instrumentation";',+ 'const marker = "two";',+ "export default defineInstrumentation({",+ " setup() {",+ " globalThis.__EVE_PROVIDER_FINGERPRINT__ = marker;",+ " },",+ "});",+ "",+ ].join("\n"),);const changedCompile = await compileAgent({ startPath: app.appRoot });const changed = await stageDevelopmentGeneration(changedCompile);expect(changed.fingerprint).not.toBe(first.fingerprint);- expect(changedCompile.manifest.instrumentation).toMatchObject({- logicalPath: "instrumentation.mjs",- });await writeFile(join(app.appRoot, "agent", "skills", "guide.md"),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.tsindex ae933450c..c720094b4 100644--- 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.ts@@ -38,11 +38,6 @@ describe("authored runtime artifacts", () => {"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";',@@ -72,7 +67,6 @@ describe("authored runtime artifacts", () => {(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,@@ -105,20 +99,6 @@ describe("authored runtime artifacts", () => {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",@@ -144,13 +124,7 @@ describe("authored runtime artifacts", () => {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/agent.ts": ["export default {", ' model: "openai/gpt-5.4",', "};", ""].join("\n"),"agent/instrumentation/otel.ts": ['import marker from "../../assets/provider.txt?raw";',"export default { marker };",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.tsindex ade10565c..1f79b1e56 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@@ -270,13 +270,16 @@ describe("application Nitro creation", () => {);});- it("preserves authored instrumentation instead of installing local tracing", async () => {+ it("lets authored instrumentation own default local tracing", async () => {const nitroStub = createNitroStub();createNitroMock.mockResolvedValueOnce(nitroStub.nitro);const { createDevelopmentApplicationNitro } =await import("#internal/nitro/host/create-application-nitro.js");const preparedHost = await createPreparedHost();- preparedHost.compiledArtifacts.instrumentationLayout = { kind: "file" };+ preparedHost.compiledArtifacts.instrumentationLayout = {+ kind: "directory",+ slots: ["audit"],+ };preparedHost.compiledArtifacts.instrumentationPluginPath = "/app/instrumentation.mjs";await createDevelopmentApplicationNitro(preparedHost);diff --git a/packages/eve/src/internal/nitro/host/create-application-nitro.ts b/packages/eve/src/internal/nitro/host/create-application-nitro.tsindex 9cbe0c53b..c2e4e666e 100644--- a/packages/eve/src/internal/nitro/host/create-application-nitro.ts+++ b/packages/eve/src/internal/nitro/host/create-application-nitro.ts@@ -57,6 +57,10 @@ const WORKFLOW_ALIAS_SPECIFIERS = ["workflow/internal/private","workflow/runtime",] as const;+const INSTRUMENTATION_ALIAS_PATHS = {+ "eve/instrumentation": "src/public/instrumentation/index.ts",+ "eve/instrumentation/otel": "src/public/instrumentation/otel.ts",+} as const;const WORKFLOW_TRANSFORM_PATCHED = Symbol("eve.workflow-transform-patched");const WORKFLOW_CACHE_PATH_FRAGMENT = "/.eve/workflow-cache/";@@ -637,6 +641,9 @@ function configureSharedApplicationNitro(for (const [specifier, resolvedPath] of Object.entries(workflowAliases)) {nitro.options.alias[specifier] = resolvedPath;}+ for (const [specifier, sourcePath] of Object.entries(INSTRUMENTATION_ALIAS_PATHS)) {+ nitro.options.alias[specifier] = resolvePackageSourceFilePath(sourcePath);+ }addWorkflowModuleSideEffectsPlugin(nitro, preparedHost.workflowBuildDir);patchWorkflowTransformExcludePath(nitro, preparedHost.workflowBuildDir);diff --git a/packages/eve/src/internal/nitro/host/dev-host-fingerprint.integration.test.ts b/packages/eve/src/internal/nitro/host/dev-host-fingerprint.integration.test.tsindex 6e66d3bbf..f7cede26f 100644--- a/packages/eve/src/internal/nitro/host/dev-host-fingerprint.integration.test.ts+++ b/packages/eve/src/internal/nitro/host/dev-host-fingerprint.integration.test.ts@@ -124,10 +124,10 @@ async function createHost(variant: HostVariant = {}): Promise<PreparedDevelopmen...(instrumentationSourcePath === undefined? {}: {- instrumentationLayout:- variant.instrumentationSlot === undefined- ? ({ kind: "file" } as const)- : ({ kind: "directory", slots: [variant.instrumentationSlot] } as const),+ instrumentationLayout: {+ kind: "directory",+ slots: [variant.instrumentationSlot ?? "provider"],+ } as const,instrumentationSourcePaths: [instrumentationSourcePath],}),workflowWorldPluginPath: join(appRoot, "workflow-world.mjs"),diff --git a/packages/eve/src/internal/nitro/host/dev-host-fingerprint.ts b/packages/eve/src/internal/nitro/host/dev-host-fingerprint.tsindex f121d2cae..029b27f05 100644--- a/packages/eve/src/internal/nitro/host/dev-host-fingerprint.ts+++ b/packages/eve/src/internal/nitro/host/dev-host-fingerprint.ts@@ -2,8 +2,6 @@ import { createHash } from "node:crypto";import { readFile } from "node:fs/promises";import { readDevelopmentEnvironmentHostValues } from "#cli/dev/environment.js";-import { resolveCompiledModuleExtensionScopeNamespace } from "#compiler/module-map.js";-import { bundleAuthoredModuleForGeneration } from "#internal/authored-module-loader.js";import { computeChannelRouteRegistrations } from "#internal/nitro/host/channel-routes.js";import type { PreparedDevelopmentApplicationHost } from "#internal/nitro/host/types.js";@@ -58,27 +56,9 @@ export async function computeDevelopmentHostFingerprint(}async function readInstrumentationSource(host: PreparedDevelopmentApplicationHost): Promise<{- readonly kind: "directory" | "file";- readonly modules: readonly { readonly slot: string | null; readonly source: string }[];+ readonly kind: "directory";+ readonly modules: readonly { readonly slot: string; readonly source: string }[];} | null> {- const instrumentation = host.compileResult.manifest.instrumentation;- if (instrumentation !== undefined) {- const binding = host.compileResult.manifest.bindings[instrumentation.sourceId];- if (binding === undefined) {- throw new Error(- `Compiled instrumentation source "${instrumentation.sourceId}" has no binding.`,- );- }- const source =- binding.backing.kind === "filesystem"- ? await bundleAuthoredModuleForGeneration(binding.backing.sourcePath, {- externalDependencies: binding.backing.externalDependencies,- extensionScopeNamespace: resolveCompiledModuleExtensionScopeNamespace(binding),- })- : JSON.stringify(binding.backing);- return { kind: "file", modules: [{ slot: null, source }] };- }-const paths = host.compiledArtifacts.instrumentationSourcePaths;const layout = host.compiledArtifacts.instrumentationLayout;if (paths === undefined || layout === undefined) {@@ -88,7 +68,7 @@ async function readInstrumentationSource(host: PreparedDevelopmentApplicationHosreturn {kind: layout.kind,modules: sources.map((source, index) => ({- slot: layout.kind === "directory" ? (layout.slots[index] ?? null) : null,+ slot: layout.slots[index]!,source,})),};diff --git a/packages/eve/src/internal/nitro/host/prepare-application-host.scenario.test.ts b/packages/eve/src/internal/nitro/host/prepare-application-host.scenario.test.tsindex e36d53b59..0654328d8 100644--- a/packages/eve/src/internal/nitro/host/prepare-application-host.scenario.test.ts+++ b/packages/eve/src/internal/nitro/host/prepare-application-host.scenario.test.ts@@ -1,5 +1,5 @@import { existsSync } from "node:fs";-import { readFile, rm, writeFile } from "node:fs/promises";+import { mkdir, readFile, rm, writeFile } from "node:fs/promises";import { join } from "node:path";import { afterEach, describe, expect, it, vi } from "vitest";@@ -85,8 +85,9 @@ describe("application host preparation", () => {packageName: "stable-dev-host-artifacts",});const agentModulePath = join(agentRoot, "agent.mjs");- const instrumentationModulePath = join(agentRoot, "instrumentation.mjs");+ const instrumentationModulePath = join(agentRoot, "instrumentation", "audit.mjs");await writeFile(agentModulePath, 'export default { model: "openai/gpt-5.4" };\n');+ await mkdir(join(agentRoot, "instrumentation"), { recursive: true });await writeFile(instrumentationModulePath, "export default {};\n");const firstHost = await prepareDevelopmentApplicationHost(appRoot);@@ -109,7 +110,7 @@ describe("application host preparation", () => {);expect(firstHost.compiledArtifacts.bootstrapPath).not.toContain("/.eve/dev-runtime/snapshots/");expect(firstHost.compiledArtifacts.instrumentationSourcePaths).toEqual([- join(firstHostDirectory, "compiled-artifacts-instrumentation-source.mjs"),+ join(firstHostDirectory, "compiled-artifacts-instrumentation-audit.mjs"),]);expect(await readFile(firstBootstrapPath, "utf8")).not.toContain(normalizeEsmImportSpecifier(agentModulePath),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 3476e9018..74600ef96 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@@ -3,7 +3,6 @@ import { describe, expect, it } from "vitest";import { compileFromMemory } from "#compiler/compile-from-memory.js";import { AgentInfoResultSchema } from "#client/agent-info-schema.js";import { buildAgentInfoResponse } from "#internal/nitro/routes/agent-info/build-agent-info-response.js";-import { defineInstrumentation } from "#public/instrumentation/index.js";import { webSearch } from "#tools/provided/web-search.js";import { defineMemory } from "#public/memory/index.js";@@ -131,31 +130,6 @@ describe("buildAgentInfoResponse", () => {);});- it("reports selected instrumentation provenance from the compiled graph", async () => {- const { manifest } = await compileFromMemory({- model: "openai/gpt-5.4",- modules: [- {- loadNamespace: async () => ({ default: defineInstrumentation({}) }),- logicalPath: "instrumentation.ts",- },- ],- });- const response = buildAgentInfoResponse(- { manifest, schedules: [] },- {- gatewayCredentials: { apiKey: false, oidc: false },- mode: "production",- },- );-- expect(response.instrumentation).toMatchObject({- binding: { backing: { kind: "programmatic" } },- logicalPath: "instrumentation.ts",- owner: { kind: "application" },- });- });-it("reports an authored webSearch sentinel as a prepared provider effect", async () => {const { manifest } = await compileFromMemory({model: "openai/gpt-5.4",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 71baf70d5..532e28124 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@@ -127,10 +127,6 @@ export function buildAgentInfoResponse(role: definition.role,})),},- instrumentation:- manifest.instrumentation === undefined- ? undefined- : toModuleSource(manifest, manifest.instrumentation),kernelEffects: projectPreparedKernelEffects(manifest),kind: "eve-agent-info",memories: manifest.memories.map((memory) => ({diff --git a/packages/eve/src/internal/nitro/routes/channel-dispatch.test.ts b/packages/eve/src/internal/nitro/routes/channel-dispatch.test.tsindex 29558098e..3935ea130 100644--- a/packages/eve/src/internal/nitro/routes/channel-dispatch.test.ts+++ b/packages/eve/src/internal/nitro/routes/channel-dispatch.test.ts@@ -24,8 +24,8 @@ import {setChannelInstrumentationKind,} from "#channel/compiled-channel.js";import type { RouteHandlerArgs } from "#channel/routes.js";-import { registerInstrumentationConfig } from "#instrumentation/config.js";-import { getInstrumentationRuntime } from "#instrumentation/runtime.js";+import { createInstrumentationHooks } from "#instrumentation/lifecycle.js";+import { registerInstrumentationRuntime } from "#instrumentation/runtime.js";import type { Runtime } from "#channel/types.js";import { readVercelProjectLink } from "#internal/vercel/project-link.js";import { DEVELOPMENT_WORKFLOW_SECRET_ENV } from "#internal/workflow/development-world-protocol.js";@@ -91,6 +91,21 @@ function createDeferred<T>() {};}+function registerChannelRequestTracing(enabled: boolean): void {+ registerInstrumentationRuntime({+ forceFlush: async () => undefined,+ hooks: createInstrumentationHooks([]),+ otelSettings: {+ functionId: undefined,+ recordInputs: false,+ recordOutputs: false,+ traceChannelRequests: enabled,+ },+ runInContext: (_operation, execute) => execute(),+ shutdown: async () => undefined,+ });+}+function createEvent(input?: {readonly body?: string;readonly headers?: Record<string, string>;@@ -826,11 +841,11 @@ describe("dispatchChannelRequest tracing", () => {apiPropagation.setGlobalPropagator(w3cPropagator as never);apiTrace.setGlobalTracerProvider(provider);// Request spans are opt-in; enable them for this suite.- registerInstrumentationConfig({ traceChannelRequests: true }, { agentName: "test" });+ registerChannelRequestTracing(true);});afterEach(() => {- registerInstrumentationConfig({}, { agentName: "test" });+ registerChannelRequestTracing(false);apiTrace.disable();apiContext.disable();apiPropagation.disable();@@ -841,34 +856,23 @@ describe("dispatchChannelRequest tracing", () => {return exporter.getFinishedSpans();}- it("uses the semantic request name for the experimental provider layout", async () => {- const instrumentationRuntime = getInstrumentationRuntime();- if (instrumentationRuntime === undefined)- throw new Error("Expected an instrumentation runtime.");- Object.defineProperty(instrumentationRuntime, "instrumentationProviders", {- configurable: true,- value: true,+ it("uses the semantic request name", async () => {+ mockedResolveNitroChannelRuntimeBundle.mockResolvedValue({+ agentName: "test-agent",+ channels: [slackChannel(async () => new Response("ok"))],+ runtime,});- try {- mockedResolveNitroChannelRuntimeBundle.mockResolvedValue({- agentName: "test-agent",- channels: [slackChannel(async () => new Response("ok"))],- runtime,- });-- await dispatchChannelRequest(createEvent({ waitUntil: vi.fn() }), "POST /slack", {} as never);-- const [span] = await finishedSpans();- expect(span!.name).toBe("agent.channel.request");- expect(span!.attributes["http.route"]).toBe("/slack");- expect(span!.attributes["operation.name"]).toBe("agent.channel.request");- expect(span!.attributes["resource.name"]).toBe("agent.channel.request");- } finally {- Reflect.deleteProperty(instrumentationRuntime, "instrumentationProviders");- }++ await dispatchChannelRequest(createEvent({ waitUntil: vi.fn() }), "POST /slack", {} as never);++ const [span] = await finishedSpans();+ expect(span!.name).toBe("agent.channel.request");+ expect(span!.attributes["http.route"]).toBe("/slack");+ expect(span!.attributes["operation.name"]).toBe("agent.channel.request");+ expect(span!.attributes["resource.name"]).toBe("agent.channel.request");});- it("emits one SERVER span named for the route with method, channel, and status attributes", async () => {+ it("emits one semantic SERVER span with route, method, channel, and status attributes", async () => {let agentContextDuringHandler = false;let spansDuringHandler = -1;mockedResolveNitroChannelRuntimeBundle.mockResolvedValue({@@ -900,7 +904,7 @@ describe("dispatchChannelRequest tracing", () => {const spans = await finishedSpans();expect(spans).toHaveLength(1);const [span] = spans;- expect(span!.name).toBe("POST /slack");+ expect(span!.name).toBe("agent.channel.request");expect(span!.kind).toBe(1 /* SpanKind.SERVER */);expect(span!.attributes).toMatchObject({"eve.channel.kind": "channel:slack",@@ -958,7 +962,7 @@ describe("dispatchChannelRequest tracing", () => {await dispatchChannelRequest(createEvent({ waitUntil: vi.fn() }), "POST /slack", {} as never);const spans = await finishedSpans();- const server = spans.find((span) => span.name === "POST /slack");+ const server = spans.find((span) => span.name === "agent.channel.request");const nested = spans.find((span) => span.name === "hook.resume");expect(server).toBeDefined();expect(nested).toBeDefined();@@ -1062,7 +1066,7 @@ describe("dispatchChannelRequest tracing", () => {).rejects.toThrow("bundle boom");const [span] = await finishedSpans();- expect(span!.name).toBe("POST /slack");+ expect(span!.name).toBe("agent.channel.request");expect(span!.status.code).toBe(2 /* SpanStatusCode.ERROR */);expect(span!.events.filter((event) => event.name === "exception")).toHaveLength(0);expect(span!.status.message).toBeUndefined();@@ -1086,7 +1090,7 @@ describe("dispatchChannelRequest tracing", () => {expect(response.status).toBe(404);const [span] = await finishedSpans();- expect(span!.name).toBe("POST /missing");+ expect(span!.name).toBe("agent.channel.request");expect(span!.attributes["http.response.status_code"]).toBe(404);expect(span!.attributes["http.route"]).toBe("/missing");expect(span!.attributes["eve.channel.name"]).toBeUndefined();@@ -1125,7 +1129,7 @@ describe("dispatchChannelRequest tracing", () => {await dispatchChannelRequest(event, "POST /eve/v1/session/:sessionId", {} as never);const [span] = await finishedSpans();- expect(span!.name).toBe("POST /eve/v1/session/:sessionId");+ expect(span!.name).toBe("agent.channel.request");const serialized = JSON.stringify({attributes: span!.attributes,events: span!.events,@@ -1151,11 +1155,11 @@ describe("dispatchChannelRequest without an OTel provider", () => {apiTrace.disable();apiContext.disable();apiPropagation.disable();- registerInstrumentationConfig({ traceChannelRequests: true }, { agentName: "test" });+ registerChannelRequestTracing(true);});afterEach(() => {- registerInstrumentationConfig({}, { agentName: "test" });+ registerChannelRequestTracing(false);apiTrace.disable();});@@ -1192,11 +1196,11 @@ describe("dispatchChannelRequest with request tracing not enabled", () => {apiContext.setGlobalContextManager(new AsyncLocalStorageContextManager().enable());apiPropagation.setGlobalPropagator(w3cPropagator as never);apiTrace.setGlobalTracerProvider(provider);- registerInstrumentationConfig({}, { agentName: "test" });+ registerChannelRequestTracing(false);});afterEach(() => {- registerInstrumentationConfig({}, { agentName: "test" });+ registerChannelRequestTracing(false);apiTrace.disable();apiContext.disable();apiPropagation.disable();@@ -1247,12 +1251,12 @@ describe("dispatchChannelRequest with request tracing not enabled", () => {});it("emits no request span by default when the flag is unset", async () => {- registerInstrumentationConfig({}, { agentName: "test" });+ registerChannelRequestTracing(false);await expectNoSpan();});it("emits no request span when the flag is explicitly false", async () => {- registerInstrumentationConfig({ traceChannelRequests: false }, { agentName: "test" });+ registerChannelRequestTracing(false);await expectNoSpan();});});diff --git a/packages/eve/src/internal/nitro/routes/channel-request-instrumentation.ts b/packages/eve/src/internal/nitro/routes/channel-request-instrumentation.tsindex 3d10e025a..b4236dd54 100644--- a/packages/eve/src/internal/nitro/routes/channel-request-instrumentation.ts+++ b/packages/eve/src/internal/nitro/routes/channel-request-instrumentation.ts@@ -75,10 +75,7 @@ export async function traceChannelRequest<T extends Response>(const { request, routeKey } = input;const parentContext = propagation.extract(context.active(), request.headers, headersGetter);- const spanName =- getInstrumentationRuntime()?.instrumentationProviders === true- ? AGENT_SPAN_NAMES.channelRequest- : routeKey;+ const spanName = AGENT_SPAN_NAMES.channelRequest;const span = trace.getTracer(TRACER_NAME).startSpan(spanName,{diff --git a/packages/eve/src/public/definitions/exact.test.ts b/packages/eve/src/public/definitions/exact.test.tsindex 582075567..be61cc8cd 100644--- a/packages/eve/src/public/definitions/exact.test.ts+++ b/packages/eve/src/public/definitions/exact.test.ts@@ -291,45 +291,23 @@ function typeOnlyFixtures(): void {});defineInstrumentation({- isEnabled: true,+ // @ts-expect-error Content capture is configured through tracePolicy.recordInputs: true,});- // Unlike the helpers above, `defineInstrumentation` takes a generic union — a- // config and a provider overlap on `events` and `setup` — so it cannot use- // `ExactDefinition`. Excess keys reach `eve build` instead.- const instrumentationWithEnabled = {- isEnabled: true,- recordInputs: true,- };- defineInstrumentation(instrumentationWithEnabled);-- defineInstrumentation({- events: {- "step.started"(input) {- const sessionId: string = input.session.id;- return { runtimeContext: { "test.session_id": sessionId } };- },- },- });-const providerWithCapture: ProviderDefinition = { capture: "content" };void providerWithCapture;defineInstrumentation({- // @ts-expect-error Instrumentation event hooks are authored through `events`.- runtimeContext: {- "step.started"() {- return { runtimeContext: {} };- },- },+ // @ts-expect-error OpenTelemetry settings are configured with otel().+ functionId: "support",});defineInstrumentation({- // @ts-expect-error Instrumentation event hooks are authored through `events`.- metadata: {- "step.started"() {- return { runtimeContext: { "test.session_id": "test-session" } };+ events: {+ "turn.started"(event) {+ const sessionId: string = event.sessionId;+ void sessionId;},},});diff --git a/packages/eve/src/public/instrumentation/index.ts b/packages/eve/src/public/instrumentation/index.tsindex b8692999b..450209778 100644--- a/packages/eve/src/public/instrumentation/index.ts+++ b/packages/eve/src/public/instrumentation/index.ts@@ -1,17 +1,11 @@/**- * Instrumentation authoring helpers for `agent/instrumentation.ts` and, with- * `experimental.instrumentationProviders` on, `agent/instrumentation/`.+ * Instrumentation authoring helpers for `agent/instrumentation/`.*/import type { ModelMessage, SystemModelMessage } from "ai";import type { SessionAuthContext, SessionParent } from "#channel/types.js";import type { InstrumentationChannel } from "#public/channels/index.js";-import {- PROVIDER,- type ProviderDefinition,- type ProviderSetupContext,-} from "#public/instrumentation/provider.js";import type { JsonObject } from "#shared/json.js";export * from "#public/instrumentation/provider.js";@@ -27,16 +21,6 @@ export {type InstrumentationChannelMetadata,} from "#public/channels/index.js";-/**- * Context passed to the {@link InstrumentationDefinition.setup} callback.- *- * The same context both layouts receive. Keeping one type is what gives- * {@link defineInstrumentation}'s union a contextual signature for `setup`;- * two divergent ones would leave every authored `setup(context)` parameter an- * implicit `any`.- */-export interface InstrumentationSetupContext extends ProviderSetupContext {}-/*** User-authored runtime context values attached to AI SDK telemetry spans.*@@ -92,9 +76,9 @@ export interface InstrumentationModelInput {}/**- * Input passed to `events["step.started"]` and to a provider's- * `runtimeContext` resolver. eve builds it after assembling the final model- * input for this attempt and before constructing the AI SDK model call.+ * Input passed to a provider's `runtimeContext` resolver. eve builds it after+ * assembling the final model input for this attempt and before constructing+ * the AI SDK model call.*/export interface InstrumentationStepStartedEventInput {readonly channel: InstrumentationChannel;@@ -110,104 +94,3 @@ export interface InstrumentationStepStartedEventInput {* step, and turn coordinates.*/export type InstrumentationRuntimeContextInput = InstrumentationStepStartedEventInput;--/**- * Result of a `step.started` callback. eve merges `runtimeContext` into the- * AI SDK telemetry span; child spans inherit the values. Keys beginning with- * `eve.` and non-JSON-serializable values are dropped. Return `undefined` to- * contribute no context.- */-export interface InstrumentationStepStartedEventResult {- /**- * Additional runtime context merged into AI SDK telemetry spans.- */- readonly runtimeContext: InstrumentationRuntimeContext;-}--/**- * Event hooks accepted by {@link defineInstrumentation}.- */-export interface InstrumentationEvents {- /**- * Resolve per-attempt runtime context before the model call. The AI SDK- * child spans inherit the returned values.- */- readonly "step.started"?: (- input: InstrumentationStepStartedEventInput,- ) => InstrumentationStepStartedEventResult | undefined;-}--/**- * Authored instrumentation settings accepted by `defineInstrumentation`.- *- * The presence of a `defineInstrumentation` export implicitly enables- * telemetry. There is no separate `isEnabled` toggle.- */-export interface InstrumentationDefinition {- /**- * Override the function identifier attached to telemetry spans- * (`ai.telemetry.functionId`). Defaults to the agent name; omitted when- * neither is set.- */- readonly functionId?: string;- /**- * Instrumentation event hooks.- */- readonly events?: InstrumentationEvents;- /**- * Whether to record full model inputs in telemetry spans. Defaults to- * `false`. Set `true` only when the destination is approved to receive- * input content.- */- readonly recordInputs?: boolean;- /**- * Whether to record full model outputs in telemetry spans. Defaults to- * `false`. Set `true` only when the destination is approved to receive- * output content.- */- readonly recordOutputs?: boolean;- /**- * Whether to emit an eve-owned HTTP `SERVER` span around each channel- * request. In the authored hierarchy, this span parents the turn trace. In- * the provider layout, a one-to-one activation remains a separate trace- * root and links to this span; when disabled, it links to any already-active- * upstream request or function span instead. Defaults to `false`.- */- readonly traceChannelRequests?: boolean;- /**- * Setup callback invoked at server startup, before the first request. Use it- * to call `registerOTel` or other OTel provider setup; `context.agentName`- * comes from `defineAgent`. A returned promise is awaited.- */- readonly setup?: (context: InstrumentationSetupContext) => void | PromiseLike<void>;-}--/**- * Declares instrumentation, in either of eve's two layouts.- *- * Export the result as the default export of `agent/instrumentation.ts`, or —- * with `experimental.instrumentationProviders` on — of one file under- * `agent/instrumentation/`. The layout decides how eve reads the value; the two- * are mutually exclusive builds, so only one can apply. `setup` runs at server- * startup, not during this call.- *- * The parameter is a union because a provider and a legacy config overlap on- * `events` and `setup`, so no value-level check separates them. One consequence- * is that excess-property checking is weaker here than it was against the- * config shape alone, and a misspelled key can reach `eve build` rather than- * failing at `tsc`.- */-export function defineInstrumentation<- const TDefinition extends InstrumentationDefinition | ProviderDefinition,->(definition: TDefinition): InstrumentationDeclaration<TDefinition> {- return { ...definition, [PROVIDER]: true };-}--/** The branded result of {@link defineInstrumentation}. */-export type InstrumentationDeclaration<- TDefinition extends InstrumentationDefinition | ProviderDefinition =- | InstrumentationDefinition- | ProviderDefinition,-> = TDefinition & {- readonly [PROVIDER]: true;-};diff --git a/packages/eve/src/public/instrumentation/otel.ts b/packages/eve/src/public/instrumentation/otel.tsindex e3d08f623..701d9246e 100644--- a/packages/eve/src/public/instrumentation/otel.ts+++ b/packages/eve/src/public/instrumentation/otel.ts@@ -5,8 +5,7 @@* can only hold one of, and an integration is a destination, of which there may* be as many as there are files.*- * Reachable only with `experimental.instrumentationProviders` on. With the flag- * off nothing discovers that directory, so these compile but never run.+ * Each destination is declared in its own path-named provider file.*/import {diff --git a/packages/eve/src/public/instrumentation/provider.test.ts b/packages/eve/src/public/instrumentation/provider.test.tsindex 771dd9c20..a2e296b76 100644--- a/packages/eve/src/public/instrumentation/provider.test.ts+++ b/packages/eve/src/public/instrumentation/provider.test.ts@@ -11,16 +11,9 @@ import {type InstrumentationMemoryOperationStartedEvent,type InstrumentationMemoryOperationTerminalEvent,type InstrumentationMemoryRecord,- type InstrumentationSetupContext,} from "#public/instrumentation/index.js";describe("defineInstrumentation", () => {- it("keeps the legacy setup context constructible with only the agent name", () => {- const context: InstrumentationSetupContext = { agentName: "weather" };-- expect(context).toEqual({ agentName: "weather" });- });-it("brands a provider-shaped declaration", () => {const provider = defineInstrumentation({events: {@@ -44,14 +37,6 @@ describe("defineInstrumentation", () => {expect(provider.tracePolicy).toBe(tracePolicy);});- it("brands a legacy config-shaped declaration", () => {- const config = defineInstrumentation({ functionId: "support", recordInputs: false });-- expect(isInstrumentationProvider(config)).toBe(true);- expect(config.functionId).toBe("support");- expect(config).toMatchObject({ functionId: "support", recordInputs: false });- });-it("infers terminal handler events from union-typed discriminants", () => {const provider = defineInstrumentation({events: {diff --git a/packages/eve/src/runtime/resolve-agent.ts b/packages/eve/src/runtime/resolve-agent.tsindex ca97420a8..147b32db5 100644--- a/packages/eve/src/runtime/resolve-agent.ts+++ b/packages/eve/src/runtime/resolve-agent.ts@@ -242,7 +242,6 @@ function createResolvedAgentConfig(if (manifest.config.experimental !== undefined) {config.experimental = {- instrumentationProviders: manifest.config.experimental.instrumentationProviders,workflow:manifest.config.experimental.workflow === undefined? undefineddiff --git a/packages/eve/src/self-modification/search-registry.test.ts b/packages/eve/src/self-modification/search-registry.test.tsindex 180bec4bc..a8c2d8872 100644--- a/packages/eve/src/self-modification/search-registry.test.ts+++ b/packages/eve/src/self-modification/search-registry.test.ts@@ -52,7 +52,10 @@ const INDEX = {},},},- { name: "instrumentation/langfuse-tracing", files: [{ target: "agent/instrumentation.ts" }] },+ {+ name: "instrumentation/langfuse-tracing",+ files: [{ target: "agent/instrumentation/langfuse-tracing.ts" }],+ },{ name: 42 },],};diff --git a/packages/eve/src/shared/agent-definition.ts b/packages/eve/src/shared/agent-definition.tsindex bd45c72b4..491d69ce0 100644--- a/packages/eve/src/shared/agent-definition.ts+++ b/packages/eve/src/shared/agent-definition.ts@@ -207,15 +207,6 @@ export interface AgentLimitsDefinition {* These options are unstable and may change or be removed in any release.*/export interface AgentExperimentalDefinition {- /**- * Reads instrumentation from an `instrumentation/` directory of providers- * rather than a single `agent/instrumentation.ts` config object.- *- * The two layouts are mutually exclusive: with this on, an- * `agent/instrumentation.ts` is a build error, and with it off, an- * `instrumentation/` directory is.- */- readonly instrumentationProviders?: boolean;/*** Runs this agent's delegated subagent calls as durable background tasks.* The originating tool call returns a task receipt immediately and thediff --git a/packages/eve/src/tracing/install-instrumentation-runtime.test.ts b/packages/eve/src/tracing/install-instrumentation-runtime.test.tsindex 32cb08c3f..28ffbbdc7 100644--- a/packages/eve/src/tracing/install-instrumentation-runtime.test.ts+++ b/packages/eve/src/tracing/install-instrumentation-runtime.test.ts@@ -63,7 +63,6 @@ describe("installInstrumentationRuntime", () => {const runtime = installInstrumentationRuntime({collected: collectOtelPipeline([otelIntegration()]),frameworkVersion: "test",- instrumentationProviders: true,providers: [{ flush: providerFlush, name: "test", shutdown: providerShutdown }],serviceName: "weather",});@@ -74,7 +73,6 @@ describe("installInstrumentationRuntime", () => {expect(forceFlush).toHaveBeenCalledOnce();expect(providerFlush).toHaveBeenCalledOnce();- expect(runtime.instrumentationProviders).toBe(true);expect(runtime.memoryOperations).toBe(true);expect(runtime.ownsAgentSpans).toBe(true);expect(runtime.otelSettings).toEqual({diff --git a/packages/eve/src/tracing/install-instrumentation-runtime.ts b/packages/eve/src/tracing/install-instrumentation-runtime.tsindex cd33c6b34..764a9d714 100644--- a/packages/eve/src/tracing/install-instrumentation-runtime.ts+++ b/packages/eve/src/tracing/install-instrumentation-runtime.ts@@ -26,9 +26,8 @@ const log = createLogger("tracing.install-instrumentation-runtime");/*** Installs the process instrumentation runtime around a collected pipeline.*- * Both layouts land here. `eve dev`'s zero-config default and an authored- * `agent/instrumentation/` directory differ only in where the declared values- * came from, so sharing the install keeps them on one runtime path.+ * `eve dev`'s zero-config default and an authored `agent/instrumentation/`+ * directory differ only in where the declared values came from.** A directory that declared no OpenTelemetry still gets a bus: its providers* see every event, they just have no spans to hang them on.@@ -36,7 +35,6 @@ const log = createLogger("tracing.install-instrumentation-runtime");export function installInstrumentationRuntime(input: {readonly collected: CollectedOtel;readonly frameworkVersion: string;- readonly instrumentationProviders?: boolean;readonly providers: readonly InstrumentationProviderDefinition[];readonly runtimeContextResolvers?: readonly RuntimeContextResolver[];readonly serviceName: string;@@ -94,7 +92,6 @@ export function installInstrumentationRuntime(input: {serialBefore,}),idGenerator: otelRuntime?.idGenerator ?? new AgentSpanIdGenerator(),- instrumentationProviders: input.instrumentationProviders,memoryOperations: otelRuntime !== undefined || input.providers.some(hasMemoryOperationHandler),otelSettings: input.collected.declared ? input.collected.settings : undefined,ownsAgentSpans: otelRuntime !== undefined,diff --git a/packages/eve/src/tracing/otel-declaration.test.ts b/packages/eve/src/tracing/otel-declaration.test.tsindex 92872b506..e8c5b6096 100644--- a/packages/eve/src/tracing/otel-declaration.test.ts+++ b/packages/eve/src/tracing/otel-declaration.test.ts@@ -90,10 +90,10 @@ describe("agentRunsIntegration", () => {});});-describe("managed export policy", () => {+describe("destination export policy", () => {it("does not redact content unless the export pipeline requests it", () => {let visibleAttributes: Readonly<Record<string, unknown>> | undefined;- const integration = managedOtelIntegration({+ const integration = otelIntegration({exportPolicy: {span: ({ attributes }) => {visibleAttributes = attributes;@@ -117,7 +117,7 @@ describe("managed export policy", () => {it("runs export policy arrays in declaration order", () => {let visibleAttributes: Readonly<Record<string, unknown>> | undefined;- const integration = managedOtelIntegration({+ const integration = otelIntegration({exportPolicy: [{span: ({ audience }) =>diff --git a/packages/eve/src/tracing/otel-declaration.ts b/packages/eve/src/tracing/otel-declaration.tsindex 9e9c96879..03504e14f 100644--- a/packages/eve/src/tracing/otel-declaration.ts+++ b/packages/eve/src/tracing/otel-declaration.ts@@ -65,7 +65,7 @@ export interface OtelOptions {* settings can only narrow it. For a trusted remote trace, eve evaluates this* policy against the immutable origin audience and intersects it with the* parent's effective ceiling, so every hop can only narrow capture. It never- * changes what authored instrumentation providers receive. A thrown error rejects trace production without+ * changes what lifecycle instrumentation receives. A thrown error rejects trace production without* silencing lifecycle providers. The policy may be invoked more than once* while a new session is being prepared, so it must be deterministic for* consistent results.@@ -102,7 +102,7 @@ export interface ManagedTraceOptions {}/** Where one `otelIntegration()` sends spans and metrics. */-export interface OtelIntegrationOptions {+export interface OtelIntegrationOptions extends ManagedTraceOptions {/** Merged into the pipeline in declaration order. */readonly spanProcessors?: readonly SpanProcessor[];/** Wrapped in eve's batching processor and appended after `spanProcessors`. */@@ -173,16 +173,11 @@ export function otelIntegration(options: OtelIntegrationOptions = {}): OtelInteg}/** @internal Local and Agent Runs destination declaration. */-export function managedOtelIntegration(- options: OtelIntegrationOptions & ManagedTraceOptions = {},-): OtelIntegration {- return createOtelIntegration(options, options.exportPolicy);+export function managedOtelIntegration(options: OtelIntegrationOptions = {}): OtelIntegration {+ return createOtelIntegration(options);}-function createOtelIntegration(- options: OtelIntegrationOptions,- exportPolicy?: SpanExportPolicy | readonly SpanExportPolicy[],-): OtelIntegration {+function createOtelIntegration(options: OtelIntegrationOptions): OtelIntegration {assertNoRemovedContentOptions(options);const declared = options.spanProcessors ?? [];const spanProcessors =@@ -196,7 +191,7 @@ function createOtelIntegration(metricReaders: options.metricReaders ?? [],runtimeContext: options.runtimeContext,spanProcessors: spanProcessors.map((processor) =>- contentFilteringProcessor(processor, exportPolicy),+ contentFilteringProcessor(processor, options.exportPolicy),),};}@@ -250,8 +245,9 @@ export interface OtelHarnessSettings {readonly functionId?: string;readonly traceChannelRequests: boolean;readonly tracePolicy?: TraceCapturePolicy;- /** Legacy `defineInstrumentation()` capture settings. Provider destinations capture fully. */+ /** Whether AI SDK spans include model and tool inputs. */readonly recordInputs: boolean;+ /** Whether AI SDK spans include model and tool outputs. */readonly recordOutputs: boolean;}diff --git a/packages/eve/test/scenarios/app-runtime-dependencies.scenario.test.ts b/packages/eve/test/scenarios/app-runtime-dependencies.scenario.test.tsindex 4a619ef6a..a653e5449 100644--- a/packages/eve/test/scenarios/app-runtime-dependencies.scenario.test.ts+++ b/packages/eve/test/scenarios/app-runtime-dependencies.scenario.test.ts@@ -891,15 +891,19 @@ describe("app runtime dependency tracing", () => {["export default {", ' model: "openai/gpt-5.4-mini",', "};", ""].join("\n"),);await writeFile(join(appRoot, "agent", "instructions.md"), "Verify hosted instrumentation.\n");+ await mkdir(join(appRoot, "agent", "instrumentation"), { recursive: true });await writeFile(- join(appRoot, "agent", "instrumentation.ts"),+ join(appRoot, "agent", "instrumentation", "dependency.ts"),['import fixtureInstrumentationDep from "fixture-instrumentation-dep";',+ 'import { defineInstrumentation } from "eve/instrumentation";',"",- "(globalThis as Record<string, unknown>).__fixtureInstrumentationDep =",- " fixtureInstrumentationDep;",- "",- "export default fixtureInstrumentationDep;",+ "export default defineInstrumentation({",+ " setup() {",+ " (globalThis as Record<string, unknown>).__fixtureInstrumentationDep =",+ " fixtureInstrumentationDep;",+ " },",+ "});","",].join("\n"),);diff --git a/packages/eve/test/scenarios/bin-build-output.scenario.test.ts b/packages/eve/test/scenarios/bin-build-output.scenario.test.tsindex 8e3eed12b..0db694b85 100644--- a/packages/eve/test/scenarios/bin-build-output.scenario.test.ts+++ b/packages/eve/test/scenarios/bin-build-output.scenario.test.ts@@ -110,10 +110,60 @@ async function readDirectorySources(root: string): Promise<string> {}function decodeEmbeddedWorkflowCode(source: string): string {- const chunks = [...source.matchAll(/Buffer\.from\((\[[\s\S]*?\])\.join\(""\), "base64"\)/gu)].map(- (match) => JSON.parse(match[1]!) as string[],- );- return chunks.map((chunk) => Buffer.from(chunk.join(""), "base64").toString("utf8")).join("\n");+ const prefix = "Buffer.from(";+ const suffix = '.join(""), "base64")';+ const decoded: string[] = [];+ let offset = 0;++ while (true) {+ const expressionStart = source.indexOf(prefix, offset);+ if (expressionStart === -1) break;++ const arrayStart = expressionStart + prefix.length;+ const arrayEnd = findJsonArrayEnd(source, arrayStart);+ if (arrayEnd !== undefined && source.startsWith(suffix, arrayEnd + 1)) {+ const chunks = JSON.parse(source.slice(arrayStart, arrayEnd + 1)) as string[];+ decoded.push(Buffer.from(chunks.join(""), "base64").toString("utf8"));+ offset = arrayEnd + suffix.length + 1;+ continue;+ }++ offset = arrayStart;+ }++ return decoded.join("\n");+}++function findJsonArrayEnd(source: string, start: number): number | undefined {+ if (source[start] !== "[") return undefined;++ let depth = 0;+ let escaped = false;+ let inString = false;++ for (let index = start; index < source.length; index++) {+ const character = source[index];+ if (inString) {+ if (escaped) {+ escaped = false;+ } else if (character === "\\") {+ escaped = true;+ } else if (character === '"') {+ inString = false;+ }+ continue;+ }++ if (character === '"') {+ inString = true;+ } else if (character === "[") {+ depth++;+ } else if (character === "]" && --depth === 0) {+ return index;+ }+ }++ return undefined;}async function runEveBuild(appRoot: string): Promise<ProcessResult> {diff --git a/packages/eve/test/scenarios/compile-agent.scenario.test.ts b/packages/eve/test/scenarios/compile-agent.scenario.test.tsindex 92f7369b0..1dc353da7 100644--- a/packages/eve/test/scenarios/compile-agent.scenario.test.ts+++ b/packages/eve/test/scenarios/compile-agent.scenario.test.ts@@ -619,20 +619,19 @@ describe("compileAgent", () => {"",].join("\n"),"agent/instructions.md": "You are a precise assistant.\n",- "agent/instrumentation.ts": [- 'import { defineInstrumentation, isChannel } from "eve/instrumentation";',- 'import supportChannel from "./channels/support.js";',+ "agent/instrumentation/support.ts": [+ 'import { isChannel } from "eve/instrumentation";',+ 'import { otelIntegration } from "eve/instrumentation/otel";',+ 'import supportChannel from "../channels/support.js";',"",- "export default defineInstrumentation({",- " events: {",- ' "step.started"(input) {',+ "export default otelIntegration({",+ " runtimeContext(input) {"," if (!isChannel(input.channel, supportChannel)) return undefined;"," const queueId: string | null = input.channel.metadata.queueId;",' const priority: "high" = input.channel.metadata.priority;'," // @ts-expect-error channel metadata contains no arbitrary fallback keys."," input.channel.metadata.missing;",- ' return { runtimeContext: { "support.has_queue": String(queueId !== null), "support.priority": priority } };',- " },",+ ' return { "support.has_queue": String(queueId !== null), "support.priority": priority };'," },","});","",diff --git a/packages/eve/test/scenarios/compiled-artifacts-bootstrap.scenario.test.ts b/packages/eve/test/scenarios/compiled-artifacts-bootstrap.scenario.test.tsindex 90935ac02..34adc24f4 100644--- a/packages/eve/test/scenarios/compiled-artifacts-bootstrap.scenario.test.ts+++ b/packages/eve/test/scenarios/compiled-artifacts-bootstrap.scenario.test.ts@@ -80,11 +80,15 @@ describe("writeCompiledArtifactsFiles", () => {await writeFile(join(agentRoot, "agent.ts"), 'export default { model: "openai/gpt-5.4" };\n');await writeFile(join(agentRoot, "instructions.md"), "You are a precise assistant.\n");+ await mkdir(join(agentRoot, "instrumentation"), { recursive: true });await writeFile(- join(agentRoot, "instrumentation.ts"),- ['(globalThis as Record<string, unknown>).__eveInstrumentationLoaded = "yes";', ""].join(- "\n",- ),+ join(agentRoot, "instrumentation", "audit.ts"),+ [+ 'import { defineInstrumentation } from "eve/instrumentation";',+ '(globalThis as Record<string, unknown>).__eveInstrumentationLoaded = "yes";',+ "export default defineInstrumentation({});",+ "",+ ].join("\n"),);const compileResult = await compileAgent({@@ -108,15 +112,12 @@ describe("writeCompiledArtifactsFiles", () => {const instrumentationPluginSource = await readFile(instrumentationPluginPath, "utf8");expect(instrumentationPluginSource).toContain(- join(outDir, "compiled-artifacts-module-map.mjs").replaceAll("\\", "/"),- );- expect(instrumentationPluginSource).toContain(- `moduleMap.nodes["__root__"].modules["instrumentation.ts"]`,+ join(outDir, "compiled-artifacts-instrumentation-audit.mjs").replaceAll("\\", "/"),);expect(instrumentationPluginSource).not.toContain(- join(agentRoot, "instrumentation.ts").replaceAll("\\", "/"),+ join(agentRoot, "instrumentation", "audit.ts").replaceAll("\\", "/"),);- expect(instrumentationPluginSource).toContain("registerInstrumentationConfig");+ expect(instrumentationPluginSource).toContain("registerInstrumentationProvider");const instrumentationPluginModule = (await import(pathToFileURL(instrumentationPluginPath).href@@ -128,7 +129,7 @@ describe("writeCompiledArtifactsFiles", () => {expect(instrumentationPluginModule.default()).toBeUndefined();});- it("registers one provider per file when the instrumentationProviders flag is on", async () => {+ it("registers one provider per file", async () => {const { agentRoot, appRoot } = await createAppRoot("eve-compiled-artifacts-providers-", {packageName: "compiled-artifacts-providers-test-agent",});@@ -139,13 +140,7 @@ describe("writeCompiledArtifactsFiles", () => {await writeFile(join(agentRoot, "agent.ts"),- [- "export default {",- ' model: "openai/gpt-5.4",',- " experimental: { instrumentationProviders: true },",- "};",- "",- ].join("\n"),+ ["export default {", ' model: "openai/gpt-5.4",', "};", ""].join("\n"),);await writeFile(join(agentRoot, "instructions.md"), "You are a precise assistant.\n");await mkdir(join(agentRoot, "instrumentation"), { recursive: true });@@ -241,13 +236,7 @@ describe("writeCompiledArtifactsFiles", () => {const outDir = join(appRoot, ".workflow-build");await writeFile(join(agentRoot, "agent.ts"),- [- "export default {",- ' model: "openai/gpt-5.4",',- " experimental: { instrumentationProviders: true },",- "};",- "",- ].join("\n"),+ ["export default {", ' model: "openai/gpt-5.4",', "};", ""].join("\n"),);await writeFile(join(agentRoot, "instructions.md"), "You are a precise assistant.\n");@@ -277,8 +266,9 @@ describe("writeCompiledArtifactsFiles", () => {await writeFile(join(agentRoot, "agent.ts"), 'export default { model: "openai/gpt-5.4" };\n');await writeFile(join(agentRoot, "instructions.md"), "You are a precise assistant.\n");+ await mkdir(join(agentRoot, "instrumentation"), { recursive: true });await writeFile(- join(agentRoot, "instrumentation.ts"),+ join(agentRoot, "instrumentation", "broken.ts"),'throw new Error("instrumentation boom");\n',);diff --git a/packages/eve/test/scenarios/dev-server-connections.scenario.test.ts b/packages/eve/test/scenarios/dev-server-connections.scenario.test.tsindex 28be7c29e..2bbf044f8 100644--- a/packages/eve/test/scenarios/dev-server-connections.scenario.test.ts+++ b/packages/eve/test/scenarios/dev-server-connections.scenario.test.ts@@ -96,6 +96,7 @@ function createBlockedInstrumentationSource(): string {return ['import { existsSync, watch, writeFileSync } from "node:fs";','import { join } from "node:path";',+ 'import { defineInstrumentation } from "eve/instrumentation";',"","declare global {"," var __EVE_INSTRUMENTATION_MARKER__: string | undefined;",@@ -120,7 +121,7 @@ function createBlockedInstrumentationSource(): string {" }","});",'globalThis.__EVE_INSTRUMENTATION_MARKER__ = "two";',- "export default {};",+ "export default defineInstrumentation({});","",].join("\n");}@@ -204,7 +205,7 @@ describe("eve dev server live connections", () => {})();await writeFile(- join(app.appRoot, "agent", "instrumentation.ts"),+ join(app.appRoot, "agent", "instrumentation", "reload.ts"),createBlockedInstrumentationSource(),);const rebuild = forceDevelopmentRebuild(server.url);@@ -248,7 +249,7 @@ describe("eve dev server live connections", () => {expect(first.localPort).toBeDefined();await writeFile(- join(app.appRoot, "agent", "instrumentation.ts"),+ join(app.appRoot, "agent", "instrumentation", "reload.ts"),createInstrumentationSource("keep-alive-two"),);await forceDevelopmentRebuild(server.url, agent);diff --git a/packages/eve/test/scenarios/dev-server-descriptors.ts b/packages/eve/test/scenarios/dev-server-descriptors.tsindex c600718f0..3fee8df19 100644--- a/packages/eve/test/scenarios/dev-server-descriptors.ts+++ b/packages/eve/test/scenarios/dev-server-descriptors.ts@@ -34,18 +34,20 @@ export const TRANSACTIONAL_REBUILD_DESCRIPTOR: ScenarioAppDescriptor = {files: {...DEV_SERVER_AGENT_DESCRIPTOR.files,"agent/channels/dev-generation.ts": createTransactionalRouteSource(),- "agent/instrumentation.ts": createInstrumentationSource("one"),+ "agent/instrumentation/reload.ts": createInstrumentationSource("one"),},};export function createInstrumentationSource(marker: string): string {return [+ 'import { defineInstrumentation } from "eve/instrumentation";',+ "","declare global {"," var __EVE_INSTRUMENTATION_MARKER__: string | undefined;","}","",`globalThis.__EVE_INSTRUMENTATION_MARKER__ = ${JSON.stringify(marker)};`,- "export default {};",+ "export default defineInstrumentation({});","",].join("\n");}diff --git a/packages/eve/test/scenarios/dev-server-rebuild.scenario.test.ts b/packages/eve/test/scenarios/dev-server-rebuild.scenario.test.tsindex bb56a7655..3763ba1dd 100644--- a/packages/eve/test/scenarios/dev-server-rebuild.scenario.test.ts+++ b/packages/eve/test/scenarios/dev-server-rebuild.scenario.test.ts@@ -194,7 +194,7 @@ describe("eve dev server rebuild transactions", () => {await expect(fetchText(server.url, "/worker-id")).resolves.toBe(initialWorkerId);await writeFile(- join(app.appRoot, "agent", "instrumentation.ts"),+ join(app.appRoot, "agent", "instrumentation", "reload.ts"),createInstrumentationSource("two"),);await forceDevelopmentRebuild(server.url);@@ -227,8 +227,8 @@ describe("eve dev server rebuild transactions", () => {await expect(fetchText(server.url, "/instrumentation-marker")).resolves.toBe("one");await writeFile(- join(app.appRoot, "agent", "instrumentation.ts"),- 'throw new Error("stage 4 rejected candidate");\nexport default {};\n',+ join(app.appRoot, "agent", "instrumentation", "reload.ts"),+ 'throw new Error("stage 4 rejected candidate");\n',);await writeFile(join(app.appRoot, "agent", "channels", "dev-generation.ts"),@@ -249,7 +249,7 @@ describe("eve dev server rebuild transactions", () => {expect(candidateRoute.status).toBe(404);await writeFile(- join(app.appRoot, "agent", "instrumentation.ts"),+ join(app.appRoot, "agent", "instrumentation", "reload.ts"),createInstrumentationSource("two"),);await forceDevelopmentRebuild(server.url);@@ -262,7 +262,7 @@ describe("eve dev server rebuild transactions", () => {createTransactionalRouteSource(),);await writeFile(- join(app.appRoot, "agent", "instrumentation.ts"),+ join(app.appRoot, "agent", "instrumentation", "reload.ts"),createInstrumentationSource("one"),);await forceDevelopmentRebuild(server.url);diff --git a/packages/eve/test/scenarios/dev-server-workflow-generations.scenario.test.ts b/packages/eve/test/scenarios/dev-server-workflow-generations.scenario.test.tsindex ff91717c9..53c6f7033 100644--- a/packages/eve/test/scenarios/dev-server-workflow-generations.scenario.test.ts+++ b/packages/eve/test/scenarios/dev-server-workflow-generations.scenario.test.ts@@ -120,7 +120,7 @@ describe("eve dev server workflow generations", () => {createGenerationMarkerToolSource("generation-two", false),);await writeFile(- join(app.appRoot, "agent", "instrumentation.ts"),+ join(app.appRoot, "agent", "instrumentation", "reload.ts"),createInstrumentationSource("two"),);await forceDevelopmentRebuild(server.url);@@ -132,10 +132,9 @@ describe("eve dev server workflow generations", () => {`Timed out waiting for the selected-generation retry.\n\nstdout:\n${server.stdout()}\n\nstderr:\n${server.stderr()}`,);expect(readCompletedMessages(firstResult.events)).toContain("generation-one");- // Instrumentation is now an ordinary compiled source. Retrying an old- // generation therefore restores that generation's instrumentation- // together with its tool modules.- expect(readCompletedMessages(firstResult.events)).toContain("instrumentation-one");+ // Providers are installed once by the active host, while durable tool+ // code can retry from the generation that originally selected it.+ expect(readCompletedMessages(firstResult.events)).toContain("instrumentation-two");const secondResult = await sendDevelopmentMessage({message: "Use get_marker.",@@ -143,9 +142,7 @@ describe("eve dev server workflow generations", () => {serverUrl: server.url,});expect(readCompletedMessages(secondResult.events)).toContain("generation-two");- // The retained generation's ordinary instrumentation module was the- // last instrumentation source evaluated in this worker.- expect(readCompletedMessages(secondResult.events)).toContain("instrumentation-one");+ expect(readCompletedMessages(secondResult.events)).toContain("instrumentation-two");} finally {await server.stop();}@@ -222,7 +219,7 @@ describe("eve dev server workflow generations", () => {createGenerationMarkerToolSource("generation-two", false),);await writeFile(- join(app.appRoot, "agent", "instrumentation.ts"),+ join(app.appRoot, "agent", "instrumentation", "reload.ts"),createInstrumentationSource("two"),);await forceDevelopmentRebuild(server.url);diff --git a/packages/eve/test/scenarios/recursive-session-result.scenario.test.ts b/packages/eve/test/scenarios/recursive-session-result.scenario.test.tsindex 2ef786fce..dd1a3c01a 100644--- a/packages/eve/test/scenarios/recursive-session-result.scenario.test.ts+++ b/packages/eve/test/scenarios/recursive-session-result.scenario.test.ts@@ -12,8 +12,7 @@ describe("eve client inside an authored tool", () => {name: "recursive-session-result",installDependencies: true,files: {- "agent/agent.ts":- 'export default { model: "openai/gpt-5.4-mini", experimental: { instrumentationProviders: true } };\n',+ "agent/agent.ts": 'export default { model: "openai/gpt-5.4-mini" };\n',"agent/instrumentation/otel.ts":'import { otel } from "eve/instrumentation/otel";\nexport default otel({ instrumentations: ["fetch"] });\n',"agent/instructions.md": "Call the requested tool, or answer directly.\n",diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 56df9f392..114672da3 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -514,8 +514,8 @@ importers:specifier: 0.5.0version: 0.5.0([email protected]([email protected]))([email protected]([email protected]([email protected]))([email protected])([email protected]))([email protected])([email protected])braintrust:- specifier: 3.24.0+ specifier: 3.29.0chat:specifier: 4.41.0@@ -8904,6 +8904,12 @@ packages:peerDependencies:zod: ^3.25.34 || ^4.0+ resolution: {integrity: sha512-VM6HVz5ydoIgIuWO9Nv8TmLA1RIBCe9qxuGHN4l//TG9s3UjeNCl006TU4mg3xZOGx2qqCMUpI2RTgfdBfQiSw==}+ hasBin: true+ peerDependencies:+ zod: ^3.25.34 || ^4.0+resolution: {integrity: sha512-3GSvyjvDI4Dur1Meg2BekJquu5uF+9R9a1+5M1Mde192eZoXbeXjzgOsgqPS2V8D5wrrip0gR5Hf/GhWQ9ZzaA==}engines: {node: ^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7}@@ -23993,6 +23999,42 @@ snapshots:transitivePeerDependencies:- '@aws-sdk/credential-provider-web-identity'- supports-color+ optional: true++ dependencies:+ '@next/env': 14.2.35+ '@vercel/functions': 1.6.0(@aws-sdk/[email protected])+ acorn: 8.18.0+ acorn-import-attributes: 1.9.5([email protected])+ ajv: 8.20.0+ argparse: 2.0.1+ astring: 1.9.0+ cjs-module-lexer: 2.2.1+ cli-progress: 3.12.0+ cli-table3: 0.6.5+ cors: 2.8.6+ dotenv: 16.6.1+ esbuild: 0.28.1+ esquery: 1.7.0+ eventsource-parser: 1.1.2+ express: 5.2.1([email protected])+ http-errors: 2.0.1+ meriyah: 6.1.4+ minimatch: 10.2.6+ module-details-from-path: 1.0.4+ mustache: 4.2.0+ pluralize: 8.0.0+ semifies: 1.0.0+ source-map: 0.7.6+ termi-link: 1.1.0+ unplugin: 2.3.11+ uuid: 11.1.1+ zod: 4.5.4+ zod-to-json-schema: 3.25.2([email protected])+ transitivePeerDependencies:+ - '@aws-sdk/credential-provider-web-identity'+ - supports-colordependencies:@@ -24867,7 +24909,8 @@ snapshots:- [email protected]: {}+ optional: true