Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

fix(eve): propagate agent trace context and conversation identity (#2958)

Chad Hietala47bd3d727ea5
diff --git a/.changeset/stable-agent-conversation.md b/.changeset/stable-agent-conversation.md
new file mode 100644
index 000000000..dc151fc87
--- /dev/null
+++ b/.changeset/stable-agent-conversation.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Preserve one observability conversation ID across local and remote agent dispatch, accepting incoming correlation only on callback-marked remote session creation. Apply the live delivery's trace-content ceiling to the selected caller context, including fallback when its action span is unavailable.
diff --git a/docs/guides/remote-agents.md b/docs/guides/remote-agents.md
index 383c69338..559b86032 100644
--- a/docs/guides/remote-agents.md
+++ b/docs/guides/remote-agents.md
@@ -139,6 +139,12 @@ Identity forwarding does not make a persistent session private to one caller. Co
Forwarding is explicit on both sides. The receiver names which forwarders it trusts with `eveChannel({ trustedForwarders })` (see [Auth & route protection](./auth-and-route-protection#accepting-forwarded-identity-from-another-deployment)); a receiver that refuses the forwarder — or has no `trustedForwarders` at all — rejects with a 403 and the dispatch fails.
+Remote tracing uses ordinary `traceparent` propagation. Trace context is not an authorization grant: it cannot assert eve parent lineage, change `rootSessionId`, or remove the normal root-session token cap.
+
+eve also carries the original `gen_ai.conversation.id` in `eve.conversation.id` baggage so you can find related traces across local and remote agents. This observability identifier does not require principal forwarding or shared execution lineage; it grants no session access and does not change trace-content policy. Only session-create requests with a callback may supply this baggage; top-level requests ignore it and establish their own conversation ID. Callback metadata is caller-supplied correlation, not verified identity.
+
+eve replaces configured `traceparent` and conversation baggage only when it has a framework value to send. Incoming baggage has an 8 KiB limit; the audience and conversation readers share whitespace, percent-decoding, and duplicate-key validation. Conversation IDs are limited to 1 KiB and exclude control characters and line separators.
+
> ⚠️ **Upgrade both deployments before resuming persistent remote sessions.** A sender with continuation forwarding includes `forwardedPrincipal` on each authenticated follow-up. A receiver that supports forwarding only on session creation rejects that continuation with HTTP 400. eve does not retry without the field because that would run the follow-up as the transport service principal and silently change caller authority. The parent retains the child handle after this failure, so you can retry the same session after upgrading the receiver.
A 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.
diff --git a/docs/reference/cli.md b/docs/reference/cli.md
index 533575ecf..c8bc556ff 100644
--- a/docs/reference/cli.md
+++ b/docs/reference/cli.md
@@ -308,7 +308,7 @@ Reads the immutable OTLP/JSON segments under `.eve/traces/v1`, so `eve dev` need
Span rows carry inline metrics when the span recorded them — `↑input`/`↓output` token counts, gateway cost, and the tool name for `execute_tool` spans — and the header aggregates models, token totals, cost, and error count across the trace's step spans. `--verbose` expands each span under its tree row: status (with the error message on failures), timing, ids, every attribute (prompts, responses, and tool payloads as transcripts or pretty-printed JSON), and every span event with its offset from span start. `--json` prints the same records as JSON, one object per selected trace.
-A local subagent keeps its own session id but records into the parent trace. Its `invoke_agent` span is parented to the `agent.action` span that dispatched it, so the span tree carries the relationship without duplicate lineage attributes; `agent.subagent.name` remains on the child invocation as a standalone label. Either session id resolves to that trace. Remote agents propagate the parent trace context over `traceparent`.
+A local subagent keeps its own session id but records into the parent trace. Its `invoke_agent` span is parented to the dispatching action. The attributes `agent.root_run.id`, `agent.parent_run.id`, and `agent.parent_call.id` identify the root session, immediate parent session, and dispatch call; `agent.subagent.name` labels the child invocation. Either session id resolves to that trace. Remote agents propagate caller trace context over `traceparent` without sharing execution lineage.
A durable session keeps one persisted trace context across turns and worker resumptions. Independently replayed attempts can still produce another trace; passing the session id shows every trace it produced, oldest first.
diff --git a/packages/eve/src/channel/types.ts b/packages/eve/src/channel/types.ts
index 877bf9186..3f52f67c8 100644
--- a/packages/eve/src/channel/types.ts
+++ b/packages/eve/src/channel/types.ts
@@ -522,6 +522,8 @@ export interface RunInput {
readonly outputSchema?: JsonObject;
};
readonly mode: RunMode;
+ /** Observability correlation only; never grants delegated-session privileges. */
+ readonly conversationId?: string;
readonly parent?: SessionParent;
/**
* Dispatching parent's open trace window. Handed down rather than looked up
diff --git a/packages/eve/src/context/keys.ts b/packages/eve/src/context/keys.ts
index f199bd723..81c9d986d 100644
--- a/packages/eve/src/context/keys.ts
+++ b/packages/eve/src/context/keys.ts
@@ -75,6 +75,7 @@ export interface Session {
export const AuthKey = new ContextKey<SessionAuthContext | null>("eve.auth");
export const InitiatorAuthKey = new ContextKey<SessionAuthContext | null>("eve.initiatorAuth");
export const SessionIdKey = new ContextKey<string>("eve.sessionId");
+export const ConversationIdKey = new ContextKey<string>("eve.conversationId");
export const SessionInboxKey = new ContextKey<SessionInboxAddress>(SESSION_INBOX_CONTEXT_KEY);
export const ContinuationTokenKey = new ContextKey<string>("eve.continuationToken");
export const ChannelRequestIdKey = new ContextKey<string>("eve.channelRequestId");
diff --git a/packages/eve/src/eve-channel/index.ts b/packages/eve/src/eve-channel/index.ts
index 5b3f0f1c5..d475d3f09 100644
--- a/packages/eve/src/eve-channel/index.ts
+++ b/packages/eve/src/eve-channel/index.ts
@@ -50,6 +50,7 @@ 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 { readConversationBaggage } from "#tracing/conversation-context.js";
import {
FAIL_CLOSED_FORWARDED_TRACE_ASSERTION,
formatTraceContentCeiling,
@@ -150,8 +151,6 @@ export function eveChannel(input: EveChannelInput): EveChannel {
const body = parseCreateBody(payload);
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 parsedParentTraceContext =
body.callback === undefined
? undefined
@@ -263,6 +262,10 @@ export function eveChannel(input: EveChannelInput): EveChannel {
body.context,
),
mode: body.mode ?? "conversation",
+ conversationId:
+ body.callback === undefined
+ ? undefined
+ : readConversationBaggage(req.headers.get("baggage")),
parentTraceContext,
title: messageResult.title,
});
diff --git a/packages/eve/src/execution/coordination-dispatch-shared.ts b/packages/eve/src/execution/coordination-dispatch-shared.ts
index 296f37215..8b5c83cc1 100644
--- a/packages/eve/src/execution/coordination-dispatch-shared.ts
+++ b/packages/eve/src/execution/coordination-dispatch-shared.ts
@@ -45,7 +45,6 @@ import {
} from "#execution/durable-session-store.js";
import { hydrateDurableSession } from "#execution/session.js";
import { buildSubagentRunInput } from "#subagents/tool.js";
-import { readSessionTraceContext } from "#tracing/agent-trace-context-store.js";
import { resolveEffectiveAgentRuntime } from "#execution/effective-agent-config.js";
import { isTaskControlAction } from "#execution/tasks/parent/dispatch.js";
import type { WorkflowToolRunOwner } from "#execution/tools/workflow/messages.js";
@@ -89,7 +88,6 @@ export interface PreparedCoordinationDispatch<PlanEntry = DispatchPlanEntry> {
readonly localDevRequest?: LocalDevRequestProvenance;
/** Lineage of the session running this dispatch, when it is itself a delegated child. */
readonly parentSession: SessionParent | undefined;
- readonly parentTraceContext: Parameters<typeof buildSubagentRunInput>[0]["parentTraceContext"];
readonly activityObserver?: ActivityObserverConfig & {
readonly workIdentity: ActivityWorkIdentityV1;
};
@@ -226,7 +224,6 @@ export async function prepareActionDispatch<PlanEntry>(input: {
initiatorAuth: ctx.get(InitiatorAuthKey) ?? null,
localDevRequest: ctx.get(LocalDevRequestKey),
parentSession: ctx.get(ParentSessionKey),
- parentTraceContext: readSessionTraceContext(input.serializedContext, session.sessionId),
plan,
activityObserver: resolvePreparedActivity(
ctx.get(ActivityObserverKey),
diff --git a/packages/eve/src/execution/multi-agent-callback-routing.scenario.test.ts b/packages/eve/src/execution/multi-agent-callback-routing.scenario.test.ts
index 179b82df2..62b89249a 100644
--- a/packages/eve/src/execution/multi-agent-callback-routing.scenario.test.ts
+++ b/packages/eve/src/execution/multi-agent-callback-routing.scenario.test.ts
@@ -289,7 +289,7 @@ describe("multi-agent callback routing", () => {
remoteAgentName: "research",
},
callbackBaseUrl: resolveWorkflowCallbackBaseUrl(deploymentOrigin),
- callbackToken,
+ parent: { continuationToken: callbackToken },
remote: {
description: "remote research agent",
kind: "remote",
diff --git a/packages/eve/src/execution/runtime-context.ts b/packages/eve/src/execution/runtime-context.ts
index d45c0e37a..5db3bf0b7 100644
--- a/packages/eve/src/execution/runtime-context.ts
+++ b/packages/eve/src/execution/runtime-context.ts
@@ -8,6 +8,7 @@ import {
ChannelDeliveryKey,
ChannelRequestIdKey,
ContinuationTokenKey,
+ ConversationIdKey,
DynamicSubagentAgentConfigKey,
InitiatorAuthKey,
ModeKey,
@@ -19,6 +20,7 @@ import {
} from "#context/keys.js";
import { BundleKey, type CompiledBundle } from "#runtime/sessions/runtime-context-keys.js";
import type { DynamicSubagentAgentConfig } from "#runtime/subagents/dynamic-agent-config.js";
+import { readConversationId } from "#tracing/conversation-context.js";
/**
* Builds the bootstrap {@link ContextContainer} for one run.
@@ -31,6 +33,8 @@ export function buildRunContext(input: {
const { bundle, run } = input;
const ctx = new ContextContainer();
const auth: SessionAuthContext | null = run.auth;
+ const conversationId = readConversationId(run.conversationId);
+ if (conversationId !== undefined) ctx.set(ConversationIdKey, conversationId);
ctx.set(BundleKey, bundle);
setChannelContext(ctx, run.adapter, { channelName: run.channelName });
diff --git a/packages/eve/src/execution/tools/subagent/invoke-step.ts b/packages/eve/src/execution/tools/subagent/invoke-step.ts
index 34063aa87..2deec3cbf 100644
--- a/packages/eve/src/execution/tools/subagent/invoke-step.ts
+++ b/packages/eve/src/execution/tools/subagent/invoke-step.ts
@@ -72,6 +72,7 @@ export type TaskAgentInvocationDispatchResult =
export async function dispatchAgentInvocation(input: {
readonly callbackBaseUrl: string;
readonly emit?: HandleEventFn;
+ readonly instrumentationCallId?: string;
readonly replyTo: string;
readonly request: AgentInvocationRequest;
readonly serializedContext: Record<string, unknown>;
@@ -217,11 +218,11 @@ export async function dispatchAgentInvocation(input: {
channelMetadata: prepared.channelMetadata,
currentSession: session,
fanoutSize: prepared.fanoutSize,
+ instrumentationCallId: input.instrumentationCallId,
initiatorAuth: prepared.initiatorAuth,
localDevRequest: prepared.localDevRequest,
parentContinuationToken: input.replyTo,
activityObserver: prepared.activityObserver,
- parentTraceContext: prepared.parentTraceContext,
sandboxSessionId: prepared.sandboxSessionId,
serializedContext: prepared.serializedContext,
session,
diff --git a/packages/eve/src/execution/tools/subagent/start.test.ts b/packages/eve/src/execution/tools/subagent/start.test.ts
new file mode 100644
index 000000000..e3a23b4d7
--- /dev/null
+++ b/packages/eve/src/execution/tools/subagent/start.test.ts
@@ -0,0 +1,113 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { startSubagent } from "#execution/tools/subagent/start.js";
+import { startLocalSubagent } from "#subagents/start-local.js";
+import { startRemoteSubagent } from "#subagents/start-remote.js";
+import {
+ readActionTraceContext,
+ readSessionTraceContext,
+} from "#tracing/agent-trace-context-store.js";
+
+vi.mock("#subagents/start-local.js", () => ({ startLocalSubagent: vi.fn() }));
+vi.mock("#subagents/start-remote.js", () => ({ startRemoteSubagent: vi.fn() }));
+vi.mock("#tracing/agent-trace-context-store.js", () => ({
+ readActionTraceContext: vi.fn(),
+ readSessionTraceContext: vi.fn(),
+}));
+
+beforeEach(() => {
+ vi.resetAllMocks();
+ vi.mocked(startLocalSubagent).mockResolvedValue({ kind: "error" } as never);
+ vi.mocked(startRemoteSubagent).mockResolvedValue({ kind: "error" } as never);
+});
+
+describe.each(["local", "remote"] as const)("startSubagent (%s)", (kind) => {
+ it.each(["caller", "action", "session", "direct"] as const)(
+ "applies the live audience ceiling to the selected %s context",
+ async (source) => {
+ const caller = {
+ decision: { action: "record", recordInputs: true, recordOutputs: true } as const,
+ forwardedTracePolicy: {
+ originAudience: "public",
+ ceiling: { recordInputs: true, recordOutputs: true },
+ } as const,
+ spanId: "2".repeat(16),
+ traceFlags: 1,
+ traceId: "1".repeat(32),
+ };
+ const childAction = {
+ ...caller,
+ spanId: "4".repeat(16),
+ traceFlags: 1,
+ traceId: "3".repeat(32),
+ };
+ const session = { ...caller, spanId: "6".repeat(16), traceId: "5".repeat(32) };
+ vi.mocked(readActionTraceContext).mockImplementation(
+ (_serializedContext, _sessionId, _turnId, callId) =>
+ callId === "workflow-call"
+ ? source === "caller"
+ ? caller
+ : undefined
+ : source === "session"
+ ? undefined
+ : childAction,
+ );
+ vi.mocked(readSessionTraceContext).mockReturnValue(session);
+ const selected = source === "caller" ? caller : source === "session" ? session : childAction;
+
+ await startSubagent({
+ auth: null,
+ batchEvent: { sequence: 1, turnId: "turn-1" },
+ bundle: {} as never,
+ callbackBaseUrl: "https://parent.example",
+ capabilities: undefined,
+ channelMetadata: { kind: "http", metadata: { audience: "private" } },
+ currentSession: {} as never,
+ fanoutSize: 1,
+ instrumentationCallId: source === "direct" ? undefined : "workflow-call",
+ initiatorAuth: null,
+ parentContinuationToken: "parent-token",
+ sandboxSessionId: "parent-session",
+ serializedContext: {},
+ session: { rootSessionId: "root-session", sessionId: "parent-session" } as never,
+ target:
+ kind === "local"
+ ? {
+ action: { callId: "child-action" } as never,
+ kind,
+ source: { type: "runtime" },
+ }
+ : { action: { callId: "child-action" } as never, kind },
+ });
+
+ expect(readActionTraceContext).toHaveBeenCalledWith(
+ {},
+ "parent-session",
+ "turn-1",
+ source === "direct" ? "child-action" : "workflow-call",
+ );
+ const start = kind === "local" ? startLocalSubagent : startRemoteSubagent;
+ const other = kind === "local" ? startRemoteSubagent : startLocalSubagent;
+ expect(start).toHaveBeenCalledWith(
+ expect.objectContaining({
+ parent: {
+ conversationId: "root-session",
+ continuationToken: "parent-token",
+ lineage: {
+ callId: "child-action",
+ rootSessionId: "root-session",
+ sessionId: "parent-session",
+ turn: { id: "turn-1", sequence: 1 },
+ },
+ traceContext: {
+ ...selected,
+ decision: { action: "record", recordInputs: false, recordOutputs: false },
+ },
+ },
+ }),
+ );
+ expect(selected.decision.recordInputs).toBe(true);
+ expect(other).not.toHaveBeenCalled();
+ },
+ );
+});
diff --git a/packages/eve/src/execution/tools/subagent/start.ts b/packages/eve/src/execution/tools/subagent/start.ts
index 02d7dd46e..32466064d 100644
--- a/packages/eve/src/execution/tools/subagent/start.ts
+++ b/packages/eve/src/execution/tools/subagent/start.ts
@@ -1,5 +1,5 @@
import type { ActivityObserverConfig } from "#channel/types.js";
-import type { LocalDevRequestProvenance } from "#context/keys.js";
+import { ConversationIdKey, type LocalDevRequestProvenance } from "#context/keys.js";
import type { ActivityWorkIdentityV1 } from "#protocol/activity.js";
import type { DynamicSubagentAgentConfig } from "#runtime/subagents/dynamic-agent-config.js";
import type { DynamicRemoteAgentConfig } from "#runtime/subagents/dynamic-remote-agent-config.js";
@@ -17,7 +17,12 @@ import type { DispatchOutcome, RuntimeSession } from "#subagents/handle-dispatch
import { startLocalSubagent } from "#subagents/start-local.js";
import { startRemoteSubagent } from "#subagents/start-remote.js";
import { buildSubagentRunInput, type SubagentInputSource } from "#subagents/tool.js";
-import { readActionTraceContext } from "#tracing/agent-trace-context-store.js";
+import {
+ readActionTraceContext,
+ readSessionTraceContext,
+} from "#tracing/agent-trace-context-store.js";
+import type { SubagentParentContext } from "#subagents/invocation.js";
+import { readConversationId } from "#tracing/conversation-context.js";
export type SubagentStartTarget =
| {
@@ -42,10 +47,10 @@ export async function startSubagent(input: {
readonly channelMetadata: Parameters<typeof buildSubagentRunInput>[0]["channelMetadata"];
readonly currentSession: RuntimeSession;
readonly fanoutSize: number;
+ readonly instrumentationCallId?: string;
readonly initiatorAuth: Parameters<typeof buildSubagentRunInput>[0]["initiatorAuth"];
readonly localDevRequest?: LocalDevRequestProvenance;
readonly parentContinuationToken: string | undefined;
- readonly parentTraceContext: Parameters<typeof buildSubagentRunInput>[0]["parentTraceContext"];
readonly activityObserver?: ActivityObserverConfig & {
readonly workIdentity: ActivityWorkIdentityV1;
};
@@ -55,13 +60,23 @@ export async function startSubagent(input: {
readonly taskId?: string;
readonly target: SubagentStartTarget;
}): Promise<DispatchOutcome> {
+ const actionCallId = input.instrumentationCallId;
const storedParentTraceContext =
+ (actionCallId === undefined
+ ? undefined
+ : readActionTraceContext(
+ input.serializedContext,
+ input.session.sessionId,
+ input.batchEvent.turnId,
+ actionCallId,
+ )) ??
readActionTraceContext(
input.serializedContext,
input.session.sessionId,
input.batchEvent.turnId,
input.target.action.callId,
- ) ?? input.parentTraceContext;
+ ) ??
+ readSessionTraceContext(input.serializedContext, input.session.sessionId);
const forwardedTracePolicy = readForwardedTraceAssertion(
storedParentTraceContext?.forwardedTracePolicy,
);
@@ -77,13 +92,26 @@ export async function startSubagent(input: {
forwardedTracePolicy,
),
};
+ const parent: SubagentParentContext = {
+ conversationId:
+ readConversationId(input.serializedContext[ConversationIdKey.name]) ??
+ input.session.rootSessionId ??
+ input.session.sessionId,
+ lineage: {
+ callId: input.target.action.callId,
+ rootSessionId: input.session.rootSessionId ?? input.session.sessionId,
+ sessionId: input.session.sessionId,
+ turn: { id: input.batchEvent.turnId, sequence: input.batchEvent.sequence },
+ },
+ continuationToken: input.parentContinuationToken,
+ traceContext: parentTraceContext,
+ };
switch (input.target.kind) {
case "local":
return startLocalSubagent({
action: input.target.action,
auth: input.auth,
- batchEvent: input.batchEvent,
bundle: input.bundle,
capabilities: input.capabilities,
channelMetadata: input.channelMetadata,
@@ -92,8 +120,7 @@ export async function startSubagent(input: {
fanoutSize: input.fanoutSize,
initiatorAuth: input.initiatorAuth,
localDevRequest: input.localDevRequest,
- parentContinuationToken: input.parentContinuationToken,
- parentTraceContext,
+ parent,
activityObserver: input.activityObserver,
sandboxSessionId: input.sandboxSessionId,
session: input.session,
@@ -104,15 +131,13 @@ export async function startSubagent(input: {
return startRemoteSubagent({
action: input.target.action,
auth: input.auth,
- batchEvent: input.batchEvent,
bundle: input.bundle,
callbackBaseUrl: input.callbackBaseUrl,
originAudience: forwardedTracePolicy?.originAudience ?? liveAudience,
currentSession: input.currentSession,
dynamicRemoteAgent: input.target.dynamicRemoteAgent,
initiatorAuth: input.initiatorAuth,
- parentContinuationToken: input.parentContinuationToken,
- parentTraceContext,
+ parent,
activityObserver: input.activityObserver,
session: input.session,
taskId: input.taskId,
diff --git a/packages/eve/src/execution/tools/subagent/task-agent-requests.ts b/packages/eve/src/execution/tools/subagent/task-agent-requests.ts
index 61fb43651..31134214b 100644
--- a/packages/eve/src/execution/tools/subagent/task-agent-requests.ts
+++ b/packages/eve/src/execution/tools/subagent/task-agent-requests.ts
@@ -9,6 +9,7 @@ import type { TaskAgentRequestDelivery } from "#tasks/types.js";
export interface AgentRequestDelivery {
readonly accumulateUsage?: boolean;
+ readonly actionCallId?: string;
readonly ownerId: string;
readonly replyTo: TaskAgentRequestDelivery["replyTo"];
readonly request: TaskAgentRequestDelivery["request"];
@@ -49,6 +50,7 @@ export async function applyTaskAgentRequest(
}
case "agent-invoke": {
const dispatched = await dispatchTaskAgentInvocationStep({
+ instrumentationCallId: delivery.actionCallId,
ownerId: delivery.ownerId,
replyTo: delivery.replyTo,
request,
diff --git a/packages/eve/src/execution/turn-workflow-tool-run.ts b/packages/eve/src/execution/turn-workflow-tool-run.ts
index 84fe44823..2776eaf88 100644
--- a/packages/eve/src/execution/turn-workflow-tool-run.ts
+++ b/packages/eve/src/execution/turn-workflow-tool-run.ts
@@ -154,6 +154,7 @@ async function handleWorkflowToolRunRequest(
await applyTaskAgentRequest(
{
accumulateUsage: message.from.resultKind !== "subagent",
+ actionCallId: message.from.resultKind === "subagent" ? message.from.callId : undefined,
ownerId: message.from.runId,
replyTo: message.replyTo,
request: message.request,
diff --git a/packages/eve/src/execution/workflow-runtime.ts b/packages/eve/src/execution/workflow-runtime.ts
index b63f1f849..d9a93f719 100644
--- a/packages/eve/src/execution/workflow-runtime.ts
+++ b/packages/eve/src/execution/workflow-runtime.ts
@@ -152,7 +152,6 @@ export function createWorkflowRuntime(config: {
initializeSessionInstrumentation({
agentName: effectiveAgent.turnAgent.id,
ctx,
- parentTraceContext: input.parentTraceContext,
});
const sessionTimeoutMs = effectiveAgent.limits?.sessionTimeoutMs;
// Retention is always the authored value: `experimental` cannot be
diff --git a/packages/eve/src/instrumentation/lifecycle.ts b/packages/eve/src/instrumentation/lifecycle.ts
index 3e1de8b9f..ca9348196 100644
--- a/packages/eve/src/instrumentation/lifecycle.ts
+++ b/packages/eve/src/instrumentation/lifecycle.ts
@@ -279,6 +279,7 @@ export interface InstrumentationSessionStartedEvent {
readonly channelType?: string;
readonly channelAudience?: ChannelAudience;
readonly idempotencyKey: string;
+ readonly parentLineage?: InstrumentationParentLineage;
readonly parentTraceContext?: InstrumentationTraceContext;
readonly rootSessionId: string;
readonly sessionId: string;
diff --git a/packages/eve/src/instrumentation/native-events.ts b/packages/eve/src/instrumentation/native-events.ts
index 99a13369a..b8a8f96d8 100644
--- a/packages/eve/src/instrumentation/native-events.ts
+++ b/packages/eve/src/instrumentation/native-events.ts
@@ -302,6 +302,7 @@ function toLifecycleEvent(
channelAudience: input.channelAudience,
channelKind: input.channelKind,
idempotencyKey: sessionIdempotencyKey(input.sessionId),
+ parentLineage: input.parentLineage,
parentTraceContext: input.parentTraceContext,
rootSessionId: input.rootSessionId ?? input.sessionId,
sessionId: input.sessionId,
diff --git a/packages/eve/src/instrumentation/prepare-trace-context.test.ts b/packages/eve/src/instrumentation/prepare-trace-context.test.ts
index f29c00557..c351e0541 100644
--- a/packages/eve/src/instrumentation/prepare-trace-context.test.ts
+++ b/packages/eve/src/instrumentation/prepare-trace-context.test.ts
@@ -1,10 +1,53 @@
-import { describe, expect, it } from "vitest";
+import { describe, expect, it, vi } from "vitest";
import { ContextContainer, contextStorage } from "#context/container.js";
import { SessionTraceSeedKey } from "#context/keys.js";
import { prepareTurnTraceContext } from "#instrumentation/prepare-trace-context.js";
describe("prepareTurnTraceContext", () => {
+ it("reuses session parent metadata without copying the seed onto a turn event", async () => {
+ const seed = { spanId: "2".repeat(16), traceFlags: 1, traceId: "1".repeat(32) };
+ const parentLineage = {
+ callId: "call-1",
+ sessionId: "parent-session",
+ turnId: "parent-turn",
+ };
+ const prepareSessionTrace = vi.fn(async (_event: unknown) => seed);
+ const prepareTurnTrace = vi.fn(async (_event: unknown) => seed);
+
+ await prepareTurnTraceContext({
+ instrumentation: { prepareSessionTrace, prepareTurnTrace },
+ session: {
+ agentName: "child",
+ channelAudience: "private",
+ parentLineage,
+ parentTraceContext: seed,
+ rootSessionId: "root-session",
+ sessionId: "child-session",
+ traceSeed: seed,
+ },
+ sequence: 0,
+ sessionStarted: false,
+ turnId: "turn-1",
+ });
+
+ const identity = {
+ agentName: "child",
+ parentLineage,
+ parentTraceContext: seed,
+ rootSessionId: "root-session",
+ sessionId: "child-session",
+ };
+ expect(prepareSessionTrace).toHaveBeenCalledWith(
+ expect.objectContaining({ ...identity, traceSeed: seed, type: "session.started" }),
+ );
+ expect(prepareTurnTrace).toHaveBeenCalledWith(
+ expect.objectContaining({ ...identity, type: "turn.started", turnId: "turn-1" }),
+ );
+ expect(prepareTurnTrace.mock.calls[0]?.[0]).not.toHaveProperty("traceSeed");
+ expect(prepareTurnTrace.mock.calls[0]?.[0]).not.toHaveProperty("channelAudience");
+ });
+
it("backfills a persisted trace decision for pre-seed workflow contexts", async () => {
const context = new ContextContainer();
const seed = {
@@ -19,9 +62,8 @@ describe("prepareTurnTraceContext", () => {
instrumentation: {
prepareSessionTrace: async () => seed,
},
- rootSessionId: "session-1",
+ session: { rootSessionId: "session-1", sessionId: "session-1" },
sequence: 0,
- sessionId: "session-1",
sessionStarted: false,
turnId: "turn-1",
}),
diff --git a/packages/eve/src/instrumentation/prepare-trace-context.ts b/packages/eve/src/instrumentation/prepare-trace-context.ts
index cf9239701..ecd8ef8a0 100644
--- a/packages/eve/src/instrumentation/prepare-trace-context.ts
+++ b/packages/eve/src/instrumentation/prepare-trace-context.ts
@@ -2,22 +2,17 @@ import { createLogger, formatError } from "#internal/logging.js";
import { contextStorage } from "#context/container.js";
import type { RuntimeTraceContext } from "#protocol/message.js";
import type {
- InstrumentationParentLineage,
InstrumentationSessionStartedEvent,
InstrumentationTraceSeed,
InstrumentationTurnStartedEvent,
} from "#instrumentation/lifecycle.js";
import { sessionIdempotencyKey, turnIdempotencyKey } from "#instrumentation/lifecycle.js";
-import type { ChannelAudience } from "#shared/channel-audience.js";
-import { SessionTraceSeedKey, type SessionTraceSeed } from "#context/keys.js";
+import { SessionTraceSeedKey } from "#context/keys.js";
const log = createLogger("harness.prepare-trace-context");
/** Prepares native session/turn tracing before their durable stream events. */
export interface PrepareTurnTraceContextInput {
- readonly agentName?: string;
- readonly channelAudience?: ChannelAudience;
- readonly channelType?: string;
readonly instrumentation?: {
readonly prepareSessionTrace?: (
event: InstrumentationSessionStartedEvent,
@@ -26,14 +21,10 @@ export interface PrepareTurnTraceContextInput {
event: InstrumentationTurnStartedEvent,
) => Promise<InstrumentationTraceSeed>;
};
- readonly parentLineage?: InstrumentationParentLineage;
- readonly parentTraceContext?: InstrumentationTraceSeed;
- readonly rootSessionId: string;
+ readonly session: Omit<InstrumentationSessionStartedEvent, "idempotencyKey" | "type">;
readonly sequence: number;
- readonly sessionId: string;
readonly sessionStarted: boolean;
readonly traceContext?: RuntimeTraceContext;
- readonly traceSeed?: SessionTraceSeed;
readonly turnId: string;
}
@@ -41,18 +32,17 @@ export async function prepareTurnTraceContext(
input: PrepareTurnTraceContextInput,
): Promise<RuntimeTraceContext | undefined> {
let prepared: InstrumentationTraceSeed | undefined;
+ const { channelAudience, channelKind, channelType, traceSeed, ...session } = input.session;
if (!input.sessionStarted && input.instrumentation?.prepareSessionTrace !== undefined) {
try {
prepared = await input.instrumentation.prepareSessionTrace({
- agentName: input.agentName,
- channelAudience: input.channelAudience,
- channelType: input.channelType,
- idempotencyKey: sessionIdempotencyKey(input.sessionId),
- parentTraceContext: input.parentTraceContext,
- rootSessionId: input.rootSessionId,
- sessionId: input.sessionId,
- traceSeed: input.traceSeed,
+ ...session,
+ channelAudience,
+ channelKind,
+ channelType,
+ idempotencyKey: sessionIdempotencyKey(session.sessionId),
+ traceSeed,
type: "session.started",
});
} catch (error) {
@@ -63,13 +53,9 @@ export async function prepareTurnTraceContext(
if (input.instrumentation?.prepareTurnTrace !== undefined) {
try {
prepared = await input.instrumentation.prepareTurnTrace({
- agentName: input.agentName,
- idempotencyKey: turnIdempotencyKey(input.sessionId, input.turnId),
- parentLineage: input.parentLineage,
- parentTraceContext: input.parentTraceContext,
- rootSessionId: input.rootSessionId,
+ ...session,
+ idempotencyKey: turnIdempotencyKey(session.sessionId, input.turnId),
sequence: input.sequence,
- sessionId: input.sessionId,
turnId: input.turnId,
type: "turn.started",
});
@@ -78,7 +64,7 @@ export async function prepareTurnTraceContext(
}
}
- if (input.traceSeed === undefined && prepared?.decision !== undefined) {
+ if (traceSeed === undefined && prepared?.decision !== undefined) {
contextStorage.getStore()?.set(SessionTraceSeedKey, prepared);
}
diff --git a/packages/eve/src/instrumentation/runtime.test.ts b/packages/eve/src/instrumentation/runtime.test.ts
index 563b50e3b..3c1b78da2 100644
--- a/packages/eve/src/instrumentation/runtime.test.ts
+++ b/packages/eve/src/instrumentation/runtime.test.ts
@@ -3,8 +3,10 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
import { ContextContainer, contextStorage } from "#context/container.js";
import {
ChannelInstrumentationKey,
+ ConversationIdKey,
OtelTraceEnabledKey,
ParentTraceContextKey,
+ ParentSessionKey,
SessionTraceSeedKey,
} from "#context/keys.js";
import { setChannelContext } from "#execution/channel-context.js";
@@ -87,19 +89,16 @@ function initializeRemoteSession(
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),
+ ctx.set(ParentTraceContextKey, {
+ forwardedTracePolicy: {
+ ceiling: input.ceiling ?? { recordInputs: true, recordOutputs: true },
+ originAudience,
},
+ spanId: "c".repeat(16),
+ traceFlags: 1,
+ traceId: "d".repeat(32),
});
+ initializeSessionInstrumentation({ agentName: "remote-agent", ctx });
return ctx;
}
@@ -225,19 +224,16 @@ describe("initializeSessionInstrumentation", () => {
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),
+ ctx.set(ParentTraceContextKey, {
+ forwardedTracePolicy: {
+ ceiling: { recordInputs: false, recordOutputs: true },
+ originAudience: "public",
},
+ spanId: "c".repeat(16),
+ traceFlags: 1,
+ traceId: "d".repeat(32),
});
+ initializeSessionInstrumentation({ agentName: "remote-agent", ctx });
const messageCount = await bindSessionInstrumentation({
agentName: "remote-agent",
@@ -322,7 +318,6 @@ describe("initializeSessionInstrumentation", () => {
initializeSessionInstrumentation({
agentName: "local-subagent",
ctx,
- parentTraceContext: ctx.get(ParentTraceContextKey),
});
expect(ctx.get(SessionTraceSeedKey)).toMatchObject({
@@ -335,9 +330,25 @@ describe("initializeSessionInstrumentation", () => {
describe("bindInstrumentationRuntime", () => {
it("returns no worker controls when no runtime is loaded", () => {
- expect(
- bindInstrumentationRuntime(undefined, new ContextContainer(), boundSession),
- ).toBeUndefined();
+ const ctx = new ContextContainer();
+ expect(bindInstrumentationRuntime(undefined, ctx, boundSession)).toBeUndefined();
+ expect(ctx.get(ConversationIdKey)).toBeUndefined();
+ });
+
+ it("uses the effective parent root to initialize correlation without replacing it", () => {
+ const ctx = createContext();
+ ctx.set(ParentSessionKey, {
+ callId: "call",
+ sessionId: "parent",
+ rootSessionId: "effective-root",
+ turn: { id: "turn", sequence: 0 },
+ });
+ const runtime = createRuntime({ capturesContent: true, publish: vi.fn() });
+ bindInstrumentationRuntime(runtime, ctx, boundSession);
+ expect(ctx.get(ConversationIdKey)).toBe("effective-root");
+ ctx.set(ConversationIdKey, "original-conversation");
+ bindInstrumentationRuntime(runtime, ctx, boundSession);
+ expect(ctx.get(ConversationIdKey)).toBe("original-conversation");
});
it("reads the channel audience when the step runs", async () => {
diff --git a/packages/eve/src/instrumentation/runtime.ts b/packages/eve/src/instrumentation/runtime.ts
index 24c753e8c..a432f0f7a 100644
--- a/packages/eve/src/instrumentation/runtime.ts
+++ b/packages/eve/src/instrumentation/runtime.ts
@@ -48,6 +48,7 @@ import type { SessionTraceSeed } from "#context/keys.js";
import { contextStorage, type ContextContainer } from "#context/container.js";
import {
ChannelInstrumentationKey,
+ ConversationIdKey,
OtelTraceEnabledKey,
ParentSessionKey,
ParentTraceContextKey,
@@ -69,12 +70,13 @@ import {
} from "#shared/instrumentation-decision.js";
import {
applyLiveDeliveryAudienceCeiling,
- type ForwardedTraceAssertion,
formatTraceContentCeiling,
+ type ForwardedTraceAssertion,
readForwardedTraceAssertion,
resolveForwardedTraceSeed,
traceContentCeilingToDecision,
} from "#shared/forwarded-trace-policy.js";
+import { readConversationId } from "#tracing/conversation-context.js";
const INSTRUMENTATION_RUNTIME_KEY = Symbol.for("eve.instrumentation-runtime");
const TURN_TRACE_STATE_KEY = "eve.harness.turnTrace";
@@ -106,18 +108,7 @@ export interface InstrumentationStepScope<TSession> {
readonly turnId: string;
}) => PreparedInstrumentationAttempt;
readonly preparePreamble: (
- input: Omit<
- PrepareTurnTraceContextInput,
- | "agentName"
- | "channelAudience"
- | "channelType"
- | "instrumentation"
- | "parentLineage"
- | "parentTraceContext"
- | "rootSessionId"
- | "sessionId"
- | "traceSeed"
- >,
+ input: Omit<PrepareTurnTraceContextInput, "instrumentation" | "session">,
) => Promise<RuntimeTraceContext | undefined>;
readonly publishInputResolutions: (input: {
readonly batch: ResolvedInputBatch;
@@ -207,6 +198,12 @@ export function bindInstrumentationRuntime(
boundSession: BoundInstrumentationSession,
): ExecutionInstrumentation | undefined {
if (runtime === undefined) return undefined;
+ if (readConversationId(ctx.get(ConversationIdKey)) === undefined) {
+ ctx.set(
+ ConversationIdKey,
+ ctx.get(ParentSessionKey)?.rootSessionId ?? boundSession.rootSessionId,
+ );
+ }
const baseHooks = runtime.hooks;
const readSessionContext = () => {
const context = contextStorage.getStore() ?? ctx;
@@ -257,15 +254,17 @@ export function bindInstrumentationRuntime(
const audience = normalizeChannelAudience(channel?.metadata.audience);
return prepareTurnTraceContext({
...input,
- agentName: boundSession.agentName,
- channelAudience: audience,
- channelType: channel?.channelType,
instrumentation: runtime,
- parentLineage: resolveParentLineage(sessionContext.parent, sessionContext.channel),
- parentTraceContext: sessionContext.parentTraceContext,
- rootSessionId: sessionContext.parent?.rootSessionId ?? boundSession.rootSessionId,
- sessionId: boundSession.sessionId,
- traceSeed: sessionContext.traceSeed,
+ session: {
+ agentName: boundSession.agentName,
+ channelAudience: audience,
+ channelType: channel?.channelType,
+ parentLineage: resolveParentLineage(sessionContext.parent, sessionContext.channel),
+ parentTraceContext: sessionContext.parentTraceContext,
+ rootSessionId: sessionContext.parent?.rootSessionId ?? boundSession.rootSessionId,
+ sessionId: boundSession.sessionId,
+ traceSeed: sessionContext.traceSeed,
+ },
});
};
const prepareExecution = (): SessionInstrumentation => {
@@ -524,12 +523,12 @@ export function bindSessionInstrumentation(input: {
export function initializeSessionInstrumentation(input: {
readonly agentName: string;
readonly ctx: ContextContainer;
- readonly parentTraceContext?: SessionTraceContext;
}): void {
const runtime = getInstrumentationRuntime();
const channel = input.ctx.get(ChannelInstrumentationKey);
+ const parentTraceContext = input.ctx.get(ParentTraceContextKey);
const forwardedTracePolicy = readForwardedTraceAssertion(
- input.parentTraceContext?.forwardedTracePolicy,
+ parentTraceContext?.forwardedTracePolicy,
);
const audience =
forwardedTracePolicy?.originAudience ?? normalizeChannelAudience(channel?.metadata.audience);
@@ -538,7 +537,7 @@ export function initializeSessionInstrumentation(input: {
audience,
channelType: channel?.channelType,
forwardedTracePolicy,
- parentTraceContext: input.parentTraceContext,
+ parentTraceContext,
runtime,
});
if (traceSeed !== undefined) {
@@ -553,10 +552,10 @@ export function initializeSessionInstrumentation(input: {
originAudience: forwardedTracePolicy.originAudience,
});
}
- if (forwardedTracePolicy !== undefined && input.parentTraceContext !== undefined) {
- const parentTraceContext = { ...input.parentTraceContext, ...traceSeed };
- delete parentTraceContext.forwardedTracePolicy;
- input.ctx.set(ParentTraceContextKey, parentTraceContext);
+ if (forwardedTracePolicy !== undefined && parentTraceContext !== undefined) {
+ const resolvedParent = { ...parentTraceContext, ...traceSeed };
+ delete resolvedParent.forwardedTracePolicy;
+ input.ctx.set(ParentTraceContextKey, resolvedParent);
}
}
input.ctx.set(OtelTraceEnabledKey, runtime?.prepareSessionTrace !== undefined);
@@ -570,6 +569,12 @@ function allocateSessionTraceSeed(input: {
readonly parentTraceContext?: SessionTraceContext;
readonly runtime: InstrumentationRuntime | undefined;
}): SessionTraceSeed | undefined {
+ const localDecision = () =>
+ resolveTracePolicy(input.runtime?.otelSettings?.tracePolicy, {
+ agentName: input.agentName,
+ audience: input.audience,
+ channelType: input.channelType,
+ });
if (input.parentTraceContext !== undefined) {
const forwardedCeiling = input.forwardedTracePolicy
? traceContentCeilingToDecision(input.forwardedTracePolicy.ceiling)
@@ -582,14 +587,7 @@ function allocateSessionTraceSeed(input: {
: (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,
- }),
- )
+ ? intersectInstrumentationDecisions(parentDecision, localDecision())
: parentDecision;
return {
decision,
@@ -602,13 +600,9 @@ function allocateSessionTraceSeed(input: {
traceId: input.parentTraceContext.traceId,
};
}
- if (input.runtime?.prepareSessionTrace === undefined) return undefined;
- if (input.runtime.idGenerator === undefined) return undefined;
- const decision = resolveTracePolicy(input.runtime.otelSettings?.tracePolicy, {
- agentName: input.agentName,
- audience: input.audience,
- channelType: input.channelType,
- });
+ if (input.runtime?.prepareSessionTrace === undefined || input.runtime.idGenerator === undefined)
+ return undefined;
+ const decision = localDecision();
const traceId = input.runtime.idGenerator.generateTraceId();
const sampled = decision.action === "record" && (input.runtime.samplesTrace?.(traceId) ?? true);
return {
diff --git a/packages/eve/src/protocol/baggage.test.ts b/packages/eve/src/protocol/baggage.test.ts
index 9e70bbe21..f9a037098 100644
--- a/packages/eve/src/protocol/baggage.test.ts
+++ b/packages/eve/src/protocol/baggage.test.ts
@@ -1,12 +1,41 @@
import { describe, expect, it } from "vitest";
-import { readForwardedAudienceBaggage, writeForwardedAudienceBaggage } from "#protocol/baggage.js";
+import {
+ readBaggageMember,
+ readForwardedAudienceBaggage,
+ writeForwardedAudienceBaggage,
+} from "#protocol/baggage.js";
const PUBLIC_OUTPUTS = {
ceiling: { recordInputs: false, recordOutputs: true },
originAudience: "public",
} as const;
+describe("baggage member parsing", () => {
+ it.each(["eve.audience", "eve.conversation.id"])("uses the same wire rules for %s", (key) => {
+ expect(readBaggageMember(`${key} = public%2Fone+two ; flag ; source=a%3Db`, key)).toEqual({
+ value: "public/one+two",
+ properties: [{ key: "flag" }, { key: "source", value: "a=b" }],
+ });
+ expect(readBaggageMember(`${key}=a,${key}=a`, key)).toBe("malformed");
+ expect(readBaggageMember(`${key}=%ZZ`, key)).toBe("malformed");
+ expect(readBaggageMember(`${key}=value\n`, key)).toBe("malformed");
+ expect(readBaggageMember(`${key}=value,vendor=${"a".repeat(8192)}`, key)).toBe("malformed");
+ expect(readBaggageMember(`${key}=%FF`, key)).toEqual({ value: "\ufffd", properties: [] });
+ expect(readBaggageMember(`${key}=%EF%BB%BFvalue`, key)).toEqual({
+ value: "\ufeffvalue",
+ properties: [],
+ });
+ });
+
+ it("decodes audience and property values before applying the policy schema", () => {
+ expect(readForwardedAudienceBaggage("eve.audience=%70ublic;ceiling=%691o0")).toEqual({
+ originAudience: "public",
+ ceiling: { recordInputs: true, recordOutputs: false },
+ });
+ });
+});
+
describe("readForwardedAudienceBaggage", () => {
it.each([
["public", true, true],
diff --git a/packages/eve/src/protocol/baggage.ts b/packages/eve/src/protocol/baggage.ts
index 8d1c46ae3..3482294b1 100644
--- a/packages/eve/src/protocol/baggage.ts
+++ b/packages/eve/src/protocol/baggage.ts
@@ -6,62 +6,108 @@ import { formatTraceContentCeiling } from "#shared/forwarded-trace-policy.js";
const EVE_AUDIENCE_KEY = "eve.audience";
const CEILING_PROPERTY_KEY = "ceiling";
+const MAX_BAGGAGE_BYTES = 8192;
+const encoder = new TextEncoder();
+const decoder = new TextDecoder("utf-8", { ignoreBOM: true });
+
+interface BaggageProperty {
+ readonly key: string;
+ readonly value?: string;
+}
+
+interface BaggageMember {
+ readonly value: string;
+ readonly properties: readonly BaggageProperty[];
+}
export type ForwardedTraceBaggage = "absent" | "malformed" | ForwardedTraceAssertion;
-/** Reads Eve's audience member without interpreting or rejecting unrelated baggage. */
+/** Reads eve's audience member without interpreting 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]!);
+ const member = readBaggageMember(value, EVE_AUDIENCE_KEY);
+ if (typeof member === "string") return member;
+ const originAudience = member.value;
+ if (originAudience !== "public" && originAudience !== "private" && originAudience !== "unknown") {
+ return "malformed";
+ }
+ const property = member.properties[0];
+ if (member.properties.length !== 1 || property?.key !== CEILING_PROPERTY_KEY) return "malformed";
+ const ceiling = property.value === undefined ? undefined : parseCeiling(property.value);
+ return ceiling === undefined ? "malformed" : { ceiling, originAudience };
}
-/** Replaces any authored Eve audience member while preserving unrelated baggage entries. */
+/** 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;
+ return replaceBaggageMember(
+ value,
+ EVE_AUDIENCE_KEY,
+ assertion === undefined
+ ? undefined
+ : `${assertion.originAudience};${CEILING_PROPERTY_KEY}=${formatTraceContentCeiling(assertion.ceiling)}`,
+ );
}
-function baggageMembers(value: string): string[] {
- return value.split(",").map(trimOws).filter(Boolean);
+/** Recognized members are singular; malformed or oversized input fails closed. */
+export function readBaggageMember(
+ value: string | null,
+ key: string,
+): BaggageMember | "absent" | "malformed" {
+ if (value === null) return "absent";
+ if (value.length > MAX_BAGGAGE_BYTES || encoder.encode(value).byteLength > MAX_BAGGAGE_BYTES) {
+ return "malformed";
+ }
+ const members = baggageMembers(value).filter((member) => baggageKey(member) === key);
+ if (members.length === 0) return "absent";
+ if (members.length !== 1) return "malformed";
+ const [head, ...segments] = members[0]!.split(";");
+ const pair = parsePair(head!);
+ if (pair?.value === undefined) return "malformed";
+ const properties: BaggageProperty[] = [];
+ for (const segment of segments) {
+ const property = parsePair(segment);
+ if (property === undefined) return "malformed";
+ properties.push(property);
+ }
+ return { value: pair.value, properties };
}
-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";
+/** Replaces a member with an encoded value and optional properties; undefined removes it. */
+export function replaceBaggageMember(
+ value: string | undefined,
+ key: string,
+ member: string | undefined,
+): string | undefined {
+ const retained = baggageMembers(value ?? "").filter((entry) => baggageKey(entry) !== key);
+ if (member !== undefined) {
+ const result = [...retained, `${key}=${member}`].join(",");
+ if (encoder.encode(result).byteLength <= MAX_BAGGAGE_BYTES) return result;
}
+ return retained.join(",") || undefined;
+}
- 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 baggageMembers(value: string): string[] {
+ return value.split(",").map(trimOws).filter(Boolean);
}
-function parsePair(segment: string): { readonly key: string; readonly value: string } | undefined {
+function parsePair(segment: string): BaggageProperty | undefined {
const separator = segment.indexOf("=");
- if (separator <= 0 || segment.indexOf("=", separator + 1) !== -1) return undefined;
- const key = trimOws(segment.slice(0, separator));
+ const key = trimOws(separator < 0 ? segment : segment.slice(0, separator));
+ if (!/^[!#$%&'*+\-.^_`|~\w]+$/u.test(key)) return undefined;
+ if (separator < 0) return { key };
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 };
+ if (
+ !/^[\x21\x23-\x2b\x2d-\x3a\x3c-\x5b\x5d-\x7e]*$/u.test(value) ||
+ /%(?![\da-f]{2})/iu.test(value)
+ ) {
+ return undefined;
+ }
+ const bytes = Uint8Array.from(value.match(/%[\da-f]{2}|./giu) ?? [], (octet) =>
+ octet.startsWith("%") ? Number.parseInt(octet.slice(1), 16) : octet.charCodeAt(0),
+ );
+ return { key, value: decoder.decode(bytes) };
}
function parseCeiling(value: string): TraceContentCeiling | undefined {
@@ -78,13 +124,8 @@ function trimOws(value: string): string {
return value.replace(/^[\t ]+|[\t ]+$/gu, "");
}
-function baggageKey(member: string): string | undefined {
+function baggageKey(member: string): string {
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;
+ return (separator < 0 ? pair : pair.slice(0, separator)).trim();
}
diff --git a/packages/eve/src/public/channels/eve-session-routes.test.ts b/packages/eve/src/public/channels/eve-session-routes.test.ts
index f9b07da5c..4329aeb61 100644
--- a/packages/eve/src/public/channels/eve-session-routes.test.ts
+++ b/packages/eve/src/public/channels/eve-session-routes.test.ts
@@ -7,8 +7,12 @@ import { mockChannelContext } from "#internal/testing/mocks/mock-channel-operati
import { none } from "#public/channels/auth.js";
import { eveChannel } from "#public/channels/eve.js";
-function route(method: "GET" | "POST", path: string) {
- const found = eveChannel({ auth: none() }).routes.find(
+function route(
+ method: "GET" | "POST",
+ path: string,
+ input: Parameters<typeof eveChannel>[0] = { auth: none() },
+) {
+ const found = eveChannel(input).routes.find(
(candidate) => candidate.method === method && candidate.path === path,
);
if (found === undefined || !("handler" in found)) throw new Error(`Missing ${method} ${path}`);
@@ -129,6 +133,65 @@ describe("eve ID-addressed session routes", () => {
);
});
+ it.each([true, false])(
+ "accepts trace correlation only with a callback (%s)",
+ async (callback) => {
+ const createSession = vi.fn().mockResolvedValue({
+ events: new ReadableStream(),
+ sessionId: "wrun_A",
+ });
+ const args = attachRouteSessionCreator(createArgs(), createSession);
+ const trustedForwarders = vi.fn(() => false);
+
+ const response = await route("POST", "/eve/v1/session", {
+ auth: none(),
+ trustedForwarders,
+ })(
+ new Request("https://eve.test/eve/v1/session", {
+ body: JSON.stringify({
+ callback: callback
+ ? {
+ callId: "call-1",
+ subagentName: "research",
+ token: "tok123",
+ url: "https://caller.example.com/eve/v1/callback/tok123",
+ }
+ : undefined,
+ message: "hello",
+ }),
+ headers: {
+ "content-type": "application/json",
+ baggage: "eve.conversation.id=original-conversation",
+ traceparent: `00-${"1".repeat(32)}-${"2".repeat(16)}-01`,
+ },
+ method: "POST",
+ }),
+ args,
+ );
+
+ expect(response.status).toBe(202);
+ await expect(response.json()).resolves.toEqual({
+ ok: true,
+ sessionId: "wrun_A",
+ status: "accepted",
+ });
+ expect(createSession).toHaveBeenCalledWith(
+ expect.objectContaining({
+ conversationId: callback ? "original-conversation" : undefined,
+ parentTraceContext: callback
+ ? {
+ isRemote: true,
+ spanId: "2".repeat(16),
+ traceFlags: 1,
+ traceId: "1".repeat(32),
+ }
+ : undefined,
+ }),
+ );
+ expect(trustedForwarders).not.toHaveBeenCalled();
+ },
+ );
+
it("rejects input responses on session creation", async () => {
const createSession = vi.fn();
const args = attachRouteSessionCreator(createArgs(), createSession);
diff --git a/packages/eve/src/subagents/invocation.ts b/packages/eve/src/subagents/invocation.ts
index 3dd65830f..fa9fe8187 100644
--- a/packages/eve/src/subagents/invocation.ts
+++ b/packages/eve/src/subagents/invocation.ts
@@ -1,6 +1,14 @@
import type { StepInput } from "#harness/types.js";
+import type { SessionParent, SessionTraceContext } from "#channel/types.js";
import { isJsonObjectValue, type JsonObject, type JsonValue } from "#shared/json.js";
+export interface SubagentParentContext {
+ readonly conversationId?: string;
+ readonly lineage: SessionParent;
+ readonly continuationToken?: string;
+ readonly traceContext?: SessionTraceContext;
+}
+
/**
* Narrowed form of {@link StepInput} whose `message` is always a plain string.
* Delegated child runs receive a synthesized text-only prompt.
diff --git a/packages/eve/src/subagents/remote-dispatch.test.ts b/packages/eve/src/subagents/remote-dispatch.test.ts
index f39881482..71e609abf 100644
--- a/packages/eve/src/subagents/remote-dispatch.test.ts
+++ b/packages/eve/src/subagents/remote-dispatch.test.ts
@@ -201,6 +201,65 @@ describe("startRemoteAgentSession", () => {
});
});
+ it.each([true, false])(
+ "preserves configured headers unless context replaces them (%s)",
+ async (hasContext) => {
+ const fetchMock = vi.fn().mockResolvedValue(
+ Response.json(
+ {
+ ok: true,
+ sessionId: "accepted-child",
+ status: "accepted",
+ },
+ { status: 202 },
+ ),
+ );
+ vi.stubGlobal("fetch", fetchMock);
+ const input = {
+ action: createAction(),
+ callbackBaseUrl: "https://caller.example.com",
+ parent: hasContext
+ ? {
+ conversationId: "logical-conversation",
+ traceContext: {
+ spanId: "2".repeat(16),
+ traceFlags: 1,
+ traceId: "1".repeat(32),
+ },
+ }
+ : undefined,
+ remote: {
+ ...createRemoteAgent(),
+ headers: {
+ Traceparent: "operator-context",
+ baggage: "eve.conversation.id=operator-id,vendor=value",
+ },
+ },
+ session: {
+ agent: { modelReference: { id: "mock/test" }, system: "", tools: [] },
+ compaction: { recentWindowSize: 10, threshold: 100000 },
+ continuationToken: "eve:parent-token",
+ history: [],
+ sessionId: "parent-session",
+ state: {},
+ },
+ };
+
+ await expect(startRemoteAgentSession(input)).resolves.toEqual({
+ sessionId: "accepted-child",
+ });
+ const headers = new Headers(fetchMock.mock.calls[0]?.[1]?.headers);
+ expect(headers.get("traceparent")).toBe(
+ hasContext ? `00-${"1".repeat(32)}-${"2".repeat(16)}-01` : "operator-context",
+ );
+ expect(headers.get("baggage")).toBe(
+ hasContext
+ ? "vendor=value,eve.conversation.id=logical-conversation"
+ : "eve.conversation.id=operator-id,vendor=value",
+ );
+ },
+ );
+
it("posts the formatted subagent message and callback metadata", async () => {
const fetchMock = vi.fn().mockResolvedValue(
new Response(
@@ -217,11 +276,6 @@ describe("startRemoteAgentSession", () => {
const childSessionId = await startRemoteAgentSession({
action: createAction(),
callbackBaseUrl: "https://caller.example.com",
- parentTraceContext: {
- spanId: "2".repeat(16),
- traceFlags: 1,
- traceId: "1".repeat(32),
- },
remote: {
...createRemoteAgent(),
headers: { Traceparent: "00-authored", "x-static": "yes" },
@@ -241,6 +295,13 @@ describe("startRemoteAgentSession", () => {
sessionId: "parent-session",
state: {},
},
+ parent: {
+ traceContext: {
+ spanId: "2".repeat(16),
+ traceFlags: 1,
+ traceId: "1".repeat(32),
+ },
+ },
});
expect(childSessionId).toEqual({ sessionId: "remote-session" });
@@ -289,7 +350,6 @@ describe("startRemoteAgentSession", () => {
await startRemoteAgentSession({
action: createAction(),
callbackBaseUrl: "https://caller.example.com",
- callbackToken: "invocation-reply",
remote: createRemoteAgent(),
session: {
agent: { modelReference: { id: "mock/test" }, system: "", tools: [] },
@@ -300,6 +360,7 @@ describe("startRemoteAgentSession", () => {
state: {},
},
taskId: "task-1",
+ parent: { continuationToken: "invocation-reply" },
});
expect(JSON.parse(fetchMock.mock.calls[0]?.[1]?.body as string)).toMatchObject({
@@ -494,7 +555,6 @@ describe("startRemoteAgentSession", () => {
await startRemoteAgentSession({
action: createAction(),
callbackBaseUrl: "https://caller.example.com",
- callbackToken: "turn-inbox",
remote: createRemoteAgent(),
session: {
agent: { modelReference: { id: "mock/test" }, system: "", tools: [] },
@@ -503,6 +563,7 @@ describe("startRemoteAgentSession", () => {
history: [],
sessionId: "parent-session",
},
+ parent: { continuationToken: "turn-inbox" },
});
expect(JSON.parse(fetchMock.mock.calls[0]?.[1]?.body as string).callback).toEqual({
@@ -615,18 +676,20 @@ describe("startRemoteAgentSession — forwarded principal", () => {
callbackBaseUrl: "https://caller.example.com",
originAudience: "private",
initiatorAuth: INITIATOR_AUTH,
- 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(),
+ parent: {
+ traceContext: {
+ decision: { action: "record", recordInputs: true, recordOutputs: false },
+ spanId: "2".repeat(16),
+ traceFlags: 1,
+ traceId: "1".repeat(32),
+ },
+ },
}),
).resolves.toEqual({ sessionId: "remote-session" });
@@ -652,14 +715,16 @@ describe("startRemoteAgentSession — forwarded principal", () => {
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(),
+ parent: {
+ traceContext: {
+ decision: { action: "record", recordInputs: false, recordOutputs: false },
+ spanId: "2".repeat(16),
+ traceFlags: 1,
+ traceId: "1".repeat(32),
+ },
+ },
});
expect(fetchMock.mock.calls[0]?.[1]?.headers).toMatchObject({
@@ -677,18 +742,20 @@ describe("startRemoteAgentSession — forwarded principal", () => {
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(),
+ parent: {
+ traceContext: {
+ decision: { action: "drop" },
+ spanId: "2".repeat(16),
+ traceFlags: 0,
+ traceId: "1".repeat(32),
+ },
+ },
});
expect(fetchMock.mock.calls[0]?.[1]?.headers).toMatchObject({ baggage: "vendor=value" });
@@ -736,13 +803,15 @@ describe("startRemoteAgentSession — forwarded principal", () => {
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(),
+ parent: {
+ traceContext: {
+ spanId: "2".repeat(16),
+ traceFlags: 1,
+ traceId: "1".repeat(32),
+ },
+ },
}),
).resolves.toEqual({ sessionId: "remote-session" });
@@ -772,16 +841,18 @@ describe("startRemoteAgentSession — forwarded principal", () => {
callbackBaseUrl: "https://caller.example.com",
originAudience: "public",
initiatorAuth: INITIATOR_AUTH,
- parentTraceContext: {
- spanId: "2".repeat(16),
- traceFlags: 1,
- traceId: "1".repeat(32),
- },
remote: {
...createRemoteAgent(),
headers: { baggage: "vendor=value,eve.audience=public" },
},
session: createSession(),
+ parent: {
+ traceContext: {
+ spanId: "2".repeat(16),
+ traceFlags: 1,
+ traceId: "1".repeat(32),
+ },
+ },
}),
).resolves.toEqual({ sessionId: "remote-session" });
diff --git a/packages/eve/src/subagents/remote-dispatch.ts b/packages/eve/src/subagents/remote-dispatch.ts
index 75bfe98dd..b037543fc 100644
--- a/packages/eve/src/subagents/remote-dispatch.ts
+++ b/packages/eve/src/subagents/remote-dispatch.ts
@@ -20,7 +20,11 @@ import type { HeadersValue } from "#client/types.js";
import { createWorkflowCallbackUrl } from "#execution/workflow-callback-url.js";
import { createRemoteAgentRouteUrl } from "#subagents/remote-route-url.js";
import { formatTraceparent } from "#protocol/traceparent.js";
-import { formatSubagentInput, normalizeRequestedOutputSchema } from "#subagents/invocation.js";
+import {
+ formatSubagentInput,
+ normalizeRequestedOutputSchema,
+ type SubagentParentContext,
+} from "#subagents/invocation.js";
import type { HarnessSession } from "#harness/types.js";
import type { RuntimeRemoteAgentDispatchRequest } from "#shared/action-types.js";
import type { RuntimeSubagentRegistry } from "#runtime/subagents/registry.js";
@@ -32,6 +36,7 @@ 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";
+import { writeConversationBaggage } from "#tracing/conversation-context.js";
const CreateSessionResponseSchema = z.object({
ok: z.literal(true),
@@ -58,7 +63,6 @@ export async function startRemoteAgentSession(input: {
/** The dispatching turn's session principal, forwarded when `remote.forwardPrincipal` is set. */
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}. */
@@ -69,12 +73,12 @@ export async function startRemoteAgentSession(input: {
* created instead of starting a second one.
*/
readonly operationId?: string;
- readonly parentTraceContext?: SessionTraceContext;
+ readonly parent?: Omit<SubagentParentContext, "lineage">;
readonly remote: ResolvedRuntimeRemoteAgentNode;
readonly session: HarnessSession;
readonly taskId?: string;
}): Promise<RemoteAgentSessionCoordinates> {
- const callbackToken = input.callbackToken ?? input.session.continuationToken;
+ const callbackToken = input.parent?.continuationToken ?? input.session.continuationToken;
if (!callbackToken) {
throw new Error("Cannot dispatch remote agent without a parent continuation token.");
}
@@ -127,20 +131,18 @@ export async function startRemoteAgentSession(input: {
}
const headers = await resolveRemoteAgentRequestHeaders(input.remote);
- const traceparent = formatTraceparent(input.parentTraceContext);
- if (traceparent !== undefined) {
- setHeader(headers, "traceparent", traceparent);
- }
+ const traceparent = formatTraceparent(input.parent?.traceContext);
+ if (traceparent !== undefined) setHeader(headers, "traceparent", traceparent);
const baggage = writeForwardedAudienceBaggage(
readHeader(headers, "baggage"),
buildForwardedTraceAssertion({
forwardedPrincipal,
originAudience: input.originAudience,
- parentTraceContext: input.parentTraceContext,
+ parentTraceContext: input.parent?.traceContext,
traceparent,
}),
);
- setHeader(headers, "baggage", baggage);
+ setHeader(headers, "baggage", writeConversationBaggage(baggage, input.parent?.conversationId));
const response = await fetch(createRemoteAgentSessionUrl(input.remote), {
body: JSON.stringify(requestBody),
headers: {
diff --git a/packages/eve/src/subagents/start-local.test.ts b/packages/eve/src/subagents/start-local.test.ts
index e715465d6..853b5b9e4 100644
--- a/packages/eve/src/subagents/start-local.test.ts
+++ b/packages/eve/src/subagents/start-local.test.ts
@@ -1,24 +1,71 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
-const { buildSubagentRunInput, createSession, waitForCommandHookOwner } = vi.hoisted(() => ({
- buildSubagentRunInput: vi.fn(() => ({
- childContinuationToken: "child-token",
- runInput: { input: { message: "work" } },
- })),
- createSession: vi.fn(async () => ({ sessionId: "child-session" })),
- waitForCommandHookOwner: vi.fn(async () => ({ runId: "child-session" })),
-}));
+import { createWorkflowRuntime, waitForCommandHookOwner } from "#execution/workflow-runtime.js";
+import { startLocalSubagent } from "#subagents/start-local.js";
+import { buildSubagentRunInput } from "#subagents/tool.js";
+
+const createSessionMock = vi.fn();
-vi.mock("#subagents/tool.js", () => ({ buildSubagentRunInput }));
vi.mock("#execution/workflow-runtime.js", () => ({
- createWorkflowRuntime: () => ({ createSession }),
- waitForCommandHookOwner,
+ createWorkflowRuntime: vi.fn(() => ({ createSession: createSessionMock })),
+ waitForCommandHookOwner: vi.fn(),
+}));
+vi.mock("#subagents/tool.js", () => ({
+ buildSubagentRunInput: vi.fn(),
}));
-import { startLocalSubagent } from "#subagents/start-local.js";
+beforeEach(() => {
+ vi.clearAllMocks();
+ createSessionMock.mockResolvedValue({
+ events: new ReadableStream(),
+ sessionId: "candidate-session",
+ });
+ vi.mocked(buildSubagentRunInput).mockReturnValue({
+ childContinuationToken: "child-token",
+ runInput: {} as never,
+ });
+ vi.mocked(waitForCommandHookOwner).mockResolvedValue({ runId: "winning-session" });
+});
describe("startLocalSubagent", () => {
- beforeEach(() => vi.clearAllMocks());
+ it("uses the session that wins continuation ownership", async () => {
+ const outcome = await startLocalSubagent({
+ action: {
+ callId: "call-1",
+ name: "research",
+ nodeId: "subagents/research",
+ subagentName: "research",
+ } as never,
+ auth: null,
+ bundle: { compiledArtifactsSource: {} } as never,
+ capabilities: undefined,
+ channelMetadata: undefined,
+ currentSession: {} as never,
+ fanoutSize: 1,
+ initiatorAuth: null,
+ parent: {
+ continuationToken: "parent-token",
+ lineage: {
+ callId: "call-1",
+ rootSessionId: "parent-session",
+ sessionId: "parent-session",
+ turn: { id: "turn-1", sequence: 0 },
+ },
+ },
+ sandboxSessionId: "parent-session",
+ session: {} as never,
+ source: { description: "Research", type: "local" },
+ });
+
+ expect(createWorkflowRuntime).toHaveBeenCalledOnce();
+ expect(outcome).toMatchObject({
+ address: {
+ continuationToken: "child-token",
+ sessionId: "winning-session",
+ },
+ kind: "called",
+ });
+ });
it("passes an inherited task activity observer through unchanged", async () => {
const activityObserver = {
@@ -36,31 +83,35 @@ describe("startLocalSubagent", () => {
await startLocalSubagent({
action: {
callId: "call-1",
- input: { message: "Search Slack" },
- kind: "subagent-call",
name: "slack",
nodeId: "subagents/slack",
subagentName: "slack",
- },
+ } as never,
activityObserver,
auth: null,
- batchEvent: { sequence: 0, turnId: "parent-turn" },
- bundle: { compiledArtifactsSource: {}, graph: {} },
+ bundle: { compiledArtifactsSource: {} } as never,
capabilities: undefined,
channelMetadata: undefined,
- currentSession: { sessionId: "parent-session" },
+ currentSession: {} as never,
fanoutSize: 1,
initiatorAuth: null,
- parentContinuationToken: "parent-token",
- parentTraceContext: undefined,
- sandboxSessionId: "sandbox-session",
- session: { sessionId: "parent-session" },
+ parent: {
+ continuationToken: "parent-token",
+ lineage: {
+ callId: "call-1",
+ rootSessionId: "parent-session",
+ sessionId: "parent-session",
+ turn: { id: "turn-1", sequence: 0 },
+ },
+ },
+ sandboxSessionId: "parent-session",
+ session: {} as never,
source: { description: "Search Slack", type: "local" },
- } as never);
+ });
expect(buildSubagentRunInput).toHaveBeenCalledWith(
expect.objectContaining({ activityObserver }),
);
- expect(createSession).toHaveBeenCalledOnce();
+ expect(createSessionMock).toHaveBeenCalledOnce();
});
});
diff --git a/packages/eve/src/subagents/start-local.ts b/packages/eve/src/subagents/start-local.ts
index d66e14da1..603eab2ea 100644
--- a/packages/eve/src/subagents/start-local.ts
+++ b/packages/eve/src/subagents/start-local.ts
@@ -8,6 +8,7 @@ import { createLogger, logError } from "#internal/logging.js";
import type { RuntimeSubagentDispatchRequest } from "#shared/action-types.js";
import type { CompiledBundle } from "#runtime/sessions/runtime-context-keys.js";
import { toErrorMessage } from "#shared/errors.js";
+import type { SubagentParentContext } from "#subagents/invocation.js";
const log = createLogger("execution.subagent-start-local");
@@ -19,7 +20,6 @@ type DynamicSubagentAgentConfig = Parameters<
export async function startLocalSubagent(input: {
readonly action: RuntimeSubagentDispatchRequest;
readonly auth: Parameters<typeof buildSubagentRunInput>[0]["auth"];
- readonly batchEvent: { readonly sequence: number; readonly turnId: string };
readonly bundle: CompiledBundle;
readonly capabilities: Parameters<typeof buildSubagentRunInput>[0]["capabilities"];
readonly channelMetadata: Parameters<typeof buildSubagentRunInput>[0]["channelMetadata"];
@@ -28,8 +28,7 @@ export async function startLocalSubagent(input: {
readonly fanoutSize: number;
readonly initiatorAuth: Parameters<typeof buildSubagentRunInput>[0]["initiatorAuth"];
readonly localDevRequest?: LocalDevRequestProvenance;
- readonly parentContinuationToken: string | undefined;
- readonly parentTraceContext: Parameters<typeof buildSubagentRunInput>[0]["parentTraceContext"];
+ readonly parent: SubagentParentContext;
readonly activityObserver?: Parameters<typeof buildSubagentRunInput>[0]["activityObserver"];
readonly sandboxSessionId: string;
readonly session: RuntimeSession;
@@ -45,14 +44,12 @@ export async function startLocalSubagent(input: {
const { childContinuationToken, runInput } = buildSubagentRunInput({
action,
auth: input.auth,
- batchEvent: input.batchEvent,
capabilities: input.capabilities,
channelMetadata: input.channelMetadata,
fanoutSize: input.fanoutSize,
initiatorAuth: input.initiatorAuth,
graph: input.bundle.graph,
- parentContinuationToken: input.parentContinuationToken,
- parentTraceContext: input.parentTraceContext,
+ parent: input.parent,
activityObserver: input.activityObserver,
sandboxSessionId: input.sandboxSessionId,
session: input.session,
diff --git a/packages/eve/src/subagents/start-remote.ts b/packages/eve/src/subagents/start-remote.ts
index a9cb7a1ea..b466eccb1 100644
--- a/packages/eve/src/subagents/start-remote.ts
+++ b/packages/eve/src/subagents/start-remote.ts
@@ -10,6 +10,7 @@ import { createLogger, logError } from "#internal/logging.js";
import type { RuntimeRemoteAgentDispatchRequest } from "#shared/action-types.js";
import type { CompiledBundle } from "#runtime/sessions/runtime-context-keys.js";
import type { ChannelAudience } from "#shared/channel-audience.js";
+import type { SubagentParentContext } from "#subagents/invocation.js";
const log = createLogger("execution.subagent-start-remote");
@@ -17,7 +18,6 @@ const log = createLogger("execution.subagent-start-remote");
export async function startRemoteSubagent(input: {
readonly action: RuntimeRemoteAgentDispatchRequest;
readonly auth: Parameters<typeof startRemoteAgentSession>[0]["auth"];
- readonly batchEvent: { readonly sequence: number; readonly turnId: string };
readonly bundle: CompiledBundle;
readonly callbackBaseUrl: string | undefined;
readonly originAudience: ChannelAudience;
@@ -26,8 +26,7 @@ export async function startRemoteSubagent(input: {
Parameters<typeof resolveRemoteAgentForAction>[0]["dynamicRemoteAgent"]
>;
readonly initiatorAuth: Parameters<typeof startRemoteAgentSession>[0]["initiatorAuth"];
- readonly parentContinuationToken: string | undefined;
- readonly parentTraceContext: Parameters<typeof startRemoteAgentSession>[0]["parentTraceContext"];
+ readonly parent: SubagentParentContext;
readonly activityObserver?: Parameters<typeof startRemoteAgentSession>[0]["activityObserver"];
readonly session: RuntimeSession;
readonly taskId?: string;
@@ -39,7 +38,7 @@ export async function startRemoteSubagent(input: {
kind: "remote-agent",
name: action.remoteAgentName,
parentSessionId: input.session.sessionId,
- parentTurnId: input.batchEvent.turnId,
+ parentTurnId: input.parent.lineage.turn.id,
});
// Preflight resolution failures happen before ownership exists, so they
@@ -75,7 +74,7 @@ export async function startRemoteSubagent(input: {
name: action.remoteAgentName,
nodeId: action.nodeId,
parentSessionId: input.session.sessionId,
- parentTurnId: input.batchEvent.turnId,
+ parentTurnId: input.parent.lineage.turn.id,
});
const credentialResolver = {
resolverId:
@@ -88,11 +87,10 @@ export async function startRemoteSubagent(input: {
action,
auth: input.auth,
callbackBaseUrl,
- callbackToken: input.parentContinuationToken,
originAudience: input.originAudience,
initiatorAuth: input.initiatorAuth,
operationId: operation.id,
- parentTraceContext: input.parentTraceContext,
+ parent: input.parent,
activityObserver,
remote: resolvedRemote,
session: input.session,
diff --git a/packages/eve/src/subagents/tool.test.ts b/packages/eve/src/subagents/tool.test.ts
index 909756075..0408defb5 100644
--- a/packages/eve/src/subagents/tool.test.ts
+++ b/packages/eve/src/subagents/tool.test.ts
@@ -4,6 +4,8 @@ import { SUBAGENT_ADAPTER_KIND } from "#subagents/adapter-state.js";
import type { HarnessSession } from "#harness/types.js";
import type { RuntimeSubagentDispatchRequest } from "#shared/action-types.js";
import { buildSubagentRunInput } from "#subagents/tool.js";
+import type { SessionTurn } from "#channel/types.js";
+import type { SubagentParentContext } from "#subagents/invocation.js";
type BuildSubagentRunInput = Parameters<typeof buildSubagentRunInput>[0];
@@ -33,6 +35,22 @@ function makeAction(): RuntimeSubagentDispatchRequest {
};
}
+function makeParent(
+ session: HarnessSession,
+ turn: SessionTurn,
+ options: Omit<SubagentParentContext, "lineage"> = {},
+): SubagentParentContext {
+ return {
+ lineage: {
+ callId: "call-1",
+ rootSessionId: session.rootSessionId ?? session.sessionId,
+ sessionId: session.sessionId,
+ turn,
+ },
+ ...options,
+ };
+}
+
function buildRuntimeSubagentRunInput(
input: Omit<BuildSubagentRunInput, "selfAgent" | "source"> & { readonly selfAgent?: boolean },
): ReturnType<typeof buildSubagentRunInput> {
@@ -56,10 +74,10 @@ describe("buildSubagentRunInput", () => {
const { runInput } = buildRuntimeSubagentRunInput({
action: makeAction(),
auth: null,
- batchEvent: { sequence: 0, turnId: "turn-0" },
capabilities: { requestInput: true },
initiatorAuth: null,
session: makeSession(),
+ parent: makeParent(makeSession(), { id: "turn-0", sequence: 0 }),
});
expect(runInput.capabilities).toEqual({ requestInput: true });
@@ -69,9 +87,9 @@ describe("buildSubagentRunInput", () => {
const { runInput } = buildRuntimeSubagentRunInput({
action: makeAction(),
auth: null,
- batchEvent: { sequence: 0, turnId: "turn-0" },
initiatorAuth: null,
session: makeSession(),
+ parent: makeParent(makeSession(), { id: "turn-0", sequence: 0 }),
});
expect(runInput.capabilities).toBeUndefined();
@@ -81,9 +99,9 @@ describe("buildSubagentRunInput", () => {
const { childContinuationToken, runInput } = buildRuntimeSubagentRunInput({
action: makeAction(),
auth: null,
- batchEvent: { sequence: 5, turnId: "turn-17" },
initiatorAuth: null,
session: makeSession(),
+ parent: makeParent(makeSession(), { id: "turn-17", sequence: 5 }),
});
expect(runInput.adapter.kind).toBe(SUBAGENT_ADAPTER_KIND);
@@ -108,10 +126,13 @@ describe("buildSubagentRunInput", () => {
const { runInput } = buildRuntimeSubagentRunInput({
action: makeAction(),
auth: null,
- batchEvent: { sequence: 0, turnId: "turn-0" },
initiatorAuth: null,
- parentContinuationToken: "turn-inbox",
session: makeSession(),
+ parent: makeParent(
+ makeSession(),
+ { id: "turn-0", sequence: 0 },
+ { continuationToken: "turn-inbox" },
+ ),
});
expect(runInput.adapter.state).toMatchObject({
@@ -123,11 +144,14 @@ describe("buildSubagentRunInput", () => {
const { runInput } = buildRuntimeSubagentRunInput({
action: makeAction(),
auth: null,
- batchEvent: { sequence: 0, turnId: "turn-0" },
initiatorAuth: null,
- parentContinuationToken: "invocation-reply-hook",
session: makeSession(),
taskId: "task-1",
+ parent: makeParent(
+ makeSession(),
+ { id: "turn-0", sequence: 0 },
+ { continuationToken: "invocation-reply-hook" },
+ ),
});
expect(runInput.adapter.state).toMatchObject({
@@ -145,10 +169,10 @@ describe("buildSubagentRunInput", () => {
const { runInput } = buildRuntimeSubagentRunInput({
action: makeAction(),
auth: null,
- batchEvent: { sequence: 0, turnId: "turn-0" },
channelMetadata: projection,
initiatorAuth: null,
session: makeSession(),
+ parent: makeParent(makeSession(), { id: "turn-0", sequence: 0 }),
});
expect(runInput.channelMetadata).toEqual(projection);
@@ -158,9 +182,9 @@ describe("buildSubagentRunInput", () => {
const { runInput } = buildRuntimeSubagentRunInput({
action: makeAction(),
auth: null,
- batchEvent: { sequence: 0, turnId: "turn-0" },
initiatorAuth: null,
session: makeSession(),
+ parent: makeParent(makeSession(), { id: "turn-0", sequence: 0 }),
});
expect(runInput.channelMetadata).toBeUndefined();
@@ -180,10 +204,13 @@ describe("buildSubagentRunInput", () => {
const { runInput } = buildRuntimeSubagentRunInput({
action: makeAction(),
auth: null,
- batchEvent: { sequence: 0, turnId: "turn-0" },
initiatorAuth: null,
- parentTraceContext,
session: makeSession(),
+ parent: makeParent(
+ makeSession(),
+ { id: "turn-0", sequence: 0 },
+ { traceContext: parentTraceContext },
+ ),
});
expect(runInput.parentTraceContext).toEqual(parentTraceContext);
@@ -198,9 +225,9 @@ describe("buildSubagentRunInput", () => {
const { runInput } = buildRuntimeSubagentRunInput({
action: makeAction(),
auth: null,
- batchEvent: { sequence: 1, turnId: "turn-99" },
initiatorAuth: null,
session: nestedSession,
+ parent: makeParent(nestedSession, { id: "turn-99", sequence: 1 }),
});
expect(runInput.parent).toEqual({
@@ -215,11 +242,16 @@ describe("buildSubagentRunInput", () => {
const { runInput } = buildRuntimeSubagentRunInput({
action: makeAction(),
auth: null,
- batchEvent: { sequence: 0, turnId: "turn-0" },
initiatorAuth: null,
session: {
...makeSession(),
},
+ parent: makeParent(
+ {
+ ...makeSession(),
+ },
+ { id: "turn-0", sequence: 0 },
+ ),
});
expect(runInput.limits).toEqual({
@@ -237,9 +269,9 @@ describe("buildSubagentRunInput", () => {
const { runInput } = buildRuntimeSubagentRunInput({
action,
auth: null,
- batchEvent: { sequence: 0, turnId: "turn-0" },
initiatorAuth: null,
session: makeSession(),
+ parent: makeParent(makeSession(), { id: "turn-0", sequence: 0 }),
});
expect(runInput.input.outputSchema).toEqual(schema);
@@ -251,11 +283,11 @@ describe("buildSubagentRunInput", () => {
const { runInput } = buildSubagentRunInput({
action: makeAction(),
auth: null,
- batchEvent: { sequence: 0, turnId: "turn-0" },
initiatorAuth: null,
selfAgent: false,
session: makeSession(),
source: { description: "Research the request.", outputSchema: schema, type: "local" },
+ parent: makeParent(makeSession(), { id: "turn-0", sequence: 0 }),
});
expect(runInput.input.outputSchema).toEqual(schema);
@@ -268,11 +300,11 @@ describe("buildSubagentRunInput", () => {
const { runInput } = buildSubagentRunInput({
action: { ...makeAction(), input: { message: "do something", outputSchema: requested } },
auth: null,
- batchEvent: { sequence: 0, turnId: "turn-0" },
initiatorAuth: null,
selfAgent: false,
session: makeSession(),
source: { description: "Research the request.", outputSchema: declared, type: "local" },
+ parent: makeParent(makeSession(), { id: "turn-0", sequence: 0 }),
});
expect(runInput.input.outputSchema).toEqual(requested);
@@ -283,19 +315,22 @@ describe("buildSubagentRunInput", () => {
const { runInput } = buildRuntimeSubagentRunInput({
action: makeAction(),
auth: null,
- batchEvent: { sequence: 0, turnId: "turn-0" },
initiatorAuth: null,
- parentTraceContext: traceContext,
session: makeSession(),
+ parent: makeParent(
+ makeSession(),
+ { id: "turn-0", sequence: 0 },
+ { traceContext: traceContext },
+ ),
});
expect(runInput.parentTraceContext).toEqual(traceContext);
const untraced = buildRuntimeSubagentRunInput({
action: makeAction(),
auth: null,
- batchEvent: { sequence: 0, turnId: "turn-0" },
initiatorAuth: null,
session: makeSession(),
+ parent: makeParent(makeSession(), { id: "turn-0", sequence: 0 }),
});
expect(untraced.runInput.parentTraceContext).toBeUndefined();
});
@@ -307,11 +342,11 @@ describe("buildSubagentRunInput", () => {
description: "Runtime action event description.",
},
auth: null,
- batchEvent: { sequence: 0, turnId: "turn-0" },
initiatorAuth: null,
selfAgent: false,
session: makeSession(),
source: { description: "Local delegate subagent description.", type: "local" },
+ parent: makeParent(makeSession(), { id: "turn-0", sequence: 0 }),
});
expect(runInput.input.message).toBe(
@@ -339,9 +374,9 @@ describe("buildSubagentRunInput", () => {
const { runInput } = buildRuntimeSubagentRunInput({
action,
auth: null,
- batchEvent: { sequence: 0, turnId: "turn-0" },
initiatorAuth: null,
session: makeSession(),
+ parent: makeParent(makeSession(), { id: "turn-0", sequence: 0 }),
});
expect(runInput.input.message).toBe(
@@ -362,11 +397,11 @@ describe("buildSubagentRunInput", () => {
const { runInput } = buildSubagentRunInput({
action: { ...makeAction(), name: "agent", nodeId: "root", subagentName: "agent" },
auth: null,
- batchEvent: { sequence: 0, turnId: "turn-0" },
initiatorAuth: null,
selfAgent: true,
session: makeSession(),
source: { outputSchema: schema, type: "runtime" },
+ parent: makeParent(makeSession(), { id: "turn-0", sequence: 0 }),
});
expect(runInput.input.outputSchema).toEqual(schema);
@@ -377,9 +412,9 @@ describe("buildSubagentRunInput", () => {
const { runInput } = buildRuntimeSubagentRunInput({
action: makeAction(),
auth: null,
- batchEvent: { sequence: 0, turnId: "turn-0" },
initiatorAuth: null,
session: makeSession(),
+ parent: makeParent(makeSession(), { id: "turn-0", sequence: 0 }),
});
expect(runInput.input.outputSchema).toBeUndefined();
@@ -393,9 +428,9 @@ describe("buildSubagentRunInput", () => {
const { runInput } = buildRuntimeSubagentRunInput({
action,
auth: null,
- batchEvent: { sequence: 0, turnId: "turn-0" },
initiatorAuth: null,
session: makeSession(),
+ parent: makeParent(makeSession(), { id: "turn-0", sequence: 0 }),
});
expect(runInput.input.outputSchema).toBeUndefined();
@@ -411,10 +446,10 @@ describe("buildSubagentRunInput", () => {
const { runInput } = buildRuntimeSubagentRunInput({
action,
auth: null,
- batchEvent: { sequence: 0, turnId: "turn-0" },
initiatorAuth: null,
selfAgent: true,
session,
+ parent: makeParent(session, { id: "turn-0", sequence: 0 }),
});
expect(runInput.adapter.state).toMatchObject({
@@ -429,10 +464,10 @@ describe("buildSubagentRunInput", () => {
const { runInput } = buildRuntimeSubagentRunInput({
action: makeAction(),
auth: null,
- batchEvent: { sequence: 0, turnId: "turn-0" },
graph: makeInheritingGraph(makeAction().nodeId),
initiatorAuth: null,
session,
+ parent: makeParent(session, { id: "turn-0", sequence: 0 }),
});
expect(runInput.adapter.state).toMatchObject({
@@ -445,11 +480,14 @@ describe("buildSubagentRunInput", () => {
const { runInput } = buildRuntimeSubagentRunInput({
action: makeAction(),
auth: null,
- batchEvent: { sequence: 0, turnId: "turn-0" },
graph: makeInheritingGraph(makeAction().nodeId),
initiatorAuth: null,
sandboxSessionId: "root-sandbox-session",
session: { ...makeSession(), sessionId: "intermediate-child-session" },
+ parent: makeParent(
+ { ...makeSession(), sessionId: "intermediate-child-session" },
+ { id: "turn-0", sequence: 0 },
+ ),
});
expect(runInput.adapter.state).toMatchObject({
@@ -461,10 +499,10 @@ describe("buildSubagentRunInput", () => {
const { runInput } = buildRuntimeSubagentRunInput({
action: makeAction(),
auth: null,
- batchEvent: { sequence: 0, turnId: "turn-0" },
graph: makeInheritingGraph(makeAction().nodeId),
initiatorAuth: null,
session: makeSession(),
+ parent: makeParent(makeSession(), { id: "turn-0", sequence: 0 }),
});
expect(runInput.adapter.state).toMatchObject({ sandboxSessionId: "parent-session" });
diff --git a/packages/eve/src/subagents/tool.ts b/packages/eve/src/subagents/tool.ts
index 69abb89ac..9e114ea0a 100644
--- a/packages/eve/src/subagents/tool.ts
+++ b/packages/eve/src/subagents/tool.ts
@@ -1,13 +1,16 @@
import { SUBAGENT_ADAPTER_KIND } from "#subagents/adapter-state.js";
-import { formatSubagentInput, normalizeRequestedOutputSchema } from "#subagents/invocation.js";
+import {
+ formatSubagentInput,
+ normalizeRequestedOutputSchema,
+ type SubagentParentContext,
+} from "#subagents/invocation.js";
import type {
ActivityObserverConfig,
ChannelInstrumentationProjection,
- RunInput,
RunSessionLimits,
SessionAuthContext,
SessionCapabilities,
- SessionTraceContext,
+ RunInput,
} from "#channel/types.js";
import type { HarnessSession } from "#harness/types.js";
import type { RuntimeSubagentDispatchRequest } from "#shared/action-types.js";
@@ -15,14 +18,6 @@ import { mintSubagentContinuationToken } from "#execution/session.js";
import { resolveRemainingSessionTokenLimits } from "#subagents/token-budget.js";
import type { JsonObject } from "#shared/json.js";
-/**
- * Pending task batch event metadata needed for child run lineage.
- */
-interface BatchEventMetadata {
- readonly sequence: number;
- readonly turnId: string;
-}
-
export type SubagentInputSource =
| {
readonly description: string;
@@ -69,7 +64,6 @@ export interface SubagentSandboxGraph {
export function buildSubagentRunInput(input: {
readonly action: RuntimeSubagentDispatchRequest;
readonly auth: SessionAuthContext | null;
- readonly batchEvent: BatchEventMetadata;
/**
* Parent's session capabilities. Forwarded verbatim so HITL
* readiness flows transparently down through a subagent chain. Undefined
@@ -93,45 +87,26 @@ export function buildSubagentRunInput(input: {
/** Durable session identity of the sandbox currently used by the parent. */
readonly sandboxSessionId?: string;
readonly selfAgent: boolean;
- /** Hook token owned by the workflow currently waiting for this child. */
- readonly parentContinuationToken?: string;
- readonly parentTraceContext?: SessionTraceContext;
+ readonly parent: SubagentParentContext;
readonly activityObserver?: ActivityObserverConfig;
readonly session: HarnessSession;
readonly source: SubagentInputSource;
/** Owning task when this child starts from a background workflow tool. */
readonly taskId?: string;
}): SubagentRunInputBuild {
- const {
- action,
- auth,
- batchEvent,
- capabilities,
- channelMetadata,
- initiatorAuth,
- session,
- source,
- } = input;
+ const { action, auth, capabilities, channelMetadata, initiatorAuth, session, source } = input;
const childContinuationToken = mintSubagentContinuationToken(
`${session.sessionId}:${action.callId}`,
);
- // Denormalize the chain root onto the child's `parent` metadata so
- // every descendant in a nested dispatch can attribute itself to the
- // top user-facing session in a single hop. A subagent that itself
- // dispatches more subagents reads the root from
- // `session.rootSessionId` here; a top-level session carries no
- // explicit root, so its own `sessionId` becomes the root for its
- // children.
- const rootSessionId = session.rootSessionId ?? session.sessionId;
const inheritedLimits: {
-readonly [K in keyof RunSessionLimits]: RunSessionLimits[K];
} = resolveRemainingSessionTokenLimits(session, input.fanoutSize);
const requestedOutputSchema = normalizeRequestedOutputSchema(action.input.outputSchema);
const adapterState: Record<string, unknown> = {
callId: action.callId,
- parentContinuationToken: input.parentContinuationToken ?? session.continuationToken,
+ parentContinuationToken: input.parent.continuationToken ?? session.continuationToken,
parentSessionId: session.sessionId,
subagentName: action.subagentName,
};
@@ -167,16 +142,9 @@ export function buildSubagentRunInput(input: {
},
limits: inheritedLimits,
mode: "conversation",
- parent: {
- callId: action.callId,
- rootSessionId,
- sessionId: session.sessionId,
- turn: {
- id: batchEvent.turnId,
- sequence: batchEvent.sequence,
- },
- },
- parentTraceContext: input.parentTraceContext,
+ conversationId: input.parent.conversationId,
+ parent: input.parent.lineage,
+ parentTraceContext: input.parent.traceContext,
activityObserver: input.activityObserver,
};
if (input.taskId !== undefined) runInput.taskId = input.taskId;
diff --git a/packages/eve/src/tracing/agent-otel-provider.test.ts b/packages/eve/src/tracing/agent-otel-provider.test.ts
index 3affaad1e..bf699a0da 100644
--- a/packages/eve/src/tracing/agent-otel-provider.test.ts
+++ b/packages/eve/src/tracing/agent-otel-provider.test.ts
@@ -325,6 +325,7 @@ async function publishTurnStarted(input: {
channelAudience: input.channelAudience ?? "public",
channelKind: "http",
idempotencyKey: sessionIdempotencyKey(input.sessionId),
+ parentLineage: input.parentLineage,
parentTraceContext: input.parentTraceContext,
rootSessionId,
sessionId: input.sessionId,
diff --git a/packages/eve/src/tracing/agent-otel-provider.ts b/packages/eve/src/tracing/agent-otel-provider.ts
index e9119dc4a..9f16ed7c8 100644
--- a/packages/eve/src/tracing/agent-otel-provider.ts
+++ b/packages/eve/src/tracing/agent-otel-provider.ts
@@ -31,8 +31,9 @@ import { createAgentApprovalInstrumentation } from "#tracing/agent-approval-inst
import { createAgentChannelDeliveryInstrumentation } from "#tracing/agent-channel-delivery-instrumentation.js";
import { createAgentToolInstrumentation } from "#tracing/agent-tool-instrumentation.js";
import { agentSpanNamingAttributes } from "#tracing/agent-span-naming.js";
+import { resolveConversationId } from "#tracing/conversation-context.js";
import { markAgentTraceContext } from "#tracing/agent-trace-context.js";
-import { runtimeContextAttributes } from "#tracing/agent-otel-runtime-context.js";
+import * as runtimeAttributes from "#tracing/agent-otel-runtime-context.js";
import {
readGatewayCost,
setAgentInvocationUsage,
@@ -230,7 +231,7 @@ export function createAgentOtelInstrumentation(
"agent.turn.id": event.scope.turnId,
"agent.name": event.scope.functionId,
...agentSpanNamingAttributes("agent.step"),
- ...runtimeContextAttributes(event.runtimeContext),
+ ...runtimeAttributes.runtimeContextAttributes(event.runtimeContext),
},
links:
activeSpanContext === undefined || activeSpanContext.traceId === turn.context.traceId
@@ -311,12 +312,13 @@ export function createAgentOtelInstrumentation(
"agent.framework.name": "eve",
"agent.framework.version": input.frameworkVersion,
"agent.name": agentName,
+ ...runtimeAttributes.agentLineageAttributes(turn),
"agent.session.id": event.sessionId,
"agent.subagent.name": turn.subagentName,
"agent.turn.id": event.turnId,
"agent.turn.sequence": turn.sequence,
"gen_ai.agent.name": agentName,
- "gen_ai.conversation.id": event.sessionId,
+ "gen_ai.conversation.id": resolveConversationId(event.sessionId),
"gen_ai.operation.name": "invoke_agent",
...agentSpanNamingAttributes(agentSpanName(agentName), "invoke_agent"),
},
@@ -378,7 +380,7 @@ export function createAgentOtelInstrumentation(
"gen_ai.provider.name": event.model.provider,
"gen_ai.request.model": event.model.modelId,
...agentSpanNamingAttributes(modelSpanName(event.model.modelId), "chat"),
- ...runtimeContextAttributes(event.runtimeContext),
+ ...runtimeAttributes.runtimeContextAttributes(event.runtimeContext),
},
},
attempt.context,
diff --git a/packages/eve/src/tracing/agent-otel-runtime-context.ts b/packages/eve/src/tracing/agent-otel-runtime-context.ts
index 7f4f06d8f..20a13d23d 100644
--- a/packages/eve/src/tracing/agent-otel-runtime-context.ts
+++ b/packages/eve/src/tracing/agent-otel-runtime-context.ts
@@ -1,6 +1,21 @@
+import type { AgentTurnTraceState } from "#tracing/agent-trace-state.js";
+
type SpanAttributePrimitive = string | number | boolean;
type SpanAttributeValue = SpanAttributePrimitive | SpanAttributePrimitive[];
+export function agentLineageAttributes(
+ turn: AgentTurnTraceState,
+): Record<string, SpanAttributeValue> {
+ const attributes: Record<string, SpanAttributeValue> = {
+ "agent.root_run.id": turn.rootSessionId,
+ };
+ if (turn.parentLineage !== undefined) {
+ attributes["agent.parent_run.id"] = turn.parentLineage.sessionId;
+ attributes["agent.parent_call.id"] = turn.parentLineage.callId;
+ }
+ return attributes;
+}
+
/** Flattens merged runtime context into AI SDK-compatible span attributes. */
export function runtimeContextAttributes(
runtimeContext: Readonly<Record<string, unknown>> | undefined,
diff --git a/packages/eve/src/tracing/agent-otel-session-context.ts b/packages/eve/src/tracing/agent-otel-session-context.ts
index 2218d2e27..19e0b3b24 100644
--- a/packages/eve/src/tracing/agent-otel-session-context.ts
+++ b/packages/eve/src/tracing/agent-otel-session-context.ts
@@ -1,7 +1,6 @@
import type { SpanContext, Tracer } from "#compiled/@opentelemetry/api/index.js";
import {
- sessionIdempotencyKey,
type InstrumentationSessionStartedEvent,
type InstrumentationTraceContext,
type InstrumentationTraceSeed,
@@ -28,10 +27,10 @@ interface AgentOtelSessionContextInput {
readonly tracePolicy?: TraceCapturePolicy;
}
+type SessionMetadata = Omit<InstrumentationSessionStartedEvent, "idempotencyKey" | "type">;
+
interface AgentOtelSessionContext {
- readonly ensureSessionContext: (
- event: InstrumentationSessionStartedEvent,
- ) => Promise<AgentSessionTraceState>;
+ readonly ensureSessionContext: (event: SessionMetadata) => Promise<AgentSessionTraceState>;
readonly prepareSessionTrace: (
event: InstrumentationSessionStartedEvent,
) => Promise<InstrumentationTraceSeed>;
@@ -43,17 +42,13 @@ interface AgentOtelSessionContext {
export function createAgentOtelSessionContext(
input: AgentOtelSessionContextInput,
): AgentOtelSessionContext {
- const openSessionTrace = (session: {
- readonly agentName?: string;
- readonly channelAudience: ChannelAudience;
- readonly channelType?: string;
- readonly rootSessionId: string;
- readonly sessionId: string;
- readonly traceDecision: ReturnType<typeof resolveTracePolicy>;
- readonly traceSeed?: InstrumentationTraceContext;
- }): SpanContext => {
+ const openSessionTrace = (
+ session: SessionMetadata,
+ channelAudience: ChannelAudience,
+ traceDecision: ReturnType<typeof resolveTracePolicy>,
+ ): SpanContext => {
if (session.traceSeed !== undefined) {
- if (session.traceDecision.action === "drop" || !isSampledTrace(session.traceSeed)) {
+ if (traceDecision.action === "drop" || !isSampledTrace(session.traceSeed)) {
return {
isRemote: false,
spanId: session.traceSeed.spanId,
@@ -66,11 +61,11 @@ export function createAgentOtelSessionContext(
attributes: {
"agent.framework.name": "eve",
"agent.framework.version": input.frameworkVersion,
- "agent.channel.audience": session.channelAudience,
+ "agent.channel.audience": channelAudience,
"agent.name": session.agentName,
"agent.session.id": session.sessionId,
- "agent.trace.schema.version": 3,
...agentSpanNamingAttributes("agent.session"),
+ "agent.trace.schema.version": 3,
},
root: true,
});
@@ -82,7 +77,7 @@ export function createAgentOtelSessionContext(
return span.spanContext();
}
// Fallback for already-running workflows that predate the seed.
- if (session.traceDecision.action === "drop") {
+ if (traceDecision.action === "drop") {
return {
isRemote: false,
spanId: input.idGenerator.deriveSpanId(`session:${session.sessionId}`),
@@ -94,11 +89,11 @@ export function createAgentOtelSessionContext(
attributes: {
"agent.framework.name": "eve",
"agent.framework.version": input.frameworkVersion,
- "agent.channel.audience": session.channelAudience,
+ "agent.channel.audience": channelAudience,
"agent.name": session.agentName,
"agent.session.id": session.sessionId,
- "agent.trace.schema.version": 3,
...agentSpanNamingAttributes("agent.session"),
+ "agent.trace.schema.version": 3,
},
root: true,
});
@@ -107,9 +102,7 @@ export function createAgentOtelSessionContext(
return span.spanContext();
};
- const ensureSessionContext = async (
- event: InstrumentationSessionStartedEvent,
- ): Promise<AgentSessionTraceState> => {
+ const ensureSessionContext = async (event: SessionMetadata): Promise<AgentSessionTraceState> => {
let state = await input.stateStore.getSession(event.sessionId);
if (state === undefined) {
const channelAudience = normalizeChannelAudience(event.channelAudience);
@@ -121,17 +114,10 @@ export function createAgentOtelSessionContext(
decision,
context:
event.parentTraceContext === undefined
- ? openSessionTrace({
- agentName: event.agentName,
- channelAudience,
- channelType: event.channelType,
- rootSessionId: event.rootSessionId,
- sessionId: event.sessionId,
- traceDecision: decision,
- traceSeed: event.traceSeed,
- })
+ ? openSessionTrace(event, channelAudience, decision)
: adoptedSpanContext(event.parentTraceContext),
rootSessionId: event.rootSessionId,
+ parentLineage: event.parentLineage,
};
await input.stateStore.setSession(event.sessionId, state);
}
@@ -159,16 +145,7 @@ export function createAgentOtelSessionContext(
};
}
- const session = await ensureSessionContext({
- agentName: event.agentName,
- channelAudience: "unknown",
- channelKind: undefined,
- idempotencyKey: sessionIdempotencyKey(event.sessionId),
- parentTraceContext: event.parentTraceContext,
- rootSessionId: event.rootSessionId,
- sessionId: event.sessionId,
- type: "session.started",
- });
+ const session = await ensureSessionContext(event);
// The turn outlives this worker, so no live span can cover it: the span
// id is allocated now for descendants to parent through, and the span
// itself is emitted at the turn's session transition.
@@ -181,11 +158,12 @@ export function createAgentOtelSessionContext(
await input.stateStore.setTurn(event.sessionId, event.turnId, {
context: turnContext,
parentIsRemote: session.context.isRemote,
+ parentLineage: event.parentLineage ?? session.parentLineage,
parentSpanId: session.context.spanId,
rootSessionId: event.rootSessionId,
sequence: event.sequence,
startTimeMs: Date.now(),
- subagentName: event.parentLineage?.subagentName,
+ subagentName: (event.parentLineage ?? session.parentLineage)?.subagentName,
});
return portableSpanContext(session.context, session.decision);
};
@@ -215,7 +193,7 @@ function adoptedSpanContext(handed: InstrumentationTraceContext): SpanContext {
}
function resolveSessionTraceDecision(
- event: InstrumentationSessionStartedEvent,
+ event: SessionMetadata,
audience: ChannelAudience,
policy: TraceCapturePolicy | undefined,
): ReturnType<typeof resolveTracePolicy> {
diff --git a/packages/eve/src/tracing/agent-trace-context-store.ts b/packages/eve/src/tracing/agent-trace-context-store.ts
index 836335f9d..ae8a0134c 100644
--- a/packages/eve/src/tracing/agent-trace-context-store.ts
+++ b/packages/eve/src/tracing/agent-trace-context-store.ts
@@ -273,6 +273,7 @@ function deserializeState(data: unknown): AgentTraceContextState {
channelKind: typeof value.channelKind === "string" ? value.channelKind : undefined,
context: value.context,
decision: readInstrumentationDecision(value.decision),
+ parentLineage: deserializeParentLineage(value.parentLineage),
rootSessionId: typeof value.rootSessionId === "string" ? value.rootSessionId : "",
} satisfies AgentSessionTraceState;
});
@@ -285,6 +286,7 @@ function deserializeState(data: unknown): AgentTraceContextState {
context: value.context,
modelUsage: deserializeModelUsage(value.modelUsage),
parentIsRemote: typeof value.parentIsRemote === "boolean" ? value.parentIsRemote : undefined,
+ parentLineage: deserializeParentLineage(value.parentLineage),
parentSpanId: value.parentSpanId,
rootSessionId: typeof value.rootSessionId === "string" ? value.rootSessionId : "",
sequence: typeof value.sequence === "number" ? value.sequence : 0,
@@ -341,6 +343,23 @@ function deserializeAction(value: unknown): AgentActionTraceState | undefined {
};
}
+function deserializeParentLineage(value: unknown): AgentSessionTraceState["parentLineage"] {
+ if (
+ !isRecord(value) ||
+ typeof value.callId !== "string" ||
+ typeof value.sessionId !== "string" ||
+ typeof value.turnId !== "string"
+ ) {
+ return undefined;
+ }
+ return {
+ callId: value.callId,
+ sessionId: value.sessionId,
+ subagentName: typeof value.subagentName === "string" ? value.subagentName : undefined,
+ turnId: value.turnId,
+ };
+}
+
function isActionKind(value: unknown): value is AgentActionTraceState["kind"] {
return (
value === "load-skill" ||
diff --git a/packages/eve/src/tracing/agent-trace-state.ts b/packages/eve/src/tracing/agent-trace-state.ts
index cc4280e95..ba1f9742a 100644
--- a/packages/eve/src/tracing/agent-trace-state.ts
+++ b/packages/eve/src/tracing/agent-trace-state.ts
@@ -2,6 +2,7 @@ import type { SpanContext } from "#compiled/@opentelemetry/api/index.js";
import type {
InstrumentationActionKind,
+ InstrumentationParentLineage,
InstrumentationTraceContext,
InstrumentationTurnFailedEvent,
InstrumentationTurnSettledEvent,
@@ -15,11 +16,13 @@ export interface AgentSessionTraceState {
readonly channelKind?: string;
readonly context: SpanContext;
readonly decision?: InstrumentationDecision;
+ readonly parentLineage?: InstrumentationParentLineage;
readonly rootSessionId: string;
}
export interface AgentTurnTraceState {
readonly context: SpanContext;
+ readonly parentLineage?: InstrumentationParentLineage;
readonly modelUsage?: { readonly inputTokens?: number; readonly outputTokens?: number };
readonly parentIsRemote?: boolean;
readonly parentSpanId: string;
diff --git a/packages/eve/src/tracing/conversation-context.test.ts b/packages/eve/src/tracing/conversation-context.test.ts
new file mode 100644
index 000000000..c8e578ba2
--- /dev/null
+++ b/packages/eve/src/tracing/conversation-context.test.ts
@@ -0,0 +1,53 @@
+import { describe, expect, it } from "vitest";
+import { ContextContainer, contextStorage } from "#context/container.js";
+import { ConversationIdKey } from "#context/keys.js";
+import {
+ readConversationBaggage,
+ readConversationId,
+ resolveConversationId,
+ writeConversationBaggage,
+} from "#tracing/conversation-context.js";
+
+describe("conversation correlation", () => {
+ it("round-trips correlation independently of policy baggage", () => {
+ const baggage = writeConversationBaggage("eve.audience=private;ceiling=i0o0", "root/session");
+ expect(readConversationBaggage(baggage!)).toBe("root/session");
+ expect(baggage).toContain("eve.audience=private;ceiling=i0o0");
+ });
+
+ it("rejects malformed, duplicate, oversized, and unsafe identifiers", () => {
+ expect(readConversationBaggage("eve.conversation.id")).toBeUndefined();
+ expect(readConversationBaggage("eve.conversation.id=%ZZ")).toBeUndefined();
+ expect(readConversationBaggage("eve.conversation.id=a,eve.conversation.id=b")).toBeUndefined();
+ expect(readConversationId("a".repeat(1025))).toBeUndefined();
+ expect(readConversationId("a\nb")).toBeUndefined();
+ expect(readConversationId("\ud800")).toBeUndefined();
+ });
+
+ it.each(["\u0000", "\u001f", "\u007f", "\u0080", "\u009f", "\u2028", "\u2029"])(
+ "rejects control or line-separator %j even when percent-encoded",
+ (character) => {
+ expect(readConversationId(`before${character}after`)).toBeUndefined();
+ expect(
+ readConversationBaggage(`eve.conversation.id=${encodeURIComponent(character)}`),
+ ).toBeUndefined();
+ },
+ );
+
+ it("leaves configured baggage unchanged when no valid replacement is available", () => {
+ const baggage = "vendor=value, eve.conversation.id=operator";
+ expect(writeConversationBaggage(baggage, undefined)).toBe(baggage);
+ expect(writeConversationBaggage(baggage, "\n")).toBe(baggage);
+ expect(writeConversationBaggage(baggage, "session")).toBe(
+ "vendor=value,eve.conversation.id=session",
+ );
+ });
+
+ it("does not derive an established conversation from privileged lineage", () => {
+ const ctx = new ContextContainer();
+ ctx.set(ConversationIdKey, "original-conversation");
+ contextStorage.run(ctx, () => {
+ expect(resolveConversationId("independent-remote-root")).toBe("original-conversation");
+ });
+ });
+});
diff --git a/packages/eve/src/tracing/conversation-context.ts b/packages/eve/src/tracing/conversation-context.ts
new file mode 100644
index 000000000..6adc5fd43
--- /dev/null
+++ b/packages/eve/src/tracing/conversation-context.ts
@@ -0,0 +1,44 @@
+import { contextStorage } from "#context/container.js";
+import { ConversationIdKey } from "#context/keys.js";
+import { readBaggageMember, replaceBaggageMember } from "#protocol/baggage.js";
+
+const BAGGAGE_KEY = "eve.conversation.id";
+const MAX_ID_BYTES = 1024;
+const encoder = new TextEncoder();
+
+export function readConversationId(value: unknown): string | undefined {
+ if (
+ typeof value !== "string" ||
+ value.length === 0 ||
+ value.length > MAX_ID_BYTES ||
+ // oxlint-disable-next-line no-control-regex -- Indexed correlation IDs must not contain controls or line separators.
+ /[\u0000-\u001f\u007f-\u009f\u2028\u2029]/u.test(value) ||
+ encoder.encode(value).byteLength > MAX_ID_BYTES
+ )
+ return undefined;
+ try {
+ encodeURIComponent(value);
+ return value;
+ } catch {
+ return undefined;
+ }
+}
+
+export function resolveConversationId(fallback: string): string {
+ return readConversationId(contextStorage.getStore()?.get(ConversationIdKey)) ?? fallback;
+}
+
+export function readConversationBaggage(value: string | null): string | undefined {
+ const member = readBaggageMember(value, BAGGAGE_KEY);
+ return typeof member === "string" ? undefined : readConversationId(member.value);
+}
+
+export function writeConversationBaggage(
+ value: string | undefined,
+ conversationId: string | undefined,
+): string | undefined {
+ const id = readConversationId(conversationId);
+ return id === undefined
+ ? value
+ : replaceBaggageMember(value, BAGGAGE_KEY, encodeURIComponent(id));
+}