Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat(eve): trace memory operations (#3265)

Chad Hietala0e2912f84661
diff --git a/.changeset/traced-memory-operations.md b/.changeset/traced-memory-operations.md
new file mode 100644
index 000000000..c6a443dcc
--- /dev/null
+++ b/.changeset/traced-memory-operations.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Add OpenTelemetry GenAI spans for memory provider recall and capture operations.
diff --git a/docs/guides/instrumentation.md b/docs/guides/instrumentation.md
index 5789b2776..59aafd552 100644
--- a/docs/guides/instrumentation.md
+++ b/docs/guides/instrumentation.md
@@ -48,13 +48,13 @@ Use the `setup` callback to register your OTel provider (for example `registerOT
Any OTel-compatible backend works (Braintrust, PostHog, Sentry, Raindrop, Arize, Honeycomb, Datadog, Jaeger). Install the exporter package you need and configure it in the callback. The [PostHog AI Observability integration](/integrations/posthog-instrumentation) provides a ready-to-install exporter and optional user identification. The [Sentry integration](/integrations/sentry-instrumentation) provides a ready-to-install OTLP exporter that sends traces to Sentry without a Sentry SDK.
-Three more fields control what the AI SDK records inside those spans (see the AI SDK's [telemetry reference](https://ai-sdk.dev/docs/ai-sdk-core/telemetry)):
+Three more fields control what eve and the AI SDK record inside those spans (see the AI SDK's [telemetry reference](https://ai-sdk.dev/docs/ai-sdk-core/telemetry)):
- `recordInputs` records full message history on each step span. It defaults to `false`; set it to `true` to include input content.
-- `recordOutputs` records model outputs on spans. It defaults to `false`; set it to `true` to include output content.
+- `recordOutputs` records model outputs and recalled memory records. It defaults to `false`; set it to `true` to include output content.
- `functionId` overrides the function name on spans (defaults to the agent name).
-eve records metadata without model or tool inputs and outputs by default. Enable either content category only after reviewing the exporter and its data-retention path.
+eve records metadata without model, tool, or memory-record content by default. Enable either content category only after reviewing the exporter and its data-retention path.
In the provider layout, eve stamps each span with `gen_ai.conversation.id`, which stays fixed across local and remote activations, including independent remote root workflows. Query this attribute to find the conversation's exported, retained traces; it does not grant access or control trace parenting. On Vercel, `vercel.session_id` additionally identifies the current Workflow run. See [Query exported traces](#query-exported-traces) for the cross-backend workflow.
@@ -108,14 +108,15 @@ The built-in OpenTelemetry provider preserves each span's OTel name and adds
| `invoke_agent weather` | `invoke_agent` | `invoke_agent weather` |
| `execute_tool search` | `execute_tool` | `execute_tool search` |
| `chat <model>` | `chat` | `chat <model>` |
+| `search_memory`, `upsert_memory` | Same as span name | Same as span name |
| `agent.step`, `agent.action`, `agent.approval`, `agent.channel.request` | Same as span name | Same as span name |
-These attributes apply to eve-owned spans in local tracing and the
+These rows apply to eve-owned spans in local tracing and the
[instrumentation provider layout](./instrumentation-providers). They do not
rename Workflow, AI SDK, or other third-party spans, or change trace IDs,
parenting, sampling, or session grouping. Legacy `instrumentation.ts` setup
-still owns its exporter configuration and [authored trace
-hierarchy](#authored-trace-hierarchy).
+still owns its exporter configuration and
+[authored trace hierarchy](#authored-trace-hierarchy).
In Datadog APM, `operation_name:invoke_agent resource_name:"invoke_agent weather"`
selects named agent invocations. Operation-based dashboards and monitors may
@@ -137,6 +138,14 @@ that discard span events, including Sentry's [direct OTLP
intake](https://docs.sentry.io/concepts/otlp/direct/traces/). These attributes
remain available when model and tool content is redacted.
+## Memory spans
+
+eve records [OpenTelemetry GenAI memory spans](https://opentelemetry.io/docs/specs/semconv/gen-ai/gen-ai-spans/#memory) for provider calls. Recalls at `turn.started` and `compaction.completed` use `search_memory`; capture handlers use `upsert_memory`. They are client spans, following the GenAI memory convention for a call to a memory system.
+
+Every memory span includes `gen_ai.operation.name` and `gen_ai.memory.store.id`. The store ID is eve's opaque `memory.scope.key`, which identifies the resolved scope without exposing the namespace or scope values. Recall spans set `gen_ai.memory.record.count` to their result count.
+
+`gen_ai.memory.records` contains recalled record content only when `recordOutputs` is enabled. eve does not set `gen_ai.memory.query.text` because a memory provider receives structured conversation messages, not a standalone search-query string. The `agent.memory.slot` and `agent.memory.phase` attributes identify the eve slot and lifecycle boundary without adding either to the span name.
+
## Agent trace contract
The provider layout and zero-config local tracing emit the following spans.
@@ -150,6 +159,8 @@ The legacy `instrumentation.ts` layout still uses its authored OTel setup.
| `agent.action` | Durable action lifecycle, including dispatch and waiting |
| `execute_tool <tool>` | In-process tool execution beneath its action |
| `agent.approval` | Approval waiting beneath its action |
+| `search_memory` | Recall memory records before a turn or after compaction |
+| `upsert_memory` | Automatic memory capture |
| `agent.channel.request` | Optional HTTP request span in the provider layout |
For background tools and subagents, the AI SDK's `execute_tool` span ends when
@@ -373,7 +384,7 @@ Without an `instrumentation.ts`, `eve dev` records spans to disk with one bounde
- [`/traces`](dev-tui#logs-and-traces) in the dev TUI: a live trace viewer that replays captured content as a conversation.
- [`eve traces`](../reference/cli#eve-traces): a span tree in the terminal, `eve traces ls` to list. Works after `eve dev` exits.
-Local traces omit model and tool inputs and outputs by default. Set `EVE_TRACES_CONTENT=on` in `.env.local` to capture that content.
+Local traces omit model, tool, and memory-record content by default. Set `EVE_TRACES_CONTENT=on` in `.env.local` to capture that content.
Writing `instrumentation.ts` replaces this: your `setup` takes over and nothing is recorded locally. For span attributes, retention, and the `EVE_TRACES*` variables, see [`eve traces`](../reference/cli#eve-traces).
diff --git a/docs/reference/cli.md b/docs/reference/cli.md
index 5f6e461c8..7379d8730 100644
--- a/docs/reference/cli.md
+++ b/docs/reference/cli.md
@@ -316,7 +316,7 @@ A durable conversation produces one bounded trace per turn. Worker replacements
Every span carries a real duration. A turn's root `invoke_agent` span is written when the turn settles, so a running turn shows only its steps.
-Model and `execute_tool` spans omit their inputs and outputs by default. Set `EVE_TRACES_CONTENT=on` to capture system prompts, prompt messages, and response text for models, plus call arguments and results for tools. Each captured value is capped at 32 KB.
+Model, `execute_tool`, and memory spans omit their content by default. Set `EVE_TRACES_CONTENT=on` to capture system prompts, prompt messages, and response text for models; call arguments and results for tools; and recalled memory records. Each captured value is capped at 32 KB.
Step spans carry token counts under `agent.usage.*`, and cost when Vercel AI Gateway served the call. Model spans also expose `gen_ai.usage.*` token counters. The CLI sums step-level counters only, so model and delegated-call totals are not counted twice.
@@ -324,13 +324,13 @@ Step spans carry token counts under `agent.usage.*`, and cost when Vercel AI Gat
eve sweeps the store when an activation's writes finish, when a session finishes, and when the dev server starts. An open conversation does not pin every completed turn's trace. Sweeps evict oldest-first past the bounds below, except that active traces, the newest traces, and anything written in the last five minutes are kept. A sweep can therefore exceed the size budget. Set the bounds in `.env.local`, which `eve dev` loads automatically; each accepts `off` to disable it individually.
-| Variable | Default | Effect |
-| ---------------------------- | -------------------- | ----------------------------------------------------------------------------------- |
-| `EVE_TRACES` | on | `off` stops writing traces and stops sweeping |
-| `EVE_TRACES_CONTENT` | off | `on` captures model prompt/response and tool input/output attributes on local spans |
-| `EVE_TRACES_MAX_AGE_MS` | `604800000` (7d) | Age after which a trace may be evicted |
-| `EVE_TRACES_MAX_TOTAL_BYTES` | `536870912` (512 MB) | Size budget for the whole store |
-| `EVE_TRACES_RETAIN_COUNT` | `20` | Newest traces kept regardless of age or size |
+| Variable | Default | Effect |
+| ---------------------------- | -------------------- | --------------------------------------------------------------------------------------------------- |
+| `EVE_TRACES` | on | `off` stops writing traces and stops sweeping |
+| `EVE_TRACES_CONTENT` | off | `on` captures model prompt/response, tool input/output, and memory-record attributes on local spans |
+| `EVE_TRACES_MAX_AGE_MS` | `604800000` (7d) | Age after which a trace may be evicted |
+| `EVE_TRACES_MAX_TOTAL_BYTES` | `536870912` (512 MB) | Size budget for the whole store |
+| `EVE_TRACES_RETAIN_COUNT` | `20` | Newest traces kept regardless of age or size |
## `eve link`
diff --git a/packages/eve/src/context/memory-event-lifecycle.ts b/packages/eve/src/context/memory-event-lifecycle.ts
index c4ac6984e..229b55147 100644
--- a/packages/eve/src/context/memory-event-lifecycle.ts
+++ b/packages/eve/src/context/memory-event-lifecycle.ts
@@ -10,6 +10,7 @@ import {
import { createLogger } from "#internal/logging.js";
import type { UnstampedMessageStreamEvent } from "#protocol/message.js";
import type { ResolvedMemoryDefinition } from "#runtime/types.js";
+import type { MemoryInstrumentation } from "#instrumentation/memory.js";
const log = createLogger("memory");
@@ -21,6 +22,7 @@ export async function dispatchMemoryLifecycleEvent(input: {
readonly memories: readonly ResolvedMemoryDefinition[];
readonly messages?: readonly ModelMessage[];
readonly nodeId: string;
+ readonly instrumentation?: MemoryInstrumentation;
}): Promise<readonly ModelMessage[]> {
let messages = input.messages ?? [];
if (input.memories.length === 0) return messages;
@@ -31,6 +33,7 @@ export async function dispatchMemoryLifecycleEvent(input: {
appRoot: input.appRoot,
ctx: input.ctx,
event: input.event,
+ instrumentation: input.instrumentation,
memories: input.memories,
nodeId: input.nodeId,
});
@@ -41,6 +44,7 @@ export async function dispatchMemoryLifecycleEvent(input: {
appRoot: input.appRoot,
ctx: input.ctx,
event: input.event,
+ instrumentation: input.instrumentation,
memories: input.memories,
messages,
nodeId: input.nodeId,
@@ -50,6 +54,7 @@ export async function dispatchMemoryLifecycleEvent(input: {
abortSignal: input.abortSignal,
ctx: input.ctx,
event: input.event,
+ instrumentation: input.instrumentation,
memories: input.memories,
messages,
});
@@ -59,6 +64,7 @@ export async function dispatchMemoryLifecycleEvent(input: {
abortSignal: input.abortSignal,
ctx: input.ctx,
event: input.event,
+ instrumentation: input.instrumentation,
memories: input.memories,
messages,
});
diff --git a/packages/eve/src/context/memory-lifecycle.test.ts b/packages/eve/src/context/memory-lifecycle.test.ts
index 92b373d61..c8e8ea79c 100644
--- a/packages/eve/src/context/memory-lifecycle.test.ts
+++ b/packages/eve/src/context/memory-lifecycle.test.ts
@@ -12,6 +12,7 @@ import {
prepareMemoryPreamble,
} from "#context/memory-lifecycle.js";
import { AuthKey, SessionIdKey, SessionKey, TurnMemoryLocksKey } from "#context/keys.js";
+import { type MemoryInstrumentation } from "#instrumentation/memory.js";
import {
defineMemory,
type MemoryDefinition,
@@ -202,6 +203,63 @@ describe("memory lifecycle", () => {
expect(drainMemoryCommit(ctx)?.history).toEqual([]);
});
+ it("instruments recalls as memory searches with validated result records", async () => {
+ const ctx = createContext();
+ const operations: unknown[] = [];
+ const results: unknown[] = [];
+ const instrumentation: MemoryInstrumentation = {
+ execute: async (operation, execute) => {
+ operations.push(operation);
+ const result = await execute();
+ results.push(result);
+ return result.value;
+ },
+ };
+ prepareMemoryPreamble(ctx, { history: [], input: [] });
+
+ await contextStorage.run(
+ ctx,
+ async () =>
+ await dispatchMemoryTurnStarted({
+ appRoot: "/app",
+ ctx,
+ event: turnStarted,
+ instrumentation,
+ memories: [
+ memory("profile", {
+ provider: {
+ recall: {
+ "turn.started": async () => ({
+ messages: [{ content: "The user prefers dark mode.", id: "preference" }],
+ }),
+ },
+ },
+ scope: "user_1",
+ }),
+ ],
+ nodeId: "__root__",
+ }),
+ );
+
+ expect(operations).toEqual([
+ {
+ idempotencyKey: "eve-memory-operation-v1:session_1:0:turn_0:turn.started:profile",
+ operationName: "search_memory",
+ phase: "turn.started",
+ slot: "profile",
+ storeId: expect.stringMatching(/^memscope1_/),
+ turnId: "turn_0",
+ },
+ ]);
+ expect(results).toEqual([
+ {
+ outputRecords: [{ content: "The user prefers dark mode.", id: "preference" }],
+ recordCount: 1,
+ value: [{ content: "The user prefers dark mode.", itemKey: expect.any(String) }],
+ },
+ ]);
+ });
+
it("captures only the settled projected history for a successful turn", async () => {
const ctx = createContext();
const capture = vi.fn(async (_context: MemoryTurnCompletedContext) => {});
@@ -260,6 +318,97 @@ describe("memory lifecycle", () => {
expect(JSON.stringify(capture.mock.calls[0]?.[0].messages)).not.toContain("eve.memory");
});
+ it("waits for sibling captures before propagating a failure", async () => {
+ const ctx = createContext();
+ const failure = new Error("alpha capture failed");
+ let releaseBravo!: () => void;
+ const bravoBlocked = new Promise<void>((resolve) => {
+ releaseBravo = resolve;
+ });
+ const bravoCapture = vi.fn(async () => await bravoBlocked);
+ const memories = [
+ memory("alpha", {
+ provider: {
+ capture: {
+ "turn.completed": async () => {
+ throw failure;
+ },
+ },
+ recall: { "turn.started": async () => null },
+ },
+ scope: "user_1",
+ }),
+ memory("bravo", {
+ provider: {
+ capture: { "turn.completed": bravoCapture },
+ recall: { "turn.started": async () => null },
+ },
+ scope: "user_1",
+ }),
+ ];
+ const turn = { id: "turn_0", input: [], sequence: 0 };
+ ctx.set(TurnMemoryLocksKey, {
+ alpha: createMemoryLock({
+ namespace: "app",
+ scope: "user_1",
+ slot: "alpha",
+ turn,
+ visibility: "scope",
+ }),
+ bravo: createMemoryLock({
+ namespace: "app",
+ scope: "user_1",
+ slot: "bravo",
+ turn,
+ visibility: "scope",
+ }),
+ });
+ const terminals: string[] = [];
+ const instrumentation: MemoryInstrumentation = {
+ async execute(operation, execute) {
+ try {
+ const result = await execute();
+ terminals.push(`${operation.slot}:completed`);
+ return result.value;
+ } catch (error) {
+ terminals.push(`${operation.slot}:failed`);
+ throw error;
+ }
+ },
+ };
+
+ const pending = contextStorage.run(
+ ctx,
+ async () =>
+ await dispatchMemoryTurnCompleted({
+ ctx,
+ event: { data: { sequence: 0, turnId: "turn_0" }, type: "turn.completed" },
+ instrumentation,
+ memories,
+ messages: [],
+ }),
+ );
+ let outcome:
+ | { readonly error?: unknown; readonly status: "fulfilled" | "rejected" }
+ | undefined;
+ const observed = pending.then(
+ () => {
+ outcome = { status: "fulfilled" };
+ },
+ (error: unknown) => {
+ outcome = { error, status: "rejected" };
+ },
+ );
+
+ await vi.waitFor(() => expect(bravoCapture).toHaveBeenCalledOnce());
+ await vi.waitFor(() => expect(terminals).toEqual(["alpha:failed"]));
+ expect(outcome).toBeUndefined();
+ releaseBravo();
+ await observed;
+ expect(outcome).toEqual({ error: failure, status: "rejected" });
+ expect(terminals).toEqual(["alpha:failed", "bravo:completed"]);
+ });
+
it("captures before compaction and recalls again after the checkpoint", async () => {
const ctx = createContext();
const phases: string[] = [];
diff --git a/packages/eve/src/context/memory-lifecycle.ts b/packages/eve/src/context/memory-lifecycle.ts
index 9caf97c97..c3c758240 100644
--- a/packages/eve/src/context/memory-lifecycle.ts
+++ b/packages/eve/src/context/memory-lifecycle.ts
@@ -17,7 +17,17 @@ import type {
} from "#protocol/message.js";
import { isEveDevEnvironment } from "#internal/application/dev-environment.js";
import { createLogger } from "#internal/logging.js";
-import { defaultNamespace, type MemoryScopeContext } from "#public/memory/index.js";
+import {
+ defaultNamespace,
+ type MemoryRecallResult,
+ type MemoryScopeContext,
+} from "#public/memory/index.js";
+import {
+ instrumentMemoryOperation,
+ type InstrumentationMemoryOperation,
+ type InstrumentationMemoryRecord,
+ type MemoryInstrumentation,
+} from "#instrumentation/memory.js";
import type { ResolvedMemoryDefinition } from "#runtime/types.js";
import {
applyMemoryRecallBatches,
@@ -53,6 +63,7 @@ export async function dispatchMemoryTurnStarted(input: {
readonly event: TurnStartedStreamEvent;
readonly memories: readonly ResolvedMemoryDefinition[];
readonly nodeId: string;
+ readonly instrumentation?: MemoryInstrumentation;
}): Promise<readonly ModelMessage[]> {
const prepared = input.ctx.get(PreparedMemoryPreambleKey);
if (prepared === undefined) return [];
@@ -85,7 +96,7 @@ export async function dispatchMemoryTurnStarted(input: {
const preRecallMessages = projectMemoryHistory({ locks, messages: prepared.history });
const callbackContext = buildCallbackContext();
const batches = (
- await Promise.all(
+ await settleMemoryOperations(
[...input.memories]
.sort((left, right) => left.logicalPath.localeCompare(right.logicalPath))
.map(async (memory): Promise<MemoryRecallBatch | null> => {
@@ -98,17 +109,36 @@ export async function dispatchMemoryTurnStarted(input: {
slot: memory.slot,
turnId: turn.id,
});
- const result = await memory.provider.recall["turn.started"]({
- ...callbackContext,
- abortSignal: input.abortSignal ?? fallbackAbortSignal,
- memory: { scope: lock.scope, slot: memory.slot },
- messages: preRecallMessages,
- operationId,
- turn,
- });
+ const result = await instrumentMemoryOperation(
+ input.instrumentation,
+ memoryInstrumentationOperation({
+ operationId,
+ operationName: "search_memory",
+ phase: "turn.started",
+ slot: memory.slot,
+ storeId: lock.scope.key,
+ turnId: turn.id,
+ }),
+ async () => {
+ const result = await memory.provider.recall["turn.started"]({
+ ...callbackContext,
+ abortSignal: input.abortSignal ?? fallbackAbortSignal,
+ memory: { scope: lock.scope, slot: memory.slot },
+ messages: preRecallMessages,
+ operationId,
+ turn,
+ });
+ const messages = validateMemoryRecallResult(result, memory.slot);
+ return {
+ outputRecords: memoryRecords(result),
+ recordCount: messages.length,
+ value: messages,
+ };
+ },
+ );
return {
lock,
- messages: validateMemoryRecallResult(result, memory.slot),
+ messages: result,
operationId,
};
}),
@@ -157,36 +187,52 @@ export async function dispatchMemoryCompactionRequested(input: {
readonly memories: readonly ResolvedMemoryDefinition[];
readonly messages: readonly ModelMessage[];
readonly nodeId: string;
+ readonly instrumentation?: MemoryInstrumentation;
}): Promise<void> {
const callbackContext = buildCallbackContext();
const locks = await resolveCompactionLocks(input);
input.ctx.set(TurnMemoryLocksKey, locks);
const turn = input.event.data.turnId.length === 0 ? null : firstLockedTurn(locks);
- await Promise.all(
+ await settleMemoryOperations(
[...input.memories]
.sort((left, right) => left.logicalPath.localeCompare(right.logicalPath))
.map(async (memory) => {
const lock = locks[memory.slot];
const capture = memory.provider.capture?.["compaction.requested"];
if (lock === undefined || capture === undefined) return;
- await capture({
- ...callbackContext,
- abortSignal: input.abortSignal ?? fallbackAbortSignal,
- compaction: {
- modelId: input.event.data.modelId,
- usageInputTokens: input.event.data.usageInputTokens,
- },
- memory: { scope: lock.scope, slot: memory.slot },
- messages: input.messages,
- operationId: memoryOperationId({
+ const operationId = memoryOperationId({
+ phase: "compaction.requested",
+ sequence: input.event.data.sequence,
+ sessionId: callbackContext.session.id,
+ slot: memory.slot,
+ turnId: turn?.id ?? null,
+ });
+ await instrumentMemoryOperation(
+ input.instrumentation,
+ memoryInstrumentationOperation({
+ operationId,
+ operationName: "upsert_memory",
phase: "compaction.requested",
- sequence: input.event.data.sequence,
- sessionId: callbackContext.session.id,
slot: memory.slot,
- turnId: turn?.id ?? null,
+ storeId: lock.scope.key,
+ turnId: turn?.id,
}),
- turn,
- });
+ async () => {
+ await capture({
+ ...callbackContext,
+ abortSignal: input.abortSignal ?? fallbackAbortSignal,
+ compaction: {
+ modelId: input.event.data.modelId,
+ usageInputTokens: input.event.data.usageInputTokens,
+ },
+ memory: { scope: lock.scope, slot: memory.slot },
+ messages: input.messages,
+ operationId,
+ turn,
+ });
+ return { value: undefined };
+ },
+ );
}),
);
}
@@ -197,6 +243,7 @@ export async function dispatchMemoryCompactionCompleted(input: {
readonly event: CompactionCompletedStreamEvent;
readonly memories: readonly ResolvedMemoryDefinition[];
readonly messages: readonly ModelMessage[];
+ readonly instrumentation?: MemoryInstrumentation;
}): Promise<readonly ModelMessage[]> {
const prepared = input.ctx.get(PreparedMemoryCompactionKey);
const rawHistory = prepared?.history ?? input.messages;
@@ -208,7 +255,7 @@ export async function dispatchMemoryCompactionCompleted(input: {
const callbackContext = buildCallbackContext();
const turn = input.event.data.turnId.length === 0 ? null : firstLockedTurn(activeLocks);
const batches = (
- await Promise.all(
+ await settleMemoryOperations(
[...input.memories]
.sort((left, right) => left.logicalPath.localeCompare(right.logicalPath))
.map(async (memory): Promise<MemoryRecallBatch | null> => {
@@ -222,18 +269,37 @@ export async function dispatchMemoryCompactionCompleted(input: {
slot: memory.slot,
turnId: turn?.id ?? null,
});
- const result = await recall({
- ...callbackContext,
- abortSignal: input.abortSignal ?? fallbackAbortSignal,
- compaction: { modelId: input.event.data.modelId },
- memory: { scope: lock.scope, slot: memory.slot },
- messages: projected,
- operationId,
- turn,
- });
+ const result = await instrumentMemoryOperation(
+ input.instrumentation,
+ memoryInstrumentationOperation({
+ operationId,
+ operationName: "search_memory",
+ phase: "compaction.completed",
+ slot: memory.slot,
+ storeId: lock.scope.key,
+ turnId: turn?.id,
+ }),
+ async () => {
+ const result = await recall({
+ ...callbackContext,
+ abortSignal: input.abortSignal ?? fallbackAbortSignal,
+ compaction: { modelId: input.event.data.modelId },
+ memory: { scope: lock.scope, slot: memory.slot },
+ messages: projected,
+ operationId,
+ turn,
+ });
+ const messages = validateMemoryRecallResult(result, memory.slot);
+ return {
+ outputRecords: memoryRecords(result),
+ recordCount: messages.length,
+ value: messages,
+ };
+ },
+ );
return {
lock,
- messages: validateMemoryRecallResult(result, memory.slot),
+ messages: result,
operationId,
};
}),
@@ -263,33 +329,49 @@ export async function dispatchMemoryTurnCompleted(input: {
readonly event: TurnCompletedStreamEvent;
readonly memories: readonly ResolvedMemoryDefinition[];
readonly messages: readonly ModelMessage[];
+ readonly instrumentation?: MemoryInstrumentation;
}): Promise<void> {
const locks = (input.ctx.get(TurnMemoryLocksKey) ?? {}) as Readonly<
Record<string, InternalMemoryLock>
>;
const callbackContext = buildCallbackContext();
const projected = projectMemoryHistory({ locks, messages: input.messages });
- await Promise.all(
+ await settleMemoryOperations(
[...input.memories]
.sort((left, right) => left.logicalPath.localeCompare(right.logicalPath))
.map(async (memory) => {
const lock = locks[memory.slot];
const capture = memory.provider.capture?.["turn.completed"];
if (lock === undefined || capture === undefined) return;
- await capture({
- ...callbackContext,
- abortSignal: input.abortSignal ?? fallbackAbortSignal,
- memory: { scope: lock.scope, slot: memory.slot },
- messages: projected,
- operationId: memoryOperationId({
+ const operationId = memoryOperationId({
+ phase: "turn.completed",
+ sequence: input.event.data.sequence,
+ sessionId: callbackContext.session.id,
+ slot: memory.slot,
+ turnId: input.event.data.turnId,
+ });
+ await instrumentMemoryOperation(
+ input.instrumentation,
+ memoryInstrumentationOperation({
+ operationId,
+ operationName: "upsert_memory",
phase: "turn.completed",
- sequence: input.event.data.sequence,
- sessionId: callbackContext.session.id,
slot: memory.slot,
- turnId: input.event.data.turnId,
+ storeId: lock.scope.key,
+ turnId: lock.turn.id,
}),
- turn: lock.turn,
- });
+ async () => {
+ await capture({
+ ...callbackContext,
+ abortSignal: input.abortSignal ?? fallbackAbortSignal,
+ memory: { scope: lock.scope, slot: memory.slot },
+ messages: projected,
+ operationId,
+ turn: lock.turn,
+ });
+ return { value: undefined };
+ },
+ );
}),
);
}
@@ -383,6 +465,21 @@ function reportDisabledMemorySlot(slot: string, resolver: "namespace" | "scope")
log.info("Memory slot is disabled for this operation", { resolver, slot });
}
+async function settleMemoryOperations<T>(operations: readonly Promise<T>[]): Promise<T[]> {
+ const results = await Promise.allSettled(operations);
+ const values: T[] = [];
+ let firstFailure: PromiseRejectedResult | undefined;
+ for (const result of results) {
+ if (result.status === "rejected") {
+ firstFailure ??= result;
+ } else {
+ values.push(result.value);
+ }
+ }
+ if (firstFailure !== undefined) throw firstFailure.reason;
+ return values;
+}
+
export function memoryOperationId(input: {
readonly phase: string;
readonly sequence: number;
@@ -399,3 +496,30 @@ export function memoryOperationId(input: {
input.slot,
].join(":");
}
+
+function memoryInstrumentationOperation(input: {
+ readonly operationId: string;
+ readonly operationName: InstrumentationMemoryOperation["operationName"];
+ readonly phase: string;
+ readonly slot: string;
+ readonly storeId: string;
+ readonly turnId?: string;
+}): InstrumentationMemoryOperation {
+ return {
+ idempotencyKey: input.operationId,
+ operationName: input.operationName,
+ phase: input.phase,
+ slot: input.slot,
+ storeId: input.storeId,
+ turnId: input.turnId,
+ };
+}
+
+function memoryRecords(result: MemoryRecallResult): readonly InstrumentationMemoryRecord[] {
+ if (result === null || result === undefined) return [];
+ return result.messages.map((message) =>
+ message.id === undefined
+ ? { content: message.content }
+ : { content: message.content, id: message.id },
+ );
+}
diff --git a/packages/eve/src/execution/workflow-steps.ts b/packages/eve/src/execution/workflow-steps.ts
index c81d1def6..20bfd7ab2 100644
--- a/packages/eve/src/execution/workflow-steps.ts
+++ b/packages/eve/src/execution/workflow-steps.ts
@@ -405,6 +405,7 @@ export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResu
appRoot: effectiveNode.agent?.metadata?.appRoot ?? "",
ctx,
event,
+ instrumentation: instrumentation?.memory,
memories: effectiveNode.agent?.memories ?? [],
messages,
nodeId: bundle.nodeId ?? "__root__",
diff --git a/packages/eve/src/instrumentation/content.ts b/packages/eve/src/instrumentation/content.ts
index c6611cfe7..e94fb0ca5 100644
--- a/packages/eve/src/instrumentation/content.ts
+++ b/packages/eve/src/instrumentation/content.ts
@@ -50,6 +50,8 @@ export function withInstrumentationDecision(
return decision.recordInputs ? event : Object.freeze({ ...event, input: undefined });
case "model.call.completed":
return decision.recordOutputs ? event : Object.freeze({ ...event, content: undefined });
+ case "memory.operation.completed":
+ return decision.recordOutputs ? event : Object.freeze({ ...event, outputRecords: undefined });
case "step.attempt.metadata":
return decision.recordOutputs
? event
@@ -59,6 +61,7 @@ export function withInstrumentationDecision(
});
case "action.failed":
case "model.call.failed":
+ case "memory.operation.failed":
case "session.failed":
case "step.attempt.failed":
case "tool.call.failed":
diff --git a/packages/eve/src/instrumentation/dispatch.ts b/packages/eve/src/instrumentation/dispatch.ts
index 32de798b2..31ad6b334 100644
--- a/packages/eve/src/instrumentation/dispatch.ts
+++ b/packages/eve/src/instrumentation/dispatch.ts
@@ -321,6 +321,13 @@ function stateOwner(event: InstrumentationEvent): InstrumentationStateOwner {
) {
return { sessionId: event.sessionId, turnId: event.turnId };
}
+ if (
+ event.type === "memory.operation.started" ||
+ event.type === "memory.operation.completed" ||
+ event.type === "memory.operation.failed"
+ ) {
+ return { sessionId: event.sessionId, turnId: event.turnId };
+ }
if (!("scope" in event)) return {};
if (event.type.startsWith("action.") || event.type.startsWith("input.")) {
return { sessionId: event.scope.sessionId, turnId: event.scope.turnId };
diff --git a/packages/eve/src/instrumentation/lifecycle.ts b/packages/eve/src/instrumentation/lifecycle.ts
index a78fd3882..94e97e19b 100644
--- a/packages/eve/src/instrumentation/lifecycle.ts
+++ b/packages/eve/src/instrumentation/lifecycle.ts
@@ -1,4 +1,5 @@
import { createInstrumentationDispatcher } from "#instrumentation/dispatch.js";
+import type * as memory from "#instrumentation/memory.js";
import type { InstrumentationStateSlot } from "#instrumentation/state.js";
import type { RuntimeTraceContext } from "#protocol/message.js";
import type { ChannelAudience } from "#shared/channel-audience.js";
@@ -580,6 +581,9 @@ export interface InstrumentationProviderDefinition {
readonly "model.call.started"?: InstrumentationEventHandler<InstrumentationModelCallStartedEvent>;
readonly "model.call.completed"?: InstrumentationEventHandler<InstrumentationModelCallCompletedEvent>;
readonly "model.call.failed"?: InstrumentationEventHandler<InstrumentationModelCallFailedEvent>;
+ readonly "memory.operation.started"?: InstrumentationEventHandler<memory.InstrumentationMemoryOperationStartedEvent>;
+ readonly "memory.operation.completed"?: InstrumentationEventHandler<memory.InstrumentationMemoryOperationCompletedEvent>;
+ readonly "memory.operation.failed"?: InstrumentationEventHandler<memory.InstrumentationMemoryOperationFailedEvent>;
readonly "input.requested"?: InstrumentationEventHandler<InstrumentationInputRequestedEvent>;
readonly "input.resolved"?: InstrumentationEventHandler<InstrumentationInputResolvedEvent>;
readonly "session.completed"?: InstrumentationEventHandler<InstrumentationSessionSettledEvent>;
@@ -625,6 +629,8 @@ export type InstrumentationCorrelatedEvent =
| InstrumentationInputResolvedEvent
| InstrumentationActionStartedEvent
| InstrumentationActionTerminalEvent
+ | memory.InstrumentationMemoryOperationStartedEvent
+ | memory.InstrumentationMemoryOperationTerminalEvent
| InstrumentationModelCallStartedEvent
| InstrumentationModelCallTerminalEvent
| InstrumentationToolCallStartedEvent
@@ -658,7 +664,8 @@ export type InstrumentationExecutionOperation =
readonly idempotencyKey: string;
readonly scope: InstrumentationAttemptScope;
readonly type: "model.call";
- };
+ }
+ | memory.InstrumentationMemoryExecutionOperation;
/** Provider-neutral hook operations consumed by the AI SDK bridge. */
export interface InstrumentationHooks {
diff --git a/packages/eve/src/instrumentation/memory.ts b/packages/eve/src/instrumentation/memory.ts
new file mode 100644
index 000000000..ca47cbf42
--- /dev/null
+++ b/packages/eve/src/instrumentation/memory.ts
@@ -0,0 +1,132 @@
+import type {
+ InstrumentationContextRunner,
+ InstrumentationHooks,
+} from "#instrumentation/lifecycle.js";
+
+/** Standard GenAI memory operations that eve can identify from its lifecycle. */
+export type InstrumentationMemoryOperationName = "search_memory" | "upsert_memory";
+
+/** One memory record in the OpenTelemetry GenAI memory-records shape. */
+export interface InstrumentationMemoryRecord {
+ readonly content: string;
+ readonly id?: string;
+}
+
+/** Stable framework context for one memory operation. */
+export interface InstrumentationMemoryOperation {
+ readonly idempotencyKey: string;
+ readonly operationName: InstrumentationMemoryOperationName;
+ /**
+ * The operation phase that caused eve to call the memory provider.
+ *
+ * This is eve-specific context; `operationName` is the corresponding
+ * OpenTelemetry GenAI operation.
+ */
+ readonly phase: string;
+ /** The path-derived memory slot. */
+ readonly slot: string;
+ /** The opaque memory scope key, used as eve's memory-store identifier. */
+ readonly storeId: string;
+ readonly turnId?: string;
+}
+
+/** Bound session identity added when eve publishes a memory operation. */
+export interface InstrumentationMemoryOperationEvent extends InstrumentationMemoryOperation {
+ readonly rootSessionId: string;
+ readonly sessionId: string;
+}
+
+export interface InstrumentationMemoryOperationStartedEvent extends InstrumentationMemoryOperationEvent {
+ readonly type: "memory.operation.started";
+}
+
+export interface InstrumentationMemoryOperationCompletedEvent extends InstrumentationMemoryOperationEvent {
+ readonly type: "memory.operation.completed";
+ /** The number of records the operation returned or changed, when known. */
+ readonly recordCount?: number;
+ /** Content. Absent unless this provider's trace policy records outputs. */
+ readonly outputRecords?: readonly InstrumentationMemoryRecord[];
+}
+
+export interface InstrumentationMemoryOperationFailedEvent extends InstrumentationMemoryOperationEvent {
+ readonly type: "memory.operation.failed";
+ /** Content. Absent unless this provider's trace policy records outputs. */
+ readonly error?: unknown;
+}
+
+export type InstrumentationMemoryOperationTerminalEvent =
+ | InstrumentationMemoryOperationCompletedEvent
+ | InstrumentationMemoryOperationFailedEvent;
+
+export interface InstrumentationMemoryExecutionOperation {
+ readonly idempotencyKey: string;
+ readonly sessionId: string;
+ readonly turnId?: string;
+ readonly type: "memory.operation";
+}
+
+/** The terminal details a memory operation reports to instrumentation. */
+export interface MemoryInstrumentationResult<T> {
+ readonly value: T;
+ readonly recordCount?: number;
+ readonly outputRecords?: readonly InstrumentationMemoryRecord[];
+}
+
+/** Runtime bridge from memory providers to the active instrumentation pipeline. */
+export interface MemoryInstrumentation {
+ execute<T>(
+ operation: InstrumentationMemoryOperation,
+ execute: () => Promise<MemoryInstrumentationResult<T>>,
+ ): Promise<T>;
+}
+
+export function createMemoryInstrumentation(input: {
+ readonly resolveContext: () => {
+ readonly hooks: InstrumentationHooks;
+ readonly rootSessionId: string;
+ };
+ readonly runInContext: InstrumentationContextRunner;
+ readonly sessionId: string;
+}): MemoryInstrumentation {
+ return {
+ async execute(operation, execute) {
+ const { hooks, rootSessionId } = input.resolveContext();
+ const event = { ...operation, rootSessionId, sessionId: input.sessionId };
+ await hooks.publish({ ...event, type: "memory.operation.started" });
+ try {
+ const result = await input.runInContext(
+ {
+ idempotencyKey: operation.idempotencyKey,
+ sessionId: input.sessionId,
+ turnId: operation.turnId,
+ type: "memory.operation",
+ },
+ execute,
+ );
+ await hooks.publish({
+ ...event,
+ outputRecords: result.outputRecords,
+ recordCount: result.recordCount,
+ type: "memory.operation.completed",
+ });
+ return result.value;
+ } catch (error) {
+ await hooks.publish({ ...event, error, type: "memory.operation.failed" });
+ throw error;
+ }
+ },
+ };
+}
+
+/** Runs one provider operation under memory instrumentation, when installed. */
+export async function instrumentMemoryOperation<T>(
+ instrumentation: MemoryInstrumentation | undefined,
+ operation: InstrumentationMemoryOperation | (() => InstrumentationMemoryOperation),
+ execute: () => Promise<MemoryInstrumentationResult<T>>,
+): Promise<T> {
+ if (instrumentation === undefined) return (await execute()).value;
+ return await instrumentation.execute(
+ typeof operation === "function" ? operation() : operation,
+ execute,
+ );
+}
diff --git a/packages/eve/src/instrumentation/provider.ts b/packages/eve/src/instrumentation/provider.ts
index 1899f1437..e710579d2 100644
--- a/packages/eve/src/instrumentation/provider.ts
+++ b/packages/eve/src/instrumentation/provider.ts
@@ -63,6 +63,16 @@ export type {
InstrumentationTurnTerminalEvent,
InstrumentationUsage,
} from "#instrumentation/lifecycle.js";
+export type {
+ InstrumentationMemoryOperation,
+ InstrumentationMemoryOperationCompletedEvent,
+ InstrumentationMemoryOperationEvent,
+ InstrumentationMemoryOperationFailedEvent,
+ InstrumentationMemoryOperationName,
+ InstrumentationMemoryOperationStartedEvent,
+ InstrumentationMemoryOperationTerminalEvent,
+ InstrumentationMemoryRecord,
+} from "#instrumentation/memory.js";
export type {
InstrumentationCapture,
TraceCaptureContext,
diff --git a/packages/eve/src/instrumentation/runtime.test.ts b/packages/eve/src/instrumentation/runtime.test.ts
index be401d720..1241220c2 100644
--- a/packages/eve/src/instrumentation/runtime.test.ts
+++ b/packages/eve/src/instrumentation/runtime.test.ts
@@ -13,6 +13,7 @@ import {
} from "#context/keys.js";
import { setChannelContext } from "#execution/channel-context.js";
import type { InstrumentationHooks } from "#instrumentation/lifecycle.js";
+import { instrumentMemoryOperation } from "#instrumentation/memory.js";
import {
bindInstrumentationRuntime,
bindSessionInstrumentation,
@@ -528,6 +529,7 @@ describe("bindInstrumentationRuntime", () => {
globalThis.AI_SDK_TELEMETRY_INTEGRATIONS = [authoredIntegration];
const runtime = {
...createRuntime({ capturesContent: true, publish: vi.fn() }),
+ memoryOperations: true,
ownsAgentSpans: true,
};
const instrumentation = bindInstrumentationRuntime(runtime, createContext(), boundSession);
@@ -561,6 +563,92 @@ describe("bindInstrumentationRuntime", () => {
}
});
+ it("does not publish memory operations without a memory instrumentation provider", async () => {
+ const publish = vi.fn();
+ const execute = vi.fn(async () => ({ value: "recalled" }));
+ const instrumentation = bindInstrumentationRuntime(
+ createRuntime({ capturesContent: true, publish }),
+ createContext(),
+ boundSession,
+ );
+
+ const result = await instrumentation?.prepareExecution().runStep(
+ {
+ environment: "test",
+ eveVersion: "0.0.0",
+ hasInput: false,
+ session: { sessionId: "session-1" },
+ },
+ async () =>
+ await instrumentMemoryOperation(
+ instrumentation?.memory,
+ {
+ idempotencyKey: "memory:search",
+ operationName: "search_memory",
+ phase: "turn.started",
+ slot: "profile",
+ storeId: "memscope1_scope",
+ turnId: "turn-1",
+ },
+ execute,
+ ),
+ );
+
+ expect(result).toBe("recalled");
+ expect(execute).toHaveBeenCalledOnce();
+ expect(publish).not.toHaveBeenCalled();
+ });
+
+ it("publishes memory operations with the effective session identity", async () => {
+ const publish = vi.fn();
+ const ctx = createContext();
+ ctx.set(ParentSessionKey, {
+ callId: "call-1",
+ rootSessionId: "conversation-root",
+ sessionId: "parent-session",
+ turn: { id: "parent-turn", sequence: 0 },
+ });
+ const instrumentation = bindInstrumentationRuntime(
+ {
+ ...createRuntime({ capturesContent: true, publish }),
+ memoryOperations: true,
+ },
+ ctx,
+ boundSession,
+ );
+
+ await instrumentMemoryOperation(
+ instrumentation?.memory,
+ {
+ idempotencyKey: "memory:search",
+ operationName: "search_memory",
+ phase: "turn.started",
+ slot: "profile",
+ storeId: "memscope1_scope",
+ turnId: "turn-1",
+ },
+ async () => ({
+ outputRecords: [{ content: "The user prefers dark mode.", id: "preference" }],
+ recordCount: 1,
+ value: undefined,
+ }),
+ );
+
+ expect(publish.mock.calls.map(([event]) => event)).toEqual([
+ expect.objectContaining({
+ rootSessionId: "conversation-root",
+ sessionId: "session-1",
+ type: "memory.operation.started",
+ }),
+ expect.objectContaining({
+ recordCount: 1,
+ rootSessionId: "conversation-root",
+ sessionId: "session-1",
+ type: "memory.operation.completed",
+ }),
+ ]);
+ });
+
it("isolates concurrent step decisions and audiences", async () => {
const ctx = createContext("private");
const runtime = createRuntime({ capturesContent: true, publish: vi.fn() });
diff --git a/packages/eve/src/instrumentation/runtime.ts b/packages/eve/src/instrumentation/runtime.ts
index 9590ce096..cb495d667 100644
--- a/packages/eve/src/instrumentation/runtime.ts
+++ b/packages/eve/src/instrumentation/runtime.ts
@@ -50,6 +50,10 @@ import { AgentSpanIdGenerator } from "#tracing/agent-span-id-generator.js";
import type { OtelHarnessSettings, RuntimeContextResolver } from "#tracing/otel-declaration.js";
import type { SessionTraceSeed } from "#context/keys.js";
import { contextStorage, type ContextContainer } from "#context/container.js";
+import {
+ createMemoryInstrumentation,
+ type MemoryInstrumentation,
+} from "#instrumentation/memory.js";
import {
ChannelInstrumentationKey,
ConversationIdKey,
@@ -154,6 +158,7 @@ export interface InstrumentationRuntime {
readonly hooks: InstrumentationHooks;
readonly idGenerator?: AgentSpanIdGenerator;
readonly instrumentationProviders?: boolean;
+ readonly memoryOperations?: boolean;
readonly ownsAgentSpans?: boolean;
readonly prepareSessionTrace?: (
event: InstrumentationSessionStartedEvent,
@@ -194,6 +199,7 @@ export interface ExecutionInstrumentation extends BackgroundTaskInstrumentation
| Omit<ChannelDeliveryStartInstrumentation, "hooks" | "policyAgentName">
| Omit<ChannelDeliveryTerminalInstrumentation, "hooks">,
) => Promise<void>;
+ readonly memory?: MemoryInstrumentation;
readonly prepareExecution: () => SessionInstrumentation;
readonly preparePreamble: InstrumentationStepScope<never>["preparePreamble"];
}
@@ -256,6 +262,20 @@ export function bindInstrumentationRuntime(
},
});
};
+ const memory: MemoryInstrumentation | undefined =
+ runtime.memoryOperations === true
+ ? createMemoryInstrumentation({
+ resolveContext: () => {
+ const sessionContext = readSessionContext();
+ return {
+ hooks: bindHooks(sessionContext),
+ rootSessionId: sessionContext.parent?.rootSessionId ?? boundSession.rootSessionId,
+ };
+ },
+ runInContext: runtime.runInContext,
+ sessionId: boundSession.sessionId,
+ })
+ : undefined;
const prepareExecution = (): SessionInstrumentation => {
const executionRuntime = captureExecutionRuntime();
return {
@@ -497,6 +517,7 @@ export function bindInstrumentationRuntime(
hooks: baseHooks,
policyAgentName: boundSession.agentName,
}),
+ memory,
prepareExecution,
preparePreamble: (input) => preparePreamble(input, readSessionContext()),
};
diff --git a/packages/eve/src/public/instrumentation/provider.test.ts b/packages/eve/src/public/instrumentation/provider.test.ts
index 5c03374ae..771dd9c20 100644
--- a/packages/eve/src/public/instrumentation/provider.test.ts
+++ b/packages/eve/src/public/instrumentation/provider.test.ts
@@ -5,6 +5,12 @@ import {
disableInstrumentation,
isInstrumentationDisabled,
isInstrumentationProvider,
+ type InstrumentationMemoryOperation,
+ type InstrumentationMemoryOperationCompletedEvent,
+ type InstrumentationMemoryOperationFailedEvent,
+ type InstrumentationMemoryOperationStartedEvent,
+ type InstrumentationMemoryOperationTerminalEvent,
+ type InstrumentationMemoryRecord,
type InstrumentationSetupContext,
} from "#public/instrumentation/index.js";
@@ -83,6 +89,41 @@ describe("defineInstrumentation", () => {
expect(isInstrumentationProvider(provider)).toBe(true);
});
+ it("exports memory operation event contracts", () => {
+ const operation: InstrumentationMemoryOperation = {
+ idempotencyKey: "memory:search",
+ operationName: "search_memory",
+ phase: "turn.started",
+ slot: "profile",
+ storeId: "scope",
+ turnId: "turn-1",
+ };
+ const record: InstrumentationMemoryRecord = { content: "Prefers dark mode.", id: "theme" };
+ const started: InstrumentationMemoryOperationStartedEvent = {
+ ...operation,
+ rootSessionId: "root-session",
+ sessionId: "session-1",
+ type: "memory.operation.started",
+ };
+ const completed: InstrumentationMemoryOperationCompletedEvent = {
+ ...started,
+ outputRecords: [record],
+ recordCount: 1,
+ type: "memory.operation.completed",
+ };
+ const failed: InstrumentationMemoryOperationFailedEvent = {
+ ...started,
+ error: new Error("failed"),
+ type: "memory.operation.failed",
+ };
+ const terminals: InstrumentationMemoryOperationTerminalEvent[] = [completed, failed];
+
+ expect(terminals.map((event) => event.type)).toEqual([
+ "memory.operation.completed",
+ "memory.operation.failed",
+ ]);
+ });
+
it("preserves the authored fields", () => {
const setup = (): void => {};
const declaration = defineInstrumentation({ setup });
diff --git a/packages/eve/src/tracing/agent-memory-instrumentation.ts b/packages/eve/src/tracing/agent-memory-instrumentation.ts
new file mode 100644
index 000000000..5b08c43c6
--- /dev/null
+++ b/packages/eve/src/tracing/agent-memory-instrumentation.ts
@@ -0,0 +1,186 @@
+import {
+ ROOT_CONTEXT,
+ SpanKind,
+ context,
+ trace,
+ type Context,
+ type Span,
+ type Tracer,
+} from "#compiled/@opentelemetry/api/index.js";
+
+import { contextStorage } from "#context/container.js";
+import { SessionTraceSeedKey } from "#context/keys.js";
+import type { InstrumentationProviderDefinition } from "#instrumentation/lifecycle.js";
+import type {
+ InstrumentationMemoryExecutionOperation,
+ InstrumentationMemoryOperationEvent,
+ InstrumentationMemoryOperationStartedEvent,
+ InstrumentationMemoryOperationTerminalEvent,
+} from "#instrumentation/memory.js";
+import { normalizeChannelAudience } from "#shared/channel-audience.js";
+import {
+ applyLiveDeliveryAudienceCeiling,
+ resolveForwardedTraceSeed,
+} from "#shared/forwarded-trace-policy.js";
+import { genAiMemoryRecordsAttribute } from "#tracing/agent-otel-content.js";
+import { agentTraceIdentityAttributes } from "#tracing/agent-otel-attributes.js";
+import { isAgentTraceContext, markAgentTraceContext } from "#tracing/agent-trace-context.js";
+import { recordAgentSpanError } from "#tracing/agent-span-error.js";
+import { agentSpanNamingAttributes } from "#tracing/agent-span-naming.js";
+import type { AgentTraceStateStore } from "#tracing/agent-trace-state.js";
+import { withChannelAudience } from "#tracing/channel-audience-context.js";
+import { withErrorContent } from "#tracing/error-content-context.js";
+import { isSampledTrace } from "#tracing/sampled-trace.js";
+import { suppressTracing } from "#tracing/suppress-tracing.js";
+
+type SpanState = { readonly context: Context; readonly span: Span };
+
+export interface AgentMemoryInstrumentation {
+ readonly events: Pick<
+ NonNullable<InstrumentationProviderDefinition["events"]>,
+ "memory.operation.completed" | "memory.operation.failed" | "memory.operation.started"
+ >;
+ runInContext<T>(
+ operation: InstrumentationMemoryExecutionOperation,
+ execute: () => PromiseLike<T>,
+ ): Promise<T>;
+}
+
+export function createAgentMemoryInstrumentation(input: {
+ readonly recordOutputs: boolean;
+ readonly stateStore: AgentTraceStateStore;
+ readonly tracer: Tracer;
+}): AgentMemoryInstrumentation {
+ const spans = new Map<string, SpanState>();
+
+ const parentContext = async (
+ event: InstrumentationMemoryOperationEvent,
+ ): Promise<Context | undefined> => {
+ const active = context.active();
+ if (isAgentTraceContext(active)) return active;
+
+ const session = await input.stateStore.getSession(event.sessionId);
+ if (event.turnId !== undefined) {
+ const turn = await input.stateStore.getTurn(event.sessionId, event.turnId);
+ if (turn !== undefined) {
+ return withChannelAudience(contextFromSpanContext(turn.context), session?.channelAudience);
+ }
+ }
+ return session === undefined
+ ? undefined
+ : withChannelAudience(contextFromSpanContext(session.context), session.channelAudience);
+ };
+
+ const onStarted = async (event: InstrumentationMemoryOperationStartedEvent): Promise<void> => {
+ if (spans.has(event.idempotencyKey)) return;
+ const parent = await parentContext(event);
+ const parentSpan = parent === undefined ? undefined : trace.getSpan(parent)?.spanContext();
+ if (parent === undefined || parentSpan === undefined || !isSampledTrace(parentSpan)) return;
+ const span = input.tracer.startSpan(
+ event.operationName,
+ {
+ attributes: memorySpanAttributes(event),
+ kind: SpanKind.CLIENT,
+ },
+ parent,
+ );
+ spans.set(event.idempotencyKey, {
+ context: trace.setSpan(parent, span),
+ span,
+ });
+ };
+
+ const onTerminal = (event: InstrumentationMemoryOperationTerminalEvent): void => {
+ const state = spans.get(event.idempotencyKey);
+ if (state === undefined) return;
+ spans.delete(event.idempotencyKey);
+ updateMemorySpan(state.span, event);
+ state.span.end();
+ };
+
+ return {
+ events: {
+ "memory.operation.completed": onTerminal,
+ "memory.operation.failed": onTerminal,
+ "memory.operation.started": onStarted,
+ },
+ async runInContext(operation, execute) {
+ const session = await input.stateStore.getSession(operation.sessionId);
+ let parent = spans.get(operation.idempotencyKey)?.context;
+ if (parent === undefined && operation.turnId !== undefined) {
+ const turn = await input.stateStore.getTurn(operation.sessionId, operation.turnId);
+ if (turn !== undefined) {
+ parent = withChannelAudience(
+ contextFromSpanContext(turn.context),
+ session?.channelAudience,
+ );
+ if (!isSampledTrace(turn.context)) parent = suppressTracing(parent);
+ }
+ }
+ if (parent === undefined && session !== undefined) {
+ parent = withChannelAudience(
+ contextFromSpanContext(session.context),
+ session.channelAudience,
+ );
+ if (!isSampledTrace(session.context)) parent = suppressTracing(parent);
+ }
+ const seed = resolveForwardedTraceSeed(contextStorage.getStore()?.get(SessionTraceSeedKey));
+ const decision = seed?.decision ?? session?.decision;
+ const effective =
+ decision === undefined
+ ? undefined
+ : applyLiveDeliveryAudienceCeiling(
+ decision,
+ normalizeChannelAudience(session?.channelAudience),
+ seed?.forwardedTracePolicy,
+ );
+ return parent === undefined
+ ? await execute()
+ : await context.with(
+ markAgentTraceContext(
+ withErrorContent(
+ parent,
+ input.recordOutputs && effective?.action === "record" && effective.recordOutputs,
+ ),
+ ),
+ execute,
+ );
+ },
+ };
+}
+
+function memorySpanAttributes(
+ event: InstrumentationMemoryOperationEvent,
+): Record<string, string | number> {
+ const attributes: Record<string, string | number> = {
+ "agent.memory.phase": event.phase,
+ "agent.memory.slot": event.slot,
+ "gen_ai.memory.store.id": event.storeId,
+ "gen_ai.operation.name": event.operationName,
+ ...agentSpanNamingAttributes(event.operationName, event.operationName),
+ ...agentTraceIdentityAttributes({
+ rootSessionId: event.rootSessionId,
+ sessionId: event.sessionId,
+ }),
+ };
+ if (event.turnId !== undefined) attributes["agent.turn.id"] = event.turnId;
+ return attributes;
+}
+
+function updateMemorySpan(span: Span, event: InstrumentationMemoryOperationTerminalEvent): void {
+ if (event.type === "memory.operation.failed") {
+ recordAgentSpanError(span, event.error);
+ } else {
+ if (event.recordCount !== undefined) {
+ span.setAttribute("gen_ai.memory.record.count", event.recordCount);
+ }
+ const records = genAiMemoryRecordsAttribute(event.outputRecords ?? []);
+ if (records !== undefined && event.outputRecords !== undefined) {
+ span.setAttribute("gen_ai.memory.records", records);
+ }
+ }
+}
+
+function contextFromSpanContext(spanContext: Parameters<typeof trace.wrapSpanContext>[0]): Context {
+ return trace.setSpan(ROOT_CONTEXT, trace.wrapSpanContext(spanContext));
+}
diff --git a/packages/eve/src/tracing/agent-otel-content.ts b/packages/eve/src/tracing/agent-otel-content.ts
index 61fd6164f..8b439a63f 100644
--- a/packages/eve/src/tracing/agent-otel-content.ts
+++ b/packages/eve/src/tracing/agent-otel-content.ts
@@ -98,6 +98,11 @@ export function genAiOutputMessagesAttribute(
]);
}
+/** Serializes memory records using the OpenTelemetry GenAI memory-records schema. */
+export function genAiMemoryRecordsAttribute(records: readonly unknown[]): string | undefined {
+ return semanticJsonAttribute(records);
+}
+
/**
* Serializes provider-executed tool results, keeping the attribute valid
* JSON under the cap: when the full payload is too big, each entry's input
diff --git a/packages/eve/src/tracing/agent-otel-provider.test.ts b/packages/eve/src/tracing/agent-otel-provider.test.ts
index 8f74c5bf1..b10bebd12 100644
--- a/packages/eve/src/tracing/agent-otel-provider.test.ts
+++ b/packages/eve/src/tracing/agent-otel-provider.test.ts
@@ -585,6 +585,74 @@ describe("createAgentOtelInstrumentation", () => {
},
);
+ it("exports and activates standard memory spans", async () => {
+ const runtime = createRuntime();
+ await publishTurnStarted({
+ hooks: runtime.hooks,
+ sessionId: "session-1",
+ turnId: "turn-1",
+ turnSequence: 0,
+ });
+ const operation = {
+ idempotencyKey: "eve-memory-operation-v1:session-1:0:turn-1:turn.started:profile",
+ operationName: "search_memory" as const,
+ phase: "turn.started",
+ rootSessionId: "session-1",
+ sessionId: "session-1",
+ slot: "profile",
+ storeId: "memscope1_scope",
+ turnId: "turn-1",
+ };
+ await runtime.hooks.publish({ ...operation, type: "memory.operation.started" });
+ const contextWith = vi.spyOn(context, "with");
+ await runtime.runInContext(
+ {
+ idempotencyKey: operation.idempotencyKey,
+ sessionId: operation.sessionId,
+ turnId: operation.turnId,
+ type: "memory.operation",
+ },
+ async () => undefined,
+ );
+ const memoryContext = contextWith.mock.calls[0]?.[0];
+ contextWith.mockRestore();
+ await runtime.hooks.publish({
+ ...operation,
+ outputRecords: [{ content: "The user prefers dark mode.", id: "preference" }],
+ recordCount: 1,
+ type: "memory.operation.completed",
+ });
+ await completeTurn(runtime.hooks, "session-1", "turn-1");
+ await runtime.provider.forceFlush();
+
+ const spans = runtime.exporter.getFinishedSpans();
+ const memory = byName(spans, "search_memory")[0]!;
+ const turn = byName(spans, "invoke_agent weather")[0]!;
+ if (memoryContext === undefined) throw new Error("memory operation did not activate a context");
+ expect(memory.kind).toBe(SpanKind.CLIENT);
+ expect(memory.parentSpanContext?.spanId).toBe(turn.spanContext().spanId);
+ expect(runtimeTrace.getSpan(memoryContext)?.spanContext().spanId).toBe(
+ memory.spanContext().spanId,
+ );
+ expect(memory.attributes).toMatchObject({
+ "agent.memory.phase": "turn.started",
+ "agent.memory.slot": "profile",
+ "agent.turn.id": "turn-1",
+ "gen_ai.memory.record.count": 1,
+ "gen_ai.memory.store.id": "memscope1_scope",
+ "gen_ai.operation.name": "search_memory",
+ "operation.name": "search_memory",
+ "resource.name": "search_memory",
+ });
+ expect(memory.attributes).not.toHaveProperty("agent.framework.name");
+ expect(memory.attributes).not.toHaveProperty("agent.framework.version");
+ expect(memory.attributes).not.toHaveProperty("agent.session.id");
+ expect(memory.attributes["gen_ai.memory.records"]).toBe(
+ '[{"content":"The user prefers dark mode.","id":"preference"}]',
+ );
+ await runtime.provider.shutdown();
+ });
+
it("uses the pre-allocated trace seed for the first activation root", async () => {
const runtime = createRuntime();
const seed: InstrumentationTraceContext = {
diff --git a/packages/eve/src/tracing/agent-otel-provider.ts b/packages/eve/src/tracing/agent-otel-provider.ts
index 30abd4aa9..6a2b4239a 100644
--- a/packages/eve/src/tracing/agent-otel-provider.ts
+++ b/packages/eve/src/tracing/agent-otel-provider.ts
@@ -34,6 +34,7 @@ import { agentSpanNamingAttributes } from "#tracing/agent-span-naming.js";
import { markAgentTraceContext } from "#tracing/agent-trace-context.js";
import { agentTraceIdentityAttributes } from "#tracing/agent-otel-attributes.js";
import * as runtimeAttributes from "#tracing/agent-otel-runtime-context.js";
+import { createAgentMemoryInstrumentation } from "#tracing/agent-memory-instrumentation.js";
import {
readGatewayCost,
setAgentInvocationUsage,
@@ -146,6 +147,11 @@ export function createAgentOtelInstrumentation(
},
tracer: input.tracer,
});
+ const memory = createAgentMemoryInstrumentation({
+ recordOutputs,
+ stateStore: input.stateStore,
+ tracer: input.tracer,
+ });
const { ensureSessionContext, prepareSessionTrace, prepareTurnTrace } =
createAgentOtelSessionContext(input);
@@ -533,6 +539,7 @@ export function createAgentOtelInstrumentation(
await tools.actionStarted(event);
},
...approvals,
+ ...memory.events,
"step.attempt.completed": onStepTerminal,
"step.attempt.failed": onStepTerminal,
"step.attempt.metadata": onStepMetadata,
@@ -557,6 +564,7 @@ export function createAgentOtelInstrumentation(
prepareSessionTrace,
prepareTurnTrace,
async runInContext(operation, execute) {
+ if (operation.type === "memory.operation") return memory.runInContext(operation, execute);
const scope = attemptScopes.get(operation.scope.attemptId) ?? operation.scope;
const contexts = executionContexts.get(scope);
let parent =
diff --git a/packages/eve/src/tracing/content-attributes.test.ts b/packages/eve/src/tracing/content-attributes.test.ts
index 2a9c68c93..b8b0df2ed 100644
--- a/packages/eve/src/tracing/content-attributes.test.ts
+++ b/packages/eve/src/tracing/content-attributes.test.ts
@@ -72,4 +72,18 @@ describe("withoutDeclinedContent", () => {
withoutDeclinedContent(attributes, { recordInputs: false, recordOutputs: false });
expect(attributes).toEqual(ATTRIBUTES);
});
+
+ it("redacts recalled memory records as output content", () => {
+ const searched = {
+ "gen_ai.memory.records": '[{"content":"Private preference"}]',
+ "gen_ai.operation.name": "search_memory",
+ };
+
+ expect(
+ withoutDeclinedContent(searched, { recordInputs: false, recordOutputs: true }),
+ ).toBeUndefined();
+ expect(withoutDeclinedContent(searched, { recordInputs: true, recordOutputs: false })).toEqual({
+ "gen_ai.operation.name": "search_memory",
+ });
+ });
});
diff --git a/packages/eve/src/tracing/content-attributes.ts b/packages/eve/src/tracing/content-attributes.ts
index bc7b3a866..df55143b9 100644
--- a/packages/eve/src/tracing/content-attributes.ts
+++ b/packages/eve/src/tracing/content-attributes.ts
@@ -51,6 +51,7 @@ const OUTPUT_CONTENT_ATTRIBUTES: ReadonlySet<string> = new Set([
"ai.response.tool_results",
"ai.toolCall.args",
"ai.toolCall.result",
+ "gen_ai.memory.records",
"gen_ai.output.messages",
"gen_ai.tool.call.result",
]);
diff --git a/packages/eve/src/tracing/install-instrumentation-runtime.test.ts b/packages/eve/src/tracing/install-instrumentation-runtime.test.ts
index b867f6ace..85e098bb4 100644
--- a/packages/eve/src/tracing/install-instrumentation-runtime.test.ts
+++ b/packages/eve/src/tracing/install-instrumentation-runtime.test.ts
@@ -75,6 +75,7 @@ describe("installInstrumentationRuntime", () => {
expect(forceFlush).toHaveBeenCalledOnce();
expect(providerFlush).toHaveBeenCalledOnce();
expect(runtime.instrumentationProviders).toBe(true);
+ expect(runtime.memoryOperations).toBe(true);
expect(runtime.ownsAgentSpans).toBe(true);
expect(runtime.otelSettings).toEqual({
functionId: undefined,
@@ -102,6 +103,25 @@ describe("installInstrumentationRuntime", () => {
expect(forceFlush).not.toHaveBeenCalled();
});
+ it("enables memory operations only for OTel or a provider that handles them", () => {
+ const withoutMemory = installInstrumentationRuntime({
+ collected: collectOtelPipeline([]),
+ frameworkVersion: "test",
+ providers: [{ events: { "turn.started": vi.fn() }, name: "turns" }],
+ serviceName: "weather",
+ });
+ delete (globalThis as Record<symbol, unknown>)[RUNTIME_GLOBAL_KEY];
+ const withMemory = installInstrumentationRuntime({
+ collected: collectOtelPipeline([]),
+ frameworkVersion: "test",
+ providers: [{ events: { "memory.operation.started": vi.fn() }, name: "memory" }],
+ serviceName: "weather",
+ });
+
+ expect(withoutMemory.memoryOperations).toBe(false);
+ expect(withMemory.memoryOperations).toBe(true);
+ });
+
it.each([
["session.completed", "conversation-1", true],
["session.failed", "conversation-1", true],
diff --git a/packages/eve/src/tracing/install-instrumentation-runtime.ts b/packages/eve/src/tracing/install-instrumentation-runtime.ts
index 30aee239a..48ed1e4e0 100644
--- a/packages/eve/src/tracing/install-instrumentation-runtime.ts
+++ b/packages/eve/src/tracing/install-instrumentation-runtime.ts
@@ -93,6 +93,7 @@ export function installInstrumentationRuntime(input: {
}),
idGenerator: otelRuntime?.idGenerator ?? new AgentSpanIdGenerator(),
instrumentationProviders: input.instrumentationProviders,
+ memoryOperations: otelRuntime !== undefined || input.providers.some(hasMemoryOperationHandler),
otelSettings: input.collected.declared ? input.collected.settings : undefined,
ownsAgentSpans: otelRuntime !== undefined,
prepareSessionTrace,
@@ -110,6 +111,14 @@ export function installInstrumentationRuntime(input: {
});
}
+function hasMemoryOperationHandler(provider: InstrumentationProviderDefinition): boolean {
+ return (
+ provider.events?.["memory.operation.started"] !== undefined ||
+ provider.events?.["memory.operation.completed"] !== undefined ||
+ provider.events?.["memory.operation.failed"] !== undefined
+ );
+}
+
function isSpanProcessor(processor: SpanProcessor | "auto"): processor is SpanProcessor {
return processor !== "auto";
}