The Open Framework for Building Agents
feat(eve): trace workflow tool invocations (#3270)
Chad Hietala47b7a385f7c3
diff --git a/.changeset/trace-workflow-invocations.md b/.changeset/trace-workflow-invocations.mdnew file mode 100644index 000000000..ee886eb7a--- /dev/null+++ b/.changeset/trace-workflow-invocations.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Emit OpenTelemetry GenAI `invoke_workflow` spans when a `defineWorkflowTool` run coordinates nested agents, using the path-derived tool name as `gen_ai.workflow.name`. Durable workflow tools without agent operations remain ordinary actions.diff --git a/docs/guides/instrumentation.md b/docs/guides/instrumentation.mdindex 59aafd552..d9d497f62 100644--- a/docs/guides/instrumentation.md+++ b/docs/guides/instrumentation.md@@ -103,20 +103,28 @@ not mark the active span as failed.The built-in OpenTelemetry provider preserves each span's OTel name and adds`operation.name` and `resource.name` for Datadog's operation/resource mapping:-| OTel span name | `operation.name` | `resource.name` |-| ----------------------------------------------------------------------- | ----------------- | ---------------------- |-| `invoke_agent weather` | `invoke_agent` | `invoke_agent weather` |-| `execute_tool search` | `execute_tool` | `execute_tool search` |-| `chat <model>` | `chat` | `chat <model>` |-| `search_memory`, `upsert_memory` | Same as span name | Same as span name |-| `agent.step`, `agent.action`, `agent.approval`, `agent.channel.request` | Same as span name | Same as span name |+| OTel span name | `operation.name` | `resource.name` |+| ----------------------------------------------------------------------- | ----------------- | ------------------------ |+| `invoke_agent weather` | `invoke_agent` | `invoke_agent weather` |+| `invoke_workflow deploy` | `invoke_workflow` | `invoke_workflow deploy` |+| `execute_tool search` | `execute_tool` | `execute_tool search` |+| `chat <model>` | `chat` | `chat <model>` |+| `search_memory`, `upsert_memory` | Same as span name | Same as span name |+| `agent.step`, `agent.action`, `agent.approval`, `agent.channel.request` | Same as span name | Same as span name |These rows apply to eve-owned spans in local tracing and the[instrumentation provider layout](./instrumentation-providers). They do notrename Workflow, AI SDK, or other third-party spans, or change trace IDs,-parenting, sampling, or session grouping. Legacy `instrumentation.ts` setup-still owns its exporter configuration and-[authored trace hierarchy](#authored-trace-hierarchy).+parenting, or session grouping. Legacy `instrumentation.ts` setup still owns+its exporter configuration and [authored trace hierarchy](#authored-trace-hierarchy).++Workflow action spans enter the sampler as `agent.action`, with+`gen_ai.operation.name` and `gen_ai.workflow.name` already present. After+sampling, eve changes the exported span name to `invoke_workflow <tool>`.+Existing name-based samplers therefore keep their `agent.action` behavior;+attribute-based samplers can select GenAI workflow operations explicitly.+Review custom attribute rules when upgrading because the new workflow+attributes may change their decisions.In Datadog APM, `operation_name:invoke_agent resource_name:"invoke_agent weather"`selects named agent invocations. Operation-based dashboards and monitors may@@ -151,22 +159,25 @@ Every memory span includes `gen_ai.operation.name` and `gen_ai.memory.store.id`.The provider layout and zero-config local tracing emit the following spans.The legacy `instrumentation.ts` layout still uses its authored OTel setup.-| Span | Meaning |-| ----------------------- | -------------------------------------------------------- |-| `invoke_agent <agent>` | One agent activation in its own trace |-| `agent.step` | One model attempt |-| `chat <model>` | One model call beneath its step |-| `agent.action` | Durable action lifecycle, including dispatch and waiting |-| `execute_tool <tool>` | In-process tool execution beneath its action |-| `agent.approval` | Approval waiting beneath its action |-| `search_memory` | Recall memory records before a turn or after compaction |-| `upsert_memory` | Automatic memory capture |-| `agent.channel.request` | Optional HTTP request span in the provider layout |+| Span | Meaning |+| ------------------------ | -------------------------------------------------------- |+| `invoke_agent <agent>` | One agent activation in its own trace |+| `agent.step` | One model attempt |+| `chat <model>` | One model call beneath its step |+| `invoke_workflow <tool>` | One workflow tool run that coordinated a nested agent |+| `agent.action` | Durable action lifecycle, including dispatch and waiting |+| `execute_tool <tool>` | In-process tool execution beneath its action |+| `agent.approval` | Approval waiting beneath its action |+| `search_memory` | Recall memory records before a turn or after compaction |+| `upsert_memory` | Automatic memory capture |+| `agent.channel.request` | Optional HTTP request span in the provider layout |For background tools and subagents, the AI SDK's `execute_tool` span ends whenthe model receives the task receipt. The enclosing `agent.action` span remains-open until the background task completes, fails, or is cancelled. Its duration,-outcome, and usage describe the background task rather than the receipt.+open until the background task completes, fails, or is cancelled. When a+workflow tool coordinates a nested `ctx.agent()` call, eve exports that span as+`invoke_workflow` instead. Its duration, outcome, and usage describe the+background task rather than the receipt.Background tool results follow the output-content policy. Recorded task failuredetails become bounded exception and status messages; redacted spans retain onlythe failure outcome, error status, and error type. The initiating turn can@@ -174,10 +185,14 @@ finish or be cancelled while the action remains open. Ending the session closesan action whose task never reported a terminal result.Schema v4 removes the session-long `agent.session` root and duplicate agent session and lineage attributes. Every eve span carries `agent.trace.schema.version=4` and `gen_ai.conversation.id`; Vercel deployments additionally carry `vercel.session_id`.-Only activations use the `invoke_agent` operation. Dispatch lifecycle spans use-`agent.action` with `agent.invocation.role=caller`; the built-in `agent` tool-executes under `execute_tool agent`. Turn IDs such as `turn_0` are local to a session,-so correlate turns by session ID and turn ID together.+Only activations use the `invoke_agent` operation. A workflow tool invocation+that coordinates at least one nested agent uses `invoke_workflow`, with its+path-derived tool name in `gen_ai.workflow.name`. Durable workflow tools without+agent operations, including `sleep`, remain `agent.action` spans. Dispatch+lifecycle spans use `agent.action` with+`agent.invocation.role=caller`; the built-in `agent` tool executes under+`execute_tool agent`. Turn IDs such as `turn_0` are local to a session, so+correlate turns by session ID and turn ID together.A conversation remains durable state; `gen_ai.conversation.id` joins the activations that operate on it.diff --git a/docs/reference/cli.md b/docs/reference/cli.mdindex 7379d8730..acd7e3c48 100644--- a/docs/reference/cli.md+++ b/docs/reference/cli.md@@ -310,7 +310,7 @@ Span rows carry inline metrics when the span recorded them — `↑input`/`↓ouEvery subagent activation starts its own trace. The first child's `invoke_agent` root links to the dispatching caller with `eve.link.type=agent.dispatch`; remote agents carry that caller context over `traceparent`. Later turns also start fresh traces without repeating the initial caller link. All related sessions retain the same `gen_ai.conversation.id`, and `agent.subagent.name` labels the child invocation.-Each `agent()` call inside an authored workflow has its own `agent.action` caller span, including sequential, parallel, and background calls. The workflow tool keeps its own `agent.action` and `execute_tool` spans. Only agent execution uses `invoke_agent`.+Each `agent()` call inside an authored workflow has its own `agent.action` caller span, including sequential, parallel, and background calls. A workflow tool that coordinates one of those calls has an enclosing `invoke_workflow <tool>` span; a workflow tool without agent calls remains `agent.action`. The tool also keeps its `execute_tool <tool>` span. Only agent execution uses `invoke_agent`.A durable conversation produces one bounded trace per turn. Worker replacements reuse the prepared context for the same turn, while a later turn or an independently replayed attempt starts a fresh trace. Passing the conversation ID shows every trace it produced, oldest first.diff --git a/packages/eve/src/cli/dev/tui/traces/trace-conversation.test.ts b/packages/eve/src/cli/dev/tui/traces/trace-conversation.test.tsindex ee7e603a3..13f49151b 100644--- a/packages/eve/src/cli/dev/tui/traces/trace-conversation.test.ts+++ b/packages/eve/src/cli/dev/tui/traces/trace-conversation.test.ts@@ -102,6 +102,38 @@ describe("buildConversationItems", () => {expect(items[2]?.result).toBe('{"temperatureF":72}');});+ it.each([+ { error: false, result: '{"deployed":true}', statusCode: 0 },+ { error: true, result: undefined, statusCode: 2 },+ ])("keeps $error workflow invocations as tool cards", ({ error, result, statusCode }) => {+ const workflow = span(+ "e".repeat(16),+ "invoke_workflow deploy",+ 2500,+ 3250,+ "b".repeat(16),+ {+ "agent.action.name": "deploy",+ "gen_ai.operation.name": "invoke_workflow",+ "gen_ai.tool.call.arguments": '{"service":"api"}',+ "gen_ai.tool.call.result": result,+ "gen_ai.workflow.name": "deploy",+ },+ statusCode,+ );+ const items = buildConversationItems(trace([...weatherTurn(), workflow]));+ const item = items.find((candidate) => candidate.span.spanId === workflow.spanId);++ expect(item).toMatchObject({+ args: '{"service":"api"}',+ durationMs: 750,+ error,+ kind: "tool",+ name: "deploy",+ result,+ });+ });+it("renders provider-executed tool results as tool cards after the assistant", () => {// Provider-executed tools (e.g. web_search) never get an execute_tool// span; their outcomes live on the model span's tool_results attribute.diff --git a/packages/eve/src/cli/dev/tui/traces/trace-conversation.ts b/packages/eve/src/cli/dev/tui/traces/trace-conversation.tsindex 5e7c8f8ee..960ce6398 100644--- a/packages/eve/src/cli/dev/tui/traces/trace-conversation.ts+++ b/packages/eve/src/cli/dev/tui/traces/trace-conversation.ts@@ -159,14 +159,21 @@ export function buildConversationItems(trace: LocalTrace): ConversationItem[] {}continue;}- if (span.name === "agent.action") {+ if (+ span.name === "agent.action" ||+ stringAttribute(span, "gen_ai.operation.name") === "invoke_workflow"+ ) {entries.push({item: {kind: "tool",args: stringAttribute(span, "gen_ai.tool.call.arguments"),durationMs: spanDurationMs(span),error: span.statusCode === 2,- name: stripTerminalControls(stringAttribute(span, "agent.action.name") ?? "action"),+ name: stripTerminalControls(+ stringAttribute(span, "agent.action.name") ??+ stringAttribute(span, "gen_ai.workflow.name") ??+ "action",+ ),result: unwrapJsonString(stringAttribute(span, "gen_ai.tool.call.result")),span,subagent,diff --git a/packages/eve/src/harness/coordination.test.ts b/packages/eve/src/harness/coordination.test.tsindex 64de7e1b7..788b31267 100644--- a/packages/eve/src/harness/coordination.test.ts+++ b/packages/eve/src/harness/coordination.test.ts@@ -22,6 +22,7 @@ import { toolOutput } from "#tools/model-output.js";import { getSessionTokenUsage, setTurnUsageState } from "#harness/turn-tag-state.js";import type { HarnessSession } from "#harness/types.js";import type { UnstampedMessageStreamEvent } from "#protocol/message.js";+import { isRuntimeWorkflowToolAction } from "#shared/action-types.js";const CHILD_SESSION_ID = "local-child-123456789012";const CHILD_CONTINUATION_TOKEN = "subagent:private-token";@@ -68,6 +69,39 @@ describe("createRuntimeActionRequestFromToolCall", () => {});});+ it("preserves workflow identity without changing observable action data", () => {+ const action = createRuntimeActionRequestFromToolCall({+ toolCall: {+ input: { service: "api" },+ toolCallId: "call-deploy",+ toolName: "deploy",+ type: "tool-call",+ },+ tools: new Map([+ [+ "deploy",+ {+ description: "Deploy.",+ inputSchema: jsonSchema({ type: "object" }),+ name: "deploy",+ workflowId: "workflow//./agent/tools/deploy//execute",+ },+ ],+ ]),+ });++ expect(action).toEqual({+ callId: "call-deploy",+ input: { service: "api" },+ kind: "tool-call",+ toolName: "deploy",+ });+ expect(JSON.stringify(action)).toBe(+ '{"callId":"call-deploy","input":{"service":"api"},"kind":"tool-call","toolName":"deploy"}',+ );+ expect(isRuntimeWorkflowToolAction(action)).toBe(true);+ });+it("uses the tool-authored label start callback without exposing it in event data", () => {const action = createPresentedRuntimeActionRequestFromToolCall({toolCall: {diff --git a/packages/eve/src/harness/coordination.ts b/packages/eve/src/harness/coordination.tsindex a7dc0c697..df37a5339 100644--- a/packages/eve/src/harness/coordination.ts+++ b/packages/eve/src/harness/coordination.ts@@ -8,6 +8,7 @@ import type {RuntimeToolCallActionRequest,RuntimeWorkflowTaskRequest,} from "#shared/action-types.js";+import { markRuntimeWorkflowToolAction } from "#shared/action-types.js";import { parseJsonObject, type JsonObject } from "#shared/json.js";import type { AgentTurnOutcome } from "#shared/agent-turn-outcome.js";import { findRunningAgentHandle, isResultBoundToRunningHandle } from "#subagents/handles/query.js";@@ -428,14 +429,16 @@ export function createRuntimeActionRequestFromToolCall(input: {callId: input.toolCall.toolCallId,toolName: input.toolCall.toolName,});- return definition?.frameworkAction === "load-skill"- ? { callId: input.toolCall.toolCallId, input: toolInput, kind: "load-skill" }- : {- callId: input.toolCall.toolCallId,- input: toolInput,- kind: "tool-call",- toolName: input.toolCall.toolName,- };+ if (definition?.frameworkAction === "load-skill") {+ return { callId: input.toolCall.toolCallId, input: toolInput, kind: "load-skill" };+ }+ const action: RuntimeActionRequest = {+ callId: input.toolCall.toolCallId,+ input: toolInput,+ kind: "tool-call",+ toolName: input.toolCall.toolName,+ };+ return definition?.workflowId === undefined ? action : markRuntimeWorkflowToolAction(action);}/** Projects one deferred harness tool call into task/control coordination. */diff --git a/packages/eve/src/instrumentation/lifecycle.ts b/packages/eve/src/instrumentation/lifecycle.tsindex 94e97e19b..6e7f5113e 100644--- a/packages/eve/src/instrumentation/lifecycle.ts+++ b/packages/eve/src/instrumentation/lifecycle.ts@@ -500,7 +500,7 @@ export interface InstrumentationActionStartedEvent {readonly idempotencyKey: string;/** Content. Absent unless this provider's trace policy records this direction. */readonly input?: unknown;- /** Whether this action owns a workflow body that may invoke nested agents. */+ /** Whether this action owns a durable workflow body. */readonly isWorkflowTool?: boolean;readonly kind: InstrumentationActionKind;readonly name: string;diff --git a/packages/eve/src/instrumentation/native-events.ts b/packages/eve/src/instrumentation/native-events.tsindex 27154f245..9f165c10b 100644--- a/packages/eve/src/instrumentation/native-events.ts+++ b/packages/eve/src/instrumentation/native-events.ts@@ -30,7 +30,11 @@ import {import type { ResolvedInputBatch } from "#harness/input-requests.js";import { RuntimeActionSettlementTimesKey } from "#harness/runtime-action-settlement-state.js";import type { HandleEventFn } from "#harness/types.js";-import type { RuntimeActionRequest, RuntimeActionResult } from "#shared/action-types.js";+import {+ isRuntimeWorkflowToolAction,+ type RuntimeActionRequest,+ type RuntimeActionResult,+} from "#shared/action-types.js";import type { ChannelAudience } from "#shared/channel-audience.js";import { deriveTaskId } from "#tasks/task-id.js";import type { TaskUsage, TaskView } from "#tasks/types.js";@@ -208,7 +212,7 @@ async function publishActionStarts(callId: action.callId,idempotencyKey,input: capturesInputs ? action.input : undefined,- ...(action.kind === "workflow-tool-call" ? { isWorkflowTool: true } : undefined),+ ...(isRuntimeWorkflowToolAction(action) ? { isWorkflowTool: true } : undefined),kind: action.kind === "workflow-tool-call" ? "tool-call" : action.kind,name: actionName(action),scope,diff --git a/packages/eve/src/shared/action-types.ts b/packages/eve/src/shared/action-types.tsindex 86eac57be..a28d2df12 100644--- a/packages/eve/src/shared/action-types.ts+++ b/packages/eve/src/shared/action-types.ts@@ -171,6 +171,24 @@ export type RuntimeActionRequest =| RuntimeToolCallActionRequest| RuntimeWorkflowToolCallActionRequest;+const RUNTIME_WORKFLOW_TOOL_ACTION = Symbol.for("eve:runtime-workflow-tool-action");++/** Marks an in-process tool action without changing its serialized protocol shape. */+export function markRuntimeWorkflowToolAction(+ action: RuntimeToolCallActionRequest,+): RuntimeToolCallActionRequest {+ Object.defineProperty(action, RUNTIME_WORKFLOW_TOOL_ACTION, { value: true });+ return action;+}++/** Reads the in-process marker or the older explicit protocol action kind. */+export function isRuntimeWorkflowToolAction(action: RuntimeActionRequest): boolean {+ return (+ action.kind === "workflow-tool-call" ||+ (action.kind === "tool-call" && Reflect.get(action, RUNTIME_WORKFLOW_TOOL_ACTION) === true)+ );+}+/** Internal agent dispatch request owned by a workflow task. */export type RuntimeAgentDispatchRequest =| RuntimeRemoteAgentDispatchRequestdiff --git a/packages/eve/src/tracing/agent-action-instrumentation.ts b/packages/eve/src/tracing/agent-action-instrumentation.tsindex 157f0885e..de3b95791 100644--- a/packages/eve/src/tracing/agent-action-instrumentation.ts+++ b/packages/eve/src/tracing/agent-action-instrumentation.ts@@ -31,7 +31,7 @@ import type {import { normalizeChannelAudience } from "#shared/channel-audience.js";import { isSampledTrace } from "#tracing/sampled-trace.js";import { withChannelAudience } from "#tracing/channel-audience-context.js";-import { AGENT_SPAN_NAMES } from "#tracing/agent-span-contract.js";+import { AGENT_SPAN_NAMES, workflowInvocationSpanName } from "#tracing/agent-span-contract.js";import { recordAgentSpanError as recordError } from "#tracing/agent-span-error.js";export interface AgentActionInstrumentation {@@ -79,6 +79,7 @@ export function createAgentActionInstrumentation(input: {callId: event.callId,channelAudience: normalizeChannelAudience(event.scope.channelAudience),inputAttribute: input.recordInputs ? contentAttribute(event.input) : undefined,+ isWorkflowTool: event.isWorkflowTool === true,kind: event.kind,name: event.name,parent: {@@ -115,6 +116,11 @@ export function createAgentActionInstrumentation(input: {const startSpan = (state: AgentActionTraceState): Span => {const invocation = isAgentInvocation(state.kind);+ const workflowName = state.kind === "tool-call" ? state.workflowName : undefined;+ const spanName =+ workflowName === undefined+ ? AGENT_SPAN_NAMES.action+ : workflowInvocationSpanName(workflowName);const span = input.idGenerator.withSpanId(state.spanId, () =>input.tracer.startSpan(AGENT_SPAN_NAMES.action,@@ -128,11 +134,20 @@ export function createAgentActionInstrumentation(input: {"agent.step.attempt": state.attemptIndex,"agent.step.index": state.stepIndex,"agent.turn.id": state.turnId,- ...agentSpanNamingAttributes("agent.action"),+ ...agentSpanNamingAttributes(+ spanName,+ workflowName === undefined ? undefined : "invoke_workflow",+ ),...agentTraceIdentityAttributes({rootSessionId: state.rootSessionId,sessionId: state.sessionId,}),+ ...(workflowName === undefined+ ? undefined+ : {+ "gen_ai.operation.name": "invoke_workflow",+ "gen_ai.workflow.name": workflowName,+ }),...(invocation? {"gen_ai.agent.name": state.name,@@ -146,6 +161,7 @@ export function createAgentActionInstrumentation(input: {contextFromActionState(state),),);+ if (workflowName !== undefined) updateSpanName(span, spanName);if (!invocation && state.inputAttribute !== undefined) {span.setAttribute("gen_ai.tool.call.arguments", state.inputAttribute);}@@ -287,6 +303,11 @@ function isAgentInvocation(kind: InstrumentationActionKind): boolean {return kind === "subagent-call" || kind === "remote-agent-call";}+function updateSpanName(span: Span, name: string): void {+ const updateName = Reflect.get(span, "updateName");+ if (typeof updateName === "function") Reflect.apply(updateName, span, [name]);+}+function recordActionError(span: Span, error: unknown, errorType?: string): void {if (error instanceof Error || error === undefined) {recordError(span, error, errorType);diff --git a/packages/eve/src/tracing/agent-invocation-coordinator.test.ts b/packages/eve/src/tracing/agent-invocation-coordinator.test.tsindex 9dc076689..a883ba9f9 100644--- a/packages/eve/src/tracing/agent-invocation-coordinator.test.ts+++ b/packages/eve/src/tracing/agent-invocation-coordinator.test.ts@@ -50,6 +50,10 @@ describe("agent invocation trace coordinator", () => {parentActionCallId: "workflow",}),]);+ await expect(readActionAnchor(serializedContext)).resolves.toMatchObject({+ isWorkflowTool: true,+ workflowName: "coordinate",+ });});it("replays one invocation with the same caller coordinates", async () => {@@ -142,6 +146,12 @@ describe("agent invocation trace coordinator", () => {expect(store.findActionAnchor("session-1", "turn-1", "workflow")?.kind).toBe(recorded ? kind : undefined,);+ expect(store.findActionAnchor("session-1", "turn-1", "workflow")?.isWorkflowTool).toBe(+ undefined,+ );+ expect(store.findActionAnchor("session-1", "turn-1", "workflow")?.workflowName).toBe(+ undefined,+ );expect(store.findInvocations("session-1")).toHaveLength(0);});});@@ -281,11 +291,19 @@ async function readInvocations(serializedContext: Record<string, unknown>) {);}+async function readActionAnchor(serializedContext: Record<string, unknown>) {+ const context = await deserializeContext(serializedContext);+ return contextStorage.run(context, () =>+ new ContextAgentTraceStateStore().findActionAnchor("session-1", "turn-1", "workflow"),+ );+}+function outerAction() {return {attemptIndex: 0,callId: "workflow",channelAudience: "private" as const,+ isWorkflowTool: true,kind: "tool-call" as const,name: "coordinate",parent: {diff --git a/packages/eve/src/tracing/agent-otel-provider.test.ts b/packages/eve/src/tracing/agent-otel-provider.test.tsindex 7b938fd41..57a1a6f1c 100644--- a/packages/eve/src/tracing/agent-otel-provider.test.ts+++ b/packages/eve/src/tracing/agent-otel-provider.test.ts@@ -2,8 +2,10 @@ import { SpanKind, SpanStatusCode, trace as apiTrace } from "@opentelemetry/api"import {BasicTracerProvider,InMemorySpanExporter,+ SamplingDecision,SimpleSpanProcessor,type ReadableSpan,+ type Sampler,type SpanProcessor,} from "@opentelemetry/sdk-trace-base";import { describe, expect, it, vi } from "vitest";@@ -18,11 +20,16 @@ import { ContextContainer, contextStorage } from "#context/container.js";import { ActiveChannelDeliveriesKey, SessionTraceSeedKey } from "#context/keys.js";import { deserializeContext, serializeContext } from "#context/serialize.js";import { createAiSdkHookBridge } from "#instrumentation/ai-sdk-hook-bridge.js";+import { createInstrumentationHandleEvent } from "#instrumentation/native-events.js";+import { createPresentedRuntimeActionRequestFromToolCall } from "#harness/action-presentation.js";+import type { HarnessToolMap } from "#harness/types.js";+import { createActionResultEvent, createActionsRequestedEvent } from "#protocol/message.js";import {createAgentOtelInstrumentation,type AgentOtelInstrumentationInput,} from "#tracing/agent-otel-provider.js";import { AgentSpanIdGenerator } from "#tracing/agent-span-id-generator.js";+import { prepareAgentInvocationTrace } from "#tracing/agent-invocation-coordinator.js";import { ContextAgentTraceStateStore } from "#tracing/agent-trace-context-store.js";import {type AgentTraceStateStore,@@ -65,6 +72,7 @@ import {takeInstrumentationActionScopeForTask,} from "#instrumentation/state.js";import { preserveSerializedBackgroundTaskObservabilityState } from "#shared/serialized-observability-state.js";+import { isRuntimeWorkflowToolAction } from "#shared/action-types.js";interface TestRuntime {readonly exporter: InMemorySpanExporter;@@ -90,11 +98,13 @@ function createRuntime(}),extraSpanProcessors: readonly SpanProcessor[] = [],samplesTrace?: AgentOtelInstrumentationInput["samplesTrace"],+ sampler?: Sampler,): TestRuntime {const exporter = new InMemorySpanExporter();const idGenerator = new AgentSpanIdGenerator();const provider = new BasicTracerProvider({idGenerator,+ sampler,spanProcessors: [new SimpleSpanProcessor(exporter), ...extraSpanProcessors],});const tracer = provider.getTracer("eve.agent");@@ -1236,7 +1246,190 @@ describe("createAgentOtelInstrumentation", () => {expect(tool.attributes).not.toHaveProperty("gen_ai.agent.name");});- it("keeps a workflow tool intact while emitting independent nested callers", async () => {+ it("projects production workflow actions and classifies only GenAI composition", async () => {+ const samplerCalls: {+ readonly attributes: Readonly<Record<string, unknown>>;+ readonly name: string;+ }[] = [];+ const sampler: Sampler = {+ shouldSample(_context, _traceId, name, _kind, attributes) {+ samplerCalls.push({ attributes, name });+ return { decision: SamplingDecision.RECORD_AND_SAMPLED };+ },+ toString: () => "recording-sampler",+ };+ const context = new ContextContainer();+ let runtime: TestRuntime | undefined;++ await contextStorage.run(context, async () => {+ runtime = createRuntime(new ContextAgentTraceStateStore(), undefined, [], undefined, sampler);+ const scope: InstrumentationAttemptScope = {+ attemptId: "session-workflow:turn-1:0:0",+ attemptIndex: 0,+ functionId: "weather",+ sessionId: "session-workflow",+ stepIndex: 0,+ turnId: "turn-1",+ };+ await publishTurnStarted({+ hooks: runtime.hooks,+ sessionId: scope.sessionId,+ turnId: scope.turnId,+ turnSequence: 0,+ });+ await runtime.hooks.publish({+ idempotencyKey: attemptIdempotencyKey(scope),+ operation: { modelId: "model", operationId: "ai.streamText", provider: "test" },+ scope,+ type: "step.attempt.started",+ });++ const tools: HarnessToolMap = new Map([+ [+ "coordinate",+ {+ description: "Coordinate research.",+ inputSchema: {} as never,+ name: "coordinate",+ workflowId: "workflow//./agent/tools/coordinate//execute",+ },+ ],+ [+ "wait",+ {+ description: "Wait durably.",+ inputSchema: {} as never,+ name: "wait",+ workflowId: "workflow//./agent/tools/wait//execute",+ },+ ],+ ]);+ const projections = [+ createPresentedRuntimeActionRequestFromToolCall({+ toolCall: {+ input: { query: "review" },+ toolCallId: "workflow",+ toolName: "coordinate",+ type: "tool-call",+ } as never,+ tools,+ }),+ createPresentedRuntimeActionRequestFromToolCall({+ toolCall: {+ input: { delay: "1m" },+ toolCallId: "wait",+ toolName: "wait",+ type: "tool-call",+ } as never,+ tools,+ }),+ ];+ expect(projections.map(({ action }) => action.kind)).toEqual(["tool-call", "tool-call"]);+ expect(projections.every(({ action }) => isRuntimeWorkflowToolAction(action))).toBe(true);++ const handleEvent = createInstrumentationHandleEvent({+ getAttemptScope: () => scope,+ handleEvent: async () => {},+ hooks: runtime.hooks,+ sessionId: scope.sessionId,+ })!;+ await handleEvent(+ createActionsRequestedEvent({+ actions: projections.map(({ action }) => action),+ sequence: 0,+ stepIndex: 0,+ turnId: scope.turnId,+ }),+ );++ const nested = prepareAgentInvocationTrace({+ invocation: {+ callId: "workflow:child",+ kind: "subagent-call",+ name: "research",+ },+ ownerId: "workflow-run",+ serializedContext: serializeContext(context),+ sessionId: scope.sessionId,+ sessionState: {+ "eve.runtime.workflowToolRuns": [+ {+ callId: "workflow",+ hookToken: "workflow-hook",+ runId: "workflow-run",+ toolName: "coordinate",+ },+ ],+ },+ startTimeMs: 2,+ turnId: scope.turnId,+ });+ const settled = nested.fail({+ callId: "workflow:child",+ isError: true,+ kind: "subagent-result",+ origin: "dispatch",+ output: "unavailable",+ subagentName: "research",+ });+ const restored = await deserializeContext(settled);+ await contextStorage.run(restored, async () => {+ const terminal = createInstrumentationHandleEvent({+ handleEvent: async () => {},+ hooks: runtime!.hooks,+ sessionId: scope.sessionId,+ })!;+ for (const [callId, toolName] of [+ ["workflow", "coordinate"],+ ["wait", "wait"],+ ] as const) {+ await terminal(+ createActionResultEvent({+ result: {+ callId,+ kind: "tool-result",+ output: { done: true },+ toolName,+ },+ sequence: 0,+ stepIndex: 0,+ turnId: scope.turnId,+ }),+ );+ }+ await runtime!.hooks.publish({+ idempotencyKey: attemptIdempotencyKey(scope),+ scope,+ type: "step.attempt.completed",+ });+ await completeTurn(runtime!.hooks, scope.sessionId, scope.turnId);+ });+ });++ await runtime!.provider.forceFlush();+ const spans = runtime!.exporter.getFinishedSpans();+ const workflow = byName(spans, "invoke_workflow coordinate")[0]!;+ const wait = spans.find((span) => span.attributes["agent.action.call_id"] === "wait")!;+ const sampledWorkflow = samplerCalls.find(+ ({ attributes }) => attributes["agent.action.call_id"] === "workflow",+ )!;++ expect(workflow.attributes).toMatchObject({+ "gen_ai.operation.name": "invoke_workflow",+ "gen_ai.workflow.name": "coordinate",+ });+ expect(wait.name).toBe("agent.action");+ expect(wait.attributes).not.toHaveProperty("gen_ai.operation.name");+ expect(sampledWorkflow).toMatchObject({+ attributes: {+ "gen_ai.operation.name": "invoke_workflow",+ "gen_ai.workflow.name": "coordinate",+ },+ name: "agent.action",+ });+ });++ it("keeps a composed workflow intact while emitting independent nested callers", async () => {const stateStore = new InMemoryAgentTraceStateStore();const runtime = createRuntime(stateStore);const scope: InstrumentationAttemptScope = {@@ -1286,15 +1479,11 @@ describe("createAgentOtelInstrumentation", () => {scope,type: "tool.call.completed",});- await runtime.hooks.publish({- idempotencyKey: actionKey,- outcome: "completed",- output: { output: "done", type: "result" },- scope,- type: "action.completed",- });- const anchor = stateStore.findActionAnchor(scope.sessionId, scope.turnId, "workflow")!;+ const action = stateStore.getAction(actionKey)!;+ const anchor = { ...action, workflowName: "coordinate" };+ stateStore.setAction(actionKey, anchor);+ stateStore.setActionAnchor(actionKey, anchor);stateStore.setInvocation(actionIdempotencyKey(scope.sessionId, scope.turnId, "workflow:first"),{@@ -1321,6 +1510,13 @@ describe("createAgentOtelInstrumentation", () => {terminal: { error: new Error("review failed"), outcome: "failed" },},);+ await runtime.hooks.publish({+ idempotencyKey: actionKey,+ outcome: "completed",+ output: { output: "done", type: "result" },+ scope,+ type: "action.completed",+ });await runtime.hooks.publish({idempotencyKey: attemptIdempotencyKey(scope),scope,@@ -1330,7 +1526,7 @@ describe("createAgentOtelInstrumentation", () => {await runtime.provider.forceFlush();const spans = runtime.exporter.getFinishedSpans();- const outer = byName(spans, "agent.action")[0]!;+ const outer = byName(spans, "invoke_workflow coordinate")[0]!;const tool = byName(spans, "execute_tool coordinate")[0]!;const first = spans.find((span) => span.attributes["agent.action.call_id"] === "workflow:first",@@ -1338,7 +1534,16 @@ describe("createAgentOtelInstrumentation", () => {const second = spans.find((span) => span.attributes["agent.action.call_id"] === "workflow:second",)!;- expect(byName(spans, "agent.action")).toHaveLength(3);+ expect(byName(spans, "agent.action")).toHaveLength(2);+ expect(outer.attributes).toMatchObject({+ "agent.action.call_id": "workflow",+ "agent.action.kind": "tool-call",+ "agent.action.name": "coordinate",+ "gen_ai.operation.name": "invoke_workflow",+ "gen_ai.workflow.name": "coordinate",+ "operation.name": "invoke_workflow",+ "resource.name": "invoke_workflow coordinate",+ });expect(first.attributes).not.toHaveProperty("gen_ai.operation.name");expect(second.attributes).not.toHaveProperty("gen_ai.operation.name");expect(tool.parentSpanContext?.spanId).toBe(outer.spanContext().spanId);diff --git a/packages/eve/src/tracing/agent-span-contract.ts b/packages/eve/src/tracing/agent-span-contract.tsindex 11a78cdef..e48521cec 100644--- a/packages/eve/src/tracing/agent-span-contract.ts+++ b/packages/eve/src/tracing/agent-span-contract.ts@@ -18,6 +18,10 @@ export function agentInvocationSpanName(agentName: string | undefined): string {return agentName === undefined ? "invoke_agent" : `invoke_agent ${agentName}`;}+export function workflowInvocationSpanName(workflowName: string): string {+ return `invoke_workflow ${workflowName}`;+}+export interface AgentSamplingOperation {readonly name: string;readonly attributes?: Readonly<Record<string, string | number | boolean | undefined>>;diff --git a/packages/eve/src/tracing/agent-telemetry-contract.integration.test.ts b/packages/eve/src/tracing/agent-telemetry-contract.integration.test.tsindex eae743578..139e3d73e 100644--- a/packages/eve/src/tracing/agent-telemetry-contract.integration.test.ts+++ b/packages/eve/src/tracing/agent-telemetry-contract.integration.test.ts@@ -639,7 +639,7 @@ describe("exported agent telemetry contract", () => {" invoked from external via channel.request"," invoke_agent parent"," agent.step",- " agent.action coordinate",+ " invoke_workflow coordinate"," agent.action child role=caller"," agent.approval approved"," execute_tool coordinate",@@ -957,6 +957,9 @@ function normalizeTraceForest(}function spanLabel(span: LocalTraceSpan): string {+ if (span.attributes["gen_ai.operation.name"] === "invoke_workflow") {+ return span.name;+ }if (span.name === "agent.action") {const role = span.attributes["agent.invocation.role"] === "caller" ? " role=caller" : "";return `agent.action ${String(span.attributes["agent.action.name"])}${role}`;diff --git a/packages/eve/src/tracing/agent-trace-context-codec.ts b/packages/eve/src/tracing/agent-trace-context-codec.tsindex e1bb803f6..7163f6234 100644--- a/packages/eve/src/tracing/agent-trace-context-codec.ts+++ b/packages/eve/src/tracing/agent-trace-context-codec.ts@@ -177,6 +177,7 @@ function deserializeAction(value: unknown): AgentActionTraceState | undefined {callId: value.callId,channelAudience: normalizeChannelAudience(value.channelAudience),inputAttribute: typeof value.inputAttribute === "string" ? value.inputAttribute : undefined,+ isWorkflowTool: value.isWorkflowTool === true ? true : undefined,kind: value.kind,name: value.name,parent: value.parent,@@ -186,6 +187,7 @@ function deserializeAction(value: unknown): AgentActionTraceState | undefined {startTimeMs: value.startTimeMs,stepIndex: value.stepIndex,turnId: value.turnId,+ workflowName: typeof value.workflowName === "string" ? value.workflowName : undefined,};}diff --git a/packages/eve/src/tracing/agent-trace-context-store.ts b/packages/eve/src/tracing/agent-trace-context-store.tsindex b54ba0b2d..9c2e3b328 100644--- a/packages/eve/src/tracing/agent-trace-context-store.ts+++ b/packages/eve/src/tracing/agent-trace-context-store.ts@@ -201,7 +201,28 @@ export function recordNestedAgentInvocation(input: {const outer = state.actions[outerKey] ?? state.actionAnchors[outerKey];if (outer === undefined) return input.serializedContext;const key = actionIdempotencyKey(input.sessionId, input.turnId, input.callId);- if (state.invocations[key] !== undefined) return input.serializedContext;+ const promote = (action: AgentActionTraceState): AgentActionTraceState =>+ action.isWorkflowTool === true && action.kind === "tool-call"+ ? { ...action, workflowName: action.name }+ : action;+ const actions =+ state.actions[outerKey] === undefined+ ? state.actions+ : { ...state.actions, [outerKey]: promote(state.actions[outerKey]) };+ const actionAnchors =+ state.actionAnchors[outerKey] === undefined+ ? state.actionAnchors+ : { ...state.actionAnchors, [outerKey]: promote(state.actionAnchors[outerKey]) };+ if (state.invocations[key] !== undefined) {+ return {+ ...input.serializedContext,+ [AgentTraceContextKey.name]: serializeAgentTraceContextState({+ ...state,+ actionAnchors,+ actions,+ }),+ };+ }const invocation: AgentInvocationTraceState = {attemptIndex: outer.attemptIndex,callId: input.callId,@@ -226,6 +247,8 @@ export function recordNestedAgentInvocation(input: {...input.serializedContext,[AgentTraceContextKey.name]: serializeAgentTraceContextState({...state,+ actionAnchors,+ actions,invocations: { ...state.invocations, [key]: invocation },}),};@@ -245,7 +268,12 @@ export function recordActionInvocationKind(input: {action.sessionId === input.sessionId &&action.turnId === input.turnId &&action.callId === input.callId- ? { ...action, kind: input.kind }+ ? {+ ...action,+ isWorkflowTool: undefined,+ kind: input.kind,+ workflowName: undefined,+ }: action;return {...input.serializedContext,diff --git a/packages/eve/src/tracing/agent-trace-state.ts b/packages/eve/src/tracing/agent-trace-state.tsindex 375ec0551..6f23ee3e8 100644--- a/packages/eve/src/tracing/agent-trace-state.ts+++ b/packages/eve/src/tracing/agent-trace-state.ts@@ -54,6 +54,7 @@ export interface AgentActionTraceState {readonly callId: string;readonly channelAudience?: ChannelAudience;readonly inputAttribute?: string;+ readonly isWorkflowTool?: boolean;readonly kind: InstrumentationActionKind;readonly name: string;readonly parent: InstrumentationTraceContext;@@ -63,11 +64,12 @@ export interface AgentActionTraceState {readonly startTimeMs: number;readonly stepIndex: number;readonly turnId: string;+ readonly workflowName?: string;}export interface AgentInvocationTraceState extends Omit<AgentActionTraceState,- "inputAttribute" | "kind"+ "inputAttribute" | "isWorkflowTool" | "kind" | "workflowName"> {readonly kind: "remote-agent-call" | "subagent-call";readonly parentActionCallId: string;