Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat(eve): add principals to Agent Runs turns (#2975)

Chad Hietala6d0485bdb79e
diff --git a/.changeset/trace-agent-principals.md b/.changeset/trace-agent-principals.md
new file mode 100644
index 000000000..2ae736f4d
--- /dev/null
+++ b/.changeset/trace-agent-principals.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Expose current and initiating principals in Agent Runs turn metadata, including channel-driven and resumed activations. Principal types remain bounded; IDs require a content-visible audience and a resolved trace policy permitting both input and output content, including any forwarded ceiling, and oversized IDs are omitted.
diff --git a/docs/guides/instrumentation.md b/docs/guides/instrumentation.md
index 52f499d0b..51c7487f3 100644
--- a/docs/guides/instrumentation.md
+++ b/docs/guides/instrumentation.md
@@ -187,6 +187,15 @@ output content, including errors reconstructed after a worker replacement.
Metadata-only capture retains failure status without those details. Error logging
outside eve's instrumented execution retains its existing exception content.
+Agent Runs activation metadata includes bounded principal summaries:
+
+- `agent.principal.current.type` and `agent.principal.current.id` describe the current caller.
+- `agent.principal.initiator.type` and `agent.principal.initiator.id` describe the authenticated principal that created the root session. The initiator remains fixed when later turns have a different caller.
+
+Types are limited to `user`, `service`, `runtime`, `app`, `anonymous`, `local-dev`, `unknown`, `none`, and `other`. Types are emitted for every audience when a principal is present. An absent type means no authentication context was set; `none` means an explicitly null principal and has no ID. The auth layer's `unknown` type stays `unknown`; unrecognized authored types become `other`.
+
+Principal IDs require a content-visible audience and a resolved trace decision that allows both `recordInputs` and `recordOutputs`. Public turns and unknown turns under `eve dev` can include IDs; private and hosted-unknown turns omit them. A user-configured trace policy or forwarded content ceiling that denies either direction omits both principal IDs before turn state is stored or sampled. Empty IDs and IDs larger than 1 KiB of UTF-8 data are omitted, not truncated; authentication records are unchanged. eve does not copy other authentication fields, such as claims, email attributes, issuers, or subjects, into these summaries.
+
## Runtime context
_Runtime context_ is an [AI SDK concept](https://ai-sdk.dev/docs/reference/ai-sdk-core/stream-text): a user-defined object that flows through a generation lifecycle. eve exposes it through `events["step.started"]`, a callback that runs once eve has assembled the model input for an attempt and returns `{ runtimeContext }`. Because eve registers the AI SDK's OpenTelemetry integration with runtime context enabled, those returned values ride onto the model-call span and its children. The field is named `runtimeContext`, not `metadata`, because AI SDK v7 carries per-call attributes on runtime context rather than a dedicated metadata field.
diff --git a/packages/eve/src/instrumentation/lifecycle.ts b/packages/eve/src/instrumentation/lifecycle.ts
index ed67126c2..a78fd3882 100644
--- a/packages/eve/src/instrumentation/lifecycle.ts
+++ b/packages/eve/src/instrumentation/lifecycle.ts
@@ -291,6 +291,31 @@ export interface InstrumentationTraceSeed extends InstrumentationTraceContext {
readonly decision?: InstrumentationDecision;
}
+export const INSTRUMENTATION_PRINCIPAL_TYPES = [
+ "anonymous",
+ "app",
+ "local-dev",
+ "none",
+ "other",
+ "runtime",
+ "service",
+ "unknown",
+ "user",
+] as const;
+
+export type InstrumentationPrincipalType = (typeof INSTRUMENTATION_PRINCIPAL_TYPES)[number];
+
+export function isInstrumentationPrincipalType(
+ value: unknown,
+): value is InstrumentationPrincipalType {
+ return INSTRUMENTATION_PRINCIPAL_TYPES.some((type) => type === value);
+}
+
+export interface InstrumentationPrincipalSummary {
+ readonly id?: string;
+ readonly type: InstrumentationPrincipalType;
+}
+
/**
* Which tool call dispatched a subagent child. The trace structure alone
* cannot say: one turn's children all parent to the same window.
@@ -332,7 +357,9 @@ export type InstrumentationSessionTransitionEvent =
export interface InstrumentationTurnStartedEvent {
readonly type: "turn.started";
readonly agentName?: string;
+ readonly currentPrincipal?: InstrumentationPrincipalSummary;
readonly idempotencyKey: string;
+ readonly initiatorPrincipal?: InstrumentationPrincipalSummary;
readonly parentLineage?: InstrumentationParentLineage;
readonly parentTraceContext?: InstrumentationTraceContext;
readonly rootSessionId: string;
diff --git a/packages/eve/src/instrumentation/prepare-trace-context.ts b/packages/eve/src/instrumentation/prepare-trace-context.ts
index ecd8ef8a0..2c89fdd01 100644
--- a/packages/eve/src/instrumentation/prepare-trace-context.ts
+++ b/packages/eve/src/instrumentation/prepare-trace-context.ts
@@ -22,6 +22,10 @@ export interface PrepareTurnTraceContextInput {
) => Promise<InstrumentationTraceSeed>;
};
readonly session: Omit<InstrumentationSessionStartedEvent, "idempotencyKey" | "type">;
+ readonly principals?: Pick<
+ InstrumentationTurnStartedEvent,
+ "currentPrincipal" | "initiatorPrincipal"
+ >;
readonly sequence: number;
readonly sessionStarted: boolean;
readonly traceContext?: RuntimeTraceContext;
@@ -54,6 +58,7 @@ export async function prepareTurnTraceContext(
try {
prepared = await input.instrumentation.prepareTurnTrace({
...session,
+ ...input.principals,
idempotencyKey: turnIdempotencyKey(session.sessionId, input.turnId),
sequence: input.sequence,
turnId: input.turnId,
diff --git a/packages/eve/src/instrumentation/principal-summary.test.ts b/packages/eve/src/instrumentation/principal-summary.test.ts
new file mode 100644
index 000000000..569c75190
--- /dev/null
+++ b/packages/eve/src/instrumentation/principal-summary.test.ts
@@ -0,0 +1,78 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import { summarizeInstrumentationPrincipal } from "#instrumentation/principal-summary.js";
+
+const principal = {
+ attributes: { email: "[email protected]" },
+ authenticator: "oidc",
+ issuer: "https://issuer.example",
+ principalId: "secret-user-id",
+ principalType: "tenant-administrator",
+ subject: "secret-subject",
+};
+
+describe("summarizeInstrumentationPrincipal", () => {
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ });
+
+ it("omits oversized IDs without truncating or changing authentication records", () => {
+ const oversized = { ...principal, principalId: "x".repeat(1025) };
+ expect(summarizeInstrumentationPrincipal(oversized, "public")).toEqual({ type: "other" });
+ expect(oversized.principalId).toHaveLength(1025);
+ expect(
+ summarizeInstrumentationPrincipal(
+ {
+ ...principal,
+ principalId: String.fromCodePoint(0x1f600).repeat(300),
+ },
+ "public",
+ ),
+ ).toEqual({ type: "other" });
+ });
+
+ it("preserves none and bounds authored principal types", () => {
+ expect(summarizeInstrumentationPrincipal(null, "public")).toEqual({
+ type: "none",
+ });
+ expect(summarizeInstrumentationPrincipal(undefined, "public")).toBeUndefined();
+ expect(summarizeInstrumentationPrincipal(principal, "public")).toEqual({
+ id: "secret-user-id",
+ type: "other",
+ });
+ expect(
+ summarizeInstrumentationPrincipal({ ...principal, principalType: "runtime" }, "public"),
+ ).toEqual({ id: "secret-user-id", type: "runtime" });
+ expect(
+ summarizeInstrumentationPrincipal({ ...principal, principalType: "unknown" }, "public"),
+ ).toEqual({ id: "secret-user-id", type: "unknown" });
+ });
+
+ it("omits IDs when the audience is not content-visible", () => {
+ expect(summarizeInstrumentationPrincipal(principal, "private")).toEqual({
+ type: "other",
+ });
+ expect(summarizeInstrumentationPrincipal(principal, "unknown")).toEqual({
+ type: "other",
+ });
+ });
+
+ it("follows the existing local-development rule for unknown audiences", () => {
+ vi.stubEnv("EVE_DEV", "1");
+
+ expect(summarizeInstrumentationPrincipal(principal, "unknown")).toEqual({
+ id: "secret-user-id",
+ type: "other",
+ });
+ });
+
+ it("never includes claims or principal attributes", () => {
+ const summary = summarizeInstrumentationPrincipal(principal, "public");
+
+ expect(summary).not.toHaveProperty("attributes");
+ expect(summary).not.toHaveProperty("issuer");
+ expect(summary).not.toHaveProperty("subject");
+ expect(JSON.stringify(summary)).not.toContain("[email protected]");
+ expect(JSON.stringify(summary)).not.toContain("secret-subject");
+ });
+});
diff --git a/packages/eve/src/instrumentation/principal-summary.ts b/packages/eve/src/instrumentation/principal-summary.ts
new file mode 100644
index 000000000..fddf15385
--- /dev/null
+++ b/packages/eve/src/instrumentation/principal-summary.ts
@@ -0,0 +1,61 @@
+import type { SessionAuthContext } from "#channel/types.js";
+import type { ContextReader } from "#context/key.js";
+import { AuthKey, InitiatorAuthKey } from "#context/keys.js";
+import {
+ isInstrumentationPrincipalType,
+ type InstrumentationPrincipalSummary,
+} from "#instrumentation/lifecycle.js";
+import type { ChannelAudience } from "#shared/channel-audience.js";
+import { shouldCaptureInstrumentationContent } from "#shared/instrumentation-content.js";
+import type { InstrumentationDecision } from "#shared/instrumentation-decision.js";
+import { resolveTracePolicyDecision } from "#shared/trace-policy.js";
+import { boundedPrincipalId } from "#tracing/telemetry-budget.js";
+
+export function summarizeInstrumentationPrincipal(
+ principal: SessionAuthContext | null | undefined,
+ audience: ChannelAudience,
+): InstrumentationPrincipalSummary | undefined {
+ if (principal === undefined) return undefined;
+ if (principal === null) return { type: "none" };
+ const type =
+ isInstrumentationPrincipalType(principal.principalType) && principal.principalType !== "none"
+ ? principal.principalType
+ : "other";
+ const id = shouldCaptureInstrumentationContent(audience)
+ ? boundedPrincipalId(principal.principalId)
+ : undefined;
+ return id === undefined ? { type } : { id, type };
+}
+
+export function applyPrincipalTraceDecision(
+ principal: InstrumentationPrincipalSummary | undefined,
+ decision: InstrumentationDecision | undefined,
+): InstrumentationPrincipalSummary | undefined {
+ if (principal === undefined) return undefined;
+ return principal.type !== "none" &&
+ decision?.action === "record" &&
+ decision.recordInputs &&
+ decision.recordOutputs
+ ? principal
+ : { type: principal.type };
+}
+
+export function readInstrumentationPrincipals(
+ context: ContextReader,
+ audience: ChannelAudience,
+ decision: InstrumentationDecision = resolveTracePolicyDecision(true, audience),
+): {
+ readonly currentPrincipal?: InstrumentationPrincipalSummary;
+ readonly initiatorPrincipal?: InstrumentationPrincipalSummary;
+} {
+ return {
+ currentPrincipal: applyPrincipalTraceDecision(
+ summarizeInstrumentationPrincipal(context.get(AuthKey), audience),
+ decision,
+ ),
+ initiatorPrincipal: applyPrincipalTraceDecision(
+ summarizeInstrumentationPrincipal(context.get(InitiatorAuthKey), audience),
+ decision,
+ ),
+ };
+}
diff --git a/packages/eve/src/instrumentation/runtime.test.ts b/packages/eve/src/instrumentation/runtime.test.ts
index 17fd3ba50..be401d720 100644
--- a/packages/eve/src/instrumentation/runtime.test.ts
+++ b/packages/eve/src/instrumentation/runtime.test.ts
@@ -2,8 +2,10 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
import { ContextContainer, contextStorage } from "#context/container.js";
import {
+ AuthKey,
ChannelInstrumentationKey,
ConversationIdKey,
+ InitiatorAuthKey,
OtelTraceEnabledKey,
ParentTraceContextKey,
ParentSessionKey,
@@ -418,6 +420,74 @@ describe("bindInstrumentationRuntime", () => {
});
});
+ it.each([
+ ["public", undefined, true],
+ ["private", undefined, false],
+ ["public", { action: "drop" }, false],
+ ["public", { action: "record", recordInputs: false, recordOutputs: true }, false],
+ ["public", { action: "record", recordInputs: true, recordOutputs: false }, false],
+ ["public", { action: "record", recordInputs: false, recordOutputs: false }, false],
+ ["public", { action: "record", recordInputs: true, recordOutputs: true }, true],
+ ] as const)(
+ "prepares %s turn traces with decision %j and permitted principal summaries",
+ async (audience, decision, includesId) => {
+ const ctx = createContext(audience);
+ if (decision !== undefined) {
+ ctx.set(SessionTraceSeedKey, {
+ decision,
+ spanId: "1".repeat(16),
+ traceFlags: decision.action === "drop" ? 0 : 1,
+ traceId: "2".repeat(32),
+ });
+ }
+ ctx.set(AuthKey, {
+ attributes: { email: "[email protected]" },
+ authenticator: "api-key",
+ principalId: "current-secret",
+ principalType: "service",
+ });
+ ctx.set(InitiatorAuthKey, {
+ attributes: { email: "[email protected]" },
+ authenticator: "oidc",
+ principalId: "initiator-secret",
+ principalType: "user",
+ });
+ const prepareTurnTrace = vi.fn().mockResolvedValue({
+ spanId: "1".repeat(16),
+ traceFlags: 1,
+ traceId: "2".repeat(32),
+ });
+ const instrumentation = bindInstrumentationRuntime(
+ {
+ ...createRuntime({ capturesContent: false, publish: vi.fn() }),
+ prepareTurnTrace,
+ },
+ ctx,
+ boundSession,
+ );
+
+ await instrumentation?.preparePreamble({
+ sequence: 0,
+ sessionStarted: true,
+ turnId: "turn-1",
+ });
+
+ const event = prepareTurnTrace.mock.calls[0]?.[0];
+ expect(event).toMatchObject({
+ currentPrincipal: { type: "service" },
+ initiatorPrincipal: { type: "user" },
+ });
+ if (includesId) {
+ expect(event?.currentPrincipal?.id).toBe("current-secret");
+ expect(event?.initiatorPrincipal?.id).toBe("initiator-secret");
+ } else {
+ expect(event?.currentPrincipal).not.toHaveProperty("id");
+ expect(event?.initiatorPrincipal).not.toHaveProperty("id");
+ }
+ expect(JSON.stringify(event)).not.toContain("@example.com");
+ },
+ );
+
it("keeps the step-entry audience for the rest of the step", async () => {
const ctx = createContext("private");
const instrumentation = bindInstrumentationRuntime(
diff --git a/packages/eve/src/instrumentation/runtime.ts b/packages/eve/src/instrumentation/runtime.ts
index 8e7fc74b4..4711169d9 100644
--- a/packages/eve/src/instrumentation/runtime.ts
+++ b/packages/eve/src/instrumentation/runtime.ts
@@ -52,10 +52,8 @@ import {
OtelTraceEnabledKey,
ParentSessionKey,
ParentTraceContextKey,
- SessionCallbackKey,
SessionTraceSeedKey,
} from "#context/keys.js";
-import { ChannelKey } from "#runtime/sessions/runtime-context-keys.js";
import { normalizeChannelAudience } from "#shared/channel-audience.js";
import { withErrorContent } from "#tracing/error-content-context.js";
import type { AgentSamplingOperation } from "#tracing/agent-span-contract.js";
@@ -64,7 +62,7 @@ import {
resolveTracePolicy,
resolveTracePolicyDecision,
} from "#tracing/sampled-trace.js";
-import { resolveParentLineage } from "#instrumentation/parent-lineage.js";
+import { readInstrumentationSessionContext } from "#instrumentation/session-context.js";
import type { ChannelInstrumentationProjection, SessionTraceContext } from "#channel/types.js";
import { readSessionTraceDecision } from "#tracing/agent-trace-context-store.js";
import {
@@ -76,7 +74,6 @@ import {
formatTraceContentCeiling,
type ForwardedTraceAssertion,
readForwardedTraceAssertion,
- resolveForwardedTraceSeed,
traceContentCeilingToDecision,
} from "#shared/forwarded-trace-policy.js";
import { readConversationId } from "#tracing/conversation-context.js";
@@ -111,7 +108,7 @@ export interface InstrumentationStepScope<TSession> {
readonly turnId: string;
}) => PreparedInstrumentationAttempt;
readonly preparePreamble: (
- input: Omit<PrepareTurnTraceContextInput, "instrumentation" | "session">,
+ input: Omit<PrepareTurnTraceContextInput, "instrumentation" | "principals" | "session">,
) => Promise<RuntimeTraceContext | undefined>;
readonly publishInputResolutions: (input: {
readonly batch: ResolvedInputBatch;
@@ -210,34 +207,14 @@ export function bindInstrumentationRuntime(
}
if (runtime === undefined) return undefined;
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);
- const parent = context.get(ParentSessionKey),
- channel = context.get(ChannelKey);
- return {
- channel,
- context,
- instrumentation: context.get(ChannelInstrumentationKey),
- forwardedTracePolicy: readForwardedTraceAssertion(traceSeed?.forwardedTracePolicy),
- parent,
- parentLineage: resolveParentLineage(parent, channel, context.get(SessionCallbackKey)),
- parentTraceContext,
- traceSeed,
- };
- };
+ const readSessionContext = () =>
+ readInstrumentationSessionContext(contextStorage.getStore() ?? ctx);
const bindHooks = (sessionContext: ReturnType<typeof readSessionContext>) => {
const channel = sessionContext.instrumentation;
return (
baseHooks.forTrace?.({
agentName: boundSession.agentName,
- audience: normalizeChannelAudience(channel?.metadata.audience),
+ audience: sessionContext.audience,
channelType: channel?.channelType,
}) ?? baseHooks
);
@@ -259,13 +236,13 @@ export function bindInstrumentationRuntime(
sessionContext: ReturnType<typeof readSessionContext>,
) => {
const channel = sessionContext.instrumentation;
- const audience = normalizeChannelAudience(channel?.metadata.audience);
return prepareTurnTraceContext({
...input,
instrumentation: runtime,
+ principals: sessionContext.principals,
session: {
agentName: boundSession.agentName,
- channelAudience: audience,
+ channelAudience: sessionContext.audience,
channelType: channel?.channelType,
parentLineage: sessionContext.parentLineage,
parentTraceContext: sessionContext.parentTraceContext,
diff --git a/packages/eve/src/instrumentation/session-context.test.ts b/packages/eve/src/instrumentation/session-context.test.ts
new file mode 100644
index 000000000..155523cf4
--- /dev/null
+++ b/packages/eve/src/instrumentation/session-context.test.ts
@@ -0,0 +1,94 @@
+import { describe, expect, it } from "vitest";
+
+import type { SessionAuthContext } from "#channel/types.js";
+import { ContextContainer } from "#context/container.js";
+import {
+ AuthKey,
+ ChannelInstrumentationKey,
+ InitiatorAuthKey,
+ ParentSessionKey,
+} from "#context/keys.js";
+import { readInstrumentationSessionContext } from "#instrumentation/session-context.js";
+
+const initiator: SessionAuthContext = {
+ attributes: { email: "[email protected]" },
+ authenticator: "oidc",
+ principalId: "initiator-secret",
+ principalType: "user",
+};
+
+const current: SessionAuthContext = {
+ attributes: {},
+ authenticator: "api-key",
+ principalId: "service-secret",
+ principalType: "service",
+};
+
+describe("readInstrumentationSessionContext", () => {
+ it("keeps the initiator stable while the current principal changes", () => {
+ const context = new ContextContainer();
+ context.set(AuthKey, current);
+ context.set(ChannelInstrumentationKey, {
+ kind: "channel:test",
+ metadata: { audience: "public" },
+ });
+ context.set(InitiatorAuthKey, initiator);
+
+ const first = readInstrumentationSessionContext(context);
+ context.set(AuthKey, initiator);
+ const continuation = readInstrumentationSessionContext(context);
+
+ expect(first.principals.currentPrincipal).toEqual({
+ id: "service-secret",
+ type: "service",
+ });
+ expect(continuation.principals.currentPrincipal).toEqual(first.principals.initiatorPrincipal);
+ expect(continuation.principals.initiatorPrincipal).toEqual(first.principals.initiatorPrincipal);
+ });
+
+ it("uses the actual principal ID across a public delegated trace tree", () => {
+ const parent = new ContextContainer();
+ parent.set(AuthKey, initiator);
+ parent.set(ChannelInstrumentationKey, {
+ kind: "channel:test",
+ metadata: { audience: "public" },
+ });
+ parent.set(InitiatorAuthKey, initiator);
+
+ const child = new ContextContainer();
+ child.set(AuthKey, initiator);
+ child.set(ChannelInstrumentationKey, {
+ kind: "channel:test",
+ metadata: { audience: "public" },
+ });
+ child.set(InitiatorAuthKey, initiator);
+ child.set(ParentSessionKey, {
+ callId: "call-1",
+ rootSessionId: "root-session",
+ sessionId: "parent-session",
+ turn: { id: "turn-1", sequence: 0 },
+ });
+
+ const parentSummary = readInstrumentationSessionContext(parent).principals.currentPrincipal;
+ const childSummary = readInstrumentationSessionContext(child).principals.currentPrincipal;
+
+ expect(childSummary).toEqual(parentSummary);
+ expect(childSummary).toEqual({ id: "initiator-secret", type: "user" });
+ expect(JSON.stringify(childSummary)).not.toContain("[email protected]");
+ });
+
+ it("keeps private principal metadata type-only", () => {
+ const context = new ContextContainer();
+ context.set(AuthKey, current);
+ context.set(ChannelInstrumentationKey, {
+ kind: "channel:test",
+ metadata: { audience: "private" },
+ });
+ context.set(InitiatorAuthKey, initiator);
+
+ expect(readInstrumentationSessionContext(context).principals).toEqual({
+ currentPrincipal: { type: "service" },
+ initiatorPrincipal: { type: "user" },
+ });
+ });
+});
diff --git a/packages/eve/src/instrumentation/session-context.ts b/packages/eve/src/instrumentation/session-context.ts
new file mode 100644
index 000000000..86c13ef08
--- /dev/null
+++ b/packages/eve/src/instrumentation/session-context.ts
@@ -0,0 +1,41 @@
+import type { AlsContext } from "#context/container.js";
+import {
+ ChannelInstrumentationKey,
+ ParentSessionKey,
+ ParentTraceContextKey,
+ SessionCallbackKey,
+ SessionTraceSeedKey,
+} from "#context/keys.js";
+import { resolveParentLineage } from "#instrumentation/parent-lineage.js";
+import { readInstrumentationPrincipals } from "#instrumentation/principal-summary.js";
+import { ChannelKey } from "#runtime/sessions/runtime-context-keys.js";
+import {
+ readForwardedTraceAssertion,
+ resolveForwardedTraceSeed,
+} from "#shared/forwarded-trace-policy.js";
+import { normalizeChannelAudience } from "#shared/channel-audience.js";
+
+export function readInstrumentationSessionContext(context: AlsContext) {
+ const storedTraceSeed = context.get(SessionTraceSeedKey);
+ const resolvedTraceState = resolveForwardedTraceSeed(storedTraceSeed);
+ const traceSeed =
+ storedTraceSeed === undefined || resolvedTraceState === undefined
+ ? undefined
+ : { ...storedTraceSeed, ...resolvedTraceState };
+ const parent = context.get(ParentSessionKey);
+ const channel = context.get(ChannelKey);
+ const instrumentation = context.get(ChannelInstrumentationKey);
+ const audience = normalizeChannelAudience(instrumentation?.metadata.audience);
+ return {
+ audience,
+ channel,
+ context,
+ forwardedTracePolicy: readForwardedTraceAssertion(traceSeed?.forwardedTracePolicy),
+ instrumentation,
+ parent,
+ parentLineage: resolveParentLineage(parent, channel, context.get(SessionCallbackKey)),
+ parentTraceContext: context.get(ParentTraceContextKey),
+ principals: readInstrumentationPrincipals(context, audience, traceSeed?.decision),
+ traceSeed,
+ };
+}
diff --git a/packages/eve/src/tracing/agent-otel-provider.test.ts b/packages/eve/src/tracing/agent-otel-provider.test.ts
index 18cfe632b..5b5ea0078 100644
--- a/packages/eve/src/tracing/agent-otel-provider.test.ts
+++ b/packages/eve/src/tracing/agent-otel-provider.test.ts
@@ -36,6 +36,7 @@ import {
type InstrumentationEvent,
type InstrumentationHooks,
type InstrumentationParentLineage,
+ type InstrumentationPrincipalSummary,
type InstrumentationTraceContext,
type InstrumentationUsage,
} from "#instrumentation/lifecycle.js";
@@ -81,6 +82,7 @@ function createRuntime(
recordOutputs: true,
}),
extraSpanProcessors: readonly SpanProcessor[] = [],
+ samplesTrace?: AgentOtelInstrumentationInput["samplesTrace"],
): TestRuntime {
const exporter = new InMemorySpanExporter();
const idGenerator = new AgentSpanIdGenerator();
@@ -96,6 +98,7 @@ function createRuntime(
idGenerator,
recordInputs: true,
recordOutputs: true,
+ samplesTrace,
stateStore,
tracer,
};
@@ -311,7 +314,9 @@ async function emitAttempt(input: {
async function publishTurnStarted(input: {
readonly channelAudience?: ChannelAudience;
+ readonly currentPrincipal?: InstrumentationPrincipalSummary;
readonly hooks: InstrumentationHooks;
+ readonly initiatorPrincipal?: InstrumentationPrincipalSummary;
readonly parentLineage?: InstrumentationParentLineage;
readonly parentTraceContext?: InstrumentationTraceContext;
readonly rootSessionId?: string;
@@ -334,7 +339,9 @@ async function publishTurnStarted(input: {
type: "session.started",
});
await input.hooks.publish({
+ currentPrincipal: input.currentPrincipal,
idempotencyKey: turnIdempotencyKey(input.sessionId, input.turnId),
+ initiatorPrincipal: input.initiatorPrincipal,
parentLineage: input.parentLineage,
parentTraceContext: input.parentTraceContext,
rootSessionId,
@@ -511,6 +518,66 @@ describe("createAgentOtelInstrumentation", () => {
expect(turn.parentSpanContext).toBeUndefined();
});
+ it.each([
+ false,
+ { emit: true, recordInputs: false, recordOutputs: false },
+ { emit: true, recordInputs: false, recordOutputs: true },
+ { emit: true, recordInputs: true, recordOutputs: false },
+ { emit: true, recordInputs: true, recordOutputs: true },
+ ] as const)(
+ "applies trace policy %j to principals before sampling and storage",
+ async (policy) => {
+ const store = new InMemoryAgentTraceStateStore();
+ const samplesTrace = vi.fn(() => true);
+ const runtime = createRuntime(store, () => policy, [], samplesTrace);
+ const includesId = policy !== false && policy.recordInputs && policy.recordOutputs;
+ try {
+ await runtime.prepareSessionTrace({
+ agentName: "weather",
+ channelAudience: "public",
+ idempotencyKey: sessionIdempotencyKey("session-1"),
+ rootSessionId: "session-1",
+ sessionId: "session-1",
+ type: "session.started",
+ });
+ await runtime.prepareTurnTrace({
+ currentPrincipal: { id: "current-secret", type: "service" },
+ initiatorPrincipal: { id: "initiator-secret", type: "user" },
+ idempotencyKey: turnIdempotencyKey("session-1", "turn-1"),
+ rootSessionId: "session-1",
+ sequence: 0,
+ sessionId: "session-1",
+ turnId: "turn-1",
+ type: "turn.started",
+ });
+ const turn = await store.getTurn("session-1", "turn-1");
+ expect(turn?.currentPrincipal).toStrictEqual(
+ includesId ? { id: "current-secret", type: "service" } : { type: "service" },
+ );
+ expect(turn?.initiatorPrincipal).toStrictEqual(
+ includesId ? { id: "initiator-secret", type: "user" } : { type: "user" },
+ );
+ expect(samplesTrace).toHaveBeenCalledTimes(policy === false ? 0 : 1);
+ if (!includesId) expect(JSON.stringify(samplesTrace.mock.calls)).not.toContain("-secret");
+ await completeTurn(runtime.hooks, "session-1", "turn-1");
+ await runtime.provider.forceFlush();
+ const spans = runtime.exporter.getFinishedSpans();
+ expect(spans).toHaveLength(policy === false ? 0 : 1);
+ if (policy !== false) {
+ expect(spans[0]?.attributes["agent.principal.current.type"]).toBe("service");
+ expect(spans[0]?.attributes["agent.principal.current.id"]).toBe(
+ includesId ? "current-secret" : undefined,
+ );
+ expect(spans[0]?.attributes["agent.principal.initiator.id"]).toBe(
+ includesId ? "initiator-secret" : undefined,
+ );
+ }
+ } finally {
+ await runtime.provider.shutdown();
+ }
+ },
+ );
+
it("uses the pre-allocated trace seed for the first activation root", async () => {
const runtime = createRuntime();
const seed: InstrumentationTraceContext = {
@@ -573,7 +640,9 @@ describe("createAgentOtelInstrumentation", () => {
};
await publishTurnStarted({
+ currentPrincipal: { id: "user-123", type: "user" },
hooks: runtime.hooks,
+ initiatorPrincipal: { type: "none" },
parentLineage,
parentTraceContext: parent,
rootSessionId: "root-session",
@@ -597,9 +666,13 @@ describe("createAgentOtelInstrumentation", () => {
},
]);
expect(invocation.attributes).toMatchObject({
+ "agent.principal.current.id": "user-123",
+ "agent.principal.current.type": "user",
+ "agent.principal.initiator.type": "none",
"gen_ai.conversation.id": "root-session",
"gen_ai.operation.name": "invoke_agent",
});
+ expect(invocation.attributes).not.toHaveProperty("agent.principal.initiator.id");
expect(invocation.attributes).not.toHaveProperty("agent.parent_call.id");
expect(invocation.attributes).not.toHaveProperty("agent.parent_run.id");
expect(invocation.attributes).not.toHaveProperty("agent.root_run.id");
diff --git a/packages/eve/src/tracing/agent-otel-runtime-context.ts b/packages/eve/src/tracing/agent-otel-runtime-context.ts
index f328bb6ff..e654247b3 100644
--- a/packages/eve/src/tracing/agent-otel-runtime-context.ts
+++ b/packages/eve/src/tracing/agent-otel-runtime-context.ts
@@ -1,7 +1,7 @@
import type { AgentTurnTraceState } from "#tracing/agent-trace-state.js";
-import { agentTraceIdentityAttributes } from "#tracing/agent-otel-attributes.js";
import { agentSpanNamingAttributes } from "#tracing/agent-span-naming.js";
import { agentInvocationSpanName } from "#tracing/agent-span-contract.js";
+import { agentTraceIdentityAttributes } from "#tracing/agent-otel-attributes.js";
type SpanAttributePrimitive = string | number | boolean;
type SpanAttributeValue = SpanAttributePrimitive | SpanAttributePrimitive[];
@@ -17,6 +17,7 @@ export function agentActivationAttributes(input: {
"agent.framework.name": "eve",
"agent.framework.version": input.frameworkVersion,
"agent.name": input.agentName,
+ ...agentPrincipalAttributes(input.turn),
"agent.channel.delivery.id": input.turn.channelDelivery?.deliveryId,
"agent.channel.delivery.input": input.turn.channelDelivery?.inputAttribute,
"agent.channel.kind": input.turn.channelDelivery?.channelKind,
@@ -35,6 +36,15 @@ export function agentActivationAttributes(input: {
};
}
+export function agentPrincipalAttributes(turn: AgentTurnTraceState): Record<string, string> {
+ const attributes: Record<string, string> = {};
+ setOptionalAttribute(attributes, "agent.principal.current.id", turn.currentPrincipal?.id);
+ setOptionalAttribute(attributes, "agent.principal.current.type", turn.currentPrincipal?.type);
+ setOptionalAttribute(attributes, "agent.principal.initiator.id", turn.initiatorPrincipal?.id);
+ setOptionalAttribute(attributes, "agent.principal.initiator.type", turn.initiatorPrincipal?.type);
+ return attributes;
+}
+
/** Flattens merged runtime context into AI SDK-compatible span attributes. */
export function runtimeContextAttributes(
runtimeContext: Readonly<Record<string, unknown>> | undefined,
@@ -73,3 +83,11 @@ function flattenContextAttribute(
}
}
}
+
+function setOptionalAttribute(
+ attributes: Record<string, string>,
+ key: string,
+ value: string | undefined,
+): void {
+ if (value !== undefined) attributes[key] = value;
+}
diff --git a/packages/eve/src/tracing/agent-otel-session-context.ts b/packages/eve/src/tracing/agent-otel-session-context.ts
index c43661ff2..8116023f7 100644
--- a/packages/eve/src/tracing/agent-otel-session-context.ts
+++ b/packages/eve/src/tracing/agent-otel-session-context.ts
@@ -23,6 +23,7 @@ import {
} from "#tracing/agent-span-contract.js";
import { agentActivationAttributes } from "#tracing/agent-otel-runtime-context.js";
import type { AgentTurnTraceState } from "#tracing/agent-trace-state.js";
+import { applyPrincipalTraceDecision } from "#instrumentation/principal-summary.js";
interface AgentOtelSessionContextInput {
readonly frameworkVersion: string;
@@ -91,6 +92,8 @@ export function createAgentOtelSessionContext(
const turn: AgentTurnTraceState = {
caller: caller === undefined ? undefined : adoptedSpanContext(caller),
context: turnContext,
+ currentPrincipal: applyPrincipalTraceDecision(event.currentPrincipal, session.decision),
+ initiatorPrincipal: applyPrincipalTraceDecision(event.initiatorPrincipal, session.decision),
parentLineage: event.parentLineage ?? session.parentLineage,
rootSessionId: event.rootSessionId,
sequence: event.sequence,
diff --git a/packages/eve/src/tracing/agent-telemetry-contract.integration.test.ts b/packages/eve/src/tracing/agent-telemetry-contract.integration.test.ts
index 6c7f352cf..d32429af3 100644
--- a/packages/eve/src/tracing/agent-telemetry-contract.integration.test.ts
+++ b/packages/eve/src/tracing/agent-telemetry-contract.integration.test.ts
@@ -9,8 +9,10 @@ import { SpanStatusCode } from "#compiled/@opentelemetry/api/index.js";
import { JsonTraceSerializer } from "#compiled/@opentelemetry/otlp-transformer/index.js";
import { ContextContainer, contextStorage } from "#context/container.js";
import {
+ AuthKey,
ChannelInstrumentationKey,
ConversationIdKey,
+ InitiatorAuthKey,
ParentSessionKey,
ParentTraceContextKey,
SessionTraceSeedKey,
@@ -98,6 +100,18 @@ function createRuntime() {
function contextFor(audience: "public" | "private") {
const ctx = new ContextContainer();
ctx.set(ChannelInstrumentationKey, { kind: "http", metadata: { audience } });
+ ctx.set(AuthKey, {
+ principalId: "current-user",
+ principalType: "service",
+ authenticator: "api-key",
+ attributes: { secret: "auth-only-secret" },
+ });
+ ctx.set(InitiatorAuthKey, {
+ principalId: "initiator-user",
+ principalType: "user",
+ authenticator: "oidc",
+ attributes: { secret: "auth-only-secret" },
+ });
return ctx;
}
@@ -512,6 +526,17 @@ describe("exported agent telemetry contract", () => {
.sort(),
).toEqual(["invoke_agent child", "invoke_agent parent"]);
expect(parsed.filter(isAgentTurnSpan)).toHaveLength(2);
+ for (const activation of parsed.filter(isAgentTurnSpan)) {
+ expect(activation.attributes["agent.principal.current.type"]).toBe("service");
+ expect(activation.attributes["agent.principal.initiator.type"]).toBe("user");
+ expect(activation.attributes["agent.principal.current.id"]).toBe(
+ audience === "public" ? "current-user" : undefined,
+ );
+ expect(activation.attributes["agent.principal.initiator.id"]).toBe(
+ audience === "public" ? "initiator-user" : undefined,
+ );
+ }
+ expect(new TextDecoder().decode(bytes)).not.toContain("auth-only-secret");
const caller = parsed.find((span) => span.attributes["agent.invocation.role"] === "caller")!;
const activation = parsed.find(
(span) => span.name === "invoke_agent child" && isAgentTurnSpan(span),
@@ -571,4 +596,141 @@ describe("exported agent telemetry contract", () => {
await runtime.shutdown();
},
);
+
+ it("exports new current principals but the same initiator on resumed activations", async () => {
+ const runtime = createRuntime();
+ const ctx = contextFor("public");
+ const hooks = runtime.hooks.forTrace!({ agentName: "parent", audience: "public" });
+ const binding = bindInstrumentationRuntime(runtime, ctx, {
+ agentName: "parent",
+ rootSessionId: "parent",
+ sessionId: "parent",
+ })!;
+ await contextStorage.run(ctx, async () => {
+ for (const [sequence, principalId] of ["first", "second"].entries()) {
+ ctx.set(AuthKey, {
+ principalId,
+ principalType: "user",
+ authenticator: "api-key",
+ attributes: {},
+ });
+ const turnId = `turn_${sequence}`;
+ await binding.preparePreamble({ sequence, sessionStarted: sequence > 0, turnId });
+ await hooks.publish({
+ idempotencyKey: turnIdempotencyKey("parent", turnId),
+ sessionId: "parent",
+ turnId,
+ type: "turn.completed",
+ });
+ await hooks.publish({
+ idempotencyKey: sessionIdempotencyKey("parent"),
+ sessionId: "parent",
+ turnId,
+ type: "session.waiting",
+ });
+ }
+ });
+ await runtime.forceFlush();
+ const spans = runtime.exporter.getFinishedSpans();
+ expect(spans.map((span) => span.attributes["agent.principal.current.id"])).toEqual([
+ "first",
+ "second",
+ ]);
+ expect(spans.map((span) => span.attributes["agent.principal.initiator.id"])).toEqual([
+ "initiator-user",
+ "initiator-user",
+ ]);
+ expect(new Set(spans.map((span) => span.spanContext().traceId)).size).toBe(2);
+ await runtime.shutdown();
+ });
+
+ it.each([
+ ["private", false, false],
+ ["private", true, true],
+ ["public", false, true],
+ ["public", true, false],
+ ["public", true, true],
+ ] as const)(
+ "bounds public-channel principal IDs by origin %s and input/output ceiling %s/%s",
+ async (originAudience, recordInputs, recordOutputs) => {
+ const runtime = createRuntime();
+ const hooks = runtime.hooks.forTrace!({ agentName: "child", audience: "public" });
+ const registered = vi
+ .spyOn(instrumentation, "getInstrumentationRuntime")
+ .mockReturnValue(runtime);
+ let ctx = contextFor("public");
+ ctx.set(ParentTraceContextKey, {
+ forwardedTracePolicy: {
+ ceiling: { recordInputs, recordOutputs },
+ originAudience,
+ },
+ spanId: "c".repeat(16),
+ traceFlags: 1,
+ traceId: "d".repeat(32),
+ });
+ const includesIds = originAudience === "public" && recordInputs && recordOutputs;
+ try {
+ instrumentation.initializeSessionInstrumentation({ agentName: "child", ctx });
+ expect(ctx.get(SessionTraceSeedKey)?.decision).toEqual({
+ action: "record",
+ recordInputs: originAudience === "public" && recordInputs,
+ recordOutputs: originAudience === "public" && recordOutputs,
+ });
+ for (let sequence = 0; sequence < 2; sequence++) {
+ const turnId = `turn_${sequence}`;
+ await contextStorage.run(ctx, async () => {
+ await bindInstrumentationRuntime(runtime, ctx, {
+ agentName: "child",
+ rootSessionId: "child",
+ sessionId: "child",
+ })!.preparePreamble({ sequence, sessionStarted: sequence > 0, turnId });
+ });
+ const serialized = serializeContext(ctx);
+ const traceState = JSON.stringify(serialized[AGENT_TRACE_CONTEXT_KEY]);
+ if (!includesIds) {
+ expect(traceState).not.toContain("current-user");
+ expect(traceState).not.toContain("initiator-user");
+ }
+ expect(traceState).not.toContain("auth-only-secret");
+ ctx = await deserializeContext(serialized);
+ await contextStorage.run(ctx, async () => {
+ await hooks.publish({
+ idempotencyKey: turnIdempotencyKey("child", turnId),
+ sessionId: "child",
+ turnId,
+ type: "turn.completed",
+ });
+ await hooks.publish({
+ idempotencyKey: sessionIdempotencyKey("child"),
+ sessionId: "child",
+ turnId,
+ type: "session.waiting",
+ });
+ });
+ }
+ await runtime.forceFlush();
+ const spans = runtime.exporter.getFinishedSpans();
+ expect(spans).toHaveLength(2);
+ for (const span of spans) {
+ expect(span.attributes["agent.principal.current.type"]).toBe("service");
+ expect(span.attributes["agent.principal.initiator.type"]).toBe("user");
+ expect(span.attributes["agent.principal.current.id"]).toBe(
+ includesIds ? "current-user" : undefined,
+ );
+ expect(span.attributes["agent.principal.initiator.id"]).toBe(
+ includesIds ? "initiator-user" : undefined,
+ );
+ }
+ const bytes = new TextDecoder().decode(JsonTraceSerializer.serializeRequest(spans)!);
+ expect(bytes).not.toContain("auth-only-secret");
+ if (!includesIds) {
+ expect(bytes).not.toContain("current-user");
+ expect(bytes).not.toContain("initiator-user");
+ }
+ } finally {
+ registered.mockRestore();
+ await runtime.shutdown();
+ }
+ },
+ );
});
diff --git a/packages/eve/src/tracing/agent-trace-context-codec.ts b/packages/eve/src/tracing/agent-trace-context-codec.ts
index 3aec9db5e..e1bb803f6 100644
--- a/packages/eve/src/tracing/agent-trace-context-codec.ts
+++ b/packages/eve/src/tracing/agent-trace-context-codec.ts
@@ -10,6 +10,8 @@ import type {
import { normalizeChannelAudience } from "#shared/channel-audience.js";
import { readInstrumentationDecision } from "#shared/instrumentation-decision.js";
import { boundedTraceError } from "#tracing/bounded-error.js";
+import { boundedPrincipalId } from "#tracing/telemetry-budget.js";
+import { isInstrumentationPrincipalType } from "#instrumentation/lifecycle.js";
export const AGENT_TRACE_CONTEXT_KEY = "eve.harness.agentTrace";
@@ -112,6 +114,8 @@ function deserializeTurn(value: unknown): AgentTurnTraceState | undefined {
caller: isSpanContext(value.caller) ? value.caller : undefined,
channelDelivery: deserializeTurnChannelDelivery(value.channelDelivery),
context: value.context,
+ currentPrincipal: deserializePrincipalSummary(value.currentPrincipal),
+ initiatorPrincipal: deserializePrincipalSummary(value.initiatorPrincipal),
modelUsage: deserializeModelUsage(value.modelUsage),
parentLineage: deserializeParentLineage(value.parentLineage),
rootSessionId: typeof value.rootSessionId === "string" ? value.rootSessionId : "",
@@ -143,6 +147,14 @@ function deserializeTurnChannelDelivery(value: unknown): AgentTurnTraceState["ch
};
}
+function deserializePrincipalSummary(
+ value: unknown,
+): AgentTurnTraceState["currentPrincipal"] | undefined {
+ if (!isRecord(value) || !isInstrumentationPrincipalType(value.type)) return undefined;
+ const id = value.type === "none" ? undefined : boundedPrincipalId(value.id);
+ return id === undefined ? { type: value.type } : { id, type: value.type };
+}
+
function deserializeAction(value: unknown): AgentActionTraceState | undefined {
if (
!isRecord(value) ||
diff --git a/packages/eve/src/tracing/agent-trace-context-store.test.ts b/packages/eve/src/tracing/agent-trace-context-store.test.ts
index 356543f59..8e0c083aa 100644
--- a/packages/eve/src/tracing/agent-trace-context-store.test.ts
+++ b/packages/eve/src/tracing/agent-trace-context-store.test.ts
@@ -3,6 +3,8 @@ import { describe, expect, it } from "vitest";
import { ContextContainer, contextStorage } from "#context/container.js";
import { SessionTraceSeedKey } from "#context/keys.js";
import { deserializeContext, serializeContext } from "#context/serialize.js";
+import { INSTRUMENTATION_PRINCIPAL_TYPES } from "#instrumentation/lifecycle.js";
+import { deserializeAgentTraceContextState } from "#tracing/agent-trace-context-codec.js";
import {
ContextAgentTraceStateStore,
preserveSerializedAgentTraceState,
@@ -31,6 +33,8 @@ describe("ContextAgentTraceStateStore", () => {
requestTraceContext: { ...spanContext("5", "6"), isRemote: true },
},
context: spanContext("1", "3"),
+ currentPrincipal: { id: "user-123", type: "user" },
+ initiatorPrincipal: { type: "none" },
modelUsage: { inputTokens: 12, outputTokens: 4 },
caller: { ...spanContext("4", "2"), isRemote: true },
rootSessionId: "session-1",
@@ -56,11 +60,17 @@ describe("ContextAgentTraceStateStore", () => {
requestId: "request-1",
requestTraceContext: { ...spanContext("5", "6"), isRemote: true },
},
+ currentPrincipal: { id: "user-123", type: "user" },
+ initiatorPrincipal: { type: "none" },
modelUsage: { inputTokens: 12, outputTokens: 4 },
caller: { ...spanContext("4", "2"), isRemote: true },
startTimeMs: 1_700_000_000_000,
subagentName: "researcher",
});
+ expect(store.getTurn("session-1", "turn-1")?.initiatorPrincipal).toStrictEqual({
+ type: "none",
+ });
+ expect(JSON.stringify(store.getTurn("session-1", "turn-1"))).not.toContain("attributes");
const terminal = store.getTurn("session-1", "turn-1")?.terminal;
expect(terminal?.type).toBe("turn.failed");
expect(terminal?.type === "turn.failed" ? terminal.error : undefined).toMatchObject({
@@ -69,6 +79,33 @@ describe("ContextAgentTraceStateStore", () => {
});
});
+ it.each([
+ ...INSTRUMENTATION_PRINCIPAL_TYPES.map((type) => ({
+ input: { type, id: "user-123" },
+ expected: type === "none" ? { type } : { type, id: "user-123" },
+ })),
+ { input: { type: "unrecognized", id: "user-123" }, expected: undefined },
+ ...[undefined, null, 123, "", "x".repeat(1025), String.fromCodePoint(0x1f600).repeat(257)].map(
+ (id) => ({
+ input: { type: "user", id },
+ expected: { type: "user" },
+ }),
+ ),
+ ])("restores bounded principal summaries from $input", ({ input, expected }) => {
+ const state = deserializeAgentTraceContextState({
+ turns: {
+ turn: {
+ context: spanContext("1", "2"),
+ currentPrincipal: input,
+ initiatorPrincipal: input,
+ startTimeMs: 1,
+ },
+ },
+ });
+ expect(state.turns.turn?.currentPrincipal).toStrictEqual(expected);
+ expect(state.turns.turn?.initiatorPrincipal).toStrictEqual(expected);
+ });
+
it("removes terminal state", () => {
contextStorage.run(new ContextContainer(), () => {
const store = new ContextAgentTraceStateStore();
diff --git a/packages/eve/src/tracing/agent-trace-state.ts b/packages/eve/src/tracing/agent-trace-state.ts
index da53a8bcb..375ec0551 100644
--- a/packages/eve/src/tracing/agent-trace-state.ts
+++ b/packages/eve/src/tracing/agent-trace-state.ts
@@ -4,6 +4,7 @@ import type {
InstrumentationActionKind,
InstrumentationActionOutcome,
InstrumentationParentLineage,
+ InstrumentationPrincipalSummary,
InstrumentationTraceContext,
InstrumentationTurnFailedEvent,
InstrumentationTurnSettledEvent,
@@ -26,6 +27,8 @@ export interface AgentTurnTraceState {
readonly caller?: SpanContext;
readonly channelDelivery?: AgentTurnChannelDeliveryTraceState;
readonly context: SpanContext;
+ readonly currentPrincipal?: InstrumentationPrincipalSummary;
+ readonly initiatorPrincipal?: InstrumentationPrincipalSummary;
readonly parentLineage?: InstrumentationParentLineage;
readonly modelUsage?: { readonly inputTokens?: number; readonly outputTokens?: number };
readonly rootSessionId: string;
diff --git a/packages/eve/src/tracing/telemetry-budget.test.ts b/packages/eve/src/tracing/telemetry-budget.test.ts
index 9e4232b9b..0eb8de393 100644
--- a/packages/eve/src/tracing/telemetry-budget.test.ts
+++ b/packages/eve/src/tracing/telemetry-budget.test.ts
@@ -1,5 +1,21 @@
import { describe, expect, it } from "vitest";
-import { telemetryByteLength, truncateTelemetryText } from "#tracing/telemetry-budget.js";
+import {
+ boundedPrincipalId,
+ telemetryByteLength,
+ truncateTelemetryText,
+} from "#tracing/telemetry-budget.js";
+
+describe("boundedPrincipalId", () => {
+ it.each(["x".repeat(1024), String.fromCodePoint(0x1f600).repeat(256)])(
+ "preserves a principal ID at the UTF-8 byte limit",
+ (id) => expect(boundedPrincipalId(id)).toBe(id),
+ );
+
+ it.each([undefined, null, 123, "", "x".repeat(1025), String.fromCodePoint(0x1f600).repeat(257)])(
+ "omits malformed, empty, or oversized IDs",
+ (id) => expect(boundedPrincipalId(id)).toBeUndefined(),
+ );
+});
describe("trace text bounds", () => {
it("counts UTF-8 bytes without splitting characters", () => {
diff --git a/packages/eve/src/tracing/telemetry-budget.ts b/packages/eve/src/tracing/telemetry-budget.ts
index 9256c0005..378a636e3 100644
--- a/packages/eve/src/tracing/telemetry-budget.ts
+++ b/packages/eve/src/tracing/telemetry-budget.ts
@@ -1,3 +1,14 @@
+export const TELEMETRY_PRINCIPAL_ID_BYTES = 1024;
+
+export function boundedPrincipalId(value: unknown): string | undefined {
+ return typeof value === "string" &&
+ value.length > 0 &&
+ value.length <= TELEMETRY_PRINCIPAL_ID_BYTES &&
+ telemetryByteLength(value) <= TELEMETRY_PRINCIPAL_ID_BYTES
+ ? value
+ : undefined;
+}
+
const encoder = new TextEncoder();
const decoder = new TextDecoder();
const MARKER = "... [truncated]";