Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat(eve): unify conversation audience classification (#3325)

Chad Hietala0e0f3cc2ea1d
diff --git a/.changeset/unify-conversation-audience.md b/.changeset/unify-conversation-audience.md
new file mode 100644
index 000000000..580eb09db
--- /dev/null
+++ b/.changeset/unify-conversation-audience.md
@@ -0,0 +1,7 @@
+---
+"eve": minor
+---
+
+- Adds `audience(input)` to `defineChannel` and a durable conversation context for trace policies.
+- `eveChannel` now defaults anonymous callers to public and authenticated callers to private. Trace content is public-or-development by default.
+- `metadata().audience` is deprecated. Channel epoch 19 extensions keep working through a warned fallback; move classification to `audience(input)`.
diff --git a/docs/channels/custom.mdx b/docs/channels/custom.mdx
index 990ad7734..686a0f142 100644
--- a/docs/channels/custom.mdx
+++ b/docs/channels/custom.mdx
@@ -310,9 +310,29 @@ export default defineChannel({
The projection is re-evaluated whenever adapter state changes after channel event handlers run. Dynamic tool resolvers read it via `ctx.channel.metadata` and narrow it with `isChannel`. See [Dynamic capabilities](../guides/dynamic-capabilities) for the full consumption pattern.
-Metadata may include an `audience` classification: `public`, `private`, or `unknown`. Omit it when the channel cannot classify the conversation confidently; eve normalizes missing and invalid values to `unknown`. Consumers must treat `unknown` as non-public.
+### Conversation audience
-When a parent agent dispatches a subagent, the framework forwards the parent's channel metadata projection to the child. The same `metadata(state)` projector also serves instrumentation metadata resolvers.
+Use `audience(input)` to classify who can observe the conversation. The hook runs after route authentication and before the session is created:
+
+```ts
+import { defineChannel, POST } from "eve/channels";
+
+export default defineChannel({
+ state: { visibility: "workspace" as "workspace" | "private" | "unknown" },
+ audience({ state, auth }) {
+ if (state.visibility === "workspace") return "public";
+ if (auth?.principalType === "user") return "private";
+ return "unknown";
+ },
+ routes: [POST("/webhook", async () => new Response("ok"))],
+});
+```
+
+The input contains the channel's `state`, authenticated `auth` principal, `channel`, `mode`, and `environment`. Return `"public"`, `"private"`, or `"unknown"`. Return `"unknown"` when the channel does not have enough evidence to classify confidently; consumers treat it as non-public. A missing, throwing, asynchronous, or malformed classifier also fails closed to `"unknown"`.
+
+Classification is fixed when the session is created. Continuation turns from a different caller do not reclassify an existing session. When a parent dispatches a local subagent, the child inherits the parent's audience while the framework forwards the parent's custom channel metadata separately.
+
+`metadata(state)` remains a channel-owned projection of custom observability fields. It no longer carries a reserved `audience` key. Channel extensions built before channel epoch 20 can still use that key; eve accepts it as a deprecated fallback and warns once, then authors should move classification to `audience(input)`.
## Continuation tokens
diff --git a/docs/channels/eve.mdx b/docs/channels/eve.mdx
index 36725222f..064374b44 100644
--- a/docs/channels/eve.mdx
+++ b/docs/channels/eve.mdx
@@ -157,6 +157,45 @@ Neither admits browser users or external clients in production. For a public app
For the full auth model and helper list, see [Auth & route protection](../guides/auth-and-route-protection).
+## Audience
+
+The eve channel classifies who can observe a session when that session is created:
+
+| Session creator | Default audience |
+| ----------------------------------------- | ---------------- |
+| Anonymous caller | `public` |
+| `user`, `service`, or `runtime` principal | `private` |
+| Any other principal type | `unknown` |
+
+Anonymous HTTP surfaces are public because anyone who can reach the surface can read it. Authenticated `user`, `service`, and `runtime` sessions are private because they belong to one identified party. Other authenticated principal types remain `unknown`: trace consumers record metadata but omit content by default in preview and production.
+
+Pass a constant or a function to override the default:
+
+```ts title="agent/channels/eve.ts"
+import { none, vercelOidc } from "eve/channels/auth";
+import { eveChannel } from "eve/channels/eve";
+
+export default eveChannel({
+ auth: [vercelOidc()],
+ audience: "private",
+});
+```
+
+```ts title="agent/channels/eve.ts"
+import { vercelOidc } from "eve/channels/auth";
+import { eveChannel } from "eve/channels/eve";
+
+export default eveChannel({
+ auth: [vercelOidc(), none()],
+ audience({ auth, environment }) {
+ if (auth === null) return environment === "development" ? "public" : "unknown";
+ return "private";
+ },
+});
+```
+
+The function receives the authenticated principal, channel, run mode, and deployment environment. Classification is fixed at session creation; a continuation turn from a different caller does not reclassify the session. When another eve deployment forwards a request without an accepted forwarded trace assertion, the calling deployment's principal is used for classification, so the session remains `private`. A custom [trace policy](../guides/instrumentation-providers#control-inputs-and-outputs) can still admit or deny content independently.
+
## Customization
Use `onMessage` to add request-specific context before the agent sees the user message, and `events` to observe stream events from sessions this channel created:
diff --git a/docs/guides/instrumentation-providers.md b/docs/guides/instrumentation-providers.md
index 5ea12a02a..c8fd46f9d 100644
--- a/docs/guides/instrumentation-providers.md
+++ b/docs/guides/instrumentation-providers.md
@@ -65,10 +65,10 @@ Each provider has an independent `tracePolicy`. It decides whether the provider
import { defineInstrumentation } from "eve/instrumentation";
export default defineInstrumentation({
- tracePolicy: ({ audience }) => ({
+ tracePolicy: ({ audience, environment }) => ({
emit: true,
- recordInputs: audience === "public",
- recordOutputs: audience === "public",
+ recordInputs: audience === "public" || environment === "development",
+ recordOutputs: audience === "public" || environment === "development",
}),
events: {
"model.call.started": (event) => {
@@ -81,9 +81,11 @@ export default defineInstrumentation({
});
```
-The policy receives `agentName`, `audience`, and, when available, `channelType`. `audience` is `"public"`, `"private"`, or `"unknown"`.
+The policy receives `agentName`, `channel`, `audience`, `mode`, `environment`, and `principalType`. `audience` is `"public"`, `"private"`, or `"unknown"`. `environment` is `"development"`, `"preview"`, or `"production"`.
-The default policy emits metadata for every audience and includes inputs and outputs only for `public` conversations. Return an explicit decision to change that behavior:
+`principalType` is the principal used for classification. Normal channels report their route or session principal; forwarded eve sessions report the calling deployment's principal. Sessions that predate the durable conversation key report their session initiator.
+
+The default policy emits metadata for every audience and includes inputs and outputs for `public` conversations and for any audience in a development environment. Preview behaves like production: an `unknown` conversation records metadata only. Return an explicit decision to change that behavior:
| Decision | Result |
| --------------------------------------------- | ------------------------------------------------------------ |
@@ -162,10 +164,10 @@ import { otel } from "eve/instrumentation/otel";
export default otel({
resource: { "deployment.environment": process.env.VERCEL_ENV ?? "development" },
- tracePolicy: ({ audience }) => ({
+ tracePolicy: ({ audience, environment }) => ({
emit: true,
- recordInputs: audience === "public",
- recordOutputs: audience === "public",
+ recordInputs: audience === "public" || environment === "development",
+ recordOutputs: audience === "public" || environment === "development",
}),
});
```
diff --git a/docs/guides/instrumentation.md b/docs/guides/instrumentation.md
index 32ab928d5..d0f28b8cb 100644
--- a/docs/guides/instrumentation.md
+++ b/docs/guides/instrumentation.md
@@ -62,7 +62,7 @@ You are responsible for ensuring any observability or eval provider is approved
The third configurable surface, [runtime context events](#runtime-context), attaches per-model-call values to these spans.
-Built-in messaging channels classify their instrumentation metadata with an `audience`: `public`, `private`, or `unknown`. Slack public channels and Chat SDK workspace-visible threads are public; direct and private conversations are private; platform surfaces without enough visibility evidence remain unknown. Proactive Slack `receive` / `ctx.send` handoffs stay `unknown` unless the caller passes `audience` on the target, for example when a webhook or schedule already knows the destination channel is public.
+Channels classify their conversation with an `audience`: `public`, `private`, or `unknown`. The eve channel classifies anonymous callers as public and authenticated `user`, `service`, or `runtime` callers as private. Slack public-channel handoffs and Chat SDK workspace-visible threads are public; direct and private conversations are private; platform surfaces without enough visibility evidence remain unknown. Inbound Slack webhooks remain `unknown`; proactive Slack `receive` / `ctx.send` handoffs also stay `unknown` unless the caller passes `audience` on the target, for example when a webhook or schedule already knows the destination channel is public.
## Channel delivery traces
@@ -253,7 +253,7 @@ Agent Runs activation metadata includes bounded principal summaries:
Types are limited to `user`, `service`, `runtime`, `app`, `anonymous`, `local-dev`, `unknown`, `none`, and `other`. Types are emitted for every audience when a principal is present. An absent type means no authentication context was set; `none` means an explicitly null principal and has no ID. The auth layer's `unknown` type stays `unknown`; unrecognized authored types become `other`.
-Principal IDs require a content-visible audience and a resolved trace decision that allows both `recordInputs` and `recordOutputs`. Public turns and unknown turns under `eve dev` can include IDs; private and hosted-unknown turns omit them. A user-configured trace policy or forwarded content ceiling that denies either direction omits both principal IDs before turn state is stored or sampled. Empty IDs and IDs larger than 1 KiB of UTF-8 data are omitted, not truncated; authentication records are unchanged. eve does not copy other authentication fields, such as claims, email attributes, issuers, or subjects, into these summaries.
+Principal IDs require content-visible capture and a resolved trace decision that allows both `recordInputs` and `recordOutputs`. Public turns and every audience in a development environment can include IDs; private and unknown turns omit them in preview and production. A user-configured trace policy or forwarded content ceiling that denies either direction omits both principal IDs before turn state is stored or sampled. Empty IDs and IDs larger than 1 KiB of UTF-8 data are omitted, not truncated; authentication records are unchanged. eve does not copy other authentication fields, such as claims, email attributes, issuers, or subjects, into these summaries.
## Query exported traces
diff --git a/docs/guides/remote-agents.md b/docs/guides/remote-agents.md
index cc94f203b..9565e3c72 100644
--- a/docs/guides/remote-agents.md
+++ b/docs/guides/remote-agents.md
@@ -173,7 +173,7 @@ export default eveChannel({
The request must also include a callback and a valid sampled `traceparent`. Those fields identify a remote call, but they do not establish trust. `trustedForwarders` is the authorization boundary.
-The receiver combines the incoming ceiling with its own trace policy. Each hop may narrow the result, but it cannot restore inputs or outputs removed earlier. The original audience stays the same across remote and local subagent hops. Public origins may include content by default; private and unknown origins stay metadata-only unless both deployments explicitly allow them.
+The receiver combines the incoming ceiling with its own trace policy. Each hop may narrow the result, but it cannot restore inputs or outputs removed earlier. The original audience stays the same across remote and local subagent hops. Public origins may include content by default. Private and unknown origins stay metadata-only in preview and production unless both deployments explicitly allow them; a receiver running in development still applies the development content default.
The live delivery audience still matters. An unknown callback delivery, or one matching the origin, uses the session decision. A different explicit audience applies its own hard ceiling, so a private delivery stays redacted even when the trace began in public.
diff --git a/packages/eve/extension-contracts/compatibility/channel/v19.ts b/packages/eve/extension-contracts/compatibility/channel/v19.ts
new file mode 100644
index 000000000..2462a4352
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/channel/v19.ts
@@ -0,0 +1,11 @@
+import { defineChannel, POST } from "#public/channels/index.js";
+
+export default defineChannel({
+ metadata: () => ({ audience: "public" }),
+ routes: [
+ POST("/continue/:sessionId", async (_request, { attachSession, params }) => {
+ const result = await attachSession(params.sessionId!).send("Continue.", { auth: null });
+ return Response.json({ accepted: result.status === "accepted" });
+ }),
+ ],
+});
diff --git a/packages/eve/extension-contracts/compatibility/connection/v16.ts b/packages/eve/extension-contracts/compatibility/connection/v16.ts
new file mode 100644
index 000000000..c9adb6c9f
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/connection/v16.ts
@@ -0,0 +1,6 @@
+import { defineMcpClientConnection } from "#public/connections/index.js";
+
+export default defineMcpClientConnection({
+ description: "Call-aware MCP service",
+ url: "https://example.com/mcp",
+});
diff --git a/packages/eve/extension-contracts/compatibility/dynamicInstructions/v19.ts b/packages/eve/extension-contracts/compatibility/dynamicInstructions/v19.ts
new file mode 100644
index 000000000..745446593
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/dynamicInstructions/v19.ts
@@ -0,0 +1,8 @@
+import { defineDynamic, defineInstructions } from "#public/instructions/index.js";
+
+export default defineDynamic({
+ events: {
+ "session.started": (_event, ctx) =>
+ defineInstructions({ markdown: `Use session ${ctx.session.id} for correlation.` }),
+ },
+});
diff --git a/packages/eve/extension-contracts/compatibility/dynamicSkill/v18.ts b/packages/eve/extension-contracts/compatibility/dynamicSkill/v18.ts
new file mode 100644
index 000000000..bd9ab80cf
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/dynamicSkill/v18.ts
@@ -0,0 +1,11 @@
+import { defineDynamic, defineSkill } from "#public/skills/index.js";
+
+export default defineDynamic({
+ events: {
+ "turn.started": (_event, ctx) =>
+ defineSkill({
+ description: `Review session ${ctx.session.id}.`,
+ markdown: "# Review\n\nCheck each claim.",
+ }),
+ },
+});
diff --git a/packages/eve/extension-contracts/compatibility/dynamicTool/v35.ts b/packages/eve/extension-contracts/compatibility/dynamicTool/v35.ts
new file mode 100644
index 000000000..0552088f0
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/dynamicTool/v35.ts
@@ -0,0 +1,20 @@
+import { z } from "zod";
+
+import { defineDynamic, defineTool } from "#public/tools/index.js";
+
+export default defineDynamic({
+ events: {
+ "session.started": () =>
+ defineTool({
+ description: "Report deployment progress.",
+ inputSchema: z.object({ service: z.string() }),
+ outputSchema: z.object({ url: z.string() }),
+ label: {
+ complete: ({ service }, { url }) => `Deployed ${service} to ${url}`,
+ delta: ({ service }) => `Deploying ${service}`,
+ start: ({ service }) => `Deploy ${service}`,
+ },
+ execute: async ({ service }) => ({ url: `https://${service}.example.com` }),
+ }),
+ },
+});
diff --git a/packages/eve/extension-contracts/compatibility/subagent/v14.ts b/packages/eve/extension-contracts/compatibility/subagent/v14.ts
new file mode 100644
index 000000000..fb9a0645b
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/subagent/v14.ts
@@ -0,0 +1,5 @@
+import { defineWorkspaceAgent } from "#public/index.js";
+
+export default defineWorkspaceAgent({
+ name: "research",
+});
diff --git a/packages/eve/extension-contracts/reports/channel/v20.json b/packages/eve/extension-contracts/reports/channel/v20.json
new file mode 100644
index 000000000..dbad1e608
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/channel/v20.json
@@ -0,0 +1,21 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "channel",
+ "epoch": 20,
+ "sha256": "b935c021d2229ad3482370457f72531693080c661da75aee845a2b7695bad66a",
+ "exports": [
+ "DELETE",
+ "GET",
+ "HEAD",
+ "OPTIONS",
+ "PATCH",
+ "POST",
+ "PUT",
+ "WS",
+ "createWebSocketUpgradeServer",
+ "defineChannel",
+ "disableRoute",
+ "isChannel",
+ "isDisabledRouteSentinel"
+ ]
+}
diff --git a/packages/eve/extension-contracts/reports/connection/v17.json b/packages/eve/extension-contracts/reports/connection/v17.json
new file mode 100644
index 000000000..79003aa62
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/connection/v17.json
@@ -0,0 +1,16 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "connection",
+ "epoch": 17,
+ "sha256": "c87ec9d2c3ae844b570a67be2352234ff1033fc8fdfc14d37b702066d8a80e94",
+ "exports": [
+ "ConnectionAuthorizationFailedError",
+ "ConnectionAuthorizationRequiredError",
+ "defineDynamic",
+ "defineInteractiveAuthorization",
+ "defineMcpClientConnection",
+ "defineOpenAPIConnection",
+ "isConnectionAuthorizationFailedError",
+ "isConnectionAuthorizationRequiredError"
+ ]
+}
diff --git a/packages/eve/extension-contracts/reports/dynamicInstructions/v20.json b/packages/eve/extension-contracts/reports/dynamicInstructions/v20.json
new file mode 100644
index 000000000..130f007e1
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/dynamicInstructions/v20.json
@@ -0,0 +1,7 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "dynamicInstructions",
+ "epoch": 20,
+ "sha256": "d5bf678de224fab5583e99924b79a4f82feb5ee7c8cdea222960a52beb7e0bf5",
+ "exports": ["defineDynamic"]
+}
diff --git a/packages/eve/extension-contracts/reports/dynamicSkill/v19.json b/packages/eve/extension-contracts/reports/dynamicSkill/v19.json
new file mode 100644
index 000000000..8fa4d8c0d
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/dynamicSkill/v19.json
@@ -0,0 +1,7 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "dynamicSkill",
+ "epoch": 19,
+ "sha256": "e903fa962cbf8040996626c2b28623760bacd11e5014167a32b0d4f419b50a61",
+ "exports": ["defineDynamic"]
+}
diff --git a/packages/eve/extension-contracts/reports/dynamicTool/v36.json b/packages/eve/extension-contracts/reports/dynamicTool/v36.json
new file mode 100644
index 000000000..da06c8726
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/dynamicTool/v36.json
@@ -0,0 +1,14 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "dynamicTool",
+ "epoch": 36,
+ "sha256": "56967dbefa3b0f2fd65de7c1e63131bf07cff109706471f14eb58eea6d1ac00b",
+ "exports": [
+ "DynamicToolEntry",
+ "DynamicToolEvents",
+ "DynamicToolResult",
+ "DynamicToolSet",
+ "defineDurableCallback",
+ "defineDynamic"
+ ]
+}
diff --git a/packages/eve/extension-contracts/reports/subagent/v15.json b/packages/eve/extension-contracts/reports/subagent/v15.json
new file mode 100644
index 000000000..70bac1888
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/subagent/v15.json
@@ -0,0 +1,23 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "subagent",
+ "epoch": 15,
+ "sha256": "11834f91cbdc2ffd4776e19f573d66bc12062c46fb950048d42431c5aa3b6884",
+ "exports": [
+ "AgentCompactionDefinition",
+ "AgentDefinition",
+ "AgentModelDefinition",
+ "AgentStaticModelDefinition",
+ "DefinedAgent",
+ "DynamicLocalSubagentDefinition",
+ "DynamicSubagentDefinition",
+ "RemoteAgentDefinition",
+ "RemoteAgentDefinitionInput",
+ "WorkspaceAgentDefinition",
+ "WorkspaceAgentTransport",
+ "defineAgent",
+ "defineDynamic",
+ "defineRemoteAgent",
+ "defineWorkspaceAgent"
+ ]
+}
diff --git a/packages/eve/src/channel/adapter.ts b/packages/eve/src/channel/adapter.ts
index 1cf535237..461788bc9 100644
--- a/packages/eve/src/channel/adapter.ts
+++ b/packages/eve/src/channel/adapter.ts
@@ -10,7 +10,7 @@ import type {
FetchFileResult,
FetchFileFunction,
} from "#shared/channel-definition.js";
-import type { ChannelAudienceMetadata } from "#shared/channel-audience.js";
+import type { ChannelAudienceProjector } from "#channel/audience.js";
const log = createLogger("channel.adapter");
@@ -103,9 +103,7 @@ export type ChannelEventHandlers<TCtx extends ChannelAdapterContext<any> = Chann
*/
export type { FetchFileContext, FetchFileResult };
-export type ChannelInstrumentationMetadata = Readonly<
- Record<string, unknown> & ChannelAudienceMetadata
->;
+export type ChannelInstrumentationMetadata = Readonly<Record<string, unknown>>;
export type ChannelInstrumentationMetadataProjector = (
state: Record<string, unknown> | undefined,
@@ -177,6 +175,7 @@ export type ChannelAdapter<TCtx extends ChannelAdapterContext<any> = ChannelAdap
*/
readonly instrumentation?: {
readonly metadata?: ChannelInstrumentationMetadataProjector;
+ readonly audience?: ChannelAudienceProjector;
};
} & ChannelEventHandlers<TCtx>;
diff --git a/packages/eve/src/channel/audience.ts b/packages/eve/src/channel/audience.ts
new file mode 100644
index 000000000..82947fc33
--- /dev/null
+++ b/packages/eve/src/channel/audience.ts
@@ -0,0 +1,88 @@
+import type { ChannelAudience } from "#shared/channel-audience.js";
+import type { AudienceInput } from "#shared/conversation-context.js";
+import { normalizeChannelAudience } from "#shared/channel-audience.js";
+import { isThenable } from "#shared/guards.js";
+
+type ChannelAudienceSource = {
+ readonly kind: string;
+ readonly state?: Record<string, unknown> | undefined;
+ readonly instrumentation?: {
+ readonly audience?: ChannelAudienceProjector;
+ readonly metadata?: (state: Record<string, unknown> | undefined) => unknown;
+ };
+};
+
+const deprecatedAudienceChannels = new Set<string>();
+
+function warnDeprecatedMetadataAudience(kind: string): void {
+ if (deprecatedAudienceChannels.has(kind)) return;
+ deprecatedAudienceChannels.add(kind);
+ console.warn(`channel ${kind} uses deprecated metadata audience; move it to the audience() hook`);
+}
+
+export type ChannelAudienceProjector = (
+ input: AudienceInput<Record<string, unknown> | undefined>,
+) => ChannelAudience;
+
+export function resolveAudience(
+ adapter: ChannelAudienceSource,
+ input: AudienceInput<Record<string, unknown> | undefined>,
+): ChannelAudience {
+ return normalize(adapter, input);
+}
+
+export function createMetadataAudienceProjector(
+ source: { readonly kind: string },
+ metadata: (state: Record<string, unknown> | undefined) => unknown,
+): ChannelAudienceProjector {
+ return (input) =>
+ resolveAudience(
+ {
+ kind: source.kind,
+ state: input.state,
+ instrumentation: { metadata },
+ },
+ input,
+ );
+}
+
+function normalize(
+ adapter: ChannelAudienceSource,
+ input: AudienceInput<Record<string, unknown> | undefined>,
+): ChannelAudience {
+ const instrumentation = adapter.instrumentation;
+ const project = instrumentation?.audience;
+ if (project === undefined) {
+ const projectMetadata = instrumentation?.metadata;
+ if (projectMetadata === undefined) return "unknown";
+ let projection: unknown;
+ try {
+ projection = projectMetadata(adapter.state);
+ } catch {
+ console.warn(`ignoring deprecated channel audience metadata for channel ${adapter.kind}`);
+ return "unknown";
+ }
+ if (isThenable(projection)) {
+ console.warn(`ignoring deprecated channel audience metadata for channel ${adapter.kind}`);
+ void Promise.resolve(projection).catch(() => undefined);
+ return "unknown";
+ }
+ if (typeof projection !== "object" || projection === null) return "unknown";
+ const audience = (projection as Record<string, unknown>).audience;
+ if (audience === undefined) return "unknown";
+ warnDeprecatedMetadataAudience(adapter.kind);
+ return normalizeChannelAudience(audience);
+ }
+ try {
+ const value = project(input);
+ if (isThenable(value)) {
+ console.warn("ignoring channel audience classifier because it returned a Promise");
+ void Promise.resolve(value).catch(() => undefined);
+ return "unknown";
+ }
+ return normalizeChannelAudience(value);
+ } catch {
+ console.warn("ignoring channel audience classifier after failure");
+ return "unknown";
+ }
+}
diff --git a/packages/eve/src/channel/conversation-context.ts b/packages/eve/src/channel/conversation-context.ts
new file mode 100644
index 000000000..e99577664
--- /dev/null
+++ b/packages/eve/src/channel/conversation-context.ts
@@ -0,0 +1,52 @@
+import type { RunInput } from "#channel/types.js";
+import { resolveAudience } from "#channel/audience.js";
+import { buildChannelInstrumentationProjection } from "#channel/instrumentation.js";
+import { normalizeInstrumentationChannelKind } from "#shared/instrumentation-channel-kind.js";
+import {
+ resolveConversationContext,
+ type ConversationContext,
+ type ConversationEnvironment,
+} from "#shared/conversation-context.js";
+import { readForwardedTraceAssertion } from "#shared/forwarded-trace-policy.js";
+
+export function buildConversationContext(
+ run: RunInput,
+ environment: ConversationEnvironment,
+): ConversationContext {
+ const hasRouteAuth = Object.hasOwn(run, "audienceAuth");
+ const auth = hasRouteAuth ? (run.audienceAuth ?? null) : run.auth;
+ const projection = buildChannelInstrumentationProjection({
+ adapter: run.adapter,
+ channelName: run.channelName,
+ });
+ const channel = {
+ kind: normalizeInstrumentationChannelKind(projection.kind),
+ name: run.channelName,
+ };
+ const inherited = run.inheritedConversation;
+ const forwardedTracePolicy = readForwardedTraceAssertion(
+ run.parentTraceContext?.forwardedTracePolicy,
+ );
+ const audience =
+ forwardedTracePolicy?.originAudience ??
+ inherited?.audience ??
+ resolveAudience(run.adapter, {
+ state: run.adapter.state,
+ auth,
+ channel,
+ mode: run.mode,
+ environment,
+ });
+
+ return {
+ ...resolveConversationContext(undefined, {
+ channelKind: projection.kind,
+ environment,
+ forwardedTracePolicy,
+ mode: run.mode,
+ principalType: auth?.principalType,
+ }),
+ audience,
+ channel,
+ };
+}
diff --git a/packages/eve/src/channel/instrumentation.test.ts b/packages/eve/src/channel/instrumentation.test.ts
index 7c39df851..717c5a29b 100644
--- a/packages/eve/src/channel/instrumentation.test.ts
+++ b/packages/eve/src/channel/instrumentation.test.ts
@@ -1,7 +1,21 @@
-import { describe, expect, it } from "vitest";
+import { afterEach, describe, expect, it, vi } from "vitest";
import type { ChannelAdapter } from "#channel/adapter.js";
import { buildChannelInstrumentationProjection } from "#channel/instrumentation.js";
+import { resolveAudience } from "#channel/audience.js";
+import type { AudienceInput } from "#shared/conversation-context.js";
+
+const audienceInput: AudienceInput<Record<string, unknown>> = {
+ auth: null,
+ channel: { kind: "channel:support", name: "support" },
+ environment: "production",
+ mode: "conversation",
+ state: {},
+};
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
describe("channel instrumentation", () => {
it("uses the registered path-derived channel name as the instrumentation kind", () => {
@@ -13,35 +27,122 @@ describe("channel instrumentation", () => {
expect(buildChannelInstrumentationProjection({ adapter, channelName: "support" })).toEqual({
channelType: "slack",
kind: "channel:support",
- metadata: { audience: "unknown" },
+ metadata: {},
});
});
it.each(["public", "private", "unknown"] as const)("preserves the %s audience", (audience) => {
const adapter: ChannelAdapter = {
- instrumentation: { metadata: () => ({ audience }) },
+ instrumentation: { audience: () => audience },
kind: "slack",
state: {},
};
- expect(buildChannelInstrumentationProjection({ adapter }).metadata).toEqual({ audience });
+ expect(resolveAudience(adapter, audienceInput)).toBe(audience);
});
- it("normalizes an invalid audience to unknown without dropping other metadata", () => {
+ it("normalizes an invalid audience to unknown", () => {
const adapter: ChannelAdapter = {
instrumentation: {
- metadata: () => ({ audience: "everyone", threadId: "thread-1" }) as never,
+ audience: () => "everyone" as never,
},
kind: "slack",
state: {},
};
+ expect(resolveAudience(adapter, audienceInput)).toBe("unknown");
+ });
+
+ it("drops the former audience key from metadata", () => {
+ const adapter: ChannelAdapter = {
+ instrumentation: { metadata: () => ({ audience: "public", threadId: "thread-1" }) },
+ kind: "slack",
+ state: {},
+ };
+
expect(buildChannelInstrumentationProjection({ adapter }).metadata).toEqual({
- audience: "unknown",
threadId: "thread-1",
});
});
+ it("uses deprecated metadata audience as the v19 compatibility fallback", () => {
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined);
+ const adapter: ChannelAdapter = {
+ instrumentation: { metadata: () => ({ audience: "public", threadId: "thread-1" }) },
+ kind: "legacy-kind",
+ state: {},
+ };
+
+ expect(resolveAudience(adapter, audienceInput)).toBe("public");
+ expect(warn).toHaveBeenCalledExactlyOnceWith(
+ "channel legacy-kind uses deprecated metadata audience; move it to the audience() hook",
+ );
+ expect(buildChannelInstrumentationProjection({ adapter }).metadata).toEqual({
+ threadId: "thread-1",
+ });
+ });
+
+ it("prefers the audience hook over deprecated metadata audience", () => {
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined);
+ const adapter: ChannelAdapter = {
+ instrumentation: {
+ audience: () => "private",
+ metadata: () => ({ audience: "public" }),
+ },
+ kind: "legacy-hook-wins",
+ state: {},
+ };
+
+ expect(resolveAudience(adapter, audienceInput)).toBe("private");
+ expect(warn).not.toHaveBeenCalled();
+ });
+
+ it("ignores an asynchronous audience classifier", () => {
+ const adapter: ChannelAdapter = {
+ instrumentation: { audience: () => Promise.resolve("public") as never },
+ kind: "failing-classifier",
+ state: {},
+ };
+
+ expect(resolveAudience(adapter, audienceInput)).toBe("unknown");
+ });
+
+ it("consumes a rejected classifier promise before failing closed", async () => {
+ const unhandledRejection = vi.fn();
+ process.once("unhandledRejection", unhandledRejection);
+ const adapter: ChannelAdapter = {
+ instrumentation: {
+ audience: () => Promise.reject(new Error("classifier failed")) as never,
+ },
+ kind: "slack",
+ state: {},
+ };
+
+ expect(resolveAudience(adapter, audienceInput)).toBe("unknown");
+ await new Promise((resolve) => setImmediate(resolve));
+
+ expect(unhandledRejection).not.toHaveBeenCalled();
+ process.removeListener("unhandledRejection", unhandledRejection);
+ });
+
+ it("does not log authored classifier failures verbatim", () => {
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined);
+ const adapter: ChannelAdapter = {
+ instrumentation: {
+ audience() {
+ throw new Error("secret-classifier-failure");
+ },
+ },
+ kind: "slack",
+ state: {},
+ };
+
+ expect(resolveAudience(adapter, audienceInput)).toBe("unknown");
+ expect(warn).toHaveBeenCalledExactlyOnceWith(
+ "ignoring channel audience classifier after failure",
+ );
+ });
+
it("observes rejected thenables before ignoring channel metadata", async () => {
let observed = false;
const promise = Promise.reject(new Error("metadata failed"));
@@ -63,7 +164,7 @@ describe("channel instrumentation", () => {
expect(buildChannelInstrumentationProjection({ adapter, channelName: "support" })).toEqual({
channelType: "slack",
kind: "channel:support",
- metadata: { audience: "unknown" },
+ metadata: {},
});
await Promise.resolve();
diff --git a/packages/eve/src/channel/instrumentation.ts b/packages/eve/src/channel/instrumentation.ts
index bb18ca391..dcdb3fe75 100644
--- a/packages/eve/src/channel/instrumentation.ts
+++ b/packages/eve/src/channel/instrumentation.ts
@@ -5,7 +5,6 @@ import {
resolveInstrumentationProjection,
} from "#internal/instrumentation.js";
import { createLogger } from "#internal/logging.js";
-import { normalizeChannelAudience } from "#shared/channel-audience.js";
const log = createLogger("channel.instrumentation");
@@ -51,7 +50,7 @@ function resolveKind(input: {
function resolveMetadata(adapter: ChannelAdapter): ChannelInstrumentationMetadata {
const project = adapter.instrumentation?.metadata;
if (project === undefined) {
- return { audience: "unknown" };
+ return {};
}
const projection = resolveInstrumentationProjection({
@@ -60,8 +59,6 @@ function resolveMetadata(adapter: ChannelAdapter): ChannelInstrumentationMetadat
source: getAdapterKind(adapter),
});
- return {
- ...projection,
- audience: normalizeChannelAudience(projection?.audience),
- };
+ const { audience: _ignoredAudience, ...metadata } = projection ?? {};
+ return metadata;
}
diff --git a/packages/eve/src/channel/subagent-emitter.test.ts b/packages/eve/src/channel/subagent-emitter.test.ts
index 06646d6e7..f13911e8d 100644
--- a/packages/eve/src/channel/subagent-emitter.test.ts
+++ b/packages/eve/src/channel/subagent-emitter.test.ts
@@ -34,7 +34,6 @@ describe("subagent adapter", () => {
parentSessionId: "parent-session",
subagentName: "summarizer",
},
- audience: "unknown",
});
const rehydrated = deserializeRuntimeAdapter(
diff --git a/packages/eve/src/channel/types.ts b/packages/eve/src/channel/types.ts
index 3f52f67c8..481d2bc69 100644
--- a/packages/eve/src/channel/types.ts
+++ b/packages/eve/src/channel/types.ts
@@ -15,6 +15,7 @@ import type { AgentLimitsDefinition } from "#shared/agent-definition.js";
import type { JsonObject } from "#shared/json.js";
import type { InstrumentationDecision } from "#shared/instrumentation-decision.js";
import type { ForwardedTraceAssertion } from "#shared/forwarded-trace-policy.js";
+import type { ConversationContext } from "#shared/conversation-context.js";
import type {
TaskAgentRequestDelivery,
TaskAuthorizationEventDelivery,
@@ -463,6 +464,8 @@ export interface RunInput {
*/
readonly channelName?: string;
readonly channelMetadata?: ChannelInstrumentationProjection;
+ /** Parent conversation classification inherited by a local subagent. */
+ readonly inheritedConversation?: ConversationContext;
/** Inbound channel operation that created this session. */
readonly delivery?: ChannelDeliveryMetadata;
/**
@@ -470,6 +473,12 @@ export interface RunInput {
* request was accepted with no credentials.
*/
readonly auth: SessionAuthContext | null;
+ /**
+ * Route-authenticated principal used to classify the conversation. This
+ * stays separate from `auth` because a channel may project a different
+ * principal into session auth after route authentication.
+ */
+ readonly audienceAuth?: SessionAuthContext | null;
/**
* Session-level capabilities. When omitted, every flag is
* interpreted as `false`. Channel routes that can reach a human
diff --git a/packages/eve/src/compiler/extension-compatibility.ts b/packages/eve/src/compiler/extension-compatibility.ts
index c1a3ece89..373aea2d2 100644
--- a/packages/eve/src/compiler/extension-compatibility.ts
+++ b/packages/eve/src/compiler/extension-compatibility.ts
@@ -43,10 +43,10 @@ const EXTENSION_CAPABILITY_CONTRACTS = {
},
},
dynamicTool: {
- current: 35,
+ current: 36,
supported: [
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 22, 28, 29, 30, 31, 32,
- 33, 34, 35,
+ 33, 34, 35, 36,
],
dropped: {
21: "Message and reasoning append events now expose deltas instead of cumulative snapshots.",
@@ -58,8 +58,8 @@ const EXTENSION_CAPABILITY_CONTRACTS = {
},
},
channel: {
- current: 19,
- supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 19],
+ current: 20,
+ supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 19, 20],
dropped: {
12: "Message and reasoning append events now expose deltas instead of cumulative snapshots.",
},
@@ -72,8 +72,8 @@ const EXTENSION_CAPABILITY_CONTRACTS = {
},
},
subagent: {
- current: 14,
- supported: [3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14],
+ current: 15,
+ supported: [3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
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",
@@ -81,8 +81,8 @@ const EXTENSION_CAPABILITY_CONTRACTS = {
},
},
connection: {
- current: 16,
- supported: [1, 2, 3, 4, 5, 6, 7, 8, 11, 12, 13, 14, 15, 16],
+ current: 17,
+ supported: [1, 2, 3, 4, 5, 6, 7, 8, 11, 12, 13, 14, 15, 16, 17],
dropped: {
9: "Dynamic connection resolvers no longer receive conversation or channel continuation data",
10: "Message and reasoning append events now expose deltas instead of cumulative snapshots.",
@@ -106,16 +106,16 @@ const EXTENSION_CAPABILITY_CONTRACTS = {
},
skill: { current: 1, supported: [1], dropped: {} },
dynamicSkill: {
- current: 18,
- supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 15, 16, 17, 18],
+ current: 19,
+ supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 15, 16, 17, 18, 19],
dropped: {
13: "Message and reasoning append events now expose deltas instead of cumulative snapshots.",
},
},
instructions: { current: 2, supported: [1, 2], dropped: {} },
dynamicInstructions: {
- current: 19,
- supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17, 18, 19],
+ current: 20,
+ supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17, 18, 19, 20],
dropped: {
14: "Message and reasoning append events now expose deltas instead of cumulative snapshots.",
},
diff --git a/packages/eve/src/context/dynamic-resolve-context.ts b/packages/eve/src/context/dynamic-resolve-context.ts
index 44f28d038..aecb1acbd 100644
--- a/packages/eve/src/context/dynamic-resolve-context.ts
+++ b/packages/eve/src/context/dynamic-resolve-context.ts
@@ -12,6 +12,7 @@ import {
} from "#context/keys.js";
import { ChannelKey } from "#runtime/sessions/runtime-context-keys.js";
import { getAdapterKind } from "#channel/adapter.js";
+import { ConversationContextKey } from "#shared/conversation-context.js";
type ReadableContext = Pick<AlsContext, "get">;
@@ -47,6 +48,9 @@ export function buildResolveContext(
continuationToken,
metadata: channelInstrumentation?.metadata,
},
+ ...(ctx.get(ConversationContextKey) === undefined
+ ? undefined
+ : { conversation: ctx.get(ConversationContextKey) }),
messages,
};
}
diff --git a/packages/eve/src/dynamic/definition.ts b/packages/eve/src/dynamic/definition.ts
index 6bcd908c3..b0468d959 100644
--- a/packages/eve/src/dynamic/definition.ts
+++ b/packages/eve/src/dynamic/definition.ts
@@ -3,6 +3,7 @@ import type { ModelMessage } from "ai";
import type { SessionAuth } from "#context/keys.js";
import { stampDefinitionKey } from "#internal/authored-definition/source-identity.js";
import type { UnstampedMessageStreamEvent } from "#protocol/message.js";
+import type { ConversationContext } from "#shared/conversation-context.js";
/**
* Stream event types allowed for dynamic tool resolvers. Dispatch
@@ -60,6 +61,11 @@ export interface DynamicResolveContext {
/** Free-form channel-specific metadata attached to the request. */
readonly metadata?: Readonly<Record<string, unknown>>;
};
+ /**
+ * Immutable classification and execution context for the active conversation.
+ * Absent on sessions persisted before this context key existed.
+ */
+ readonly conversation?: ConversationContext;
/** Conversation history visible at this resolve point, oldest first. */
readonly messages: readonly ModelMessage[];
}
diff --git a/packages/eve/src/eve-channel/audience.test.ts b/packages/eve/src/eve-channel/audience.test.ts
new file mode 100644
index 000000000..9cfd96ce9
--- /dev/null
+++ b/packages/eve/src/eve-channel/audience.test.ts
@@ -0,0 +1,33 @@
+import { describe, expect, it } from "vitest";
+
+import { defaultEveAudience } from "#eve-channel/audience.js";
+import type { AudienceInput } from "#shared/conversation-context.js";
+
+function input(principalType: string | null): Omit<AudienceInput<undefined>, "state"> {
+ return {
+ auth:
+ principalType === null
+ ? null
+ : {
+ attributes: {},
+ authenticator: "test",
+ principalType,
+ },
+ channel: { kind: "http" },
+ environment: "production",
+ mode: "conversation",
+ };
+}
+
+describe("defaultEveAudience", () => {
+ it.each([
+ [null, "public"],
+ ["anonymous", "public"],
+ ["user", "private"],
+ ["service", "private"],
+ ["runtime", "private"],
+ ["app", "unknown"],
+ ] as const)("classifies %s as %s", (principalType, audience) => {
+ expect(defaultEveAudience(input(principalType))).toBe(audience);
+ });
+});
diff --git a/packages/eve/src/eve-channel/audience.ts b/packages/eve/src/eve-channel/audience.ts
new file mode 100644
index 000000000..5f37bd318
--- /dev/null
+++ b/packages/eve/src/eve-channel/audience.ts
@@ -0,0 +1,13 @@
+import type { ChannelAudience } from "#shared/channel-audience.js";
+import type { AudienceInput } from "#shared/conversation-context.js";
+
+export function defaultEveAudience(
+ input: Omit<AudienceInput<undefined>, "state">,
+): ChannelAudience {
+ const principalType = input.auth?.principalType ?? "anonymous";
+ if (principalType === "anonymous") return "public";
+ if (principalType === "user" || principalType === "service" || principalType === "runtime") {
+ return "private";
+ }
+ return "unknown";
+}
diff --git a/packages/eve/src/eve-channel/index.ts b/packages/eve/src/eve-channel/index.ts
index 9108d2d23..1f84eea76 100644
--- a/packages/eve/src/eve-channel/index.ts
+++ b/packages/eve/src/eve-channel/index.ts
@@ -59,6 +59,7 @@ import {
formatTraceContentCeiling,
} from "#shared/forwarded-trace-policy.js";
import { routeAuth } from "#public/channels/auth.js";
+import { defaultEveAudience } from "#eve-channel/audience.js";
import { mergeUploadPolicy } from "#public/channels/upload-policy.js";
import { defineChannel, DELETE, GET, HEAD, PATCH, POST, PUT } from "#public/definitions/channel.js";
import {
@@ -104,6 +105,10 @@ export function eveChannel(input: EveChannelInput): EveChannel {
return defineChannel<undefined, EveEventContext>({
cors: normalizeEveCors(input.cors),
turnPolicy: input.turnPolicy,
+ audience: (classifierInput) => {
+ const audience = input.audience ?? defaultEveAudience;
+ return typeof audience === "function" ? audience(classifierInput) : audience;
+ },
routes: [
GET(EVE_HEALTH_ROUTE_PATH, async () => healthResponse()),
HEAD(EVE_HEALTH_ROUTE_PATH, async () => healthResponse()),
@@ -295,6 +300,7 @@ export function eveChannel(input: EveChannelInput): EveChannel {
try {
handle = await createSession({
activityObserver: body.activityObserver,
+ audienceAuth: authResult,
auth: messageResult.auth,
capabilities:
body.capabilities ?? (body.mode === "task" ? undefined : { requestInput: true }),
diff --git a/packages/eve/src/eve-channel/types.ts b/packages/eve/src/eve-channel/types.ts
index 3e54c1042..68b02bbfa 100644
--- a/packages/eve/src/eve-channel/types.ts
+++ b/packages/eve/src/eve-channel/types.ts
@@ -5,11 +5,13 @@ import type { TrustedForwarders } from "#channel/forwarded-principal.js";
import type { AuthFn } from "#public/channels/auth.js";
import type { UploadPolicyInput } from "#public/channels/upload-policy.js";
import type {
+ AudienceInput,
Channel,
ChannelContinuationOps,
ChannelEvents,
ChannelMethod,
} from "#public/definitions/channel.js";
+import type { ChannelAudience } from "#shared/channel-audience.js";
/**
* Event-handler channel context exposed by `eveChannel({ events })`. The default eve HTTP channel
@@ -94,6 +96,20 @@ export interface EveChannelInput {
* the next; exhaustion (including the empty array) rejects with 401. Include `none()` last for anonymous traffic.
*/
readonly auth: AuthFn<Request> | readonly AuthFn<Request>[];
+ /**
+ * Conversation audience classification, fixed when the session is created.
+ *
+ * By default, anonymous callers are `public` and `user`, `service`, or
+ * `runtime` principals are `private`. Every other principal type is
+ * `unknown`, which trace consumers treat as non-public.
+ *
+ * Pass a constant audience, or a function receiving the authenticated
+ * principal, channel, run mode, and deployment environment. Continuation
+ * turns from a different caller do not reclassify an existing session.
+ */
+ readonly audience?:
+ | ChannelAudience
+ | ((input: Omit<AudienceInput<undefined>, "state">) => ChannelAudience);
/**
* The trusted-forwarders policy: which transport-authenticated callers may
* assert a forwarded principal, callback-marked public trace audience, or
diff --git a/packages/eve/src/execution/coordination-dispatch-shared.ts b/packages/eve/src/execution/coordination-dispatch-shared.ts
index 8b5c83cc1..d1e43e8fa 100644
--- a/packages/eve/src/execution/coordination-dispatch-shared.ts
+++ b/packages/eve/src/execution/coordination-dispatch-shared.ts
@@ -14,6 +14,7 @@ import {
ParentSessionKey,
SandboxKey,
} from "#context/keys.js";
+import { ConversationContextKey } from "#shared/conversation-context.js";
import { ContextContainer } from "#context/container.js";
import { withContextScope } from "#context/run-step.js";
import {
@@ -82,6 +83,9 @@ export interface PreparedCoordinationDispatch<PlanEntry = DispatchPlanEntry> {
readonly bundle: CompiledBundle;
readonly capabilities: Parameters<typeof buildSubagentRunInput>[0]["capabilities"];
readonly channelMetadata: Parameters<typeof buildSubagentRunInput>[0]["channelMetadata"];
+ readonly inheritedConversation: Parameters<
+ typeof buildSubagentRunInput
+ >[0]["inheritedConversation"];
/** Number of local children sharing the parent's remaining token quota. */
readonly fanoutSize: number;
readonly initiatorAuth: Parameters<typeof buildSubagentRunInput>[0]["initiatorAuth"];
@@ -220,6 +224,7 @@ export async function prepareActionDispatch<PlanEntry>(input: {
bundle,
capabilities: ctx.get(CapabilitiesKey),
channelMetadata: ctx.get(ChannelInstrumentationKey),
+ inheritedConversation: ctx.get(ConversationContextKey),
fanoutSize: input.fanoutSize ?? batch.localFanoutSize ?? 0,
initiatorAuth: ctx.get(InitiatorAuthKey) ?? null,
localDevRequest: ctx.get(LocalDevRequestKey),
diff --git a/packages/eve/src/execution/eve-workflow-attributes.test.ts b/packages/eve/src/execution/eve-workflow-attributes.test.ts
index 123348649..b0bc1b410 100644
--- a/packages/eve/src/execution/eve-workflow-attributes.test.ts
+++ b/packages/eve/src/execution/eve-workflow-attributes.test.ts
@@ -22,13 +22,32 @@ import {
SessionTraceSeedKey,
} from "#context/keys.js";
import { CHANNEL_CONTEXT_KEY_NAME } from "#context/key-names.js";
+import { ConversationContextKey } from "#shared/conversation-context.js";
+
+const publicConversation = {
+ audience: "public",
+ channel: { kind: "channel:slack", name: "slack" },
+ environment: "production",
+ mode: "conversation",
+ principalType: "anonymous",
+} as const;
+
+const unknownConversation = {
+ audience: "unknown",
+ channel: { kind: "http" },
+ environment: "production",
+ mode: "conversation",
+ principalType: "anonymous",
+} as const;
const slackChannelCtx = {
- "eve.channel": { kind: "slack", state: { team: "T1" }, audience: "public" },
+ "eve.channel": { kind: "slack", state: { team: "T1" } },
+ [ConversationContextKey.name]: publicConversation,
} satisfies Record<string, unknown>;
const subagentChainCtx = {
- "eve.channel": { kind: "slack", state: {}, audience: "public" },
+ "eve.channel": { kind: "slack", state: {} },
+ [ConversationContextKey.name]: publicConversation,
"eve.parentSession": {
callId: "call_subagent_0",
sessionId: "wrun_parent_subagent",
@@ -62,17 +81,15 @@ describe("readScheduleId", () => {
});
describe("isWorkflowTraceContentVisible", () => {
- it("reads audience from the shared serialized channel slot", () => {
+ it("reads audience from the shared serialized conversation slot", () => {
expect(
- isWorkflowTraceContentVisible({
- [CHANNEL_CONTEXT_KEY_NAME]: { audience: "public", kind: "slack" },
- }),
+ isWorkflowTraceContentVisible({ [ConversationContextKey.name]: publicConversation }),
).toBe(true);
});
it("uses the effective decision from a forwarded trace seed", () => {
const serializedContext = {
- [CHANNEL_CONTEXT_KEY_NAME]: { audience: "unknown", kind: "http" },
+ [ConversationContextKey.name]: unknownConversation,
[SessionTraceSeedKey.name]: {
decision: { action: "record", recordInputs: true, recordOutputs: true },
forwardedTracePolicy: {
@@ -83,10 +100,7 @@ describe("isWorkflowTraceContentVisible", () => {
traceFlags: 1,
traceId: "2".repeat(32),
},
- [ChannelInstrumentationKey.name]: {
- kind: "eve",
- metadata: { audience: "public" },
- },
+ [ChannelInstrumentationKey.name]: { kind: "eve", metadata: {} },
};
expect(isWorkflowTraceContentVisible(serializedContext)).toBe(true);
@@ -143,11 +157,8 @@ describe("isWorkflowTraceContentVisible", () => {
it("does not infer forwarded acceptance from projected metadata", () => {
const serializedContext = {
- [CHANNEL_CONTEXT_KEY_NAME]: { audience: "unknown", kind: "http" },
- [ChannelInstrumentationKey.name]: {
- kind: "eve",
- metadata: { audience: "public" },
- },
+ [ConversationContextKey.name]: unknownConversation,
+ [ChannelInstrumentationKey.name]: { kind: "eve", metadata: {} },
};
expect(isWorkflowTraceContentVisible(serializedContext)).toBe(false);
@@ -332,12 +343,12 @@ describe("buildSessionAttributes", () => {
expect(attrs["$eve.title"]).toBe("private prompt");
});
- it("allows unknown session content during local eve dev", () => {
- vi.stubEnv("EVE_DEV", "1");
-
+ it("allows unknown session content in development", () => {
const attrs = buildSessionAttributes({
inputMessage: "local prompt",
- serializedContext: {},
+ serializedContext: {
+ [ConversationContextKey.name]: { ...unknownConversation, environment: "development" },
+ },
});
expect(attrs["$eve.is_trace_content_visible"]).toBe(true);
diff --git a/packages/eve/src/execution/eve-workflow-attributes.ts b/packages/eve/src/execution/eve-workflow-attributes.ts
index 0a2d17bc9..ad089fe29 100644
--- a/packages/eve/src/execution/eve-workflow-attributes.ts
+++ b/packages/eve/src/execution/eve-workflow-attributes.ts
@@ -44,7 +44,10 @@ import {
import type { EveAttributeValue } from "#runtime/attributes/normalize.js";
import { isNonEmptyString } from "#shared/guards.js";
import { shouldCaptureInstrumentationContent } from "#shared/instrumentation-content.js";
-import { normalizeChannelAudience } from "#shared/channel-audience.js";
+import {
+ ConversationContextKey,
+ normalizeConversationContext,
+} from "#shared/conversation-context.js";
import { isSampledTrace } from "#tracing/sampled-trace.js";
import { resolveForwardedTraceSeed } from "#shared/forwarded-trace-policy.js";
@@ -63,7 +66,6 @@ export interface SessionIdentitySummary {
/** Untyped channel adapter snapshot as it survives serialization. */
interface SerializedChannelAdapter {
readonly kind?: unknown;
- readonly audience?: unknown;
}
/** Untyped session parent snapshot as it survives serialization. */
@@ -111,10 +113,11 @@ export function isWorkflowTraceContentVisible(serializedContext: Record<string,
return decision?.action === "record" && decision.recordInputs && decision.recordOutputs;
}
}
- const channel = serializedContext[CHANNEL_CONTEXT_KEY_NAME] as
- | SerializedChannelAdapter
- | undefined;
- return shouldCaptureInstrumentationContent(normalizeChannelAudience(channel?.audience));
+ const conversation = normalizeConversationContext(serializedContext[ConversationContextKey.name]);
+ return shouldCaptureInstrumentationContent({
+ audience: conversation?.audience ?? "unknown",
+ environment: conversation?.environment ?? "production",
+ });
}
export function isWorkflowOtelTraceEnabled(serializedContext: Record<string, unknown>): boolean {
diff --git a/packages/eve/src/execution/runtime-context.test.ts b/packages/eve/src/execution/runtime-context.test.ts
index 94799a58f..9a8283df9 100644
--- a/packages/eve/src/execution/runtime-context.test.ts
+++ b/packages/eve/src/execution/runtime-context.test.ts
@@ -14,6 +14,7 @@ import {
} from "#context/keys.js";
import { setChannelContext } from "#execution/channel-context.js";
import { buildRunContext } from "#execution/runtime-context.js";
+import { ConversationContextKey } from "#shared/conversation-context.js";
function createTestSession(
input: { readonly auth?: SessionAuthContext | null; readonly parent?: Session["parent"] } = {},
@@ -272,10 +273,17 @@ describe("buildRunContext", () => {
expect(ctx.get(ActivityObserverKey)).toEqual({ sink, workIdentity });
});
- it("grafts parent metadata onto the child's own kind", () => {
+ it("grafts parent custom metadata and inherits the conversation audience", () => {
const parentProjection = {
kind: "channel:slack",
- metadata: { audience: "public" as const, threadTs: "1234.5678", userId: "U123" },
+ metadata: { threadTs: "1234.5678", userId: "U123" },
+ };
+ const inheritedConversation = {
+ audience: "public" as const,
+ channel: { kind: "channel:slack" as const, name: "slack" },
+ environment: "production" as const,
+ mode: "conversation" as const,
+ principalType: "user",
};
const ctx = buildRunContext({
bundle: createMinimalBundle(),
@@ -283,6 +291,7 @@ describe("buildRunContext", () => {
auth: null,
adapter: { kind: "subagent" },
channelMetadata: parentProjection,
+ inheritedConversation,
continuationToken: "t",
input: { message: "hi" },
mode: "task",
@@ -291,18 +300,16 @@ describe("buildRunContext", () => {
const result = ctx.get(ChannelInstrumentationKey)!;
expect(result.kind).toBe("subagent");
- expect(result.metadata).toEqual({
- audience: "public",
- threadTs: "1234.5678",
- userId: "U123",
+ expect(result.metadata).toEqual({ threadTs: "1234.5678", userId: "U123" });
+ expect(ctx.get(ConversationContextKey)).toEqual({
+ ...inheritedConversation,
+ channel: { kind: "subagent", name: undefined },
+ mode: "task",
+ principalType: "anonymous",
});
setChannelContext(ctx, { kind: "subagent", state: { persisted: true } });
- expect(ctx.get(ChannelInstrumentationKey)?.metadata).toEqual({
- audience: "public",
- threadTs: "1234.5678",
- userId: "U123",
- });
+ expect(ctx.get(ChannelInstrumentationKey)?.metadata).toEqual(parentProjection.metadata);
});
it("uses the adapter's own projection when channelMetadata is not provided", () => {
@@ -320,7 +327,7 @@ describe("buildRunContext", () => {
const projection = ctx.get(ChannelInstrumentationKey);
expect(projection).toBeDefined();
expect(projection!.kind).toBe("http");
- expect(projection!.metadata).toEqual({ audience: "unknown" });
+ expect(projection!.metadata).toEqual({});
});
it("keeps forwarded origin policy separate from inherited channel metadata", () => {
@@ -333,7 +340,7 @@ describe("buildRunContext", () => {
run: {
auth: null,
adapter: { kind: "eve" },
- channelMetadata: { kind: "eve", metadata: { audience: "unknown" } },
+ channelMetadata: { kind: "eve", metadata: {} },
input: { message: "hi" },
mode: "task",
parentTraceContext: {
@@ -346,6 +353,6 @@ describe("buildRunContext", () => {
});
expect(ctx.get(ParentTraceContextKey)?.forwardedTracePolicy).toEqual(forwardedTracePolicy);
- expect(ctx.get(ChannelInstrumentationKey)?.metadata.audience).toBe("unknown");
+ expect(ctx.get(ConversationContextKey)?.audience).toBe("private");
});
});
diff --git a/packages/eve/src/execution/runtime-context.ts b/packages/eve/src/execution/runtime-context.ts
index 5db3bf0b7..de782ecca 100644
--- a/packages/eve/src/execution/runtime-context.ts
+++ b/packages/eve/src/execution/runtime-context.ts
@@ -21,6 +21,9 @@ import {
import { BundleKey, type CompiledBundle } from "#runtime/sessions/runtime-context-keys.js";
import type { DynamicSubagentAgentConfig } from "#runtime/subagents/dynamic-agent-config.js";
import { readConversationId } from "#tracing/conversation-context.js";
+import { buildConversationContext } from "#channel/conversation-context.js";
+import { ConversationContextKey } from "#shared/conversation-context.js";
+import { resolveInstrumentationEnvironment } from "#internal/application/dev-environment.js";
/**
* Builds the bootstrap {@link ContextContainer} for one run.
@@ -38,6 +41,10 @@ export function buildRunContext(input: {
ctx.set(BundleKey, bundle);
setChannelContext(ctx, run.adapter, { channelName: run.channelName });
+ ctx.set(
+ ConversationContextKey,
+ buildConversationContext(run, resolveInstrumentationEnvironment()),
+ );
if (run.channelMetadata !== undefined) {
const existing = ctx.get(ChannelInstrumentationKey);
diff --git a/packages/eve/src/execution/tools/subagent/invoke-step.ts b/packages/eve/src/execution/tools/subagent/invoke-step.ts
index e4bf66a1b..fd3b17f4c 100644
--- a/packages/eve/src/execution/tools/subagent/invoke-step.ts
+++ b/packages/eve/src/execution/tools/subagent/invoke-step.ts
@@ -109,7 +109,7 @@ export async function dispatchAgentInvocation(input: {
}
const invocationAction = entry.kind === "start" ? entry.target.action : entry.action;
const tracing = prepareAgentInvocationTrace({
- channelMetadata: prepared.channelMetadata,
+ conversation: prepared.inheritedConversation,
invocation: invocationAction,
ownerId: input.ownerId,
serializedContext: prepared.serializedContext,
@@ -240,6 +240,7 @@ export async function dispatchAgentInvocation(input: {
callbackBaseUrl: input.callbackBaseUrl,
capabilities: prepared.capabilities,
channelMetadata: prepared.channelMetadata,
+ inheritedConversation: prepared.inheritedConversation,
currentSession: session,
fanoutSize: prepared.fanoutSize,
initiatorAuth: prepared.initiatorAuth,
diff --git a/packages/eve/src/execution/tools/subagent/start.ts b/packages/eve/src/execution/tools/subagent/start.ts
index 9b80d1f8a..8f3eb9cd3 100644
--- a/packages/eve/src/execution/tools/subagent/start.ts
+++ b/packages/eve/src/execution/tools/subagent/start.ts
@@ -37,6 +37,9 @@ export async function startSubagent(input: {
readonly callbackBaseUrl: string | undefined;
readonly capabilities: Parameters<typeof buildSubagentRunInput>[0]["capabilities"];
readonly channelMetadata: Parameters<typeof buildSubagentRunInput>[0]["channelMetadata"];
+ readonly inheritedConversation?: Parameters<
+ typeof buildSubagentRunInput
+ >[0]["inheritedConversation"];
readonly currentSession: RuntimeSession;
readonly fanoutSize: number;
readonly initiatorAuth: Parameters<typeof buildSubagentRunInput>[0]["initiatorAuth"];
@@ -75,6 +78,7 @@ export async function startSubagent(input: {
bundle: input.bundle,
capabilities: input.capabilities,
channelMetadata: input.channelMetadata,
+ inheritedConversation: input.inheritedConversation,
currentSession: input.currentSession,
dynamicSubagentAgentConfig: input.target.dynamicSubagentAgentConfig,
fanoutSize: input.fanoutSize,
diff --git a/packages/eve/src/execution/workflow-entry.integration.test.ts b/packages/eve/src/execution/workflow-entry.integration.test.ts
index f02759124..f0734c96f 100644
--- a/packages/eve/src/execution/workflow-entry.integration.test.ts
+++ b/packages/eve/src/execution/workflow-entry.integration.test.ts
@@ -28,6 +28,7 @@ import type {
import type { ResolvedToolDefinition } from "#runtime/types.js";
import { toInputSchema } from "#tools/schema.js";
import { defineHook } from "#public/definitions/hook.js";
+import { ConversationContextKey } from "#shared/conversation-context.js";
function buildSerializedContext(overrides: {
acceptedDeploymentId?: string;
@@ -47,19 +48,25 @@ function buildSerializedContext(overrides: {
};
};
}): Record<string, unknown> {
- const channel: { kind: unknown; state: unknown; audience?: unknown } = {
+ const channel: { kind: unknown; state: unknown } = {
kind: overrides.channelKind,
state: overrides.channelState ?? {},
};
- if (overrides.audience !== undefined) {
- channel.audience = overrides.audience;
- }
const context: Record<string, unknown> = {
"eve.auth": overrides.auth ?? null,
"eve.bundle": { source: createBundledRuntimeCompiledArtifactsSource() },
"eve.channel": channel,
"eve.mode": overrides.mode,
};
+ if (overrides.audience !== undefined) {
+ context[ConversationContextKey.name] = {
+ audience: overrides.audience,
+ channel: { kind: overrides.channelKind },
+ environment: "production",
+ mode: overrides.mode,
+ principalType: "anonymous",
+ };
+ }
if (overrides.acceptedDeploymentId !== undefined) {
context["eve.channelDelivery"] = {
acceptedDeploymentId: overrides.acceptedDeploymentId,
diff --git a/packages/eve/src/execution/workflow-runtime.test.ts b/packages/eve/src/execution/workflow-runtime.test.ts
index 7d802a3be..3ae31f71b 100644
--- a/packages/eve/src/execution/workflow-runtime.test.ts
+++ b/packages/eve/src/execution/workflow-runtime.test.ts
@@ -27,6 +27,7 @@ import { AgentSpanIdGenerator } from "#tracing/agent-span-id-generator.js";
import type { RuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";
import { getCompiledRuntimeAgentBundle } from "#runtime/sessions/compiled-agent-cache.js";
import { markAgentTraceContext } from "#tracing/agent-trace-context.js";
+import type { TraceCaptureContext } from "#shared/trace-policy.js";
const getHookByTokenMock = vi.fn();
const getRawHookByTokenMock = vi.fn();
@@ -945,7 +946,10 @@ describe("createWorkflowRuntime#createSession", () => {
});
describe("createWorkflowRuntime#createSession trace seed allocation", () => {
- const adapter: ChannelAdapter = { kind: "http" };
+ const adapter: ChannelAdapter = {
+ kind: "http",
+ instrumentation: { audience: () => "public" },
+ };
function buildRuntime() {
return createWorkflowRuntime({ compiledArtifactsSource: {} as RuntimeCompiledArtifactsSource });
@@ -1009,7 +1013,7 @@ describe("createWorkflowRuntime#createSession trace seed allocation", () => {
await buildRuntime().createSession({
adapter,
auth: null,
- channelMetadata: { kind: "http", metadata: { audience: "public" } },
+ channelMetadata: { kind: "http", metadata: {} },
input: { message: "hello" },
mode: "conversation",
});
@@ -1032,15 +1036,15 @@ describe("createWorkflowRuntime#createSession trace seed allocation", () => {
expect(tracePolicy).toHaveBeenCalledOnce();
});
- it("passes the channel adapter kind as channelType to the policy", async () => {
+ it("passes the conversation channel to the policy", async () => {
const idGenerator = new AgentSpanIdGenerator();
- let captured: { channelType?: string } | undefined;
+ let captured: TraceCaptureContext | undefined;
registerInstrumentationRuntime({
forceFlush: async () => undefined,
hooks: undefined as never,
idGenerator,
otelSettings: {
- tracePolicy: (trace: { channelType?: string }) => {
+ tracePolicy: (trace: TraceCaptureContext) => {
captured = trace;
return true;
},
@@ -1058,12 +1062,12 @@ describe("createWorkflowRuntime#createSession trace seed allocation", () => {
await buildRuntime().createSession({
adapter: { kind: "slack" },
auth: null,
- channelMetadata: { kind: "slack", metadata: { audience: "public" } },
+ channelMetadata: { kind: "slack", metadata: {} },
input: { message: "hello" },
mode: "conversation",
});
- expect(captured?.channelType).toBe("slack");
+ expect(captured?.channel.kind).toBe("channel:slack");
});
it("allocates an unsampled trace seed when the policy is unsampled", async () => {
diff --git a/packages/eve/src/execution/workflow-steps.test.ts b/packages/eve/src/execution/workflow-steps.test.ts
index 196bd5481..04bc83e98 100644
--- a/packages/eve/src/execution/workflow-steps.test.ts
+++ b/packages/eve/src/execution/workflow-steps.test.ts
@@ -60,6 +60,7 @@ import { resolveEffectiveOutputSchema } from "#execution/effective-output-schema
import { turnStep } from "#execution/workflow-steps.js";
import { routeProxiedDeliverStep } from "#execution/proxied-deliver-step.js";
import { turnWorkflowReference } from "#execution/workflow-runtime.js";
+import { ConversationContextKey } from "#shared/conversation-context.js";
const bindSessionInstrumentationSpy = vi.hoisted(() => vi.fn());
vi.mock("#instrumentation/runtime.js", async (importOriginal) => {
@@ -851,6 +852,13 @@ describe("dispatchTurnStep", () => {
it("lets the development world retain its stamped generation", async () => {
vi.stubEnv("EVE_DEV", "1");
const input = createTurnInput();
+ input.serializedContext[ConversationContextKey.name] = {
+ audience: "unknown",
+ channel: { kind: "http" },
+ environment: "development",
+ mode: "conversation",
+ principalType: "anonymous",
+ };
startMock.mockResolvedValue({ runId: "turn-run" });
await expect(dispatchTurnStep(input)).resolves.toEqual({ runId: "turn-run" });
@@ -3467,9 +3475,7 @@ describe("runProxySubagentEventStep", () => {
},
});
expect(result.serializedContext[ChannelInstrumentationKey.name]).toMatchObject({
- metadata: {
- audience: "unknown",
- },
+ metadata: {},
});
// And the parent session's proxy-entry map is reflected on the
diff --git a/packages/eve/src/harness/tool-loop.test.ts b/packages/eve/src/harness/tool-loop.test.ts
index 0e1337a5f..4ae54858f 100644
--- a/packages/eve/src/harness/tool-loop.test.ts
+++ b/packages/eve/src/harness/tool-loop.test.ts
@@ -50,6 +50,11 @@ import type { DynamicResolveContext } from "#dynamic/definition.js";
import { registerDurableDynamicCallback } from "#tools/durable-callbacks.js";
import type { RunMode } from "#shared/run-mode.js";
import type { ChannelAudience } from "#shared/channel-audience.js";
+import {
+ ConversationContextKey,
+ type ConversationEnvironment,
+ type ConversationContext,
+} from "#shared/conversation-context.js";
import type { InstrumentationDecision } from "#shared/instrumentation-decision.js";
import { compactMessages, shouldCompact } from "#harness/compaction.js";
import {
@@ -146,6 +151,7 @@ vi.mock("#instrumentation/ai-sdk-telemetry.js", () => ({
}));
let declaredAudience: ChannelAudience = "unknown";
+let declaredEnvironment: ConversationEnvironment = "production";
let declaredDecision: InstrumentationDecision | undefined;
let declaredInstrumentation: SessionInstrumentation | undefined;
let declaredRuntime: InstrumentationRuntime | undefined;
@@ -153,12 +159,10 @@ let declaredRuntime: InstrumentationRuntime | undefined;
function createInstrumentationContext(
decision: InstrumentationDecision | undefined,
audience: ChannelAudience,
+ environment: ConversationEnvironment = "production",
): ContextContainer {
const ctx = new ContextContainer();
- ctx.set(ChannelInstrumentationKey, {
- kind: "channel:test",
- metadata: { audience },
- });
+ setConversationContext(ctx, audience, "channel:test", {}, environment);
if (decision !== undefined) {
ctx.set(SessionTraceSeedKey, {
decision,
@@ -170,14 +174,33 @@ function createInstrumentationContext(
return ctx;
}
+function setConversationContext(
+ ctx: ContextContainer,
+ audience: ChannelAudience,
+ kind: ConversationContext["channel"]["kind"],
+ metadata: Readonly<Record<string, unknown>> = {},
+ environment: ConversationEnvironment = "production",
+): void {
+ ctx.set(ChannelInstrumentationKey, { kind, metadata });
+ ctx.set(ConversationContextKey, {
+ audience,
+ channel: { kind, name: "test" },
+ environment,
+ mode: "conversation",
+ principalType: "anonymous",
+ });
+}
+
function declareTelemetry(
config:
| (Readonly<Record<string, unknown>> & { readonly events?: InstrumentationEvents })
| undefined,
decision?: InstrumentationDecision,
audience: ChannelAudience = "unknown",
+ environment: ConversationEnvironment = "production",
): void {
declaredAudience = audience;
+ declaredEnvironment = environment;
declaredDecision = decision;
declaredRuntime =
config === undefined
@@ -195,7 +218,7 @@ function declareTelemetry(
};
declaredInstrumentation = bindInstrumentationRuntime(
declaredRuntime,
- createInstrumentationContext(decision, audience),
+ createInstrumentationContext(decision, audience, environment),
{
agentName: "test-agent",
rootSessionId: "test-session",
@@ -226,6 +249,7 @@ function bindHookInstrumentation(
createInstrumentationContext(
useDeclaredRuntime ? declaredDecision : undefined,
useDeclaredRuntime ? declaredAudience : "unknown",
+ useDeclaredRuntime ? declaredEnvironment : "production",
),
{ agentName: "test-agent", rootSessionId: "test-session", sessionId: "test-session" },
)!.prepareExecution();
@@ -5288,10 +5312,7 @@ describe("createToolLoopHarness", () => {
const { emit, events } = createEventCollector();
const runStep = createToolLoopHarness({ ...config, handleEvent: emit });
const ctx = new ContextContainer();
- ctx.set(ChannelInstrumentationKey, {
- kind: "channel:public",
- metadata: { audience: "public" },
- });
+ setConversationContext(ctx, "public", "channel:public");
const result = await contextStorage.run(ctx, () => runStep(session, { message: "Hi" }));
// The second agent was constructed for the retry.
@@ -11455,10 +11476,7 @@ describe("createToolLoopHarness", () => {
}),
);
const ctx = new ContextContainer();
- ctx.set(ChannelInstrumentationKey, {
- kind: "channel:private",
- metadata: { audience: "private" },
- });
+ setConversationContext(ctx, "private", "channel:private");
await contextStorage.run(ctx, () => runStep(createTestSession(), { message: "private" }));
@@ -11540,10 +11558,7 @@ describe("createToolLoopHarness", () => {
);
const runStep = createToolLoopHarness(createTestConfig());
const ctx = new ContextContainer();
- ctx.set(ChannelInstrumentationKey, {
- kind: "channel:public",
- metadata: { audience: "public" },
- });
+ setConversationContext(ctx, "public", "channel:public");
await contextStorage.run(ctx, () => runStep(createTestSession(), { message: "hello" }));
@@ -11582,10 +11597,7 @@ describe("createToolLoopHarness", () => {
);
const runStep = createToolLoopHarness(createTestConfig());
const ctx = new ContextContainer();
- ctx.set(ChannelInstrumentationKey, {
- kind: "channel:public",
- metadata: { audience: "public" },
- });
+ setConversationContext(ctx, "public", "channel:public");
await contextStorage.run(ctx, () => runStep(createTestSession(), { message: "hello" }));
@@ -11839,10 +11851,7 @@ describe("createToolLoopHarness", () => {
);
const ctx = new ContextContainer();
- ctx.set(ChannelInstrumentationKey, {
- kind: "channel:public",
- metadata: { audience: "public" },
- });
+ setConversationContext(ctx, "public", "channel:public");
await contextStorage.run(ctx, () => runStep(createTestSession(), { message: "hi" }));
const bridge = mockCreateAiSdkHookBridge.mock.results[0]!.value;
@@ -11882,8 +11891,7 @@ describe("createToolLoopHarness", () => {
});
});
- it("keeps unknown model telemetry content in a local development worker", async () => {
- vi.stubEnv("EVE_DEV", "1");
+ it("keeps unknown model telemetry content in development", async () => {
setupMockAgent({
finishReason: "stop",
response: { messages: [{ content: "Hello!", role: "assistant" }] },
@@ -11891,11 +11899,16 @@ describe("createToolLoopHarness", () => {
toolCalls: [],
toolResults: [],
});
- declareTelemetry({
- recordInputs: true,
- recordOutputs: true,
- tracePolicy: () => true,
- });
+ declareTelemetry(
+ {
+ recordInputs: true,
+ recordOutputs: true,
+ tracePolicy: () => true,
+ },
+ undefined,
+ "unknown",
+ "development",
+ );
const runStep = createToolLoopHarness(createTestConfig("conversation"));
await runStep(createTestSession(), { message: "hi" });
@@ -11951,12 +11964,8 @@ describe("createToolLoopHarness", () => {
);
const ctx = new ContextContainer();
- ctx.set(ChannelInstrumentationKey, {
- kind: "channel:support",
- metadata: {
- audience: "public",
- triggeringUserId: "U123",
- },
+ setConversationContext(ctx, "public", "channel:support", {
+ triggeringUserId: "U123",
});
const hidden = {
diff --git a/packages/eve/src/instrumentation/ai-sdk-hook-bridge.test.ts b/packages/eve/src/instrumentation/ai-sdk-hook-bridge.test.ts
index 6d3223902..0a3d14775 100644
--- a/packages/eve/src/instrumentation/ai-sdk-hook-bridge.test.ts
+++ b/packages/eve/src/instrumentation/ai-sdk-hook-bridge.test.ts
@@ -23,13 +23,19 @@ const scope: InstrumentationAttemptScope = {
turnId: "turn-1",
};
+const traceContext = (audience: "public" | "private" | "unknown" = "unknown") => ({
+ agentName: "test-agent",
+ audience,
+ channel: { kind: "http" as const },
+ environment: "production" as const,
+ mode: "conversation" as const,
+ principalType: "anonymous",
+});
+
function createInstrumentationHooks(
...args: Parameters<typeof createUnboundInstrumentationHooks>
): ReturnType<typeof createUnboundInstrumentationHooks> {
- return createUnboundInstrumentationHooks(...args).forTrace!({
- agentName: "test-agent",
- audience: "unknown",
- });
+ return createUnboundInstrumentationHooks(...args).forTrace!(traceContext());
}
describe("createAiSdkHookBridge", () => {
diff --git a/packages/eve/src/instrumentation/channel-delivery.test.ts b/packages/eve/src/instrumentation/channel-delivery.test.ts
index 50e645312..77f3b35b9 100644
--- a/packages/eve/src/instrumentation/channel-delivery.test.ts
+++ b/packages/eve/src/instrumentation/channel-delivery.test.ts
@@ -10,6 +10,22 @@ import {
bindInstrumentationRuntime,
type InstrumentationRuntime,
} from "#instrumentation/runtime.js";
+import { ConversationContextKey, type ConversationContext } from "#shared/conversation-context.js";
+
+function setConversation(
+ ctx: ContextContainer,
+ audience: "public" | "private",
+ kind: ConversationContext["channel"]["kind"] = "channel:slack",
+): void {
+ ctx.set(ChannelInstrumentationKey, { kind, metadata: {} });
+ ctx.set(ConversationContextKey, {
+ audience,
+ channel: { kind, name: "slack" },
+ environment: "production",
+ mode: "conversation",
+ principalType: "anonymous",
+ });
+}
function bindHooks(
hooks: InstrumentationRuntime["hooks"],
@@ -60,10 +76,7 @@ describe("channel delivery instrumentation", () => {
traceFlags: 1,
traceId: "11111111111111111111111111111111",
};
- ctx.set(ChannelInstrumentationKey, {
- kind: "channel:slack",
- metadata: { audience: "public" },
- });
+ setConversation(ctx, "public");
ctx.set(ParentTraceContextKey, parentTraceContext);
const instrumentation = bindHooks(hooks, ctx);
@@ -115,10 +128,7 @@ describe("channel delivery instrumentation", () => {
},
]);
const ctx = new ContextContainer();
- ctx.set(ChannelInstrumentationKey, {
- kind: "channel:slack",
- metadata: { audience: "private" },
- });
+ setConversation(ctx, "private");
const instrumentation = bindHooks(hooks, ctx);
await contextStorage.run(ctx, () =>
instrumentation?.instrumentChannelDelivery({
@@ -156,11 +166,7 @@ describe("channel delivery instrumentation", () => {
},
]);
const ctx = new ContextContainer();
- ctx.set(ChannelInstrumentationKey, {
- channelType: "slack",
- kind: "channel:slack",
- metadata: { audience: "public" },
- });
+ setConversation(ctx, "public");
const instrumentation = bindHooks(hooks, ctx, "Weather Display Name");
await contextStorage.run(ctx, async () => {
@@ -184,11 +190,7 @@ describe("channel delivery instrumentation", () => {
sessionId: "session-1",
turnId: "turn_0",
});
- ctx.set(ChannelInstrumentationKey, {
- channelType: "slack",
- kind: "channel:slack",
- metadata: { audience: "private" },
- });
+ setConversation(ctx, "private");
await instrumentation?.instrumentChannelDelivery({
ctx,
includeTurn: true,
@@ -201,7 +203,10 @@ describe("channel delivery instrumentation", () => {
expect(tracePolicy.mock.calls[0]?.[0]).toEqual({
agentName: "Weather Display Name",
audience: "public",
- channelType: "slack",
+ channel: { kind: "channel:slack", name: "slack" },
+ environment: "production",
+ mode: "conversation",
+ principalType: "anonymous",
});
});
});
diff --git a/packages/eve/src/instrumentation/channel-delivery.ts b/packages/eve/src/instrumentation/channel-delivery.ts
index 5fa4a1b0d..a44eac4ca 100644
--- a/packages/eve/src/instrumentation/channel-delivery.ts
+++ b/packages/eve/src/instrumentation/channel-delivery.ts
@@ -13,7 +13,10 @@ import type {
InstrumentationHooks,
} from "#instrumentation/lifecycle.js";
import { channelDeliveryIdempotencyKey } from "#instrumentation/lifecycle.js";
-import { normalizeChannelAudience } from "#shared/channel-audience.js";
+import {
+ ConversationContextKey,
+ UNKNOWN_CONVERSATION_CONTEXT,
+} from "#shared/conversation-context.js";
export interface ChannelDeliveryStartInstrumentation {
readonly agentName?: string;
@@ -47,11 +50,12 @@ export async function instrumentChannelDelivery(
for (const item of active) {
const policyAgentName = item.policyAgentName ?? item.agentName;
if (policyAgentName === undefined) continue;
+ const conversation = input.ctx.get(ConversationContextKey) ?? UNKNOWN_CONVERSATION_CONTEXT;
const hooks =
input.hooks.forTrace?.({
agentName: policyAgentName,
- audience: normalizeChannelAudience(item.delivery.channelAudience),
- channelType: item.channelType,
+ ...conversation,
+ audience: item.delivery.channelAudience ?? conversation.audience,
}) ?? input.hooks;
await hooks.publish({
agentName: item.agentName,
@@ -74,13 +78,12 @@ export async function instrumentChannelDelivery(
if (input.hooks === undefined || input.delivery.deliveryMetadata === undefined) return;
const active: ActiveChannelDelivery[] = [];
- const channel = input.ctx.get(ChannelInstrumentationKey);
- const channelAudience = normalizeChannelAudience(channel?.metadata.audience);
+ const conversation = input.ctx.get(ConversationContextKey) ?? UNKNOWN_CONVERSATION_CONTEXT;
+ const channelAudience = conversation.audience;
const hooks =
input.hooks.forTrace?.({
agentName: input.policyAgentName,
- audience: channelAudience,
- channelType: channel?.channelType,
+ ...conversation,
}) ?? input.hooks;
for (const metadata of input.delivery.deliveryMetadata) {
const payload = input.delivery.payloads[metadata.payloadIndex];
@@ -97,7 +100,7 @@ export async function instrumentChannelDelivery(
!capturesInputs || payload === undefined ? undefined : projectDeliveryInput(payload);
const item: ActiveChannelDelivery = {
agentName: input.agentName,
- channelType: channel?.channelType,
+ channelType: input.ctx.get(ChannelInstrumentationKey)?.channelType,
delivery,
policyAgentName: input.policyAgentName,
rootSessionId: input.rootSessionId,
diff --git a/packages/eve/src/instrumentation/content-policy.test.ts b/packages/eve/src/instrumentation/content-policy.test.ts
index b9322f7b5..736f360b7 100644
--- a/packages/eve/src/instrumentation/content-policy.test.ts
+++ b/packages/eve/src/instrumentation/content-policy.test.ts
@@ -17,13 +17,18 @@ const event: InstrumentationEvent = {
type: "model.call.started",
};
+const contentContext = (
+ audience: "public" | "private" | "unknown",
+ environment: "development" | "preview" | "production" = "production",
+) => ({ audience, environment });
+
describe("instrumentationEventForTraceDecision", () => {
it("applies directional OTel content decisions", () => {
expect(
instrumentationEventForTraceDecision(
event,
{ action: "record", recordInputs: false, recordOutputs: true },
- "public",
+ contentContext("public"),
),
).toMatchObject({ input: undefined });
});
@@ -42,7 +47,7 @@ describe("instrumentationEventForTraceDecision", () => {
type: "input.requested",
},
decision,
- "public",
+ contentContext("public"),
),
).toMatchObject({ request: { prompt: "Approve weather?" } });
expect(
@@ -57,7 +62,7 @@ describe("instrumentationEventForTraceDecision", () => {
type: "input.resolved",
},
decision,
- "public",
+ contentContext("public"),
),
).toMatchObject({ response: undefined });
});
@@ -67,7 +72,7 @@ describe("instrumentationEventForTraceDecision", () => {
instrumentationEventForTraceDecision(
event,
{ action: "record", recordInputs: true, recordOutputs: true },
- "private",
+ contentContext("private"),
),
).toMatchObject({ input: undefined });
});
@@ -77,15 +82,15 @@ describe("instrumentationEventForTraceDecision", () => {
instrumentationEventForTraceDecision(
event,
{ action: "record", recordInputs: true, recordOutputs: false },
- "private",
+ contentContext("private"),
{ applyAudienceCeiling: false },
),
).toMatchObject({ input: { instructions: "private prompt" } });
});
it("removes content from dropped OTel traces", () => {
- expect(instrumentationEventForTraceDecision(event, { action: "drop" }, "public")).toMatchObject(
- { input: undefined },
- );
+ expect(
+ instrumentationEventForTraceDecision(event, { action: "drop" }, contentContext("public")),
+ ).toMatchObject({ input: undefined });
});
});
diff --git a/packages/eve/src/instrumentation/content-policy.ts b/packages/eve/src/instrumentation/content-policy.ts
index 80695d849..4a4a64af4 100644
--- a/packages/eve/src/instrumentation/content-policy.ts
+++ b/packages/eve/src/instrumentation/content-policy.ts
@@ -3,19 +3,21 @@ import {
withoutInstrumentationContent,
} from "#instrumentation/content.js";
import type { InstrumentationEvent } from "#instrumentation/lifecycle.js";
-import type { ChannelAudience } from "#shared/channel-audience.js";
-import { applyAudienceCeiling } from "#shared/instrumentation-content.js";
+import {
+ applyAudienceCeiling,
+ type InstrumentationContentContext,
+} from "#shared/instrumentation-content.js";
import type { InstrumentationDecision } from "#shared/instrumentation-decision.js";
/** Applies OpenTelemetry's trace content ceiling to one OTel provider event. */
export function instrumentationEventForTraceDecision(
event: InstrumentationEvent,
decision: InstrumentationDecision,
- audience: ChannelAudience,
+ content: InstrumentationContentContext,
options: { readonly applyAudienceCeiling?: boolean } = {},
): InstrumentationEvent {
const effective =
- options.applyAudienceCeiling === false ? decision : applyAudienceCeiling(decision, audience);
+ options.applyAudienceCeiling === false ? decision : applyAudienceCeiling(decision, content);
return effective.action === "drop"
? withoutInstrumentationContent(event)
: withInstrumentationDecision(event, effective);
diff --git a/packages/eve/src/instrumentation/eve-channel-audience-production.scenario.test.ts b/packages/eve/src/instrumentation/eve-channel-audience-production.scenario.test.ts
new file mode 100644
index 000000000..32ebbb8c3
--- /dev/null
+++ b/packages/eve/src/instrumentation/eve-channel-audience-production.scenario.test.ts
@@ -0,0 +1,113 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import { isCompiledChannel } from "#channel/compiled-channel.js";
+import type { RunInput, SessionAuthContext } from "#channel/types.js";
+import { eveChannel } from "#eve-channel/index.js";
+import {
+ modelCallIdempotencyKey,
+ sessionIdempotencyKey,
+ type InstrumentationEvent,
+} from "#instrumentation/lifecycle.js";
+import {
+ finalizeInstrumentationProviders,
+ registerInstrumentationProvider,
+ seedInstrumentationProviders,
+} from "#instrumentation/providers.js";
+import { none } from "#public/channels/auth.js";
+import { defineInstrumentation } from "#public/instrumentation/index.js";
+import { buildConversationContext } from "#channel/conversation-context.js";
+
+afterEach(() => {
+ vi.unstubAllEnvs();
+});
+
+describe("eve channel production audience", () => {
+ it("classifies callers and captures content only for public sessions", async () => {
+ vi.stubEnv("EVE_DEV_WORKER_APP_ROOT", undefined);
+ vi.stubEnv("VERCEL_ENV", "production");
+
+ const events: InstrumentationEvent[] = [];
+ seedInstrumentationProviders();
+ await registerInstrumentationProvider({
+ agentName: "weather",
+ slot: "audit",
+ value: defineInstrumentation({
+ events: {
+ "model.call.started": (event) => {
+ events.push(event);
+ },
+ "session.started": (event) => {
+ events.push(event);
+ },
+ },
+ }),
+ });
+ const runtime = finalizeInstrumentationProviders({ serviceName: "weather" });
+ const channel = eveChannel({ auth: none() });
+ if (!isCompiledChannel(channel)) throw new Error("Expected a compiled eve channel.");
+
+ const user: SessionAuthContext = {
+ attributes: {},
+ authenticator: "test",
+ principalId: "user-1",
+ principalType: "user",
+ };
+ const conversationFor = (auth: SessionAuthContext | null) =>
+ buildConversationContext(
+ {
+ adapter: channel.adapter,
+ auth,
+ input: { message: "private message" },
+ mode: "conversation",
+ } satisfies RunInput,
+ "production",
+ );
+
+ for (const conversation of [conversationFor(null), conversationFor(user)]) {
+ const hooks = runtime.hooks.forTrace!({ agentName: "weather", ...conversation });
+ await hooks.publish({
+ channelAudience: conversation.audience,
+ channelKind: conversation.channel.kind,
+ idempotencyKey: sessionIdempotencyKey(`session-${conversation.audience}`),
+ rootSessionId: `session-${conversation.audience}`,
+ sessionId: `session-${conversation.audience}`,
+ type: "session.started",
+ });
+ await hooks.publish({
+ idempotencyKey: modelCallIdempotencyKey(
+ {
+ attemptId: `session-${conversation.audience}:turn-1:0:0`,
+ attemptIndex: 0,
+ sessionId: `session-${conversation.audience}`,
+ stepIndex: 0,
+ turnId: "turn-1",
+ },
+ 0,
+ ),
+ input: { instructions: "private instructions", messages: [] },
+ model: { modelId: "test", provider: "test" },
+ scope: {
+ attemptId: `session-${conversation.audience}:turn-1:0:0`,
+ attemptIndex: 0,
+ channelAudience: conversation.audience,
+ sessionId: `session-${conversation.audience}`,
+ stepIndex: 0,
+ turnId: "turn-1",
+ },
+ type: "model.call.started",
+ });
+ }
+
+ expect(events).toHaveLength(4);
+ expect(events[0]).toMatchObject({ channelAudience: "public", type: "session.started" });
+ expect(events[1]).toMatchObject({
+ input: { instructions: "private instructions" },
+ type: "model.call.started",
+ });
+ expect(events[2]).toMatchObject({ channelAudience: "private", type: "session.started" });
+ expect(events[3]).toMatchObject({ input: undefined, type: "model.call.started" });
+
+ await runtime.forceFlush();
+ await runtime.shutdown();
+ });
+});
diff --git a/packages/eve/src/instrumentation/lifecycle.test.ts b/packages/eve/src/instrumentation/lifecycle.test.ts
index 1e9344fcd..8d85104c3 100644
--- a/packages/eve/src/instrumentation/lifecycle.test.ts
+++ b/packages/eve/src/instrumentation/lifecycle.test.ts
@@ -26,6 +26,19 @@ import {
} from "#instrumentation/state.js";
const { logDebug, logWarn } = vi.hoisted(() => ({ logDebug: vi.fn(), logWarn: vi.fn() }));
+
+const traceContext = (
+ agentName = "test-agent",
+ audience: "public" | "private" | "unknown" = "unknown",
+) => ({
+ agentName,
+ audience,
+ channel: { kind: "http" as const },
+ environment: "production" as const,
+ mode: "conversation" as const,
+ principalType: "anonymous",
+});
+
vi.mock("#internal/logging.js", () => ({
createLogger: () => ({ debug: logDebug, warn: logWarn }),
formatError: (error: unknown) => error,
@@ -34,10 +47,7 @@ vi.mock("#internal/logging.js", () => ({
function createInstrumentationHooks(
...args: Parameters<typeof createUnboundInstrumentationHooks>
): ReturnType<typeof createUnboundInstrumentationHooks> {
- return createUnboundInstrumentationHooks(...args).forTrace!({
- agentName: "test-agent",
- audience: "unknown",
- });
+ return createUnboundInstrumentationHooks(...args).forTrace!(traceContext());
}
const scope: InstrumentationAttemptScope = {
@@ -886,12 +896,8 @@ describe("trace policies", () => {
it("defaults provider content to the audience-aware policy", () => {
const hooks = createInstrumentationHooks([{ name: "provider" }]);
- expect(hooks.forTrace?.({ agentName: "weather", audience: "public" }).capturesContent).toBe(
- true,
- );
- expect(hooks.forTrace?.({ agentName: "weather", audience: "private" }).capturesContent).toBe(
- false,
- );
+ expect(hooks.forTrace?.(traceContext("weather", "public")).capturesContent).toBe(true);
+ expect(hooks.forTrace?.(traceContext("weather", "private")).capturesContent).toBe(false);
});
it("passes trace context to each provider policy", () => {
@@ -901,11 +907,7 @@ describe("trace policies", () => {
recordOutputs: false,
}));
const hooks = createInstrumentationHooks([{ name: "provider", tracePolicy }]);
- const trace = {
- agentName: "weather",
- audience: "private" as const,
- channelType: "slack",
- };
+ const trace = traceContext("weather", "private");
tracePolicy.mockClear();
expect(hooks.forTrace?.(trace).capturesContent).toBe(true);
@@ -943,7 +945,7 @@ describe("trace policies", () => {
name: "private-audit",
tracePolicy: () => ({ emit: true, recordInputs: true, recordOutputs: false }),
},
- ]).forTrace!({ agentName: "weather", audience: "private" });
+ ]).forTrace!(traceContext("weather", "private"));
await hooks.publish({
callId: "call-1",
@@ -976,7 +978,7 @@ describe("trace policies", () => {
name: "outputs",
tracePolicy: () => ({ emit: true, recordInputs: false, recordOutputs: true }),
},
- ]).forTrace!({ agentName: "weather", audience: "public" });
+ ]).forTrace!(traceContext("weather", "public"));
await hooks.publish({
idempotencyKey: "model-1",
@@ -1018,7 +1020,7 @@ describe("trace policies", () => {
name: "inputs-only",
tracePolicy: () => ({ emit: true, recordInputs: true, recordOutputs: false }),
},
- ]).forTrace!({ agentName: "weather", audience: "public" });
+ ]).forTrace!(traceContext("weather", "public"));
await hooks.publish({
error,
@@ -1053,10 +1055,8 @@ describe("trace policies", () => {
]).capturesContent,
).toBe(false);
expect(
- createInstrumentationHooks([{ name: "quiet" }]).forTrace!({
- agentName: "weather",
- audience: "private",
- }).capturesContent,
+ createInstrumentationHooks([{ name: "quiet" }]).forTrace!(traceContext("weather", "private"))
+ .capturesContent,
).toBe(false);
expect(
createInstrumentationHooks([
@@ -1068,7 +1068,7 @@ describe("trace policies", () => {
name: "also-quiet",
tracePolicy: () => ({ emit: true, recordInputs: false, recordOutputs: false }),
},
- ]).forTrace!({ agentName: "weather", audience: "public" }).capturesContent,
+ ]).forTrace!(traceContext("weather", "public")).capturesContent,
).toBe(false);
expect(
createInstrumentationHooks([
@@ -1077,7 +1077,7 @@ describe("trace policies", () => {
name: "loud",
tracePolicy: () => ({ emit: true, recordInputs: true, recordOutputs: true }),
},
- ]).forTrace!({ agentName: "weather", audience: "public" }).capturesContent,
+ ]).forTrace!(traceContext("weather", "public")).capturesContent,
).toBe(true);
expect(
createInstrumentationHooks({
@@ -1087,7 +1087,7 @@ describe("trace policies", () => {
tracePolicy: () => ({ emit: true, recordInputs: true, recordOutputs: true }),
},
],
- }).forTrace!({ agentName: "weather", audience: "public" }).capturesContent,
+ }).forTrace!(traceContext("weather", "public")).capturesContent,
).toBe(true);
});
@@ -1099,7 +1099,7 @@ describe("trace policies", () => {
name: "dropped",
tracePolicy: () => false,
},
- ]).forTrace!({ agentName: "weather", audience: "public" });
+ ]).forTrace!(traceContext("weather", "public"));
await hooks.publish({
idempotencyKey: turnIdempotencyKey("session-1", "turn-1"),
@@ -1130,8 +1130,8 @@ describe("trace policies", () => {
tracePolicy: () => ({ emit: true, recordInputs: false, recordOutputs: false }),
},
]);
- const hooks = unboundHooks.forTrace!({ agentName: "weather", audience: "public" });
- unboundHooks.forTrace!({ agentName: "weather", audience: "private" });
+ const hooks = unboundHooks.forTrace!(traceContext("weather", "public"));
+ unboundHooks.forTrace!(traceContext("weather", "private"));
await hooks.publish({
idempotencyKey: turnIdempotencyKey("session-1", "turn-1"),
@@ -1165,7 +1165,7 @@ describe("trace policies", () => {
events: { "step.attempt.metadata": wantsContent },
name: "content",
},
- ]).forTrace!({ agentName: "weather", audience: "private" });
+ ]).forTrace!(traceContext("weather", "private"));
const providerMetadata = {
gateway: {
cost: "0.01",
@@ -1204,7 +1204,7 @@ describe("trace policies", () => {
name: "content",
tracePolicy: () => ({ emit: true, recordInputs: true, recordOutputs: true }),
},
- ]).forTrace!({ agentName: "weather", audience: "private" });
+ ]).forTrace!(traceContext("weather", "private"));
const error = { output: "private tool output", requestBody: "private request" };
const actionScope = { ...scope };
@@ -1271,7 +1271,7 @@ describe("trace policies", () => {
},
name: "content",
},
- ]).forTrace!({ agentName: "weather", audience: "private" });
+ ]).forTrace!(traceContext("weather", "private"));
const idempotencyKey = inputIdempotencyKey(scope.sessionId, scope.turnId, "request-1");
await hooks.publish({
@@ -1323,7 +1323,7 @@ describe("trace policies", () => {
name: "content",
},
],
- }).forTrace!({ agentName: "weather", audience: "private" });
+ }).forTrace!(traceContext("weather", "private"));
const event = {
idempotencyKey: toolCallIdempotencyKey(scope, "call-1", 0),
diff --git a/packages/eve/src/instrumentation/principal-summary.test.ts b/packages/eve/src/instrumentation/principal-summary.test.ts
index 569c75190..6d68014c4 100644
--- a/packages/eve/src/instrumentation/principal-summary.test.ts
+++ b/packages/eve/src/instrumentation/principal-summary.test.ts
@@ -11,6 +11,11 @@ const principal = {
subject: "secret-subject",
};
+const contentContext = (
+ audience: "public" | "private" | "unknown",
+ environment: "development" | "preview" | "production" = "production",
+) => ({ audience, environment });
+
describe("summarizeInstrumentationPrincipal", () => {
afterEach(() => {
vi.unstubAllEnvs();
@@ -18,7 +23,9 @@ describe("summarizeInstrumentationPrincipal", () => {
it("omits oversized IDs without truncating or changing authentication records", () => {
const oversized = { ...principal, principalId: "x".repeat(1025) };
- expect(summarizeInstrumentationPrincipal(oversized, "public")).toEqual({ type: "other" });
+ expect(summarizeInstrumentationPrincipal(oversized, contentContext("public"))).toEqual({
+ type: "other",
+ });
expect(oversized.principalId).toHaveLength(1025);
expect(
summarizeInstrumentationPrincipal(
@@ -26,48 +33,54 @@ describe("summarizeInstrumentationPrincipal", () => {
...principal,
principalId: String.fromCodePoint(0x1f600).repeat(300),
},
- "public",
+ contentContext("public"),
),
).toEqual({ type: "other" });
});
it("preserves none and bounds authored principal types", () => {
- expect(summarizeInstrumentationPrincipal(null, "public")).toEqual({
+ expect(summarizeInstrumentationPrincipal(null, contentContext("public"))).toEqual({
type: "none",
});
- expect(summarizeInstrumentationPrincipal(undefined, "public")).toBeUndefined();
- expect(summarizeInstrumentationPrincipal(principal, "public")).toEqual({
+ expect(summarizeInstrumentationPrincipal(undefined, contentContext("public"))).toBeUndefined();
+ expect(summarizeInstrumentationPrincipal(principal, contentContext("public"))).toEqual({
id: "secret-user-id",
type: "other",
});
expect(
- summarizeInstrumentationPrincipal({ ...principal, principalType: "runtime" }, "public"),
+ summarizeInstrumentationPrincipal(
+ { ...principal, principalType: "runtime" },
+ contentContext("public"),
+ ),
).toEqual({ id: "secret-user-id", type: "runtime" });
expect(
- summarizeInstrumentationPrincipal({ ...principal, principalType: "unknown" }, "public"),
+ summarizeInstrumentationPrincipal(
+ { ...principal, principalType: "unknown" },
+ contentContext("public"),
+ ),
).toEqual({ id: "secret-user-id", type: "unknown" });
});
it("omits IDs when the audience is not content-visible", () => {
- expect(summarizeInstrumentationPrincipal(principal, "private")).toEqual({
+ expect(summarizeInstrumentationPrincipal(principal, contentContext("private"))).toEqual({
type: "other",
});
- expect(summarizeInstrumentationPrincipal(principal, "unknown")).toEqual({
+ expect(summarizeInstrumentationPrincipal(principal, contentContext("unknown"))).toEqual({
type: "other",
});
});
- it("follows the existing local-development rule for unknown audiences", () => {
- vi.stubEnv("EVE_DEV", "1");
-
- expect(summarizeInstrumentationPrincipal(principal, "unknown")).toEqual({
+ it("follows the explicit development rule for unknown audiences", () => {
+ expect(
+ summarizeInstrumentationPrincipal(principal, contentContext("unknown", "development")),
+ ).toEqual({
id: "secret-user-id",
type: "other",
});
});
it("never includes claims or principal attributes", () => {
- const summary = summarizeInstrumentationPrincipal(principal, "public");
+ const summary = summarizeInstrumentationPrincipal(principal, contentContext("public"));
expect(summary).not.toHaveProperty("attributes");
expect(summary).not.toHaveProperty("issuer");
diff --git a/packages/eve/src/instrumentation/principal-summary.ts b/packages/eve/src/instrumentation/principal-summary.ts
index fddf15385..6cba63e4e 100644
--- a/packages/eve/src/instrumentation/principal-summary.ts
+++ b/packages/eve/src/instrumentation/principal-summary.ts
@@ -5,15 +5,17 @@ import {
isInstrumentationPrincipalType,
type InstrumentationPrincipalSummary,
} from "#instrumentation/lifecycle.js";
-import type { ChannelAudience } from "#shared/channel-audience.js";
-import { shouldCaptureInstrumentationContent } from "#shared/instrumentation-content.js";
+import {
+ shouldCaptureInstrumentationContent,
+ type InstrumentationContentContext,
+} from "#shared/instrumentation-content.js";
import type { InstrumentationDecision } from "#shared/instrumentation-decision.js";
import { resolveTracePolicyDecision } from "#shared/trace-policy.js";
import { boundedPrincipalId } from "#tracing/telemetry-budget.js";
export function summarizeInstrumentationPrincipal(
principal: SessionAuthContext | null | undefined,
- audience: ChannelAudience,
+ content: InstrumentationContentContext,
): InstrumentationPrincipalSummary | undefined {
if (principal === undefined) return undefined;
if (principal === null) return { type: "none" };
@@ -21,7 +23,7 @@ export function summarizeInstrumentationPrincipal(
isInstrumentationPrincipalType(principal.principalType) && principal.principalType !== "none"
? principal.principalType
: "other";
- const id = shouldCaptureInstrumentationContent(audience)
+ const id = shouldCaptureInstrumentationContent(content)
? boundedPrincipalId(principal.principalId)
: undefined;
return id === undefined ? { type } : { id, type };
@@ -42,19 +44,19 @@ export function applyPrincipalTraceDecision(
export function readInstrumentationPrincipals(
context: ContextReader,
- audience: ChannelAudience,
- decision: InstrumentationDecision = resolveTracePolicyDecision(true, audience),
+ content: InstrumentationContentContext,
+ decision: InstrumentationDecision = resolveTracePolicyDecision(true, content),
): {
readonly currentPrincipal?: InstrumentationPrincipalSummary;
readonly initiatorPrincipal?: InstrumentationPrincipalSummary;
} {
return {
currentPrincipal: applyPrincipalTraceDecision(
- summarizeInstrumentationPrincipal(context.get(AuthKey), audience),
+ summarizeInstrumentationPrincipal(context.get(AuthKey), content),
decision,
),
initiatorPrincipal: applyPrincipalTraceDecision(
- summarizeInstrumentationPrincipal(context.get(InitiatorAuthKey), audience),
+ summarizeInstrumentationPrincipal(context.get(InitiatorAuthKey), content),
decision,
),
};
diff --git a/packages/eve/src/instrumentation/providers-otel-policy.test.ts b/packages/eve/src/instrumentation/providers-otel-policy.test.ts
index 39d2fa49d..88e4a87aa 100644
--- a/packages/eve/src/instrumentation/providers-otel-policy.test.ts
+++ b/packages/eve/src/instrumentation/providers-otel-policy.test.ts
@@ -24,6 +24,15 @@ vi.mock("#tracing/otel-registration.js", () => ({
const REGISTRY_GLOBAL_KEY = Symbol.for("eve.harness-instrumentation-providers");
const RUNTIME_GLOBAL_KEY = Symbol.for("eve.instrumentation-runtime");
+const traceContext = (audience: "public" | "private" | "unknown") => ({
+ agentName: "weather-agent",
+ audience,
+ channel: { kind: "http" as const },
+ environment: "production" as const,
+ mode: "conversation" as const,
+ principalType: "anonymous",
+});
+
describe("otel and authored provider composition", () => {
beforeEach(() => {
delete (globalThis as Record<symbol, unknown>)[REGISTRY_GLOBAL_KEY];
@@ -51,10 +60,7 @@ describe("otel and authored provider composition", () => {
}),
});
const runtime = finalizeInstrumentationProviders({ serviceName: "weather-agent" });
- const hooks = runtime.hooks.forTrace!({
- agentName: "weather-agent",
- audience: "private",
- });
+ const hooks = runtime.hooks.forTrace!(traceContext("private"));
await contextStorage.run(new ContextContainer(), () =>
hooks.publish({
diff --git a/packages/eve/src/instrumentation/providers.integration.test.ts b/packages/eve/src/instrumentation/providers.integration.test.ts
index ae30e6000..54ca00ce4 100644
--- a/packages/eve/src/instrumentation/providers.integration.test.ts
+++ b/packages/eve/src/instrumentation/providers.integration.test.ts
@@ -10,6 +10,15 @@ import { defineInstrumentation } from "#public/instrumentation/index.js";
const REGISTRY_GLOBAL_KEY = Symbol.for("eve.harness-instrumentation-providers");
const RUNTIME_GLOBAL_KEY = Symbol.for("eve.instrumentation-runtime");
+const traceContext = (audience: "public" | "private" | "unknown") => ({
+ agentName: "weather",
+ audience,
+ channel: { kind: "http" as const },
+ environment: "production" as const,
+ mode: "conversation" as const,
+ principalType: "anonymous",
+});
+
function deferred(): { readonly promise: Promise<void>; readonly resolve: () => void } {
let resolve!: () => void;
const promise = new Promise<void>((complete) => {
@@ -69,7 +78,7 @@ describe("authored instrumentation provider dispatch", () => {
expect(order).toEqual(["first:setup", "first:setup-complete", "second:setup"]);
const runtime = finalizeInstrumentationProviders({ serviceName: "weather" });
- const hooks = runtime.hooks.forTrace!({ agentName: "weather", audience: "unknown" });
+ const hooks = runtime.hooks.forTrace!(traceContext("unknown"));
const publication = hooks.publish({
idempotencyKey: turnIdempotencyKey("session-1", "turn-1"),
rootSessionId: "session-1",
diff --git a/packages/eve/src/instrumentation/providers.test.ts b/packages/eve/src/instrumentation/providers.test.ts
index eadcfa6ef..a0b284a6f 100644
--- a/packages/eve/src/instrumentation/providers.test.ts
+++ b/packages/eve/src/instrumentation/providers.test.ts
@@ -23,6 +23,15 @@ import {
const REGISTRY_GLOBAL_KEY = Symbol.for("eve.harness-instrumentation-providers");
const RUNTIME_GLOBAL_KEY = Symbol.for("eve.instrumentation-runtime");
+const traceContext = (audience: "public" | "private" | "unknown") => ({
+ agentName: "weather",
+ audience,
+ channel: { kind: "http" as const },
+ environment: "production" as const,
+ mode: "conversation" as const,
+ principalType: "anonymous",
+});
+
function register(slot: string, value: unknown): Promise<void> {
return registerInstrumentationProvider({ agentName: "weather-agent", slot, value });
}
@@ -217,9 +226,7 @@ describe("finalizeInstrumentationProviders", () => {
await register("rows", defineInstrumentation({ events: { "turn.started": started } }));
const runtime = finalizeInstrumentationProviders({ serviceName: "weather-agent" });
- await runtime.hooks.forTrace!({ agentName: "weather-agent", audience: "unknown" }).publish(
- turnStarted,
- );
+ await runtime.hooks.forTrace!(traceContext("unknown")).publish(turnStarted);
expect(runtime.instrumentationProviders).toBe(true);
expect(started).toHaveBeenCalledOnce();
@@ -236,9 +243,7 @@ describe("finalizeInstrumentationProviders", () => {
const runtime = finalizeInstrumentationProviders({ serviceName: "weather-agent" });
- expect(
- runtime.hooks.forTrace?.({ agentName: "weather", audience: "private" }).capturesContent,
- ).toBe(expected);
+ expect(runtime.hooks.forTrace?.(traceContext("private")).capturesContent).toBe(expected);
},
);
@@ -253,9 +258,7 @@ describe("finalizeInstrumentationProviders", () => {
const runtime = finalizeInstrumentationProviders({ serviceName: "weather-agent" });
- expect(
- runtime.hooks.forTrace?.({ agentName: "weather", audience: "private" }).capturesContent,
- ).toBe(true);
+ expect(runtime.hooks.forTrace?.(traceContext("private")).capturesContent).toBe(true);
});
it("still runs execution when no destination was declared", async () => {
diff --git a/packages/eve/src/instrumentation/runtime-global.ts b/packages/eve/src/instrumentation/runtime-global.ts
new file mode 100644
index 000000000..4db1d2d8f
--- /dev/null
+++ b/packages/eve/src/instrumentation/runtime-global.ts
@@ -0,0 +1,27 @@
+import type { InstrumentationRuntime } from "#instrumentation/runtime.js";
+
+const INSTRUMENTATION_RUNTIME_KEY = Symbol.for("eve.instrumentation-runtime");
+
+type InstrumentationGlobal = typeof globalThis & {
+ [INSTRUMENTATION_RUNTIME_KEY]?: InstrumentationRuntime;
+};
+
+const globalRuntime = globalThis as InstrumentationGlobal;
+
+/** Registers the process instrumentation runtime before agent execution begins. */
+export function registerInstrumentationRuntime(
+ runtime: InstrumentationRuntime,
+): InstrumentationRuntime {
+ const existing = globalRuntime[INSTRUMENTATION_RUNTIME_KEY];
+ if (existing !== undefined) {
+ // A legacy config may reload without taking ownership from the installed runtime.
+ existing.otelSettings = runtime.otelSettings;
+ return existing;
+ }
+ globalRuntime[INSTRUMENTATION_RUNTIME_KEY] = runtime;
+ return runtime;
+}
+
+export function getInstrumentationRuntime(): InstrumentationRuntime | undefined {
+ return globalRuntime[INSTRUMENTATION_RUNTIME_KEY];
+}
diff --git a/packages/eve/src/instrumentation/runtime.test.ts b/packages/eve/src/instrumentation/runtime.test.ts
index 1241220c2..9648d0585 100644
--- a/packages/eve/src/instrumentation/runtime.test.ts
+++ b/packages/eve/src/instrumentation/runtime.test.ts
@@ -27,6 +27,7 @@ import { AgentSpanIdGenerator } from "#tracing/agent-span-id-generator.js";
import { ContextAgentTraceStateStore } from "#tracing/agent-trace-context-store.js";
import type { TraceCapturePolicy } from "#tracing/otel-declaration.js";
import { readForwardedAudienceBaggage, writeForwardedAudienceBaggage } from "#protocol/baggage.js";
+import { ConversationContextKey } from "#shared/conversation-context.js";
const boundSession = {
agentName: "test-agent",
@@ -56,7 +57,14 @@ function createContext(audience: "private" | "public" | "unknown" = "public"): C
const ctx = new ContextContainer();
ctx.set(ChannelInstrumentationKey, {
kind: "channel:test",
- metadata: { audience },
+ metadata: {},
+ });
+ ctx.set(ConversationContextKey, {
+ audience,
+ channel: { kind: "channel:test", name: "test" },
+ environment: "production",
+ mode: "conversation",
+ principalType: "anonymous",
});
return ctx;
}
@@ -156,22 +164,17 @@ describe("initializeSessionInstrumentation", () => {
] as const)(
"applies the live %s delivery audience independently from a public origin",
async (deliveryAudience, recordsContent) => {
- const ctx = initializeRemoteSession(() => true);
- ctx.set(ChannelInstrumentationKey, {
- kind: "channel:test",
- metadata: { audience: deliveryAudience },
- });
+ const ctx = initializeRemoteSession(() => true, { liveAudience: deliveryAudience });
- expect(
- await readTelemetry(
- bindSessionInstrumentation({
- agentName: "remote-agent",
- ctx,
- rootSessionId: "session-1",
- sessionId: "session-1",
- }),
- ),
- ).toMatchObject({
+ const telemetry = await readTelemetry(
+ bindSessionInstrumentation({
+ agentName: "remote-agent",
+ ctx,
+ rootSessionId: "session-1",
+ sessionId: "session-1",
+ }),
+ );
+ expect(telemetry).toMatchObject({
recordInputs: recordsContent,
recordOutputs: recordsContent,
});
@@ -378,7 +381,7 @@ describe("bindInstrumentationRuntime", () => {
expect(ctx.get(ConversationIdKey)).toBe("original-conversation");
});
- it("reads the channel audience when the step runs", async () => {
+ it("keeps the durable audience when projection metadata changes", async () => {
const ctx = createContext("public");
const instrumentation = bindInstrumentationRuntime(
createRuntime({ capturesContent: true, publish: vi.fn() }),
@@ -392,8 +395,8 @@ describe("bindInstrumentationRuntime", () => {
});
expect(await readTelemetry(instrumentation)).toMatchObject({
- recordInputs: false,
- recordOutputs: false,
+ recordInputs: true,
+ recordOutputs: true,
});
});
@@ -401,11 +404,6 @@ describe("bindInstrumentationRuntime", () => {
const boundHooks: InstrumentationHooks = { capturesContent: false, publish: vi.fn() };
const forTrace = vi.fn(() => boundHooks);
const ctx = createContext("private");
- ctx.set(ChannelInstrumentationKey, {
- channelType: "slack",
- kind: "channel:test",
- metadata: { audience: "private" },
- });
const instrumentation = bindInstrumentationRuntime(
createRuntime({ capturesContent: false, forTrace, publish: vi.fn() }),
ctx,
@@ -417,7 +415,10 @@ describe("bindInstrumentationRuntime", () => {
expect(forTrace).toHaveBeenCalledExactlyOnceWith({
agentName: "Weather Display Name",
audience: "private",
- channelType: "slack",
+ channel: { kind: "channel:test", name: "test" },
+ environment: "production",
+ mode: "conversation",
+ principalType: "anonymous",
});
});
@@ -689,6 +690,13 @@ describe("bindInstrumentationRuntime", () => {
kind: "channel:test",
metadata: { audience: "public" },
});
+ ctx.set(ConversationContextKey, {
+ audience: "public",
+ channel: { kind: "channel:test", name: "test" },
+ environment: "production",
+ mode: "conversation",
+ principalType: "anonymous",
+ });
const second = instrumentation?.runStep(stepInput, async (scope) => readScopedState(scope));
releaseFirst();
@@ -798,7 +806,7 @@ describe("bindInstrumentationRuntime", () => {
setChannelContext(ctx, { kind: "subagent", state: { persisted: true } });
- expect(ctx.get(ChannelInstrumentationKey)?.metadata.audience).toBe("public");
+ expect(ctx.get(ConversationContextKey)?.audience).toBe("public");
expect(
await readTelemetry(
bindInstrumentationRuntime(
diff --git a/packages/eve/src/instrumentation/runtime.ts b/packages/eve/src/instrumentation/runtime.ts
index cb495d667..ac3a69c39 100644
--- a/packages/eve/src/instrumentation/runtime.ts
+++ b/packages/eve/src/instrumentation/runtime.ts
@@ -40,29 +40,21 @@ import {
type ChannelDeliveryStartInstrumentation,
type ChannelDeliveryTerminalInstrumentation,
} from "#instrumentation/channel-delivery.js";
-import { createLogger, recordErrorOnSpan } from "#internal/logging.js";
+import { recordErrorOnSpan } from "#internal/logging.js";
import {
prepareTurnTraceContext,
type PrepareTurnTraceContextInput,
} from "#instrumentation/prepare-trace-context.js";
import type { RuntimeTraceContext } from "#protocol/message.js";
-import { AgentSpanIdGenerator } from "#tracing/agent-span-id-generator.js";
import type { OtelHarnessSettings, RuntimeContextResolver } from "#tracing/otel-declaration.js";
-import type { SessionTraceSeed } from "#context/keys.js";
+import { AgentSpanIdGenerator } from "#tracing/agent-span-id-generator.js";
import { contextStorage, type ContextContainer } from "#context/container.js";
import {
createMemoryInstrumentation,
type MemoryInstrumentation,
} from "#instrumentation/memory.js";
-import {
- ChannelInstrumentationKey,
- ConversationIdKey,
- OtelTraceEnabledKey,
- ParentSessionKey,
- ParentTraceContextKey,
- SessionTraceSeedKey,
-} from "#context/keys.js";
-import { normalizeChannelAudience } from "#shared/channel-audience.js";
+import { ConversationIdKey, ParentSessionKey } from "#context/keys.js";
+import type { ConversationContext } from "#shared/conversation-context.js";
import { withErrorContent } from "#tracing/error-content-context.js";
import type { AgentSamplingOperation } from "#tracing/agent-span-contract.js";
import {
@@ -71,24 +63,20 @@ import {
resolveTracePolicyDecision,
} from "#tracing/sampled-trace.js";
import { readInstrumentationSessionContext } from "#instrumentation/session-context.js";
-import type { ChannelInstrumentationProjection, SessionTraceContext } from "#channel/types.js";
import { readSessionTraceDecision } from "#tracing/agent-trace-context-store.js";
-import {
- intersectInstrumentationDecisions,
- readInstrumentationDecision,
-} from "#shared/instrumentation-decision.js";
-import {
- applyLiveDeliveryAudienceCeiling,
- formatTraceContentCeiling,
- type ForwardedTraceAssertion,
- readForwardedTraceAssertion,
- traceContentCeilingToDecision,
-} from "#shared/forwarded-trace-policy.js";
+import { readInstrumentationDecision } from "#shared/instrumentation-decision.js";
+import { applyLiveDeliveryAudienceCeiling } from "#shared/forwarded-trace-policy.js";
import { readConversationId } from "#tracing/conversation-context.js";
+import {
+ getInstrumentationRuntime,
+ registerInstrumentationRuntime,
+} from "#instrumentation/runtime-global.js";
+import { initializeSessionInstrumentation } from "#instrumentation/session-init.js";
-const INSTRUMENTATION_RUNTIME_KEY = Symbol.for("eve.instrumentation-runtime");
+export { getInstrumentationRuntime, registerInstrumentationRuntime };
+export { initializeSessionInstrumentation };
const TURN_TRACE_STATE_KEY = "eve.harness.turnTrace";
-const log = createLogger("instrumentation.runtime");
+import type { SessionTraceSeed } from "#context/keys.js";
interface InstrumentedStepSession {
readonly sessionId: string;
@@ -220,12 +208,10 @@ export function bindInstrumentationRuntime(
const readSessionContext = () =>
readInstrumentationSessionContext(contextStorage.getStore() ?? ctx);
const bindHooks = (sessionContext: ReturnType<typeof readSessionContext>) => {
- const channel = sessionContext.instrumentation;
return (
baseHooks.forTrace?.({
agentName: boundSession.agentName,
- audience: sessionContext.audience,
- channelType: channel?.channelType,
+ ...sessionContext.conversation,
}) ?? baseHooks
);
};
@@ -245,15 +231,14 @@ export function bindInstrumentationRuntime(
input: Parameters<ExecutionInstrumentation["preparePreamble"]>[0],
sessionContext: ReturnType<typeof readSessionContext>,
) => {
- const channel = sessionContext.instrumentation;
return prepareTurnTraceContext({
...input,
instrumentation: runtime,
principals: sessionContext.principals,
session: {
agentName: boundSession.agentName,
- channelAudience: sessionContext.audience,
- channelType: channel?.channelType,
+ channelAudience: sessionContext.conversation.audience,
+ channelType: sessionContext.instrumentation?.channelType,
parentLineage: sessionContext.parentLineage,
parentTraceContext: sessionContext.parentTraceContext,
rootSessionId: sessionContext.parent?.rootSessionId ?? boundSession.rootSessionId,
@@ -286,7 +271,7 @@ export function bindInstrumentationRuntime(
const decision = resolveStepInstrumentationDecision(
settings,
boundSession.agentName,
- policyContext.instrumentation,
+ policyContext.conversation,
policyContext.traceSeed,
readSessionTraceDecision(policyContext.context, boundSession.sessionId),
);
@@ -338,9 +323,9 @@ export function bindInstrumentationRuntime(
const runtimeContextSnapshot = snapshotInstrumentationRuntimeContext(
sessionContext.context,
);
- const channel = sessionContext.instrumentation;
- const audience = normalizeChannelAudience(channel?.metadata.audience);
- const capturesContent = shouldCaptureInstrumentationContent(audience);
+ const conversation = sessionContext.conversation;
+ const audience = conversation.audience;
+ const capturesContent = shouldCaptureInstrumentationContent(conversation);
const effectiveDecision =
decision === undefined
? decision
@@ -348,6 +333,7 @@ export function bindInstrumentationRuntime(
decision,
audience,
sessionContext.forwardedTracePolicy,
+ conversation.environment,
);
const capturesRuntimeContextInput =
effectiveDecision === undefined
@@ -409,7 +395,7 @@ export function bindInstrumentationRuntime(
...eventInput,
agentName: boundSession.agentName,
channelAudience: audience,
- channelKind: channel?.kind,
+ channelKind: conversation.channel.kind,
hooks,
parentLineage: sessionContext.parentLineage,
parentTraceContext: sessionContext.parentTraceContext,
@@ -536,123 +522,22 @@ export function bindSessionInstrumentation(input: {
});
}
-export function initializeSessionInstrumentation(input: {
- readonly agentName: string;
- readonly ctx: ContextContainer;
-}): void {
- const runtime = getInstrumentationRuntime();
- const channel = input.ctx.get(ChannelInstrumentationKey);
- const parentTraceContext = input.ctx.get(ParentTraceContextKey);
- const forwardedTracePolicy = readForwardedTraceAssertion(
- parentTraceContext?.forwardedTracePolicy,
- );
- const audience =
- forwardedTracePolicy?.originAudience ?? normalizeChannelAudience(channel?.metadata.audience);
- const traceSeed = allocateSessionTraceSeed({
- agentName: input.agentName,
- audience,
- channelType: channel?.channelType,
- forwardedTracePolicy,
- parentTraceContext,
- runtime,
- });
- if (traceSeed !== undefined) {
- input.ctx.set(SessionTraceSeedKey, traceSeed);
- if (forwardedTracePolicy !== undefined) {
- log.info("resolved forwarded trace policy", {
- ceilingEffective:
- traceSeed.decision?.action === "record"
- ? formatTraceContentCeiling(traceSeed.decision)
- : "drop",
- ceilingIn: formatTraceContentCeiling(forwardedTracePolicy.ceiling),
- originAudience: forwardedTracePolicy.originAudience,
- });
- }
- if (forwardedTracePolicy !== undefined && parentTraceContext !== undefined) {
- const resolvedParent = {
- ...parentTraceContext,
- decision: traceSeed.decision,
- traceFlags: traceSeed.traceFlags,
- };
- delete resolvedParent.forwardedTracePolicy;
- input.ctx.set(ParentTraceContextKey, resolvedParent);
- }
- }
- input.ctx.set(OtelTraceEnabledKey, runtime?.prepareSessionTrace !== undefined);
-}
-
-function allocateSessionTraceSeed(input: {
- readonly agentName: string;
- readonly audience: ReturnType<typeof normalizeChannelAudience>;
- readonly channelType?: string;
- readonly forwardedTracePolicy: ForwardedTraceAssertion | undefined;
- readonly parentTraceContext?: SessionTraceContext;
- readonly runtime: InstrumentationRuntime | undefined;
-}): SessionTraceSeed | undefined {
- const localDecision = () =>
- resolveTracePolicy(input.runtime?.otelSettings?.tracePolicy, {
- agentName: input.agentName,
- audience: input.audience,
- channelType: input.channelType,
- });
- if (input.parentTraceContext !== undefined) {
- const forwardedCeiling = input.forwardedTracePolicy
- ? traceContentCeilingToDecision(input.forwardedTracePolicy.ceiling)
- : undefined;
- const inheritedDecision = readInstrumentationDecision(input.parentTraceContext.decision);
- const parentDecision = !isSampledTrace(input.parentTraceContext)
- ? { action: "drop" as const }
- : forwardedCeiling
- ? inheritedDecision === undefined
- ? forwardedCeiling
- : intersectInstrumentationDecisions(forwardedCeiling, inheritedDecision)
- : (inheritedDecision ??
- resolveTracePolicyDecision(isSampledTrace(input.parentTraceContext), input.audience));
- const decision = input.forwardedTracePolicy
- ? intersectInstrumentationDecisions(parentDecision, localDecision())
- : parentDecision;
- const idGenerator = input.runtime?.idGenerator ?? new AgentSpanIdGenerator();
- return {
- decision,
- ...(input.forwardedTracePolicy === undefined
- ? undefined
- : { forwardedTracePolicy: input.forwardedTracePolicy }),
- spanId: idGenerator.allocateSpanId(),
- traceFlags: decision.action === "drop" ? 0 : input.parentTraceContext.traceFlags,
- traceId: idGenerator.generateTraceId(),
- };
- }
- if (input.runtime?.prepareSessionTrace === undefined || input.runtime.idGenerator === undefined)
- return undefined;
- const decision = localDecision();
- const traceId = input.runtime.idGenerator.generateTraceId();
- const sampled = decision.action === "record";
- return {
- decision,
- spanId: input.runtime.idGenerator.allocateSpanId(),
- traceFlags: sampled ? 1 : 0,
- traceId,
- };
-}
-
function resolveStepInstrumentationDecision(
settings: OtelHarnessSettings | undefined,
agentName: string,
- channel: ChannelInstrumentationProjection | undefined,
+ conversation: ConversationContext,
traceSeed: SessionTraceSeed | undefined,
persisted: InstrumentationDecision | undefined,
): InstrumentationDecision | undefined {
if (settings === undefined) return undefined;
if (traceSeed?.decision !== undefined) return readInstrumentationDecision(traceSeed.decision);
if (persisted !== undefined) return persisted;
- const audience = normalizeChannelAudience(channel?.metadata.audience);
if (traceSeed !== undefined) {
- return resolveTracePolicyDecision(isSampledTrace(traceSeed), audience);
+ return resolveTracePolicyDecision(isSampledTrace(traceSeed), conversation);
}
return resolveTracePolicy(settings.tracePolicy, {
agentName,
- audience,
- channelType: channel?.channelType,
+ ...conversation,
});
}
@@ -667,27 +552,3 @@ function isValidSpanContext(spanContext: {
spanContext.spanId !== "0000000000000000"
);
}
-
-type InstrumentationGlobal = typeof globalThis & {
- [INSTRUMENTATION_RUNTIME_KEY]?: InstrumentationRuntime;
-};
-
-const globalRuntime = globalThis as InstrumentationGlobal;
-
-/** Registers the process instrumentation runtime before agent execution begins. */
-export function registerInstrumentationRuntime(
- runtime: InstrumentationRuntime,
-): InstrumentationRuntime {
- const existing = globalRuntime[INSTRUMENTATION_RUNTIME_KEY];
- if (existing !== undefined) {
- // A legacy config may reload without taking ownership from the installed runtime.
- existing.otelSettings = runtime.otelSettings;
- return existing;
- }
- globalRuntime[INSTRUMENTATION_RUNTIME_KEY] = runtime;
- return runtime;
-}
-
-export function getInstrumentationRuntime(): InstrumentationRuntime | undefined {
- return globalRuntime[INSTRUMENTATION_RUNTIME_KEY];
-}
diff --git a/packages/eve/src/instrumentation/session-context.test.ts b/packages/eve/src/instrumentation/session-context.test.ts
index 155523cf4..184ef4e7a 100644
--- a/packages/eve/src/instrumentation/session-context.test.ts
+++ b/packages/eve/src/instrumentation/session-context.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, it } from "vitest";
+import { afterEach, describe, expect, it, vi } from "vitest";
import type { SessionAuthContext } from "#channel/types.js";
import { ContextContainer } from "#context/container.js";
@@ -7,8 +7,10 @@ import {
ChannelInstrumentationKey,
InitiatorAuthKey,
ParentSessionKey,
+ ModeKey,
} from "#context/keys.js";
import { readInstrumentationSessionContext } from "#instrumentation/session-context.js";
+import { ConversationContextKey } from "#shared/conversation-context.js";
const initiator: SessionAuthContext = {
attributes: { email: "[email protected]" },
@@ -24,14 +26,24 @@ const current: SessionAuthContext = {
principalType: "service",
};
+function setConversation(context: ContextContainer, audience: "public" | "private"): void {
+ context.set(ChannelInstrumentationKey, { kind: "channel:test", metadata: {} });
+ context.set(ConversationContextKey, {
+ audience,
+ channel: { kind: "channel:test", name: "test" },
+ environment: "production",
+ mode: "conversation",
+ principalType: "user",
+ });
+}
+
describe("readInstrumentationSessionContext", () => {
+ afterEach(() => vi.unstubAllEnvs());
+
it("keeps the initiator stable while the current principal changes", () => {
const context = new ContextContainer();
context.set(AuthKey, current);
- context.set(ChannelInstrumentationKey, {
- kind: "channel:test",
- metadata: { audience: "public" },
- });
+ setConversation(context, "public");
context.set(InitiatorAuthKey, initiator);
const first = readInstrumentationSessionContext(context);
@@ -49,18 +61,12 @@ describe("readInstrumentationSessionContext", () => {
it("uses the actual principal ID across a public delegated trace tree", () => {
const parent = new ContextContainer();
parent.set(AuthKey, initiator);
- parent.set(ChannelInstrumentationKey, {
- kind: "channel:test",
- metadata: { audience: "public" },
- });
+ setConversation(parent, "public");
parent.set(InitiatorAuthKey, initiator);
const child = new ContextContainer();
child.set(AuthKey, initiator);
- child.set(ChannelInstrumentationKey, {
- kind: "channel:test",
- metadata: { audience: "public" },
- });
+ setConversation(child, "public");
child.set(InitiatorAuthKey, initiator);
child.set(ParentSessionKey, {
callId: "call-1",
@@ -80,10 +86,7 @@ describe("readInstrumentationSessionContext", () => {
it("keeps private principal metadata type-only", () => {
const context = new ContextContainer();
context.set(AuthKey, current);
- context.set(ChannelInstrumentationKey, {
- kind: "channel:test",
- metadata: { audience: "private" },
- });
+ setConversation(context, "private");
context.set(InitiatorAuthKey, initiator);
expect(readInstrumentationSessionContext(context).principals).toEqual({
@@ -91,4 +94,22 @@ describe("readInstrumentationSessionContext", () => {
initiatorPrincipal: { type: "user" },
});
});
+
+ it("resolves legacy sessions consistently in development", () => {
+ vi.stubEnv("EVE_DEV", "1");
+ const context = new ContextContainer();
+ context.set(ChannelInstrumentationKey, { kind: "channel:test", metadata: {} });
+ context.set(AuthKey, current);
+ context.set(ModeKey, "task");
+
+ const { conversation } = readInstrumentationSessionContext(context);
+
+ expect(conversation).toEqual({
+ audience: "unknown",
+ channel: { kind: "channel:test", name: undefined },
+ environment: "development",
+ mode: "task",
+ principalType: "service",
+ });
+ });
});
diff --git a/packages/eve/src/instrumentation/session-context.ts b/packages/eve/src/instrumentation/session-context.ts
index 86c13ef08..6f8b1af7f 100644
--- a/packages/eve/src/instrumentation/session-context.ts
+++ b/packages/eve/src/instrumentation/session-context.ts
@@ -1,11 +1,18 @@
import type { AlsContext } from "#context/container.js";
import {
ChannelInstrumentationKey,
+ ModeKey,
ParentSessionKey,
ParentTraceContextKey,
+ AuthKey,
SessionCallbackKey,
SessionTraceSeedKey,
} from "#context/keys.js";
+import {
+ ConversationContextKey,
+ resolveConversationContext,
+} from "#shared/conversation-context.js";
+import { resolveInstrumentationEnvironment } from "#internal/application/dev-environment.js";
import { resolveParentLineage } from "#instrumentation/parent-lineage.js";
import { readInstrumentationPrincipals } from "#instrumentation/principal-summary.js";
import { ChannelKey } from "#runtime/sessions/runtime-context-keys.js";
@@ -13,7 +20,6 @@ import {
readForwardedTraceAssertion,
resolveForwardedTraceSeed,
} from "#shared/forwarded-trace-policy.js";
-import { normalizeChannelAudience } from "#shared/channel-audience.js";
export function readInstrumentationSessionContext(context: AlsContext) {
const storedTraceSeed = context.get(SessionTraceSeedKey);
@@ -25,17 +31,25 @@ export function readInstrumentationSessionContext(context: AlsContext) {
const parent = context.get(ParentSessionKey);
const channel = context.get(ChannelKey);
const instrumentation = context.get(ChannelInstrumentationKey);
- const audience = normalizeChannelAudience(instrumentation?.metadata.audience);
+ const forwardedTracePolicy = readForwardedTraceAssertion(traceSeed?.forwardedTracePolicy);
+ const conversation = resolveConversationContext(context.get(ConversationContextKey), {
+ channelKind: instrumentation?.kind,
+ environment: resolveInstrumentationEnvironment(),
+ forwardedTracePolicy,
+ mode: context.get(ModeKey),
+ principalType: context.get(AuthKey)?.principalType,
+ });
return {
- audience,
+ audience: conversation.audience,
channel,
+ conversation,
context,
- forwardedTracePolicy: readForwardedTraceAssertion(traceSeed?.forwardedTracePolicy),
+ forwardedTracePolicy,
instrumentation,
parent,
parentLineage: resolveParentLineage(parent, channel, context.get(SessionCallbackKey)),
parentTraceContext: context.get(ParentTraceContextKey),
- principals: readInstrumentationPrincipals(context, audience, traceSeed?.decision),
+ principals: readInstrumentationPrincipals(context, conversation, traceSeed?.decision),
traceSeed,
};
}
diff --git a/packages/eve/src/instrumentation/session-init.test.ts b/packages/eve/src/instrumentation/session-init.test.ts
new file mode 100644
index 000000000..294fac7ba
--- /dev/null
+++ b/packages/eve/src/instrumentation/session-init.test.ts
@@ -0,0 +1,56 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import { ContextContainer } from "#context/container.js";
+import { AuthKey, ChannelInstrumentationKey, ModeKey, SessionTraceSeedKey } from "#context/keys.js";
+import { initializeSessionInstrumentation } from "#instrumentation/session-init.js";
+import { registerInstrumentationRuntime } from "#instrumentation/runtime-global.js";
+import type { InstrumentationRuntime } from "#instrumentation/runtime.js";
+import { AgentSpanIdGenerator } from "#tracing/agent-span-id-generator.js";
+import type { TraceCapturePolicy } from "#tracing/otel-declaration.js";
+
+afterEach(() => {
+ vi.unstubAllEnvs();
+ delete (globalThis as Record<symbol, unknown>)[Symbol.for("eve.instrumentation-runtime")];
+});
+
+function createRuntime(tracePolicy: TraceCapturePolicy): InstrumentationRuntime {
+ return {
+ forceFlush: async () => undefined,
+ hooks: { capturesContent: true, publish: async () => undefined },
+ otelSettings: {
+ recordInputs: true,
+ recordOutputs: true,
+ tracePolicy,
+ traceChannelRequests: false,
+ },
+ runInContext: (_operation, execute) => execute(),
+ shutdown: async () => undefined,
+ };
+}
+
+describe("initializeSessionInstrumentation", () => {
+ it("reconstructs a legacy conversation from session context", () => {
+ vi.stubEnv("EVE_DEV", "1");
+ registerInstrumentationRuntime({
+ ...createRuntime(
+ ({ environment, principalType }) =>
+ environment === "development" && principalType === "service",
+ ),
+ idGenerator: new AgentSpanIdGenerator(),
+ prepareSessionTrace: async () => ({ spanId: "", traceFlags: 0, traceId: "" }),
+ });
+ const ctx = new ContextContainer();
+ ctx.set(ChannelInstrumentationKey, { kind: "channel:test", metadata: {} });
+ ctx.set(AuthKey, {
+ attributes: {},
+ authenticator: "test",
+ principalId: "service-1",
+ principalType: "service",
+ });
+ ctx.set(ModeKey, "task");
+
+ initializeSessionInstrumentation({ agentName: "test-agent", ctx });
+
+ expect(ctx.get(SessionTraceSeedKey)?.decision).toMatchObject({ action: "record" });
+ });
+});
diff --git a/packages/eve/src/instrumentation/session-init.ts b/packages/eve/src/instrumentation/session-init.ts
new file mode 100644
index 000000000..70f09fe04
--- /dev/null
+++ b/packages/eve/src/instrumentation/session-init.ts
@@ -0,0 +1,145 @@
+import type { ContextContainer } from "#context/container.js";
+import {
+ AuthKey,
+ ChannelInstrumentationKey,
+ ModeKey,
+ OtelTraceEnabledKey,
+ ParentTraceContextKey,
+ SessionTraceSeedKey,
+ type SessionTraceSeed,
+} from "#context/keys.js";
+import type { SessionTraceContext } from "#channel/types.js";
+import { createLogger } from "#internal/logging.js";
+import { resolveInstrumentationEnvironment } from "#internal/application/dev-environment.js";
+import {
+ ConversationContextKey,
+ resolveConversationContext,
+ type ConversationContext,
+} from "#shared/conversation-context.js";
+import {
+ formatTraceContentCeiling,
+ readForwardedTraceAssertion,
+ type ForwardedTraceAssertion,
+ traceContentCeilingToDecision,
+} from "#shared/forwarded-trace-policy.js";
+import {
+ intersectInstrumentationDecisions,
+ readInstrumentationDecision,
+} from "#shared/instrumentation-decision.js";
+import {
+ isSampledTrace,
+ resolveTracePolicy,
+ resolveTracePolicyDecision,
+} from "#tracing/sampled-trace.js";
+import { AgentSpanIdGenerator } from "#tracing/agent-span-id-generator.js";
+import { getInstrumentationRuntime } from "#instrumentation/runtime-global.js";
+import type { InstrumentationRuntime } from "#instrumentation/runtime.js";
+
+const log = createLogger("instrumentation.session-init");
+
+export function initializeSessionInstrumentation(input: {
+ readonly agentName: string;
+ readonly ctx: ContextContainer;
+}): void {
+ const runtime = getInstrumentationRuntime();
+ const parentTraceContext = input.ctx.get(ParentTraceContextKey);
+ const forwardedTracePolicy = readForwardedTraceAssertion(
+ parentTraceContext?.forwardedTracePolicy,
+ );
+ const storedConversation = input.ctx.get(ConversationContextKey);
+ const conversation = resolveConversationContext(
+ storedConversation,
+ {
+ channelKind: input.ctx.get(ChannelInstrumentationKey)?.kind,
+ environment: resolveInstrumentationEnvironment(),
+ forwardedTracePolicy,
+ mode: input.ctx.get(ModeKey),
+ principalType: input.ctx.get(AuthKey)?.principalType,
+ },
+ { forwardedOverridesStored: true },
+ );
+ const traceSeed = allocateSessionTraceSeed({
+ agentName: input.agentName,
+ conversation,
+ channelType: input.ctx.get(ChannelInstrumentationKey)?.channelType,
+ forwardedTracePolicy,
+ parentTraceContext,
+ runtime,
+ });
+ if (traceSeed !== undefined) {
+ input.ctx.set(SessionTraceSeedKey, traceSeed);
+ if (forwardedTracePolicy !== undefined) {
+ log.info("resolved forwarded trace policy", {
+ ceilingEffective:
+ traceSeed.decision?.action === "record"
+ ? formatTraceContentCeiling(traceSeed.decision)
+ : "drop",
+ ceilingIn: formatTraceContentCeiling(forwardedTracePolicy.ceiling),
+ originAudience: forwardedTracePolicy.originAudience,
+ });
+ }
+ if (forwardedTracePolicy !== undefined && parentTraceContext !== undefined) {
+ const resolvedParent = {
+ ...parentTraceContext,
+ decision: traceSeed.decision,
+ traceFlags: traceSeed.traceFlags,
+ };
+ delete resolvedParent.forwardedTracePolicy;
+ input.ctx.set(ParentTraceContextKey, resolvedParent);
+ }
+ }
+ input.ctx.set(OtelTraceEnabledKey, runtime?.prepareSessionTrace !== undefined);
+}
+
+function allocateSessionTraceSeed(input: {
+ readonly agentName: string;
+ readonly conversation: ConversationContext;
+ readonly channelType?: string;
+ readonly forwardedTracePolicy: ForwardedTraceAssertion | undefined;
+ readonly parentTraceContext?: SessionTraceContext;
+ readonly runtime: InstrumentationRuntime | undefined;
+}): SessionTraceSeed | undefined {
+ const localDecision = () =>
+ resolveTracePolicy(input.runtime?.otelSettings?.tracePolicy, {
+ agentName: input.agentName,
+ ...input.conversation,
+ });
+ if (input.parentTraceContext !== undefined) {
+ const forwardedCeiling = input.forwardedTracePolicy
+ ? traceContentCeilingToDecision(input.forwardedTracePolicy.ceiling)
+ : undefined;
+ const inheritedDecision = readInstrumentationDecision(input.parentTraceContext.decision);
+ const parentDecision = !isSampledTrace(input.parentTraceContext)
+ ? { action: "drop" as const }
+ : forwardedCeiling
+ ? inheritedDecision === undefined
+ ? forwardedCeiling
+ : intersectInstrumentationDecisions(forwardedCeiling, inheritedDecision)
+ : (inheritedDecision ??
+ resolveTracePolicyDecision(isSampledTrace(input.parentTraceContext), input.conversation));
+ const decision = input.forwardedTracePolicy
+ ? intersectInstrumentationDecisions(parentDecision, localDecision())
+ : parentDecision;
+ const idGenerator = input.runtime?.idGenerator ?? new AgentSpanIdGenerator();
+ return {
+ decision,
+ ...(input.forwardedTracePolicy === undefined
+ ? undefined
+ : { forwardedTracePolicy: input.forwardedTracePolicy }),
+ spanId: idGenerator.allocateSpanId(),
+ traceFlags: decision.action === "drop" ? 0 : input.parentTraceContext.traceFlags,
+ traceId: idGenerator.generateTraceId(),
+ };
+ }
+ if (input.runtime?.prepareSessionTrace === undefined || input.runtime.idGenerator === undefined)
+ return undefined;
+ const decision = localDecision();
+ const traceId = input.runtime.idGenerator.generateTraceId();
+ const sampled = decision.action === "record";
+ return {
+ decision,
+ spanId: input.runtime.idGenerator.allocateSpanId(),
+ traceFlags: sampled ? 1 : 0,
+ traceId,
+ };
+}
diff --git a/packages/eve/src/instrumentation/setup-context.ts b/packages/eve/src/instrumentation/setup-context.ts
index b23dfe575..34247c404 100644
--- a/packages/eve/src/instrumentation/setup-context.ts
+++ b/packages/eve/src/instrumentation/setup-context.ts
@@ -1,5 +1,5 @@
import {
- isEveDevEnvironment,
+ resolveInstrumentationEnvironment,
resolveEveEvaluationRunId,
} from "#internal/application/dev-environment.js";
import { resolveInstalledPackageInfo } from "#internal/application/package.js";
@@ -24,8 +24,3 @@ export function createInstrumentationSetupContext(agentName: string): ProviderSe
frameworkVersion: resolveInstalledPackageInfo().version,
};
}
-
-function resolveInstrumentationEnvironment(): ProviderSetupContext["environment"] {
- if (isEveDevEnvironment() || process.env.VERCEL_ENV === "development") return "development";
- return process.env.VERCEL_ENV === "preview" ? "preview" : "production";
-}
diff --git a/packages/eve/src/internal/application/dev-environment.ts b/packages/eve/src/internal/application/dev-environment.ts
index daa2ff244..464763f23 100644
--- a/packages/eve/src/internal/application/dev-environment.ts
+++ b/packages/eve/src/internal/application/dev-environment.ts
@@ -1,11 +1,19 @@
/** Environment flag set for processes that belong to an `eve dev` session. */
export const EVE_DEV_ENV_FLAG = "EVE_DEV";
+export type InstrumentationEnvironment = "development" | "preview" | "production";
+
/** Reports whether this process belongs to an `eve dev` session. */
export function isEveDevEnvironment(): boolean {
return process.env[EVE_DEV_ENV_FLAG] === "1";
}
+/** Resolves the deployment environment used by setup hooks and trace policies. */
+export function resolveInstrumentationEnvironment(): InstrumentationEnvironment {
+ if (isEveDevEnvironment() || process.env.VERCEL_ENV === "development") return "development";
+ return process.env.VERCEL_ENV === "preview" ? "preview" : "production";
+}
+
/** Environment flag set for a server `eve eval` started to run against. */
export const EVE_EVALUATION_ENV_FLAG = "EVE_EVALUATION";
diff --git a/packages/eve/src/internal/instrumentation.ts b/packages/eve/src/internal/instrumentation.ts
index 79d3c1308..e380f0c34 100644
--- a/packages/eve/src/internal/instrumentation.ts
+++ b/packages/eve/src/internal/instrumentation.ts
@@ -10,36 +10,12 @@
* file but not the other).
*/
import { type Logger, formatError } from "#internal/logging.js";
-import type { InstrumentationChannelKind } from "#public/channels/index.js";
import { isPlainRecord, isThenable } from "#shared/guards.js";
import { parseJsonObject } from "#shared/json.js";
-
-/**
- * Framework-owned channel kinds that are not derived from a route file
- * path. Keep in sync with the non-`channel:<name>` keys of
- * {@link InstrumentationChannelKind} (currently every key except
- * `"unknown"`, which is the fallback rather than a real channel).
- */
-const FRAMEWORK_CHANNEL_KINDS: ReadonlySet<string> = new Set(["http", "schedule", "subagent"]);
-
-/**
- * Returns `true` when `kind` is a valid instrumentation channel kind: a
- * framework kind (`"http"`, `"schedule"`, `"subagent"`) or a
- * path-derived `channel:<name>` kind.
- */
-export function isInstrumentationChannelKind(kind: string): kind is InstrumentationChannelKind {
- return kind.startsWith("channel:") || FRAMEWORK_CHANNEL_KINDS.has(kind);
-}
-
-/**
- * Narrows a raw kind string to the public {@link InstrumentationChannelKind}
- * union, falling back to `"unknown"` for anything unrecognized or absent.
- */
-export function normalizeInstrumentationChannelKind(
- rawKind: string | undefined,
-): InstrumentationChannelKind {
- return rawKind !== undefined && isInstrumentationChannelKind(rawKind) ? rawKind : "unknown";
-}
+export {
+ isInstrumentationChannelKind,
+ normalizeInstrumentationChannelKind,
+} from "#shared/instrumentation-channel-kind.js";
/**
* Invokes a user-authored instrumentation projector defensively.
diff --git a/packages/eve/src/public/channels/chat-sdk/audience.ts b/packages/eve/src/public/channels/chat-sdk/audience.ts
index f7acc19d3..fce2fd7a3 100644
--- a/packages/eve/src/public/channels/chat-sdk/audience.ts
+++ b/packages/eve/src/public/channels/chat-sdk/audience.ts
@@ -4,20 +4,20 @@ import type {
ChatSdkChannelState,
ChatSdkInstrumentationMetadata,
} from "#public/channels/chat-sdk/chatSdkChannel.js";
+import type { AudienceInput } from "#shared/conversation-context.js";
export function chatSdkInstrumentationMetadata(
state: ChatSdkChannelState,
): ChatSdkInstrumentationMetadata {
return {
adapterName: state.thread?.adapterName ?? null,
- audience: chatSdkAudience(state.thread),
channelId: state.thread?.channelId ?? null,
isDM: state.thread?.isDM ?? null,
threadId: state.thread?.id ?? null,
};
}
-function chatSdkAudience(thread: SerializedThread | null): ChannelAudience {
+export function chatSdkAudience(thread: SerializedThread | null): ChannelAudience {
if (thread?.isDM === true) return "private";
if (thread?.channelVisibility === "workspace") return "public";
if (thread?.channelVisibility === "private" || thread?.channelVisibility === "external") {
@@ -25,3 +25,8 @@ function chatSdkAudience(thread: SerializedThread | null): ChannelAudience {
}
return "unknown";
}
+
+export const chatSdkInstrumentation = {
+ audience: (input: AudienceInput<ChatSdkChannelState>) => chatSdkAudience(input.state.thread),
+ metadata: chatSdkInstrumentationMetadata,
+} as const;
diff --git a/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.test.ts b/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.test.ts
index 187e3477f..17bf394de 100644
--- a/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.test.ts
+++ b/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.test.ts
@@ -141,7 +141,7 @@ describe("chatSdkChannel", () => {
[{ isDM: true, channelVisibility: "unknown" }, "private"],
[{ isDM: false, channelVisibility: "workspace" }, "public"],
[{ isDM: false, channelVisibility: "private" }, "private"],
- ] as const)("projects the $audience audience", (thread, audience) => {
+ ] as const)("classifies the $audience audience", (thread, audience) => {
const bridge = chatSdkChannel({
adapters: { test: testAdapter() },
state: memoryState(),
@@ -157,7 +157,15 @@ describe("chatSdkChannel", () => {
...thread,
};
- expect(adapter.instrumentation?.metadata?.(adapter.state)).toMatchObject({ audience });
+ expect(
+ adapter.instrumentation?.audience?.({
+ auth: null,
+ channel: { kind: "channel:chat-sdk" },
+ environment: "production",
+ mode: "conversation",
+ state: adapter.state,
+ }),
+ ).toBe(audience);
});
it("mounts GET and POST webhook routes per Chat SDK adapter", () => {
diff --git a/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.ts b/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.ts
index 95f9a9a3f..7b57bd277 100644
--- a/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.ts
+++ b/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.ts
@@ -44,8 +44,7 @@ import {
type RouteHandlerArgs,
type Session,
} from "#public/definitions/channel.js";
-import { chatSdkInstrumentationMetadata } from "#public/channels/chat-sdk/audience.js";
-import type { ChannelAudience } from "#shared/channel-audience.js";
+import { chatSdkInstrumentation } from "#public/channels/chat-sdk/audience.js";
const log = createLogger("chat-sdk.channel");
const DEFAULT_ROUTE = "/eve/v1";
@@ -105,7 +104,6 @@ export interface ChatSdkReceiveTarget {
* Channel-owned metadata exposed to eve instrumentation.
*/
export interface ChatSdkInstrumentationMetadata extends Record<string, unknown> {
- readonly audience: ChannelAudience;
readonly adapterName: string | null;
readonly channelId: string | null;
readonly isDM: boolean | null;
@@ -296,7 +294,7 @@ export function chatSdkChannel<TAdapters extends ChatSdkAdapters>(
kindHint: "chat-sdk",
turnPolicy: config.turnPolicy,
state: initialState(),
- metadata: chatSdkInstrumentationMetadata,
+ ...chatSdkInstrumentation,
context(state) {
return {
bot,
diff --git a/packages/eve/src/public/channels/discord/audience.ts b/packages/eve/src/public/channels/discord/audience.ts
index 9951f1776..6883b67ca 100644
--- a/packages/eve/src/public/channels/discord/audience.ts
+++ b/packages/eve/src/public/channels/discord/audience.ts
@@ -11,7 +11,6 @@ export function discordInstrumentationMetadata(
state: DiscordChannelState,
): DiscordInstrumentationMetadata {
return {
- audience: state.audience ?? "unknown",
channelId: state.channelId,
guildId: state.guildId,
};
diff --git a/packages/eve/src/public/channels/discord/discordChannel.test.ts b/packages/eve/src/public/channels/discord/discordChannel.test.ts
index 62cc73bd8..e89479a45 100644
--- a/packages/eve/src/public/channels/discord/discordChannel.test.ts
+++ b/packages/eve/src/public/channels/discord/discordChannel.test.ts
@@ -52,11 +52,19 @@ function callEvent(
return contextStorage.run(stubAlsContext, () => callAdapterEventHandler(adapter, event, ctx));
}
-describe("discordChannel() audience metadata", () => {
- it.each(["private", "unknown"] as const)("projects the %s audience", (audience) => {
+describe("discordChannel() audience classification", () => {
+ it.each(["private", "unknown"] as const)("classifies the %s audience", (audience) => {
const adapter = withState(getAdapter(discordChannel()), { audience });
- expect(adapter.instrumentation?.metadata?.(adapter.state)).toMatchObject({ audience });
+ expect(
+ adapter.instrumentation?.audience?.({
+ auth: null,
+ channel: { kind: "channel:discord" },
+ environment: "production",
+ mode: "conversation",
+ state: adapter.state,
+ }),
+ ).toBe(audience);
});
});
@@ -552,7 +560,6 @@ describe("discordChannel() default event handlers", () => {
auth: null,
message: "start",
state: {
- audience: "unknown",
applicationId: null,
channelId: "C01",
conversationId: null,
diff --git a/packages/eve/src/public/channels/discord/discordChannel.ts b/packages/eve/src/public/channels/discord/discordChannel.ts
index cae98085a..e5e09badf 100644
--- a/packages/eve/src/public/channels/discord/discordChannel.ts
+++ b/packages/eve/src/public/channels/discord/discordChannel.ts
@@ -228,6 +228,7 @@ export function discordChannel(config: DiscordChannelConfig = {}): DiscordChanne
turnPolicy: config.turnPolicy,
state: initialDiscordState(),
metadata: discordInstrumentationMetadata,
+ audience: ({ state }) => state.audience ?? "unknown",
context(state, session) {
return rebuildDiscordContext(state, session, config);
@@ -300,7 +301,6 @@ export function discordChannel(config: DiscordChannelConfig = {}): DiscordChanne
return from(discordContinuationToken(channelId, conversationId)).send(input.message, {
auth: input.auth,
state: {
- audience: "unknown",
applicationId: null,
channelId,
conversationId: conversationId || null,
@@ -656,7 +656,6 @@ function stateFromInteraction(
function initialDiscordState(): DiscordChannelState {
return {
- audience: "unknown",
applicationId: null,
channelId: null,
conversationId: null,
diff --git a/packages/eve/src/public/channels/discord/index.ts b/packages/eve/src/public/channels/discord/index.ts
index e175b25af..e2e629ea5 100644
--- a/packages/eve/src/public/channels/discord/index.ts
+++ b/packages/eve/src/public/channels/discord/index.ts
@@ -11,7 +11,6 @@ export type { ModelMessage } from "ai";
* Discord sessions, used for tracing and observability.
*/
export interface DiscordInstrumentationMetadata extends Record<string, unknown> {
- readonly audience: import("#shared/channel-audience.js").ChannelAudience;
/** Originating Discord channel id, or `null` when unavailable. */
readonly channelId: string | null;
/** Originating Discord guild id, or `null` when the interaction was not in a guild. */
diff --git a/packages/eve/src/public/channels/eve-forwarded-principal.integration.test.ts b/packages/eve/src/public/channels/eve-forwarded-principal.integration.test.ts
index 9c21d2978..7a4ca6810 100644
--- a/packages/eve/src/public/channels/eve-forwarded-principal.integration.test.ts
+++ b/packages/eve/src/public/channels/eve-forwarded-principal.integration.test.ts
@@ -15,11 +15,11 @@ import { contextStorage } from "#context/container.js";
import { serializeContext } from "#context/serialize.js";
import {
AuthKey,
- ChannelInstrumentationKey,
InitiatorAuthKey,
ParentTraceContextKey,
SessionTraceSeedKey,
} from "#context/keys.js";
+import { ConversationContextKey } from "#shared/conversation-context.js";
import { buildRunContext } from "#execution/runtime-context.js";
import { setChannelContext } from "#execution/channel-context.js";
import { buildSessionAttributes } from "#execution/eve-workflow-attributes.js";
@@ -159,14 +159,14 @@ describe("eveChannel forwarded principal → runtime principal", () => {
const current = ctx.get(AuthKey);
const initiator = ctx.get(InitiatorAuthKey);
- expect(ctx.get(ChannelInstrumentationKey)?.metadata.audience).toBe("unknown");
+ expect(ctx.get(ConversationContextKey)?.audience).toBe("private");
expect(ctx.get(ParentTraceContextKey)?.forwardedTracePolicy).toEqual({
ceiling: { recordInputs: true, recordOutputs: false },
originAudience: "private",
});
setChannelContext(ctx, { ...run.adapter, state: { persisted: true } });
- expect(ctx.get(ChannelInstrumentationKey)?.metadata.audience).toBe("unknown");
+ expect(ctx.get(ConversationContextKey)?.audience).toBe("private");
ctx.set(SessionTraceSeedKey, {
decision: { action: "record", recordInputs: true, recordOutputs: false },
forwardedTracePolicy: {
@@ -269,7 +269,7 @@ describe("eveChannel forwarded principal → runtime principal", () => {
...options,
},
});
- expect(ctx.get(ChannelInstrumentationKey)?.metadata.audience).toBe("unknown");
+ expect(ctx.get(ConversationContextKey)?.audience).toBe("unknown");
expect(ctx.get(ParentTraceContextKey)?.forwardedTracePolicy).toEqual({
ceiling: { recordInputs: false, recordOutputs: false },
originAudience: "unknown",
@@ -349,7 +349,7 @@ describe("eveChannel forwarded principal → runtime principal", () => {
...options,
},
});
- expect(ctx.get(ChannelInstrumentationKey)?.metadata.audience).toBe("unknown");
+ expect(ctx.get(ConversationContextKey)?.audience).toBe("unknown");
});
it("resolves the transport service principal (and fails Connect) without forwarding", async () => {
diff --git a/packages/eve/src/public/channels/eve.test.ts b/packages/eve/src/public/channels/eve.test.ts
index b2977e443..654374c3b 100644
--- a/packages/eve/src/public/channels/eve.test.ts
+++ b/packages/eve/src/public/channels/eve.test.ts
@@ -709,6 +709,20 @@ describe("eveChannel — onMessage", () => {
expect(options.auth).toEqual(OVERRIDE_AUTH);
});
+ it("keeps route authentication separate from onMessage session auth", async () => {
+ const handler = createEveCreateHandler({
+ auth: () => ACCEPTED_AUTH,
+ onMessage: () => ({ auth: null, context: ["anonymous session projection"] }),
+ });
+
+ const response = await handler.fetch(createJsonMessageRequest({ message: "hi" }));
+
+ expect(response.status).toBe(202);
+ const runInput = handler.createSession.mock.calls[0]?.[0] as RunInput;
+ expect(runInput.auth).toBeNull();
+ expect(runInput.audienceAuth).toEqual(ACCEPTED_AUTH);
+ });
+
it("does not run onMessage when auth rejects", async () => {
const onMessage = vi.fn(() => ({ auth: null, context: ["never"] }));
const handler = createEveCreateHandler({
diff --git a/packages/eve/src/public/channels/index.ts b/packages/eve/src/public/channels/index.ts
index ca42631d7..f3f239983 100644
--- a/packages/eve/src/public/channels/index.ts
+++ b/packages/eve/src/public/channels/index.ts
@@ -16,7 +16,9 @@ export {
type ResetSessionResult,
type Channel,
type ChannelAudience,
- type ChannelAudienceMetadata,
+ type AudienceInput,
+ type AudiencePrincipal,
+ type ConversationEnvironment,
type ChannelFrom,
type ChannelReceiveContext,
type ChannelResolveSession,
@@ -55,14 +57,10 @@ export {
import { getChannelInstrumentationKind } from "#channel/compiled-channel.js";
import type { Channel, InferChannelMetadata } from "#public/definitions/channel.js";
-import type { ChannelAudienceMetadata } from "#shared/channel-audience.js";
-
/**
* Base channel metadata shape used by framework channel kinds.
*/
-export type InstrumentationChannelMetadata = Readonly<
- Record<string, unknown> & ChannelAudienceMetadata
->;
+export type InstrumentationChannelMetadata = Readonly<Record<string, unknown>>;
/**
* Kind discriminator exposed to instrumentation and dynamic resolvers.
diff --git a/packages/eve/src/public/channels/slack/slackChannel.test.ts b/packages/eve/src/public/channels/slack/slackChannel.test.ts
index bf450aa28..60deff75b 100644
--- a/packages/eve/src/public/channels/slack/slackChannel.test.ts
+++ b/packages/eve/src/public/channels/slack/slackChannel.test.ts
@@ -428,12 +428,18 @@ describe("slackChannel()", () => {
expect(channel).toMatchObject({ turnPolicy: "queue" });
});
- it("projects the durable audience into instrumentation metadata", () => {
+ it("classifies from durable state through the audience hook", () => {
const adapter = withState(getAdapter(slackChannel()), { audience: "private" });
- expect(adapter.instrumentation?.metadata?.(adapter.state)).toMatchObject({
- audience: "private",
- });
+ expect(
+ adapter.instrumentation?.audience?.({
+ auth: null,
+ channel: { kind: "channel:slack" },
+ environment: "production",
+ mode: "conversation",
+ state: adapter.state,
+ }),
+ ).toBe("private");
});
});
@@ -1889,7 +1895,6 @@ describe("slackChannel() inbound mention pipeline", () => {
}),
message: "Imperative follow-up",
state: {
- audience: "unknown",
channelId: "C_BOUND",
installationTeamId: null,
teamId: "T01",
diff --git a/packages/eve/src/public/channels/slack/slackChannel.ts b/packages/eve/src/public/channels/slack/slackChannel.ts
index 61282c2b1..ccff4e732 100644
--- a/packages/eve/src/public/channels/slack/slackChannel.ts
+++ b/packages/eve/src/public/channels/slack/slackChannel.ts
@@ -257,7 +257,6 @@ export interface SlackChannelState {
* can attach extra span attributes.
*/
export interface SlackInstrumentationMetadata extends Record<string, unknown> {
- readonly audience: ChannelAudience;
readonly channelId: string | null;
readonly teamId: string | null;
readonly threadTs: string | null;
@@ -925,7 +924,6 @@ export function slackChannel(config: SlackChannelConfig = {}): SlackChannel {
kindHint: "slack",
turnPolicy: config.turnPolicy,
state: {
- audience: "unknown",
channelId: null as string | null,
threadTs: null as string | null,
teamId: null as string | null,
@@ -943,13 +941,13 @@ export function slackChannel(config: SlackChannelConfig = {}): SlackChannel {
fetchFile: slackFetchFile,
metadata(state): SlackInstrumentationMetadata {
return {
- audience: state.audience ?? "unknown",
channelId: state.channelId,
teamId: state.teamId,
threadTs: state.threadTs,
triggeringUserId: state.triggeringUserId ?? null,
};
},
+ audience: ({ state }) => state.audience ?? "unknown",
context(state, session) {
return rebuildSlackContext(state, session, config.credentials);
@@ -1340,7 +1338,6 @@ async function dispatchSlackMessage(input: {
});
const author = input.message.author;
const channelState: SlackChannelState = {
- audience: "unknown",
channelId: input.message.channelId,
installationTeamId: input.installationTeamId ?? null,
teamId: input.message.teamId ?? null,
diff --git a/packages/eve/src/public/channels/teams/index.ts b/packages/eve/src/public/channels/teams/index.ts
index 65bbb41c2..89c15aa23 100644
--- a/packages/eve/src/public/channels/teams/index.ts
+++ b/packages/eve/src/public/channels/teams/index.ts
@@ -7,7 +7,6 @@ export type { ModelMessage } from "ai";
* null when the inbound activity did not include it.
*/
export interface TeamsInstrumentationMetadata extends Record<string, unknown> {
- readonly audience: import("#shared/channel-audience.js").ChannelAudience;
readonly channelId: string | null;
readonly conversationType: string | null;
readonly teamId: string | null;
diff --git a/packages/eve/src/public/channels/teams/teamsChannel.test.ts b/packages/eve/src/public/channels/teams/teamsChannel.test.ts
index 484c4710d..e77ed3ce5 100644
--- a/packages/eve/src/public/channels/teams/teamsChannel.test.ts
+++ b/packages/eve/src/public/channels/teams/teamsChannel.test.ts
@@ -131,9 +131,15 @@ describe("teamsChannel", () => {
if (!teamsAdapter.state) throw new Error("Expected Teams state.");
teamsAdapter.state.conversationType = conversationType;
- expect(teamsAdapter.instrumentation?.metadata?.(teamsAdapter.state)).toMatchObject({
- audience,
- });
+ expect(
+ teamsAdapter.instrumentation?.audience?.({
+ auth: null,
+ channel: { kind: "channel:teams" },
+ environment: "production",
+ mode: "conversation",
+ state: teamsAdapter.state,
+ }),
+ ).toBe(audience);
});
it("dispatches verified personal messages with Teams state", async () => {
diff --git a/packages/eve/src/public/channels/teams/teamsChannel.ts b/packages/eve/src/public/channels/teams/teamsChannel.ts
index 64b987113..18f8f4bcd 100644
--- a/packages/eve/src/public/channels/teams/teamsChannel.ts
+++ b/packages/eve/src/public/channels/teams/teamsChannel.ts
@@ -307,11 +307,11 @@ export function teamsChannel(config: TeamsChannelConfig = {}): TeamsChannel {
credentials: config.credentials,
}),
metadata: (state) => ({
- audience: teamsAudience(state.conversationType),
channelId: state.channelId,
conversationType: state.conversationType,
teamId: state.teamId,
}),
+ audience: ({ state }) => teamsAudience(state.conversationType),
context(state, session) {
return rebuildTeamsContext(state, session, config);
diff --git a/packages/eve/src/public/channels/telegram/audience.ts b/packages/eve/src/public/channels/telegram/audience.ts
index 6b9a16eb3..369888f37 100644
--- a/packages/eve/src/public/channels/telegram/audience.ts
+++ b/packages/eve/src/public/channels/telegram/audience.ts
@@ -1,19 +1,28 @@
import type { ChannelAudience } from "#shared/channel-audience.js";
import type { TelegramInstrumentationMetadata } from "#public/channels/telegram/index.js";
import type { TelegramChannelState } from "#public/channels/telegram/telegramChannel.js";
+import type { AudienceInput } from "#shared/conversation-context.js";
export function telegramInstrumentationMetadata(
state: TelegramChannelState,
): TelegramInstrumentationMetadata {
return {
- audience: telegramAudience(state.chatType),
chatId: state.chatId,
chatType: state.chatType,
triggeringUserId: state.triggeringUserId ?? null,
};
}
-function telegramAudience(chatType: TelegramChannelState["chatType"]): ChannelAudience {
+export function telegramAudience(state: TelegramChannelState): ChannelAudience {
+ return telegramAudienceForChatType(state.chatType);
+}
+
+export const telegramInstrumentation = {
+ audience: (input: AudienceInput<TelegramChannelState>) => telegramAudience(input.state),
+ metadata: telegramInstrumentationMetadata,
+} as const;
+
+function telegramAudienceForChatType(chatType: TelegramChannelState["chatType"]): ChannelAudience {
if (
chatType === "private" ||
chatType === "group" ||
diff --git a/packages/eve/src/public/channels/telegram/index.ts b/packages/eve/src/public/channels/telegram/index.ts
index 843c34b3e..98927dc8b 100644
--- a/packages/eve/src/public/channels/telegram/index.ts
+++ b/packages/eve/src/public/channels/telegram/index.ts
@@ -7,7 +7,6 @@ export type { ModelMessage } from "ai";
* inbound update populates it.
*/
export interface TelegramInstrumentationMetadata extends Record<string, unknown> {
- readonly audience: import("#shared/channel-audience.js").ChannelAudience;
readonly chatId: string | null;
readonly chatType: import("#public/channels/telegram/inbound.js").TelegramChatType | null;
readonly triggeringUserId: string | null;
diff --git a/packages/eve/src/public/channels/telegram/telegramChannel.test.ts b/packages/eve/src/public/channels/telegram/telegramChannel.test.ts
index dcdd6ebdf..d24c69d83 100644
--- a/packages/eve/src/public/channels/telegram/telegramChannel.test.ts
+++ b/packages/eve/src/public/channels/telegram/telegramChannel.test.ts
@@ -153,7 +153,15 @@ describe("telegramChannel() inbound route", () => {
] as const)("maps %s chats to the %s audience", (chatType, audience) => {
const adapter = withState(getAdapter(telegramChannel()), { chatType });
- expect(adapter.instrumentation?.metadata?.(adapter.state)).toMatchObject({ audience });
+ expect(
+ adapter.instrumentation?.audience?.({
+ auth: null,
+ channel: { kind: "channel:telegram" },
+ environment: "production",
+ mode: "conversation",
+ state: adapter.state,
+ }),
+ ).toBe(audience);
});
it("dispatches verified private messages with Telegram auth and chat-wide token", async () => {
diff --git a/packages/eve/src/public/channels/telegram/telegramChannel.ts b/packages/eve/src/public/channels/telegram/telegramChannel.ts
index c99c63a35..38ca341ad 100644
--- a/packages/eve/src/public/channels/telegram/telegramChannel.ts
+++ b/packages/eve/src/public/channels/telegram/telegramChannel.ts
@@ -72,7 +72,7 @@ import {
type TelegramWebhookVerifier,
} from "#public/channels/telegram/verify.js";
import { defineChannel, POST, type Channel } from "#public/definitions/channel.js";
-import { telegramInstrumentationMetadata } from "#public/channels/telegram/audience.js";
+import { telegramInstrumentation } from "#public/channels/telegram/audience.js";
import { parseJsonObject, type JsonObject } from "#shared/json.js";
const log = createLogger("telegram.channel");
@@ -251,7 +251,7 @@ export function telegramChannel(config: TelegramChannelConfig = {}): TelegramCha
kindHint: "telegram",
turnPolicy: config.turnPolicy,
state: initialTelegramState(config.botUsername),
- metadata: telegramInstrumentationMetadata,
+ ...telegramInstrumentation,
fetchFile: createTelegramFetchFile({
api: config.api,
credentials: config.credentials,
diff --git a/packages/eve/src/public/channels/twilio/twilioChannel.test.ts b/packages/eve/src/public/channels/twilio/twilioChannel.test.ts
index db22ee82c..c48952cca 100644
--- a/packages/eve/src/public/channels/twilio/twilioChannel.test.ts
+++ b/packages/eve/src/public/channels/twilio/twilioChannel.test.ts
@@ -182,9 +182,15 @@ describe("twilioChannel() inbound text pipeline", () => {
it("classifies phone conversations as direct", () => {
const adapter = getAdapter(twilioChannel({ allowFrom: "*" }));
- expect(adapter.instrumentation?.metadata?.(adapter.state)).toMatchObject({
- audience: "private",
- });
+ expect(
+ adapter.instrumentation?.audience?.({
+ auth: null,
+ channel: { kind: "channel:twilio" },
+ environment: "production",
+ mode: "conversation",
+ state: adapter.state,
+ }),
+ ).toBe("private");
});
it("mounts message, voice, and transcription routes below the base route", () => {
diff --git a/packages/eve/src/public/channels/twilio/twilioChannel.ts b/packages/eve/src/public/channels/twilio/twilioChannel.ts
index 138c17e57..45fa9dff6 100644
--- a/packages/eve/src/public/channels/twilio/twilioChannel.ts
+++ b/packages/eve/src/public/channels/twilio/twilioChannel.ts
@@ -45,7 +45,6 @@ import {
import { type TwilioAuthToken, type TwilioWebhookUrl } from "#public/channels/twilio/verify.js";
import { readNonEmptyString } from "#shared/guards.js";
import { defineChannel, GET, POST, type Channel } from "#public/definitions/channel.js";
-import type { ChannelAudience } from "#shared/channel-audience.js";
const log = createLogger("twilio.channel");
@@ -79,7 +78,6 @@ export interface TwilioChannelState {
/** Per-session instrumentation snapshot for Twilio runtime telemetry. Reports the active phone-number pair and the most recent message and call SIDs. */
export interface TwilioInstrumentationMetadata extends Record<string, unknown> {
- readonly audience: ChannelAudience;
readonly from: string | null;
readonly lastCallSid: string | null;
readonly lastMessageSid: string | null;
@@ -311,13 +309,13 @@ export function twilioChannel(config: TwilioChannelConfig): TwilioChannel {
},
metadata(state): TwilioInstrumentationMetadata {
return {
- audience: "private",
from: state.from,
lastCallSid: state.lastCallSid ?? null,
lastMessageSid: state.lastMessageSid ?? null,
to: state.to,
};
},
+ audience: () => "private",
context(state, session) {
return rebuildTwilioContext(state, session, config);
diff --git a/packages/eve/src/public/definitions/channel.test.ts b/packages/eve/src/public/definitions/channel.test.ts
index 3e18f29ce..b59ab9c69 100644
--- a/packages/eve/src/public/definitions/channel.test.ts
+++ b/packages/eve/src/public/definitions/channel.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, it } from "vitest";
+import { describe, expect, it, vi } from "vitest";
import { buildAdapterContext } from "#channel/adapter-context.js";
import { callAdapterEventHandler, type ChannelAdapter } from "#channel/adapter.js";
@@ -159,6 +159,59 @@ describe("defineChannel", () => {
expect(adapter.instrumentation?.metadata?.(adapter.state)).toEqual({ threadTs: null });
});
+ it("keeps the HTTP fast path when only an audience classifier is declared", () => {
+ const channel = defineChannel({
+ audience: () => "public",
+ routes: [POST("/x", async () => new Response("ok"))],
+ });
+
+ const adapter = getAdapter(channel);
+ expect(adapter.kind).toBe("http");
+ expect(adapter.instrumentation?.metadata).toBeUndefined();
+ expect(
+ adapter.instrumentation?.audience?.({
+ auth: null,
+ channel: { kind: "http" },
+ environment: "production",
+ mode: "conversation",
+ state: undefined,
+ }),
+ ).toBe("public");
+ });
+
+ it("drops the former audience key from custom metadata", () => {
+ const channel = defineChannel({
+ metadata: () => ({ audience: "public", custom: "value" }),
+ routes: [POST("/x", async () => new Response("ok"))],
+ });
+
+ const adapter = getAdapter(channel);
+ expect(adapter.instrumentation?.metadata?.(adapter.state)).toEqual({ custom: "value" });
+ });
+
+ it("classifies legacy metadata audience after defineChannel strips it", () => {
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined);
+ const channel = defineChannel({
+ metadata: () => ({ audience: "public", custom: "value" }),
+ routes: [POST("/x", async () => new Response("ok"))],
+ });
+ const adapter = getAdapter(channel);
+
+ expect(
+ adapter.instrumentation?.audience?.({
+ auth: null,
+ channel: { kind: "channel:legacy" },
+ environment: "production",
+ mode: "conversation",
+ state: adapter.state,
+ }),
+ ).toBe("public");
+ expect(adapter.instrumentation?.metadata?.(adapter.state)).toEqual({ custom: "value" });
+ expect(warn).toHaveBeenCalledExactlyOnceWith(
+ "channel defineChannel uses deprecated metadata audience; move it to the audience() hook",
+ );
+ });
+
it("infers channel metadata from metadata() return values", () => {
const channel = defineChannel({
state: { threadTs: null as string | null },
diff --git a/packages/eve/src/public/definitions/channel.ts b/packages/eve/src/public/definitions/channel.ts
index 8b7a7e65e..5660cd402 100644
--- a/packages/eve/src/public/definitions/channel.ts
+++ b/packages/eve/src/public/definitions/channel.ts
@@ -1,4 +1,8 @@
import type { ChannelAdapter, ChannelInstrumentationMetadata } from "#channel/adapter.js";
+import {
+ createMetadataAudienceProjector,
+ type ChannelAudienceProjector,
+} from "#channel/audience.js";
import { defaultDeliverResult } from "#channel/adapter.js";
import {
CHANNEL_SENTINEL,
@@ -35,7 +39,12 @@ export type {
TurnPolicy,
} from "#channel/types.js";
export type { Session, SessionHandle } from "#channel/session.js";
-export type { ChannelAudience, ChannelAudienceMetadata } from "#shared/channel-audience.js";
+export type { ChannelAudience } from "#shared/channel-audience.js";
+export type {
+ AudienceInput,
+ AudiencePrincipal,
+ ConversationEnvironment,
+} from "#shared/conversation-context.js";
export type { SessionRespondOptions, SessionSendOptions } from "#channel/session.js";
export type {
ChannelFrom,
@@ -327,10 +336,14 @@ function buildAdapter<TState, TCtx, TReceiveTarget, TMetadata extends Record<str
const hasFetchFile = definition.fetchFile !== undefined;
const metadata = definition.metadata;
const hasMetadata = metadata !== undefined;
+ const audience = definition.audience;
const hasBehavior = hasState || hasContext || hasMetadata;
const eventHandlers: Record<string, unknown> = {};
let hasEventHandlers = false;
+ const legacyAudienceSource = {
+ kind: definition.kindHint ?? "defineChannel",
+ };
const events = definition.events;
for (const eventType of eventTypes) {
@@ -364,7 +377,16 @@ function buildAdapter<TState, TCtx, TReceiveTarget, TMetadata extends Record<str
}
if (!hasBehavior && !hasEventHandlers && !hasFetchFile) {
- return { kind: definition.kindHint ?? HTTP_ADAPTER_KIND } as ChannelAdapter<any>;
+ return {
+ kind: definition.kindHint ?? HTTP_ADAPTER_KIND,
+ ...(audience === undefined
+ ? undefined
+ : {
+ instrumentation: {
+ audience: audience as ChannelAudienceProjector,
+ },
+ }),
+ } as ChannelAdapter<any>;
}
const adapter: ChannelAdapter<any> = {
@@ -372,12 +394,31 @@ function buildAdapter<TState, TCtx, TReceiveTarget, TMetadata extends Record<str
state: hasState ? { ...(definition.state as Record<string, unknown>) } : {},
fetchFile: definition.fetchFile,
instrumentation:
- metadata === undefined
+ metadata === undefined && audience === undefined
? undefined
: {
- metadata(state): ChannelInstrumentationMetadata {
- return metadata(state as NonNullable<TState>);
- },
+ ...(metadata === undefined
+ ? undefined
+ : {
+ metadata(state): ChannelInstrumentationMetadata {
+ const projected = metadata(state as NonNullable<TState>) as Record<
+ string,
+ unknown
+ >;
+ const { audience: _ignoredAudience, ...customMetadata } = projected;
+ return customMetadata;
+ },
+ }),
+ ...(audience === undefined
+ ? metadata !== undefined
+ ? {
+ audience: createMetadataAudienceProjector(
+ legacyAudienceSource,
+ metadata as (state: Record<string, unknown> | undefined) => unknown,
+ ),
+ }
+ : undefined
+ : { audience: audience as ChannelAudienceProjector }),
},
createAdapterContext(base): any {
diff --git a/packages/eve/src/runtime/sessions/runtime-context-keys.ts b/packages/eve/src/runtime/sessions/runtime-context-keys.ts
index 70c43bf06..3a0b37af9 100644
--- a/packages/eve/src/runtime/sessions/runtime-context-keys.ts
+++ b/packages/eve/src/runtime/sessions/runtime-context-keys.ts
@@ -4,10 +4,8 @@
*/
import type { ChannelAdapter } from "#channel/adapter.js";
-import type { ChannelAudience } from "#shared/channel-audience.js";
import { getAdapterKind } from "#channel/adapter.js";
import { ContextKey } from "#context/key.js";
-import { buildChannelInstrumentationProjection } from "#channel/instrumentation.js";
import { CHANNEL_CONTEXT_KEY_NAME } from "#context/key-names.js";
import { deserializeRuntimeAdapter } from "#runtime/channels/registry.js";
import {
@@ -24,7 +22,6 @@ import {
interface SerializedAdapter {
readonly kind: string;
readonly state: Record<string, unknown>;
- readonly audience?: ChannelAudience;
}
/** Compiled bundle on the durable context — re-exported under a stable name. */
@@ -38,11 +35,9 @@ interface SerializedBundle {
export const ChannelKey = new ContextKey<ChannelAdapter>(CHANNEL_CONTEXT_KEY_NAME, {
codec: {
serialize(adapter): SerializedAdapter {
- const projection = buildChannelInstrumentationProjection({ adapter });
return {
kind: getAdapterKind(adapter),
state: adapter.state ? { ...adapter.state } : {},
- audience: projection.metadata.audience,
};
},
deserialize(data, ctx): ChannelAdapter {
diff --git a/packages/eve/src/shared/channel-audience.ts b/packages/eve/src/shared/channel-audience.ts
index 8dce2d281..c3970cf22 100644
--- a/packages/eve/src/shared/channel-audience.ts
+++ b/packages/eve/src/shared/channel-audience.ts
@@ -3,10 +3,6 @@ export const CHANNEL_AUDIENCES = ["public", "private", "unknown"] as const;
/** Who can observe the conversation on its originating channel. */
export type ChannelAudience = (typeof CHANNEL_AUDIENCES)[number];
-export interface ChannelAudienceMetadata {
- readonly audience?: ChannelAudience;
-}
-
export function normalizeChannelAudience(value: unknown): ChannelAudience {
return typeof value === "string" && CHANNEL_AUDIENCES.includes(value as ChannelAudience)
? (value as ChannelAudience)
diff --git a/packages/eve/src/shared/channel-definition.ts b/packages/eve/src/shared/channel-definition.ts
index 4660f6ea5..a48498936 100644
--- a/packages/eve/src/shared/channel-definition.ts
+++ b/packages/eve/src/shared/channel-definition.ts
@@ -5,7 +5,8 @@ import type { RouteDefinition } from "#channel/routes.js";
import type { Session, SessionHandle } from "#channel/session.js";
import type { DeliverPayload, SessionAuthContext, TurnPolicy } from "#channel/types.js";
import type { StepInput } from "#harness/types.js";
-import type { ChannelAudienceMetadata } from "#shared/channel-audience.js";
+import type { AudienceInput } from "#shared/conversation-context.js";
+import type { ChannelAudience } from "#shared/channel-audience.js";
/**
* Enriched return shape from a channel's {@link ChannelAdapter.fetchFile}
@@ -46,8 +47,9 @@ export interface GenericReceiveInput<TReceiveTarget = Record<string, unknown>> {
* The object passed to {@link defineChannel}. `routes` is required; `state`
* seeds durable adapter state, `context` builds the per-step `channel` argument
* for `events` and `deliver`, `events` handle session lifecycle, `receive`
- * accepts cross-channel handoffs, `fetchFile` stages remote file URLs, and
- * `metadata` projects observability data.
+ * accepts cross-channel handoffs, `fetchFile` stages remote file URLs,
+ * `audience` classifies conversation visibility, and `metadata` projects
+ * custom observability data.
*
* Generics: `TState` (adapter state), `TCtx` (context factory return type),
* `TReceiveTarget` (cross-channel target shape), `TMetadata` (instrumentation
@@ -58,7 +60,7 @@ export interface GenericChannelDefinition<
TState = undefined,
TCtx = void,
TReceiveTarget = Record<string, unknown>,
- TMetadata extends Record<string, unknown> & ChannelAudienceMetadata = Record<string, unknown>,
+ TMetadata extends Record<string, unknown> = Record<string, unknown>,
> {
/** Policy used by message sends that do not provide an explicit override. */
readonly turnPolicy?: TurnPolicy;
@@ -109,6 +111,14 @@ export interface GenericChannelDefinition<
*/
readonly metadata?: (state: NonNullable<TState>) => TMetadata;
+ /**
+ * Classifies who can observe the originating conversation. The hook runs
+ * after route auth with channel state, the authenticated principal, run mode,
+ * and deployment environment. Return `"unknown"` when classification is not
+ * confident; consumers treat it as non-public.
+ */
+ readonly audience?: (input: AudienceInput<TState>) => ChannelAudience;
+
/**
* Identifier of the adapter family this channel belongs to. Set by
* higher-level wrappers (e.g. `slackChannel` passes `"slack"`) so downstream
diff --git a/packages/eve/src/shared/conversation-context.test.ts b/packages/eve/src/shared/conversation-context.test.ts
new file mode 100644
index 000000000..4da1cdaf5
--- /dev/null
+++ b/packages/eve/src/shared/conversation-context.test.ts
@@ -0,0 +1,177 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import type { RunInput, SessionAuthContext } from "#channel/types.js";
+import { ChannelKey } from "#runtime/sessions/runtime-context-keys.js";
+import { resolveInstrumentationEnvironment } from "#internal/application/dev-environment.js";
+import { buildConversationContext } from "#channel/conversation-context.js";
+import {
+ ConversationContextKey,
+ UNKNOWN_CONVERSATION_CONTEXT,
+} from "#shared/conversation-context.js";
+
+const auth: SessionAuthContext = {
+ attributes: {},
+ authenticator: "test",
+ principalId: "user-1",
+ principalType: "user",
+};
+
+function run(input: Partial<RunInput>): RunInput {
+ return {
+ adapter: { kind: "http" },
+ auth: null,
+ input: { message: "hello" },
+ mode: "conversation",
+ ...input,
+ };
+}
+
+describe("resolveInstrumentationEnvironment", () => {
+ afterEach(() => vi.unstubAllEnvs());
+
+ it("resolves development, preview, and production", () => {
+ vi.stubEnv("EVE_DEV", "1");
+ expect(resolveInstrumentationEnvironment()).toBe("development");
+
+ vi.stubEnv("EVE_DEV", "0");
+ vi.stubEnv("VERCEL_ENV", "development");
+ expect(resolveInstrumentationEnvironment()).toBe("development");
+
+ vi.stubEnv("VERCEL_ENV", "preview");
+ expect(resolveInstrumentationEnvironment()).toBe("preview");
+
+ vi.stubEnv("VERCEL_ENV", "production");
+ expect(resolveInstrumentationEnvironment()).toBe("production");
+ });
+});
+
+describe("buildConversationContext", () => {
+ it("classifies through the channel audience hook", () => {
+ const context = buildConversationContext(
+ run({
+ adapter: {
+ kind: "http",
+ instrumentation: {
+ audience: () => "private",
+ },
+ },
+ auth,
+ }),
+ "preview",
+ );
+
+ expect(context).toEqual({
+ audience: "private",
+ channel: { kind: "http", name: undefined },
+ environment: "preview",
+ mode: "conversation",
+ principalType: "user",
+ });
+ });
+
+ it("uses the path-derived channel kind for authored channels", () => {
+ const context = buildConversationContext(
+ run({ adapter: { kind: "slack" }, channelName: "support" }),
+ "production",
+ );
+
+ expect(context.channel).toEqual({ kind: "channel:support", name: "support" });
+ expect(context.audience).toBe("unknown");
+ });
+
+ it("classifies from route authentication separately from session auth", () => {
+ const context = buildConversationContext(
+ run({
+ adapter: {
+ kind: "http",
+ instrumentation: {
+ audience: ({ auth }) => (auth?.principalType === "user" ? "private" : "public"),
+ },
+ },
+ audienceAuth: auth,
+ auth: null,
+ }),
+ "production",
+ );
+
+ expect(context).toMatchObject({ audience: "private", principalType: "user" });
+ });
+
+ it("treats an explicit null route principal as unauthenticated", () => {
+ const context = buildConversationContext(
+ run({
+ adapter: {
+ kind: "http",
+ instrumentation: { audience: ({ auth }) => (auth === null ? "public" : "private") },
+ },
+ audienceAuth: null,
+ auth,
+ }),
+ "production",
+ );
+
+ expect(context).toMatchObject({ audience: "public", principalType: "anonymous" });
+ });
+
+ it("inherits the parent audience for local subagents", () => {
+ const context = buildConversationContext(
+ run({
+ adapter: { kind: "subagent" },
+ inheritedConversation: {
+ audience: "public",
+ channel: { kind: "channel:slack", name: "slack" },
+ environment: "production",
+ mode: "conversation",
+ principalType: "user",
+ },
+ mode: "task",
+ }),
+ "production",
+ );
+
+ expect(context).toMatchObject({ audience: "public", channel: { kind: "subagent" } });
+ });
+
+ it("lets a trusted forwarded origin win over local classification", () => {
+ const context = buildConversationContext(
+ run({
+ adapter: {
+ kind: "eve",
+ instrumentation: { audience: () => "public" },
+ },
+ parentTraceContext: {
+ forwardedTracePolicy: {
+ ceiling: { recordInputs: false, recordOutputs: true },
+ originAudience: "private",
+ },
+ spanId: "1".repeat(16),
+ traceFlags: 1,
+ traceId: "2".repeat(32),
+ },
+ }),
+ "production",
+ );
+
+ expect(context.audience).toBe("private");
+ });
+});
+
+describe("ConversationContextKey", () => {
+ it("round-trips a valid context and fails malformed projections closed", () => {
+ const context = buildConversationContext(run({ auth }), "production");
+
+ expect(ConversationContextKey.codec?.deserialize(context, new Map() as never)).toEqual(context);
+ expect(
+ ConversationContextKey.codec?.deserialize({ audience: "public" }, new Map() as never),
+ ).toEqual(UNKNOWN_CONVERSATION_CONTEXT);
+ });
+
+ it("keeps audience out of the durable channel adapter wire shape", () => {
+ const serialized = ChannelKey.codec?.serialize({
+ kind: "http",
+ instrumentation: { metadata: () => ({ audience: "public", custom: "value" }) },
+ });
+
+ expect(serialized).toEqual({ kind: "http", state: {} });
+ });
+});
diff --git a/packages/eve/src/shared/conversation-context.ts b/packages/eve/src/shared/conversation-context.ts
new file mode 100644
index 000000000..dc8cfb2c8
--- /dev/null
+++ b/packages/eve/src/shared/conversation-context.ts
@@ -0,0 +1,138 @@
+import type { InstrumentationChannelKind } from "#public/channels/index.js";
+import { ContextKey } from "#context/key.js";
+import { normalizeInstrumentationChannelKind } from "#shared/instrumentation-channel-kind.js";
+import { isNonEmptyString } from "#shared/guards.js";
+import { normalizeChannelAudience, type ChannelAudience } from "#shared/channel-audience.js";
+import type { RunMode } from "#shared/run-mode.js";
+import type { ForwardedTraceAssertion } from "#shared/forwarded-trace-policy.js";
+
+export type ConversationEnvironment = "development" | "preview" | "production";
+
+export interface ConversationContext {
+ readonly channel: {
+ readonly kind: InstrumentationChannelKind;
+ readonly name?: string;
+ };
+ readonly audience: ChannelAudience;
+ readonly mode: RunMode;
+ readonly environment: ConversationEnvironment;
+ readonly principalType: string;
+}
+
+export interface AudiencePrincipal {
+ readonly principalType: string;
+ readonly authenticator: string;
+ readonly attributes: Readonly<Record<string, string | readonly string[]>>;
+}
+
+export interface AudienceInput<TState> {
+ readonly state: TState;
+ readonly auth: AudiencePrincipal | null;
+ readonly channel: ConversationContext["channel"];
+ readonly mode: RunMode;
+ readonly environment: ConversationEnvironment;
+}
+
+/** Safe projection for durable sessions created before `eve.conversation` existed. */
+export const UNKNOWN_CONVERSATION_CONTEXT: ConversationContext = {
+ audience: "unknown",
+ channel: { kind: "unknown" },
+ environment: "production",
+ mode: "conversation",
+ principalType: "anonymous",
+};
+
+export interface ConversationContextFallback {
+ readonly channelKind?: string;
+ readonly environment: ConversationEnvironment;
+ readonly forwardedTracePolicy?: ForwardedTraceAssertion;
+ readonly mode?: RunMode;
+ readonly principalType?: string;
+}
+
+/**
+ * Reconstructs a durable conversation when its key predates the key itself.
+ * All callers must use this helper so legacy sessions resolve privacy fields
+ * from one source of truth.
+ */
+export function resolveConversationContext(
+ stored: ConversationContext | undefined,
+ fallback: ConversationContextFallback,
+ options: { readonly forwardedOverridesStored?: boolean } = {},
+): ConversationContext {
+ if (stored !== undefined) {
+ return !options.forwardedOverridesStored || fallback.forwardedTracePolicy === undefined
+ ? stored
+ : { ...stored, audience: fallback.forwardedTracePolicy.originAudience };
+ }
+ return {
+ ...UNKNOWN_CONVERSATION_CONTEXT,
+ audience: fallback.forwardedTracePolicy?.originAudience ?? "unknown",
+ channel: {
+ kind: normalizeInstrumentationChannelKind(fallback.channelKind),
+ },
+ environment: fallback.environment,
+ mode: fallback.mode ?? "conversation",
+ principalType: fallback.principalType ?? "anonymous",
+ };
+}
+
+interface SerializedConversationContext {
+ readonly audience?: unknown;
+ readonly channel?: unknown;
+ readonly environment?: unknown;
+ readonly mode?: unknown;
+ readonly principalType?: unknown;
+}
+
+export const ConversationContextKey = new ContextKey<ConversationContext>("eve.conversation", {
+ codec: {
+ serialize: (value) => value,
+ deserialize: (data) => {
+ if (typeof data !== "object" || data === null || Array.isArray(data)) {
+ return UNKNOWN_CONVERSATION_CONTEXT;
+ }
+ const conversation = normalizeConversationContext(data);
+ if (conversation === undefined) {
+ return UNKNOWN_CONVERSATION_CONTEXT;
+ }
+ return conversation;
+ },
+ },
+});
+
+export function normalizeConversationContext(value: unknown): ConversationContext | undefined {
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return undefined;
+ const candidate = value as SerializedConversationContext;
+ const channel = normalizeConversationChannel(candidate.channel);
+ const mode = candidate.mode;
+ const environment = candidate.environment;
+ const principalType = candidate.principalType;
+ if (
+ channel === undefined ||
+ (mode !== "conversation" && mode !== "task") ||
+ (environment !== "development" && environment !== "preview" && environment !== "production") ||
+ !isNonEmptyString(principalType)
+ ) {
+ return undefined;
+ }
+ return {
+ audience: normalizeChannelAudience(candidate.audience),
+ channel,
+ environment,
+ mode,
+ principalType,
+ };
+}
+
+function normalizeConversationChannel(value: unknown): ConversationContext["channel"] | undefined {
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return undefined;
+ const candidate = value as { kind?: unknown; name?: unknown };
+ const kind = normalizeInstrumentationChannelKind(
+ typeof candidate.kind === "string" ? candidate.kind : undefined,
+ );
+ return {
+ kind,
+ name: isNonEmptyString(candidate.name) ? candidate.name : undefined,
+ };
+}
diff --git a/packages/eve/src/shared/forwarded-trace-policy.test.ts b/packages/eve/src/shared/forwarded-trace-policy.test.ts
index bbfb15244..4ab3ac5d5 100644
--- a/packages/eve/src/shared/forwarded-trace-policy.test.ts
+++ b/packages/eve/src/shared/forwarded-trace-policy.test.ts
@@ -88,7 +88,7 @@ describe("applyLiveDeliveryAudienceCeiling", () => {
["private", forwardedTracePolicy, false],
["private", undefined, false],
] as const)("handles the %s delivery audience", (audience, policy, recordsContent) => {
- expect(applyLiveDeliveryAudienceCeiling(decision, audience, policy)).toEqual({
+ expect(applyLiveDeliveryAudienceCeiling(decision, audience, policy, "production")).toEqual({
action: "record",
recordInputs: recordsContent,
recordOutputs: recordsContent,
diff --git a/packages/eve/src/shared/forwarded-trace-policy.ts b/packages/eve/src/shared/forwarded-trace-policy.ts
index 078e802c5..9de5d35c0 100644
--- a/packages/eve/src/shared/forwarded-trace-policy.ts
+++ b/packages/eve/src/shared/forwarded-trace-policy.ts
@@ -1,5 +1,8 @@
import type { ChannelAudience } from "#shared/channel-audience.js";
-import { applyAudienceCeiling } from "#shared/instrumentation-content.js";
+import {
+ applyAudienceCeiling,
+ type InstrumentationContentContext,
+} from "#shared/instrumentation-content.js";
import type { InstrumentationDecision } from "#shared/instrumentation-decision.js";
import {
DROP_INSTRUMENTATION,
@@ -59,11 +62,12 @@ export function applyLiveDeliveryAudienceCeiling(
decision: InstrumentationDecision,
liveAudience: ChannelAudience,
forwardedTracePolicy: ForwardedTraceAssertion | undefined,
+ environment: InstrumentationContentContext["environment"],
): InstrumentationDecision {
return forwardedTracePolicy !== undefined &&
(liveAudience === "unknown" || liveAudience === forwardedTracePolicy.originAudience)
? decision
- : applyAudienceCeiling(decision, liveAudience);
+ : applyAudienceCeiling(decision, { audience: liveAudience, environment });
}
export function readForwardedTraceAssertion(value: unknown): ForwardedTraceAssertion | undefined {
diff --git a/packages/eve/src/shared/instrumentation-channel-kind.ts b/packages/eve/src/shared/instrumentation-channel-kind.ts
new file mode 100644
index 000000000..860480eb2
--- /dev/null
+++ b/packages/eve/src/shared/instrumentation-channel-kind.ts
@@ -0,0 +1,13 @@
+import type { InstrumentationChannelKind } from "#public/channels/index.js";
+
+const FRAMEWORK_CHANNEL_KINDS: ReadonlySet<string> = new Set(["http", "schedule", "subagent"]);
+
+export function isInstrumentationChannelKind(kind: string): kind is InstrumentationChannelKind {
+ return kind.startsWith("channel:") || FRAMEWORK_CHANNEL_KINDS.has(kind);
+}
+
+export function normalizeInstrumentationChannelKind(
+ rawKind: string | undefined,
+): InstrumentationChannelKind {
+ return rawKind !== undefined && isInstrumentationChannelKind(rawKind) ? rawKind : "unknown";
+}
diff --git a/packages/eve/src/shared/instrumentation-content.ts b/packages/eve/src/shared/instrumentation-content.ts
index b500f6e5e..5a0631910 100644
--- a/packages/eve/src/shared/instrumentation-content.ts
+++ b/packages/eve/src/shared/instrumentation-content.ts
@@ -1,19 +1,25 @@
-import type { ChannelAudience } from "#shared/channel-audience.js";
import type { InstrumentationDecision } from "#shared/instrumentation-decision.js";
-import { isEveDevEnvironment } from "#internal/application/dev-environment.js";
+import type { ConversationEnvironment } from "#shared/conversation-context.js";
+import type { ChannelAudience } from "#shared/channel-audience.js";
+
+export interface InstrumentationContentContext {
+ readonly audience: ChannelAudience;
+ readonly environment: ConversationEnvironment;
+}
-/** Hosted instrumentation records conversation content only for known-public channels. */
-export function shouldCaptureInstrumentationContent(audience: ChannelAudience): boolean {
- if (audience === "public") return true;
- return audience === "unknown" && isEveDevEnvironment();
+/** Content is public evidence, or local debugging evidence in development. */
+export function shouldCaptureInstrumentationContent(
+ context: InstrumentationContentContext,
+): boolean {
+ return context.audience === "public" || context.environment === "development";
}
/** Per-delivery audience is a hard ceiling over the session-level trace decision. */
export function applyAudienceCeiling(
decision: InstrumentationDecision,
- audience: ChannelAudience,
+ context: InstrumentationContentContext,
): InstrumentationDecision {
- if (decision.action === "drop" || shouldCaptureInstrumentationContent(audience)) {
+ if (decision.action === "drop" || shouldCaptureInstrumentationContent(context)) {
return decision;
}
return { action: "record", recordInputs: false, recordOutputs: false };
diff --git a/packages/eve/src/shared/trace-policy.ts b/packages/eve/src/shared/trace-policy.ts
index a46a4bb63..e7b440440 100644
--- a/packages/eve/src/shared/trace-policy.ts
+++ b/packages/eve/src/shared/trace-policy.ts
@@ -1,5 +1,5 @@
-import type { ChannelAudience } from "#shared/channel-audience.js";
import { shouldCaptureInstrumentationContent } from "#shared/instrumentation-content.js";
+import type { ConversationContext } from "#shared/conversation-context.js";
import {
DROP_INSTRUMENTATION,
type InstrumentationDecision,
@@ -8,11 +8,7 @@ import {
/** @deprecated Use `TraceCapturePolicy` to select directional content. */
export type InstrumentationCapture = "content" | "metadata";
-export interface TraceCaptureContext {
- readonly agentName: string;
- readonly audience: ChannelAudience;
- readonly channelType?: string;
-}
+export type TraceCaptureContext = { readonly agentName: string } & ConversationContext;
export type TracePolicyDecision =
| { readonly emit: false }
@@ -42,18 +38,14 @@ export function resolveTracePolicy(
onError?: (error: unknown) => void,
): InstrumentationDecision {
try {
- const decision = policy?.({
- agentName: trace.agentName,
- audience: trace.audience,
- channelType: trace.channelType,
- });
+ const decision = policy?.(trace);
return resolveTracePolicyDecision(
decision ?? {
emit: true,
- recordInputs: trace.audience === "public",
- recordOutputs: trace.audience === "public",
+ recordInputs: trace.audience === "public" || trace.environment === "development",
+ recordOutputs: trace.audience === "public" || trace.environment === "development",
},
- trace.audience,
+ trace,
);
} catch (error) {
try {
@@ -65,11 +57,14 @@ export function resolveTracePolicy(
export function resolveTracePolicyDecision(
decision: TracePolicyDecision | boolean,
- audience: ChannelAudience,
+ context: {
+ readonly audience: TraceCaptureContext["audience"];
+ readonly environment: TraceCaptureContext["environment"];
+ },
): InstrumentationDecision {
if (decision === false) return DROP_INSTRUMENTATION;
if (decision === true) {
- const content = shouldCaptureInstrumentationContent(audience);
+ const content = shouldCaptureInstrumentationContent(context);
return { action: "record", recordInputs: content, recordOutputs: content };
}
if (!decision.emit) return DROP_INSTRUMENTATION;
diff --git a/packages/eve/src/subagents/auth-proxy.integration.test.ts b/packages/eve/src/subagents/auth-proxy.integration.test.ts
index 6abada6c8..88d050d00 100644
--- a/packages/eve/src/subagents/auth-proxy.integration.test.ts
+++ b/packages/eve/src/subagents/auth-proxy.integration.test.ts
@@ -222,7 +222,6 @@ describe("subagent authorization proxy", () => {
expect(required.serializedContext[ChannelKey.name]).toEqual({
kind: authorizationAdapter.kind,
state: { pendingName: "linear" },
- audience: "unknown",
});
const completedEvent: SubagentAuthorizationEvent = {
@@ -246,7 +245,6 @@ describe("subagent authorization proxy", () => {
expect(completed.serializedContext[ChannelKey.name]).toEqual({
kind: authorizationAdapter.kind,
state: { outcome: "authorized" },
- audience: "unknown",
});
expect(chunks).toHaveLength(6);
expect(decodeEvent(chunks[0]!)).toMatchObject(requiredEvent);
diff --git a/packages/eve/src/subagents/start-local.ts b/packages/eve/src/subagents/start-local.ts
index 603eab2ea..ad8a0a88b 100644
--- a/packages/eve/src/subagents/start-local.ts
+++ b/packages/eve/src/subagents/start-local.ts
@@ -23,6 +23,9 @@ export async function startLocalSubagent(input: {
readonly bundle: CompiledBundle;
readonly capabilities: Parameters<typeof buildSubagentRunInput>[0]["capabilities"];
readonly channelMetadata: Parameters<typeof buildSubagentRunInput>[0]["channelMetadata"];
+ readonly inheritedConversation?: Parameters<
+ typeof buildSubagentRunInput
+ >[0]["inheritedConversation"];
readonly currentSession: RuntimeSession;
readonly dynamicSubagentAgentConfig?: DynamicSubagentAgentConfig;
readonly fanoutSize: number;
@@ -46,6 +49,7 @@ export async function startLocalSubagent(input: {
auth: input.auth,
capabilities: input.capabilities,
channelMetadata: input.channelMetadata,
+ inheritedConversation: input.inheritedConversation,
fanoutSize: input.fanoutSize,
initiatorAuth: input.initiatorAuth,
graph: input.bundle.graph,
diff --git a/packages/eve/src/subagents/tool.ts b/packages/eve/src/subagents/tool.ts
index 9e114ea0a..b241e4c82 100644
--- a/packages/eve/src/subagents/tool.ts
+++ b/packages/eve/src/subagents/tool.ts
@@ -17,6 +17,7 @@ import type { RuntimeSubagentDispatchRequest } from "#shared/action-types.js";
import { mintSubagentContinuationToken } from "#execution/session.js";
import { resolveRemainingSessionTokenLimits } from "#subagents/token-budget.js";
import type { JsonObject } from "#shared/json.js";
+import type { ConversationContext } from "#shared/conversation-context.js";
export type SubagentInputSource =
| {
@@ -71,6 +72,8 @@ export function buildSubagentRunInput(input: {
*/
readonly capabilities?: SessionCapabilities;
readonly channelMetadata?: ChannelInstrumentationProjection;
+ /** Parent's immutable conversation classification. */
+ readonly inheritedConversation?: ConversationContext;
/**
* Number of local subagent calls dispatched in this batch. The parent's
* remaining token quota is split evenly across them so parallel children
@@ -94,7 +97,16 @@ export function buildSubagentRunInput(input: {
/** Owning task when this child starts from a background workflow tool. */
readonly taskId?: string;
}): SubagentRunInputBuild {
- const { action, auth, capabilities, channelMetadata, initiatorAuth, session, source } = input;
+ const {
+ action,
+ auth,
+ capabilities,
+ channelMetadata,
+ inheritedConversation,
+ initiatorAuth,
+ session,
+ source,
+ } = input;
const childContinuationToken = mintSubagentContinuationToken(
`${session.sessionId}:${action.callId}`,
@@ -131,6 +143,7 @@ export function buildSubagentRunInput(input: {
auth,
capabilities,
channelMetadata,
+ inheritedConversation,
continuationToken: childContinuationToken,
initiatorAuth,
input: {
diff --git a/packages/eve/src/tracing/agent-invocation-coordinator.test.ts b/packages/eve/src/tracing/agent-invocation-coordinator.test.ts
index a883ba9f9..9aabf564e 100644
--- a/packages/eve/src/tracing/agent-invocation-coordinator.test.ts
+++ b/packages/eve/src/tracing/agent-invocation-coordinator.test.ts
@@ -9,8 +9,16 @@ import { deriveAgentActionSpanId } from "#tracing/agent-span-id-generator.js";
import { ContextAgentTraceStateStore } from "#tracing/agent-trace-context-store.js";
import { deriveTaskId } from "#tasks/task-id.js";
import { actionIdempotencyKey } from "#instrumentation/lifecycle.js";
+import type { ConversationContext } from "#shared/conversation-context.js";
const outerKey = actionIdempotencyKey("session-1", "turn-1", "workflow");
+const conversation: ConversationContext = {
+ audience: "private",
+ channel: { kind: "http" },
+ environment: "production",
+ mode: "conversation",
+ principalType: "anonymous",
+};
const sessionState = {
"eve.runtime.workflowToolRuns": [
@@ -120,7 +128,7 @@ describe("agent invocation trace coordinator", () => {
const serializedContext = await serializeContext(context);
const prepared = prepareAgentInvocationTrace({
- channelMetadata: { kind: "http", metadata: { audience: "private" } },
+ conversation,
invocation: {
callId: "workflow",
kind,
@@ -261,7 +269,7 @@ describe("agent invocation trace coordinator", () => {
function prepare(serializedContext: Record<string, unknown>, callId: string) {
return prepareAgentInvocationTrace({
- channelMetadata: { kind: "http", metadata: { audience: "private" } },
+ conversation,
invocation: {
callId,
kind: "subagent-call",
diff --git a/packages/eve/src/tracing/agent-invocation-coordinator.ts b/packages/eve/src/tracing/agent-invocation-coordinator.ts
index b44b7bf5b..6f0b87fb3 100644
--- a/packages/eve/src/tracing/agent-invocation-coordinator.ts
+++ b/packages/eve/src/tracing/agent-invocation-coordinator.ts
@@ -1,10 +1,11 @@
-import type { ChannelInstrumentationProjection, SessionTraceContext } from "#channel/types.js";
+import type { SessionTraceContext } from "#channel/types.js";
import { ConversationIdKey } from "#context/keys.js";
import { readConversationId } from "#tracing/conversation-context.js";
import type { RuntimeSubagentResult } from "#shared/action-types.js";
import type { SessionStateMap } from "#harness/types.js";
import { getWorkflowToolRuns } from "#harness/workflow-tool-runs.js";
-import { normalizeChannelAudience, type ChannelAudience } from "#shared/channel-audience.js";
+import { type ChannelAudience } from "#shared/channel-audience.js";
+import type { ConversationContext } from "#shared/conversation-context.js";
import {
applyLiveDeliveryAudienceCeiling,
readForwardedTraceAssertion,
@@ -29,7 +30,7 @@ export interface AgentChildTraceDispatch {
}
export function prepareAgentInvocationTrace(input: {
- readonly channelMetadata?: ChannelInstrumentationProjection;
+ readonly conversation?: ConversationContext;
readonly invocation: {
readonly callId: string;
readonly kind: "remote-agent-call" | "subagent-call";
@@ -58,7 +59,9 @@ export function prepareAgentInvocationTrace(input: {
: taskAction?.callId;
const turnId = taskAction?.turnId ?? input.turnId;
const parentTurnContext = readTurnTraceContext(input.serializedContext, input.sessionId, turnId);
- const liveAudience = normalizeChannelAudience(input.channelMetadata?.metadata.audience);
+ const conversation = input.conversation;
+ const liveAudience = conversation?.audience ?? "unknown";
+ const environment = conversation?.environment ?? "production";
const outerTrace =
(parentActionCallId === undefined
? undefined
@@ -75,6 +78,7 @@ export function prepareAgentInvocationTrace(input: {
outerTrace.decision,
liveAudience,
outerTrace.forwardedTracePolicy,
+ environment,
);
const serializedContext =
parentActionCallId === undefined
@@ -118,6 +122,7 @@ export function prepareAgentInvocationTrace(input: {
storedParentTraceContext.decision,
liveAudience,
forwardedTracePolicy,
+ environment,
),
};
return {
diff --git a/packages/eve/src/tracing/agent-memory-instrumentation.ts b/packages/eve/src/tracing/agent-memory-instrumentation.ts
index 5b08c43c6..bfd743994 100644
--- a/packages/eve/src/tracing/agent-memory-instrumentation.ts
+++ b/packages/eve/src/tracing/agent-memory-instrumentation.ts
@@ -32,6 +32,7 @@ import { withChannelAudience } from "#tracing/channel-audience-context.js";
import { withErrorContent } from "#tracing/error-content-context.js";
import { isSampledTrace } from "#tracing/sampled-trace.js";
import { suppressTracing } from "#tracing/suppress-tracing.js";
+import type { ConversationEnvironment } from "#shared/conversation-context.js";
type SpanState = { readonly context: Context; readonly span: Span };
@@ -47,10 +48,12 @@ export interface AgentMemoryInstrumentation {
}
export function createAgentMemoryInstrumentation(input: {
- readonly recordOutputs: boolean;
+ readonly environment: ConversationEnvironment;
+ readonly recordOutputs?: boolean;
readonly stateStore: AgentTraceStateStore;
readonly tracer: Tracer;
}): AgentMemoryInstrumentation {
+ const recordOutputs = input.recordOutputs ?? false;
const spans = new Map<string, SpanState>();
const parentContext = async (
@@ -133,6 +136,7 @@ export function createAgentMemoryInstrumentation(input: {
decision,
normalizeChannelAudience(session?.channelAudience),
seed?.forwardedTracePolicy,
+ input.environment,
);
return parent === undefined
? await execute()
@@ -140,7 +144,7 @@ export function createAgentMemoryInstrumentation(input: {
markAgentTraceContext(
withErrorContent(
parent,
- input.recordOutputs && effective?.action === "record" && effective.recordOutputs,
+ recordOutputs && effective?.action === "record" && effective.recordOutputs,
),
),
execute,
diff --git a/packages/eve/src/tracing/agent-otel-provider.test.ts b/packages/eve/src/tracing/agent-otel-provider.test.ts
index 7b0a5c27f..6965403ba 100644
--- a/packages/eve/src/tracing/agent-otel-provider.test.ts
+++ b/packages/eve/src/tracing/agent-otel-provider.test.ts
@@ -58,6 +58,7 @@ import {
} from "#tracing/span-export-policy.js";
import { CONTENT_ATTRIBUTE_LIMIT } from "#tracing/agent-otel-content.js";
import type { TraceCapturePolicy } from "#tracing/otel-declaration.js";
+import type { TraceCaptureContext } from "#shared/trace-policy.js";
import {
actionIdempotencyKey,
attemptIdempotencyKey,
@@ -74,6 +75,15 @@ import {
import { preserveSerializedBackgroundTaskObservabilityState } from "#shared/serialized-observability-state.js";
import { isRuntimeWorkflowToolAction } from "#shared/action-types.js";
+const traceContext = (audience: ChannelAudience = "public") => ({
+ agentName: "weather",
+ audience,
+ channel: { kind: "http" as const },
+ environment: "production" as const,
+ mode: "conversation" as const,
+ principalType: "anonymous",
+});
+
interface TestRuntime {
readonly exporter: InMemorySpanExporter;
readonly hooks: InstrumentationHooks;
@@ -121,10 +131,7 @@ function createRuntime(
};
if (tracePolicy !== null) agentOtelInput.tracePolicy = tracePolicy;
const agentOtel = createAgentOtelInstrumentation(agentOtelInput);
- const hooks = createInstrumentationHooks([agentOtel.hook]).forTrace!({
- agentName: "weather",
- audience: "public",
- });
+ const hooks = createInstrumentationHooks([agentOtel.hook]).forTrace!(traceContext());
return {
exporter,
hooks,
@@ -167,10 +174,7 @@ async function emitAttempt(input: {
turnId: input.turnId,
};
const hooks =
- input.hooks.forTrace?.({
- agentName: "weather",
- audience: scope.channelAudience ?? "unknown",
- }) ?? input.hooks;
+ input.hooks.forTrace?.(traceContext(scope.channelAudience ?? "unknown")) ?? input.hooks;
if (input.turnAlreadyStarted !== true) {
await publishTurnStarted({ ...input, hooks });
}
@@ -802,15 +806,15 @@ describe("createAgentOtelInstrumentation", () => {
expect(turn.parentSpanContext).toBeUndefined();
});
- it("passes channelType to the policy on the seedless fallback path", async () => {
- let captured: { channelType?: string } | undefined;
+ it("passes the channel to the policy on the seedless fallback path", async () => {
+ let captured: TraceCaptureContext | undefined;
const runtime = createRuntime(undefined, (trace) => {
captured = trace;
return true;
});
const sessionEvent = {
agentName: "weather",
- channelType: "slack",
+ channelKind: "channel:slack",
idempotencyKey: sessionIdempotencyKey("session-noseed-kind"),
rootSessionId: "session-noseed-kind",
sessionId: "session-noseed-kind",
@@ -819,7 +823,7 @@ describe("createAgentOtelInstrumentation", () => {
await runtime.prepareSessionTrace(sessionEvent);
- expect(captured?.channelType).toBe("slack");
+ expect(captured?.channel.kind).toBe("channel:slack");
});
it("allocates independent trace context for delegated agents", async () => {
@@ -2696,7 +2700,7 @@ describe("createAgentOtelInstrumentation", () => {
stepIndex: 0,
turnId: "turn-1",
};
- const hooks = runtime.hooks.forTrace!({ agentName: "weather", audience: "public" });
+ const hooks = runtime.hooks.forTrace!(traceContext("public"));
await hooks.publish({
agentName: "weather",
channelAudience: "public",
@@ -2765,10 +2769,7 @@ describe("createAgentOtelInstrumentation", () => {
stateStore: new InMemoryAgentTraceStateStore(),
tracer: provider.getTracer("eve.agent"),
});
- const hooks = createInstrumentationHooks([agentOtel.hook]).forTrace!({
- agentName: "weather",
- audience: "public",
- });
+ const hooks = createInstrumentationHooks([agentOtel.hook]).forTrace!(traceContext("public"));
await emitAttempt({
hooks,
runInContext: agentOtel.runInContext,
diff --git a/packages/eve/src/tracing/agent-otel-provider.ts b/packages/eve/src/tracing/agent-otel-provider.ts
index dd20970d3..c23901cf9 100644
--- a/packages/eve/src/tracing/agent-otel-provider.ts
+++ b/packages/eve/src/tracing/agent-otel-provider.ts
@@ -75,10 +75,13 @@ import {
} from "#tracing/agent-span-contract.js";
import { withErrorContent } from "#tracing/error-content-context.js";
import { recordAgentSpanError as recordError } from "#tracing/agent-span-error.js";
+import { resolveInstrumentationEnvironment } from "#internal/application/dev-environment.js";
+import type { ConversationEnvironment } from "#shared/conversation-context.js";
type SpanState = { readonly context: Context; readonly span: Span };
export interface AgentOtelInstrumentationInput {
+ readonly environment?: ConversationEnvironment;
/** Whether any destination records model and tool inputs. */
readonly recordInputs?: boolean;
/** Whether any destination records model and tool outputs. */
@@ -107,6 +110,7 @@ export interface AgentOtelInstrumentation {
export function createAgentOtelInstrumentation(
input: AgentOtelInstrumentationInput,
): AgentOtelInstrumentation {
+ const environment = input.environment ?? resolveInstrumentationEnvironment();
const recordInputs = input.recordInputs ?? false;
const recordOutputs = input.recordOutputs ?? false;
const executionContexts = new WeakMap<InstrumentationAttemptScope, Map<string, Context>>();
@@ -146,13 +150,9 @@ export function createAgentOtelInstrumentation(
},
tracer: input.tracer,
});
- const memory = createAgentMemoryInstrumentation({
- recordOutputs,
- stateStore: input.stateStore,
- tracer: input.tracer,
- });
+ const memory = createAgentMemoryInstrumentation({ ...input, environment });
const { ensureSessionContext, prepareSessionTrace, prepareTurnTrace } =
- createAgentOtelSessionContext(input);
+ createAgentOtelSessionContext({ ...input, environment });
const projectEvent = async (event: InstrumentationEvent): Promise<InstrumentationEvent> => {
const session = await input.stateStore.getSession(sessionIdForEvent(event));
@@ -164,17 +164,17 @@ export function createAgentOtelInstrumentation(
eventSeed,
contextTraceState?.forwardedTracePolicy,
);
+ const decisionForTrace = (trace: { readonly traceFlags: number } | undefined) =>
+ trace === undefined
+ ? undefined
+ : resolveTracePolicyDecision(isSampledTrace(trace), { audience, environment });
const decision =
eventTraceState?.decision ??
contextTraceState?.decision ??
readInstrumentationDecision(session?.decision) ??
- (eventSeed !== undefined
- ? resolveTracePolicyDecision(isSampledTrace(eventSeed), audience)
- : contextSeed !== undefined
- ? resolveTracePolicyDecision(isSampledTrace(contextSeed), audience)
- : session !== undefined
- ? resolveTracePolicyDecision(isSampledTrace(session.context), audience)
- : undefined);
+ decisionForTrace(eventSeed) ??
+ decisionForTrace(contextSeed) ??
+ decisionForTrace(session?.context);
if (decision === undefined) return withoutInstrumentationContent(event);
const normalizedEvent =
eventTraceState === undefined || !("traceSeed" in event) || event.traceSeed === undefined
@@ -199,8 +199,9 @@ export function createAgentOtelInstrumentation(
},
audience,
eventTraceState?.forwardedTracePolicy ?? contextTraceState?.forwardedTracePolicy,
+ environment,
),
- audience,
+ { audience, environment },
{ applyAudienceCeiling: false },
);
};
@@ -591,6 +592,7 @@ export function createAgentOtelInstrumentation(
decision,
normalizeChannelAudience(operation.scope.channelAudience),
seed?.forwardedTracePolicy,
+ environment,
);
return parent === undefined
? execute()
diff --git a/packages/eve/src/tracing/agent-otel-session-context.ts b/packages/eve/src/tracing/agent-otel-session-context.ts
index 8116023f7..4e0dc77f7 100644
--- a/packages/eve/src/tracing/agent-otel-session-context.ts
+++ b/packages/eve/src/tracing/agent-otel-session-context.ts
@@ -24,8 +24,11 @@ import {
import { agentActivationAttributes } from "#tracing/agent-otel-runtime-context.js";
import type { AgentTurnTraceState } from "#tracing/agent-trace-state.js";
import { applyPrincipalTraceDecision } from "#instrumentation/principal-summary.js";
+import { normalizeInstrumentationChannelKind } from "#internal/instrumentation.js";
+import type { ConversationEnvironment } from "#shared/conversation-context.js";
interface AgentOtelSessionContextInput {
+ readonly environment: ConversationEnvironment;
readonly frameworkVersion: string;
readonly idGenerator: AgentSpanIdGenerator;
readonly samplesTrace?: (traceId: string, operation?: AgentSamplingOperation) => boolean;
@@ -52,7 +55,12 @@ export function createAgentOtelSessionContext(
let state = await input.stateStore.getSession(event.sessionId);
if (state === undefined) {
const channelAudience = normalizeChannelAudience(event.channelAudience);
- const decision = resolveSessionTraceDecision(event, channelAudience, input.tracePolicy);
+ const decision = resolveSessionTraceDecision(
+ event,
+ channelAudience,
+ input.environment,
+ input.tracePolicy,
+ );
state = {
agentName: event.agentName,
channelAudience,
@@ -186,8 +194,10 @@ function freshTurnContext(
function resolveSessionTraceDecision(
event: SessionMetadata,
audience: ChannelAudience,
+ environment: ConversationEnvironment,
policy: TraceCapturePolicy | undefined,
): ReturnType<typeof resolveTracePolicy> {
+ const content = { audience, environment };
if (event.parentTraceContext !== undefined && !isSampledTrace(event.parentTraceContext)) {
return { action: "drop" };
}
@@ -195,19 +205,24 @@ function resolveSessionTraceDecision(
return readInstrumentationDecision(event.traceSeed.decision) ?? { action: "drop" };
}
if (event.traceSeed !== undefined) {
- return resolveTracePolicyDecision(isSampledTrace(event.traceSeed), audience);
+ return resolveTracePolicyDecision(isSampledTrace(event.traceSeed), content);
}
if (event.parentTraceContext !== undefined) {
- return resolveTracePolicyDecision(isSampledTrace(event.parentTraceContext), audience);
+ return resolveTracePolicyDecision(isSampledTrace(event.parentTraceContext), content);
}
if (event.agentName === undefined) {
- return policy === undefined ? resolveTracePolicyDecision(true, audience) : { action: "drop" };
+ return policy === undefined ? resolveTracePolicyDecision(true, content) : { action: "drop" };
}
// The tool loop can evaluate the same policy before this first-session
// preparation path; the persisted decision removes that window on replay.
return resolveTracePolicy(policy, {
agentName: event.agentName,
audience,
- channelType: event.channelType,
+ channel: {
+ kind: normalizeInstrumentationChannelKind(event.channelKind ?? event.channelType),
+ },
+ environment,
+ mode: "conversation",
+ principalType: "unknown",
});
}
diff --git a/packages/eve/src/tracing/agent-telemetry-contract.integration.test.ts b/packages/eve/src/tracing/agent-telemetry-contract.integration.test.ts
index e64480ad8..901de1842 100644
--- a/packages/eve/src/tracing/agent-telemetry-contract.integration.test.ts
+++ b/packages/eve/src/tracing/agent-telemetry-contract.integration.test.ts
@@ -55,6 +55,16 @@ import {
redactSpanInputs,
redactSpanOutputs,
} from "#tracing/span-export-policy.js";
+import { ConversationContextKey } from "#shared/conversation-context.js";
+
+const traceContext = (agentName: string, audience: "public" | "private") => ({
+ agentName,
+ audience,
+ channel: { kind: "http" as const },
+ environment: "production" as const,
+ mode: "conversation" as const,
+ principalType: "anonymous",
+});
function createRuntime() {
const exporter = new InMemorySpanExporter();
@@ -101,7 +111,8 @@ function createRuntime() {
function contextFor(audience: "public" | "private") {
const ctx = new ContextContainer();
- ctx.set(ChannelInstrumentationKey, { kind: "http", metadata: { audience } });
+ ctx.set(ChannelInstrumentationKey, { kind: "http", metadata: {} });
+ ctx.set(ConversationContextKey, traceContext("parent", audience));
ctx.set(AuthKey, {
principalId: "current-user",
principalType: "service",
@@ -221,7 +232,7 @@ describe("exported agent telemetry contract", () => {
async (type) => {
const runtime = createRuntime();
const ctx = contextFor("public");
- const hooks = runtime.hooks.forTrace!({ agentName: "parent", audience: "public" });
+ const hooks = runtime.hooks.forTrace!(traceContext("parent", "public"));
await contextStorage.run(ctx, async () => {
const store = new ContextAgentTraceStateStore();
store.setInvocation(actionIdempotencyKey("parent", "turn_0", "nested"), {
@@ -264,7 +275,7 @@ describe("exported agent telemetry contract", () => {
let parent = contextFor(audience);
parent.set(ConversationIdKey, "original-conversation");
const scope = scopeFor("parent", audience);
- const hooks = runtime.hooks.forTrace!({ agentName: "parent", audience });
+ const hooks = runtime.hooks.forTrace!(traceContext("parent", audience));
const actionKey = actionIdempotencyKey("parent", "turn_0", "workflow");
const operation = { modelId: "test", operationId: "ai.streamText", provider: "test" };
const binding = bindInstrumentationRuntime(runtime, parent, {
@@ -344,7 +355,7 @@ describe("exported agent telemetry contract", () => {
type: "input.resolved",
});
dispatch = prepareAgentInvocationTrace({
- channelMetadata: parent.get(ChannelInstrumentationKey),
+ conversation: parent.get(ConversationContextKey),
invocation: { callId: "nested", kind: "subagent-call", name: "child" },
ownerId: "workflow-run",
startTimeMs: Date.now(),
@@ -381,7 +392,7 @@ describe("exported agent telemetry contract", () => {
});
}
const childScope = scopeFor("child", audience);
- const childHooks = runtime.hooks.forTrace!({ agentName: "child", audience });
+ const childHooks = runtime.hooks.forTrace!(traceContext("child", audience));
await contextStorage.run(child, async () => {
const childBinding = bindInstrumentationRuntime(runtime, child, {
agentName: "child",
@@ -678,7 +689,7 @@ describe("exported agent telemetry contract", () => {
it("exports new current principals but the same initiator on resumed activations", async () => {
const runtime = createRuntime();
const ctx = contextFor("public");
- const hooks = runtime.hooks.forTrace!({ agentName: "parent", audience: "public" });
+ const hooks = runtime.hooks.forTrace!(traceContext("parent", "public"));
const binding = bindInstrumentationRuntime(runtime, ctx, {
agentName: "parent",
rootSessionId: "parent",
@@ -741,7 +752,7 @@ describe("exported agent telemetry contract", () => {
"bounds public-channel principal IDs by origin %s and input/output ceiling %s/%s",
async (originAudience, recordInputs, recordOutputs) => {
const runtime = createRuntime();
- const hooks = runtime.hooks.forTrace!({ agentName: "child", audience: "public" });
+ const hooks = runtime.hooks.forTrace!(traceContext("child", "public"));
const registered = vi
.spyOn(instrumentation, "getInstrumentationRuntime")
.mockReturnValue(runtime);
@@ -826,7 +837,7 @@ describe("exported agent telemetry contract", () => {
async (outcome) => {
const runtime = createRuntime();
const ctx = contextFor("private");
- const hooks = runtime.hooks.forTrace!({ agentName: "parent", audience: "private" });
+ const hooks = runtime.hooks.forTrace!(traceContext("parent", "private"));
const binding = bindInstrumentationRuntime(runtime, ctx, {
agentName: "parent",
rootSessionId: "parent",
diff --git a/packages/eve/src/tracing/install-instrumentation-runtime.test.ts b/packages/eve/src/tracing/install-instrumentation-runtime.test.ts
index 85e098bb4..32cb08c3f 100644
--- a/packages/eve/src/tracing/install-instrumentation-runtime.test.ts
+++ b/packages/eve/src/tracing/install-instrumentation-runtime.test.ts
@@ -144,7 +144,7 @@ describe("installInstrumentationRuntime", () => {
providers: [],
serviceName: "weather",
});
- const hooks = runtime.hooks.forTrace!({ agentName: "weather", audience: "unknown" });
+ const hooks = runtime.hooks.forTrace!(traceContext("unknown"));
const event = {
idempotencyKey: sessionIdempotencyKey(sessionId),
sessionId,
@@ -178,7 +178,7 @@ describe("installInstrumentationRuntime", () => {
serviceName: "weather",
});
const idempotencyKey = turnIdempotencyKey("session-1", "turn-1");
- const hooks = runtime.hooks.forTrace!({ agentName: "weather", audience: "unknown" });
+ const hooks = runtime.hooks.forTrace!(traceContext("unknown"));
await contextStorage.run(new ContextContainer(), async () => {
await hooks.publish({
@@ -201,3 +201,12 @@ describe("installInstrumentationRuntime", () => {
expect(authoredTerminalState).toHaveBeenCalledExactlyOnceWith("authored");
});
});
+
+const traceContext = (audience: "public" | "private" | "unknown") => ({
+ agentName: "weather",
+ audience,
+ channel: { kind: "http" as const },
+ environment: "production" as const,
+ mode: "conversation" as const,
+ principalType: "anonymous",
+});
diff --git a/packages/eve/src/tracing/install-instrumentation-runtime.ts b/packages/eve/src/tracing/install-instrumentation-runtime.ts
index 48ed1e4e0..cd33c6b34 100644
--- a/packages/eve/src/tracing/install-instrumentation-runtime.ts
+++ b/packages/eve/src/tracing/install-instrumentation-runtime.ts
@@ -12,6 +12,7 @@ import {
type InstrumentationRuntime,
} from "#instrumentation/runtime.js";
import { createLogger, formatError } from "#internal/logging.js";
+import { resolveInstrumentationEnvironment } from "#internal/application/dev-environment.js";
import { AgentSpanIdGenerator } from "#tracing/agent-span-id-generator.js";
import { ContextAgentTraceStateStore } from "#tracing/agent-trace-context-store.js";
import { createAgentOtelInstrumentation } from "#tracing/agent-otel-provider.js";
@@ -54,6 +55,7 @@ export function installInstrumentationRuntime(input: {
serviceName: input.serviceName,
});
const agentOtel = createAgentOtelInstrumentation({
+ environment: resolveInstrumentationEnvironment(),
frameworkVersion: input.frameworkVersion,
idGenerator: otelRuntime.idGenerator,
recordInputs: input.collected.settings.recordInputs,
diff --git a/packages/eve/src/tracing/local-instrumentation-runtime.scenario.test.ts b/packages/eve/src/tracing/local-instrumentation-runtime.scenario.test.ts
index f3e0f8dd5..3843d9257 100644
--- a/packages/eve/src/tracing/local-instrumentation-runtime.scenario.test.ts
+++ b/packages/eve/src/tracing/local-instrumentation-runtime.scenario.test.ts
@@ -28,6 +28,15 @@ import { LocalTraceSpanProcessor } from "#tracing/local-trace-span-processor.js"
const temporaryDirectories: string[] = [];
const require = createRequire(import.meta.url);
+const traceContext = (audience: "public" | "private" | "unknown") => ({
+ agentName: "weather",
+ audience,
+ channel: { kind: "http" as const },
+ environment: "production" as const,
+ mode: "conversation" as const,
+ principalType: "anonymous",
+});
+
afterEach(async () => {
await Promise.all(
temporaryDirectories.splice(0).map((path) => rm(path, { force: true, recursive: true })),
@@ -59,7 +68,7 @@ describe("local instrumentation runtime", () => {
};
const delivery = runtimeTrace.getTracer("workflow").startSpan("workflow.delivery");
const activeContext = runtimeTrace.setSpan(COMPILED_ROOT_CONTEXT, delivery);
- const hooks = runtime.hooks.forTrace!({ agentName: "weather", audience: "unknown" });
+ const hooks = runtime.hooks.forTrace!(traceContext("unknown"));
const exerciseRuntime = async () => {
await hooks.publish({
diff --git a/packages/eve/src/tracing/local-instrumentation-runtime.ts b/packages/eve/src/tracing/local-instrumentation-runtime.ts
index 99cbe0f72..104ba2ac6 100644
--- a/packages/eve/src/tracing/local-instrumentation-runtime.ts
+++ b/packages/eve/src/tracing/local-instrumentation-runtime.ts
@@ -11,9 +11,8 @@ import {
type TraceCapturePolicy,
} from "#tracing/otel-declaration.js";
-/** Zero-config local tracing keeps unclassified HTTP/TUI sessions observable. @internal */
-export const localTracePolicy: TraceCapturePolicy = ({ audience }) =>
- audience === "public" || audience === "unknown";
+/** Zero-config local tracing keeps public and unclassified sessions observable. @internal */
+export const localTracePolicy: TraceCapturePolicy = ({ audience }) => audience !== "private";
/** Installs the zero-config local OTel runtime once in an `eve dev` worker. */
export function installLocalInstrumentationRuntime(input: {
diff --git a/packages/eve/src/tracing/local-traces.test.ts b/packages/eve/src/tracing/local-traces.test.ts
index 562b094c3..3d5426e6f 100644
--- a/packages/eve/src/tracing/local-traces.test.ts
+++ b/packages/eve/src/tracing/local-traces.test.ts
@@ -30,6 +30,15 @@ function agentSpan(sessionId: string, traceId: string): unknown {
};
}
+const traceContext = (audience: "public" | "private" | "unknown") => ({
+ agentName: "weather",
+ audience,
+ channel: { kind: "http" as const },
+ environment: "production" as const,
+ mode: "conversation" as const,
+ principalType: "anonymous",
+});
+
afterEach(() => {
vi.unstubAllEnvs();
});
@@ -105,11 +114,6 @@ describe("localTracePolicy", () => {
["unknown", true],
["private", false],
] as const)("accepts the %s audience: %s", (audience, accepted) => {
- expect(
- localTracePolicy({
- agentName: "weather",
- audience,
- }),
- ).toBe(accepted);
+ expect(localTracePolicy(traceContext(audience))).toBe(accepted);
});
});
diff --git a/packages/eve/src/tracing/sampled-trace.test.ts b/packages/eve/src/tracing/sampled-trace.test.ts
index 7f9be14c3..d850e9ca0 100644
--- a/packages/eve/src/tracing/sampled-trace.test.ts
+++ b/packages/eve/src/tracing/sampled-trace.test.ts
@@ -2,6 +2,22 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import { resolveTracePolicy, resolveTracePolicyDecision } from "#tracing/sampled-trace.js";
+const contentContext = (
+ audience: "public" | "private" | "unknown",
+ environment: "development" | "preview" | "production" = "production",
+) => ({ audience, environment });
+
+const traceContext = (
+ audience: "public" | "private" | "unknown",
+ environment: "development" | "preview" | "production" = "production",
+) => ({
+ agentName: "weather",
+ ...contentContext(audience, environment),
+ channel: { kind: "http" as const },
+ mode: "conversation" as const,
+ principalType: "anonymous",
+});
+
describe("resolveTracePolicyDecision", () => {
afterEach(() => vi.unstubAllEnvs());
@@ -24,28 +40,31 @@ describe("resolveTracePolicyDecision", () => {
{ action: "record", recordInputs: true, recordOutputs: true },
],
] as const)("normalizes the explicit $decision.emit decision", (decision, expected) => {
- expect(resolveTracePolicyDecision(decision, "private")).toEqual(expected);
+ expect(resolveTracePolicyDecision(decision, contentContext("private"))).toEqual(expected);
});
it("maps false to the legacy drop behavior", () => {
- expect(resolveTracePolicyDecision(false, "public")).toEqual({ action: "drop" });
+ expect(resolveTracePolicyDecision(false, contentContext("public"))).toEqual({
+ action: "drop",
+ });
});
it.each([
- ["public", true],
- ["private", false],
- ["unknown", false],
- ] as const)("maps true through the hosted %s audience ceiling", (audience, content) => {
- expect(resolveTracePolicyDecision(true, audience)).toEqual({
+ ["public", "production", true],
+ ["private", "production", false],
+ ["unknown", "production", false],
+ ["unknown", "development", true],
+ ["unknown", "preview", false],
+ ] as const)("maps true through the %s %s content ceiling", (audience, environment, content) => {
+ expect(resolveTracePolicyDecision(true, contentContext(audience, environment))).toEqual({
action: "record",
recordInputs: content,
recordOutputs: content,
});
});
- it("preserves unknown local content for a legacy true decision", () => {
- vi.stubEnv("EVE_DEV", "1");
- expect(resolveTracePolicyDecision(true, "unknown")).toEqual({
+ it("preserves unknown development content for a legacy true decision", () => {
+ expect(resolveTracePolicyDecision(true, contentContext("unknown", "development"))).toEqual({
action: "record",
recordInputs: true,
recordOutputs: true,
@@ -54,12 +73,9 @@ describe("resolveTracePolicyDecision", () => {
it("fails closed when the policy throws", () => {
expect(
- resolveTracePolicy(
- () => {
- throw new Error("boom");
- },
- { agentName: "weather", audience: "public" },
- ),
+ resolveTracePolicy(() => {
+ throw new Error("boom");
+ }, traceContext("public")),
).toEqual({ action: "drop" });
});
@@ -69,7 +85,7 @@ describe("resolveTracePolicyDecision", () => {
() => {
throw new Error("policy failed");
},
- { agentName: "weather", audience: "public" },
+ traceContext("public"),
() => {
throw new Error("reporting failed");
},
@@ -78,14 +94,19 @@ describe("resolveTracePolicyDecision", () => {
});
it.each([
- ["public", true],
- ["private", false],
- ["unknown", false],
- ] as const)("emits the default %s trace with the expected content", (audience, content) => {
- expect(resolveTracePolicy(undefined, { agentName: "weather", audience })).toEqual({
- action: "record",
- recordInputs: content,
- recordOutputs: content,
- });
- });
+ ["public", "production", true],
+ ["private", "production", false],
+ ["unknown", "production", false],
+ ["unknown", "development", true],
+ ["unknown", "preview", false],
+ ] as const)(
+ "emits the default %s %s trace with the expected content",
+ (audience, environment, content) => {
+ expect(resolveTracePolicy(undefined, traceContext(audience, environment))).toEqual({
+ action: "record",
+ recordInputs: content,
+ recordOutputs: content,
+ });
+ },
+ );
});
diff --git a/packages/eve/test/scenarios/compiled-artifacts-bootstrap.scenario.test.ts b/packages/eve/test/scenarios/compiled-artifacts-bootstrap.scenario.test.ts
index 40596675b..90935ac02 100644
--- a/packages/eve/test/scenarios/compiled-artifacts-bootstrap.scenario.test.ts
+++ b/packages/eve/test/scenarios/compiled-artifacts-bootstrap.scenario.test.ts
@@ -17,6 +17,15 @@ import { useTemporaryAppRoots } from "../../src/internal/testing/use-temporary-a
const createAppRoot = useTemporaryAppRoots();
+const traceContext = (audience: "public" | "private" | "unknown") => ({
+ agentName: "weather",
+ audience,
+ channel: { kind: "http" as const },
+ environment: "production" as const,
+ mode: "conversation" as const,
+ principalType: "anonymous",
+});
+
describe("writeCompiledArtifactsFiles", () => {
afterEach(() => {
delete (globalThis as Record<string, unknown>).__eveInstrumentationLoaded;
@@ -213,9 +222,7 @@ describe("writeCompiledArtifactsFiles", () => {
]);
const providers = getInstrumentationProviders();
expect(providers.map((entry) => entry.slot)).toEqual(["local", "otel"]);
- expect(
- providers[0]?.provider.tracePolicy?.({ agentName: "weather", audience: "public" }),
- ).toEqual({
+ expect(providers[0]?.provider.tracePolicy?.(traceContext("public"))).toEqual({
emit: true,
recordInputs: true,
recordOutputs: false,
diff --git a/research/channel-audience-content-policy.md b/research/channel-audience-content-policy.md
index d6619a61e..942ac0297 100644
--- a/research/channel-audience-content-policy.md
+++ b/research/channel-audience-content-policy.md
@@ -1,7 +1,7 @@
---
issue: https://github.com/vercel/eve/issues/2331
-status: proposed
-last_updated: "2026-09-01"
+status: implemented
+last_updated: "2026-09-13"
---
# Audience-aware trace content policy
@@ -10,19 +10,39 @@ last_updated: "2026-09-01"
Messaging agents need different trace behavior for public and private conversations. Public messages may be traced with model and tool content; private conversations should not produce traces unless an author explicitly admits them. Zero-config local tracing additionally retains unclassified HTTP/TUI sessions for debugging.
-This proposal adds a fail-closed audience classification to channel instrumentation metadata, classifies built-in messaging channels from durable platform state, and separates the process-wide trace gate from each destination's ordered export pipeline.
+This design adds a fail-closed `audience(input)` classification hook to channels, persists one framework-owned conversation context, classifies built-in messaging channels from durable platform state, and separates the process-wide trace gate from each destination's ordered export pipeline.
## Channel contract
-Channels may project one of three values from their existing synchronous `metadata(state)` callback:
+Channels declare a synchronous `audience(input)` hook. It runs after route authentication and receives channel state, the authenticated principal, channel identity, run mode, and deployment environment:
```ts
type ChannelAudience = "public" | "private" | "unknown";
+
+interface AudienceInput<TState> {
+ readonly state: TState;
+ readonly auth: AudiencePrincipal | null;
+ readonly channel: { readonly kind: InstrumentationChannelKind; readonly name?: string };
+ readonly mode: RunMode;
+ readonly environment: "development" | "preview" | "production";
+}
```
-The field is optional for authored channels. Eve normalizes absent, malformed, and unsupported values to `unknown`. Built-in channel metadata interfaces require the field and classify only from platform evidence already captured during dispatch; ambiguous and proactive destinations remain `unknown` rather than performing observability-only network requests. Proactive Slack `receive` / `ctx.send` targets may optionally supply `audience` when the caller already knows channel visibility, for example a webhook that classified the Slack destination before handoff.
+The hook is optional for authored channels. eve normalizes absent, malformed, throwing, asynchronous, and unsupported results to `unknown`. Built-in channels classify only from platform evidence already captured during dispatch; ambiguous and proactive destinations remain `unknown` rather than performing observability-only network requests. Proactive Slack `receive` / `ctx.send` targets may optionally supply `audience` state when the caller already knows channel visibility, for example a webhook that classified the Slack destination before handoff. `metadata(state)` returns custom observability fields only.
-The normalized audience is persisted with session trace state and exported as `agent.channel.audience` only on each `agent.session` window. Durable Eve state and an internal OpenTelemetry context key make the same value available to descendant export policies without duplicating a public attribute onto every span. Local subagents inherit the parent audience. A remote agent with principal forwarding propagates the immutable origin audience and the current hop's effective directional ceiling through one `eve.audience` W3C Baggage member. The receiver accepts it only with the same `trustedForwarders` decision that admitted the principal, then intersects it with its own process policy. Every later hop forwards that intersection; malformed and mixed-version assertions become metadata-only.
+The framework builds one `ConversationContext` when a session is created and persists it under `eve.conversation`:
+
+```ts
+interface ConversationContext {
+ readonly channel: { readonly kind: InstrumentationChannelKind; readonly name?: string };
+ readonly audience: ChannelAudience;
+ readonly mode: RunMode;
+ readonly environment: "development" | "preview" | "production";
+ readonly principalType: string;
+}
+```
+
+The normalized audience is exported as `agent.channel.audience` only on each `agent.session` window. Durable eve state and an internal OpenTelemetry context key make the same value available to descendant export policies without duplicating a public attribute onto every span. Local subagents inherit the parent audience. A remote agent with principal forwarding propagates the immutable origin audience and the current hop's effective directional ceiling through one `eve.audience` W3C Baggage member. The receiver accepts it only with the same `trustedForwarders` decision that admitted the principal, then intersects it with its own process policy. Every later hop forwards that intersection; malformed and mixed-version assertions become metadata-only.
## Public tracing API
@@ -31,10 +51,9 @@ This surface is available only when `experimental.instrumentationProviders` is e
The process-wide declaration owns trace creation:
```ts
-interface TraceCaptureContext {
+type TraceCaptureContext = {
readonly agentName: string;
- readonly audience: ChannelAudience;
- readonly channelType?: string;
+} & ConversationContext;
}
type TracePolicyDecision =
@@ -127,10 +146,10 @@ For example, this retains every conversation while capturing content only for pu
```ts
// agent/instrumentation/otel.ts
export default otel({
- tracePolicy: ({ audience }) => ({
+ tracePolicy: ({ audience, environment }) => ({
emit: true,
- recordInputs: audience === "public",
- recordOutputs: audience === "public",
+ recordInputs: audience === "public" || environment === "development",
+ recordOutputs: audience === "public" || environment === "development",
}),
});
@@ -149,18 +168,18 @@ export default agentRuns({
The default authored and production head policy is equivalent to:
```ts
-({ audience }) => ({
+({ audience, environment }) => ({
emit: true,
- recordInputs: audience === "public",
- recordOutputs: audience === "public",
+ recordInputs: audience === "public" || environment === "development",
+ recordOutputs: audience === "public" || environment === "development",
});
```
-| Audience | Trace created by default | Content by default |
-| --------- | ------------------------ | ------------------ |
-| `public` | Yes | Yes |
-| `private` | Yes | No |
-| `unknown` | Yes | No |
+| Audience | Development content | Preview and production content |
+| --------- | ------------------- | ------------------------------ |
+| `public` | Yes | Yes |
+| `private` | Yes | No |
+| `unknown` | Yes | No |
An explicit provider policy can authorize content for any audience. The OTel
policy remains subject to its process-wide audience ceiling.
@@ -168,16 +187,20 @@ policy remains subject to its process-wide audience ceiling.
The default policy for local tracing for `eve dev` is equivalent to:
```ts
-({ audience }) => audience === "public" || audience === "unknown";
+({ audience }) =>
+ audience === "private"
+ ? { emit: false }
+ : { emit: true, recordInputs: true, recordOutputs: true },
```
This keeps unclassified local HTTP/TUI sessions observable while still rejecting channels classified as `private`.
+Because local tracing runs in development, every emitted trace uses the development content default.
The runtime order is:
-1. Derive and normalize the channel audience.
+1. Build and persist the conversation context, deriving and normalizing the channel audience once.
2. Evaluate the process-wide `tracePolicy` before creating `agent.session`.
-3. For accepted traces, capture complete Eve and AI SDK spans.
+3. For accepted traces, capture complete eve and AI SDK spans.
4. Run each managed destination's composed export policies in declaration order. Custom integrations run their declared span processors.
5. Hand the resulting facade to that destination's processors or exporter.