The Open Framework for Building Agents
feat(eve): preserve trusted remote trace ceilings (#2736)
Chad Hietalaf43525a64b6d
diff --git a/.changeset/bright-spans-travel.md b/.changeset/bright-spans-travel.mdnew file mode 100644index 000000000..9c06c848a--- /dev/null+++ b/.changeset/bright-spans-travel.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Preserve trace content across principal-forwarding remote agents by intersecting the parent's directional capture ceiling with each trusted receiver's policy. Origin audience remains immutable across hops, private content requires explicit approval on both sides, and malformed or mixed-version assertions degrade to metadata-only.diff --git a/docs/guides/auth-and-route-protection.md b/docs/guides/auth-and-route-protection.mdindex dc58df5de..84330b457 100644--- a/docs/guides/auth-and-route-protection.md+++ b/docs/guides/auth-and-route-protection.md@@ -239,7 +239,11 @@ export default eveChannel({The predicate authorizes the _forwarder_ (the verified route-auth principal — who is asserting), not the forwarded principal (what is asserted). Match it precisely: a permissive predicate like `() => true` lets any caller that passes route auth assert any principal, including preview deployments of your own project when `vercelOidc()` is in the walk. `trustedForwarders` exists only on your authored channel — the framework default channel never accepts a forwarded principal, so a receiving deployment must author `agent/channels/eve.ts`.-When the predicate accepts a create request, `ctx.session.auth.current` and `.initiator` carry the forwarded user exactly as if they had called your deployment directly. On continuation, only `auth.current` is replaced; `auth.initiator` remains the session creator. User-scoped connections, local subagents, and further `forwardPrincipal` hops therefore see the active turn's caller. The forwarder is recorded on accepted contexts as the `eve:forwarded-by` attribute (always overwritten by the receiver, so a forwarder cannot falsify it). Rejections fail loud: a forwarded body without `trustedForwarders` configured or with a forwarder the predicate refuses is a `403`, and a malformed payload is a `400`. Only principal metadata is ever accepted — tokens and credentials never cross the hop.+When the predicate accepts a create request, `ctx.session.auth.current` and `.initiator` carry the forwarded user exactly as if they had called your deployment directly. On continuation, only `auth.current` is replaced; `auth.initiator` remains the session creator. User-scoped connections, local subagents, and further `forwardPrincipal` hops therefore see the active turn's caller.++The forwarder is recorded on accepted contexts as the `eve:forwarded-by` attribute (always overwritten by the receiver, so a forwarder cannot falsify it). Rejections fail loud: a forwarded body without `trustedForwarders` configured or with a forwarder the predicate refuses is a `403`, and a malformed payload is a `400`. Only principal metadata is ever accepted — tokens and credentials never cross the hop.++For requests marked as remote delegations by a callback body and valid sampled `traceparent`, the same accepted `trustedForwarders` result may admit an origin audience and directional content ceiling from one W3C Baggage member. The assertion is not an authorization grant: the receiver's trace policy independently decides against the immutable origin audience, and the two decisions are intersected. Every later hop forwards only that narrowed result. Malformed, partial, unsampled, or mixed-version assertions become metadata-only. The callback and headers are caller-supplied—the verified transport principal and `trustedForwarders` are the trust boundary. See [Preserving trace content](./remote-agents#preserving-trace-content).> ⚠️ Both deployments must support continuation forwarding before you resume persistent remote sessions. A create-only receiver rejects a forwarded continuation with HTTP 400; the sender does not fall back to service authority. See [Forwarding the caller identity](./remote-agents#forwarding-the-caller-identity) for the upgrade behavior.diff --git a/docs/guides/remote-agents.md b/docs/guides/remote-agents.mdindex 11f3f8bfe..3cb016be7 100644--- a/docs/guides/remote-agents.md+++ b/docs/guides/remote-agents.md@@ -143,6 +143,31 @@ Forwarding is explicit on both sides. The receiver names which forwarders it truA receiver on an eve version that predates all principal forwarding may instead drop the unknown field and run the session as your app's service identity; per-user connections there fail with `principal_required`. On remote requests where the dispatching turn has no auth, the field is omitted and the call proceeds on transport trust alone.+## Preserving trace content++With `forwardPrincipal: true`, a sampled trace carries its original audience and the maximum content the next hop may record. For example, `eve.audience=private;ceiling=i0o1` allows outputs but not inputs. eve sends this as [W3C Baggage](https://www.w3.org/TR/baggage/).++The receiver uses it only after `trustedForwarders` accepts the authenticated calling deployment:++```ts title="agent/channels/eve.ts"+import { eveChannel } from "eve/channels/eve";+import { vercelOidc, vercelSubject } from "eve/channels/auth";++export default eveChannel({+ auth: [vercelOidc()],+ trustedForwarders: (forwarder) =>+ forwarder.subject === vercelSubject({ teamSlug: "acme", projectName: "router" }),+});+```++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 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.++Missing, malformed, duplicate, unsampled, untrusted, and mixed-version assertions fall back to metadata-only tracing. Dropped traces use only the unsampled trace flag. The decision is fixed when the remote session starts and reused by continuations. Agent Runs shows Workflow content only when both inputs and outputs are allowed.+## How remote dispatch and callbacks workA local subagent runs inline. A remote one runs in its own deployment, so dispatch is asynchronous:diff --git a/packages/eve/src/channel/types.ts b/packages/eve/src/channel/types.tsindex 955aa69a8..8c757e625 100644--- a/packages/eve/src/channel/types.ts+++ b/packages/eve/src/channel/types.ts@@ -12,6 +12,7 @@ import type { ChannelAdapter } from "#channel/adapter.js";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 { TaskView } from "#tasks/types.js";export type { ContextAccessor } from "#context/key.js";@@ -88,6 +89,7 @@ export interface SessionParent {*/export interface SessionTraceContext {readonly decision?: InstrumentationDecision;+ readonly forwardedTracePolicy?: ForwardedTraceAssertion;readonly spanId: string;readonly traceFlags: number;readonly traceId: string;diff --git a/packages/eve/src/context/keys.ts b/packages/eve/src/context/keys.tsindex 0b0cb494b..70188aa85 100644--- a/packages/eve/src/context/keys.ts+++ b/packages/eve/src/context/keys.ts@@ -6,7 +6,6 @@import type { LanguageModel, ModelMessage, SystemModelMessage } from "ai";-import type { InstrumentationDecision } from "#shared/instrumentation-decision.js";import type {ActivityObserverConfig,ChannelDeliveryMetadata,@@ -107,17 +106,13 @@ export const ActiveChannelDeliveriesKey = new ContextKey<readonly ActiveChannelDexport const ChannelInstrumentationKey = new ContextKey<ChannelInstrumentationProjection>("eve.channelInstrumentation",);+/** Trace ceiling and immutable origin accepted from a trusted forwarding deployment. */export const ModeKey = new ContextKey<RunMode>("eve.mode");export const ParentSessionKey = new ContextKey<SessionParent>("eve.parentSession");/** Separate from {@link ParentSessionKey} so it stays out of what extensions read. */export const ParentTraceContextKey = new ContextKey<SessionTraceContext>("eve.parentTraceContext");-export interface SessionTraceSeed {- readonly decision?: InstrumentationDecision;- readonly traceId: string;- readonly spanId: string;- readonly traceFlags: number;-}+export type SessionTraceSeed = SessionTraceContext;export const SessionTraceSeedKey = new ContextKey<SessionTraceSeed>("eve.sessionTraceSeed");export const OtelTraceEnabledKey = new ContextKey<boolean>("eve.otelTraceEnabled");diff --git a/packages/eve/src/eve-channel/index.ts b/packages/eve/src/eve-channel/index.tsindex 072115f9c..d89a90f8e 100644--- a/packages/eve/src/eve-channel/index.ts+++ b/packages/eve/src/eve-channel/index.ts@@ -1,4 +1,4 @@-import type { SessionAuthContext } from "#channel/types.js";+import type { SessionAuthContext, SessionTraceContext } from "#channel/types.js";import type { Session } from "#channel/session.js";import { resolveForwardedPrincipal } from "#channel/forwarded-principal.js";import { isRuntimeSessionOwnershipConflictError } from "#execution/runtime-errors.js";@@ -50,6 +50,11 @@ import type { ClearResponse } from "#protocol/clear-session.js";import type { CompactResponse } from "#protocol/compact-session.js";import type { ResetResponse } from "#protocol/reset-session.js";import { parseTraceparent } from "#protocol/traceparent.js";+import { readForwardedAudienceBaggage } from "#protocol/baggage.js";+import {+ FAIL_CLOSED_FORWARDED_TRACE_ASSERTION,+ formatTraceContentCeiling,+} from "#shared/forwarded-trace-policy.js";import { routeAuth } from "#public/channels/auth.js";import { mergeUploadPolicy } from "#public/channels/upload-policy.js";import { defineChannel, DELETE, GET, HEAD, PATCH, POST, PUT } from "#public/definitions/channel.js";@@ -148,7 +153,7 @@ export function eveChannel(input: EveChannelInput): EveChannel {if (body instanceof Response) return body;// Top-level sessions own their trace. Callback sessions are delegated// remote agents and intentionally continue the dispatching agent trace.- const parentTraceContext =+ const parsedParentTraceContext =body.callback === undefined? undefined: parseTraceparent(req.headers.get("traceparent"));@@ -185,6 +190,46 @@ export function eveChannel(input: EveChannelInput): EveChannel {}}+ const forwardedTraceAssertion =+ parsedParentTraceContext === undefined+ ? "absent"+ : readForwardedAudienceBaggage(req.headers.get("baggage"));+ const acceptsForwardedTracePolicy =+ forwarded.accepted &&+ parsedParentTraceContext !== undefined &&+ (parsedParentTraceContext.traceFlags & 1) === 1;+ const acceptedForwardedTracePolicy = !acceptsForwardedTracePolicy+ ? undefined+ : typeof forwardedTraceAssertion === "object"+ ? forwardedTraceAssertion+ : forwardedTraceAssertion === "malformed"+ ? FAIL_CLOSED_FORWARDED_TRACE_ASSERTION+ : undefined;+ let parentTraceContext: SessionTraceContext | undefined = parsedParentTraceContext;+ if (acceptedForwardedTracePolicy !== undefined && parsedParentTraceContext !== undefined) {+ parentTraceContext = {+ ...parsedParentTraceContext,+ forwardedTracePolicy: acceptedForwardedTracePolicy,+ };+ }+ if (forwardedTraceAssertion === "malformed") {+ log.warn("using metadata-only policy for malformed forwarded audience baggage", {+ forwarder: authResult.principalId,+ });+ } else if (typeof forwardedTraceAssertion === "object") {+ if (acceptedForwardedTracePolicy !== undefined) {+ log.info("accepted forwarded trace policy", {+ audience: forwardedTraceAssertion.originAudience,+ ceiling: formatTraceContentCeiling(forwardedTraceAssertion.ceiling),+ forwarder: authResult.principalId,+ });+ } else {+ log.warn("ignoring forwarded trace policy without an accepted sampled principal", {+ forwarder: authResult.principalId,+ });+ }+ }+const messageResult = await resolveOnMessage({auth: forwarded.auth,config: input,diff --git a/packages/eve/src/eve-channel/types.ts b/packages/eve/src/eve-channel/types.tsindex d643f3754..7d6e8f7f5 100644--- a/packages/eve/src/eve-channel/types.ts+++ b/packages/eve/src/eve-channel/types.ts@@ -96,21 +96,21 @@ export interface EveChannelInput {readonly auth: AuthFn<Request> | readonly AuthFn<Request>[];/*** The trusted-forwarders policy: which transport-authenticated callers may- * assert a forwarded principal on the create-session or continuation route (the- * `forwardedPrincipal` body field a `defineRemoteAgent({ forwardPrincipal:- * true })` sender emits). The predicate receives the *verified* route-auth- * principal of the forwarder — who is asserting, never what is asserted —- * and must match it precisely (for example+ * assert a forwarded principal or callback-marked public trace audience. The predicate+ * receives the *verified* route-auth principal of the forwarder — who is+ * asserting, never what is asserted — and must match it precisely (for example* `(forwarder) => forwarder.subject === vercelSubject({ teamSlug, projectName })`).* A permissive predicate lets any authenticated forwarder assert any- * principal.+ * principal and public trace audience.** When a trusted forwarder's assertion is accepted on session creation, the* forwarded principal replaces `session.auth.current` and* `session.auth.initiator`. On continuation, only `session.auth.current`* changes; the initiator remains pinned to the session's creator. The* forwarder is recorded on accepted contexts as the `eve:forwarded-by`- * attribute. Omit the option to reject every forwarded assertion with 403.+ * attribute. An accepted public audience is evaluated by this deployment's+ * trace policies; the default records model and tool content. Omit the option+ * to reject forwarded principals with 403 and ignore forwarded audience.*/readonly trustedForwarders?: TrustedForwarders;/**diff --git a/packages/eve/src/execution/dispatch-runtime-actions-shared.ts b/packages/eve/src/execution/dispatch-runtime-actions-shared.tsindex c6b93d07e..bb5552ec7 100644--- a/packages/eve/src/execution/dispatch-runtime-actions-shared.ts+++ b/packages/eve/src/execution/dispatch-runtime-actions-shared.ts@@ -82,6 +82,11 @@ import { isTaskControlAction } from "#execution/tasks/parent/dispatch.js";import { isWorkflowToolAction } from "#execution/tool-run/dispatch.js";import { isSubagentDelegationAction } from "#harness/subagent-depth.js";import { resolvePreparedAgentAction } from "#execution/prepared-agent-action.js";+import { normalizeChannelAudience } from "#shared/channel-audience.js";+import {+ applyLiveDeliveryAudienceCeiling,+ readForwardedTraceAssertion,+} from "#shared/forwarded-trace-policy.js";const log = createLogger("execution.dispatch-runtime-actions");@@ -624,13 +629,28 @@ export async function startSubagent(input: {readonly taskOwned: boolean;readonly target: DispatchStartTarget;}): Promise<DispatchOutcome> {- const parentTraceContext =+ const storedParentTraceContext =readActionTraceContext(input.serializedContext,input.session.sessionId,input.batchEvent.turnId,input.target.action.callId,) ?? input.parentTraceContext;+ const forwardedTracePolicy = readForwardedTraceAssertion(+ storedParentTraceContext?.forwardedTracePolicy,+ );+ const liveAudience = normalizeChannelAudience(input.channelMetadata?.metadata.audience);+ const parentTraceContext =+ storedParentTraceContext?.decision === undefined+ ? storedParentTraceContext+ : {+ ...storedParentTraceContext,+ decision: applyLiveDeliveryAudienceCeiling(+ storedParentTraceContext.decision,+ liveAudience,+ forwardedTracePolicy,+ ),+ };switch (input.target.kind) {case "local":@@ -662,6 +682,7 @@ export async function startSubagent(input: {batchEvent: input.batchEvent,bundle: input.bundle,callbackBaseUrl: input.callbackBaseUrl,+ originAudience: forwardedTracePolicy?.originAudience ?? liveAudience,currentSession: input.currentSession,dynamicRemoteAgent: input.target.dynamicRemoteAgent,initiatorAuth: input.initiatorAuth,diff --git a/packages/eve/src/execution/dispatch-runtime-actions-step.integration.test.ts b/packages/eve/src/execution/dispatch-runtime-actions-step.integration.test.tsindex 5143bce9d..abe3fa4b7 100644--- a/packages/eve/src/execution/dispatch-runtime-actions-step.integration.test.ts+++ b/packages/eve/src/execution/dispatch-runtime-actions-step.integration.test.ts@@ -2,6 +2,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";import type { ChannelAdapter } from "#channel/adapter.js";import type { SessionAuthContext } from "#channel/types.js";+import type { ChannelAudience } from "#shared/channel-audience.js";import { ContextContainer, loadContext } from "#context/container.js";import { RemoteAgentContinueRequestError } from "#execution/remote-agent-dispatch.js";import { RuntimeSessionOwnershipConflictError } from "#execution/runtime-errors.js";@@ -34,6 +35,7 @@ import {type LocalDevRequestProvenance,SessionIdKey,SessionKey,+ SessionTraceSeedKey,} from "#context/keys.js";import { BundleKey, ChannelKey } from "#runtime/sessions/runtime-context-keys.js";import { createBundledRuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";@@ -646,16 +648,33 @@ describe("dispatchRuntimeActionsStep child starts", () => {const session = createStartSession({ kind: "remote" });const traceId = "4".repeat(32);const actionSpanId = "5".repeat(16);- installContext(session, {- definition: REMOTE_REGISTRY_DEFINITION,- nodeId: "remote/research",- });+ installContext(+ session,+ {+ definition: REMOTE_REGISTRY_DEFINITION,+ nodeId: "remote/research",+ },+ false,+ null,+ undefined,+ "private",+ );const result = await dispatchRuntimeActionsStep({callbackBaseUrl: "https://caller.example.com",parentContinuationToken: "turn-inbox",parentWritable: createWritable(),serializedContext: {+ [SessionTraceSeedKey.name]: {+ decision: { action: "record", recordInputs: true, recordOutputs: true },+ forwardedTracePolicy: {+ ceiling: { recordInputs: true, recordOutputs: true },+ originAudience: "public",+ },+ spanId: "3".repeat(16),+ traceFlags: 1,+ traceId,+ },"eve.harness.agentTrace": {actions: {"action-1": {@@ -682,7 +701,18 @@ describe("dispatchRuntimeActionsStep child starts", () => {expect(result.results).toEqual([]);expect(mocks.startRemoteAgentSession).toHaveBeenCalledWith(expect.objectContaining({- parentTraceContext: { isRemote: false, spanId: actionSpanId, traceFlags: 1, traceId },+ originAudience: "public",+ parentTraceContext: expect.objectContaining({+ decision: { action: "record", recordInputs: false, recordOutputs: false },+ forwardedTracePolicy: {+ ceiling: { recordInputs: true, recordOutputs: true },+ originAudience: "public",+ },+ isRemote: false,+ spanId: actionSpanId,+ traceFlags: 1,+ traceId,+ }),}),);expect(getAgentHandleStore(readResultSessionState(result, session))).toEqual({@@ -1335,6 +1365,7 @@ function installContext(tasks = false,auth: SessionAuthContext | null = null,localDevRequest?: LocalDevRequestProvenance,+ channelAudience?: ChannelAudience,): void {const subagentsByNodeId = new Map<string, { definition: unknown }>();if (remote !== undefined) {@@ -1359,7 +1390,12 @@ function installContext([AuthKey, auth],[BundleKey, bundle],[CapabilitiesKey, undefined],- [ChannelInstrumentationKey, undefined],+ [+ ChannelInstrumentationKey,+ channelAudience === undefined+ ? undefined+ : { kind: "slack", metadata: { audience: channelAudience } },+ ],[InitiatorAuthKey, null],[ChannelKey, ADAPTER],]);diff --git a/packages/eve/src/execution/eve-workflow-attributes.test.ts b/packages/eve/src/execution/eve-workflow-attributes.test.tsindex 189acb6d7..2a56d4d3f 100644--- a/packages/eve/src/execution/eve-workflow-attributes.test.ts+++ b/packages/eve/src/execution/eve-workflow-attributes.test.ts@@ -15,7 +15,12 @@ import {readScheduleId,readSessionTraceId,} from "#execution/eve-workflow-attributes.js";-import { ChannelRequestIdKey, ScheduleIdKey } from "#context/keys.js";+import {+ ChannelInstrumentationKey,+ ChannelRequestIdKey,+ ScheduleIdKey,+ SessionTraceSeedKey,+} from "#context/keys.js";import { CHANNEL_CONTEXT_KEY_NAME } from "#context/key-names.js";const slackChannelCtx = {@@ -64,6 +69,82 @@ describe("isWorkflowTraceContentVisible", () => {}),).toBe(true);});++ it("uses the effective decision from a forwarded trace seed", () => {+ const serializedContext = {+ [CHANNEL_CONTEXT_KEY_NAME]: { audience: "unknown", kind: "http" },+ [SessionTraceSeedKey.name]: {+ decision: { action: "record", recordInputs: true, recordOutputs: true },+ forwardedTracePolicy: {+ ceiling: { recordInputs: true, recordOutputs: true },+ originAudience: "public",+ },+ spanId: "1".repeat(16),+ traceFlags: 1,+ traceId: "2".repeat(32),+ },+ [ChannelInstrumentationKey.name]: {+ kind: "eve",+ metadata: { audience: "public" },+ },+ };++ expect(isWorkflowTraceContentVisible(serializedContext)).toBe(true);+ expect(buildSessionAttributes({ inputMessage: "research", serializedContext })).toMatchObject({+ "$eve.is_trace_content_visible": true,+ });+ });++ 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" },+ },+ };++ expect(isWorkflowTraceContentVisible(serializedContext)).toBe(false);+ expect(buildSessionAttributes({ inputMessage: "research", serializedContext })).toMatchObject({+ "$eve.is_trace_content_visible": false,+ });+ });++ it("keeps workflow content hidden for a directional forwarded ceiling", () => {+ const serializedContext = {+ [CHANNEL_CONTEXT_KEY_NAME]: { audience: "private", kind: "eve" },+ [SessionTraceSeedKey.name]: {+ decision: { action: "record", recordInputs: false, recordOutputs: true },+ forwardedTracePolicy: {+ ceiling: { recordInputs: false, recordOutputs: true },+ originAudience: "private",+ },+ spanId: "1".repeat(16),+ traceFlags: 1,+ traceId: "2".repeat(32),+ },+ };++ expect(isWorkflowTraceContentVisible(serializedContext)).toBe(false);+ expect(buildSessionAttributes({ inputMessage: "research", serializedContext })).toMatchObject({+ "$eve.is_trace_content_visible": false,+ });+ });++ it("keeps workflow content hidden for malformed forwarded seed state", () => {+ expect(+ isWorkflowTraceContentVisible({+ [CHANNEL_CONTEXT_KEY_NAME]: { audience: "public", kind: "eve" },+ [SessionTraceSeedKey.name]: {+ decision: { action: "record", recordInputs: true, recordOutputs: true },+ forwardedTracePolicy: { originAudience: "public" },+ spanId: "1".repeat(16),+ traceFlags: 1,+ traceId: "2".repeat(32),+ },+ }),+ ).toBe(false);+ });});describe("readParentSessionId", () => {@@ -385,6 +466,19 @@ describe("readSessionTraceId", () => {).toBeUndefined();});+ it("returns undefined when a malformed durable decision resolves to drop", () => {+ expect(+ readSessionTraceId({+ "eve.sessionTraceSeed": {+ decision: { action: "record", recordInputs: "yes", recordOutputs: true },+ spanId: "a".repeat(16),+ traceFlags: 1,+ traceId: "b".repeat(32),+ },+ }),+ ).toBeUndefined();+ });+it("returns undefined when no seed is present", () => {expect(readSessionTraceId({})).toBeUndefined();});diff --git a/packages/eve/src/execution/eve-workflow-attributes.ts b/packages/eve/src/execution/eve-workflow-attributes.tsindex 6be72cec2..5c9d12ae7 100644--- a/packages/eve/src/execution/eve-workflow-attributes.ts+++ b/packages/eve/src/execution/eve-workflow-attributes.ts@@ -46,6 +46,7 @@ import { isNonEmptyString } from "#shared/guards.js";import { shouldCaptureInstrumentationContent } from "#shared/instrumentation-content.js";import { normalizeChannelAudience } from "#shared/channel-audience.js";import { isSampledTrace } from "#tracing/sampled-trace.js";+import { resolveForwardedTraceSeed } from "#shared/forwarded-trace-policy.js";/*** Active compiled graph node id for the session's agent. Returned by@@ -99,6 +100,14 @@ export function readChannelKind(serializedContext: Record<string, unknown>): str}export function isWorkflowTraceContentVisible(serializedContext: Record<string, unknown>): boolean {+ const seed = serializedContext[SessionTraceSeedKey.name] as SessionTraceSeed | undefined;+ if (seed !== undefined) {+ const traceState = resolveForwardedTraceSeed(seed)!;+ if (traceState.forwardedTracePolicy !== undefined) {+ const decision = traceState.decision;+ return decision?.action === "record" && decision.recordInputs && decision.recordOutputs;+ }+ }const channel = serializedContext[CHANNEL_CONTEXT_KEY_NAME] as| SerializedChannelAdapter| undefined;@@ -111,7 +120,9 @@ export function isWorkflowOtelTraceEnabled(serializedContext: Record<string, unkexport function readSessionTraceId(serializedContext: Record<string, unknown>): string | undefined {const seed = serializedContext[SessionTraceSeedKey.name] as SessionTraceSeed | undefined;- if (seed === undefined || !isSampledTrace(seed)) return undefined;+ if (seed === undefined) return undefined;+ const traceState = resolveForwardedTraceSeed(seed)!;+ if (!isSampledTrace(traceState)) return undefined;return isNonEmptyString(seed.traceId) ? seed.traceId : undefined;}diff --git a/packages/eve/src/execution/remote-agent-dispatch.test.ts b/packages/eve/src/execution/remote-agent-dispatch.test.tsindex b9f6ab926..8bcd1487b 100644--- a/packages/eve/src/execution/remote-agent-dispatch.test.ts+++ b/packages/eve/src/execution/remote-agent-dispatch.test.ts@@ -576,8 +576,19 @@ describe("startRemoteAgentSession — forwarded principal", () => {action: createAction(),auth: CURRENT_AUTH,callbackBaseUrl: "https://caller.example.com",+ originAudience: "private",initiatorAuth: INITIATOR_AUTH,- remote: { ...createRemoteAgent(), forwardPrincipal: true },+ parentTraceContext: {+ decision: { action: "record", recordInputs: true, recordOutputs: false },+ spanId: "2".repeat(16),+ traceFlags: 1,+ traceId: "1".repeat(32),+ },+ remote: {+ ...createRemoteAgent(),+ forwardPrincipal: true,+ headers: { baggage: "vendor=value,eve.audience=private" },+ },session: createSession(),}),).resolves.toEqual({ sessionId: "remote-session" });@@ -586,6 +597,68 @@ describe("startRemoteAgentSession — forwarded principal", () => {current: CURRENT_AUTH,initiator: INITIATOR_AUTH,});+ expect(JSON.parse(fetchMock.mock.calls[0]?.[1]?.body as string)).not.toHaveProperty(+ "forwardedTracePolicy",+ );+ expect(fetchMock.mock.calls[0]?.[1]?.headers).toMatchObject({+ baggage: "vendor=value,eve.audience=private;ceiling=i1o0",+ });+ });++ it("serializes the current delivery-effective decision as the next ceiling", async () => {+ const fetchMock = vi.fn().mockResolvedValue(createSessionResponse());+ vi.stubGlobal("fetch", fetchMock);++ await startRemoteAgentSession({+ action: createAction(),+ auth: CURRENT_AUTH,+ callbackBaseUrl: "https://caller.example.com",+ initiatorAuth: INITIATOR_AUTH,+ originAudience: "public",+ parentTraceContext: {+ decision: { action: "record", recordInputs: false, recordOutputs: false },+ spanId: "2".repeat(16),+ traceFlags: 1,+ traceId: "1".repeat(32),+ },+ remote: { ...createRemoteAgent(), forwardPrincipal: true },+ session: createSession(),+ });++ expect(fetchMock.mock.calls[0]?.[1]?.headers).toMatchObject({+ baggage: "eve.audience=public;ceiling=i0o0",+ });+ });++ it("uses unsampled trace flags as the only propagated drop signal", async () => {+ const fetchMock = vi.fn().mockResolvedValue(createSessionResponse());+ vi.stubGlobal("fetch", fetchMock);++ await startRemoteAgentSession({+ action: createAction(),+ auth: CURRENT_AUTH,+ callbackBaseUrl: "https://caller.example.com",+ initiatorAuth: INITIATOR_AUTH,+ originAudience: "private",+ parentTraceContext: {+ decision: { action: "drop" },+ spanId: "2".repeat(16),+ traceFlags: 0,+ traceId: "1".repeat(32),+ },+ remote: {+ ...createRemoteAgent(),+ forwardPrincipal: true,+ headers: { baggage: "vendor=value,eve.audience=public;ceiling=i1o1" },+ },+ session: createSession(),+ });++ expect(fetchMock.mock.calls[0]?.[1]?.headers).toMatchObject({ baggage: "vendor=value" });+ expect(fetchMock.mock.calls[0]?.[1]?.headers).not.toHaveProperty(+ "baggage",+ expect.stringContaining("drop"),+ );});it("omits the initiator when the dispatching turn has none", async () => {@@ -624,7 +697,13 @@ describe("startRemoteAgentSession — forwarded principal", () => {action: createAction(),auth: null,callbackBaseUrl: "https://caller.example.com",+ originAudience: "public",initiatorAuth: null,+ parentTraceContext: {+ spanId: "2".repeat(16),+ traceFlags: 1,+ traceId: "1".repeat(32),+ },remote: { ...createRemoteAgent(), forwardPrincipal: true },session: createSession(),}),@@ -633,6 +712,7 @@ describe("startRemoteAgentSession — forwarded principal", () => {expect(JSON.parse(fetchMock.mock.calls[0]?.[1]?.body as string)).not.toHaveProperty("forwardedPrincipal",);+ expect(fetchMock.mock.calls[0]?.[1]?.headers).not.toHaveProperty("baggage");});it("does not forward when forwardPrincipal is unset even with auth in scope", async () => {@@ -653,8 +733,17 @@ describe("startRemoteAgentSession — forwarded principal", () => {action: createAction(),auth: CURRENT_AUTH,callbackBaseUrl: "https://caller.example.com",+ originAudience: "public",initiatorAuth: INITIATOR_AUTH,- remote: createRemoteAgent(),+ parentTraceContext: {+ spanId: "2".repeat(16),+ traceFlags: 1,+ traceId: "1".repeat(32),+ },+ remote: {+ ...createRemoteAgent(),+ headers: { baggage: "vendor=value,eve.audience=public" },+ },session: createSession(),}),).resolves.toEqual({ sessionId: "remote-session" });@@ -662,6 +751,7 @@ describe("startRemoteAgentSession — forwarded principal", () => {expect(JSON.parse(fetchMock.mock.calls[0]?.[1]?.body as string)).not.toHaveProperty("forwardedPrincipal",);+ expect(fetchMock.mock.calls[0]?.[1]?.headers).toMatchObject({ baggage: "vendor=value" });});});diff --git a/packages/eve/src/execution/remote-agent-dispatch.ts b/packages/eve/src/execution/remote-agent-dispatch.tsindex 4c97e77af..cf78fe461 100644--- a/packages/eve/src/execution/remote-agent-dispatch.ts+++ b/packages/eve/src/execution/remote-agent-dispatch.ts@@ -14,6 +14,7 @@ import type {SessionAuthContext,SessionTraceContext,} from "#channel/types.js";+import type { ChannelAudience } from "#shared/channel-audience.js";import type { ForwardedPrincipal } from "#channel/forwarded-principal.js";import type { HeadersValue } from "#client/types.js";import { createWorkflowCallbackUrl } from "#execution/workflow-callback-url.js";@@ -32,6 +33,8 @@ import type { ResolvedRuntimeRemoteAgentNode } from "#runtime/types.js";import { expectFunction, expectObjectRecord } from "#internal/authored-module.js";import type { JsonObject } from "#shared/json.js";import { readTaskIdFromInboxToken } from "#tasks/task-inbox-token.js";+import { writeForwardedAudienceBaggage } from "#protocol/baggage.js";+import { decisionToTraceContentCeiling } from "#shared/forwarded-trace-policy.js";const CreateSessionResponseSchema = z.object({ok: z.literal(true),@@ -59,6 +62,7 @@ export async function startRemoteAgentSession(input: {readonly auth?: SessionAuthContext | null;readonly callbackBaseUrl: string | undefined;readonly callbackToken?: string;+ readonly originAudience?: ChannelAudience;readonly activityObserver?: ActivityObserverConfig;/** The root initiator's principal, forwarded alongside {@link auth}. */readonly initiatorAuth?: SessionAuthContext | null;@@ -127,11 +131,18 @@ export async function startRemoteAgentSession(input: {const headers = await resolveRemoteAgentRequestHeaders(input.remote);const traceparent = formatTraceparent(input.parentTraceContext);if (traceparent !== undefined) {- for (const key of Object.keys(headers)) {- if (key.toLowerCase() === "traceparent") delete headers[key];- }- headers["traceparent"] = traceparent;- }+ setHeader(headers, "traceparent", traceparent);+ }+ const baggage = writeForwardedAudienceBaggage(+ readHeader(headers, "baggage"),+ buildForwardedTraceAssertion({+ forwardedPrincipal,+ originAudience: input.originAudience,+ parentTraceContext: input.parentTraceContext,+ traceparent,+ }),+ );+ setHeader(headers, "baggage", baggage);const response = await fetch(createRemoteAgentSessionUrl(input.remote), {body: JSON.stringify(requestBody),headers: {@@ -166,6 +177,28 @@ export async function startRemoteAgentSession(input: {return { sessionId: parsed.data.sessionId };}+function buildForwardedTraceAssertion(input: {+ readonly forwardedPrincipal: ForwardedPrincipal | undefined;+ readonly originAudience: ChannelAudience | undefined;+ readonly parentTraceContext: SessionTraceContext | undefined;+ readonly traceparent: string | undefined;+}) {+ const ceiling = decisionToTraceContentCeiling(input.parentTraceContext?.decision);+ if (+ input.forwardedPrincipal === undefined ||+ input.parentTraceContext === undefined ||+ (input.parentTraceContext.traceFlags & 1) !== 1 ||+ input.traceparent === undefined ||+ ceiling === undefined+ ) {+ return undefined;+ }+ return {+ ceiling,+ originAudience: input.originAudience ?? "unknown",+ };+}+/** Continues one remote-agent session by its immutable session ID. */export async function continueRemoteAgentSession(input: {readonly activityObserver?: ActivityObserverConfig;@@ -357,6 +390,18 @@ export async function cancelRemoteAgentTurn(input: {: { status: "no_active_turn" };}+function readHeader(headers: Record<string, string>, name: string): string | undefined {+ const key = Object.keys(headers).find((candidate) => candidate.toLowerCase() === name);+ return key === undefined ? undefined : headers[key];+}++function setHeader(headers: Record<string, string>, name: string, value: string | undefined): void {+ for (const key of Object.keys(headers)) {+ if (key.toLowerCase() === name) delete headers[key];+ }+ if (value !== undefined) headers[name] = value;+}+/** Retires one exact remote child session through eve's authenticated reset route. */export async function resetRemoteAgentSession(input: {readonly headers?: Record<string, string>;diff --git a/packages/eve/src/execution/runtime-context.test.ts b/packages/eve/src/execution/runtime-context.test.tsindex 65bc93254..1c0ad0125 100644--- a/packages/eve/src/execution/runtime-context.test.ts+++ b/packages/eve/src/execution/runtime-context.test.ts@@ -4,6 +4,7 @@ import {AuthKey,ChannelInstrumentationKey,ContinuationTokenKey,+ ParentTraceContextKey,type Session,type SessionAuthContext,ActivityObserverKey,@@ -309,4 +310,30 @@ describe("buildRunContext", () => {expect(projection!.kind).toBe("http");expect(projection!.metadata).toEqual({ audience: "unknown" });});++ it("keeps forwarded origin policy separate from inherited channel metadata", () => {+ const forwardedTracePolicy = {+ ceiling: { recordInputs: false, recordOutputs: true },+ originAudience: "private",+ } as const;+ const ctx = buildRunContext({+ bundle: createMinimalBundle(),+ run: {+ auth: null,+ adapter: { kind: "eve" },+ channelMetadata: { kind: "eve", metadata: { audience: "unknown" } },+ input: { message: "hi" },+ mode: "task",+ parentTraceContext: {+ forwardedTracePolicy,+ spanId: "1".repeat(16),+ traceFlags: 1,+ traceId: "2".repeat(32),+ },+ },+ });++ expect(ctx.get(ParentTraceContextKey)?.forwardedTracePolicy).toEqual(forwardedTracePolicy);+ expect(ctx.get(ChannelInstrumentationKey)?.metadata.audience).toBe("unknown");+ });});diff --git a/packages/eve/src/execution/subagent-start-remote.ts b/packages/eve/src/execution/subagent-start-remote.tsindex 00411b8be..4c001ed1c 100644--- a/packages/eve/src/execution/subagent-start-remote.ts+++ b/packages/eve/src/execution/subagent-start-remote.ts@@ -15,6 +15,7 @@ import {import { createLogger, logError } from "#internal/logging.js";import type { RuntimeRemoteAgentCallActionRequest } from "#shared/action-types.js";import type { CompiledBundle } from "#runtime/sessions/runtime-context-keys.js";+import type { ChannelAudience } from "#shared/channel-audience.js";const log = createLogger("execution.subagent-start-remote");@@ -25,6 +26,7 @@ export async function startRemoteSubagent(input: {readonly batchEvent: { readonly sequence: number; readonly turnId: string };readonly bundle: CompiledBundle;readonly callbackBaseUrl: string | undefined;+ readonly originAudience: ChannelAudience;readonly currentSession: RuntimeSession;readonly dynamicRemoteAgent?: NonNullable<Parameters<typeof resolveRemoteAgentForAction>[0]["dynamicRemoteAgent"]@@ -99,6 +101,7 @@ export async function startRemoteSubagent(input: {auth: input.auth,callbackBaseUrl,callbackToken: input.parentContinuationToken,+ originAudience: input.originAudience,initiatorAuth: input.initiatorAuth,operationId: operation.id,parentTraceContext: input.parentTraceContext,diff --git a/packages/eve/src/execution/subagent-tool.test.ts b/packages/eve/src/execution/subagent-tool.test.tsindex 98e63814b..9f14db9d1 100644--- a/packages/eve/src/execution/subagent-tool.test.ts+++ b/packages/eve/src/execution/subagent-tool.test.ts@@ -148,6 +148,29 @@ describe("buildSubagentRunInput", () => {expect(runInput.channelMetadata).toBeUndefined();});+ it("preserves accepted forwarded trace policy through local subagents", () => {+ const parentTraceContext = {+ decision: { action: "record", recordInputs: false, recordOutputs: true },+ forwardedTracePolicy: {+ ceiling: { recordInputs: false, recordOutputs: true },+ originAudience: "private",+ },+ spanId: "1".repeat(16),+ traceFlags: 1,+ traceId: "2".repeat(32),+ } as const;+ const { runInput } = buildRuntimeSubagentRunInput({+ action: makeAction(),+ auth: null,+ batchEvent: { sequence: 0, turnId: "turn-0" },+ initiatorAuth: null,+ parentTraceContext,+ session: makeSession(),+ });++ expect(runInput.parentTraceContext).toEqual(parentTraceContext);+ });+it("propagates an existing rootSessionId through a nested subagent chain", () => {const nestedSession: HarnessSession = {...makeSession(),diff --git a/packages/eve/src/execution/workflow-steps.test.ts b/packages/eve/src/execution/workflow-steps.test.tsindex bb6119e0a..75b7cfe43 100644--- a/packages/eve/src/execution/workflow-steps.test.ts+++ b/packages/eve/src/execution/workflow-steps.test.ts@@ -12,6 +12,7 @@ import { ContextKey } from "#context/key.js";import {ActivityObserverKey,AuthKey,+ ChannelInstrumentationKey,ContinuationTokenKey,DynamicSubagentAgentConfigKey,ModeKey,@@ -22,6 +23,7 @@ import {SessionDynamicToolMetadataKey,SessionDynamicToolRuntimeRevisionKey,SessionIdKey,+ SessionTraceSeedKey,TurnTaskDeliveryKey,TurnTaskStateKey,} from "#context/keys.js";@@ -3311,7 +3313,10 @@ describe("runProxySubagentEventStep", () => {* `deserializeContext` round-trip resolves the adapter by kind* against the bundle's adapter registry.*/- function buildSerializedContextForAdapter(adapter: ChannelAdapter): Record<string, unknown> {+ function buildSerializedContextForAdapter(+ adapter: ChannelAdapter,+ options: { readonly acceptedForwardedTracePolicy?: boolean } = {},+ ): Record<string, unknown> {const bundle = {adapterRegistry: {adaptersByKind: new Map([[adapter.kind, adapter]]),@@ -3341,6 +3346,18 @@ describe("runProxySubagentEventStep", () => {ctx.set(AuthKey, null);ctx.set(BundleKey, bundle);ctx.set(ChannelKey, adapter);+ if (options.acceptedForwardedTracePolicy) {+ ctx.set(SessionTraceSeedKey, {+ decision: { action: "record", recordInputs: false, recordOutputs: true },+ forwardedTracePolicy: {+ ceiling: { recordInputs: false, recordOutputs: true },+ originAudience: "private",+ },+ spanId: "1".repeat(16),+ traceFlags: 1,+ traceId: "2".repeat(32),+ });+ }ctx.set(ContinuationTokenKey, "http:proxy-test");ctx.set(ModeKey, "conversation");ctx.set(SessionIdKey, "parent-session");@@ -3413,7 +3430,9 @@ describe("runProxySubagentEventStep", () => {const result = await runProxySubagentEventStep({hookPayload: buildHookPayload(),parentWritable: createTestWritable(),- serializedContext: buildSerializedContextForAdapter(cachingAdapter),+ serializedContext: buildSerializedContextForAdapter(cachingAdapter, {+ acceptedForwardedTracePolicy: true,+ }),sessionState,});@@ -3432,6 +3451,18 @@ describe("runProxySubagentEventStep", () => {turnId: "child-turn",requests: [expect.objectContaining({ requestId: "req-1" })],});+ expect(result.serializedContext[SessionTraceSeedKey.name]).toMatchObject({+ decision: { action: "record", recordInputs: false, recordOutputs: true },+ forwardedTracePolicy: {+ ceiling: { recordInputs: false, recordOutputs: true },+ originAudience: "private",+ },+ });+ expect(result.serializedContext[ChannelInstrumentationKey.name]).toMatchObject({+ metadata: {+ audience: "unknown",+ },+ });// And the parent session's proxy-entry map is reflected on the// returned durable session state. The flatdiff --git a/packages/eve/src/instrumentation/content-policy.test.ts b/packages/eve/src/instrumentation/content-policy.test.tsindex 5fefbfd24..b9322f7b5 100644--- a/packages/eve/src/instrumentation/content-policy.test.ts+++ b/packages/eve/src/instrumentation/content-policy.test.ts@@ -72,6 +72,17 @@ describe("instrumentationEventForTraceDecision", () => {).toMatchObject({ input: undefined });});+ it("uses an already-intersected forwarded decision without reapplying origin audience", () => {+ expect(+ instrumentationEventForTraceDecision(+ event,+ { action: "record", recordInputs: true, recordOutputs: false },+ "private",+ { applyAudienceCeiling: false },+ ),+ ).toMatchObject({ input: { instructions: "private prompt" } });+ });+it("removes content from dropped OTel traces", () => {expect(instrumentationEventForTraceDecision(event, { action: "drop" }, "public")).toMatchObject({ input: undefined },diff --git a/packages/eve/src/instrumentation/content-policy.ts b/packages/eve/src/instrumentation/content-policy.tsindex 33d19eba7..80695d849 100644--- a/packages/eve/src/instrumentation/content-policy.ts+++ b/packages/eve/src/instrumentation/content-policy.ts@@ -12,8 +12,10 @@ export function instrumentationEventForTraceDecision(event: InstrumentationEvent,decision: InstrumentationDecision,audience: ChannelAudience,+ options: { readonly applyAudienceCeiling?: boolean } = {},): InstrumentationEvent {- const effective = applyAudienceCeiling(decision, audience);+ const effective =+ options.applyAudienceCeiling === false ? decision : applyAudienceCeiling(decision, audience);return effective.action === "drop"? withoutInstrumentationContent(event): withInstrumentationDecision(event, effective);diff --git a/packages/eve/src/instrumentation/runtime.test.ts b/packages/eve/src/instrumentation/runtime.test.tsindex c6f9fcb48..0242e7b0a 100644--- a/packages/eve/src/instrumentation/runtime.test.ts+++ b/packages/eve/src/instrumentation/runtime.test.ts@@ -4,6 +4,7 @@ import { ContextContainer, contextStorage } from "#context/container.js";import {ChannelInstrumentationKey,OtelTraceEnabledKey,+ ParentTraceContextKey,SessionTraceSeedKey,} from "#context/keys.js";import type { InstrumentationHooks } from "#instrumentation/lifecycle.js";@@ -19,6 +20,7 @@ import {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";const boundSession = {agentName: "test-agent",@@ -44,7 +46,7 @@ function createRuntime(};}-function createContext(audience: "private" | "public" = "public"): ContextContainer {+function createContext(audience: "private" | "public" | "unknown" = "public"): ContextContainer {const ctx = new ContextContainer();ctx.set(ChannelInstrumentationKey, {kind: "channel:test",@@ -69,6 +71,267 @@ beforeEach(() => {delete (globalThis as Record<symbol, unknown>)[Symbol.for("eve.instrumentation-runtime")];});+function initializeRemoteSession(+ tracePolicy: TraceCapturePolicy,+ input: {+ readonly ceiling?: { readonly recordInputs: boolean; readonly recordOutputs: boolean };+ readonly liveAudience?: "private" | "public" | "unknown";+ readonly originAudience?: "private" | "public" | "unknown";+ } = {},+): ContextContainer {+ const originAudience = input.originAudience ?? "public";+ const ctx = createContext(input.liveAudience ?? originAudience);+ registerInstrumentationRuntime({+ ...createRuntime({ capturesContent: true, publish: vi.fn() }, tracePolicy),+ idGenerator: new AgentSpanIdGenerator(),+ prepareSessionTrace: vi.fn().mockResolvedValue(undefined),+ });+ initializeSessionInstrumentation({+ agentName: "remote-agent",+ ctx,+ parentTraceContext: {+ forwardedTracePolicy: {+ ceiling: input.ceiling ?? { recordInputs: true, recordOutputs: true },+ originAudience,+ },+ spanId: "c".repeat(16),+ traceFlags: 1,+ traceId: "d".repeat(32),+ },+ });+ return ctx;+}++describe("initializeSessionInstrumentation", () => {+ it("applies the receiver trace policy to a forwarded public audience", () => {+ const ctx = initializeRemoteSession(() => ({+ emit: true,+ recordInputs: false,+ recordOutputs: true,+ }));++ expect(ctx.get(SessionTraceSeedKey)).toMatchObject({+ decision: { action: "record", recordInputs: false, recordOutputs: true },+ traceFlags: 1,+ });+ });++ it("retains full capture for a sampled public remote trace", async () => {+ const ctx = initializeRemoteSession(() => true);++ expect(ctx.get(SessionTraceSeedKey)).toMatchObject({+ decision: { action: "record", recordInputs: true, recordOutputs: true },+ traceFlags: 1,+ });+ expect(ctx.get(ParentTraceContextKey)).toMatchObject({ traceFlags: 1 });+ expect(ctx.get(ParentTraceContextKey)).not.toHaveProperty("forwardedTracePolicy");+ expect(ctx.get(SessionTraceSeedKey)?.forwardedTracePolicy).toEqual({+ ceiling: { recordInputs: true, recordOutputs: true },+ originAudience: "public",+ });+ expect(+ await readTelemetry(+ bindSessionInstrumentation({+ agentName: "remote-agent",+ ctx,+ rootSessionId: "session-1",+ sessionId: "session-1",+ }),+ ),+ ).toMatchObject({ recordInputs: true, recordOutputs: true });+ });++ it.each([+ ["unknown", true],+ ["private", false],+ ] 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 },+ });++ expect(+ await readTelemetry(+ bindSessionInstrumentation({+ agentName: "remote-agent",+ ctx,+ rootSessionId: "session-1",+ sessionId: "session-1",+ }),+ ),+ ).toMatchObject({+ recordInputs: recordsContent,+ recordOutputs: recordsContent,+ });+ },+ );++ it("does not let a forwarded policy override a receiver drop decision", () => {+ const ctx = initializeRemoteSession(() => false);++ expect(ctx.get(SessionTraceSeedKey)).toMatchObject({+ decision: { action: "drop" },+ traceFlags: 0,+ });+ expect(ctx.get(ParentTraceContextKey)).toMatchObject({+ decision: { action: "drop" },+ traceFlags: 0,+ });+ });++ it("allows private content only within both hop ceilings", async () => {+ const ctx = initializeRemoteSession(+ () => ({ emit: true, recordInputs: true, recordOutputs: true }),+ {+ ceiling: { recordInputs: true, recordOutputs: false },+ liveAudience: "unknown",+ originAudience: "private",+ },+ );++ expect(ctx.get(SessionTraceSeedKey)?.decision).toEqual({+ action: "record",+ recordInputs: true,+ recordOutputs: false,+ });+ await expect(+ readTelemetry(+ bindSessionInstrumentation({+ agentName: "remote-agent",+ ctx,+ rootSessionId: "session-1",+ sessionId: "session-1",+ }),+ ),+ ).resolves.toMatchObject({ recordInputs: true, recordOutputs: false });+ });++ it("redacts runtime-context model input when the forwarded ceiling denies inputs", async () => {+ const ctx = createContext("public");+ const runtime = createRuntime({ capturesContent: true, publish: vi.fn() }, () => ({+ emit: true,+ recordInputs: true,+ recordOutputs: true,+ }));+ runtime.stepStartedRuntimeContextResolver = (event) => ({+ runtimeContext: { messageCount: event.modelInput.messages.length },+ });+ registerInstrumentationRuntime({+ ...runtime,+ idGenerator: new AgentSpanIdGenerator(),+ prepareSessionTrace: vi.fn().mockResolvedValue(undefined),+ });+ initializeSessionInstrumentation({+ agentName: "remote-agent",+ ctx,+ parentTraceContext: {+ forwardedTracePolicy: {+ ceiling: { recordInputs: false, recordOutputs: true },+ originAudience: "public",+ },+ spanId: "c".repeat(16),+ traceFlags: 1,+ traceId: "d".repeat(32),+ },+ });++ const messageCount = await bindSessionInstrumentation({+ agentName: "remote-agent",+ ctx,+ rootSessionId: "session-1",+ sessionId: "session-1",+ })+ ?.prepareExecution()+ .runStep(+ {+ environment: "test",+ eveVersion: "0.0.0",+ hasInput: true,+ session: { sessionId: "session-1" },+ },+ async (scope) =>+ scope.resolveRuntimeContext({+ eveVersion: "0.0.0",+ emissionState: { sessionStarted: true, sequence: 0, stepIndex: 0, turnId: "turn-1" },+ environment: "test",+ modelInput: {+ instructions: "private",+ messages: [{ content: "secret", role: "user" }],+ },+ session: { sessionId: "session-1" } as never,+ })?.["messageCount"],+ );++ expect(messageCount).toBe(0);+ });++ it("narrows monotonically across a three-hop chain", () => {+ const receiverPolicies = [+ { emit: true, recordInputs: true, recordOutputs: true },+ { emit: true, recordInputs: false, recordOutputs: true },+ { emit: true, recordInputs: true, recordOutputs: false },+ ] as const;+ let ceiling = { recordInputs: true, recordOutputs: true };++ for (const receiverPolicy of receiverPolicies) {+ const previous = ceiling;+ const ctx = initializeRemoteSession(() => receiverPolicy, {+ ceiling: previous,+ originAudience: "private",+ });+ const decision = ctx.get(SessionTraceSeedKey)?.decision;+ expect(decision?.action).toBe("record");+ if (decision?.action !== "record") throw new Error("Expected a record decision");+ ceiling = {+ recordInputs: decision.recordInputs,+ recordOutputs: decision.recordOutputs,+ };+ expect(Number(ceiling.recordInputs)).toBeLessThanOrEqual(Number(previous.recordInputs));+ expect(Number(ceiling.recordOutputs)).toBeLessThanOrEqual(Number(previous.recordOutputs));+ const relayed = readForwardedAudienceBaggage(+ writeForwardedAudienceBaggage(undefined, {+ ceiling,+ originAudience: "private",+ }) ?? null,+ );+ expect(relayed).toEqual({ ceiling, originAudience: "private" });+ if (typeof relayed !== "object") throw new Error("Expected a relayed trace assertion");+ ceiling = relayed.ceiling;+ }++ expect(ceiling).toEqual({ recordInputs: false, recordOutputs: false });+ });++ it("preserves sampled flags for a non-forwarded parent decision", () => {+ const ctx = createContext("public");+ ctx.set(ParentTraceContextKey, {+ decision: { action: "drop" },+ spanId: "c".repeat(16),+ traceFlags: 1,+ traceId: "d".repeat(32),+ });+ registerInstrumentationRuntime({+ ...createRuntime({ capturesContent: true, publish: vi.fn() }, () => false),+ idGenerator: new AgentSpanIdGenerator(),+ prepareSessionTrace: vi.fn().mockResolvedValue(undefined),+ });+ initializeSessionInstrumentation({+ agentName: "local-subagent",+ ctx,+ parentTraceContext: ctx.get(ParentTraceContextKey),+ });++ expect(ctx.get(SessionTraceSeedKey)).toMatchObject({+ decision: { action: "drop" },+ traceFlags: 1,+ });+ expect(ctx.get(ParentTraceContextKey)).toMatchObject({ traceFlags: 1 });+ });+});+describe("bindInstrumentationRuntime", () => {it("returns no worker controls when no runtime is loaded", () => {expect(@@ -265,6 +528,51 @@ describe("bindInstrumentationRuntime", () => {});});+ it("fails a malformed durable trace decision closed", async () => {+ const ctx = createContext();+ ctx.set(SessionTraceSeedKey, {+ decision: {+ action: "record",+ recordInputs: "yes",+ recordOutputs: true,+ } as never,+ spanId: "1".repeat(16),+ traceFlags: 1,+ traceId: "2".repeat(32),+ });++ expect(+ await readTelemetry(+ bindInstrumentationRuntime(+ createRuntime({ capturesContent: true, publish: vi.fn() }),+ ctx,+ boundSession,+ ),+ ),+ ).toMatchObject({ recordInputs: false, recordOutputs: false });+ });++ it("fails a malformed durable forwarded assertion closed", async () => {+ const ctx = createContext();+ ctx.set(SessionTraceSeedKey, {+ decision: { action: "record", recordInputs: true, recordOutputs: true },+ forwardedTracePolicy: { originAudience: "public" } as never,+ spanId: "1".repeat(16),+ traceFlags: 1,+ traceId: "2".repeat(32),+ });++ expect(+ await readTelemetry(+ bindInstrumentationRuntime(+ createRuntime({ capturesContent: true, publish: vi.fn() }),+ ctx,+ boundSession,+ ),+ ),+ ).toMatchObject({ recordInputs: false, recordOutputs: false });+ });+it("applies the live audience ceiling to a seeded decision", async () => {const ctx = createContext("private");ctx.set(SessionTraceSeedKey, {diff --git a/packages/eve/src/instrumentation/runtime.ts b/packages/eve/src/instrumentation/runtime.tsindex 3d8c50962..24c753e8c 100644--- a/packages/eve/src/instrumentation/runtime.ts+++ b/packages/eve/src/instrumentation/runtime.ts@@ -3,10 +3,7 @@ import { context as otelContext, trace } from "#compiled/@opentelemetry/api/indeimport type { InstrumentationEvents } from "#public/instrumentation/index.js";import type { InstrumentationDecision } from "#shared/instrumentation-decision.js";-import {- applyAudienceCeiling,- shouldCaptureInstrumentationContent,-} from "#shared/instrumentation-content.js";+import { shouldCaptureInstrumentationContent } from "#shared/instrumentation-content.js";import type {InstrumentationAttemptScope,InstrumentationContextRunner,@@ -39,7 +36,7 @@ import {type ChannelDeliveryStartInstrumentation,type ChannelDeliveryTerminalInstrumentation,} from "#instrumentation/channel-delivery.js";-import { recordErrorOnSpan } from "#internal/logging.js";+import { createLogger, recordErrorOnSpan } from "#internal/logging.js";import {prepareTurnTraceContext,type PrepareTurnTraceContextInput,@@ -66,9 +63,22 @@ import {import { resolveParentLineage } from "#instrumentation/parent-lineage.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,+ type ForwardedTraceAssertion,+ formatTraceContentCeiling,+ readForwardedTraceAssertion,+ resolveForwardedTraceSeed,+ traceContentCeilingToDecision,+} from "#shared/forwarded-trace-policy.js";const INSTRUMENTATION_RUNTIME_KEY = Symbol.for("eve.instrumentation-runtime");const TURN_TRACE_STATE_KEY = "eve.harness.turnTrace";+const log = createLogger("instrumentation.runtime");interface InstrumentedStepSession {readonly sessionId: string;@@ -200,13 +210,21 @@ export function bindInstrumentationRuntime(const baseHooks = runtime.hooks;const readSessionContext = () => {const context = contextStorage.getStore() ?? ctx;+ const storedTraceSeed = context.get(SessionTraceSeedKey);+ const resolvedTraceState = resolveForwardedTraceSeed(storedTraceSeed);+ const traceSeed =+ storedTraceSeed === undefined || resolvedTraceState === undefined+ ? undefined+ : { ...storedTraceSeed, ...resolvedTraceState };+ const parentTraceContext = context.get(ParentTraceContextKey);return {channel: context.get(ChannelKey),context,instrumentation: context.get(ChannelInstrumentationKey),+ forwardedTracePolicy: readForwardedTraceAssertion(traceSeed?.forwardedTracePolicy),parent: context.get(ParentSessionKey),- parentTraceContext: context.get(ParentTraceContextKey),- traceSeed: context.get(SessionTraceSeedKey),+ parentTraceContext,+ traceSeed,};};const bindHooks = (sessionContext: ReturnType<typeof readSessionContext>) => {@@ -316,7 +334,17 @@ export function bindInstrumentationRuntime(const audience = normalizeChannelAudience(channel?.metadata.audience);const capturesContent = shouldCaptureInstrumentationContent(audience);const effectiveDecision =- decision === undefined ? undefined : applyAudienceCeiling(decision, audience);+ decision === undefined+ ? decision+ : applyLiveDeliveryAudienceCeiling(+ decision,+ audience,+ sessionContext.forwardedTracePolicy,+ );+ const capturesRuntimeContextInput =+ effectiveDecision === undefined+ ? capturesContent+ : effectiveDecision.action === "record" && effectiveDecision.recordInputs;const dropsTrace = decision?.action === "drop";const content = {recordInputs:@@ -425,12 +453,9 @@ export function bindInstrumentationRuntime(if (turnSpan !== undefined) recordErrorOnSpan(turnSpan, error);},resolveRuntimeContext: (runtimeContextInput) => {- const runtimeContextAudience = normalizeChannelAudience(- runtimeContextSnapshot.channel?.metadata.audience,- );return buildTelemetryRuntimeContext({...runtimeContextInput,- capturesContent: shouldCaptureInstrumentationContent(runtimeContextAudience),+ capturesContent: capturesRuntimeContextInput,context: runtimeContextSnapshot,providerResolvers: executionRuntime.runtimeContextResolvers,stepStartedResolver: executionRuntime.stepStartedRuntimeContextResolver,@@ -503,15 +528,37 @@ export function initializeSessionInstrumentation(input: {}): void {const runtime = getInstrumentationRuntime();const channel = input.ctx.get(ChannelInstrumentationKey);- const audience = normalizeChannelAudience(channel?.metadata.audience);+ const forwardedTracePolicy = readForwardedTraceAssertion(+ input.parentTraceContext?.forwardedTracePolicy,+ );+ const audience =+ forwardedTracePolicy?.originAudience ?? normalizeChannelAudience(channel?.metadata.audience);const traceSeed = allocateSessionTraceSeed({agentName: input.agentName,audience,channelType: channel?.channelType,+ forwardedTracePolicy,parentTraceContext: input.parentTraceContext,runtime,});- if (traceSeed !== undefined) input.ctx.set(SessionTraceSeedKey, traceSeed);+ 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 && input.parentTraceContext !== undefined) {+ const parentTraceContext = { ...input.parentTraceContext, ...traceSeed };+ delete parentTraceContext.forwardedTracePolicy;+ input.ctx.set(ParentTraceContextKey, parentTraceContext);+ }+ }input.ctx.set(OtelTraceEnabledKey, runtime?.prepareSessionTrace !== undefined);}@@ -519,17 +566,39 @@ 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 {if (input.parentTraceContext !== undefined) {- const decision =- input.parentTraceContext.decision ??- resolveTracePolicyDecision(isSampledTrace(input.parentTraceContext), input.audience);+ const forwardedCeiling = input.forwardedTracePolicy+ ? traceContentCeilingToDecision(input.forwardedTracePolicy.ceiling)+ : undefined;+ const inheritedDecision = readInstrumentationDecision(input.parentTraceContext.decision);+ const parentDecision = forwardedCeiling+ ? inheritedDecision === undefined+ ? forwardedCeiling+ : intersectInstrumentationDecisions(forwardedCeiling, inheritedDecision)+ : (inheritedDecision ??+ resolveTracePolicyDecision(isSampledTrace(input.parentTraceContext), input.audience));+ const decision = input.forwardedTracePolicy+ ? intersectInstrumentationDecisions(+ parentDecision,+ resolveTracePolicy(input.runtime?.otelSettings?.tracePolicy, {+ agentName: input.agentName,+ audience: input.audience,+ channelType: input.channelType,+ }),+ )+ : parentDecision;return {decision,+ forwardedTracePolicy: input.forwardedTracePolicy,spanId: input.parentTraceContext.spanId,- traceFlags: input.parentTraceContext.traceFlags,+ traceFlags:+ input.forwardedTracePolicy !== undefined && decision.action === "drop"+ ? input.parentTraceContext.traceFlags & ~1+ : input.parentTraceContext.traceFlags,traceId: input.parentTraceContext.traceId,};}@@ -558,7 +627,7 @@ function resolveStepInstrumentationDecision(persisted: InstrumentationDecision | undefined,): InstrumentationDecision | undefined {if (settings === undefined) return undefined;- if (traceSeed?.decision !== undefined) return traceSeed.decision;+ if (traceSeed?.decision !== undefined) return readInstrumentationDecision(traceSeed.decision);if (persisted !== undefined) return persisted;const audience = normalizeChannelAudience(channel?.metadata.audience);if (traceSeed !== undefined) {diff --git a/packages/eve/src/protocol/baggage.test.ts b/packages/eve/src/protocol/baggage.test.tsnew file mode 100644index 000000000..9e70bbe21--- /dev/null+++ b/packages/eve/src/protocol/baggage.test.ts@@ -0,0 +1,95 @@+import { describe, expect, it } from "vitest";++import { readForwardedAudienceBaggage, writeForwardedAudienceBaggage } from "#protocol/baggage.js";++const PUBLIC_OUTPUTS = {+ ceiling: { recordInputs: false, recordOutputs: true },+ originAudience: "public",+} as const;++describe("readForwardedAudienceBaggage", () => {+ it.each([+ ["public", true, true],+ ["private", true, false],+ ["unknown", false, false],+ ] as const)("reads a %s origin audience with its ceiling", (originAudience, inputs, outputs) => {+ expect(+ readForwardedAudienceBaggage(+ `vendor=value,eve.audience=${originAudience};ceiling=i${inputs ? "1" : "0"}o${outputs ? "1" : "0"}`,+ ),+ ).toEqual({+ ceiling: { recordInputs: inputs, recordOutputs: outputs },+ originAudience,+ });+ });++ it("accepts W3C optional whitespace around separators", () => {+ expect(+ readForwardedAudienceBaggage(+ "vendor=value\t,\t eve.audience \t=\t private \t;\t ceiling \t=\t i1o0 \t",+ ),+ ).toEqual({+ ceiling: { recordInputs: true, recordOutputs: false },+ originAudience: "private",+ });+ });++ it.each([null, "vendor=value", "eve.capture=i1o1"])('returns absent for "%s"', (value) => {+ expect(readForwardedAudienceBaggage(value)).toBe("absent");+ });++ it.each([+ "eve.audience=public",+ "eve.audience=private",+ "eve.audience=public,eve.audience=public;ceiling=i1o1",+ "eve.audience=public;ceiling=i1o1,eve.audience=private;ceiling=i0o0",+ "eve.audience=public;ceiling=i1o1;vendor=yes",+ "eve.audience=public;vendor=yes",+ "eve.audience=public;ceiling=i1o1;ceiling=i0o0",+ "eve.audience=public;ceiling=i2o1",+ "eve.audience=public;ceiling=o1i1",+ "eve.audience=public;ceiling=drop",+ "eve.audience=everyone;ceiling=i1o1",+ "eve.audience=public;ceiling",+ "eve.audience=public;bad property=i1o1",+ "eve.audience",+ "eve.audience=public;ceiling=i1o1\n",+ "eve.audience=public;\vceiling=i1o1",+ "eve.audience=public;\fceiling=i1o1",+ "eve.audience=public;\u00a0ceiling=i1o1",+ ])("fails closed for malformed Eve baggage %s", (value) => {+ expect(readForwardedAudienceBaggage(value)).toBe("malformed");+ });+});++describe("writeForwardedAudienceBaggage", () => {+ it("preserves unrelated entries and replaces authored Eve assertions", () => {+ expect(+ writeForwardedAudienceBaggage(+ "first=1,eve.audience=private;ceiling=i1o1,second=2",+ PUBLIC_OUTPUTS,+ ),+ ).toBe("first=1,second=2,eve.audience=public;ceiling=i0o1");+ expect(+ writeForwardedAudienceBaggage("eve.audience=public,eve.capture=i1o1", PUBLIC_OUTPUTS),+ ).toBe("eve.capture=i1o1,eve.audience=public;ceiling=i0o1");+ });++ it("removes malformed authored Eve audience members", () => {+ expect(writeForwardedAudienceBaggage("eve.audience,vendor=value", PUBLIC_OUTPUTS)).toBe(+ "vendor=value,eve.audience=public;ceiling=i0o1",+ );+ expect(+ writeForwardedAudienceBaggage("eve.audience;property=x,vendor=value", PUBLIC_OUTPUTS),+ ).toBe("vendor=value,eve.audience=public;ceiling=i0o1");+ });++ it("removes authored Eve assertions when there is no sampled record decision", () => {+ expect(+ writeForwardedAudienceBaggage("eve.audience=public;ceiling=i1o1,vendor=value", undefined),+ ).toBe("vendor=value");+ expect(+ writeForwardedAudienceBaggage("eve.audience=public;ceiling=i1o1", undefined),+ ).toBeUndefined();+ });+});diff --git a/packages/eve/src/protocol/baggage.ts b/packages/eve/src/protocol/baggage.tsnew file mode 100644index 000000000..8d1c46ae3--- /dev/null+++ b/packages/eve/src/protocol/baggage.ts@@ -0,0 +1,90 @@+import type {+ ForwardedTraceAssertion,+ TraceContentCeiling,+} from "#shared/forwarded-trace-policy.js";+import { formatTraceContentCeiling } from "#shared/forwarded-trace-policy.js";++const EVE_AUDIENCE_KEY = "eve.audience";+const CEILING_PROPERTY_KEY = "ceiling";++export type ForwardedTraceBaggage = "absent" | "malformed" | ForwardedTraceAssertion;++/** Reads Eve's audience member without interpreting or rejecting unrelated baggage. */+export function readForwardedAudienceBaggage(value: string | null): ForwardedTraceBaggage {+ if (value === null) return "absent";+ const members = baggageMembers(value).filter(isEveAudienceMember);+ if (members.length === 0) return "absent";+ if (members.length !== 1) return "malformed";+ return parseEveAudienceMember(members[0]!);+}++/** Replaces any authored Eve audience member while preserving unrelated baggage entries. */+export function writeForwardedAudienceBaggage(+ value: string | undefined,+ assertion: ForwardedTraceAssertion | undefined,+): string | undefined {+ const retained = baggageMembers(value ?? "").filter((member) => !isEveAudienceMember(member));+ if (assertion !== undefined) {+ retained.push(+ `${EVE_AUDIENCE_KEY}=${assertion.originAudience};${CEILING_PROPERTY_KEY}=${formatTraceContentCeiling(assertion.ceiling)}`,+ );+ }+ return retained.length > 0 ? retained.join(",") : undefined;+}++function baggageMembers(value: string): string[] {+ return value.split(",").map(trimOws).filter(Boolean);+}++function parseEveAudienceMember(member: string): ForwardedTraceAssertion | "malformed" {+ const segments = member.split(";");+ if (segments.length !== 2) return "malformed";++ const audiencePair = parsePair(segments[0]!);+ if (audiencePair === undefined || audiencePair.key !== EVE_AUDIENCE_KEY) return "malformed";+ const originAudience = audiencePair.value;+ if (originAudience !== "public" && originAudience !== "private" && originAudience !== "unknown") {+ return "malformed";+ }++ const ceilingPair = parsePair(segments[1]!);+ if (ceilingPair === undefined || ceilingPair.key !== CEILING_PROPERTY_KEY) return "malformed";+ const ceiling = parseCeiling(ceilingPair.value);+ return ceiling === undefined ? "malformed" : { ceiling, originAudience };+}++function parsePair(segment: string): { readonly key: string; readonly value: string } | undefined {+ const separator = segment.indexOf("=");+ if (separator <= 0 || segment.indexOf("=", separator + 1) !== -1) return undefined;+ const key = trimOws(segment.slice(0, separator));+ const value = trimOws(segment.slice(separator + 1));+ if (key.length === 0 || value.length === 0) return undefined;+ if (key !== segment.slice(0, separator).trim()) return undefined;+ if (value !== segment.slice(separator + 1).trim()) return undefined;+ return { key, value };+}++function parseCeiling(value: string): TraceContentCeiling | undefined {+ const match = /^i([01])o([01])$/u.exec(value);+ return match === null+ ? undefined+ : {+ recordInputs: match[1] === "1",+ recordOutputs: match[2] === "1",+ };+}++function trimOws(value: string): string {+ return value.replace(/^[\t ]+|[\t ]+$/gu, "");+}++function baggageKey(member: string): string | undefined {+ const pair = member.split(";", 1)[0]!;+ const separator = pair.indexOf("=");+ return separator > 0 ? pair.slice(0, separator).trim() : undefined;+}++function isEveAudienceMember(member: string): boolean {+ const pair = member.split(";", 1)[0]!;+ return (baggageKey(member) ?? pair.trim()) === EVE_AUDIENCE_KEY;+}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.tsindex 5f144772d..191032dc4 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@@ -12,8 +12,17 @@ import { describe, expect, it, vi } from "vitest";import type { RouteHandlerArgs } from "#channel/routes.js";import type { RunInput, SessionAuthContext } from "#channel/types.js";import { contextStorage } from "#context/container.js";-import { AuthKey, InitiatorAuthKey } from "#context/keys.js";+import { serializeContext } from "#context/serialize.js";+import {+ AuthKey,+ ChannelInstrumentationKey,+ InitiatorAuthKey,+ ParentTraceContextKey,+ SessionTraceSeedKey,+} from "#context/keys.js";import { buildRunContext } from "#execution/runtime-context.js";+import { setChannelContext } from "#execution/channel-context.js";+import { buildSessionAttributes } from "#execution/eve-workflow-attributes.js";import { mockChannelContext } from "#internal/testing/mocks/mock-channel-operations.js";import { isConnectionAuthorizationFailedError } from "#public/connections/errors.js";import { principalKey, resolveConnectionPrincipal } from "#runtime/connections/principal.js";@@ -51,7 +60,7 @@ const FORWARDED_INITIATOR: SessionAuthContext = {function createEmptySkillBundle(): CompiledBundle {return {adapterRegistry: undefined as never,- compiledArtifactsSource: undefined as never,+ compiledArtifactsSource: { kind: "bundled" },graph: undefined as never,hookRegistry: undefined as never,moduleMap: undefined as never,@@ -99,20 +108,36 @@ function createEveCreateHandler(input: EveChannelInput) {}describe("eveChannel forwarded principal → runtime principal", () => {- it("seeds the forwarded principal into the run context and resolves a user Connect principal", async () => {+ it("preserves origin audience and ceiling across adapter-state persistence", async () => {+ const trustedForwarders = vi.fn(+ (caller: SessionAuthContext) => caller.principalId === ROUTER_CALLER.principalId,+ );const handler = createEveCreateHandler({- trustedForwarders: (caller) => caller.principalId === ROUTER_CALLER.principalId,+ trustedForwarders,auth: () => ROUTER_CALLER,});const response = await handler.fetch(new Request("https://receiver.example.com/eve/v1/session", {body: JSON.stringify({- forwardedPrincipal: { current: FORWARDED_CURRENT, initiator: FORWARDED_INITIATOR },+ forwardedPrincipal: {+ current: FORWARDED_CURRENT,+ initiator: FORWARDED_INITIATOR,+ },+ callback: {+ callId: "call-1",+ subagentName: "site-ops",+ token: "parent-token",+ url: "https://caller.example.com/eve/v1/callback/parent-token",+ },message: "check my dashboards",mode: "task",}),- headers: { "content-type": "application/json" },+ headers: {+ "content-type": "application/json",+ baggage: "vendor=value,eve.audience=private;ceiling=i1o0",+ traceparent: `00-${"1".repeat(32)}-${"2".repeat(16)}-01`,+ },method: "POST",}),);@@ -133,6 +158,45 @@ 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(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");+ ctx.set(SessionTraceSeedKey, {+ decision: { action: "record", recordInputs: true, recordOutputs: false },+ forwardedTracePolicy: {+ ceiling: { recordInputs: true, recordOutputs: false },+ originAudience: "private",+ },+ spanId: "2".repeat(16),+ traceFlags: 1,+ traceId: "1".repeat(32),+ });+ const serializedContext = serializeContext(ctx);+ expect(serializedContext[SessionTraceSeedKey.name]).toMatchObject({+ decision: { action: "record", recordInputs: true, recordOutputs: false },+ forwardedTracePolicy: {+ ceiling: { recordInputs: true, recordOutputs: false },+ originAudience: "private",+ },+ });+ expect(buildSessionAttributes({ inputMessage: "research", serializedContext })).toMatchObject({+ "$eve.is_trace_content_visible": false,+ });+ expect(ctx.get(ParentTraceContextKey)).toEqual({+ isRemote: true,+ forwardedTracePolicy: {+ ceiling: { recordInputs: true, recordOutputs: false },+ originAudience: "private",+ },+ spanId: "2".repeat(16),+ traceFlags: 1,+ traceId: "1".repeat(32),+ });expect(current).toMatchObject({attributes: { "eve:forwarded-by": ROUTER_CALLER.principalId, user_id: "U123" },principalId: "slack:U123",@@ -159,6 +223,132 @@ describe("eveChannel forwarded principal → runtime principal", () => {});// The audit attribute never enters Connect token-cache keying.expect(principalKey(principal)).toBe("user:slack:slack:U123");+ expect(trustedForwarders).toHaveBeenCalledTimes(1);+ });++ it.each(["eve.audience=public;ceiling=i1", "eve.audience=public"])(+ "keeps malformed or mixed-version baggage metadata-only: %s",+ async (baggage) => {+ const handler = createEveCreateHandler({+ trustedForwarders: () => true,+ auth: () => ROUTER_CALLER,+ });++ await handler.fetch(+ new Request("https://receiver.example.com/eve/v1/session", {+ body: JSON.stringify({+ forwardedPrincipal: { current: FORWARDED_CURRENT },+ callback: {+ callId: "call-1",+ subagentName: "site-ops",+ token: "parent-token",+ url: "https://caller.example.com/eve/v1/callback/parent-token",+ },+ message: "check my dashboards",+ mode: "task",+ }),+ headers: {+ "content-type": "application/json",+ baggage,+ traceparent: `00-${"1".repeat(32)}-${"2".repeat(16)}-01`,+ },+ method: "POST",+ }),+ );++ const options = handler.createSession.mock.calls[0]?.[0] as Omit<+ RunInput,+ "adapter" | "channelName" | "requestId"+ >;+ const ctx = buildRunContext({+ bundle: EMPTY_SKILL_BUNDLE,+ run: {+ adapter: { kind: "eve" },+ channelName: "eve",+ ...options,+ },+ });+ expect(ctx.get(ChannelInstrumentationKey)?.metadata.audience).toBe("unknown");+ expect(ctx.get(ParentTraceContextKey)?.forwardedTracePolicy).toEqual({+ ceiling: { recordInputs: false, recordOutputs: false },+ originAudience: "unknown",+ });+ },+ );++ it("ignores a ceiling that disagrees with unsampled trace flags", async () => {+ const handler = createEveCreateHandler({+ trustedForwarders: () => true,+ auth: () => ROUTER_CALLER,+ });++ await handler.fetch(+ new Request("https://receiver.example.com/eve/v1/session", {+ body: JSON.stringify({+ forwardedPrincipal: { current: FORWARDED_CURRENT },+ callback: {+ callId: "call-1",+ subagentName: "site-ops",+ token: "parent-token",+ url: "https://caller.example.com/eve/v1/callback/parent-token",+ },+ message: "check my dashboards",+ mode: "task",+ }),+ headers: {+ "content-type": "application/json",+ baggage: "eve.audience=private;ceiling=i1o1",+ traceparent: `00-${"1".repeat(32)}-${"2".repeat(16)}-00`,+ },+ method: "POST",+ }),+ );++ expect(handler.createSession.mock.calls[0]?.[0]?.parentTraceContext).not.toHaveProperty(+ "forwardedTracePolicy",+ );+ });++ it("ignores public audience baggage without an accepted forwarded principal", async () => {+ const handler = createEveCreateHandler({+ trustedForwarders: () => true,+ auth: () => ROUTER_CALLER,+ });++ await handler.fetch(+ new Request("https://receiver.example.com/eve/v1/session", {+ body: JSON.stringify({+ callback: {+ callId: "call-1",+ subagentName: "site-ops",+ token: "parent-token",+ url: "https://caller.example.com/eve/v1/callback/parent-token",+ },+ message: "check my dashboards",+ mode: "task",+ }),+ headers: {+ "content-type": "application/json",+ baggage: "eve.audience=public;ceiling=i1o1",+ traceparent: `00-${"1".repeat(32)}-${"2".repeat(16)}-01`,+ },+ method: "POST",+ }),+ );++ const options = handler.createSession.mock.calls[0]?.[0] as Omit<+ RunInput,+ "adapter" | "channelName" | "requestId"+ >;+ const ctx = buildRunContext({+ bundle: EMPTY_SKILL_BUNDLE,+ run: {+ adapter: { kind: "eve" },+ channelName: "eve",+ ...options,+ },+ });+ expect(ctx.get(ChannelInstrumentationKey)?.metadata.audience).toBe("unknown");});it("resolves the transport service principal (and fails Connect) without forwarding", async () => {@@ -206,4 +396,36 @@ describe("eveChannel forwarded principal → runtime principal", () => {expect(isConnectionAuthorizationFailedError(failure)).toBe(true);expect(failure).toMatchObject({ reason: "principal_required" });});++ it("ignores forwarded instrumentation without a delegated trace parent", async () => {+ const handler = createEveCreateHandler({+ trustedForwarders: () => true,+ auth: () => ROUTER_CALLER,+ });++ await handler.fetch(+ new Request("https://receiver.example.com/eve/v1/session", {+ body: JSON.stringify({+ forwardedPrincipal: {+ current: FORWARDED_CURRENT,+ },+ message: "check my dashboards",+ mode: "task",+ }),+ headers: {+ "content-type": "application/json",+ baggage: "eve.audience=public;ceiling=i1o1",+ traceparent: `00-${"1".repeat(32)}-${"2".repeat(16)}-01`,+ },+ method: "POST",+ }),+ );++ const options = handler.createSession.mock.calls[0]?.[0] as Omit<+ RunInput,+ "adapter" | "channelName" | "requestId"+ >;+ expect(options.channelMetadata).toBeUndefined();+ expect(options.parentTraceContext).toBeUndefined();+ });});diff --git a/packages/eve/src/public/definitions/remote-agent.ts b/packages/eve/src/public/definitions/remote-agent.tsindex 6d08675df..849886b56 100644--- a/packages/eve/src/public/definitions/remote-agent.ts+++ b/packages/eve/src/public/definitions/remote-agent.ts@@ -32,9 +32,12 @@ export interface RemoteAgentDefinition {* session's initiator pinned. Defaults to `false` — forwarding identity to* another deployment is an explicit decision, never ambient.*- * Only principal metadata crosses the wire, never tokens or credentials —- * {@link auth} keeps authenticating *this* deployment to the remote. The- * receiver must opt in with `eveChannel({ trustedForwarders })`;+ * When the parent trace is sampled and its audience is public, the same+ * option adds `eve.audience=public` to W3C Baggage. A receiver that accepts+ * this deployment through `eveChannel({ trustedForwarders })` uses that+ * audience for its own trace policy. Only principal and public-audience+ * metadata cross the wire, never tokens or credentials — {@link auth} keeps+ * authenticating *this* deployment to the remote.* a receiver that refuses the forwarder (or accepts no forwarded principal* at all) rejects with 403 and the dispatch fails.*/diff --git a/packages/eve/src/shared/forwarded-trace-policy.test.ts b/packages/eve/src/shared/forwarded-trace-policy.test.tsnew file mode 100644index 000000000..bbfb15244--- /dev/null+++ b/packages/eve/src/shared/forwarded-trace-policy.test.ts@@ -0,0 +1,97 @@+import { describe, expect, it } from "vitest";++import {+ applyLiveDeliveryAudienceCeiling,+ decisionToTraceContentCeiling,+ readForwardedTraceAssertion,+ resolveForwardedTraceSeed,+} from "#shared/forwarded-trace-policy.js";++describe("readForwardedTraceAssertion", () => {+ it("distinguishes absence from malformed durable state", () => {+ expect(readForwardedTraceAssertion(undefined)).toBeUndefined();+ expect(readForwardedTraceAssertion({ originAudience: "public" })).toEqual({+ ceiling: { recordInputs: false, recordOutputs: false },+ originAudience: "unknown",+ });+ });++ it("normalizes a valid assertion", () => {+ expect(+ readForwardedTraceAssertion({+ ceiling: { recordInputs: false, recordOutputs: true },+ originAudience: "private",+ }),+ ).toEqual({+ ceiling: { recordInputs: false, recordOutputs: true },+ originAudience: "private",+ });+ });+});++describe("decisionToTraceContentCeiling", () => {+ it("rejects drop and malformed durable decisions", () => {+ expect(decisionToTraceContentCeiling({ action: "drop" })).toBeUndefined();+ expect(+ decisionToTraceContentCeiling({+ action: "record",+ recordInputs: "yes",+ recordOutputs: true,+ }),+ ).toBeUndefined();+ });+});++describe("resolveForwardedTraceSeed", () => {+ it("intersects a malformed assertion's fail-closed ceiling with the decision", () => {+ expect(+ resolveForwardedTraceSeed({+ decision: { action: "record", recordInputs: true, recordOutputs: true },+ forwardedTracePolicy: { originAudience: "public" },+ traceFlags: 1,+ }),+ ).toEqual({+ decision: { action: "record", recordInputs: false, recordOutputs: false },+ forwardedTracePolicy: {+ ceiling: { recordInputs: false, recordOutputs: false },+ originAudience: "unknown",+ },+ traceFlags: 1,+ });+ });++ it("clears sampled flags for a malformed decision", () => {+ expect(+ resolveForwardedTraceSeed({+ decision: { action: "record", recordInputs: "yes", recordOutputs: true },+ forwardedTracePolicy: undefined,+ traceFlags: 1,+ }),+ ).toEqual({+ decision: { action: "drop" },+ forwardedTracePolicy: undefined,+ traceFlags: 0,+ });+ });+});++describe("applyLiveDeliveryAudienceCeiling", () => {+ const decision = { action: "record", recordInputs: true, recordOutputs: true } as const;+ const forwardedTracePolicy = {+ ceiling: { recordInputs: true, recordOutputs: true },+ originAudience: "public",+ } as const;++ it.each([+ ["unknown", forwardedTracePolicy, true],+ ["public", forwardedTracePolicy, true],+ ["private", forwardedTracePolicy, false],+ ["private", undefined, false],+ ] as const)("handles the %s delivery audience", (audience, policy, recordsContent) => {+ expect(applyLiveDeliveryAudienceCeiling(decision, audience, policy)).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.tsnew file mode 100644index 000000000..078e802c5--- /dev/null+++ b/packages/eve/src/shared/forwarded-trace-policy.ts@@ -0,0 +1,133 @@+import type { ChannelAudience } from "#shared/channel-audience.js";+import { applyAudienceCeiling } from "#shared/instrumentation-content.js";+import type { InstrumentationDecision } from "#shared/instrumentation-decision.js";+import {+ DROP_INSTRUMENTATION,+ intersectInstrumentationDecisions,+ readInstrumentationDecision,+} from "#shared/instrumentation-decision.js";++export const FAIL_CLOSED_FORWARDED_TRACE_ASSERTION: ForwardedTraceAssertion = {+ ceiling: { recordInputs: false, recordOutputs: false },+ originAudience: "unknown",+};++export interface TraceContentCeiling {+ readonly recordInputs: boolean;+ readonly recordOutputs: boolean;+}++export interface ForwardedTraceAssertion {+ readonly ceiling: TraceContentCeiling;+ readonly originAudience: ChannelAudience;+}++export interface ResolvedForwardedTraceState {+ readonly decision?: InstrumentationDecision;+ readonly forwardedTracePolicy?: ForwardedTraceAssertion;+ readonly traceFlags: number;+}++export interface ForwardedTraceSeedState {+ readonly decision?: unknown;+ readonly forwardedTracePolicy?: unknown;+ readonly traceFlags: number;+}++export function decisionToTraceContentCeiling(value: unknown): TraceContentCeiling | undefined {+ const decision = readInstrumentationDecision(value);+ return decision?.action === "record"+ ? {+ recordInputs: decision.recordInputs,+ recordOutputs: decision.recordOutputs,+ }+ : undefined;+}++export function traceContentCeilingToDecision(+ ceiling: TraceContentCeiling,+): InstrumentationDecision {+ return { action: "record", ...ceiling };+}++export function formatTraceContentCeiling(ceiling: TraceContentCeiling): string {+ return `i${ceiling.recordInputs ? "1" : "0"}o${ceiling.recordOutputs ? "1" : "0"}`;+}++/** Applies a distinct live delivery audience without re-capping callback or origin delivery. */+export function applyLiveDeliveryAudienceCeiling(+ decision: InstrumentationDecision,+ liveAudience: ChannelAudience,+ forwardedTracePolicy: ForwardedTraceAssertion | undefined,+): InstrumentationDecision {+ return forwardedTracePolicy !== undefined &&+ (liveAudience === "unknown" || liveAudience === forwardedTracePolicy.originAudience)+ ? decision+ : applyAudienceCeiling(decision, liveAudience);+}++export function readForwardedTraceAssertion(value: unknown): ForwardedTraceAssertion | undefined {+ if (value === undefined) return undefined;+ if (value === null || typeof value !== "object" || Array.isArray(value)) {+ return FAIL_CLOSED_FORWARDED_TRACE_ASSERTION;+ }+ const candidate = value as Partial<ForwardedTraceAssertion>;+ const ceiling = candidate.ceiling;+ if (+ ceiling === null ||+ typeof ceiling !== "object" ||+ typeof ceiling.recordInputs !== "boolean" ||+ typeof ceiling.recordOutputs !== "boolean"+ ) {+ return FAIL_CLOSED_FORWARDED_TRACE_ASSERTION;+ }+ if (+ candidate.originAudience !== "public" &&+ candidate.originAudience !== "private" &&+ candidate.originAudience !== "unknown"+ ) {+ return FAIL_CLOSED_FORWARDED_TRACE_ASSERTION;+ }+ return {+ ceiling: {+ recordInputs: ceiling.recordInputs,+ recordOutputs: ceiling.recordOutputs,+ },+ originAudience: candidate.originAudience,+ };+}++/** Resolves the coupled durable decision and assertion without allowing either to widen the other. */+function resolveForwardedTraceState(input: {+ readonly decision: unknown;+ readonly forwardedTracePolicy: unknown;+ readonly traceFlags: number;+}): ResolvedForwardedTraceState {+ const forwardedTracePolicy = readForwardedTraceAssertion(input.forwardedTracePolicy);+ let decision = readInstrumentationDecision(input.decision);+ if (forwardedTracePolicy !== undefined) {+ const ceiling = traceContentCeilingToDecision(forwardedTracePolicy.ceiling);+ decision =+ decision === undefined+ ? DROP_INSTRUMENTATION+ : intersectInstrumentationDecisions(decision, ceiling);+ }+ return {+ decision,+ forwardedTracePolicy,+ traceFlags: decision?.action === "drop" ? input.traceFlags & ~1 : input.traceFlags,+ };+}++export function resolveForwardedTraceSeed(+ seed: ForwardedTraceSeedState | undefined,+ fallbackPolicy?: ForwardedTraceAssertion,+): ResolvedForwardedTraceState | undefined {+ if (seed === undefined) return undefined;+ const hasPolicy = Object.prototype.hasOwnProperty.call(seed, "forwardedTracePolicy");+ return resolveForwardedTraceState({+ decision: seed.decision,+ forwardedTracePolicy: hasPolicy ? seed.forwardedTracePolicy : fallbackPolicy,+ traceFlags: seed.traceFlags,+ });+}diff --git a/packages/eve/src/shared/instrumentation-decision.test.ts b/packages/eve/src/shared/instrumentation-decision.test.tsnew file mode 100644index 000000000..1678fcf42--- /dev/null+++ b/packages/eve/src/shared/instrumentation-decision.test.ts@@ -0,0 +1,24 @@+import { describe, expect, it } from "vitest";++import { readInstrumentationDecision } from "#shared/instrumentation-decision.js";++describe("readInstrumentationDecision", () => {+ it("preserves absence and valid decisions", () => {+ expect(readInstrumentationDecision(undefined)).toBeUndefined();+ expect(+ readInstrumentationDecision({+ action: "record",+ recordInputs: false,+ recordOutputs: true,+ }),+ ).toEqual({ action: "record", recordInputs: false, recordOutputs: true });+ });++ it.each([+ null,+ { action: "record", recordInputs: "yes", recordOutputs: true },+ { action: "unknown" },+ ])("fails malformed durable state closed as drop", (value) => {+ expect(readInstrumentationDecision(value)).toEqual({ action: "drop" });+ });+});diff --git a/packages/eve/src/shared/instrumentation-decision.ts b/packages/eve/src/shared/instrumentation-decision.tsindex 0b2520498..0d876da6d 100644--- a/packages/eve/src/shared/instrumentation-decision.ts+++ b/packages/eve/src/shared/instrumentation-decision.ts@@ -7,3 +7,34 @@ export type InstrumentationDecision =};export const DROP_INSTRUMENTATION: InstrumentationDecision = { action: "drop" };++/** Reads durable decision state, treating malformed persisted values as drop. */+export function readInstrumentationDecision(value: unknown): InstrumentationDecision | undefined {+ if (value === undefined) return undefined;+ if (value === null || typeof value !== "object" || Array.isArray(value)) {+ return DROP_INSTRUMENTATION;+ }+ const decision = value as Partial<InstrumentationDecision>;+ if (decision.action === "drop") return DROP_INSTRUMENTATION;+ return decision.action === "record" &&+ typeof decision.recordInputs === "boolean" &&+ typeof decision.recordOutputs === "boolean"+ ? {+ action: "record",+ recordInputs: decision.recordInputs,+ recordOutputs: decision.recordOutputs,+ }+ : DROP_INSTRUMENTATION;+}++export function intersectInstrumentationDecisions(+ left: InstrumentationDecision,+ right: InstrumentationDecision,+): InstrumentationDecision {+ if (left.action === "drop" || right.action === "drop") return DROP_INSTRUMENTATION;+ return {+ action: "record",+ recordInputs: left.recordInputs && right.recordInputs,+ recordOutputs: left.recordOutputs && right.recordOutputs,+ };+}diff --git a/packages/eve/src/tracing/agent-otel-provider.test.ts b/packages/eve/src/tracing/agent-otel-provider.test.tsindex ef8f7ad33..97f3bd99d 100644--- a/packages/eve/src/tracing/agent-otel-provider.test.ts+++ b/packages/eve/src/tracing/agent-otel-provider.test.ts@@ -14,6 +14,7 @@ import {trace as runtimeTrace,} from "#compiled/@opentelemetry/api/index.js";import { ContextContainer, contextStorage } from "#context/container.js";+import { SessionTraceSeedKey } from "#context/keys.js";import { deserializeContext, serializeContext } from "#context/serialize.js";import { createAiSdkHookBridge } from "#instrumentation/ai-sdk-hook-bridge.js";import {@@ -884,6 +885,127 @@ describe("createAgentOtelInstrumentation", () => {});});+ it("preserves a private decision already intersected with a forwarded ceiling", async () => {+ const stateStore = new InMemoryAgentTraceStateStore();+ stateStore.setSession("session-forwarded-private", {+ channelAudience: "private",+ context: spanContext("1", "2"),+ decision: { action: "record", recordInputs: true, recordOutputs: false },+ rootSessionId: "session-forwarded-private",+ });+ const runtime = createRuntime(stateStore, null);+ const ctx = new ContextContainer();+ ctx.set(SessionTraceSeedKey, {+ ...spanContext("1", "2"),+ decision: { action: "record", recordInputs: true, recordOutputs: false },+ forwardedTracePolicy: {+ ceiling: { recordInputs: true, recordOutputs: false },+ originAudience: "private",+ },+ });++ await expect(+ contextStorage.run(ctx, () =>+ runtime.projectEvent(modelStartedEvent("session-forwarded-private")),+ ),+ ).resolves.toMatchObject({ input: { instructions: "private prompt" } });+ });++ it("applies a fail-closed forwarded ceiling to event-carried trace seeds", async () => {+ const runtime = createRuntime(new InMemoryAgentTraceStateStore(), null);+ const ctx = new ContextContainer();+ const traceSeed = {+ ...spanContext("1", "2"),+ decision: { action: "record", recordInputs: true, recordOutputs: true },+ forwardedTracePolicy: { originAudience: "public" },+ } as never;+ ctx.set(SessionTraceSeedKey, traceSeed);+ const event = {+ delivery: {+ channelAudience: "public" as const,+ channelKind: "channel:slack",+ channelName: "slack",+ deliveryId: "delivery-malformed-seed",+ },+ idempotencyKey: "channel-delivery:session-1:delivery-malformed-seed",+ input: { message: "private" },+ rootSessionId: "session-1",+ sessionId: "session-1",+ traceSeed,+ type: "channel.delivery.started" as const,+ };++ await expect(contextStorage.run(ctx, () => runtime.projectEvent(event))).resolves.toMatchObject(+ { input: undefined },+ );+ });++ it("caps forwarded content for an explicitly private delivery", async () => {+ const runtime = createRuntime(new InMemoryAgentTraceStateStore(), null);+ const ctx = new ContextContainer();+ const traceSeed = {+ ...spanContext("1", "2"),+ decision: { action: "record", recordInputs: true, recordOutputs: true },+ forwardedTracePolicy: {+ ceiling: { recordInputs: true, recordOutputs: true },+ originAudience: "public",+ },+ } as const;+ ctx.set(SessionTraceSeedKey, traceSeed);++ await expect(+ contextStorage.run(ctx, () =>+ runtime.projectEvent({+ delivery: {+ channelAudience: "private",+ channelKind: "channel:slack",+ channelName: "slack",+ deliveryId: "delivery-private",+ },+ idempotencyKey: "channel-delivery:session-1:delivery-private",+ input: { message: "private" },+ rootSessionId: "session-1",+ sessionId: "session-1",+ traceSeed,+ type: "channel.delivery.started",+ }),+ ),+ ).resolves.toMatchObject({ input: undefined });+ });++ it("normalizes an event-carried drop before opening its session span", async () => {+ const runtime = createRuntime(new InMemoryAgentTraceStateStore(), null);+ const ctx = new ContextContainer();+ const traceSeed = {+ ...spanContext("1", "2"),+ decision: { action: "record", recordInputs: "yes", recordOutputs: true },+ forwardedTracePolicy: {+ ceiling: { recordInputs: true, recordOutputs: true },+ originAudience: "public",+ },+ } as never;+ ctx.set(SessionTraceSeedKey, traceSeed);++ await contextStorage.run(ctx, () =>+ runtime.hooks.publish({+ delivery: {+ channelAudience: "public",+ channelKind: "channel:slack",+ channelName: "slack",+ deliveryId: "delivery-malformed-decision",+ },+ idempotencyKey: "channel-delivery:session-1:delivery-malformed-decision",+ input: { message: "private" },+ rootSessionId: "session-1",+ sessionId: "session-1",+ traceSeed,+ type: "channel.delivery.started",+ }),+ );+ await runtime.provider.forceFlush();+ expect(byName(runtime.exporter.getFinishedSpans(), "agent.session")).toHaveLength(0);+ });+it("reconstructs a sampled public session decision when persisted policy is absent", async () => {const stateStore = new InMemoryAgentTraceStateStore();stateStore.setSession("session-sampled", {diff --git a/packages/eve/src/tracing/agent-otel-provider.ts b/packages/eve/src/tracing/agent-otel-provider.tsindex ee3e16c98..493ecf6ca 100644--- a/packages/eve/src/tracing/agent-otel-provider.ts+++ b/packages/eve/src/tracing/agent-otel-provider.ts@@ -36,6 +36,11 @@ import { setAgentUsage } from "#tracing/agent-otel-usage.js";import { createAgentOtelSessionContext } from "#tracing/agent-otel-session-context.js";import type { TraceCapturePolicy } from "#tracing/otel-declaration.js";import { isSampledTrace, resolveTracePolicyDecision } from "#tracing/sampled-trace.js";+import {+ applyLiveDeliveryAudienceCeiling,+ resolveForwardedTraceSeed,+} from "#shared/forwarded-trace-policy.js";+import { readInstrumentationDecision } from "#shared/instrumentation-decision.js";import { withChannelAudience } from "#tracing/channel-audience-context.js";import { suppressTracing } from "#tracing/suppress-tracing.js";import { normalizeChannelAudience, type ChannelAudience } from "#shared/channel-audience.js";@@ -143,10 +148,15 @@ export function createAgentOtelInstrumentation(const audience = audienceForEvent(event, session?.channelAudience);const eventSeed = "traceSeed" in event ? event.traceSeed : undefined;const contextSeed = contextStorage.getStore()?.get(SessionTraceSeedKey);+ const contextTraceState = resolveForwardedTraceSeed(contextSeed);+ const eventTraceState = resolveForwardedTraceSeed(+ eventSeed,+ contextTraceState?.forwardedTracePolicy,+ );const decision =- eventSeed?.decision ??- contextSeed?.decision ??- session?.decision ??+ eventTraceState?.decision ??+ contextTraceState?.decision ??+ readInstrumentationDecision(session?.decision) ??(eventSeed !== undefined? resolveTracePolicyDecision(isSampledTrace(eventSeed), audience): contextSeed !== undefined@@ -155,16 +165,32 @@ export function createAgentOtelInstrumentation(? resolveTracePolicyDecision(isSampledTrace(session.context), audience): undefined);if (decision === undefined) return withoutInstrumentationContent(event);- return instrumentationEventForTraceDecision(- event,- decision.action === "drop"- ? decision+ const normalizedEvent =+ eventTraceState === undefined || !("traceSeed" in event) || event.traceSeed === undefined+ ? event: {- action: "record",- recordInputs: recordInputs && decision.recordInputs,- recordOutputs: recordOutputs && decision.recordOutputs,- },+ ...event,+ traceSeed: {+ ...event.traceSeed,+ decision: eventTraceState.decision,+ traceFlags: eventTraceState.traceFlags,+ },+ };+ return instrumentationEventForTraceDecision(+ normalizedEvent,+ applyLiveDeliveryAudienceCeiling(+ decision.action === "drop"+ ? decision+ : {+ action: "record",+ recordInputs: recordInputs && decision.recordInputs,+ recordOutputs: recordOutputs && decision.recordOutputs,+ },+ audience,+ eventTraceState?.forwardedTracePolicy ?? contextTraceState?.forwardedTracePolicy,+ ),audience,+ { applyAudienceCeiling: false },);};@@ -233,8 +259,6 @@ export function createAgentOtelInstrumentation(attemptScopes.delete(event.scope.attemptId);const attempt = steps.get(scope);if (attempt === undefined) return;- // The span event drops the `attempt` segment: this span *is* one attempt,- // and `agent.step.attempt` on it already says which.attempt.span.addEvent(event.type === "step.attempt.completed" ? "step.completed" : "step.failed",);diff --git a/packages/eve/src/tracing/agent-otel-session-context.ts b/packages/eve/src/tracing/agent-otel-session-context.tsindex a45036d60..4d87a5bab 100644--- a/packages/eve/src/tracing/agent-otel-session-context.ts+++ b/packages/eve/src/tracing/agent-otel-session-context.ts@@ -17,6 +17,7 @@ import {resolveTracePolicyDecision,} from "#tracing/sampled-trace.js";import type { AgentSessionTraceState, AgentTraceStateStore } from "#tracing/agent-trace-state.js";+import { readInstrumentationDecision } from "#shared/instrumentation-decision.js";interface AgentOtelSessionContextInput {readonly frameworkVersion: string;@@ -51,7 +52,7 @@ export function createAgentOtelSessionContext(readonly traceSeed?: InstrumentationTraceContext;}): SpanContext => {if (session.traceSeed !== undefined) {- if (!isSampledTrace(session.traceSeed)) {+ if (session.traceDecision.action === "drop" || !isSampledTrace(session.traceSeed)) {return {isRemote: false,spanId: session.traceSeed.spanId,@@ -215,7 +216,9 @@ function resolveSessionTraceDecision(audience: ChannelAudience,policy: TraceCapturePolicy | undefined,): ReturnType<typeof resolveTracePolicy> {- if (event.traceSeed?.decision !== undefined) return event.traceSeed.decision;+ if (event.traceSeed?.decision !== undefined) {+ return readInstrumentationDecision(event.traceSeed.decision) ?? { action: "drop" };+ }if (event.traceSeed !== undefined) {return resolveTracePolicyDecision(isSampledTrace(event.traceSeed), audience);}diff --git a/packages/eve/src/tracing/agent-trace-context-store.test.ts b/packages/eve/src/tracing/agent-trace-context-store.test.tsindex 4069519a0..b52f7014a 100644--- a/packages/eve/src/tracing/agent-trace-context-store.test.ts+++ b/packages/eve/src/tracing/agent-trace-context-store.test.ts@@ -134,6 +134,10 @@ describe("readSessionTraceContext", () => {await contextStorage.run(context, () => {context.set(SessionTraceSeedKey, {decision: { action: "record", recordInputs: true, recordOutputs: false },+ forwardedTracePolicy: {+ ceiling: { recordInputs: true, recordOutputs: true },+ originAudience: "private",+ },spanId: "2".repeat(16),traceFlags: 1,traceId: "1".repeat(32),@@ -148,6 +152,10 @@ describe("readSessionTraceContext", () => {expect(readSessionTraceContext(serialized, "session-1")).toEqual({...spanContext("1", "2"),decision: { action: "record", recordInputs: true, recordOutputs: false },+ forwardedTracePolicy: {+ ceiling: { recordInputs: true, recordOutputs: false },+ originAudience: "private",+ },});expect(readSessionTraceContext(serialized, "session-2")).toBeUndefined();expect(readSessionTraceContext({}, "session-1")).toBeUndefined();@@ -191,6 +199,10 @@ describe("readActionTraceContext", () => {await contextStorage.run(context, () => {context.set(SessionTraceSeedKey, {decision: { action: "record", recordInputs: true, recordOutputs: false },+ forwardedTracePolicy: {+ ceiling: { recordInputs: true, recordOutputs: true },+ originAudience: "private",+ },spanId: "2".repeat(16),traceFlags: 1,traceId: "1".repeat(32),@@ -213,6 +225,10 @@ describe("readActionTraceContext", () => {expect(readActionTraceContext(serialized, "session-1", "turn-1", "call-1")).toEqual({decision: { action: "record", recordInputs: true, recordOutputs: false },+ forwardedTracePolicy: {+ ceiling: { recordInputs: true, recordOutputs: false },+ originAudience: "private",+ },isRemote: false,spanId: "3".repeat(16),traceFlags: 1,diff --git a/packages/eve/src/tracing/agent-trace-context-store.ts b/packages/eve/src/tracing/agent-trace-context-store.tsindex 13773b2ac..836335f9d 100644--- a/packages/eve/src/tracing/agent-trace-context-store.ts+++ b/packages/eve/src/tracing/agent-trace-context-store.ts@@ -12,7 +12,14 @@ import type {AgentTurnTraceState,} from "#tracing/agent-trace-state.js";import { normalizeChannelAudience } from "#shared/channel-audience.js";-import type { InstrumentationDecision } from "#shared/instrumentation-decision.js";+import {+ type InstrumentationDecision,+ readInstrumentationDecision,+} from "#shared/instrumentation-decision.js";+import {+ decisionToTraceContentCeiling,+ resolveForwardedTraceSeed,+} from "#shared/forwarded-trace-policy.js";interface AgentTraceContextState {readonly actions: Readonly<Record<string, AgentActionTraceState>>;@@ -102,8 +109,28 @@ function withTraceDecision(storedDecision?: InstrumentationDecision,): SessionTraceContext {const seed = serializedContext[SessionTraceSeedKey.name] as SessionTraceSeed | undefined;- const decision = storedDecision ?? seed?.decision;- return decision === undefined ? context : { ...context, decision };+ const traceState = resolveForwardedTraceSeed({+ decision: storedDecision ?? seed?.decision,+ forwardedTracePolicy: seed?.forwardedTracePolicy,+ traceFlags: context.traceFlags,+ })!;+ const decision = traceState.decision;+ const forwardedTracePolicy = traceState.forwardedTracePolicy;+ const ceiling = decisionToTraceContentCeiling(decision);+ const resolvedContext = { ...context, traceFlags: traceState.traceFlags };+ if (forwardedTracePolicy === undefined) {+ return decision === undefined ? resolvedContext : { ...resolvedContext, decision };+ }+ const narrowedForwardedTracePolicy =+ ceiling === undefined ? forwardedTracePolicy : { ...forwardedTracePolicy, ceiling };+ if (decision === undefined) {+ return { ...resolvedContext, forwardedTracePolicy: narrowedForwardedTracePolicy };+ }+ return {+ ...resolvedContext,+ decision,+ forwardedTracePolicy: narrowedForwardedTracePolicy,+ };}/** Durable trace state backed by eve's serialized Workflow context. */@@ -245,7 +272,7 @@ function deserializeState(data: unknown): AgentTraceContextState {channelAudience: normalizeChannelAudience(value.channelAudience),channelKind: typeof value.channelKind === "string" ? value.channelKind : undefined,context: value.context,- decision: deserializeInstrumentationDecision(value.decision),+ decision: readInstrumentationDecision(value.decision),rootSessionId: typeof value.rootSessionId === "string" ? value.rootSessionId : "",} satisfies AgentSessionTraceState;});@@ -381,20 +408,6 @@ function isTurnTerminalType(return value === "turn.cancelled" || value === "turn.completed" || value === "turn.failed";}-function deserializeInstrumentationDecision(value: unknown): InstrumentationDecision | undefined {- if (!isRecord(value)) return undefined;- if (value.action === "drop") return { action: "drop" };- return value.action === "record" &&- typeof value.recordInputs === "boolean" &&- typeof value.recordOutputs === "boolean"- ? {- action: "record",- recordInputs: value.recordInputs,- recordOutputs: value.recordOutputs,- }- : undefined;-}-function isRecord(value: unknown): value is Record<string, unknown> {return typeof value === "object" && value !== null && !Array.isArray(value);}diff --git a/packages/eve/src/tracing/otel-declaration.ts b/packages/eve/src/tracing/otel-declaration.tsindex b16a2239c..1171b5aef 100644--- a/packages/eve/src/tracing/otel-declaration.ts+++ b/packages/eve/src/tracing/otel-declaration.ts@@ -70,9 +70,11 @@ export interface OtelOptions {* existing audience-aware behavior; explicit decisions can disable emission* or select input and output capture independently. Defaults to emitting* every audience, with content only for public conversations. The result is- * an OpenTelemetry capture ceiling: per-delivery audience and destination- * settings can only narrow it. It never changes what authored instrumentation- * providers receive. A thrown error rejects trace production without+ * an OpenTelemetry capture ceiling: local delivery audience and destination+ * settings can only narrow it. For a trusted remote trace, eve evaluates this+ * policy against the immutable origin audience and intersects it with the+ * parent's effective ceiling, so every hop can only narrow capture. It never+ * changes what authored instrumentation providers receive. A thrown error rejects trace production without* silencing lifecycle providers. The policy may be invoked more than once* while a new session is being prepared, so it must be deterministic for* consistent results.diff --git a/research/channel-audience-content-policy.md b/research/channel-audience-content-policy.mdindex 9a387b3f7..5d05dcc8d 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/2331status: proposed-last_updated: "2026-08-28"+last_updated: "2026-08-31"---# Audience-aware trace content policy@@ -22,7 +22,7 @@ type ChannelAudience = "public" | "private" | "unknown";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.-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. Remote agents classify their receiving channel independently rather than trusting opaque metadata across deployment boundaries.+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.## Public tracing API@@ -59,9 +59,11 @@ interface ProviderDefinition {declare function otel(options?: OtelOptions): OtelDeclaration;```-The `otel()` trace decision is a process-wide OTel ceiling. Each delivery is-intersected with its own audience classification, and destination settings may-narrow it further. A provider's `defineInstrumentation({ tracePolicy })` decision+The `otel()` trace decision is a process-wide OTel ceiling. Each local delivery is+intersected with its own audience classification. An accepted remote ceiling is+instead intersected with the receiver policy evaluated against the immutable origin+audience, permitting private content only when both sides explicitly approve it.+Destination settings may narrow the result further. A provider's `defineInstrumentation({ tracePolicy })` decisionis independent: `false` skips that provider, `true` uses audience-aware content,and an explicit emitted decision authorizes its input and output directions evenfor private channels. An omitted provider policy uses the default audience-aware