Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat(eve): add provider-neutral AI lifecycle bridge (#1169)

Chad Hietala8156c7ad753c
diff --git a/packages/eve/src/harness/ai-sdk-hook-bridge.test.ts b/packages/eve/src/harness/ai-sdk-hook-bridge.test.ts
new file mode 100644
index 000000000..ee6a98412
--- /dev/null
+++ b/packages/eve/src/harness/ai-sdk-hook-bridge.test.ts
@@ -0,0 +1,254 @@
+import { describe, expect, it, vi } from "vitest";
+
+import { createAiSdkHookBridge } from "#harness/ai-sdk-hook-bridge.js";
+import {
+ createInstrumentationHooks,
+ type InstrumentationAttemptScope,
+ type InstrumentationProviderDefinition,
+} from "#harness/instrumentation-lifecycle.js";
+
+const scope: InstrumentationAttemptScope = {
+ attemptId: "turn-1:step-0:attempt-0",
+ attemptIndex: 0,
+ sessionId: "session-1",
+ stepIndex: 0,
+ turnId: "turn-1",
+};
+
+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`;
+ },
+ after(event, state) {
+ calls.push(`${name}:after:${event.id}:${String(state)}`);
+ },
+ },
+ },
+ });
+ 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 },
+ ]);
+ await Reflect.apply(bridge.onLanguageModelCallEnd!, bridge, [
+ {
+ callId: "call-1",
+ content: [],
+ finishReason: "stop",
+ performance: { responseTimeMs: 1 },
+ responseId: "response-1",
+ usage: { inputTokens: 1, outputTokens: 1 },
+ },
+ ]);
+
+ 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`,
+ ]);
+ });
+
+ it("uses an eve-owned context runner while executing the model exactly once", async () => {
+ const order: string[] = [];
+ const hooks = createInstrumentationHooks([]);
+ const bridge = createAiSdkHookBridge(scope, hooks, async (_operation, execute) => {
+ order.push("enter");
+ const result = await execute();
+ order.push("exit");
+ return result;
+ });
+ const execute = vi.fn(async () => "result");
+ await Reflect.apply(bridge.onLanguageModelCallStart!, bridge, [
+ { callId: "call-1", modelId: "model", provider: "test", tools: undefined },
+ ]);
+
+ const result = await bridge.executeLanguageModelCall!({
+ callId: "call-1",
+ execute,
+ });
+
+ expect(result).toBe("result");
+ expect(execute).toHaveBeenCalledTimes(1);
+ expect(order).toEqual(["enter", "exit"]);
+ });
+
+ 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) } } },
+ ]);
+ const bridge = createAiSdkHookBridge(scope, hooks, (operation, execute) => {
+ ids.push(operation.id);
+ return execute();
+ });
+ 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 }]);
+ await Reflect.apply(bridge.onLanguageModelCallStart!, bridge, [
+ { callId: "call-1", modelId: "model", provider: "test", tools: undefined },
+ ]);
+ await Reflect.apply(bridge.onStepStart!, bridge, [{ callId: "call-1", stepNumber: 1 }]);
+
+ await bridge.executeLanguageModelCall!({ callId: "call-1", execute: async () => "result" });
+
+ const expected = `${scope.attemptId}:model:call-1:0`;
+ expect(ids).toEqual([expected, expected]);
+ });
+
+ it("executes directly when no start identity exists", async () => {
+ let adapterCalls = 0;
+ const hooks = createInstrumentationHooks([]);
+ const bridge = createAiSdkHookBridge(scope, hooks, (_operation, execute) => {
+ adapterCalls += 1;
+ return execute();
+ });
+ const execute = vi.fn(async () => "result");
+
+ expect(await bridge.executeLanguageModelCall!({ callId: "missing", execute })).toBe("result");
+ expect(execute).toHaveBeenCalledOnce();
+ expect(adapterCalls).toBe(0);
+ });
+
+ it("isolates a failing provider from the remaining providers", async () => {
+ const after = vi.fn();
+ const hooks = createInstrumentationHooks([
+ {
+ events: {
+ "model.call": {
+ before() {
+ throw new Error("provider failed");
+ },
+ },
+ },
+ },
+ { events: { "model.call": { before: () => "state", after } } },
+ ]);
+ const bridge = createAiSdkHookBridge(scope, hooks);
+
+ await Reflect.apply(bridge.onLanguageModelCallStart!, bridge, [
+ { callId: "call-1", 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(after).toHaveBeenCalledOnce();
+ });
+
+ it("terminalizes started operations when the attempt errors", async () => {
+ const after = vi.fn();
+ const hooks = createInstrumentationHooks([
+ { events: { "model.call": { before: () => "state", after } } },
+ ]);
+ const bridge = createAiSdkHookBridge(scope, hooks);
+
+ await Reflect.apply(bridge.onLanguageModelCallStart!, bridge, [
+ { callId: "call-1", modelId: "model", provider: "test", tools: undefined },
+ ]);
+ const error = new Error("model failed");
+ await Reflect.apply(bridge.onError!, bridge, [error]);
+
+ expect(after).toHaveBeenCalledExactlyOnceWith(
+ expect.objectContaining({ error, type: "model.call.failed" }),
+ "state",
+ );
+ });
+
+ it("publishes frozen callback snapshots", async () => {
+ const started = vi.fn();
+ const hooks = createInstrumentationHooks([{ events: { "attempt.started": started } }]);
+ const bridge = createAiSdkHookBridge(scope, hooks);
+ const operation = {
+ callId: "call-1",
+ modelId: "model",
+ operationId: "ai.streamText",
+ provider: "test",
+ };
+ 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);
+ });
+
+ it("retains state for parallel tool starts", async () => {
+ const resolvers = new Map<string, () => void>();
+ const terminalStates = new Map<string, unknown>();
+ const hooks = createInstrumentationHooks([
+ {
+ events: {
+ "tool.call": {
+ before(event) {
+ return new Promise<string>((resolve) => {
+ resolvers.set(event.id, () => resolve(`state:${event.id}`));
+ });
+ },
+ after(event, state) {
+ terminalStates.set(event.id, state);
+ },
+ },
+ },
+ },
+ ]);
+ const bridge = createAiSdkHookBridge(scope, hooks);
+ const start = (toolCallId: string) =>
+ Reflect.apply(bridge.onToolExecutionStart!, bridge, [
+ {
+ callId: "call-1",
+ toolCall: { input: {}, toolCallId, toolName: "search" },
+ },
+ ]);
+ const first = start("tool-1");
+ const second = start("tool-2");
+ await vi.waitFor(() => expect(resolvers.size).toBe(2));
+
+ const firstId = `${scope.attemptId}:tool:tool-1:0`;
+ const secondId = `${scope.attemptId}:tool:tool-2:0`;
+ resolvers.get(secondId)!();
+ resolvers.get(firstId)!();
+ await Promise.all([first, second]);
+
+ const end = (toolCallId: string) =>
+ Reflect.apply(bridge.onToolExecutionEnd!, bridge, [
+ {
+ callId: "call-1",
+ messages: [],
+ toolCall: { input: {}, toolCallId, toolName: "search" },
+ toolExecutionMs: 1,
+ toolOutput: { output: {}, type: "tool-result" },
+ },
+ ]);
+ await Promise.all([end("tool-1"), end("tool-2")]);
+
+ expect(terminalStates).toEqual(
+ new Map([
+ [firstId, `state:${firstId}`],
+ [secondId, `state:${secondId}`],
+ ]),
+ );
+ });
+});
diff --git a/packages/eve/src/harness/ai-sdk-hook-bridge.ts b/packages/eve/src/harness/ai-sdk-hook-bridge.ts
new file mode 100644
index 000000000..e2779999e
--- /dev/null
+++ b/packages/eve/src/harness/ai-sdk-hook-bridge.ts
@@ -0,0 +1,178 @@
+import type { Telemetry } from "ai";
+
+import type {
+ InstrumentationAttemptScope,
+ InstrumentationAttemptStartedEvent,
+ InstrumentationContextRunner,
+ InstrumentationHooks,
+ InstrumentationModelCallCompletedEvent,
+ InstrumentationModelCallStartedEvent,
+ InstrumentationToolCallCompletedEvent,
+ InstrumentationToolCallStartedEvent,
+} from "#harness/instrumentation-lifecycle.js";
+
+type TelemetryEvent<TKey extends keyof Telemetry> = Parameters<NonNullable<Telemetry[TKey]>>[0];
+
+interface AttemptState {
+ readonly modelIds: Map<string, string>;
+ readonly scope: InstrumentationAttemptScope;
+ readonly toolIds: Map<string, string>;
+ operationStart?: Readonly<TelemetryEvent<"onStart">>;
+ stepStart?: Readonly<TelemetryEvent<"onStepStart">>;
+}
+
+/** Creates one provider-neutral AI SDK bridge for one actual model attempt. */
+export function createAiSdkHookBridge(
+ scope: InstrumentationAttemptScope,
+ hooks: InstrumentationHooks,
+ runInContext: InstrumentationContextRunner = directRunInContext,
+): Telemetry {
+ const state: AttemptState = {
+ modelIds: new Map(),
+ scope,
+ toolIds: new Map(),
+ };
+
+ return {
+ onStart(event) {
+ state.operationStart = snapshot(event);
+ },
+ async onStepStart(event) {
+ state.stepStart = snapshot(event);
+ const started = toAttemptStarted(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);
+ },
+ executeLanguageModelCall({ callId, execute }) {
+ const id = state.modelIds.get(callId);
+ return id === undefined
+ ? execute()
+ : runInContext({ id, scope, type: "model.call" }, execute);
+ },
+ async onLanguageModelCallEnd(event) {
+ const id = state.modelIds.get(event.callId);
+ if (id === undefined) return;
+ state.modelIds.delete(event.callId);
+ const completed = toModelCallCompleted(state, id, event);
+ await hooks.after("model.call", completed);
+ },
+ 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);
+ },
+ executeTool({ toolCallId, execute }) {
+ const id = state.toolIds.get(toolCallId);
+ return id === undefined ? execute() : runInContext({ id, scope, type: "tool.call" }, execute);
+ },
+ async onToolExecutionEnd(event) {
+ const toolCallId = event.toolCall.toolCallId;
+ const id = state.toolIds.get(toolCallId);
+ if (id === undefined) return;
+ state.toolIds.delete(toolCallId);
+ const completed = toToolCallCompleted(state, id, event);
+ await hooks.after("tool.call", completed);
+ },
+ async onAbort(event) {
+ await failOpenOperations(event);
+ },
+ async onError(error) {
+ await failOpenOperations(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" }));
+ }
+ for (const id of state.toolIds.values()) {
+ pending.push(hooks.after("tool.call", { error, id, scope, type: "tool.call.failed" }));
+ }
+ state.modelIds.clear();
+ state.toolIds.clear();
+ await Promise.all(pending);
+ }
+}
+
+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,
+ scope: state.scope,
+ step: state.stepStart,
+ type: "attempt.started",
+ };
+}
+
+function createModelCallIdentity(state: AttemptState, callId: string): string {
+ return `${state.scope.attemptId}:model:${callId}:${state.stepStart?.stepNumber ?? 0}`;
+}
+
+function toModelCallStarted(
+ state: AttemptState,
+ id: string,
+ source: TelemetryEvent<"onLanguageModelCallStart">,
+): InstrumentationModelCallStartedEvent {
+ return {
+ id,
+ scope: state.scope,
+ source: snapshot(source),
+ type: "model.call.started",
+ };
+}
+
+function toModelCallCompleted(
+ state: AttemptState,
+ id: string,
+ source: TelemetryEvent<"onLanguageModelCallEnd">,
+): InstrumentationModelCallCompletedEvent {
+ return {
+ id,
+ scope: state.scope,
+ source: snapshot(source),
+ type: "model.call.completed",
+ };
+}
+
+function createToolCallIdentity(state: AttemptState, toolCallId: string): string {
+ return `${state.scope.attemptId}:tool:${toolCallId}:${state.stepStart?.stepNumber ?? 0}`;
+}
+
+function toToolCallStarted(
+ state: AttemptState,
+ id: string,
+ source: TelemetryEvent<"onToolExecutionStart">,
+): InstrumentationToolCallStartedEvent {
+ return {
+ id,
+ scope: state.scope,
+ source: snapshot(source),
+ type: "tool.call.started",
+ };
+}
+
+function toToolCallCompleted(
+ state: AttemptState,
+ id: string,
+ source: TelemetryEvent<"onToolExecutionEnd">,
+): InstrumentationToolCallCompletedEvent {
+ return {
+ id,
+ scope: state.scope,
+ source: snapshot(source),
+ type: "tool.call.completed",
+ };
+}
diff --git a/packages/eve/src/harness/instrumentation-lifecycle.ts b/packages/eve/src/harness/instrumentation-lifecycle.ts
new file mode 100644
index 000000000..e58f1beb2
--- /dev/null
+++ b/packages/eve/src/harness/instrumentation-lifecycle.ts
@@ -0,0 +1,216 @@
+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. */
+export interface InstrumentationAttemptScope {
+ readonly attemptId: string;
+ readonly attemptIndex: number;
+ readonly functionId?: string;
+ readonly sessionId: string;
+ readonly stepIndex: number;
+ readonly turnId: string;
+}
+
+export interface InstrumentationAttemptStartedEvent {
+ readonly type: "attempt.started";
+ readonly scope: InstrumentationAttemptScope;
+ readonly operation: TelemetryEvent<"onStart">;
+ readonly step: TelemetryEvent<"onStepStart">;
+}
+
+export interface InstrumentationModelCallStartedEvent {
+ readonly type: "model.call.started";
+ readonly id: string;
+ readonly scope: InstrumentationAttemptScope;
+ readonly source: TelemetryEvent<"onLanguageModelCallStart">;
+}
+
+export interface InstrumentationModelCallCompletedEvent {
+ readonly type: "model.call.completed";
+ readonly id: string;
+ readonly scope: InstrumentationAttemptScope;
+ readonly source: TelemetryEvent<"onLanguageModelCallEnd">;
+}
+
+export interface InstrumentationModelCallFailedEvent {
+ readonly type: "model.call.failed";
+ readonly error: unknown;
+ readonly id: string;
+ readonly scope: InstrumentationAttemptScope;
+}
+
+export type InstrumentationModelCallTerminalEvent =
+ | InstrumentationModelCallCompletedEvent
+ | InstrumentationModelCallFailedEvent;
+
+export interface InstrumentationToolCallStartedEvent {
+ readonly type: "tool.call.started";
+ readonly id: string;
+ readonly scope: InstrumentationAttemptScope;
+ readonly source: TelemetryEvent<"onToolExecutionStart">;
+}
+
+export interface InstrumentationToolCallCompletedEvent {
+ readonly type: "tool.call.completed";
+ readonly id: string;
+ readonly scope: InstrumentationAttemptScope;
+ readonly source: TelemetryEvent<"onToolExecutionEnd">;
+}
+
+export interface InstrumentationToolCallFailedEvent {
+ readonly type: "tool.call.failed";
+ readonly error: unknown;
+ readonly id: string;
+ readonly scope: InstrumentationAttemptScope;
+}
+
+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>;
+}
+
+/** 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 "tool.call"?: RelatedLifecycleHook<
+ InstrumentationToolCallStartedEvent,
+ InstrumentationToolCallTerminalEvent
+ >;
+ };
+}
+
+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;
+
+export type InstrumentationPointEvent = InstrumentationAttemptStartedEvent;
+
+/** Trusted framework operation for activating context around AI SDK execution. */
+export type InstrumentationContextRunner = <T>(
+ operation: InstrumentationExecutionOperation,
+ execute: () => PromiseLike<T>,
+) => PromiseLike<T>;
+
+/** Stable identity supplied only to a trusted framework context runner. */
+export type InstrumentationExecutionOperation =
+ | {
+ readonly id: string;
+ readonly scope: InstrumentationAttemptScope;
+ readonly type: "model.call";
+ }
+ | {
+ readonly id: string;
+ readonly scope: InstrumentationAttemptScope;
+ readonly type: "tool.call";
+ };
+
+/** 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>;
+}
+
+const log = createLogger("harness.instrumentation-lifecycle");
+
+/** Creates failure-isolated hooks backed by an ordered provider list. */
+export function createInstrumentationHooks(
+ providers: readonly InstrumentationProviderDefinition[],
+): InstrumentationHooks {
+ const relatedState = new WeakMap<InstrumentationAttemptScope, Map<string, unknown>>();
+
+ const publish = async (event: InstrumentationPointEvent): 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);
+ } catch (error) {
+ warn(`${name}.before`, 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}`;
+}
diff --git a/research/provider-neutral-local-observability.md b/research/provider-neutral-local-observability.md
new file mode 100644
index 000000000..c9852b2ed
--- /dev/null
+++ b/research/provider-neutral-local-observability.md
@@ -0,0 +1,212 @@
+---
+issue: TBD
+status: proposed
+last_updated: "2026-07-24"
+---
+
+# Provider-neutral local observability
+
+## Summary
+
+eve should produce useful local traces without depending on Workflow tracing, changing production
+instrumentation, or coupling observability providers directly to the AI SDK.
+
+The first consumer is zero-config tracing in `eve dev`, but the lifecycle contract must support
+OTel, Vercel, Braintrust, and custom providers.
+
+## Desired flow
+
+```text
+eve lifecycle boundaries -------------------+
+ +--> eve lifecycle hooks
+AI SDK callbacks -> per-attempt bridge -------+ |
+ +--> local OTel provider
+AI SDK execute() -> eve-owned context runner +--> Vercel provider
+ +--> Braintrust provider
+ +--> custom providers
+```
+
+The AI SDK bridge is an adapter, not an instrumentation provider. It translates AI SDK callbacks
+into immutable, eve-owned lifecycle events.
+
+Providers never receive raw AI SDK event types or execution functions.
+
+## Lifecycle contract
+
+The bridge receives stable attempt scope and typed lifecycle hooks:
+
+```ts
+createAiSdkHookBridge(scope, hooks, runInContext): Telemetry;
+```
+
+```ts
+interface LifecycleHooks {
+ publish(event: LifecycleEvent): Promise<void>;
+
+ before(name: "model.call", event: ModelCallStartedEvent): Promise<void>;
+ after(name: "model.call", event: ModelCallTerminalEvent): Promise<void>;
+
+ before(name: "tool.call", event: ToolCallStartedEvent): Promise<void>;
+ after(name: "tool.call", event: ToolCallTerminalEvent): Promise<void>;
+}
+```
+
+Lifecycle events use eve-owned identities and payloads. AI SDK `callId` values are bridge
+correlation details, not provider run identities.
+
+Related `before` state is retained per provider and operation, then supplied only to that
+provider's `after`. Attempt state is scoped by object identity and WeakMap-backed so abandoned
+attempts do not leak state.
+
+## Bridge responsibilities
+
+The bridge:
+
+- snapshots AI SDK callbacks;
+- maps them into eve-owned lifecycle events;
+- assigns stable attempt, model-call, and tool-call identities;
+- publishes starts and terminals through typed hooks;
+- terminalizes open operations on errors and aborts;
+- invokes trusted `runInContext` with a typed model or tool operation while calling execution
+ exactly once.
+
+The bridge does not create spans, export records, apply provider capture policy, or publish durable
+eve-native events.
+
+Session, turn, compaction, suspension, and canonical step-terminal events are published directly
+by the eve harness.
+
+## Provider responsibilities
+
+Providers are ordinary lifecycle hook definitions. Each provider subscribes by defining handlers
+only for the eve-owned events it cares about; the lifecycle dispatcher invokes those handlers when
+the corresponding boundaries occur.
+
+An OTel provider may return spans from `before` and close them in `after`. Braintrust may retain
+native row handles. Vercel may enqueue normalized records.
+
+Each provider owns an independent trace graph. It creates or restores its root from provider-owned,
+serializable session state and derives later parentage from that state. Providers do not use ambient
+Workflow context, or another provider's active context, as their trace parent.
+
+Providers never receive an execution function. A built-in integration that needs ambient context
+may register a trusted internal `runInContext` alongside its event definition; it is passed directly
+to the bridge and is not part of the provider or hook contract.
+
+## Local tracing
+
+`eve dev` registers a private local OTel provider that consumes the same lifecycle events as other
+providers.
+
+The local provider:
+
+- uses its own tracer provider;
+- creates one trace per eve session, independently from Workflow context;
+- never installs a global tracer provider or context manager;
+- never captures Workflow spans;
+- persists traces as OTLP/JSON for later inspection.
+
+Authored instrumentation and local capture may observe the same attempt concurrently without
+executing the model or tool more than once.
+
+## Agent OTel semantics
+
+The local OTel provider emits an agent-first structural convention. GenAI spans may remain nested
+implementation detail, but they do not define the agent run.
+
+```text
+session trace {agent.session.id}
+ +-- agent.turn {agent.turn.id, agent.turn.sequence}
+ +-- agent.step {agent.step.index, agent.step.attempt}
+ +-- model-provider spans
+ +-- agent.action {agent.action.kind, name, call_id}
+ +-- tool-provider spans
+```
+
+The session is the trace, not a long-lived span. All turns share its trace id. Session lifecycle
+events attach to the turn that causes the transition; a transition without a turn may use a
+zero-duration marker span.
+
+An `agent.step` covers one model call and the actions it requests through their resolution.
+`agent.action.kind` is an open discriminator for `tool`, `skill`, `subagent`, and `remote-agent`.
+Subagents use their own session trace and link back to the calling action.
+
+The `agent.*` namespace contains cheap structural attributes: session, turn, step and attempt
+identity; action identity; agent/framework identity; channel and environment; principal; and
+parent/root lineage. Message content, model output, tool arguments, and tool results are optional
+capture, off by default.
+
+The OTel provider owns this mapping. The AI SDK bridge and lifecycle hooks do not contain OTel span
+names, attributes, or parent contexts.
+
+## Runtime integration
+
+The bridge is injected per actual model attempt:
+
+```text
+runModelCallWithRetries(attempt)
+ -> create stable AttemptScope
+ -> createAiSdkHookBridge(scope, hooks, runInContext)
+ -> telemetry.integrations = [bridge, authoredOtel?]
+ -> AI SDK invokes callbacks and trusted runInContext
+```
+
+The harness supplies `sessionId`, `turnId`, logical step index, and retry attempt index. The bridge
+derives stable model/tool identities once at their start callbacks and stores callback snapshots in
+invocation-local attempt state. `onStepEnd` and `onEnd` only snapshot results; the harness later
+publishes the canonical terminal event after durable actions are emitted. On replay, the harness
+recreates this attempt state; only provider-owned serializable context crosses Workflow boundaries.
+
+The existing eve stream keeps its current `step.started` boundary. AI SDK `onStepStart` is named
+`attempt.started` in the instrumentation lifecycle because it begins one concrete model attempt;
+retries and recovery calls therefore have distinct starts and terminals without introducing a
+second meaning for `step.started`.
+
+AI SDK per-call integrations replace its global list. eve explicitly composes the bridge with its
+known `@ai-sdk/otel` adapter when the documented `instrumentation.ts` OTel path is active. Direct
+AI SDK `registerTelemetry()` calls are not part of eve's supported customization surface.
+
+Braintrust's documented eve integration uses eve hooks and `defineInstrumentation`, so per-call
+bridge injection does not disable it.
+
+## Compatibility
+
+Production keeps its current `defineInstrumentation` and `@ai-sdk/otel` behavior until provider
+migration is explicitly shipped.
+
+Without lifecycle hooks, no bridge override is present and production follows its existing authored
+instrumentation path unchanged.
+
+Existing stream hooks and current `step.started` semantics remain unchanged during the initial
+local-tracing work.
+
+## Delivery phases
+
+1. **Lifecycle bridge.** Land the unused attempt scope, WeakMap-backed state, typed hooks, related
+ before/after correlation, a trusted context runner, and the AI SDK callback adapter. No
+ runtime wiring.
+2. **Per-attempt wiring.** Add optional internal lifecycle hooks to the harness and pass one bridge
+ through `telemetry.integrations` per retry attempt, composing authored OTel when active. No
+ provider or trace output yet.
+3. **Local OTel provider.** Add a private provider that maps lifecycle events to the `agent.*`
+ convention and proves the trace tree in memory. Production remains unchanged.
+4. **Persistence.** Write session traces as OTLP/JSON, restore provider-owned session context across
+ dev worker restarts, and apply payload capture policy. No browser UI.
+5. **Inspection.** Add minimal `eve trace ls` and `eve trace show` commands. A graphical viewer is a
+ separate design after the trace model stabilizes.
+6. **Public providers.** Promote the proven lifecycle contract into public hooks and migrate OTel,
+ Vercel, Braintrust, and custom instrumentation onto it.
+
+The current bridge PR is phase 1 only: it lands unused primitives and cannot emit a trace.
+
+## Acceptance criteria
+
+- The provider-neutral lifecycle layer imports no AI SDK or OTel types.
+- Multiple providers observe one attempt while execution occurs exactly once.
+- No provider definition receives model or tool execution functions.
+- Documented authored instrumentation continues to observe eve calls.
+- Each eve provider can build its trace without inheriting Workflow or another provider's trace.
+- Parallel tool calls retain independent provider state.
+- Errors and aborts terminalize all started model and tool operations.
+- Local traces contain no Workflow spans.
+- Enabling local tracing does not change production instrumentation behavior.