Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

fix(eve): preserve remote dispatch caller through ingress (#3299)

Chad Hietalaa34ecf026b58
diff --git a/.changeset/preserve-remote-dispatch-caller.md b/.changeset/preserve-remote-dispatch-caller.md
new file mode 100644
index 000000000..b809a7507
--- /dev/null
+++ b/.changeset/preserve-remote-dispatch-caller.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Preserve remote subagent caller spans across platform HTTP ingress so schema v4 `agent.dispatch` links target the dispatching `agent.action` rather than the request span. Remote dispatch now records the prior eve parent in W3C `tracestate` while retaining standard `traceparent` transport correlation.
diff --git a/docs/guides/instrumentation.md b/docs/guides/instrumentation.md
index 5ff98c1ea..97056051a 100644
--- a/docs/guides/instrumentation.md
+++ b/docs/guides/instrumentation.md
@@ -207,8 +207,10 @@ A conversation remains durable state; `gen_ai.conversation.id` joins the activat
Each activation owns a fresh trace identity, including local and remote
subagents. The first child activation links to its caller with
-`eve.link.type=agent.dispatch`; incoming `traceparent` provides that link, not
-the child trace ID. Later turns do not reuse the original caller link.
+`eve.link.type=agent.dispatch`; remote dispatch preserves that caller separately
+in W3C `tracestate` while HTTP intermediaries update `traceparent`. Older peers
+fall back to the incoming transport context. Later turns do not reuse the
+original caller link.
Conversation baggage is independent of execution lineage and trace-policy
ceilings, which remain in force across the boundary.
@@ -288,7 +290,7 @@ invoke_agent support session=S, turn=turn_1, conversation=S
The conversation filter finds all three retained traces. eve initializes the conversation ID once and carries it through the existing parent context for local dispatch and `eve.conversation.id` baggage for remote dispatch. Remote session creation does not carry execution lineage or add authorization requirements for tracing. Existing authentication, principal forwarding, and root-session limits remain unchanged.
-`traceparent` carries the caller's trace and span IDs for the causal link; adopting it as the child's parent would instead keep both in the same trace. Resolved trace-policy decisions and trusted remote content ceilings continue across this boundary independently of correlation, and an unsampled caller cannot be widened into a sampled child. No synthetic session span is needed.
+Remote dispatch records the caller's span ID in eve's W3C `tracestate` entry because HTTP intermediaries may advance `traceparent` to their own request span. The receiver combines that prior parent with the current trace identity for the causal link and retains the transport context for `channel.request`; adopting either as the child's parent would instead keep both in the same trace. Resolved trace-policy decisions and trusted remote content ceilings continue across this boundary independently of correlation, and an unsampled caller cannot be widened into a sampled child. No synthetic session span is needed.
Activation duration is elapsed time for that activation, including waits inside it, not the lifetime of the conversation or CPU time. Idle time between ended activations is not part of their durations. For token totals, choose one level: filter to `chat` model spans and sum `gen_ai.usage.*`, or filter to activations and sum their `agent.usage.input_tokens` and `agent.usage.output_tokens`. Exclude caller summaries from the activation total. Query cache usage on model spans. Do not add model, step, activation, and caller counters together.
diff --git a/docs/guides/remote-agents.md b/docs/guides/remote-agents.md
index fd75ecc4a..cc94f203b 100644
--- a/docs/guides/remote-agents.md
+++ b/docs/guides/remote-agents.md
@@ -139,16 +139,16 @@ 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.
+Remote tracing uses [W3C Trace Context](https://www.w3.org/TR/trace-context/). `traceparent` identifies the immediate HTTP parent, while eve's `eve=<caller-span-id>` vendor entry in `tracestate` preserves the dispatching caller when an intermediary advances `traceparent` to its own request span. The receiver uses the eve entry for the child's `agent.dispatch` link and the transport context for request correlation. Older senders and missing or malformed eve entries fall back to `traceparent`. 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. Session execution establishes this ID even without an instrumentation runtime. 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. If adding an audience assertion or conversation ID would exceed 8 KiB, eve rejects the dispatch before sending a request instead of dropping the member. Reduce `remote.headers.baggage` to leave room for these framework values.
+eve replaces configured `traceparent` and conversation baggage only when it has a framework value to send. It replaces its own `tracestate` entry while preserving other valid vendor entries; without a valid caller context, eve removes only its entry. 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. If adding an audience assertion or conversation ID would exceed 8 KiB, eve rejects the dispatch before sending a request instead of dropping the member. Reduce `remote.headers.baggage` to leave room for these framework values.
In the [provider trace contract](./instrumentation#agent-trace-contract), each
-child activation starts a separate trace. The first activation uses the incoming
-`traceparent` as an `agent.dispatch` span link rather than adopting the caller's
-trace ID.
+child activation starts a separate trace. The first activation uses the
+caller preserved in W3C `tracestate`, falling back to incoming `traceparent`,
+as an `agent.dispatch` span link rather than adopting the caller's trace ID.
> ⚠️ **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.
diff --git a/docs/reference/cli.md b/docs/reference/cli.md
index acd7e3c48..5f9ecc991 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.
-Every subagent activation starts its own trace. The first child's `invoke_agent` root links to the dispatching caller with `eve.link.type=agent.dispatch`; remote agents carry that caller context over `traceparent`. Later turns also start fresh traces without repeating the initial caller link. All related sessions retain the same `gen_ai.conversation.id`, and `agent.subagent.name` labels the child invocation.
+Every subagent activation starts its own trace. The first child's `invoke_agent` root links to the dispatching caller with `eve.link.type=agent.dispatch`; remote agents preserve that caller in W3C `tracestate` even when HTTP `traceparent` advances through platform ingress. Later turns also start fresh traces without repeating the initial caller link. All related sessions retain the same `gen_ai.conversation.id`, and `agent.subagent.name` labels the child invocation.
Each `agent()` call inside an authored workflow has its own `agent.action` caller span, including sequential, parallel, and background calls. A workflow tool that coordinates one of those calls has an enclosing `invoke_workflow <tool>` span; a workflow tool without agent calls remains `agent.action`. The tool also keeps its `execute_tool <tool>` span. Only agent execution uses `invoke_agent`.
diff --git a/packages/eve/scripts/vendor-compiled/declarations/@opentelemetry/api.d.ts b/packages/eve/scripts/vendor-compiled/declarations/@opentelemetry/api.d.ts
index 0089b87a2..d31678b68 100644
--- a/packages/eve/scripts/vendor-compiled/declarations/@opentelemetry/api.d.ts
+++ b/packages/eve/scripts/vendor-compiled/declarations/@opentelemetry/api.d.ts
@@ -5,6 +5,8 @@ export interface TraceState {
unset(key: string): TraceState;
}
+export declare function createTraceState(rawTraceState?: string): TraceState;
+
export interface SpanContext {
isRemote?: boolean;
spanId: string;
diff --git a/packages/eve/src/eve-channel/index.ts b/packages/eve/src/eve-channel/index.ts
index d475d3f09..68af40935 100644
--- a/packages/eve/src/eve-channel/index.ts
+++ b/packages/eve/src/eve-channel/index.ts
@@ -48,7 +48,7 @@ import type { CancelTurnResponse } from "#protocol/cancel-turn.js";
import type { ClearResponse } from "#protocol/clear-session.js";
import type { CompactResponse } from "#protocol/compact-session.js";
import type { ResetResponse } from "#protocol/reset-session.js";
-import { parseTraceparent } from "#protocol/traceparent.js";
+import { parseTraceparent, readAgentDispatchTraceContext } from "#protocol/traceparent.js";
import { readForwardedAudienceBaggage } from "#protocol/baggage.js";
import { readConversationBaggage } from "#tracing/conversation-context.js";
import {
@@ -151,10 +151,17 @@ export function eveChannel(input: EveChannelInput): EveChannel {
const body = parseCreateBody(payload);
if (body instanceof Response) return body;
- const parsedParentTraceContext =
+ const transportParentTraceContext =
body.callback === undefined
? undefined
: parseTraceparent(req.headers.get("traceparent"));
+ const parsedParentTraceContext =
+ body.callback === undefined
+ ? undefined
+ : (readAgentDispatchTraceContext(
+ req.headers.get("tracestate"),
+ transportParentTraceContext,
+ ) ?? transportParentTraceContext);
const policyRejection = checkUploadPolicy(body, uploadPolicy);
if (policyRejection !== null) return policyRejection;
@@ -189,13 +196,13 @@ export function eveChannel(input: EveChannelInput): EveChannel {
}
const forwardedTraceAssertion =
- parsedParentTraceContext === undefined
+ transportParentTraceContext === undefined
? "absent"
: readForwardedAudienceBaggage(req.headers.get("baggage"));
const acceptsForwardedTracePolicy =
forwarded.accepted &&
- parsedParentTraceContext !== undefined &&
- (parsedParentTraceContext.traceFlags & 1) === 1;
+ transportParentTraceContext !== undefined &&
+ (transportParentTraceContext.traceFlags & 1) === 1;
const acceptedForwardedTracePolicy = !acceptsForwardedTracePolicy
? undefined
: typeof forwardedTraceAssertion === "object"
diff --git a/packages/eve/src/protocol/traceparent.test.ts b/packages/eve/src/protocol/traceparent.test.ts
index bc5c20189..2cff92caf 100644
--- a/packages/eve/src/protocol/traceparent.test.ts
+++ b/packages/eve/src/protocol/traceparent.test.ts
@@ -1,6 +1,11 @@
import { describe, expect, it } from "vitest";
-import { formatTraceparent, parseTraceparent } from "#protocol/traceparent.js";
+import {
+ formatTraceparent,
+ parseTraceparent,
+ readAgentDispatchTraceContext,
+ writeAgentDispatchTracestate,
+} from "#protocol/traceparent.js";
const TRACE_ID = "1".repeat(32);
const SPAN_ID = "2".repeat(16);
@@ -38,3 +43,61 @@ describe("traceparent", () => {
).toBeUndefined();
});
});
+
+describe("agent dispatch tracestate", () => {
+ const transport = {
+ isRemote: true,
+ spanId: "3".repeat(16),
+ traceFlags: 1,
+ traceId: TRACE_ID,
+ } as const;
+
+ it("preserves and restores the prior eve parent", () => {
+ const value = writeAgentDispatchTracestate("vendor=opaque", {
+ spanId: SPAN_ID,
+ traceFlags: 1,
+ traceId: TRACE_ID,
+ });
+ expect(value).toBe(`eve=${SPAN_ID},vendor=opaque`);
+ expect(readAgentDispatchTraceContext(value!, transport)).toEqual({
+ ...transport,
+ spanId: SPAN_ID,
+ });
+ });
+
+ it("removes authored eve state without a valid caller", () => {
+ expect(writeAgentDispatchTracestate(`eve=${SPAN_ID},vendor=opaque`, undefined)).toBe(
+ "vendor=opaque",
+ );
+ });
+
+ it.each([null, "vendor=opaque", "eve=malformed", "eve=0000000000000000"])(
+ "ignores unusable state %p",
+ (value) => {
+ expect(readAgentDispatchTraceContext(value, transport)).toBeUndefined();
+ },
+ );
+ it("requires the transport trace identity", () => {
+ expect(readAgentDispatchTraceContext(`eve=${SPAN_ID}`, undefined)).toBeUndefined();
+ });
+
+ it("evicts the least-recent member to retain W3C entry limits", () => {
+ const value = writeAgentDispatchTracestate(
+ Array.from({ length: 32 }, (_, index) => `v${index}=a`).join(","),
+ { spanId: SPAN_ID, traceFlags: 1, traceId: TRACE_ID },
+ )!;
+ expect(value.split(",")).toHaveLength(32);
+ expect(value.startsWith(`eve=${SPAN_ID},v0=a`)).toBe(true);
+ expect(value).not.toContain("v31=a");
+ });
+
+ it("evicts the least-recent member to retain the W3C length limit", () => {
+ const value = writeAgentDispatchTracestate(
+ Array.from({ length: 20 }, (_, index) => `v${index}=${"a".repeat(21)}`).join(","),
+ { spanId: SPAN_ID, traceFlags: 1, traceId: TRACE_ID },
+ )!;
+ expect(value.length).toBeLessThanOrEqual(512);
+ expect(value.startsWith(`eve=${SPAN_ID},v0=`)).toBe(true);
+ expect(value).not.toContain("v19=");
+ });
+});
diff --git a/packages/eve/src/protocol/traceparent.ts b/packages/eve/src/protocol/traceparent.ts
index 26debde84..e7d2861c9 100644
--- a/packages/eve/src/protocol/traceparent.ts
+++ b/packages/eve/src/protocol/traceparent.ts
@@ -1,3 +1,5 @@
+import { createTraceState, type TraceState } from "#compiled/@opentelemetry/api/index.js";
+
export interface TraceparentContext {
readonly isRemote?: boolean;
readonly spanId: string;
@@ -6,6 +8,10 @@ export interface TraceparentContext {
}
const TRACEPARENT_PATTERN = /^00-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/iu;
+const EVE_TRACESTATE_KEY = "eve";
+const EVE_DISPATCH_PARENT_PATTERN = /^([0-9a-f]{16})$/u;
+const MAX_TRACESTATE_ENTRIES = 32;
+const MAX_TRACESTATE_LENGTH = 512;
/** Formats a W3C version-00 traceparent, or omits an invalid context. */
export function formatTraceparent(context: TraceparentContext | undefined): string | undefined {
@@ -38,6 +44,53 @@ export function parseTraceparent(value: string | null): TraceparentContext | und
};
}
+/**
+ * Restores the eve caller span preserved in W3C `tracestate`.
+ *
+ * `traceparent` remains the immediate HTTP parent, so its trace identity and
+ * flags stay authoritative while eve's vendor entry supplies the earlier
+ * semantic caller span ID.
+ */
+export function readAgentDispatchTraceContext(
+ value: string | null,
+ transport: TraceparentContext | undefined,
+): TraceparentContext | undefined {
+ if (value === null || transport === undefined) return undefined;
+ const encoded = createTraceState(value).get(EVE_TRACESTATE_KEY);
+ const match = encoded === undefined ? null : EVE_DISPATCH_PARENT_PATTERN.exec(encoded);
+ const spanId = match?.[1];
+ return spanId === undefined || !validId(spanId, 16) ? undefined : { ...transport, spanId };
+}
+
+/**
+ * Writes eve's prior-parent vendor entry while preserving other valid
+ * `tracestate` members and W3C size limits.
+ */
+export function writeAgentDispatchTracestate(
+ value: string | undefined,
+ context: TraceparentContext | undefined,
+): string | undefined {
+ const state = createTraceState(value);
+ if (context === undefined || formatTraceparent(context) === undefined) {
+ return boundedTracestate(state.unset(EVE_TRACESTATE_KEY));
+ }
+ return boundedTracestate(state.set(EVE_TRACESTATE_KEY, context.spanId.toLowerCase()));
+}
+
+function boundedTracestate(initial: TraceState): string | undefined {
+ let state = initial;
+ let serialized = state.serialize();
+ let entries = serialized.split(",").filter(Boolean);
+ while (entries.length > MAX_TRACESTATE_ENTRIES || serialized.length > MAX_TRACESTATE_LENGTH) {
+ const last = entries.at(-1);
+ if (last === undefined) return undefined;
+ state = state.unset(last.slice(0, last.indexOf("=")));
+ serialized = state.serialize();
+ entries = serialized.split(",").filter(Boolean);
+ }
+ return serialized || undefined;
+}
+
function validId(value: string, length: number): boolean {
return value.length === length && /^[0-9a-f]+$/iu.test(value) && !/^0+$/u.test(value);
}
diff --git a/packages/eve/src/public/channels/eve-forwarded-principal.integration.test.ts b/packages/eve/src/public/channels/eve-forwarded-principal.integration.test.ts
index 191032dc4..9c21d2978 100644
--- a/packages/eve/src/public/channels/eve-forwarded-principal.integration.test.ts
+++ b/packages/eve/src/public/channels/eve-forwarded-principal.integration.test.ts
@@ -136,7 +136,8 @@ describe("eveChannel forwarded principal → runtime principal", () => {
headers: {
"content-type": "application/json",
baggage: "vendor=value,eve.audience=private;ceiling=i1o0",
- traceparent: `00-${"1".repeat(32)}-${"2".repeat(16)}-01`,
+ tracestate: `eve=${"2".repeat(16)}`,
+ traceparent: `00-${"1".repeat(32)}-${"3".repeat(16)}-01`,
},
method: "POST",
}),
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 4329aeb61..c001a5e24 100644
--- a/packages/eve/src/public/channels/eve-session-routes.test.ts
+++ b/packages/eve/src/public/channels/eve-session-routes.test.ts
@@ -133,6 +133,89 @@ describe("eve ID-addressed session routes", () => {
);
});
+ it("preserves the dispatch caller when the transport trace advances through ingress", async () => {
+ const createSession = vi.fn().mockResolvedValue({
+ events: new ReadableStream(),
+ sessionId: "wrun_A",
+ });
+ const args = attachRouteSessionCreator(createArgs(), createSession);
+
+ const response = await route("POST", "/eve/v1/session")(
+ new Request("https://eve.test/eve/v1/session", {
+ body: JSON.stringify({
+ callback: {
+ callId: "call-1",
+ subagentName: "research",
+ token: "tok123",
+ url: "https://caller.example.com/eve/v1/callback/tok123",
+ },
+ message: "hello",
+ mode: "conversation",
+ }),
+ headers: {
+ "content-type": "application/json",
+ tracestate: `eve=${"2".repeat(16)}`,
+ traceparent: `00-${"1".repeat(32)}-${"3".repeat(16)}-01`,
+ },
+ method: "POST",
+ }),
+ args,
+ );
+
+ expect(response.status).toBe(202);
+ expect(createSession).toHaveBeenCalledWith(
+ expect.objectContaining({
+ parentTraceContext: {
+ isRemote: true,
+ spanId: "2".repeat(16),
+ traceFlags: 1,
+ traceId: "1".repeat(32),
+ },
+ }),
+ );
+ });
+
+ it("falls back to transport correlation when the dispatch tracestate entry is malformed", async () => {
+ const createSession = vi.fn().mockResolvedValue({
+ events: new ReadableStream(),
+ sessionId: "wrun_A",
+ });
+ const args = attachRouteSessionCreator(createArgs(), createSession);
+
+ const response = await route("POST", "/eve/v1/session")(
+ new Request("https://eve.test/eve/v1/session", {
+ body: JSON.stringify({
+ callback: {
+ callId: "call-1",
+ subagentName: "research",
+ token: "tok123",
+ url: "https://caller.example.com/eve/v1/callback/tok123",
+ },
+ message: "hello",
+ }),
+ headers: {
+ "content-type": "application/json",
+ tracestate: "eve=malformed",
+ traceparent: `00-${"1".repeat(32)}-${"3".repeat(16)}-01`,
+ },
+ method: "POST",
+ }),
+ args,
+ );
+
+ expect(response.status).toBe(202);
+ expect(createSession).toHaveBeenCalledWith(
+ expect.objectContaining({
+ parentTraceContext: {
+ isRemote: true,
+ spanId: "3".repeat(16),
+ traceFlags: 1,
+ traceId: "1".repeat(32),
+ },
+ }),
+ );
+ });
+
it.each([true, false])(
"accepts trace correlation only with a callback (%s)",
async (callback) => {
@@ -162,6 +245,7 @@ describe("eve ID-addressed session routes", () => {
headers: {
"content-type": "application/json",
baggage: "eve.conversation.id=original-conversation",
+ tracestate: `eve=${"3".repeat(16)}`,
traceparent: `00-${"1".repeat(32)}-${"2".repeat(16)}-01`,
},
method: "POST",
@@ -181,7 +265,7 @@ describe("eve ID-addressed session routes", () => {
parentTraceContext: callback
? {
isRemote: true,
- spanId: "2".repeat(16),
+ spanId: "3".repeat(16),
traceFlags: 1,
traceId: "1".repeat(32),
}
diff --git a/packages/eve/src/subagents/remote-dispatch.test.ts b/packages/eve/src/subagents/remote-dispatch.test.ts
index 82a96215d..7438f0bae 100644
--- a/packages/eve/src/subagents/remote-dispatch.test.ts
+++ b/packages/eve/src/subagents/remote-dispatch.test.ts
@@ -232,6 +232,7 @@ describe("startRemoteAgentSession", () => {
...createRemoteAgent(),
headers: {
Traceparent: "operator-context",
+ Tracestate: `eve=${"a".repeat(16)},vendor=opaque`,
baggage: "eve.conversation.id=operator-id,vendor=value",
},
},
@@ -252,6 +253,9 @@ describe("startRemoteAgentSession", () => {
expect(headers.get("traceparent")).toBe(
hasContext ? `00-${"1".repeat(32)}-${"2".repeat(16)}-01` : "operator-context",
);
+ expect(headers.get("tracestate")).toBe(
+ hasContext ? `eve=${"2".repeat(16)},vendor=opaque` : "vendor=opaque",
+ );
expect(headers.get("baggage")).toBe(
hasContext
? "vendor=value,eve.conversation.id=logical-conversation"
@@ -310,6 +314,7 @@ describe("startRemoteAgentSession", () => {
headers: {
authorization: "Bearer remote-token",
"content-type": "application/json",
+ tracestate: `eve=${"2".repeat(16)}`,
traceparent: `00-${"1".repeat(32)}-${"2".repeat(16)}-01`,
"x-static": "yes",
},
diff --git a/packages/eve/src/subagents/remote-dispatch.ts b/packages/eve/src/subagents/remote-dispatch.ts
index b037543fc..77a606430 100644
--- a/packages/eve/src/subagents/remote-dispatch.ts
+++ b/packages/eve/src/subagents/remote-dispatch.ts
@@ -19,7 +19,7 @@ import type { ForwardedPrincipal } from "#channel/forwarded-principal.js";
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 { formatTraceparent, writeAgentDispatchTracestate } from "#protocol/traceparent.js";
import {
formatSubagentInput,
normalizeRequestedOutputSchema,
@@ -133,6 +133,11 @@ export async function startRemoteAgentSession(input: {
const headers = await resolveRemoteAgentRequestHeaders(input.remote);
const traceparent = formatTraceparent(input.parent?.traceContext);
if (traceparent !== undefined) setHeader(headers, "traceparent", traceparent);
+ setHeader(
+ headers,
+ "tracestate",
+ writeAgentDispatchTracestate(readHeader(headers, "tracestate"), input.parent?.traceContext),
+ );
const baggage = writeForwardedAudienceBaggage(
readHeader(headers, "baggage"),
buildForwardedTraceAssertion({