Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat(eve): correlate Gateway calls with agent conversations (#3861)

Chad Hietalaaaea9b6b768f
diff --git a/.changeset/gateway-conversation-session-id.md b/.changeset/gateway-conversation-session-id.md
new file mode 100644
index 000000000..dc048e954
--- /dev/null
+++ b/.changeset/gateway-conversation-session-id.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Send the Agent Runs conversation ID as the AI Gateway session ID for model and compaction calls, so Gateway generations from one conversation can be grouped together. Preserve an explicitly configured Gateway session ID.
diff --git a/docs/agent-config.md b/docs/agent-config.md
index 00099718a..aaa3554bc 100644
--- a/docs/agent-config.md
+++ b/docs/agent-config.md
@@ -60,6 +60,13 @@ at either provider path takes precedence and is forwarded unchanged. When
`auth.current` is `null`, eve does not add an identifier. The same rules apply
to compaction calls.
+For AI Gateway model calls, eve sets `providerOptions.gateway.sessionId` to the
+`gen_ai.conversation.id` used by Agent Runs. By default, all turns in a
+conversation, including delegated subagents and compaction calls routed through
+Gateway, share that ID so their Gateway generations can be found together.
+Direct-provider calls do not receive the option. An authored `gateway.sessionId`
+takes precedence; AI Gateway hashes IDs longer than 256 characters.
+
### Choose the model dynamically
To select a model from the incoming prompt with an AI SDK evaluation model, use
diff --git a/packages/eve/src/execution/runtime-context.ts b/packages/eve/src/execution/runtime-context.ts
index a71d47788..a41c238f0 100644
--- a/packages/eve/src/execution/runtime-context.ts
+++ b/packages/eve/src/execution/runtime-context.ts
@@ -23,7 +23,7 @@ import {
import { deriveSessionTitle } from "#execution/eve-workflow-attributes.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";
+import { readConversationId } from "#shared/conversation-identity.js";
import { buildConversationContext } from "#channel/conversation-context.js";
import { ConversationContextKey } from "#shared/conversation-context.js";
import { resolveInstrumentationEnvironment } from "#internal/application/dev-environment.js";
diff --git a/packages/eve/src/execution/tools/subagent/start.ts b/packages/eve/src/execution/tools/subagent/start.ts
index c8a2df430..a85b20914 100644
--- a/packages/eve/src/execution/tools/subagent/start.ts
+++ b/packages/eve/src/execution/tools/subagent/start.ts
@@ -14,7 +14,7 @@ import { startRemoteSubagent } from "#subagents/start-remote.js";
import { buildSubagentRunInput, type SubagentInputSource } from "#subagents/tool.js";
import type { SubagentParentContext } from "#subagents/invocation.js";
import type { AgentChildTraceDispatch } from "#tracing/agent-invocation-coordinator.js";
-import { resolveConversationId } from "#tracing/conversation-context.js";
+import { resolveConversationId } from "#shared/conversation-identity.js";
export type SubagentStartTarget =
| {
diff --git a/packages/eve/src/harness/provider-safety.ts b/packages/eve/src/harness/provider-safety.ts
index 3f4e1de99..334b73764 100644
--- a/packages/eve/src/harness/provider-safety.ts
+++ b/packages/eve/src/harness/provider-safety.ts
@@ -1,4 +1,6 @@
+import type { LanguageModel } from "ai";
import type { SessionAuthContext } from "#channel/types.js";
+import { mergeGatewaySessionId } from "#internal/gateway.js";
import { invocationOwnerKey } from "#internal/invocation/metadata.js";
import type { RuntimeModelReference } from "#runtime/agent/bootstrap.js";
import { mergeObjects } from "#shared/objects.js";
@@ -27,3 +29,18 @@ export function mergeProviderSafetyIdentifier(
return defaults === undefined ? providerOptions : mergeObjects(defaults, providerOptions);
}
+
+/** Composes the per-call defaults shared by model steps and compaction. */
+export function resolveCallProviderOptions(input: {
+ readonly auth: SessionAuthContext | null;
+ readonly conversationId: string;
+ readonly model: LanguageModel;
+ readonly modelReference: RuntimeModelReference;
+ readonly providerOptions: Readonly<Record<string, unknown>> | undefined;
+}): Record<string, unknown> | undefined {
+ return mergeGatewaySessionId(
+ input.model,
+ mergeProviderSafetyIdentifier(input.modelReference, input.providerOptions, input.auth),
+ input.conversationId,
+ );
+}
diff --git a/packages/eve/src/harness/step-hooks.test.ts b/packages/eve/src/harness/step-hooks.test.ts
index b07c8b729..17fa13a47 100644
--- a/packages/eve/src/harness/step-hooks.test.ts
+++ b/packages/eve/src/harness/step-hooks.test.ts
@@ -1,5 +1,8 @@
-import type { ModelMessage } from "ai";
+import type { LanguageModel, ModelMessage } from "ai";
+import { MockLanguageModelV3 } from "ai/test";
import { describe, expect, it, vi } from "vitest";
+import { ContextContainer, contextStorage } from "#context/container.js";
+import { ConversationIdKey } from "#context/keys.js";
import { buildStepHooks } from "#harness/step-hooks.js";
import type { HarnessEmissionState } from "#harness/emission.js";
import type { HarnessSession } from "#harness/types.js";
@@ -62,4 +65,107 @@ describe("buildStepHooks", () => {
messages,
);
});
+
+ it("sends the trace conversation ID to Gateway without changing direct-provider options", async () => {
+ const session: HarnessSession = {
+ ...createSession(),
+ rootSessionId: "root-session",
+ agent: {
+ ...createSession().agent,
+ modelReference: {
+ id: "anthropic/claude-sonnet-4-5",
+ providerOptions: { gateway: { order: ["bedrock"] }, openai: { store: false } },
+ },
+ },
+ };
+ const context = new ContextContainer();
+ context.set(ConversationIdKey, "forwarded-conversation");
+ const prepare = (
+ model: LanguageModel,
+ cachePath: Parameters<typeof buildStepHooks>[0]["cachePath"],
+ ) =>
+ buildStepHooks({ emissionState, marker: undefined, cachePath, session }).prepareStep({
+ messages: [],
+ model,
+ instructions: undefined,
+ initialInstructions: undefined,
+ initialMessages: [],
+ responseMessages: [],
+ runtimeContext: {},
+ toolsContext: {},
+ experimental_sandbox: undefined,
+ stepNumber: 0,
+ steps: [],
+ });
+
+ await contextStorage.run(context, async () => {
+ expect(
+ (await prepare("anthropic/claude-sonnet-4-5", { kind: "gateway-auto" }))?.providerOptions,
+ ).toEqual({
+ gateway: { caching: "auto", order: ["bedrock"], sessionId: "forwarded-conversation" },
+ openai: { store: false },
+ });
+ expect(
+ (
+ await prepare(
+ new MockLanguageModelV3({
+ modelId: "anthropic/claude-sonnet-4-5",
+ provider: "gateway.language-model",
+ }),
+ { kind: "gateway-auto" },
+ )
+ )?.providerOptions,
+ ).toEqual({
+ gateway: { caching: "auto", order: ["bedrock"], sessionId: "forwarded-conversation" },
+ openai: { store: false },
+ });
+ expect(
+ (
+ await prepare(
+ new MockLanguageModelV3({
+ modelId: "claude-sonnet-4-5",
+ provider: "anthropic.messages",
+ }),
+ { kind: "none" },
+ )
+ )?.providerOptions,
+ ).toEqual({
+ gateway: { order: ["bedrock"] },
+ openai: { store: false },
+ });
+ });
+ });
+
+ it("preserves an authored Gateway session ID", async () => {
+ const hooks = buildStepHooks({
+ cachePath: { kind: "none" },
+ emissionState,
+ marker: undefined,
+ session: {
+ ...createSession(),
+ agent: {
+ ...createSession().agent,
+ modelReference: {
+ id: "anthropic/claude-sonnet-4-5",
+ providerOptions: { gateway: { sessionId: "authored-session" } },
+ },
+ },
+ },
+ });
+
+ const prepared = await hooks.prepareStep({
+ messages: [],
+ model: "anthropic/claude-sonnet-4-5",
+ instructions: undefined,
+ initialInstructions: undefined,
+ initialMessages: [],
+ responseMessages: [],
+ runtimeContext: {},
+ toolsContext: {},
+ experimental_sandbox: undefined,
+ stepNumber: 0,
+ steps: [],
+ });
+ expect(prepared?.providerOptions).toEqual({ gateway: { sessionId: "authored-session" } });
+ });
});
diff --git a/packages/eve/src/harness/step-hooks.ts b/packages/eve/src/harness/step-hooks.ts
index 325b01ad8..5552872ac 100644
--- a/packages/eve/src/harness/step-hooks.ts
+++ b/packages/eve/src/harness/step-hooks.ts
@@ -32,7 +32,7 @@ import {
mergeGatewayAutoCaching,
type PromptCachePath,
} from "#harness/prompt-cache.js";
-import { mergeProviderSafetyIdentifier } from "#harness/provider-safety.js";
+import { resolveCallProviderOptions } from "#harness/provider-safety.js";
import {
collectActionPresentation,
createPresentedRuntimeActionRequestFromToolCall,
@@ -49,6 +49,7 @@ import { contextStorage } from "#context/container.js";
import { isAuthorizationSignal, isPendingAuthorizationToolOutput } from "#harness/authorization.js";
import { readToolInterrupt } from "#harness/tool-interrupts.js";
import { AuthKey } from "#context/keys.js";
+import { resolveConversationId } from "#shared/conversation-identity.js";
// ---------------------------------------------------------------------------
// Step result type
@@ -174,7 +175,7 @@ export function buildStepHooks(input: StepHooksInput): StepHooks {
// session history — no prepareStep snapshot required.
// -------------------------------------------------------------------------
- const prepareStep: PrepareStepFunction<ToolSet> = async ({ messages }) => {
+ const prepareStep: PrepareStepFunction<ToolSet> = async ({ messages, model }) => {
let processed = messages;
if (input.cachePath.kind === "anthropic-direct" && input.marker) {
@@ -186,11 +187,13 @@ export function buildStepHooks(input: StepHooksInput): StepHooks {
};
const modelReference = requireSessionModelReference(session);
- const providerOptions = mergeProviderSafetyIdentifier(
+ const providerOptions = resolveCallProviderOptions({
+ auth: input.auth ?? contextStorage.getStore()?.get(AuthKey) ?? null,
+ conversationId: resolveConversationId(session.rootSessionId ?? session.sessionId),
+ model,
modelReference,
- modelReference.providerOptions,
- input.auth ?? contextStorage.getStore()?.get(AuthKey) ?? null,
- );
+ providerOptions: modelReference.providerOptions,
+ });
if (input.cachePath.kind === "gateway-auto") {
stepResult.providerOptions = mergeGatewayAutoCaching(providerOptions) as NonNullable<
typeof stepResult.providerOptions
diff --git a/packages/eve/src/harness/tool-loop.test.ts b/packages/eve/src/harness/tool-loop.test.ts
index 0c11f35b9..ec85627e0 100644
--- a/packages/eve/src/harness/tool-loop.test.ts
+++ b/packages/eve/src/harness/tool-loop.test.ts
@@ -20,6 +20,7 @@ import { defineMemory } from "#public/memory/index.js";
import {
AuthKey,
ChannelInstrumentationKey,
+ ConversationIdKey,
HistoryStateKey,
InitiatorAuthKey,
LiveStepDynamicModelSelectionKey,
@@ -1550,7 +1551,7 @@ describe("createToolLoopHarness", () => {
const prepared = await prepareStep({
context: undefined,
messages: [],
- model: null,
+ model: selectedModel,
stepNumber: 0,
steps: [],
});
@@ -5816,10 +5817,12 @@ describe("createToolLoopHarness", () => {
messages: [],
stepNumber: 0,
steps: [],
- model: null,
+ model: agentCall?.model,
context: undefined,
});
- expect(stepResult.providerOptions).toEqual({ gateway: { caching: "auto" } });
+ expect(stepResult.providerOptions).toEqual({
+ gateway: { caching: "auto", sessionId: "test-session" },
+ });
});
it("emits assistant/tool events in response order when a step completes after tool work", async () => {
@@ -8602,7 +8605,7 @@ describe("createToolLoopHarness", () => {
const prepared = await prepareStep({
context: undefined,
messages,
- model: undefined,
+ model: settings.model,
stepNumber: 0,
steps: [],
});
@@ -8927,6 +8930,34 @@ describe("createToolLoopHarness", () => {
});
});
+ it("groups Gateway compaction under the forwarded trace conversation", async () => {
+ vi.mocked(shouldCompact).mockReturnValue(true);
+ vi.mocked(compactMessages).mockResolvedValue([
+ createFrameworkUserMessage("context.compaction", "Summary"),
+ { content: "summary", role: "assistant" },
+ ]);
+ setupMockAgent({
+ finishReason: "stop",
+ response: { messages: [{ content: "ok", role: "assistant" }] },
+ text: "ok",
+ toolCalls: [],
+ toolResults: [],
+ });
+ const { emit } = createEventCollector();
+ const config = createTestConfig(emit, {
+ resolveModel: vi.fn().mockResolvedValue("anthropic/claude-sonnet-4-5"),
+ });
+ const session = createTestSession({ rootSessionId: "root-session" });
+ const ctx = new ContextContainer();
+ ctx.set(ConversationIdKey, "forwarded-conversation");
+
+ await contextStorage.run(ctx, () => createToolLoopHarness(config)(session, { message: "Hi" }));
+
+ expect(vi.mocked(compactMessages).mock.calls[0]?.[3]).toEqual({
+ gateway: { sessionId: "forwarded-conversation" },
+ });
+ });
+
it("resolves model and step capabilities before compacting the final request", async () => {
vi.mocked(shouldCompact).mockReturnValue(true);
const compactedHistory: HarnessModelMessage[] = [
@@ -9483,6 +9514,7 @@ describe("createToolLoopHarness", () => {
};
type PromptAgentSettings = MockAgentSettings & {
instructions?: unknown;
+ model: LanguageModel;
tools?: Record<
string,
{ description?: unknown; inputSchema?: unknown; providerOptions?: unknown }
@@ -9510,7 +9542,7 @@ describe("createToolLoopHarness", () => {
const prepared = await prepareStep({
context: undefined,
messages: call.messages,
- model: {},
+ model: settings.model,
stepNumber: 0,
steps: [],
});
@@ -9679,9 +9711,9 @@ describe("createToolLoopHarness", () => {
firstPrompt.tools,
]);
expect(modelCalls.map((call) => call.providerOptions)).toEqual([
- { gateway: { caching: "auto" } },
- { gateway: { caching: "auto" } },
- { gateway: { caching: "auto" } },
+ { gateway: { caching: "auto", sessionId: "test-session" } },
+ { gateway: { caching: "auto", sessionId: "test-session" } },
+ { gateway: { caching: "auto", sessionId: "test-session" } },
]);
expect(modelCalls.map((call) => call.messages)).toEqual([
[{ content: "Add 1 and 2.", kind: "user" as const, role: "user" }],
@@ -9742,7 +9774,7 @@ describe("createToolLoopHarness", () => {
await prepareStep({
context: undefined,
messages: [],
- model: null,
+ model: agentCall?.model,
stepNumber: 0,
steps: [],
})
@@ -9750,11 +9782,11 @@ describe("createToolLoopHarness", () => {
};
await expect(readProviderOptions(0)).resolves.toEqual({
- gateway: { caching: "auto" },
+ gateway: { caching: "auto", sessionId: "test-session" },
openai: { safetyIdentifier: invocationOwnerKey(auth), store: false },
});
await expect(readProviderOptions(1)).resolves.toEqual({
- gateway: { caching: "auto" },
+ gateway: { caching: "auto", sessionId: "test-session" },
openai: { safetyIdentifier: invocationOwnerKey(nextAuth), store: false },
});
});
@@ -9787,11 +9819,11 @@ describe("createToolLoopHarness", () => {
messages: [],
stepNumber: 0,
steps: [],
- model: null,
+ model: agentCall?.model,
context: undefined,
});
expect(stepResult.providerOptions).toEqual({
- gateway: { caching: "auto" },
+ gateway: { caching: "auto", sessionId: "test-session" },
});
});
@@ -9833,11 +9865,11 @@ describe("createToolLoopHarness", () => {
messages: [],
stepNumber: 0,
steps: [],
- model: null,
+ model: agentCall?.model,
context: undefined,
});
expect(stepResult.providerOptions).toEqual({
- gateway: { order: ["anthropic", "bedrock"], caching: "auto" },
+ gateway: { order: ["anthropic", "bedrock"], caching: "auto", sessionId: "test-session" },
});
});
@@ -9879,11 +9911,11 @@ describe("createToolLoopHarness", () => {
messages: [],
stepNumber: 0,
steps: [],
- model: null,
+ model: agentCall?.model,
context: undefined,
});
expect(stepResult.providerOptions).toEqual({
- gateway: { caching: false },
+ gateway: { caching: false, sessionId: "test-session" },
});
});
@@ -9994,7 +10026,7 @@ describe("createToolLoopHarness", () => {
],
stepNumber: 0,
steps: [],
- model: null,
+ model: agentCall?.model,
context: undefined,
});
@@ -10041,7 +10073,7 @@ describe("createToolLoopHarness", () => {
messages: [],
stepNumber: 0,
steps: [],
- model: null,
+ model: agentCall?.model,
context: undefined,
});
expect(stepResult.providerOptions).toBeUndefined();
diff --git a/packages/eve/src/harness/tool-loop.ts b/packages/eve/src/harness/tool-loop.ts
index adde8fe1d..25af5135e 100644
--- a/packages/eve/src/harness/tool-loop.ts
+++ b/packages/eve/src/harness/tool-loop.ts
@@ -215,7 +215,8 @@ import {
readGatewayGenerationId,
type HarnessStepResult,
} from "#harness/step-hooks.js";
-import { mergeProviderSafetyIdentifier } from "#harness/provider-safety.js";
+import { resolveCallProviderOptions } from "#harness/provider-safety.js";
+import { resolveConversationId } from "#shared/conversation-identity.js";
import {
buildToolApproval,
buildToolSetFromDefinitions,
@@ -3128,11 +3129,13 @@ async function maybeCompact(input: {
});
const compactionModelReference =
session.agent.compactionModelReference ?? requireSessionModelReference(session);
- const providerOptions = mergeProviderSafetyIdentifier(
- compactionModelReference,
- compaction.providerOptions,
- input.auth,
- ) as Parameters<typeof compactMessages>[3];
+ const providerOptions = resolveCallProviderOptions({
+ auth: input.auth,
+ conversationId: resolveConversationId(session.rootSessionId ?? session.sessionId),
+ model: compaction.model,
+ modelReference: compactionModelReference,
+ providerOptions: compaction.providerOptions,
+ }) as Parameters<typeof compactMessages>[3];
if (emit) {
const ctx = contextStorage.getStore();
diff --git a/packages/eve/src/instrumentation/runtime.ts b/packages/eve/src/instrumentation/runtime.ts
index bce082eb0..eb082e939 100644
--- a/packages/eve/src/instrumentation/runtime.ts
+++ b/packages/eve/src/instrumentation/runtime.ts
@@ -65,7 +65,7 @@ import { readInstrumentationSessionContext } from "#instrumentation/session-cont
import { readSessionTraceDecision } from "#tracing/agent-trace-context-store.js";
import { readInstrumentationDecision } from "#shared/instrumentation-decision.js";
import { applyLiveDeliveryAudienceCeiling } from "#shared/forwarded-trace-policy.js";
-import { readConversationId } from "#tracing/conversation-context.js";
+import { readConversationId } from "#shared/conversation-identity.js";
import {
getInstrumentationRuntime,
registerInstrumentationRuntime,
diff --git a/packages/eve/src/internal/gateway.ts b/packages/eve/src/internal/gateway.ts
index 63a6bbf57..e5db5ba06 100644
--- a/packages/eve/src/internal/gateway.ts
+++ b/packages/eve/src/internal/gateway.ts
@@ -32,3 +32,26 @@ export function resolveProviderHeaders(model: LanguageModel): Record<string, str
export function isGatewayModel(model: LanguageModel): boolean {
return typeof model === "string" || model.provider?.split(".")[0] === "gateway";
}
+
+/** Groups Gateway generations under the same identity used by eve's agent spans. */
+export function mergeGatewaySessionId(
+ model: LanguageModel,
+ providerOptions: Readonly<Record<string, unknown>> | undefined,
+ conversationId: string,
+): Record<string, unknown> | undefined {
+ if (!isGatewayModel(model)) return providerOptions;
+
+ const gateway = providerOptions?.gateway;
+ const gatewayOptions =
+ gateway !== null && typeof gateway === "object" && !Array.isArray(gateway)
+ ? (gateway as Record<string, unknown>)
+ : undefined;
+ if (typeof gatewayOptions?.sessionId === "string" && gatewayOptions.sessionId.trim()) {
+ return providerOptions;
+ }
+
+ return {
+ ...providerOptions,
+ gateway: { ...gatewayOptions, sessionId: conversationId },
+ };
+}
diff --git a/packages/eve/src/self-modification/extension/subagents/agent/tools/search_traces.ts b/packages/eve/src/self-modification/extension/subagents/agent/tools/search_traces.ts
index 4b5e82246..2601504fe 100644
--- a/packages/eve/src/self-modification/extension/subagents/agent/tools/search_traces.ts
+++ b/packages/eve/src/self-modification/extension/subagents/agent/tools/search_traces.ts
@@ -3,7 +3,7 @@ import { defineTool } from "eve/tools";
import { context, trace } from "#compiled/@opentelemetry/api/index.js";
import { queryLocalTraceSummaries, type LocalTraceSortBy } from "#tracing/local-trace-query.js";
import { summarizeLocalTrace, type LocalTraceSummary } from "#tracing/local-trace-summary.js";
-import { resolveConversationId } from "#tracing/conversation-context.js";
+import { resolveConversationId } from "#shared/conversation-identity.js";
import {
localTraceConversationMarker,
localTraceIndexedMarker,
diff --git a/packages/eve/src/shared/conversation-identity.ts b/packages/eve/src/shared/conversation-identity.ts
new file mode 100644
index 000000000..543053aac
--- /dev/null
+++ b/packages/eve/src/shared/conversation-identity.ts
@@ -0,0 +1,27 @@
+import { contextStorage } from "#context/container.js";
+import { ConversationIdKey } from "#context/keys.js";
+
+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;
+}
diff --git a/packages/eve/src/tracing/agent-invocation-coordinator.ts b/packages/eve/src/tracing/agent-invocation-coordinator.ts
index 7150754ca..33353b594 100644
--- a/packages/eve/src/tracing/agent-invocation-coordinator.ts
+++ b/packages/eve/src/tracing/agent-invocation-coordinator.ts
@@ -1,6 +1,6 @@
import type { SessionTraceContext } from "#channel/types.js";
import { ConversationIdKey } from "#context/keys.js";
-import { readConversationId } from "#tracing/conversation-context.js";
+import { readConversationId } from "#shared/conversation-identity.js";
import type { RuntimeSubagentResult } from "#shared/action-types.js";
import type { SessionStateMap } from "#harness/types.js";
import { getBlockingWorkflowToolRuns } from "#harness/workflow-tool-runs.js";
diff --git a/packages/eve/src/tracing/agent-otel-attributes.ts b/packages/eve/src/tracing/agent-otel-attributes.ts
index bd2086bac..4fd91029c 100644
--- a/packages/eve/src/tracing/agent-otel-attributes.ts
+++ b/packages/eve/src/tracing/agent-otel-attributes.ts
@@ -1,4 +1,4 @@
-import { resolveConversationId } from "#tracing/conversation-context.js";
+import { resolveConversationId } from "#shared/conversation-identity.js";
import { AGENT_TRACE_SCHEMA_VERSION } from "#tracing/agent-span-contract.js";
export function agentTraceIdentityAttributes(input: {
diff --git a/packages/eve/src/tracing/conversation-context.test.ts b/packages/eve/src/tracing/conversation-context.test.ts
index c8e578ba2..5cd229f71 100644
--- a/packages/eve/src/tracing/conversation-context.test.ts
+++ b/packages/eve/src/tracing/conversation-context.test.ts
@@ -1,10 +1,9 @@
import { describe, expect, it } from "vitest";
import { ContextContainer, contextStorage } from "#context/container.js";
import { ConversationIdKey } from "#context/keys.js";
+import { readConversationId, resolveConversationId } from "#shared/conversation-identity.js";
import {
readConversationBaggage,
- readConversationId,
- resolveConversationId,
writeConversationBaggage,
} from "#tracing/conversation-context.js";
diff --git a/packages/eve/src/tracing/conversation-context.ts b/packages/eve/src/tracing/conversation-context.ts
index 6adc5fd43..67c46ddf3 100644
--- a/packages/eve/src/tracing/conversation-context.ts
+++ b/packages/eve/src/tracing/conversation-context.ts
@@ -1,32 +1,7 @@
-import { contextStorage } from "#context/container.js";
-import { ConversationIdKey } from "#context/keys.js";
import { readBaggageMember, replaceBaggageMember } from "#protocol/baggage.js";
+import { readConversationId } from "#shared/conversation-identity.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);
diff --git a/packages/eve/src/tracing/install-instrumentation-runtime.ts b/packages/eve/src/tracing/install-instrumentation-runtime.ts
index 764a9d714..eb83a723b 100644
--- a/packages/eve/src/tracing/install-instrumentation-runtime.ts
+++ b/packages/eve/src/tracing/install-instrumentation-runtime.ts
@@ -19,7 +19,7 @@ import { createAgentOtelInstrumentation } from "#tracing/agent-otel-provider.js"
import { hasConversationRelease, type LocalTracesProcessor } from "#tracing/local-traces.js";
import type { CollectedOtel, RuntimeContextResolver } from "#tracing/otel-declaration.js";
import { registerOtelPipeline, type RegisteredOtelPipeline } from "#tracing/otel-registration.js";
-import { readConversationId } from "#tracing/conversation-context.js";
+import { readConversationId } from "#shared/conversation-identity.js";
const log = createLogger("tracing.install-instrumentation-runtime");