The Open Framework for Building Agents
refactor(eve): define the flat instrumentation lifecycle protocol (#1856)
Chad Hietala749581b5b3a0
diff --git a/.changeset/flat-instrumentation-lifecycle.md b/.changeset/flat-instrumentation-lifecycle.mdnew file mode 100644index 000000000..4a51ef59a--- /dev/null+++ b/.changeset/flat-instrumentation-lifecycle.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Instrumentation lifecycle events now use eve-owned payloads and flat event names, including `step.attempt.*` and durable `input.requested`/`input.resolved` boundaries, instead of AI SDK callback types and paired hooks. Existing spans and attributes are unchanged.diff --git a/packages/eve/src/harness/ai-sdk-hook-bridge.test.ts b/packages/eve/src/harness/ai-sdk-hook-bridge.test.tsindex 4093b51ca..7b6017360 100644--- a/packages/eve/src/harness/ai-sdk-hook-bridge.test.ts+++ b/packages/eve/src/harness/ai-sdk-hook-bridge.test.ts@@ -3,9 +3,14 @@ import { describe, expect, it, vi } from "vitest";import { createAiSdkHookBridge } from "#harness/ai-sdk-hook-bridge.js";import {createInstrumentationHooks,- type InstrumentationAttemptMetadataEvent,type InstrumentationAttemptScope,+ type InstrumentationModelCallStartedEvent,+ type InstrumentationModelCallTerminalEvent,type InstrumentationProviderDefinition,+ type InstrumentationStepAttemptMetadataEvent,+ type InstrumentationStepAttemptStartedEvent,+ type InstrumentationToolCallStartedEvent,+ type InstrumentationToolCallTerminalEvent,} from "#harness/instrumentation-lifecycle.js";const scope: InstrumentationAttemptScope = {@@ -19,24 +24,25 @@ const scope: InstrumentationAttemptScope = {describe("createAiSdkHookBridge", () => {it("publishes normalized model lifecycle to every provider", async () => {const calls: string[] = [];- const provider = (name: string): InstrumentationProviderDefinition => ({- events: {- "model.call": {- before(event) {- calls.push(`${name}:before:${event.id}`);- return `${name}-state`;+ const provider = (name: string): InstrumentationProviderDefinition => {+ const states = new Map<string, string>();+ return {+ events: {+ "model.call.started"(event) {+ calls.push(`${name}:started:${event.id}`);+ states.set(event.id, `${name}-state`);},- after(event, state) {- calls.push(`${name}:after:${event.id}:${String(state)}`);+ "model.call.completed"(event) {+ calls.push(`${name}:completed:${event.id}:${String(states.get(event.id))}`);},},- },- });+ };+ };const hooks = createInstrumentationHooks([provider("a"), provider("b")]);const bridge = createAiSdkHookBridge(scope, hooks);await Reflect.apply(bridge.onLanguageModelCallStart!, bridge, [- { callId: "call-1", modelId: "model", provider: "test", tools: undefined },+ { callId: "call-1", messages: [], modelId: "model", provider: "test", tools: undefined },]);await Reflect.apply(bridge.onLanguageModelCallEnd!, bridge, [{@@ -51,10 +57,10 @@ describe("createAiSdkHookBridge", () => {const id = `${scope.attemptId}:model:call-1:0`;expect(calls).toEqual([- `a:before:${id}`,- `b:before:${id}`,- `a:after:${id}:a-state`,- `b:after:${id}:b-state`,+ `a:started:${id}`,+ `b:started:${id}`,+ `a:completed:${id}:a-state`,+ `b:completed:${id}:b-state`,]);});@@ -69,7 +75,7 @@ describe("createAiSdkHookBridge", () => {});const execute = vi.fn(async () => "result");await Reflect.apply(bridge.onLanguageModelCallStart!, bridge, [- { callId: "call-1", modelId: "model", provider: "test", tools: undefined },+ { callId: "call-1", messages: [], modelId: "model", provider: "test", tools: undefined },]);const result = await bridge.executeLanguageModelCall!({@@ -85,7 +91,7 @@ describe("createAiSdkHookBridge", () => {it("passes the identity captured at model-call start to the context runner", async () => {const ids: string[] = [];const hooks = createInstrumentationHooks([- { events: { "model.call": { before: (event) => ids.push(event.id) } } },+ { events: { "model.call.started": (event) => void ids.push(event.id) } },]);const bridge = createAiSdkHookBridge(scope, hooks, (operation, execute) => {ids.push(operation.id);@@ -96,7 +102,7 @@ describe("createAiSdkHookBridge", () => {]);await Reflect.apply(bridge.onStepStart!, bridge, [{ callId: "call-1", stepNumber: 0 }]);await Reflect.apply(bridge.onLanguageModelCallStart!, bridge, [- { callId: "call-1", modelId: "model", provider: "test", tools: undefined },+ { callId: "call-1", messages: [], modelId: "model", provider: "test", tools: undefined },]);await Reflect.apply(bridge.onStepStart!, bridge, [{ callId: "call-1", stepNumber: 1 }]);@@ -120,12 +126,12 @@ describe("createAiSdkHookBridge", () => {expect(adapterCalls).toBe(0);});- it("publishes step provider metadata as attempt.metadata, skipping steps without any", async () => {- const events: InstrumentationAttemptMetadataEvent[] = [];+ it("publishes step provider metadata as step.metadata, skipping steps without any", async () => {+ const events: InstrumentationStepAttemptMetadataEvent[] = [];const hooks = createInstrumentationHooks([{events: {- "attempt.metadata": (event) => {+ "step.attempt.metadata": (event) => {events.push(event);},},@@ -142,7 +148,7 @@ describe("createAiSdkHookBridge", () => {{providerMetadata: { gateway: { cost: "0.000082" } },scope,- type: "attempt.metadata",+ type: "step.attempt.metadata",},]);});@@ -152,19 +158,21 @@ describe("createAiSdkHookBridge", () => {const hooks = createInstrumentationHooks([{events: {- "model.call": {- before() {- throw new Error("provider failed");- },+ "model.call.started"() {+ throw new Error("provider failed");},},},- { events: { "model.call": { before: () => "state", after } } },+ {+ events: {+ "model.call.completed": after,+ },+ },]);const bridge = createAiSdkHookBridge(scope, hooks);await Reflect.apply(bridge.onLanguageModelCallStart!, bridge, [- { callId: "call-1", modelId: "model", provider: "test", tools: undefined },+ { callId: "call-1", messages: [], modelId: "model", provider: "test", tools: undefined },]);await Reflect.apply(bridge.onLanguageModelCallEnd!, bridge, [{@@ -182,62 +190,293 @@ describe("createAiSdkHookBridge", () => {it("terminalizes started operations when the attempt errors", async () => {const after = vi.fn();- const hooks = createInstrumentationHooks([- { events: { "model.call": { before: () => "state", after } } },- ]);+ const hooks = createInstrumentationHooks([{ events: { "model.call.failed": after } }]);const bridge = createAiSdkHookBridge(scope, hooks);await Reflect.apply(bridge.onLanguageModelCallStart!, bridge, [- { callId: "call-1", modelId: "model", provider: "test", tools: undefined },+ { callId: "call-1", messages: [], modelId: "model", provider: "test", tools: undefined },]);const error = new Error("model failed");- await Reflect.apply(bridge.onError!, bridge, [error]);+ await Reflect.apply(bridge.onError!, bridge, [{ callId: "call-1", error }]);expect(after).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ error, type: "model.call.failed" }),- "state",);});- it("publishes frozen callback snapshots", async () => {+ it("terminalizes started operations with the abort reason", async () => {+ const after = vi.fn();+ const hooks = createInstrumentationHooks([{ events: { "tool.call.failed": after } }]);+ const bridge = createAiSdkHookBridge(scope, hooks);+ const toolCall = { input: {}, toolCallId: "tool-1", toolName: "search" };++ await Reflect.apply(bridge.onToolExecutionStart!, bridge, [{ callId: "call-1", toolCall }]);+ const reason = new Error("model aborted");+ await Reflect.apply(bridge.onAbort!, bridge, [{ callId: "call-1", reason, steps: [] }]);++ expect(after).toHaveBeenCalledExactlyOnceWith(+ expect.objectContaining({ error: reason, type: "tool.call.failed" }),+ );+ });++ it("publishes an immutable operation projection to every provider", async () => {+ const mutator = vi.fn((event: InstrumentationStepAttemptStartedEvent) => {+ expect(Object.isFrozen(event)).toBe(true);+ expect(Object.isFrozen(event.operation)).toBe(true);+ expect(Reflect.set(event.operation, "modelId", "corrupted-model")).toBe(false);+ expect(Reflect.set(event.operation, "operationId", "corrupted-operation")).toBe(false);+ expect(Reflect.set(event.operation, "provider", "corrupted-provider")).toBe(false);+ });const started = vi.fn();- const hooks = createInstrumentationHooks([{ events: { "attempt.started": started } }]);+ const hooks = createInstrumentationHooks([+ { events: { "step.attempt.started": mutator } },+ { events: { "step.attempt.started": started } },+ ]);const bridge = createAiSdkHookBridge(scope, hooks);- const operation = {- callId: "call-1",- modelId: "model",- operationId: "ai.streamText",- provider: "test",++ Reflect.apply(bridge.onStart!, bridge, [+ { callId: "call-1", modelId: "model", operationId: "ai.streamText", provider: "test" },+ ]);+ await Reflect.apply(bridge.onStepStart!, bridge, [{ callId: "call-1", stepNumber: 0 }]);++ const expected = {+ operation: { modelId: "model", operationId: "ai.streamText", provider: "test" },+ scope,+ type: "step.attempt.started",};- const step = { callId: "call-1", stepNumber: 0 };-- Reflect.apply(bridge.onStart!, bridge, [operation]);- await Reflect.apply(bridge.onStepStart!, bridge, [step]);-- expect(started).toHaveBeenCalledOnce();- const event = started.mock.calls[0]?.[0];- expect(event).toEqual({ operation, scope, step, type: "attempt.started" });- expect(event.operation).not.toBe(operation);- expect(event.step).not.toBe(step);- expect(Object.isFrozen(event.operation)).toBe(true);- expect(Object.isFrozen(event.step)).toBe(true);+ expect(mutator).toHaveBeenCalledExactlyOnceWith(expected);+ expect(started).toHaveBeenCalledExactlyOnceWith(expected);+ });++ it("projects the model call callbacks onto eve fields only", async () => {+ const before = vi.fn((event: InstrumentationModelCallStartedEvent) => {+ expect(Object.isFrozen(event)).toBe(true);+ expect(Object.isFrozen(event.input)).toBe(true);+ expect(Object.isFrozen(event.input.messages)).toBe(true);+ expect(Object.isFrozen(event.model)).toBe(true);+ });+ const after = vi.fn((event: InstrumentationModelCallTerminalEvent) => {+ if (event.type !== "model.call.completed") throw new Error("expected completed model call");+ expect(Object.isFrozen(event)).toBe(true);+ expect(Object.isFrozen(event.content)).toBe(true);+ expect(event.content.every((part) => Object.isFrozen(part))).toBe(true);+ expect(Object.isFrozen(event.usage)).toBe(true);+ expect(Object.isFrozen(event.usage.inputTokenDetails)).toBe(true);+ });+ const hooks = createInstrumentationHooks([+ { events: { "model.call.completed": after, "model.call.started": before } },+ ]);+ const bridge = createAiSdkHookBridge(scope, hooks);++ await Reflect.apply(bridge.onLanguageModelCallStart!, bridge, [+ {+ callId: "call-1",+ instructions: "be brief",+ messages: [{ content: "hi", role: "user" }],+ modelId: "model",+ provider: "test",+ tools: undefined,+ },+ ]);+ await Reflect.apply(bridge.onLanguageModelCallEnd!, bridge, [+ {+ callId: "call-1",+ content: [+ { text: "thinking", type: "reasoning" },+ { text: "hello", type: "text" },+ { input: { a: 1 }, toolCallId: "tool-1", toolName: "search", type: "tool-call" },+ {+ input: { a: 1 },+ output: "ok",+ toolCallId: "tool-1",+ toolName: "search",+ type: "tool-result",+ },+ {+ error: "boom",+ input: { a: 2 },+ toolCallId: "tool-2",+ toolName: "search",+ type: "tool-error",+ },+ { type: "some-future-kind" },+ ],+ finishReason: "tool-calls",+ performance: { responseTimeMs: 1 },+ responseId: "response-1",+ usage: {+ inputTokenDetails: { cacheReadTokens: 3, cacheWriteTokens: 4 },+ inputTokens: 1,+ outputTokens: 2,+ },+ },+ ]);++ expect(before).toHaveBeenCalledExactlyOnceWith({+ id: `${scope.attemptId}:model:call-1:0`,+ input: { instructions: "be brief", messages: [{ content: "hi", role: "user" }] },+ model: { modelId: "model", provider: "test" },+ scope,+ type: "model.call.started",+ });+ // An unrecognized part kind is dropped rather than forwarded, so widening+ // InstrumentationContentPart is what makes a new kind reachable.+ expect(after).toHaveBeenCalledExactlyOnceWith({+ content: [+ { text: "thinking", type: "reasoning" },+ { text: "hello", type: "text" },+ { callId: "tool-1", input: { a: 1 }, toolName: "search", type: "tool-call" },+ {+ callId: "tool-1",+ input: { a: 1 },+ output: "ok",+ toolName: "search",+ type: "tool-result",+ },+ {+ callId: "tool-2",+ error: "boom",+ input: { a: 2 },+ toolName: "search",+ type: "tool-error",+ },+ ],+ finishReason: "tool-calls",+ id: `${scope.attemptId}:model:call-1:0`,+ scope,+ type: "model.call.completed",+ usage: {+ inputTokenDetails: { cacheReadTokens: 3, cacheWriteTokens: 4 },+ inputTokens: 1,+ outputTokens: 2,+ },+ });+ });++ it.each([+ {+ expected: { output: "ok", type: "result" },+ toolOutput: { output: "ok", type: "tool-result" },+ },+ {+ expected: { error: "boom", type: "error" },+ toolOutput: { error: "boom", type: "tool-error" },+ },+ ])(+ "collapses tool output $toolOutput.type onto $expected.type",+ async ({ expected, toolOutput }) => {+ const before = vi.fn((event: InstrumentationToolCallStartedEvent) => {+ expect(Object.isFrozen(event)).toBe(true);+ });+ const after = vi.fn((event: InstrumentationToolCallTerminalEvent) => {+ if (event.type !== "tool.call.completed") throw new Error("expected completed tool call");+ expect(Object.isFrozen(event)).toBe(true);+ expect(Object.isFrozen(event.output)).toBe(true);+ });+ const hooks = createInstrumentationHooks([+ { events: { "tool.call.completed": after, "tool.call.started": before } },+ ]);+ const bridge = createAiSdkHookBridge(scope, hooks);+ const toolCall = { input: { q: "eve" }, toolCallId: "tool-1", toolName: "search" };++ await Reflect.apply(bridge.onToolExecutionStart!, bridge, [{ callId: "call-1", toolCall }]);+ await Reflect.apply(bridge.onToolExecutionEnd!, bridge, [+ { callId: "call-1", toolCall, toolExecutionMs: 1, toolOutput },+ ]);++ expect(before).toHaveBeenCalledExactlyOnceWith({+ callId: "tool-1",+ id: `${scope.attemptId}:tool:tool-1:0`,+ input: { q: "eve" },+ scope,+ toolName: "search",+ type: "tool.call.started",+ });+ expect(after).toHaveBeenCalledExactlyOnceWith({+ id: `${scope.attemptId}:tool:tool-1:0`,+ output: expected,+ scope,+ type: "tool.call.completed",+ });+ },+ );++ it("keeps each provider's state to itself", async () => {+ const observed = new Map<string, unknown>();+ const provider = (name: string): InstrumentationProviderDefinition => {+ const own = new Map<string, string>();+ return {+ events: {+ "model.call.completed": (event) => {+ observed.set(name, own.get(event.id));+ },+ "model.call.started": (event) => void own.set(event.id, `${name}-state`),+ },+ };+ };+ const hooks = createInstrumentationHooks([provider("a"), provider("b")]);+ const bridge = createAiSdkHookBridge(scope, hooks);++ await Reflect.apply(bridge.onLanguageModelCallStart!, bridge, [+ { callId: "call-1", messages: [], modelId: "model", provider: "test", tools: undefined },+ ]);+ await Reflect.apply(bridge.onLanguageModelCallEnd!, bridge, [+ {+ callId: "call-1",+ content: [],+ finishReason: "stop",+ performance: { responseTimeMs: 1 },+ responseId: "response-1",+ usage: { inputTokens: 1, outputTokens: 1 },+ },+ ]);++ expect(observed).toEqual(+ new Map([+ ["a", "a-state"],+ ["b", "b-state"],+ ]),+ );+ });++ it("skips a terminal handler when the operation never started", async () => {+ const completed = vi.fn();+ const hooks = createInstrumentationHooks([{ events: { "model.call.completed": completed } }]);+ const bridge = createAiSdkHookBridge(scope, hooks);++ // No onLanguageModelCallStart, so the bridge holds no id and publishes+ // nothing — the handler must not run against empty state.+ await Reflect.apply(bridge.onLanguageModelCallEnd!, bridge, [+ {+ callId: "call-1",+ content: [],+ finishReason: "stop",+ performance: { responseTimeMs: 1 },+ responseId: "response-1",+ usage: { inputTokens: 1, outputTokens: 1 },+ },+ ]);++ expect(completed).not.toHaveBeenCalled();});it("retains state for parallel tool starts", async () => {const resolvers = new Map<string, () => void>();+ const started = new Map<string, string>();const terminalStates = new Map<string, unknown>();const hooks = createInstrumentationHooks([{events: {- "tool.call": {- before(event) {- return new Promise<string>((resolve) => {+ async "tool.call.started"(event) {+ started.set(+ event.id,+ await new Promise<string>((resolve) => {resolvers.set(event.id, () => resolve(`state:${event.id}`));- });- },- after(event, state) {- terminalStates.set(event.id, state);- },+ }),+ );+ },+ "tool.call.completed"(event) {+ terminalStates.set(event.id, started.get(event.id));},},},diff --git a/packages/eve/src/harness/ai-sdk-hook-bridge.ts b/packages/eve/src/harness/ai-sdk-hook-bridge.tsindex 80945ae65..d0239cf18 100644--- a/packages/eve/src/harness/ai-sdk-hook-bridge.ts+++ b/packages/eve/src/harness/ai-sdk-hook-bridge.ts@@ -2,13 +2,17 @@ import type { Telemetry } from "ai";import type {InstrumentationAttemptScope,- InstrumentationAttemptStartedEvent,+ InstrumentationStepAttemptStartedEvent,+ InstrumentationContentPart,InstrumentationContextRunner,InstrumentationHooks,InstrumentationModelCallCompletedEvent,InstrumentationModelCallStartedEvent,+ InstrumentationOperationRef,InstrumentationToolCallCompletedEvent,InstrumentationToolCallStartedEvent,+ InstrumentationToolOutput,+ InstrumentationUsage,} from "#harness/instrumentation-lifecycle.js";type TelemetryEvent<TKey extends keyof Telemetry> = Parameters<NonNullable<Telemetry[TKey]>>[0];@@ -17,8 +21,9 @@ interface AttemptState {readonly modelIds: Map<string, string>;readonly scope: InstrumentationAttemptScope;readonly toolIds: Map<string, string>;- operationStart?: Readonly<TelemetryEvent<"onStart">>;- stepStart?: Readonly<TelemetryEvent<"onStepStart">>;+ operation?: InstrumentationOperationRef;+ // Only the number is kept: it disambiguates call identities within an attempt.+ stepNumber?: number;}/** Creates one provider-neutral AI SDK bridge for one actual model attempt. */@@ -35,18 +40,22 @@ export function createAiSdkHookBridge(return {onStart(event) {- state.operationStart = snapshot(event);+ state.operation = Object.freeze({+ modelId: event.modelId,+ operationId: event.operationId,+ provider: event.provider,+ });},async onStepStart(event) {- state.stepStart = snapshot(event);- const started = toAttemptStarted(state);+ state.stepNumber = event.stepNumber;+ const started = toStepAttemptStarted(state);if (started !== undefined) await hooks.publish(started);},async onLanguageModelCallStart(event) {const id = createModelCallIdentity(state, event.callId);state.modelIds.set(event.callId, id);const started = toModelCallStarted(state, id, event);- await hooks.before("model.call", started);+ await hooks.publish(started);},executeLanguageModelCall({ callId, execute }) {const id = state.modelIds.get(callId);@@ -59,24 +68,26 @@ export function createAiSdkHookBridge(if (id === undefined) return;state.modelIds.delete(event.callId);const completed = toModelCallCompleted(state, id, event);- await hooks.after("model.call", completed);+ await hooks.publish(completed);},async onStepEnd(event) {// Step results carry provider metadata (e.g. Vercel AI Gateway cost)// that the per-call telemetry events don't. Publish it for providers// that know what to do with it; skip when there is none.if (event.providerMetadata === undefined) return;- await hooks.publish({- providerMetadata: event.providerMetadata,- scope: state.scope,- type: "attempt.metadata",- });+ await hooks.publish(+ Object.freeze({+ providerMetadata: event.providerMetadata,+ scope: state.scope,+ type: "step.attempt.metadata",+ }),+ );},async onToolExecutionStart(event) {const id = createToolCallIdentity(state, event.toolCall.toolCallId);state.toolIds.set(event.toolCall.toolCallId, id);const started = toToolCallStarted(state, id, event);- await hooks.before("tool.call", started);+ await hooks.publish(started);},executeTool({ toolCallId, execute }) {const id = state.toolIds.get(toolCallId);@@ -88,23 +99,23 @@ export function createAiSdkHookBridge(if (id === undefined) return;state.toolIds.delete(toolCallId);const completed = toToolCallCompleted(state, id, event);- await hooks.after("tool.call", completed);+ await hooks.publish(completed);},async onAbort(event) {- await failOpenOperations(event);+ await failOpenOperations(event.reason);},- async onError(error) {- await failOpenOperations(error);+ async onError(event) {+ await failOpenOperations((event as { readonly error: unknown }).error);},};async function failOpenOperations(error: unknown): Promise<void> {const pending: Promise<void>[] = [];for (const id of state.modelIds.values()) {- pending.push(hooks.after("model.call", { error, id, scope, type: "model.call.failed" }));+ pending.push(hooks.publish(Object.freeze({ error, id, scope, type: "model.call.failed" })));}for (const id of state.toolIds.values()) {- pending.push(hooks.after("tool.call", { error, id, scope, type: "tool.call.failed" }));+ pending.push(hooks.publish(Object.freeze({ error, id, scope, type: "tool.call.failed" })));}state.modelIds.clear();state.toolIds.clear();@@ -114,22 +125,19 @@ export function createAiSdkHookBridge(const directRunInContext: InstrumentationContextRunner = (_operation, execute) => execute();-function snapshot<T extends object>(event: T): Readonly<T> {- return Object.freeze({ ...event });-}--function toAttemptStarted(state: AttemptState): InstrumentationAttemptStartedEvent | undefined {- if (state.operationStart === undefined || state.stepStart === undefined) return undefined;- return {- operation: state.operationStart,+function toStepAttemptStarted(+ state: AttemptState,+): InstrumentationStepAttemptStartedEvent | undefined {+ if (state.operation === undefined || state.stepNumber === undefined) return undefined;+ return Object.freeze({+ operation: state.operation,scope: state.scope,- step: state.stepStart,- type: "attempt.started",- };+ type: "step.attempt.started",+ });}function createModelCallIdentity(state: AttemptState, callId: string): string {- return `${state.scope.attemptId}:model:${callId}:${state.stepStart?.stepNumber ?? 0}`;+ return `${state.scope.attemptId}:model:${callId}:${state.stepNumber ?? 0}`;}function toModelCallStarted(@@ -137,12 +145,16 @@ function toModelCallStarted(id: string,source: TelemetryEvent<"onLanguageModelCallStart">,): InstrumentationModelCallStartedEvent {- return {+ return Object.freeze({id,+ input: Object.freeze({+ instructions: source.instructions,+ messages: Object.freeze([...source.messages]),+ }),+ model: Object.freeze({ modelId: source.modelId, provider: source.provider }),scope: state.scope,- source: snapshot(source),type: "model.call.started",- };+ });}function toModelCallCompleted(@@ -150,16 +162,79 @@ function toModelCallCompleted(id: string,source: TelemetryEvent<"onLanguageModelCallEnd">,): InstrumentationModelCallCompletedEvent {- return {+ return Object.freeze({+ content: toContentParts(source.content),+ finishReason: source.finishReason,id,scope: state.scope,- source: snapshot(source),type: "model.call.completed",- };+ usage: toUsage(source.usage),+ });+}++function toUsage(usage: TelemetryEvent<"onLanguageModelCallEnd">["usage"]): InstrumentationUsage {+ return Object.freeze({+ inputTokenDetails: Object.freeze({+ cacheReadTokens: usage.inputTokenDetails?.cacheReadTokens,+ cacheWriteTokens: usage.inputTokenDetails?.cacheWriteTokens,+ }),+ inputTokens: usage.inputTokens,+ outputTokens: usage.outputTokens,+ });+}++/** Drops kinds eve does not record; see {@link InstrumentationContentPart}. */+function toContentParts(+ content: TelemetryEvent<"onLanguageModelCallEnd">["content"],+): readonly InstrumentationContentPart[] {+ const parts: InstrumentationContentPart[] = [];+ for (const part of content) {+ switch (part.type) {+ case "text":+ case "reasoning":+ parts.push(Object.freeze({ text: part.text, type: part.type }));+ break;+ case "tool-call":+ parts.push(+ Object.freeze({+ callId: part.toolCallId,+ input: part.input,+ toolName: part.toolName,+ type: "tool-call",+ }),+ );+ break;+ case "tool-result":+ parts.push(+ Object.freeze({+ callId: part.toolCallId,+ input: part.input,+ output: part.output,+ toolName: part.toolName,+ type: "tool-result",+ }),+ );+ break;+ case "tool-error":+ parts.push(+ Object.freeze({+ callId: part.toolCallId,+ error: part.error,+ input: part.input,+ toolName: part.toolName,+ type: "tool-error",+ }),+ );+ break;+ default:+ break;+ }+ }+ return Object.freeze(parts);}function createToolCallIdentity(state: AttemptState, toolCallId: string): string {- return `${state.scope.attemptId}:tool:${toolCallId}:${state.stepStart?.stepNumber ?? 0}`;+ return `${state.scope.attemptId}:tool:${toolCallId}:${state.stepNumber ?? 0}`;}function toToolCallStarted(@@ -167,12 +242,14 @@ function toToolCallStarted(id: string,source: TelemetryEvent<"onToolExecutionStart">,): InstrumentationToolCallStartedEvent {- return {+ return Object.freeze({+ callId: source.toolCall.toolCallId,id,+ input: source.toolCall.input,scope: state.scope,- source: snapshot(source),+ toolName: source.toolCall.toolName,type: "tool.call.started",- };+ });}function toToolCallCompleted(@@ -180,10 +257,18 @@ function toToolCallCompleted(id: string,source: TelemetryEvent<"onToolExecutionEnd">,): InstrumentationToolCallCompletedEvent {- return {+ return Object.freeze({id,+ output: toToolOutput(source.toolOutput),scope: state.scope,- source: snapshot(source),type: "tool.call.completed",- };+ });+}++function toToolOutput(+ toolOutput: TelemetryEvent<"onToolExecutionEnd">["toolOutput"],+): InstrumentationToolOutput {+ return toolOutput.type === "tool-result"+ ? Object.freeze({ output: toolOutput.output, type: "result" })+ : Object.freeze({ error: toolOutput.error, type: "error" });}diff --git a/packages/eve/src/harness/instrumentation-lifecycle.ts b/packages/eve/src/harness/instrumentation-lifecycle.tsindex b352b3b22..d3e87826c 100644--- a/packages/eve/src/harness/instrumentation-lifecycle.ts+++ b/packages/eve/src/harness/instrumentation-lifecycle.ts@@ -1,10 +1,14 @@-import type { Telemetry } from "ai";-import { createLogger, formatError } from "#internal/logging.js";-type TelemetryEvent<TKey extends keyof Telemetry> = Parameters<NonNullable<Telemetry[TKey]>>[0];--/** Stable eve identity for one actual model attempt. */+/**+ * Stable eve identity for one actual model attempt.+ *+ * A step retried three times produces three of these, all sharing `stepIndex`+ * and separated by `attemptIndex` — which is why the events carrying this+ * scope are named `step.attempt.*` and not `step.*`. The protocol's `step.*`+ * and the `events["step.started"]` resolver hook fire once per step; these+ * fire once per attempt.+ */export interface InstrumentationAttemptScope {readonly attemptId: string;readonly attemptIndex: number;@@ -15,11 +19,129 @@ export interface InstrumentationAttemptScope {readonly turnId: string;}-export interface InstrumentationAttemptStartedEvent {- readonly type: "attempt.started";+/** The model SDK operation an attempt runs through. */+export interface InstrumentationOperationRef {+ readonly modelId: string;+ readonly operationId: string;+ readonly provider: string;+}++export interface InstrumentationModelRef {+ readonly modelId: string;+ readonly provider: string;+}++/** Token usage for one model call. A field is absent when the provider omits it. */+export interface InstrumentationUsage {+ readonly inputTokenDetails?: {+ readonly cacheReadTokens?: number;+ readonly cacheWriteTokens?: number;+ };+ readonly inputTokens?: number;+ readonly outputTokens?: number;+}++/** Final model input for one call. Message shape stays opaque to this layer. */+export interface InstrumentationModelInput {+ readonly instructions?: unknown;+ readonly messages: readonly unknown[];+}++/**+ * The model response parts eve records. A kind outside this union is dropped+ * when the bridge maps a response, so widening the union is what makes a new+ * kind reachable by a provider.+ */+export type InstrumentationContentPart =+ | { readonly type: "text"; readonly text: string }+ | { readonly type: "reasoning"; readonly text: string }+ | {+ readonly type: "tool-call";+ readonly callId: string;+ readonly input: unknown;+ readonly toolName: string;+ }+ | {+ readonly type: "tool-result";+ readonly callId: string;+ readonly input: unknown;+ readonly output: unknown;+ readonly toolName: string;+ }+ | {+ readonly type: "tool-error";+ readonly callId: string;+ readonly error: unknown;+ readonly input: unknown;+ readonly toolName: string;+ };++/** How one tool execution ended. */+export type InstrumentationToolOutput =+ | { readonly type: "result"; readonly output: unknown }+ | { readonly type: "error"; readonly error: unknown };++/** Framework-owned reason an agent suspended for user input. */+export type InstrumentationInputKind = "question" | "session-limit" | "tool-approval";++export interface InstrumentationInputOption {+ readonly description?: string;+ readonly id: string;+ readonly label: string;+ readonly style?: "danger" | "default" | "primary";+}++/** User-facing input request content projected without runtime-owned types. */+export interface InstrumentationInputRequest {+ readonly allowFreeform?: boolean;+ readonly display?: "confirmation" | "select" | "text";+ readonly options?: readonly InstrumentationInputOption[];+ readonly prompt: string;+}++/** User response content projected without runtime-owned types. */+export interface InstrumentationInputResponse {+ readonly optionId?: string;+ readonly text?: string;+}++export type InstrumentationInputOutcome =+ | "answered"+ | "approved"+ | "cancelled"+ | "denied"+ | "failed"+ | "ignored"+ | "invalid";++export interface InstrumentationInputRequestedEvent {+ readonly type: "input.requested";+ readonly action: {+ readonly callId: string;+ readonly name: string;+ };+ readonly id: string;+ readonly kind: InstrumentationInputKind;+ readonly request: InstrumentationInputRequest;+ readonly requestId: string;+ readonly scope: InstrumentationAttemptScope;+}++export interface InstrumentationInputResolvedEvent {+ readonly type: "input.resolved";+ readonly error?: unknown;+ readonly id: string;+ readonly kind: InstrumentationInputKind;+ readonly outcome: InstrumentationInputOutcome;+ readonly requestId: string;+ readonly response?: InstrumentationInputResponse;+ readonly scope: InstrumentationAttemptScope;+}++export interface InstrumentationStepAttemptStartedEvent {+ readonly type: "step.attempt.started";+ readonly operation: InstrumentationOperationRef;readonly scope: InstrumentationAttemptScope;- readonly operation: TelemetryEvent<"onStart">;- readonly step: TelemetryEvent<"onStepStart">;}export interface InstrumentationSessionStartedEvent {@@ -48,13 +170,30 @@ export interface InstrumentationParentLineage {readonly turnId: string;}-export interface InstrumentationSessionTransitionEvent {- readonly type: "session.completed" | "session.failed" | "session.waiting";- readonly error?: unknown;+/**+ * A session transition that carries no failure.+ *+ * `session.waiting` sits here rather than with the failed shape because it is+ * not terminal: the session suspends awaiting input or approval and may resume+ * with a new turn.+ */+export interface InstrumentationSessionSettledEvent {+ readonly type: "session.completed" | "session.waiting";+ readonly sessionId: string;+ readonly turnId?: string;+}++export interface InstrumentationSessionFailedEvent {+ readonly type: "session.failed";+ readonly error: unknown;readonly sessionId: string;readonly turnId?: string;}+export type InstrumentationSessionTransitionEvent =+ | InstrumentationSessionSettledEvent+ | InstrumentationSessionFailedEvent;+export interface InstrumentationTurnStartedEvent {readonly type: "turn.started";readonly parentLineage?: InstrumentationParentLineage;@@ -72,19 +211,19 @@ export interface InstrumentationTurnTerminalEvent {readonly turnId: string;}-export interface InstrumentationAttemptTerminalEvent {- readonly type: "attempt.completed" | "attempt.failed";+export interface InstrumentationStepAttemptTerminalEvent {+ readonly type: "step.attempt.completed" | "step.attempt.failed";readonly error?: unknown;readonly scope: InstrumentationAttemptScope;}/**- * Provider metadata for one completed step, as reported by the AI SDK+ * Provider metadata for one completed attempt, as reported by the AI SDK* (`StepResult.providerMetadata`). Carries Vercel AI Gateway cost data when* the request went through the gateway; absent for other providers.*/-export interface InstrumentationAttemptMetadataEvent {- readonly type: "attempt.metadata";+export interface InstrumentationStepAttemptMetadataEvent {+ readonly type: "step.attempt.metadata";readonly scope: InstrumentationAttemptScope;readonly providerMetadata: Readonly<Record<string, unknown>>;}@@ -92,15 +231,18 @@ export interface InstrumentationAttemptMetadataEvent {export interface InstrumentationModelCallStartedEvent {readonly type: "model.call.started";readonly id: string;+ readonly input: InstrumentationModelInput;+ readonly model: InstrumentationModelRef;readonly scope: InstrumentationAttemptScope;- readonly source: TelemetryEvent<"onLanguageModelCallStart">;}export interface InstrumentationModelCallCompletedEvent {readonly type: "model.call.completed";+ readonly content: readonly InstrumentationContentPart[];+ readonly finishReason: string;readonly id: string;readonly scope: InstrumentationAttemptScope;- readonly source: TelemetryEvent<"onLanguageModelCallEnd">;+ readonly usage: InstrumentationUsage;}export interface InstrumentationModelCallFailedEvent {@@ -116,16 +258,18 @@ export type InstrumentationModelCallTerminalEvent =export interface InstrumentationToolCallStartedEvent {readonly type: "tool.call.started";+ readonly callId: string;readonly id: string;+ readonly input: unknown;readonly scope: InstrumentationAttemptScope;- readonly source: TelemetryEvent<"onToolExecutionStart">;+ readonly toolName: string;}export interface InstrumentationToolCallCompletedEvent {readonly type: "tool.call.completed";readonly id: string;+ readonly output: InstrumentationToolOutput;readonly scope: InstrumentationAttemptScope;- readonly source: TelemetryEvent<"onToolExecutionEnd">;}export interface InstrumentationToolCallFailedEvent {@@ -139,79 +283,59 @@ export type InstrumentationToolCallTerminalEvent =| InstrumentationToolCallCompletedEvent| InstrumentationToolCallFailedEvent;-export interface RelatedLifecycleHook<TStart, TTerminal> {- readonly before?: (event: TStart) => unknown | PromiseLike<unknown>;- readonly after?: (event: TTerminal, state: unknown) => void | PromiseLike<void>;-}+/**+ * The AI SDK can omit a model terminal when an incomplete stream closes. A+ * provider that correlates starts with terminals must scope that state to the+ * attempt and release anything still open when the step attempt terminates.+ */+export type InstrumentationEventHandler<TEvent> = (event: TEvent) => void | PromiseLike<void>;/** Internal provider shape mirrored by the future public hook contract. */export interface InstrumentationProviderDefinition {readonly events?: {- readonly "model.call"?: RelatedLifecycleHook<- InstrumentationModelCallStartedEvent,- InstrumentationModelCallTerminalEvent- >;- readonly "attempt.started"?: (- event: InstrumentationAttemptStartedEvent,- ) => void | PromiseLike<void>;- readonly "attempt.completed"?: (- event: InstrumentationAttemptTerminalEvent,- ) => void | PromiseLike<void>;- readonly "attempt.failed"?: (- event: InstrumentationAttemptTerminalEvent,- ) => void | PromiseLike<void>;- readonly "attempt.metadata"?: (- event: InstrumentationAttemptMetadataEvent,- ) => void | PromiseLike<void>;- readonly "session.completed"?: (- event: InstrumentationSessionTransitionEvent,- ) => void | PromiseLike<void>;- readonly "session.failed"?: (- event: InstrumentationSessionTransitionEvent,- ) => void | PromiseLike<void>;- readonly "session.started"?: (- event: InstrumentationSessionStartedEvent,- ) => void | PromiseLike<void>;- readonly "session.waiting"?: (- event: InstrumentationSessionTransitionEvent,- ) => void | PromiseLike<void>;- readonly "tool.call"?: RelatedLifecycleHook<- InstrumentationToolCallStartedEvent,- InstrumentationToolCallTerminalEvent- >;- readonly "turn.cancelled"?: (- event: InstrumentationTurnTerminalEvent,- ) => void | PromiseLike<void>;- readonly "turn.completed"?: (- event: InstrumentationTurnTerminalEvent,- ) => void | PromiseLike<void>;- readonly "turn.failed"?: (event: InstrumentationTurnTerminalEvent) => void | PromiseLike<void>;- readonly "turn.started"?: (event: InstrumentationTurnStartedEvent) => void | PromiseLike<void>;+ readonly "step.attempt.started"?: InstrumentationEventHandler<InstrumentationStepAttemptStartedEvent>;+ readonly "step.attempt.completed"?: InstrumentationEventHandler<InstrumentationStepAttemptTerminalEvent>;+ readonly "step.attempt.failed"?: InstrumentationEventHandler<InstrumentationStepAttemptTerminalEvent>;+ readonly "step.attempt.metadata"?: InstrumentationEventHandler<InstrumentationStepAttemptMetadataEvent>;+ readonly "model.call.started"?: InstrumentationEventHandler<InstrumentationModelCallStartedEvent>;+ readonly "model.call.completed"?: InstrumentationEventHandler<InstrumentationModelCallCompletedEvent>;+ readonly "model.call.failed"?: InstrumentationEventHandler<InstrumentationModelCallFailedEvent>;+ readonly "input.requested"?: InstrumentationEventHandler<InstrumentationInputRequestedEvent>;+ readonly "input.resolved"?: InstrumentationEventHandler<InstrumentationInputResolvedEvent>;+ readonly "session.completed"?: InstrumentationEventHandler<InstrumentationSessionSettledEvent>;+ readonly "session.failed"?: InstrumentationEventHandler<InstrumentationSessionFailedEvent>;+ readonly "session.started"?: InstrumentationEventHandler<InstrumentationSessionStartedEvent>;+ readonly "session.waiting"?: InstrumentationEventHandler<InstrumentationSessionSettledEvent>;+ readonly "tool.call.started"?: InstrumentationEventHandler<InstrumentationToolCallStartedEvent>;+ readonly "tool.call.completed"?: InstrumentationEventHandler<InstrumentationToolCallCompletedEvent>;+ readonly "tool.call.failed"?: InstrumentationEventHandler<InstrumentationToolCallFailedEvent>;+ readonly "turn.cancelled"?: InstrumentationEventHandler<InstrumentationTurnTerminalEvent>;+ readonly "turn.completed"?: InstrumentationEventHandler<InstrumentationTurnTerminalEvent>;+ readonly "turn.failed"?: InstrumentationEventHandler<InstrumentationTurnTerminalEvent>;+ readonly "turn.started"?: InstrumentationEventHandler<InstrumentationTurnStartedEvent>;};}-export interface InstrumentationRelatedEventMap {- readonly "model.call": {- readonly start: InstrumentationModelCallStartedEvent;- readonly terminal: InstrumentationModelCallTerminalEvent;- };- readonly "tool.call": {- readonly start: InstrumentationToolCallStartedEvent;- readonly terminal: InstrumentationToolCallTerminalEvent;- };-}--export type InstrumentationRelatedEventName = keyof InstrumentationRelatedEventMap;+/** Events that carry an operation `id`, pairing a start with its terminal. */+export type InstrumentationCorrelatedEvent =+ | InstrumentationInputRequestedEvent+ | InstrumentationInputResolvedEvent+ | InstrumentationModelCallStartedEvent+ | InstrumentationModelCallTerminalEvent+ | InstrumentationToolCallStartedEvent+ | InstrumentationToolCallTerminalEvent;export type InstrumentationPointEvent =- | InstrumentationAttemptStartedEvent- | InstrumentationAttemptMetadataEvent- | InstrumentationAttemptTerminalEvent+ | InstrumentationStepAttemptStartedEvent+ | InstrumentationStepAttemptMetadataEvent+ | InstrumentationStepAttemptTerminalEvent| InstrumentationSessionStartedEvent| InstrumentationSessionTransitionEvent| InstrumentationTurnStartedEvent| InstrumentationTurnTerminalEvent;+export type InstrumentationEvent = InstrumentationCorrelatedEvent | InstrumentationPointEvent;+/** Trusted framework operation for activating context around AI SDK execution. */export type InstrumentationContextRunner = <T>(operation: InstrumentationExecutionOperation,@@ -233,15 +357,7 @@ export type InstrumentationExecutionOperation =/** Provider-neutral hook operations consumed by the AI SDK bridge. */export interface InstrumentationHooks {- after<TKey extends InstrumentationRelatedEventName>(- name: TKey,- event: InstrumentationRelatedEventMap[TKey]["terminal"],- ): Promise<void>;- before<TKey extends InstrumentationRelatedEventName>(- name: TKey,- event: InstrumentationRelatedEventMap[TKey]["start"],- ): Promise<void>;- publish(event: InstrumentationPointEvent): Promise<void>;+ publish(event: InstrumentationEvent): Promise<void>;}const log = createLogger("harness.instrumentation-lifecycle");@@ -250,71 +366,20 @@ const log = createLogger("harness.instrumentation-lifecycle");export function createInstrumentationHooks(providers: readonly InstrumentationProviderDefinition[],): InstrumentationHooks {- const relatedState = new WeakMap<InstrumentationAttemptScope, Map<string, unknown>>();-- const publish = async (event: InstrumentationPointEvent): Promise<void> => {+ const publish = async (event: InstrumentationEvent): Promise<void> => {for (const provider of providers) {const handler = provider.events?.[event.type];if (handler === undefined) continue;try {- await (handler as (value: typeof event) => void | PromiseLike<void>)(event);- } catch (error) {- warn(event.type, error);- }- }- };-- const before = async <TKey extends InstrumentationRelatedEventName>(- name: TKey,- event: InstrumentationRelatedEventMap[TKey]["start"],- ): Promise<void> => {- const attemptState = relatedState.get(event.scope) ?? new Map<string, unknown>();- relatedState.set(event.scope, attemptState);- for (const [providerIndex, provider] of providers.entries()) {- const handler = provider.events?.[name]?.before;- if (handler === undefined) continue;- try {- const state = await (handler as (value: typeof event) => unknown)(event);- attemptState.set(relatedStateKey(providerIndex, event.id), state);+ await (handler as InstrumentationEventHandler<InstrumentationEvent>)(event);} catch (error) {- warn(`${name}.before`, error);+ log.warn("instrumentation provider failed", {+ boundary: event.type,+ error: formatError(error),+ });}}};- const after = async <TKey extends InstrumentationRelatedEventName>(- name: TKey,- event: InstrumentationRelatedEventMap[TKey]["terminal"],- ): Promise<void> => {- const attemptState = relatedState.get(event.scope);- for (const [providerIndex, provider] of providers.entries()) {- const handler = provider.events?.[name]?.after;- const stateKey = relatedStateKey(providerIndex, event.id);- if (handler === undefined || !attemptState?.has(stateKey)) continue;- const state = attemptState.get(stateKey);- attemptState.delete(stateKey);- try {- await (handler as (value: typeof event, state: unknown) => void | PromiseLike<void>)(- event,- state,- );- } catch (error) {- warn(`${name}.after`, error);- }- }- };-- const warn = (boundary: string, error: unknown): void => {- log.warn("instrumentation provider failed", { boundary, error: formatError(error) });- };-- return {- after,- before,- publish,- };-}--function relatedStateKey(providerIndex: number, operationId: string): string {- return `${providerIndex}:${operationId}`;+ return { publish };}diff --git a/packages/eve/src/harness/instrumentation-native-events.test.ts b/packages/eve/src/harness/instrumentation-native-events.test.tsindex 629e8a9ee..7f6bdd8c3 100644--- a/packages/eve/src/harness/instrumentation-native-events.test.ts+++ b/packages/eve/src/harness/instrumentation-native-events.test.ts@@ -15,8 +15,6 @@ describe("createInstrumentationHandleEvent", () => {it("publishes native lifecycle transitions after durable handling", async () => {const order: string[] = [];const hooks: InstrumentationHooks = {- after: async () => {},- before: async () => {},publish: async (event) => {order.push(`lifecycle:${event.type}`);},@@ -69,8 +67,6 @@ describe("createInstrumentationHandleEvent", () => {expect(createInstrumentationHandleEvent({hooks: {- after: async () => {},- before: async () => {},publish: async () => {},},sessionId: "session-1",@@ -83,8 +79,6 @@ describe("createInstrumentationHandleEvent", () => {const handleEvent = createInstrumentationHandleEvent({handleEvent: async () => {},hooks: {- after: async () => {},- before: async () => {},publish: async (event) => {events.push(event);},@@ -109,8 +103,6 @@ describe("createInstrumentationHandleEvent", () => {const handleEvent = createInstrumentationHandleEvent({handleEvent: async () => {},hooks: {- after: async () => {},- before: async () => {},publish: async (event) => {events.push(event);},diff --git a/packages/eve/src/harness/tool-loop.test.ts b/packages/eve/src/harness/tool-loop.test.tsindex 46c7ab923..660c43e44 100644--- a/packages/eve/src/harness/tool-loop.test.ts+++ b/packages/eve/src/harness/tool-loop.test.ts@@ -10184,7 +10184,7 @@ describe("createToolLoopHarness", () => {});const attemptCompleted = vi.fn();const hooks = createInstrumentationHooks([- { events: { "attempt.completed": attemptCompleted } },+ { events: { "step.attempt.completed": attemptCompleted } },]);const runInContext: InstrumentationContextRunner = (_operation, execute) => execute();const config = createTestConfig("conversation", undefined, {@@ -10221,7 +10221,7 @@ describe("createToolLoopHarness", () => {expect(attemptCompleted).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({scope: expect.objectContaining({ attemptIndex: 0 }),- type: "attempt.completed",+ type: "step.attempt.completed",}),);});diff --git a/packages/eve/src/harness/tool-loop.ts b/packages/eve/src/harness/tool-loop.tsindex 738548c49..f0d43f46f 100644--- a/packages/eve/src/harness/tool-loop.ts+++ b/packages/eve/src/harness/tool-loop.ts@@ -1430,7 +1430,10 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {try {const result = await executeModelCall();if (attemptScope !== undefined) {- await instrumentationHooks?.publish({ scope: attemptScope, type: "attempt.completed" });+ await instrumentationHooks?.publish({+ scope: attemptScope,+ type: "step.attempt.completed",+ });}return result;} catch (error) {@@ -1438,7 +1441,7 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {await instrumentationHooks?.publish({error,scope: attemptScope,- type: "attempt.failed",+ type: "step.attempt.failed",});}return rethrowNoOutputAsEmptyResponse(error);diff --git a/packages/eve/src/tracing/agent-otel-provider.test.ts b/packages/eve/src/tracing/agent-otel-provider.test.tsindex d8380faf1..c36dfa4e6 100644--- a/packages/eve/src/tracing/agent-otel-provider.test.ts+++ b/packages/eve/src/tracing/agent-otel-provider.test.ts@@ -8,12 +8,12 @@ import {import { describe, expect, it } from "vitest";import { createAiSdkHookBridge } from "#harness/ai-sdk-hook-bridge.js";+import { createAgentOtelInstrumentation } from "#tracing/agent-otel-provider.js";+import { AgentSpanIdGenerator } from "#tracing/agent-span-id-generator.js";import {- createAgentOtelInstrumentation,+ InMemoryAgentTraceStateStore,SESSION_WINDOW_TURN_LIMIT,-} from "#tracing/agent-otel-provider.js";-import { AgentSpanIdGenerator } from "#tracing/agent-span-id-generator.js";-import { InMemoryAgentTraceStateStore } from "#tracing/agent-trace-state.js";+} from "#tracing/agent-trace-state.js";import {createInstrumentationHooks,type InstrumentationAttemptScope,@@ -49,10 +49,13 @@ function createRuntime(stateStore = new InMemoryAgentTraceStateStore()): TestRunasync function emitAttempt(input: {readonly attemptIndex?: number;+ readonly attemptError?: Error;readonly hooks: InstrumentationHooks;readonly runInContext: InstrumentationContextRunner;readonly providerMetadata?: Readonly<Record<string, unknown>>;readonly sessionId: string;+ readonly skipModelTerminal?: boolean;+ readonly skipToolTerminal?: boolean;readonly toolError?: Error;readonly turnAlreadyStarted?: boolean;readonly turnId: string;@@ -98,38 +101,40 @@ async function emitAttempt(input: {},]);await bridge.executeLanguageModelCall!({ callId: "call-1", execute: async () => undefined });- await Reflect.apply(bridge.onLanguageModelCallEnd!, bridge, [- {- callId: "call-1",- content: [- { type: "reasoning", text: "thinking about weather" },- { type: "text", text: "Checking the weather." },- {- input: { query: "weather today" },- providerExecuted: true,- toolCallId: "search-1",- toolName: "web_search",- type: "tool-call",- },- {- input: { query: "weather today" },- output: { results: ["sunny"] },- providerExecuted: true,- toolCallId: "search-1",- toolName: "web_search",- type: "tool-result",+ if (input.skipModelTerminal !== true) {+ await Reflect.apply(bridge.onLanguageModelCallEnd!, bridge, [+ {+ callId: "call-1",+ content: [+ { type: "reasoning", text: "thinking about weather" },+ { type: "text", text: "Checking the weather." },+ {+ input: { query: "weather today" },+ providerExecuted: true,+ toolCallId: "search-1",+ toolName: "web_search",+ type: "tool-call",+ },+ {+ input: { query: "weather today" },+ output: { results: ["sunny"] },+ providerExecuted: true,+ toolCallId: "search-1",+ toolName: "web_search",+ type: "tool-result",+ },+ ],+ finishReason: "tool-calls",+ performance: { responseTimeMs: 10 },+ responseId: "response-1",+ usage: {+ inputTokenDetails: { cacheReadTokens: 4, cacheWriteTokens: 2 },+ inputTokens: 10,+ outputTokens: 5,},- ],- finishReason: "tool-calls",- performance: { responseTimeMs: 10 },- responseId: "response-1",- usage: {- inputTokenDetails: { cacheReadTokens: 4, cacheWriteTokens: 2 },- inputTokens: 10,- outputTokens: 5,},- },- ]);+ ]);+ }await Reflect.apply(bridge.onToolExecutionStart!, bridge, [{callId: "call-1",@@ -141,28 +146,34 @@ async function emitAttempt(input: {execute: async () => undefined,toolCallId: "tool-1",});- await Reflect.apply(bridge.onToolExecutionEnd!, bridge, [- {- callId: "call-1",- messages: [],- toolCall: { input: {}, toolCallId: "tool-1", toolName: "weather" },- toolExecutionMs: 1,- toolOutput:- input.toolError === undefined- ? { output: { temperature: 72 }, type: "tool-result" }- : { error: input.toolError, type: "tool-error" },- },- ]);+ if (input.skipToolTerminal !== true) {+ await Reflect.apply(bridge.onToolExecutionEnd!, bridge, [+ {+ callId: "call-1",+ messages: [],+ toolCall: { input: {}, toolCallId: "tool-1", toolName: "weather" },+ toolExecutionMs: 1,+ toolOutput:+ input.toolError === undefined+ ? { output: { temperature: 72 }, type: "tool-result" }+ : { error: input.toolError, type: "tool-error" },+ },+ ]);+ }if (input.providerMetadata !== undefined) {await input.hooks.publish({providerMetadata: input.providerMetadata,scope,- type: "attempt.metadata",+ type: "step.attempt.metadata",});}- await input.hooks.publish({ scope, type: "attempt.completed" });+ await input.hooks.publish(+ input.attemptError === undefined+ ? { scope, type: "step.attempt.completed" }+ : { error: input.attemptError, scope, type: "step.attempt.failed" },+ );await input.hooks.publish({sessionId: input.sessionId,turnId: input.turnId,@@ -248,6 +259,7 @@ describe("createAgentOtelInstrumentation", () => {expect(session.attributes).toMatchObject({"agent.session.id": "session-1","agent.session.window": 0,+ "agent.trace.schema.version": 1,});expect(turn.parentSpanContext?.spanId).toBe(session.spanContext().spanId);expect(step.parentSpanContext?.spanId).toBe(turn.spanContext().spanId);@@ -284,6 +296,54 @@ describe("createAgentOtelInstrumentation", () => {});});+ it("ends model and tool spans still open when the step attempt terminates", async () => {+ const runtime = createRuntime();+ await emitAttempt({+ hooks: runtime.hooks,+ runInContext: runtime.runInContext,+ sessionId: "session-1",+ skipModelTerminal: true,+ skipToolTerminal: true,+ turnId: "turn-1",+ turnSequence: 0,+ });+ await runtime.provider.forceFlush();++ const spans = runtime.exporter.getFinishedSpans();+ expect(byName(spans, "ai.streamText.doStream")).toHaveLength(1);+ expect(byName(spans, "agent.action")).toHaveLength(1);+ expect(byName(spans, "ai.toolCall")).toHaveLength(1);+ expect(byName(spans, "agent.step")).toHaveLength(1);+ });++ it("records a failed attempt on model, tool, and action spans still open", async () => {+ const runtime = createRuntime();+ const error = new Error("attempt failed");+ await emitAttempt({+ attemptError: error,+ hooks: runtime.hooks,+ runInContext: runtime.runInContext,+ sessionId: "session-1",+ skipModelTerminal: true,+ skipToolTerminal: true,+ turnId: "turn-1",+ turnSequence: 0,+ });+ await runtime.provider.forceFlush();++ const spans = runtime.exporter.getFinishedSpans();+ for (const name of ["ai.streamText.doStream", "agent.action", "ai.toolCall"]) {+ const span = byName(spans, name)[0]!;+ expect(span.status).toEqual({ code: SpanStatusCode.ERROR, message: error.message });+ expect(span.events).toContainEqual(+ expect.objectContaining({+ attributes: expect.objectContaining({ "exception.message": error.message }),+ name: "exception",+ }),+ );+ }+ });+it("captures model and tool inputs/outputs on the operation spans", async () => {const runtime = createRuntime();await emitAttempt({@@ -311,10 +371,10 @@ describe("createAgentOtelInstrumentation", () => {// Provider-executed tools never reach the tool loop; their calls and// results are captured off the model response content.expect(model.attributes["ai.response.tool_calls"]).toBe(- '[{"input":{"query":"weather today"},"toolName":"web_search"}]',+ '[{"callId":"search-1","input":{"query":"weather today"},"toolName":"web_search"}]',);expect(model.attributes["ai.response.tool_results"]).toBe(- '[{"input":{"query":"weather today"},"output":{"results":["sunny"]},"toolName":"web_search"}]',+ '[{"callId":"search-1","input":{"query":"weather today"},"output":{"results":["sunny"]},"toolName":"web_search"}]',);expect(tool.attributes["gen_ai.tool.call.arguments"]).toBe('{"secret":"value"}');expect(tool.attributes["gen_ai.tool.call.result"]).toBe('{"temperature":72}');diff --git a/packages/eve/src/tracing/agent-otel-provider.ts b/packages/eve/src/tracing/agent-otel-provider.tsindex 548bc237c..84e7e7620 100644--- a/packages/eve/src/tracing/agent-otel-provider.ts+++ b/packages/eve/src/tracing/agent-otel-provider.ts@@ -9,6 +9,11 @@ import {trace,} from "#compiled/@opentelemetry/api/index.js";+import {+ SESSION_WINDOW_TURN_LIMIT,+ type AgentSessionTraceState,+ type AgentTraceStateStore,+} from "#tracing/agent-trace-state.js";import {contentAttribute,messagesContentAttribute,@@ -17,12 +22,11 @@ import {toolResultsContentAttribute,} from "#tracing/agent-otel-content.js";import type { AgentSpanIdGenerator } from "#tracing/agent-span-id-generator.js";-import type { AgentSessionTraceState, AgentTraceStateStore } from "#tracing/agent-trace-state.js";import type {- InstrumentationAttemptMetadataEvent,+ InstrumentationStepAttemptMetadataEvent,InstrumentationAttemptScope,- InstrumentationAttemptStartedEvent,- InstrumentationAttemptTerminalEvent,+ InstrumentationStepAttemptStartedEvent,+ InstrumentationStepAttemptTerminalEvent,InstrumentationContextRunner,InstrumentationModelCallTerminalEvent,InstrumentationModelCallStartedEvent,@@ -35,6 +39,7 @@ import type {InstrumentationToolCallTerminalEvent,InstrumentationTurnStartedEvent,InstrumentationTurnTerminalEvent,+ InstrumentationUsage,} from "#harness/instrumentation-lifecycle.js";interface SpanState {@@ -51,9 +56,6 @@ interface ToolSpanState extends SpanState {readonly toolSpan: Span;}-/** Sized so an ordinary session stays one trace and only an outsized one rolls. */-export const SESSION_WINDOW_TURN_LIMIT = 200;-export interface AgentOtelInstrumentationInput {/*** Capture model prompts/responses and tool call inputs/outputs as span@@ -86,6 +88,8 @@ export function createAgentOtelInstrumentation(// that worker is lost, Workflow retries the whole step from entry rather// than resuming this callback sequence in a replacement process.const steps = new WeakMap<InstrumentationAttemptScope, AttemptSpanState>();+ const modelSpans = new WeakMap<InstrumentationAttemptScope, Map<string, SpanState>>();+ const toolSpans = new WeakMap<InstrumentationAttemptScope, Map<string, ToolSpanState>>();const onSessionStarted = async (event: InstrumentationSessionStartedEvent): Promise<void> => {await ensureSessionContext(event);@@ -126,7 +130,7 @@ export function createAgentOtelInstrumentation(});};- const onAttemptStarted = async (event: InstrumentationAttemptStartedEvent): Promise<void> => {+ const onStepStarted = async (event: InstrumentationStepAttemptStartedEvent): Promise<void> => {const turn = await input.stateStore.getTurn(event.scope.sessionId, event.scope.turnId);if (turn === undefined) return;const turnContext = contextFromSpanContext(turn.context);@@ -170,14 +174,17 @@ export function createAgentOtelInstrumentation(});};- const onAttemptTerminal = (event: InstrumentationAttemptTerminalEvent): void => {+ const onStepTerminal = (event: InstrumentationStepAttemptTerminalEvent): void => {executionContexts.delete(event.scope);+ drainOpenSpans(event);const attempt = steps.get(event.scope);if (attempt === undefined) return;+ // The span event drops the `attempt` segment: this span *is* one attempt,+ // and `agent.step.attempt` on it already says which.attempt.step.span.addEvent(- event.type === "attempt.completed" ? "step.completed" : "step.failed",+ event.type === "step.attempt.completed" ? "step.completed" : "step.failed",);- if (event.type === "attempt.failed") {+ if (event.type === "step.attempt.failed") {recordError(attempt.operation.span, event.error);recordError(attempt.step.span, event.error);}@@ -247,46 +254,47 @@ export function createAgentOtelInstrumentation(}};- const beforeModelCall = (event: InstrumentationModelCallStartedEvent): SpanState | undefined => {+ const onModelCallStarted = (event: InstrumentationModelCallStartedEvent): void => {const attempt = steps.get(event.scope);- if (attempt === undefined) return undefined;- attempt.step.span.setAttribute("agent.model.id", event.source.modelId);- attempt.step.span.setAttribute("agent.model.provider", event.source.provider);+ if (attempt === undefined) return;+ attempt.step.span.setAttribute("agent.model.id", event.model.modelId);+ attempt.step.span.setAttribute("agent.model.provider", event.model.provider);const span = input.tracer.startSpan(modelSpanName(attempt.operation.name),{attributes: {"gen_ai.operation.name": attempt.operation.name,- "gen_ai.provider.name": event.source.provider,- "gen_ai.request.model": event.source.modelId,+ "gen_ai.provider.name": event.model.provider,+ "gen_ai.request.model": event.model.modelId,},},attempt.operation.context,);if (captureContent) {- const messages = messagesContentAttribute(event.source.messages);+ const messages = messagesContentAttribute(event.input.messages);if (messages !== undefined) span.setAttribute("ai.prompt.messages", messages);- const system = systemPromptAttribute(event.source.instructions);+ const system = systemPromptAttribute(event.input.instructions);if (system !== undefined) span.setAttribute("ai.prompt.system", system);}const state = { context: trace.setSpan(attempt.operation.context, span), span };getExecutionContexts(event.scope).models.set(event.id, state.context);- return state;+ getSpanStates(modelSpans, event.scope).set(event.id, state);};- const afterModelCall = (event: InstrumentationModelCallTerminalEvent, state: unknown): void => {+ const onModelCallTerminal = (event: InstrumentationModelCallTerminalEvent): void => {executionContexts.get(event.scope)?.models.delete(event.id);- if (!isSpanState(state)) return;+ const state = takeSpanState(modelSpans, event.scope, event.id);+ if (state === undefined) return;if (event.type === "model.call.failed") {recordError(state.span, event.error);} else {- setUsage(state.span, event.source.usage);+ setUsage(state.span, event.usage);const attempt = steps.get(event.scope);- if (attempt !== undefined) setUsage(attempt.step.span, event.source.usage);+ if (attempt !== undefined) setUsage(attempt.step.span, event.usage);if (captureContent) {- state.span.setAttribute("ai.response.finish_reason", event.source.finishReason);+ state.span.setAttribute("ai.response.finish_reason", event.finishReason);const reasoning = textContentAttribute(- event.source.content+ event.content.filter((part) => part.type === "reasoning").map((part) => part.text).filter((part) => part.trim().length > 0)@@ -294,15 +302,15 @@ export function createAgentOtelInstrumentation();if (reasoning !== undefined) state.span.setAttribute("ai.response.reasoning", reasoning);const text = textContentAttribute(- event.source.content+ event.content.filter((part) => part.type === "text").map((part) => part.text).join(""),);if (text !== undefined) state.span.setAttribute("ai.response.text", text);- const toolCalls = event.source.content+ const toolCalls = event.content.filter((part) => part.type === "tool-call")- .map((part) => ({ input: part.input, toolName: part.toolName }));+ .map((part) => ({ callId: part.callId, input: part.input, toolName: part.toolName }));if (toolCalls.length > 0) {const json = contentAttribute(toolCalls, false);if (json !== undefined) state.span.setAttribute("ai.response.tool_calls", json);@@ -310,12 +318,22 @@ export function createAgentOtelInstrumentation(// Provider-executed tools (e.g. web_search) run inside the model call,// never reach eve's tool loop, and so never get an ai.toolCall span.// Their results only exist as content parts on the model response.- const toolResults = event.source.content+ const toolResults = event.content.filter((part) => part.type === "tool-result" || part.type === "tool-error").map((part) =>part.type === "tool-result"- ? { input: part.input, output: part.output, toolName: part.toolName }- : { error: errorText(part.error), input: part.input, toolName: part.toolName },+ ? {+ callId: part.callId,+ input: part.input,+ output: part.output,+ toolName: part.toolName,+ }+ : {+ callId: part.callId,+ error: errorText(part.error),+ input: part.input,+ toolName: part.toolName,+ },);if (toolResults.length > 0) {const json = toolResultsContentAttribute(toolResults);@@ -326,18 +344,16 @@ export function createAgentOtelInstrumentation(state.span.end();};- const beforeToolCall = (- event: InstrumentationToolCallStartedEvent,- ): ToolSpanState | undefined => {+ const onToolCallStarted = (event: InstrumentationToolCallStartedEvent): void => {const attempt = steps.get(event.scope);- if (attempt === undefined) return undefined;+ if (attempt === undefined) return;const actionSpan = input.tracer.startSpan("agent.action",{attributes: {- "agent.action.call_id": event.source.toolCall.toolCallId,+ "agent.action.call_id": event.callId,"agent.action.kind": "tool",- "agent.action.name": event.source.toolCall.toolName,+ "agent.action.name": event.toolName,"agent.framework.name": "eve","agent.framework.version": input.frameworkVersion,"agent.root.session.id": event.scope.rootSessionId ?? event.scope.sessionId,@@ -355,14 +371,14 @@ export function createAgentOtelInstrumentation({attributes: {"gen_ai.operation.name": "execute_tool",- "gen_ai.tool.call.id": event.source.toolCall.toolCallId,- "gen_ai.tool.name": event.source.toolCall.toolName,+ "gen_ai.tool.call.id": event.callId,+ "gen_ai.tool.name": event.toolName,},},actionContext,);if (captureContent) {- const args = contentAttribute(event.source.toolCall.input, false);+ const args = contentAttribute(event.input, false);if (args !== undefined) toolSpan.setAttribute("gen_ai.tool.call.arguments", args);}const state: ToolSpanState = {@@ -371,20 +387,21 @@ export function createAgentOtelInstrumentation(toolSpan,};getExecutionContexts(event.scope).tools.set(event.id, state.context);- return state;+ getSpanStates(toolSpans, event.scope).set(event.id, state);};- const afterToolCall = (event: InstrumentationToolCallTerminalEvent, state: unknown): void => {+ const onToolCallTerminal = (event: InstrumentationToolCallTerminalEvent): void => {executionContexts.get(event.scope)?.tools.delete(event.id);- if (!isToolSpanState(state)) return;+ const state = takeSpanState(toolSpans, event.scope, event.id);+ if (state === undefined) return;if (event.type === "tool.call.failed") {recordError(state.toolSpan, event.error);recordError(state.span, event.error);- } else if (event.source.toolOutput.type !== "tool-result") {- recordError(state.toolSpan, event.source.toolOutput.error);- recordError(state.span, event.source.toolOutput.error);+ } else if (event.output.type === "error") {+ recordError(state.toolSpan, event.output.error);+ recordError(state.span, event.output.error);} else if (captureContent) {- const result = contentAttribute(event.source.toolOutput.output, false);+ const result = contentAttribute(event.output.output, false);if (result !== undefined) state.toolSpan.setAttribute("gen_ai.tool.call.result", result);}state.toolSpan.end();@@ -406,6 +423,7 @@ export function createAgentOtelInstrumentation("agent.root.session.id": window.rootSessionId,"agent.session.id": window.sessionId,"agent.session.window": window.index,+ "agent.trace.schema.version": 1,...(window.previousTraceId === undefined? {}: { "agent.session.window.previous.trace.id": window.previousTraceId }),@@ -466,7 +484,7 @@ export function createAgentOtelInstrumentation(};};- const onAttemptMetadata = (event: InstrumentationAttemptMetadataEvent): void => {+ const onStepMetadata = (event: InstrumentationStepAttemptMetadataEvent): void => {const attempt = steps.get(event.scope);if (attempt === undefined) return;// Vercel AI Gateway reports per-call cost in providerMetadata.gateway;@@ -482,16 +500,20 @@ export function createAgentOtelInstrumentation(return {hook: {events: {- "attempt.completed": onAttemptTerminal,- "attempt.failed": onAttemptTerminal,- "attempt.metadata": onAttemptMetadata,- "attempt.started": onAttemptStarted,- "model.call": { after: afterModelCall, before: beforeModelCall },+ "step.attempt.completed": onStepTerminal,+ "step.attempt.failed": onStepTerminal,+ "step.attempt.metadata": onStepMetadata,+ "step.attempt.started": onStepStarted,+ "model.call.completed": onModelCallTerminal,+ "model.call.failed": onModelCallTerminal,+ "model.call.started": onModelCallStarted,"session.completed": onSessionTransition,"session.failed": onSessionTransition,"session.started": onSessionStarted,"session.waiting": onSessionTransition,- "tool.call": { after: afterToolCall, before: beforeToolCall },+ "tool.call.completed": onToolCallTerminal,+ "tool.call.failed": onToolCallTerminal,+ "tool.call.started": onToolCallStarted,"turn.cancelled": onTurnTerminal,"turn.completed": onTurnTerminal,"turn.failed": onTurnTerminal,@@ -519,6 +541,48 @@ export function createAgentOtelInstrumentation(}return state;}++ function drainOpenSpans(event: InstrumentationStepAttemptTerminalEvent): void {+ for (const state of modelSpans.get(event.scope)?.values() ?? []) {+ if (event.type === "step.attempt.failed") recordError(state.span, event.error);+ state.span.end();+ }+ modelSpans.delete(event.scope);+ for (const state of toolSpans.get(event.scope)?.values() ?? []) {+ if (event.type === "step.attempt.failed") {+ recordError(state.toolSpan, event.error);+ recordError(state.span, event.error);+ }+ state.toolSpan.end();+ state.span.end();+ }+ toolSpans.delete(event.scope);+ }+}++function getSpanStates<T>(+ spans: WeakMap<InstrumentationAttemptScope, Map<string, T>>,+ scope: InstrumentationAttemptScope,+): Map<string, T> {+ let scoped = spans.get(scope);+ if (scoped === undefined) {+ scoped = new Map();+ spans.set(scope, scoped);+ }+ return scoped;+}++function takeSpanState<T>(+ spans: WeakMap<InstrumentationAttemptScope, Map<string, T>>,+ scope: InstrumentationAttemptScope,+ id: string,+): T | undefined {+ const scoped = spans.get(scope);+ const state = scoped?.get(id);+ if (scoped === undefined) return undefined;+ scoped.delete(id);+ if (scoped.size === 0) spans.delete(scope);+ return state;}function parentLineageAttributes(@@ -584,14 +648,6 @@ function readUsd(value: unknown): number | undefined {return Number.isFinite(parsed) ? parsed : undefined;}-function isSpanState(value: unknown): value is SpanState {- return typeof value === "object" && value !== null && "context" in value && "span" in value;-}--function isToolSpanState(value: unknown): value is ToolSpanState {- return isSpanState(value) && "toolSpan" in value;-}-function isRecord(value: unknown): value is Record<string, unknown> {return typeof value === "object" && value !== null && !Array.isArray(value);}@@ -602,17 +658,7 @@ function modelSpanName(operationName: string): string {: "ai.streamText.doStream";}-function setUsage(- span: Span,- usage: {- readonly inputTokenDetails?: {- readonly cacheReadTokens?: number;- readonly cacheWriteTokens?: number;- };- readonly inputTokens?: number;- readonly outputTokens?: number;- },-): void {+function setUsage(span: Span, usage: InstrumentationUsage): void {if (usage.inputTokens !== undefined) {span.setAttribute("agent.usage.input_tokens", usage.inputTokens);}diff --git a/packages/eve/src/tracing/agent-trace-state.ts b/packages/eve/src/tracing/agent-trace-state.tsindex 6564b9685..dc571f48d 100644--- a/packages/eve/src/tracing/agent-trace-state.ts+++ b/packages/eve/src/tracing/agent-trace-state.ts@@ -5,6 +5,9 @@ import type {InstrumentationTurnTerminalEvent,} from "#harness/instrumentation-lifecycle.js";+/** Sized so an ordinary session stays one trace and only an outsized one rolls. */+export const SESSION_WINDOW_TURN_LIMIT = 200;+export interface AgentSessionTraceState {readonly agentName?: string;readonly channelKind?: string;@@ -72,6 +75,6 @@ export class InMemoryAgentTraceStateStore implements AgentTraceStateStore {}}-function turnKey(sessionId: string, turnId: string): string {+export function turnKey(sessionId: string, turnId: string): string {return `${sessionId}:${turnId}`;}diff --git a/packages/eve/src/tracing/local-instrumentation-runtime.scenario.test.ts b/packages/eve/src/tracing/local-instrumentation-runtime.scenario.test.tsindex 6f6ca81eb..34f017215 100644--- a/packages/eve/src/tracing/local-instrumentation-runtime.scenario.test.ts+++ b/packages/eve/src/tracing/local-instrumentation-runtime.scenario.test.ts@@ -71,7 +71,7 @@ describe("local instrumentation runtime", () => {]);await Reflect.apply(bridge.onStepStart!, bridge, [{ callId: "call-1", stepNumber: 0 }]);await Reflect.apply(bridge.onLanguageModelCallStart!, bridge, [- { callId: "call-1", modelId: "model-1", provider: "test", tools: undefined },+ { callId: "call-1", messages: [], modelId: "model-1", provider: "test", tools: undefined },]);await bridge.executeLanguageModelCall!({callId: "call-1",@@ -117,7 +117,7 @@ describe("local instrumentation runtime", () => {toolOutput: { output: { temperature: 72 }, type: "tool-result" },},]);- await runtime.hooks.publish({ scope, type: "attempt.completed" });+ await runtime.hooks.publish({ scope, type: "step.attempt.completed" });await runtime.hooks.publish({sessionId: "session-1",turnId: "turn-1",diff --git a/scripts/guard-invariants.mjs b/scripts/guard-invariants.mjsindex 2cde88fb2..46d50511a 100644--- a/scripts/guard-invariants.mjs+++ b/scripts/guard-invariants.mjs@@ -93,16 +93,26 @@* dropped, every retained epoch needs a compiling fixture, and* every public authoring value must belong to a capability.*+ * rule 37 — The instrumentation lifecycle contract stays provider-neutral.+ * `harness/instrumentation-lifecycle.ts` must not import from+ * `ai`: its event payloads are eve's published shape, so deriving+ * them from the model SDK's callback types would make an SDK+ * upgrade a breaking change for every provider. Map at the bridge.+ ** Baselines for rules with pre-existing violations live in* `guard-invariants-baseline.json`. Counts and allowlists in that file* may only shrink (as offenders are removed) — they may never grow.*/import { readFile, readdir, lstat } from "node:fs/promises";+import { createRequire } from "node:module";import { join, relative, resolve, sep } from "node:path";import { fileURLToPath } from "node:url";import matter from "gray-matter";import { checkExtensionCapabilityContracts } from "./extension-capability-contracts.mjs";+const require = createRequire(import.meta.url);+const extractorRequire = createRequire(require.resolve("@microsoft/api-extractor/package.json"));+const ts = extractorRequire("typescript");const REPO_ROOT = resolve(fileURLToPath(import.meta.url), "../..");const BASELINE_PATH = join(REPO_ROOT, "scripts/guard-invariants-baseline.json");@@ -182,6 +192,7 @@ function isTsLike(relPath) {* rule28: Violation[];* rule33: Violation[];* rule35: Violation[];+ * rule37: Violation[];* symlinks: string[];* }} state*/@@ -210,6 +221,7 @@ async function scanRepo(state) {checkRule28(posix, lines, state.rule28);checkRule33(posix, lines, state.rule33);checkRule35(posix, lines, state.rule35);+ checkRule37(posix, content, state.rule37);}}@@ -332,6 +344,75 @@ function checkRule35(posix, lines, violations) {});}+// ---------- Rule 37: instrumentation lifecycle provider boundary ----------++const INSTRUMENTATION_LIFECYCLE_CONTRACT = "packages/eve/src/harness/instrumentation-lifecycle.ts";++/**+ * @param {string} posix+ * @param {string} source+ * @param {Violation[]} violations+ */+function checkRule37(posix, source, violations) {+ if (posix !== INSTRUMENTATION_LIFECYCLE_CONTRACT) return;++ const sourceFile = ts.createSourceFile(+ posix,+ source,+ ts.ScriptTarget.Latest,+ true,+ ts.ScriptKind.TS,+ );+ const visit = (node) => {+ const specifier = importSpecifier(node);+ if (specifier !== undefined && (specifier.text === "ai" || specifier.text.startsWith("ai/"))) {+ violations.push({+ rule: 37,+ file: posix,+ line: sourceFile.getLineAndCharacterOfPosition(specifier.getStart(sourceFile)).line + 1,+ message: `imports from "ai". Lifecycle event payloads are eve's own shape, so an AI SDK type reaching them makes an SDK upgrade a breaking change for every provider. Add an eve type here and map to it in ai-sdk-hook-bridge.ts.`,+ });+ }+ ts.forEachChild(node, visit);+ };+ visit(sourceFile);+}++function importSpecifier(node) {+ if (+ (ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) &&+ node.moduleSpecifier !== undefined &&+ ts.isStringLiteralLike(node.moduleSpecifier)+ ) {+ return node.moduleSpecifier;+ }+ if (+ ts.isImportEqualsDeclaration(node) &&+ ts.isExternalModuleReference(node.moduleReference) &&+ node.moduleReference.expression !== undefined &&+ ts.isStringLiteralLike(node.moduleReference.expression)+ ) {+ return node.moduleReference.expression;+ }+ if (+ ts.isImportTypeNode(node) &&+ ts.isLiteralTypeNode(node.argument) &&+ ts.isStringLiteralLike(node.argument.literal)+ ) {+ return node.argument.literal;+ }+ if (+ ts.isCallExpression(node) &&+ (node.expression.kind === ts.SyntaxKind.ImportKeyword ||+ (ts.isIdentifier(node.expression) && node.expression.text === "require")) &&+ node.arguments[0] !== undefined &&+ ts.isStringLiteralLike(node.arguments[0])+ ) {+ return node.arguments[0];+ }+ return undefined;+}+// ---------- Rule 19: AsyncLocalStorage instances ----------const NEW_ALS_RE = /new\s+AsyncLocalStorage\s*[<(]/;@@ -1066,6 +1147,7 @@ async function main() {rule28: /** @type {Violation[]} */ ([]),rule33: /** @type {Violation[]} */ ([]),rule35: /** @type {Violation[]} */ ([]),+ rule37: /** @type {Violation[]} */ ([]),symlinks: /** @type {string[]} */ ([]),};@@ -1162,6 +1244,9 @@ async function main() {violations.push({ rule: 36, ...issue });}+ // Rule 37+ violations.push(...state.rule37);+if (violations.length === 0) {process.stdout.write("[eve:guard:invariants] ok — all mechanical lints passed.\n");return;