eve 0.54.0 → 0.54.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (138) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/dist/src/chunks/{use-eve-agent-BR8EpIOX.js → use-eve-agent-CxPlg0KL.js} +0 -1
  3. package/dist/src/chunks/{use-eve-agent-XnfjQt1Z.js → use-eve-agent-D-KQzzyW.js} +0 -1
  4. package/dist/src/cli/dev/tui/setup-commands.js +1 -1
  5. package/dist/src/cli/dev/tui/tool-presentation.js +1 -1
  6. package/dist/src/cli/dev/tui/traces/trace-content.d.ts +1 -3
  7. package/dist/src/cli/dev/tui/traces/trace-content.js +2 -2
  8. package/dist/src/cli/dev/tui/traces/trace-conversation.js +1 -1
  9. package/dist/src/cli/dev/tui/traces/trace-view.js +1 -1
  10. package/dist/src/client/agent-info-schema.d.ts +0 -1
  11. package/dist/src/client/agent-info-schema.js +1 -1
  12. package/dist/src/compiled/.vendor-stamp.json +3 -1
  13. package/dist/src/compiled/just-secrets/LICENSE +21 -0
  14. package/dist/src/compiled/just-secrets/index.d.ts +20 -0
  15. package/dist/src/compiled/just-secrets/index.js +2 -0
  16. package/dist/src/compiled/just-secrets/windows.ps1 +138 -0
  17. package/dist/src/compiler/default-tool-policy.js +1 -1
  18. package/dist/src/compiler/extension-compatibility.d.ts +6 -6
  19. package/dist/src/compiler/extension-compatibility.js +1 -1
  20. package/dist/src/compiler/manifest.js +1 -1
  21. package/dist/src/compiler/normalize-manifest-helpers.d.ts +2 -1
  22. package/dist/src/compiler/normalize-manifest-helpers.js +1 -1
  23. package/dist/src/compiler/normalize-manifest.js +1 -1
  24. package/dist/src/compiler/resolve-workspace-subagent.d.ts +13 -0
  25. package/dist/src/compiler/resolve-workspace-subagent.js +1 -0
  26. package/dist/src/context/memory-event-lifecycle.d.ts +2 -0
  27. package/dist/src/context/memory-event-lifecycle.js +1 -1
  28. package/dist/src/context/memory-lifecycle.d.ts +5 -0
  29. package/dist/src/context/memory-lifecycle.js +1 -1
  30. package/dist/src/execution/coordination-dispatch-step.js +1 -1
  31. package/dist/src/execution/create-session-step.js +1 -1
  32. package/dist/src/execution/durable-session-migrations/snapshot.d.ts +0 -16
  33. package/dist/src/execution/durable-session-migrations/snapshot.js +1 -1
  34. package/dist/src/execution/parked-delivery-wait.js +1 -1
  35. package/dist/src/execution/session.d.ts +0 -2
  36. package/dist/src/execution/session.js +1 -1
  37. package/dist/src/execution/tasks/parent/dispatch.d.ts +1 -12
  38. package/dist/src/execution/tasks/parent/dispatch.js +1 -1
  39. package/dist/src/execution/tools/sleep-workflow.js +1 -1
  40. package/dist/src/execution/tools/subagent/invoke-agent.d.ts +1 -2
  41. package/dist/src/execution/tools/subagent/invoke-agent.js +1 -1
  42. package/dist/src/execution/tools/tasks.d.ts +1 -8
  43. package/dist/src/execution/tools/tasks.js +1 -1
  44. package/dist/src/execution/workflow-steps.js +1 -1
  45. package/dist/src/framework/sources/registry.js +1 -1
  46. package/dist/src/harness/compaction.js +1 -1
  47. package/dist/src/harness/coordination.js +1 -1
  48. package/dist/src/harness/emission.js +1 -1
  49. package/dist/src/harness/execute-tool.d.ts +2 -4
  50. package/dist/src/harness/messages.d.ts +1 -1
  51. package/dist/src/harness/messages.js +1 -1
  52. package/dist/src/harness/model-call-error.d.ts +5 -0
  53. package/dist/src/harness/model-call-error.js +1 -1
  54. package/dist/src/harness/semantic-errors/rules/model-provider.js +1 -1
  55. package/dist/src/harness/step-hooks.d.ts +17 -10
  56. package/dist/src/harness/step-hooks.js +1 -1
  57. package/dist/src/harness/tool-loop.js +2 -2
  58. package/dist/src/instrumentation/content.js +1 -1
  59. package/dist/src/instrumentation/dispatch.js +1 -1
  60. package/dist/src/instrumentation/lifecycle.d.ts +7 -3
  61. package/dist/src/instrumentation/memory.d.ts +72 -0
  62. package/dist/src/instrumentation/memory.js +1 -0
  63. package/dist/src/instrumentation/native-events.js +1 -1
  64. package/dist/src/instrumentation/provider.d.ts +1 -0
  65. package/dist/src/instrumentation/runtime.d.ts +3 -0
  66. package/dist/src/instrumentation/runtime.js +1 -1
  67. package/dist/src/internal/application/package.js +1 -1
  68. package/dist/src/internal/nitro/routes/index.d.ts +6 -0
  69. package/dist/src/internal/nitro/routes/index.js +7 -7
  70. package/dist/src/internal/vercel/assemble-eve-services.js +1 -1
  71. package/dist/src/internal/vercel/build-agent-workspace.js +1 -1
  72. package/dist/src/internal/vercel/build-multi-agent-landing-page.d.ts +3 -0
  73. package/dist/src/internal/vercel/build-multi-agent-landing-page.js +1 -0
  74. package/dist/src/internal/vercel/eve-service-contribution.d.ts +4 -0
  75. package/dist/src/internal/vercel/eve-service-contribution.js +1 -1
  76. package/dist/src/public/definitions/workspace-agent.d.ts +25 -0
  77. package/dist/src/public/definitions/workspace-agent.js +1 -0
  78. package/dist/src/public/index.d.ts +1 -0
  79. package/dist/src/public/index.js +1 -1
  80. package/dist/src/public/models/openai/chatgpt/credential-store.d.ts +22 -4
  81. package/dist/src/public/models/openai/chatgpt/credential-store.js +1 -1
  82. package/dist/src/public/models/openai/chatgpt/oauth.d.ts +6 -4
  83. package/dist/src/public/models/openai/chatgpt/token-broker.js +1 -1
  84. package/dist/src/setup/flows/chatgpt-auth.js +1 -1
  85. package/dist/src/setup/flows/model.d.ts +0 -2
  86. package/dist/src/setup/flows/model.js +1 -1
  87. package/dist/src/setup/scaffold/create/project.js +1 -1
  88. package/dist/src/shared/action-types.d.ts +4 -0
  89. package/dist/src/shared/action-types.js +1 -1
  90. package/dist/src/shared/dispatch-action.d.ts +1 -1
  91. package/dist/src/subagents/callback-route.js +1 -1
  92. package/dist/src/subagents/callback-step.d.ts +0 -8
  93. package/dist/src/subagents/callback-step.js +1 -1
  94. package/dist/src/svelte/index.js +1 -1
  95. package/dist/src/svelte/use-eve-agent.js +1 -1
  96. package/dist/src/tasks/delivery-context.d.ts +2 -2
  97. package/dist/src/tasks/delivery-context.js +2 -2
  98. package/dist/src/tasks/session-index.d.ts +6 -3
  99. package/dist/src/tasks/session-index.js +1 -1
  100. package/dist/src/tasks/session-task-cohorts.d.ts +10 -2
  101. package/dist/src/tasks/session-task-cohorts.js +1 -1
  102. package/dist/src/tools/behavior.d.ts +1 -3
  103. package/dist/src/tools/framework/task-contract.d.ts +0 -4
  104. package/dist/src/tools/framework/task-contract.js +1 -1
  105. package/dist/src/tracing/agent-action-instrumentation.js +1 -1
  106. package/dist/src/tracing/agent-approval-instrumentation.js +1 -1
  107. package/dist/src/tracing/agent-channel-delivery-instrumentation.js +1 -1
  108. package/dist/src/tracing/agent-memory-instrumentation.d.ts +13 -0
  109. package/dist/src/tracing/agent-memory-instrumentation.js +1 -0
  110. package/dist/src/tracing/agent-otel-content.d.ts +4 -12
  111. package/dist/src/tracing/agent-otel-content.js +3 -3
  112. package/dist/src/tracing/agent-otel-provider.js +2 -2
  113. package/dist/src/tracing/agent-span-contract.d.ts +1 -0
  114. package/dist/src/tracing/agent-span-contract.js +1 -1
  115. package/dist/src/tracing/agent-tool-instrumentation.js +1 -1
  116. package/dist/src/tracing/agent-trace-context-codec.js +1 -1
  117. package/dist/src/tracing/agent-trace-context-store.js +1 -1
  118. package/dist/src/tracing/agent-trace-state.d.ts +3 -1
  119. package/dist/src/tracing/content-attributes.js +1 -1
  120. package/dist/src/tracing/install-instrumentation-runtime.js +1 -1
  121. package/dist/src/vue/index.js +1 -1
  122. package/dist/src/vue/use-eve-agent.js +1 -1
  123. package/docs/concepts/built-in-tools.md +0 -20
  124. package/docs/concepts/sessions-runs-and-streaming.md +9 -1
  125. package/docs/guides/frontend/overview.mdx +1 -1
  126. package/docs/guides/instrumentation.md +65 -30
  127. package/docs/reference/cli.md +9 -9
  128. package/docs/reference/typescript-api.md +7 -3
  129. package/docs/subagents/index.mdx +46 -10
  130. package/package.json +2 -6
  131. package/dist/src/execution/tasks/child/update-step.d.ts +0 -6
  132. package/dist/src/execution/tasks/child/update-step.js +0 -1
  133. package/dist/src/execution/tasks/child/update.d.ts +0 -8
  134. package/dist/src/execution/tasks/child/update.js +0 -1
  135. package/dist/src/public/tools/task-update.d.ts +0 -1
  136. package/dist/src/public/tools/task-update.js +0 -1
  137. package/dist/src/tools/framework/task-update.d.ts +0 -5
  138. package/dist/src/tools/framework/task-update.js +0 -1
@@ -4,7 +4,7 @@ export type ToolAvailabilityCondition = "delegated-task-child" | "requires-reque
4
4
  /** Native behavior declared by a selected compiled tool. */
5
5
  export type CompiledToolHandling = {
6
6
  readonly kind: "dispatch";
7
- readonly action: "self-agent" | "task-cancel" | "task-update";
7
+ readonly action: "self-agent" | "task-cancel";
8
8
  } | {
9
9
  readonly kind: "provider-tool";
10
10
  readonly provider: WebSearchProvider;
@@ -41,8 +41,6 @@ export type PreparedDispatchTarget = {
41
41
  readonly subagentName: string;
42
42
  } | {
43
43
  readonly kind: "task-cancel";
44
- } | {
45
- readonly kind: "task-update";
46
44
  } | {
47
45
  readonly kind: "workflow-tool-call";
48
46
  readonly workflowId: string;
@@ -1,14 +1,10 @@
1
1
  import { z } from "#compiled/zod/index.js";
2
2
  export declare const TASK_CANCEL_TOOL_NAME = "task_cancel";
3
- export declare const TASK_UPDATE_TOOL_NAME = "task_update";
4
3
  /** Framework task-control tool names lowered by the runtime. */
5
4
  export declare const TASK_TOOL_NAMES: ReadonlySet<string>;
6
5
  export declare const TASK_CANCEL_INPUT_SCHEMA: z.ZodObject<{
7
6
  taskIds: z.ZodArray<z.ZodString>;
8
7
  }, z.core.$strict>;
9
- export declare const TASK_UPDATE_INPUT_SCHEMA: z.ZodObject<{
10
- message: z.ZodString;
11
- }, z.core.$strict>;
12
8
  /** Strict model-visible task projection. */
13
9
  export declare const TASK_VIEW_JSON_SCHEMA: z.ZodDiscriminatedUnion<[z.ZodObject<{
14
10
  metadata: z.ZodObject<{
@@ -1 +1 @@
1
- import{z}from"#compiled/zod/index.js";import{jsonValueSchema}from"#shared/json-schemas.js";const TASK_CANCEL_TOOL_NAME=`task_cancel`,TASK_UPDATE_TOOL_NAME=`task_update`,TASK_TOOL_NAMES=new Set([TASK_CANCEL_TOOL_NAME,TASK_UPDATE_TOOL_NAME]),TASK_IDS_SCHEMA=z.array(z.string().min(1)).min(1).describe(`Task ids from earlier subagent task receipts.`),TASK_CANCEL_INPUT_SCHEMA=z.strictObject({taskIds:TASK_IDS_SCHEMA}),TASK_UPDATE_INPUT_SCHEMA=z.strictObject({message:z.string().min(1).describe(`Brief description of what this task is currently doing.`)}),taskMetadataJsonSchema=z.object({agentId:z.string().optional(),kind:z.string(),mode:z.enum([`local`,`remote`]).optional(),name:z.string()}),taskOutputJsonSchema=z.object({data:jsonValueSchema,type:z.enum([`result`,`error`])}),taskViewJsonBaseShape={metadata:taskMetadataJsonSchema,taskId:z.string()},TASK_VIEW_JSON_SCHEMA=z.discriminatedUnion(`status`,[z.object({...taskViewJsonBaseShape,status:z.literal(`working`)}),z.object({...taskViewJsonBaseShape,inputRequests:z.array(jsonValueSchema).readonly(),status:z.literal(`input_required`)}),z.object({...taskViewJsonBaseShape,lastOutput:taskOutputJsonSchema.extend({type:z.literal(`result`)}),status:z.literal(`completed`)}),z.object({...taskViewJsonBaseShape,lastOutput:taskOutputJsonSchema.extend({type:z.literal(`error`)}),status:z.literal(`failed`)}),z.object({...taskViewJsonBaseShape,status:z.literal(`cancelled`)})]),TASK_VIEW_OUTPUT_SCHEMA=z.object({inputRequests:z.array(z.unknown()).optional(),lastOutput:z.object({data:z.unknown(),type:z.enum([`result`,`error`])}).optional(),metadata:z.object({agentId:z.string().optional(),kind:z.string(),mode:z.enum([`local`,`remote`]).optional(),name:z.string()}),status:z.enum([`working`,`input_required`,`completed`,`failed`,`cancelled`]),taskId:z.string()}),TASK_VIEWS_OUTPUT_SCHEMA=z.object({tasks:z.array(TASK_VIEW_OUTPUT_SCHEMA)}),SUBAGENT_TASK_RECEIPT_OUTPUT_SCHEMA=z.strictObject({agentId:z.string(),status:z.literal(`working`),taskId:z.string()});export{SUBAGENT_TASK_RECEIPT_OUTPUT_SCHEMA,TASK_CANCEL_INPUT_SCHEMA,TASK_CANCEL_TOOL_NAME,TASK_TOOL_NAMES,TASK_UPDATE_INPUT_SCHEMA,TASK_UPDATE_TOOL_NAME,TASK_VIEWS_OUTPUT_SCHEMA,TASK_VIEW_JSON_SCHEMA,TASK_VIEW_OUTPUT_SCHEMA};
1
+ import{z}from"#compiled/zod/index.js";import{jsonValueSchema}from"#shared/json-schemas.js";const TASK_CANCEL_TOOL_NAME=`task_cancel`,TASK_TOOL_NAMES=new Set([TASK_CANCEL_TOOL_NAME]),TASK_IDS_SCHEMA=z.array(z.string().min(1)).min(1).describe(`Task ids from earlier subagent task receipts.`),TASK_CANCEL_INPUT_SCHEMA=z.strictObject({taskIds:TASK_IDS_SCHEMA}),taskMetadataJsonSchema=z.object({agentId:z.string().optional(),kind:z.string(),mode:z.enum([`local`,`remote`]).optional(),name:z.string()}),taskOutputJsonSchema=z.object({data:jsonValueSchema,type:z.enum([`result`,`error`])}),taskViewJsonBaseShape={metadata:taskMetadataJsonSchema,taskId:z.string()},TASK_VIEW_JSON_SCHEMA=z.discriminatedUnion(`status`,[z.object({...taskViewJsonBaseShape,status:z.literal(`working`)}),z.object({...taskViewJsonBaseShape,inputRequests:z.array(jsonValueSchema).readonly(),status:z.literal(`input_required`)}),z.object({...taskViewJsonBaseShape,lastOutput:taskOutputJsonSchema.extend({type:z.literal(`result`)}),status:z.literal(`completed`)}),z.object({...taskViewJsonBaseShape,lastOutput:taskOutputJsonSchema.extend({type:z.literal(`error`)}),status:z.literal(`failed`)}),z.object({...taskViewJsonBaseShape,status:z.literal(`cancelled`)})]),TASK_VIEW_OUTPUT_SCHEMA=z.object({inputRequests:z.array(z.unknown()).optional(),lastOutput:z.object({data:z.unknown(),type:z.enum([`result`,`error`])}).optional(),metadata:z.object({agentId:z.string().optional(),kind:z.string(),mode:z.enum([`local`,`remote`]).optional(),name:z.string()}),status:z.enum([`working`,`input_required`,`completed`,`failed`,`cancelled`]),taskId:z.string()}),TASK_VIEWS_OUTPUT_SCHEMA=z.object({tasks:z.array(TASK_VIEW_OUTPUT_SCHEMA)}),SUBAGENT_TASK_RECEIPT_OUTPUT_SCHEMA=z.strictObject({agentId:z.string(),status:z.literal(`working`),taskId:z.string()});export{SUBAGENT_TASK_RECEIPT_OUTPUT_SCHEMA,TASK_CANCEL_INPUT_SCHEMA,TASK_CANCEL_TOOL_NAME,TASK_TOOL_NAMES,TASK_VIEWS_OUTPUT_SCHEMA,TASK_VIEW_JSON_SCHEMA,TASK_VIEW_OUTPUT_SCHEMA};
@@ -1 +1 @@
1
- import{normalizeChannelAudience}from"#shared/channel-audience.js";import{AGENT_SPAN_NAMES}from"#tracing/agent-span-contract.js";import{isSampledTrace}from"#tracing/sampled-trace.js";import{ROOT_CONTEXT,SpanKind,trace}from"#compiled/@opentelemetry/api/index.js";import{actionIdempotencyKey,attemptIdempotencyKey}from"#instrumentation/lifecycle.js";import{agentSpanNamingAttributes}from"#tracing/agent-span-naming.js";import{agentTraceIdentityAttributes}from"#tracing/agent-otel-attributes.js";import{contentAttribute,textContentAttribute}from"#tracing/agent-otel-content.js";import{setAgentUsage}from"#tracing/agent-otel-usage.js";import{withChannelAudience}from"#tracing/channel-audience-context.js";import{recordAgentSpanError}from"#tracing/agent-span-error.js";function createAgentActionInstrumentation(e){let t=new Map,onStarted=async n=>{let r=await e.resolveTraceContext(n);if(r===void 0||!isSampledTrace(r))return;let i=await e.stateStore.getAction(n.idempotencyKey)??{attemptIndex:n.scope.attemptIndex,callId:n.callId,channelAudience:normalizeChannelAudience(n.scope.channelAudience),inputAttribute:e.recordInputs?contentAttribute(n.input,!1):void 0,kind:n.kind,name:n.name,parent:{spanId:e.idGenerator.deriveSpanId(attemptIdempotencyKey(n.scope)),traceFlags:r.traceFlags,traceId:r.traceId},rootSessionId:n.scope.rootSessionId??n.scope.sessionId,sessionId:n.scope.sessionId,spanId:e.idGenerator.deriveSpanId(`action:${n.idempotencyKey}`),startTimeMs:Date.now(),stepIndex:n.scope.stepIndex,turnId:n.scope.turnId};await e.stateStore.setAction(n.idempotencyKey,i),n.isWorkflowTool===!0&&await e.stateStore.setActionAnchor(n.idempotencyKey,i);let a=t.get(n.scope.attemptId)??new Set;a.add(n.idempotencyKey),t.set(n.scope.attemptId,a)},onTerminal=async t=>{let n=await e.stateStore.getAction(t.idempotencyKey);if(n!==void 0)try{finishActionSpan(n,t)}finally{await e.stateStore.deleteAction(t.idempotencyKey),forget(t.idempotencyKey)}},startSpan=t=>{let n=isAgentInvocation(t.kind),r=e.idGenerator.withSpanId(t.spanId,()=>e.tracer.startSpan(AGENT_SPAN_NAMES.action,{attributes:{"agent.action.call_id":t.callId,"agent.action.kind":t.kind,"agent.action.name":t.name,"agent.framework.name":`eve`,"agent.framework.version":e.frameworkVersion,"agent.step.attempt":t.attemptIndex,"agent.step.index":t.stepIndex,"agent.turn.id":t.turnId,...agentSpanNamingAttributes(`agent.action`),...agentTraceIdentityAttributes({rootSessionId:t.rootSessionId,sessionId:t.sessionId}),...n?{"gen_ai.agent.name":t.name,"agent.invocation.role":`caller`}:void 0},kind:t.kind===`remote-agent-call`?SpanKind.CLIENT:SpanKind.INTERNAL,startTime:t.startTimeMs},contextFromActionState(t)));return!n&&t.inputAttribute!==void 0&&r.setAttribute(`gen_ai.tool.call.arguments`,t.inputAttribute),r};return{async contextFor(t,n,r){let i=actionIdempotencyKey(t,n,r),a=await e.stateStore.getAction(i);if(a!==void 0)return actionContext(a);let o=await e.stateStore.findAction(t,r);return o===void 0?void 0:actionContext(o)},async deleteForSession(t){await e.stateStore.deleteActions(t),await e.stateStore.deleteActionAnchors(t),await e.stateStore.deleteInvocations(t)},async failForAttempt(n,r){let i=t.get(n.attemptId);if(i!==void 0){t.delete(n.attemptId);for(let t of i){let n=await e.stateStore.getAction(t);if(n===void 0)continue;let i=startSpan(n);recordAgentSpanError(i,r),i.end(),await e.stateStore.deleteAction(t)}}},flushSettledInvocations:()=>flushInvocations(),async flushForSessionTransition(e){let t=e.type===`session.completed`?{outcome:`abandoned`}:e.type===`session.failed`?{error:e.error,outcome:`failed`}:void 0;await flushInvocations(e.sessionId,t)},events:{"action.completed":onTerminal,"action.failed":onTerminal,"action.started":onStarted}};async function flushInvocations(t,n){for(let r of await e.stateStore.findInvocations(t)){let t=r.terminal??n;t!==void 0&&(finishInvocationSpan(r,t),await e.stateStore.deleteInvocation(actionIdempotencyKey(r.sessionId,r.turnId,r.callId)))}}function forget(e){for(let[n,r]of t)r.delete(e),r.size===0&&t.delete(n)}function finishActionSpan(t,n){let r=startSpan(t);if(r.setAttribute(`agent.action.outcome`,n.outcome),n.type===`action.failed`)n.errorCode!==void 0&&r.setAttribute(`agent.action.error.code`,n.errorCode),recordActionError(r,n.error,n.errorCode);else if(n.output.type===`error`)recordActionError(r,n.output.error);else if(n.usage!==void 0&&setAgentUsage(r,n.usage),e.recordOutputs&&!isAgentInvocation(t.kind)){let e=contentAttribute(n.output.output,!1);e!==void 0&&r.setAttribute(`gen_ai.tool.call.result`,e)}r.end(n.acceptedAtMs)}function finishInvocationSpan(t,n){let r=startSpan(t);r.setAttribute(`agent.action.outcome`,n.outcome),n.usage!==void 0&&setAgentUsage(r,n.usage),n.outcome===`failed`&&recordAgentSpanError(r,e.recordOutputs&&t.recordOutputs===!0?n.error:void 0),r.end(n.acceptedAtMs)}}function actionContext(e){let t={isRemote:!1,spanId:e.spanId,traceFlags:e.parent.traceFlags,traceId:e.parent.traceId};return{context:withChannelAudience(trace.setSpan(ROOT_CONTEXT,trace.wrapSpanContext(t)),e.channelAudience),spanContext:t}}function contextFromActionState(e){return withChannelAudience(trace.setSpan(ROOT_CONTEXT,trace.wrapSpanContext({...e.parent,isRemote:!1})),e.channelAudience)}function isAgentInvocation(e){return e===`subagent-call`||e===`remote-agent-call`}function recordActionError(e,t,n){if(t instanceof Error||t===void 0){recordAgentSpanError(e,t,n);return}let r=serializedErrorDetail(t);if(r===void 0){recordAgentSpanError(e,void 0,n);return}let i=Error(r);n!==void 0&&(i.name=n),recordAgentSpanError(e,i,n)}function serializedErrorDetail(e){if(typeof e==`string`)return textContentAttribute(e);let t=contentAttribute(e,!1);if(typeof e!=`object`||!e||Array.isArray(e))return t;let n=Reflect.get(e,`message`);return typeof n==`string`?textContentAttribute(t===void 0?n:`${n}\n${t}`):t}export{createAgentActionInstrumentation};
1
+ import{normalizeChannelAudience}from"#shared/channel-audience.js";import{AGENT_SPAN_NAMES,workflowInvocationSpanName}from"#tracing/agent-span-contract.js";import{isSampledTrace}from"#tracing/sampled-trace.js";import{ROOT_CONTEXT,SpanKind,trace}from"#compiled/@opentelemetry/api/index.js";import{actionIdempotencyKey,attemptIdempotencyKey}from"#instrumentation/lifecycle.js";import{agentSpanNamingAttributes}from"#tracing/agent-span-naming.js";import{agentTraceIdentityAttributes}from"#tracing/agent-otel-attributes.js";import{contentAttribute,textContentAttribute}from"#tracing/agent-otel-content.js";import{setAgentUsage}from"#tracing/agent-otel-usage.js";import{withChannelAudience}from"#tracing/channel-audience-context.js";import{recordAgentSpanError}from"#tracing/agent-span-error.js";function createAgentActionInstrumentation(e){let t=new Map,onStarted=async n=>{let r=await e.resolveTraceContext(n);if(r===void 0||!isSampledTrace(r))return;let i=await e.stateStore.getAction(n.idempotencyKey)??{attemptIndex:n.scope.attemptIndex,callId:n.callId,channelAudience:normalizeChannelAudience(n.scope.channelAudience),inputAttribute:e.recordInputs?contentAttribute(n.input):void 0,isWorkflowTool:n.isWorkflowTool===!0,kind:n.kind,name:n.name,parent:{spanId:e.idGenerator.deriveSpanId(attemptIdempotencyKey(n.scope)),traceFlags:r.traceFlags,traceId:r.traceId},rootSessionId:n.scope.rootSessionId??n.scope.sessionId,sessionId:n.scope.sessionId,spanId:e.idGenerator.deriveSpanId(`action:${n.idempotencyKey}`),startTimeMs:Date.now(),stepIndex:n.scope.stepIndex,turnId:n.scope.turnId};await e.stateStore.setAction(n.idempotencyKey,i),n.isWorkflowTool===!0&&await e.stateStore.setActionAnchor(n.idempotencyKey,i);let a=t.get(n.scope.attemptId)??new Set;a.add(n.idempotencyKey),t.set(n.scope.attemptId,a)},onTerminal=async t=>{let n=await e.stateStore.getAction(t.idempotencyKey);if(n!==void 0)try{finishActionSpan(n,t)}finally{await e.stateStore.deleteAction(t.idempotencyKey),forget(t.idempotencyKey)}},startSpan=t=>{let n=isAgentInvocation(t.kind),r=t.kind===`tool-call`?t.workflowName:void 0,i=r===void 0?AGENT_SPAN_NAMES.action:workflowInvocationSpanName(r),a=e.idGenerator.withSpanId(t.spanId,()=>e.tracer.startSpan(AGENT_SPAN_NAMES.action,{attributes:{"agent.action.call_id":t.callId,"agent.action.kind":t.kind,"agent.action.name":t.name,"agent.framework.name":`eve`,"agent.framework.version":e.frameworkVersion,"agent.step.attempt":t.attemptIndex,"agent.step.index":t.stepIndex,"agent.turn.id":t.turnId,...agentSpanNamingAttributes(i,r===void 0?void 0:`invoke_workflow`),...agentTraceIdentityAttributes({rootSessionId:t.rootSessionId,sessionId:t.sessionId}),...r===void 0?void 0:{"gen_ai.operation.name":`invoke_workflow`,"gen_ai.workflow.name":r},...n?{"gen_ai.agent.name":t.name,"agent.invocation.role":`caller`}:void 0},kind:t.kind===`remote-agent-call`?SpanKind.CLIENT:SpanKind.INTERNAL,startTime:t.startTimeMs},contextFromActionState(t)));return r!==void 0&&updateSpanName(a,i),!n&&t.inputAttribute!==void 0&&a.setAttribute(`gen_ai.tool.call.arguments`,t.inputAttribute),a};return{async contextFor(t,n,r){let i=actionIdempotencyKey(t,n,r),a=await e.stateStore.getAction(i);if(a!==void 0)return actionContext(a);let o=await e.stateStore.findAction(t,r);return o===void 0?void 0:actionContext(o)},async deleteForSession(t){await e.stateStore.deleteActions(t),await e.stateStore.deleteActionAnchors(t),await e.stateStore.deleteInvocations(t)},async failForAttempt(n,r){let i=t.get(n.attemptId);if(i!==void 0){t.delete(n.attemptId);for(let t of i){let n=await e.stateStore.getAction(t);if(n===void 0)continue;let i=startSpan(n);recordAgentSpanError(i,r),i.end(),await e.stateStore.deleteAction(t)}}},flushSettledInvocations:()=>flushInvocations(),async flushForSessionTransition(e){let t=e.type===`session.completed`?{outcome:`abandoned`}:e.type===`session.failed`?{error:e.error,outcome:`failed`}:void 0;await flushInvocations(e.sessionId,t)},events:{"action.completed":onTerminal,"action.failed":onTerminal,"action.started":onStarted}};async function flushInvocations(t,n){for(let r of await e.stateStore.findInvocations(t)){let t=r.terminal??n;t!==void 0&&(finishInvocationSpan(r,t),await e.stateStore.deleteInvocation(actionIdempotencyKey(r.sessionId,r.turnId,r.callId)))}}function forget(e){for(let[n,r]of t)r.delete(e),r.size===0&&t.delete(n)}function finishActionSpan(t,n){let r=startSpan(t);if(r.setAttribute(`agent.action.outcome`,n.outcome),n.type===`action.failed`)n.errorCode!==void 0&&r.setAttribute(`agent.action.error.code`,n.errorCode),recordActionError(r,n.error,n.errorCode);else if(n.output.type===`error`)recordActionError(r,n.output.error);else if(n.usage!==void 0&&setAgentUsage(r,n.usage),e.recordOutputs&&!isAgentInvocation(t.kind)){let e=contentAttribute(n.output.output);e!==void 0&&r.setAttribute(`gen_ai.tool.call.result`,e)}r.end(n.acceptedAtMs)}function finishInvocationSpan(t,n){let r=startSpan(t);r.setAttribute(`agent.action.outcome`,n.outcome),n.usage!==void 0&&setAgentUsage(r,n.usage),n.outcome===`failed`&&recordAgentSpanError(r,e.recordOutputs&&t.recordOutputs===!0?n.error:void 0),r.end(n.acceptedAtMs)}}function actionContext(e){let t={isRemote:!1,spanId:e.spanId,traceFlags:e.parent.traceFlags,traceId:e.parent.traceId};return{context:withChannelAudience(trace.setSpan(ROOT_CONTEXT,trace.wrapSpanContext(t)),e.channelAudience),spanContext:t}}function contextFromActionState(e){return withChannelAudience(trace.setSpan(ROOT_CONTEXT,trace.wrapSpanContext({...e.parent,isRemote:!1})),e.channelAudience)}function isAgentInvocation(e){return e===`subagent-call`||e===`remote-agent-call`}function updateSpanName(e,t){let n=Reflect.get(e,`updateName`);typeof n==`function`&&Reflect.apply(n,e,[t])}function recordActionError(e,t,n){if(t instanceof Error||t===void 0){recordAgentSpanError(e,t,n);return}let r=serializedErrorDetail(t);if(r===void 0){recordAgentSpanError(e,void 0,n);return}let i=Error(r);n!==void 0&&(i.name=n),recordAgentSpanError(e,i,n)}function serializedErrorDetail(e){if(typeof e==`string`)return textContentAttribute(e);let t=contentAttribute(e);if(typeof e!=`object`||!e||Array.isArray(e))return t;let n=Reflect.get(e,`message`);return typeof n==`string`?textContentAttribute(t===void 0?n:`${n}\n${t}`):t}export{createAgentActionInstrumentation};
@@ -1 +1 @@
1
- import{normalizeChannelAudience}from"#shared/channel-audience.js";import{AGENT_SPAN_NAMES}from"#tracing/agent-span-contract.js";import{ROOT_CONTEXT,trace}from"#compiled/@opentelemetry/api/index.js";import{agentSpanNamingAttributes}from"#tracing/agent-span-naming.js";import{agentTraceIdentityAttributes}from"#tracing/agent-otel-attributes.js";import{contentAttribute}from"#tracing/agent-otel-content.js";import{withChannelAudience}from"#tracing/channel-audience-context.js";import{recordAgentSpanError}from"#tracing/agent-span-error.js";function createAgentApprovalInstrumentation(e){return{"input.requested":async(t,n)=>{if(t.kind!==`tool-approval`||readState(n.state.get())!==void 0)return;let r=await e.actionContextFor(t.scope.sessionId,t.scope.turnId,t.action.callId);if(r===void 0)return;let i={actionCallId:t.action.callId,actionName:t.action.name,attemptIndex:t.scope.attemptIndex,channelAudience:normalizeChannelAudience(t.scope.channelAudience),parent:{spanId:r.spanContext.spanId,traceFlags:r.spanContext.traceFlags,traceId:r.spanContext.traceId},requestId:t.requestId,rootSessionId:t.scope.rootSessionId??t.scope.sessionId,sessionId:t.scope.sessionId,startTimeMs:Date.now(),stepIndex:t.scope.stepIndex,turnId:t.scope.turnId},a=contentAttribute(t.request,!1);a!==void 0&&(i.requestAttribute=a),n.state.set(i)},"input.resolved":(t,n)=>{let r=readState(n.state.get());if(r===void 0)return;let i=e.idGenerator.withSpanId(e.idGenerator.deriveSpanId(`approval:${t.idempotencyKey}`),()=>e.tracer.startSpan(AGENT_SPAN_NAMES.approval,{attributes:{"agent.action.call_id":r.actionCallId,"agent.action.name":r.actionName,"agent.approval.kind":`tool-approval`,"agent.approval.outcome":t.outcome,"agent.approval.request_id":r.requestId,"agent.framework.name":`eve`,"agent.framework.version":e.frameworkVersion,"agent.step.attempt":r.attemptIndex,"agent.step.index":r.stepIndex,"agent.turn.id":r.turnId,...agentSpanNamingAttributes(`agent.approval`),...agentTraceIdentityAttributes({rootSessionId:r.rootSessionId,sessionId:r.sessionId})},startTime:r.startTimeMs},withChannelAudience(trace.setSpan(ROOT_CONTEXT,trace.wrapSpanContext({...r.parent,isRemote:!1})),r.channelAudience)));if(r.requestAttribute!==void 0&&i.setAttribute(`agent.approval.request`,r.requestAttribute),t.response!==void 0){let e=contentAttribute(t.response,!1);e!==void 0&&i.setAttribute(`agent.approval.response`,e)}t.outcome===`failed`&&recordAgentSpanError(i,t.error),i.end()}}}function readState(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t=e,n=t.parent;if(typeof n!=`object`||!n||Array.isArray(n))return;let r=n;if(typeof t.actionCallId!=`string`||typeof t.actionName!=`string`||typeof t.attemptIndex!=`number`||typeof r.spanId!=`string`||typeof r.traceFlags!=`number`||typeof r.traceId!=`string`||typeof t.requestId!=`string`||typeof t.rootSessionId!=`string`||typeof t.sessionId!=`string`||typeof t.startTimeMs!=`number`||typeof t.stepIndex!=`number`||typeof t.turnId!=`string`)return;let i=t.requestAttribute;if(i===void 0||typeof i==`string`)return{actionCallId:t.actionCallId,actionName:t.actionName,attemptIndex:t.attemptIndex,channelAudience:normalizeChannelAudience(t.channelAudience),parent:{isRemote:!1,spanId:r.spanId,traceFlags:r.traceFlags,traceId:r.traceId},requestAttribute:i,requestId:t.requestId,rootSessionId:t.rootSessionId,sessionId:t.sessionId,startTimeMs:t.startTimeMs,stepIndex:t.stepIndex,turnId:t.turnId}}export{createAgentApprovalInstrumentation};
1
+ import{normalizeChannelAudience}from"#shared/channel-audience.js";import{AGENT_SPAN_NAMES}from"#tracing/agent-span-contract.js";import{ROOT_CONTEXT,trace}from"#compiled/@opentelemetry/api/index.js";import{agentSpanNamingAttributes}from"#tracing/agent-span-naming.js";import{agentTraceIdentityAttributes}from"#tracing/agent-otel-attributes.js";import{contentAttribute}from"#tracing/agent-otel-content.js";import{withChannelAudience}from"#tracing/channel-audience-context.js";import{recordAgentSpanError}from"#tracing/agent-span-error.js";function createAgentApprovalInstrumentation(e){return{"input.requested":async(t,n)=>{if(t.kind!==`tool-approval`||readState(n.state.get())!==void 0)return;let r=await e.actionContextFor(t.scope.sessionId,t.scope.turnId,t.action.callId);if(r===void 0)return;let i={actionCallId:t.action.callId,actionName:t.action.name,attemptIndex:t.scope.attemptIndex,channelAudience:normalizeChannelAudience(t.scope.channelAudience),parent:{spanId:r.spanContext.spanId,traceFlags:r.spanContext.traceFlags,traceId:r.spanContext.traceId},requestId:t.requestId,rootSessionId:t.scope.rootSessionId??t.scope.sessionId,sessionId:t.scope.sessionId,startTimeMs:Date.now(),stepIndex:t.scope.stepIndex,turnId:t.scope.turnId},a=contentAttribute(t.request);a!==void 0&&(i.requestAttribute=a),n.state.set(i)},"input.resolved":(t,n)=>{let r=readState(n.state.get());if(r===void 0)return;let i=e.idGenerator.withSpanId(e.idGenerator.deriveSpanId(`approval:${t.idempotencyKey}`),()=>e.tracer.startSpan(AGENT_SPAN_NAMES.approval,{attributes:{"agent.action.call_id":r.actionCallId,"agent.action.name":r.actionName,"agent.approval.kind":`tool-approval`,"agent.approval.outcome":t.outcome,"agent.approval.request_id":r.requestId,"agent.framework.name":`eve`,"agent.framework.version":e.frameworkVersion,"agent.step.attempt":r.attemptIndex,"agent.step.index":r.stepIndex,"agent.turn.id":r.turnId,...agentSpanNamingAttributes(`agent.approval`),...agentTraceIdentityAttributes({rootSessionId:r.rootSessionId,sessionId:r.sessionId})},startTime:r.startTimeMs},withChannelAudience(trace.setSpan(ROOT_CONTEXT,trace.wrapSpanContext({...r.parent,isRemote:!1})),r.channelAudience)));if(r.requestAttribute!==void 0&&i.setAttribute(`agent.approval.request`,r.requestAttribute),t.response!==void 0){let e=contentAttribute(t.response);e!==void 0&&i.setAttribute(`agent.approval.response`,e)}t.outcome===`failed`&&recordAgentSpanError(i,t.error),i.end()}}}function readState(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t=e,n=t.parent;if(typeof n!=`object`||!n||Array.isArray(n))return;let r=n;if(typeof t.actionCallId!=`string`||typeof t.actionName!=`string`||typeof t.attemptIndex!=`number`||typeof r.spanId!=`string`||typeof r.traceFlags!=`number`||typeof r.traceId!=`string`||typeof t.requestId!=`string`||typeof t.rootSessionId!=`string`||typeof t.sessionId!=`string`||typeof t.startTimeMs!=`number`||typeof t.stepIndex!=`number`||typeof t.turnId!=`string`)return;let i=t.requestAttribute;if(i===void 0||typeof i==`string`)return{actionCallId:t.actionCallId,actionName:t.actionName,attemptIndex:t.attemptIndex,channelAudience:normalizeChannelAudience(t.channelAudience),parent:{isRemote:!1,spanId:r.spanId,traceFlags:r.traceFlags,traceId:r.traceId},requestAttribute:i,requestId:t.requestId,rootSessionId:t.rootSessionId,sessionId:t.sessionId,startTimeMs:t.startTimeMs,stepIndex:t.stepIndex,turnId:t.turnId}}export{createAgentApprovalInstrumentation};
@@ -1 +1 @@
1
- import{contextStorage}from"#context/container.js";import{ActiveChannelDeliveriesKey}from"#context/keys.js";import{isSampledTrace}from"#tracing/sampled-trace.js";import{sessionIdempotencyKey}from"#instrumentation/lifecycle.js";import{contentAttribute}from"#tracing/agent-otel-content.js";function createAgentChannelDeliveryInstrumentation(e){let onStarted=async(t,n)=>{let r=await e.ensureSessionContext({agentName:t.agentName,channelAudience:t.delivery.channelAudience,channelKind:t.delivery.channelKind,idempotencyKey:sessionIdempotencyKey(t.sessionId),parentTraceContext:t.parentTraceContext,rootSessionId:t.rootSessionId,sessionId:t.sessionId,traceSeed:t.traceSeed,type:`session.started`}),i=t.turnId===void 0||t.sequence===void 0?void 0:await e.stateStore.getTurn(t.sessionId,t.turnId);if(!isSampledTrace(i?.context??r.context))return;let a=e.recordInputs?contentAttribute(t.input,!1):void 0,o={};a!==void 0&&(o.inputAttribute=a),t.delivery.requestTraceContext!==void 0&&(o.requestTraceContext={spanId:t.delivery.requestTraceContext.spanId,traceFlags:t.delivery.requestTraceContext.traceFlags,traceId:t.delivery.requestTraceContext.traceId}),n.state.set(o)},onTerminal=async(t,n)=>{let r=readState(n.state.get());if(r===void 0||t.turnId===void 0)return;let i=await e.stateStore.getTurn(t.sessionId,t.turnId);i!==void 0&&isSampledTrace(i.context)&&isOnlyActiveDelivery(t.sessionId,t.turnId,t.delivery.deliveryId)&&await e.stateStore.updateTurn(t.sessionId,t.turnId,e=>({...e,channelDelivery:{channelKind:t.delivery.channelKind,channelName:t.delivery.channelName,deliveryId:t.delivery.deliveryId,...r.inputAttribute===void 0?void 0:{inputAttribute:r.inputAttribute},...t.delivery.requestId===void 0?void 0:{requestId:t.delivery.requestId},...r.requestTraceContext===void 0?void 0:{requestTraceContext:r.requestTraceContext}}}))};return{"channel.delivery.cancelled":onTerminal,"channel.delivery.completed":onTerminal,"channel.delivery.failed":onTerminal,"channel.delivery.started":onStarted}}function isOnlyActiveDelivery(e,t,n){let r=contextStorage.getStore()?.get(ActiveChannelDeliveriesKey),i=r?.[0];return r?.length===1&&i?.sessionId===e&&i.turnId===t&&i.delivery.deliveryId===n}function readState(e){if(!isRecord(e))return;let t=isSpanContext(e.requestTraceContext)?e.requestTraceContext:void 0;return{inputAttribute:typeof e.inputAttribute==`string`?e.inputAttribute:void 0,requestTraceContext:t}}function isSpanContext(e){return isRecord(e)&&typeof e.spanId==`string`&&typeof e.traceFlags==`number`&&typeof e.traceId==`string`}function isRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}export{createAgentChannelDeliveryInstrumentation};
1
+ import{contextStorage}from"#context/container.js";import{ActiveChannelDeliveriesKey}from"#context/keys.js";import{isSampledTrace}from"#tracing/sampled-trace.js";import{sessionIdempotencyKey}from"#instrumentation/lifecycle.js";import{contentAttribute}from"#tracing/agent-otel-content.js";function createAgentChannelDeliveryInstrumentation(e){let onStarted=async(t,n)=>{let r=await e.ensureSessionContext({agentName:t.agentName,channelAudience:t.delivery.channelAudience,channelKind:t.delivery.channelKind,idempotencyKey:sessionIdempotencyKey(t.sessionId),parentTraceContext:t.parentTraceContext,rootSessionId:t.rootSessionId,sessionId:t.sessionId,traceSeed:t.traceSeed,type:`session.started`}),i=t.turnId===void 0||t.sequence===void 0?void 0:await e.stateStore.getTurn(t.sessionId,t.turnId);if(!isSampledTrace(i?.context??r.context))return;let a=e.recordInputs?contentAttribute(t.input):void 0,o={};a!==void 0&&(o.inputAttribute=a),t.delivery.requestTraceContext!==void 0&&(o.requestTraceContext={spanId:t.delivery.requestTraceContext.spanId,traceFlags:t.delivery.requestTraceContext.traceFlags,traceId:t.delivery.requestTraceContext.traceId}),n.state.set(o)},onTerminal=async(t,n)=>{let r=readState(n.state.get());if(r===void 0||t.turnId===void 0)return;let i=await e.stateStore.getTurn(t.sessionId,t.turnId);i!==void 0&&isSampledTrace(i.context)&&isOnlyActiveDelivery(t.sessionId,t.turnId,t.delivery.deliveryId)&&await e.stateStore.updateTurn(t.sessionId,t.turnId,e=>({...e,channelDelivery:{channelKind:t.delivery.channelKind,channelName:t.delivery.channelName,deliveryId:t.delivery.deliveryId,...r.inputAttribute===void 0?void 0:{inputAttribute:r.inputAttribute},...t.delivery.requestId===void 0?void 0:{requestId:t.delivery.requestId},...r.requestTraceContext===void 0?void 0:{requestTraceContext:r.requestTraceContext}}}))};return{"channel.delivery.cancelled":onTerminal,"channel.delivery.completed":onTerminal,"channel.delivery.failed":onTerminal,"channel.delivery.started":onStarted}}function isOnlyActiveDelivery(e,t,n){let r=contextStorage.getStore()?.get(ActiveChannelDeliveriesKey),i=r?.[0];return r?.length===1&&i?.sessionId===e&&i.turnId===t&&i.delivery.deliveryId===n}function readState(e){if(!isRecord(e))return;let t=isSpanContext(e.requestTraceContext)?e.requestTraceContext:void 0;return{inputAttribute:typeof e.inputAttribute==`string`?e.inputAttribute:void 0,requestTraceContext:t}}function isSpanContext(e){return isRecord(e)&&typeof e.spanId==`string`&&typeof e.traceFlags==`number`&&typeof e.traceId==`string`}function isRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}export{createAgentChannelDeliveryInstrumentation};
@@ -0,0 +1,13 @@
1
+ import { type Tracer } from "#compiled/@opentelemetry/api/index.js";
2
+ import type { InstrumentationProviderDefinition } from "#instrumentation/lifecycle.js";
3
+ import type { InstrumentationMemoryExecutionOperation } from "#instrumentation/memory.js";
4
+ import type { AgentTraceStateStore } from "#tracing/agent-trace-state.js";
5
+ export interface AgentMemoryInstrumentation {
6
+ readonly events: Pick<NonNullable<InstrumentationProviderDefinition["events"]>, "memory.operation.completed" | "memory.operation.failed" | "memory.operation.started">;
7
+ runInContext<T>(operation: InstrumentationMemoryExecutionOperation, execute: () => PromiseLike<T>): Promise<T>;
8
+ }
9
+ export declare function createAgentMemoryInstrumentation(input: {
10
+ readonly recordOutputs: boolean;
11
+ readonly stateStore: AgentTraceStateStore;
12
+ readonly tracer: Tracer;
13
+ }): AgentMemoryInstrumentation;
@@ -0,0 +1 @@
1
+ import{normalizeChannelAudience}from"#shared/channel-audience.js";import{contextStorage}from"#context/container.js";import{SessionTraceSeedKey}from"#context/keys.js";import{applyLiveDeliveryAudienceCeiling,resolveForwardedTraceSeed}from"#shared/forwarded-trace-policy.js";import{isSampledTrace}from"#tracing/sampled-trace.js";import{ROOT_CONTEXT,SpanKind,context,trace}from"#compiled/@opentelemetry/api/index.js";import{isAgentTraceContext,markAgentTraceContext}from"#tracing/agent-trace-context.js";import{withErrorContent}from"#tracing/error-content-context.js";import{agentSpanNamingAttributes}from"#tracing/agent-span-naming.js";import{agentTraceIdentityAttributes}from"#tracing/agent-otel-attributes.js";import{genAiMemoryRecordsAttribute}from"#tracing/agent-otel-content.js";import{withChannelAudience}from"#tracing/channel-audience-context.js";import{recordAgentSpanError}from"#tracing/agent-span-error.js";import{suppressTracing}from"#tracing/suppress-tracing.js";function createAgentMemoryInstrumentation(e){let t=new Map,parentContext=async t=>{let n=context.active();if(isAgentTraceContext(n))return n;let r=await e.stateStore.getSession(t.sessionId);if(t.turnId!==void 0){let n=await e.stateStore.getTurn(t.sessionId,t.turnId);if(n!==void 0)return withChannelAudience(contextFromSpanContext(n.context),r?.channelAudience)}return r===void 0?void 0:withChannelAudience(contextFromSpanContext(r.context),r.channelAudience)},onStarted=async n=>{if(t.has(n.idempotencyKey))return;let r=await parentContext(n),i=r===void 0?void 0:trace.getSpan(r)?.spanContext();if(r===void 0||i===void 0||!isSampledTrace(i))return;let a=e.tracer.startSpan(n.operationName,{attributes:memorySpanAttributes(n),kind:SpanKind.CLIENT},r);t.set(n.idempotencyKey,{context:trace.setSpan(r,a),span:a})},onTerminal=e=>{let n=t.get(e.idempotencyKey);n!==void 0&&(t.delete(e.idempotencyKey),updateMemorySpan(n.span,e),n.span.end())};return{events:{"memory.operation.completed":onTerminal,"memory.operation.failed":onTerminal,"memory.operation.started":onStarted},async runInContext(n,r){let i=await e.stateStore.getSession(n.sessionId),a=t.get(n.idempotencyKey)?.context;if(a===void 0&&n.turnId!==void 0){let t=await e.stateStore.getTurn(n.sessionId,n.turnId);t!==void 0&&(a=withChannelAudience(contextFromSpanContext(t.context),i?.channelAudience),isSampledTrace(t.context)||(a=suppressTracing(a)))}a===void 0&&i!==void 0&&(a=withChannelAudience(contextFromSpanContext(i.context),i.channelAudience),isSampledTrace(i.context)||(a=suppressTracing(a)));let o=resolveForwardedTraceSeed(contextStorage.getStore()?.get(SessionTraceSeedKey)),s=o?.decision??i?.decision,c=s===void 0?void 0:applyLiveDeliveryAudienceCeiling(s,normalizeChannelAudience(i?.channelAudience),o?.forwardedTracePolicy);return a===void 0?await r():await context.with(markAgentTraceContext(withErrorContent(a,e.recordOutputs&&c?.action===`record`&&c.recordOutputs)),r)}}}function memorySpanAttributes(e){let t={"agent.memory.phase":e.phase,"agent.memory.slot":e.slot,"gen_ai.memory.store.id":e.storeId,"gen_ai.operation.name":e.operationName,...agentSpanNamingAttributes(e.operationName,e.operationName),...agentTraceIdentityAttributes({rootSessionId:e.rootSessionId,sessionId:e.sessionId})};return e.turnId!==void 0&&(t[`agent.turn.id`]=e.turnId),t}function updateMemorySpan(e,t){if(t.type===`memory.operation.failed`)recordAgentSpanError(e,t.error);else{t.recordCount!==void 0&&e.setAttribute(`gen_ai.memory.record.count`,t.recordCount);let n=genAiMemoryRecordsAttribute(t.outputRecords??[]);n!==void 0&&t.outputRecords!==void 0&&e.setAttribute(`gen_ai.memory.records`,n)}}function contextFromSpanContext(e){return trace.setSpan(ROOT_CONTEXT,trace.wrapSpanContext(e))}export{createAgentMemoryInstrumentation};
@@ -7,24 +7,16 @@
7
7
  */
8
8
  /** Content attributes are capped so a giant payload cannot bloat a span segment. */
9
9
  export declare const CONTENT_ATTRIBUTE_LIMIT: number;
10
- /**
11
- * Serializes one payload value. `strip` removes {@link CONTENT_NOISE_KEYS};
12
- * pass `false` for tool data, where those keys may be legitimate domain
13
- * fields the user authored or the tool returned.
14
- */
15
- export declare function contentAttribute(value: unknown, strip?: boolean): string | undefined;
16
- /**
17
- * Serializes the prompt messages, keeping the result parseable: oldest
18
- * messages drop first behind an omission marker, and a single message over
19
- * the cap is truncated at the text level rather than the JSON level.
20
- */
21
- export declare function messagesContentAttribute(messages: unknown): string | undefined;
10
+ /** Serializes one payload value as capped JSON. */
11
+ export declare function contentAttribute(value: unknown): string | undefined;
22
12
  /** Serializes model messages using the OpenTelemetry GenAI message schema. */
23
13
  export declare function genAiInputMessagesAttribute(messages: unknown): string | undefined;
24
14
  /** Serializes the system prompt using the OpenTelemetry GenAI instruction schema. */
25
15
  export declare function genAiSystemInstructionsAttribute(instructions: unknown): string | undefined;
26
16
  /** Serializes one model response using the OpenTelemetry GenAI message schema. */
27
17
  export declare function genAiOutputMessagesAttribute(content: readonly unknown[], finishReason: string): string | undefined;
18
+ /** Serializes memory records using the OpenTelemetry GenAI memory-records schema. */
19
+ export declare function genAiMemoryRecordsAttribute(records: readonly unknown[]): string | undefined;
28
20
  /**
29
21
  * Serializes provider-executed tool results, keeping the attribute valid
30
22
  * JSON under the cap: when the full payload is too big, each entry's input
@@ -1,4 +1,4 @@
1
- import{isUserMessageKind}from"#harness/messages.js";const CONTENT_ATTRIBUTE_LIMIT=32768,CONTENT_NOISE_KEYS=new Set([`providerOptions`,`providerMetadata`]),TRUNCATED_MESSAGES_KEY=`eve.truncated`;function contentAttribute(e,t=!0){if(e===void 0)return;let n=t?stripContentNoise(e,0):e,r;try{r=JSON.stringify(n)}catch{return}if(r!==void 0)return textContentAttribute(r)}function messagesContentAttribute(e){if(!Array.isArray(e))return contentAttribute(e);let t=stripContentNoise(e,0),n=stringifyContent(t);if(n!==void 0&&n.length<=32768)return n;for(let e=1;e<t.length;e+=1){let n=stringifyContent([{[TRUNCATED_MESSAGES_KEY]:{omittedMessages:e}},...t.slice(e)]);if(n!==void 0&&n.length<=32768)return n}return truncateSingleMessage(t)}function genAiInputMessagesAttribute(e){if(!Array.isArray(e))return;let t=e.flatMap(e=>{if(!isRecord(e)||e.role===`system`||typeof e.role!=`string`)return[];let t=semanticParts(e.content);if(t.length===0)return[];let n=e.role===`user`&&isUserMessageKind(e.kind)?e.kind:void 0;return[n===void 0?{parts:t,role:e.role}:{kind:n,parts:t,role:e.role}]});for(let e=0;e<t.length;e+=1){let n=semanticJsonAttribute(t.slice(e));if(n!==void 0)return n}return semanticJsonAttribute([])}function genAiSystemInstructionsAttribute(e){let t=systemPromptAttribute(e);return t===void 0?void 0:semanticJsonAttribute([{content:t,type:`text`}])}function genAiOutputMessagesAttribute(e,t){let n=semanticParts(e);return semanticJsonAttribute([{finish_reason:t===`tool-calls`?`tool_call`:t,parts:n,role:`assistant`}])}function toolResultsContentAttribute(e){if(e.length===0)return;let t=stringifyContent(e);if(t!==void 0&&t.length<=32768)return t;for(let t=CONTENT_ATTRIBUTE_LIMIT;t>=0;t=t>=256?Math.floor(t/2):-1){let n=stringifyContent(e.map(e=>cappedToolResult(e,t)));if(n!==void 0&&n.length<=32768)return n}}function cappedToolResult(e,t){let n={toolName:e.toolName};for(let r of[`input`,`output`,`error`]){if(!(r in e))continue;let i=e[r],a=typeof i==`string`?i:stringifyContent(i)??``;n[r]=a.length<=t?a:`${a.slice(0,t)}… [truncated]`}return n}function systemPromptAttribute(e){if(typeof e==`string`)return textContentAttribute(e);if(!isRecord(e)&&!Array.isArray(e))return;let t=Array.isArray(e)?e:[e],n=[];for(let e of t)if(isRecord(e)){if(typeof e.content==`string`)n.push(e.content);else if(Array.isArray(e.content))for(let t of e.content)isRecord(t)&&t.type===`text`&&typeof t.text==`string`&&n.push(t.text)}let r=n.join(`
1
+ import{isUserMessageKind}from"#harness/messages.js";const CONTENT_ATTRIBUTE_LIMIT=32768;function contentAttribute(e){if(e===void 0)return;let t;try{t=JSON.stringify(e)}catch{return}if(t!==void 0)return textContentAttribute(t)}function genAiInputMessagesAttribute(e){if(!Array.isArray(e))return;let t=e.flatMap(e=>{if(!isRecord(e)||e.role===`system`||typeof e.role!=`string`)return[];let t=semanticParts(e.content);if(t.length===0)return[];let n=e.role===`user`&&isUserMessageKind(e.kind)?e.kind:void 0;return[n===void 0?{parts:t,role:e.role}:{kind:n,parts:t,role:e.role}]});for(let e=0;e<t.length;e+=1){let n=semanticJsonAttribute(t.slice(e));if(n!==void 0)return n}return truncateSingleSemanticMessage(t)??semanticJsonAttribute([])}function genAiSystemInstructionsAttribute(e){let t=systemPromptAttribute(e);return t===void 0?void 0:semanticJsonAttribute([{content:t,type:`text`}])}function genAiOutputMessagesAttribute(e,t){let n=semanticParts(e);return semanticJsonAttribute([{finish_reason:t===`tool-calls`?`tool_call`:t,parts:n,role:`assistant`}])}function genAiMemoryRecordsAttribute(e){return semanticJsonAttribute(e)}function toolResultsContentAttribute(e){if(e.length===0)return;let t=stringifyContent(e);if(t!==void 0&&t.length<=32768)return t;for(let t=CONTENT_ATTRIBUTE_LIMIT;t>=0;t=t>=256?Math.floor(t/2):-1){let n=stringifyContent(e.map(e=>cappedToolResult(e,t)));if(n!==void 0&&n.length<=32768)return n}}function cappedToolResult(e,t){let n={toolName:e.toolName};for(let r of[`input`,`output`,`error`]){if(!(r in e))continue;let i=e[r],a=typeof i==`string`?i:stringifyContent(i)??``;n[r]=a.length<=t?a:`${a.slice(0,t)}… [truncated]`}return n}function systemPromptAttribute(e){if(typeof e==`string`)return textContentAttribute(e);if(!isRecord(e)&&!Array.isArray(e))return;let t=Array.isArray(e)?e:[e],n=[];for(let e of t)if(isRecord(e)){if(typeof e.content==`string`)n.push(e.content);else if(Array.isArray(e.content))for(let t of e.content)isRecord(t)&&t.type===`text`&&typeof t.text==`string`&&n.push(t.text)}let r=n.join(`
2
2
 
3
- `).trim();return r.length===0?void 0:textContentAttribute(r)}function textContentAttribute(e){if(e.length!==0)return e.length<=32768?e:`${e.slice(0,CONTENT_ATTRIBUTE_LIMIT)}… [truncated]`}function stripContentNoise(e,t){if(t>32||typeof e!=`object`||!e)return e;if(Array.isArray(e))return e.map(e=>stripContentNoise(e,t+1));let n={};for(let[r,i]of Object.entries(e))CONTENT_NOISE_KEYS.has(r)||(n[r]=stripContentNoise(i,t+1));return n}function truncateSingleMessage(e){if(e.length===0)return;let t=e[e.length-1];if(!isRecord(t))return;let n={[TRUNCATED_MESSAGES_KEY]:{omittedMessages:e.length-1}},r=typeof t.role==`string`?t.role:`user`,i=``;if(typeof t.content==`string`)i=t.content;else if(Array.isArray(t.content))for(let e of t.content)isRecord(e)&&e.type===`text`&&typeof e.text==`string`&&(i+=(i?`
4
- `:``)+e.text);for(let e=Math.min(i.length,CONTENT_ATTRIBUTE_LIMIT);e>0;e-=256){let t=stringifyContent([n,{role:r,content:e>=i.length?i:`${i.slice(0,e)}… [truncated]`}]);if(t!==void 0&&t.length<=32768)return t}return stringifyContent([n,{role:r,content:``}])}function stringifyContent(e){try{return JSON.stringify(e)}catch{return}}function semanticJsonAttribute(e){let t=stringifyContent(e);return t!==void 0&&t.length<=32768?t:void 0}function semanticParts(e){if(typeof e==`string`)return[{content:e,type:`text`}];if(!Array.isArray(e))return[];let t=[];for(let n of e){let e=semanticPart(n);e!==void 0&&t.push(e)}return t}function semanticPart(e){if(isRecord(e)&&typeof e.type==`string`)switch(e.type){case`text`:case`reasoning`:{let t=typeof e.text==`string`?e.text:e.content;return typeof t==`string`?{content:t,type:e.type}:void 0}case`tool-call`:return{arguments:e.input,id:stringValue(e.toolCallId)??stringValue(e.callId)??null,name:e.toolName,type:`tool_call`};case`tool-result`:return{id:stringValue(e.toolCallId)??stringValue(e.callId)??null,response:toolResponse(e.output),type:`tool_call_response`};case`tool-error`:return{id:stringValue(e.toolCallId)??stringValue(e.callId)??null,response:e.error instanceof Error?e.error.message:e.error,type:`tool_call_response`};default:return{type:e.type}}}function toolResponse(e){return isRecord(e)?(e.type===`text`||e.type===`error-text`||e.type===`json`||e.type===`error-json`)&&`value`in e?e.value:e.type===`execution-denied`?{denied:!0,reason:e.reason}:e:e}function stringValue(e){return typeof e==`string`?e:void 0}function isRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}export{CONTENT_ATTRIBUTE_LIMIT,contentAttribute,genAiInputMessagesAttribute,genAiOutputMessagesAttribute,genAiSystemInstructionsAttribute,messagesContentAttribute,systemPromptAttribute,textContentAttribute,toolResultsContentAttribute};
3
+ `).trim();return r.length===0?void 0:textContentAttribute(r)}function textContentAttribute(e){if(e.length!==0)return e.length<=32768?e:`${e.slice(0,CONTENT_ATTRIBUTE_LIMIT)}… [truncated]`}function stringifyContent(e){try{return JSON.stringify(e)}catch{return}}function semanticJsonAttribute(e){let t=stringifyContent(e);return t!==void 0&&t.length<=32768?t:void 0}function truncateSingleSemanticMessage(e){let t=e.at(-1);if(t===void 0||typeof t.role!=`string`)return;let n=semanticMessageText(t.parts),r=typeof t.kind==`string`?{kind:t.kind,role:t.role}:{role:t.role};for(let e=Math.min(n.length,CONTENT_ATTRIBUTE_LIMIT);e>0;e-=256){let t=semanticJsonAttribute([{...r,parts:[{content:`${n.slice(0,e)}… [truncated]`,type:`text`}]}]);if(t!==void 0)return t}return semanticJsonAttribute([{...r,parts:[{content:`… [truncated]`,type:`text`}]}])}function semanticMessageText(e){if(!Array.isArray(e))return``;let t=``;for(let n of e){if(!isRecord(n)||n.type!==`text`||typeof n.content!=`string`)continue;let e=t.length===0?``:`
4
+ `,r=32769-t.length-e.length;if(r<=0)break;t+=e+n.content.slice(0,r)}return t}function semanticParts(e){if(typeof e==`string`)return[{content:e,type:`text`}];if(!Array.isArray(e))return[];let t=[];for(let n of e){let e=semanticPart(n);e!==void 0&&t.push(e)}return t}function semanticPart(e){if(isRecord(e)&&typeof e.type==`string`)switch(e.type){case`text`:case`reasoning`:{let t=typeof e.text==`string`?e.text:e.content;return typeof t==`string`?{content:t,type:e.type}:void 0}case`tool-call`:return{arguments:e.input,id:stringValue(e.toolCallId)??stringValue(e.callId)??null,name:e.toolName,type:`tool_call`};case`tool-result`:return{id:stringValue(e.toolCallId)??stringValue(e.callId)??null,response:toolResponse(e.output),type:`tool_call_response`};case`tool-error`:return{id:stringValue(e.toolCallId)??stringValue(e.callId)??null,response:e.error instanceof Error?e.error.message:e.error,type:`tool_call_response`};default:return{type:e.type}}}function toolResponse(e){return isRecord(e)?(e.type===`text`||e.type===`error-text`||e.type===`json`||e.type===`error-json`)&&`value`in e?e.value:e.type===`execution-denied`?{denied:!0,reason:e.reason}:e:e}function stringValue(e){return typeof e==`string`?e:void 0}function isRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}export{CONTENT_ATTRIBUTE_LIMIT,contentAttribute,genAiInputMessagesAttribute,genAiMemoryRecordsAttribute,genAiOutputMessagesAttribute,genAiSystemInstructionsAttribute,systemPromptAttribute,textContentAttribute,toolResultsContentAttribute};
@@ -1,2 +1,2 @@
1
- import{normalizeChannelAudience}from"#shared/channel-audience.js";import{contextStorage}from"#context/container.js";import{SessionTraceSeedKey}from"#context/keys.js";import{AGENT_SPAN_NAMES,agentInvocationSpanName}from"#tracing/agent-span-contract.js";import{applyLiveDeliveryAudienceCeiling,resolveForwardedTraceSeed}from"#shared/forwarded-trace-policy.js";import{isSampledTrace,resolveTracePolicyDecision}from"#tracing/sampled-trace.js";import{ROOT_CONTEXT,SpanKind,context,trace}from"#compiled/@opentelemetry/api/index.js";import{markAgentTraceContext}from"#tracing/agent-trace-context.js";import{attemptIdempotencyKey}from"#instrumentation/lifecycle.js";import{withoutInstrumentationContent}from"#instrumentation/content.js";import{withErrorContent}from"#tracing/error-content-context.js";import{readInstrumentationDecision}from"#shared/instrumentation-decision.js";import{agentSpanNamingAttributes}from"#tracing/agent-span-naming.js";import{agentTraceIdentityAttributes}from"#tracing/agent-otel-attributes.js";import{contentAttribute,genAiInputMessagesAttribute,genAiOutputMessagesAttribute,genAiSystemInstructionsAttribute,messagesContentAttribute,systemPromptAttribute,textContentAttribute,toolResultsContentAttribute}from"#tracing/agent-otel-content.js";import{readGatewayCost,setAgentInvocationUsage,setAgentUsage,setGenAiUsage}from"#tracing/agent-otel-usage.js";import{withChannelAudience}from"#tracing/channel-audience-context.js";import{recordAgentSpanError}from"#tracing/agent-span-error.js";import{instrumentationEventForTraceDecision}from"#instrumentation/content-policy.js";import{createAgentActionInstrumentation}from"#tracing/agent-action-instrumentation.js";import{createAgentApprovalInstrumentation}from"#tracing/agent-approval-instrumentation.js";import{createAgentChannelDeliveryInstrumentation}from"#tracing/agent-channel-delivery-instrumentation.js";import{createAgentToolInstrumentation}from"#tracing/agent-tool-instrumentation.js";import*as runtimeAttributes from"#tracing/agent-otel-runtime-context.js";import{createAgentOtelSessionContext}from"#tracing/agent-otel-session-context.js";import{suppressTracing}from"#tracing/suppress-tracing.js";function createAgentOtelInstrumentation(e){let t=e.recordInputs??!1,n=e.recordOutputs??!1,r=new WeakMap,i=new Map,a=new WeakMap,o=new WeakMap,s=createAgentActionInstrumentation({frameworkVersion:e.frameworkVersion,idGenerator:e.idGenerator,recordInputs:t,recordOutputs:n,resolveTraceContext:async t=>(await e.stateStore.getTurn(t.scope.sessionId,t.scope.turnId))?.context,stateStore:e.stateStore,tracer:e.tracer}),c=createAgentApprovalInstrumentation({actionContextFor:s.contextFor,frameworkVersion:e.frameworkVersion,idGenerator:e.idGenerator,tracer:e.tracer}),l=createAgentToolInstrumentation({actionContextFor:s.contextFor,idGenerator:e.idGenerator,recordInputs:t,recordOutputs:n,resolveFallback:e=>{let t=i.get(e.scope.attemptId)??e.scope,n=a.get(t);return n===void 0?void 0:{context:n.context,spanContext:n.span.spanContext()}},tracer:e.tracer}),{ensureSessionContext:u,prepareSessionTrace:d,prepareTurnTrace:f}=createAgentOtelSessionContext(e),projectEvent=async r=>{let i=await e.stateStore.getSession(sessionIdForEvent(r)),a=audienceForEvent(r,i?.channelAudience),o=`traceSeed`in r?r.traceSeed:void 0,s=contextStorage.getStore()?.get(SessionTraceSeedKey),c=resolveForwardedTraceSeed(s),l=resolveForwardedTraceSeed(o,c?.forwardedTracePolicy),u=l?.decision??c?.decision??readInstrumentationDecision(i?.decision)??(o===void 0?s===void 0?i===void 0?void 0:resolveTracePolicyDecision(isSampledTrace(i.context),a):resolveTracePolicyDecision(isSampledTrace(s),a):resolveTracePolicyDecision(isSampledTrace(o),a));if(u===void 0)return withoutInstrumentationContent(r);let d=l===void 0||!(`traceSeed`in r)||r.traceSeed===void 0?r:{...r,traceSeed:{...r.traceSeed,decision:l.decision,traceFlags:l.traceFlags}};return instrumentationEventForTraceDecision(d,applyLiveDeliveryAudienceCeiling(u.action===`drop`?u:{action:`record`,recordInputs:t&&u.recordInputs,recordOutputs:n&&u.recordOutputs},a,l?.forwardedTracePolicy??c?.forwardedTracePolicy),a,{applyAudienceCeiling:!1})},onSessionStarted=async e=>{await d(e)},onTurnStarted=async e=>{await f(e)},onStepStarted=async t=>{let n=await e.stateStore.getTurn(t.scope.sessionId,t.scope.turnId);if(n===void 0||!isSampledTrace(n.context))return;let r=withChannelAudience(contextFromSpanContext(n.context),t.scope.channelAudience),o=trace.getSpan(context.active())?.spanContext(),s=e.idGenerator.withSpanId(e.idGenerator.deriveSpanId(attemptIdempotencyKey(t.scope)),()=>e.tracer.startSpan(AGENT_SPAN_NAMES.step,{attributes:{"agent.framework.name":`eve`,"agent.framework.version":e.frameworkVersion,"agent.step.attempt":t.scope.attemptIndex,"agent.step.index":t.scope.stepIndex,"agent.turn.id":t.scope.turnId,"agent.name":t.scope.functionId,...agentSpanNamingAttributes(`agent.step`),...agentTraceIdentityAttributes({rootSessionId:t.scope.rootSessionId??t.scope.sessionId,sessionId:t.scope.sessionId}),...runtimeAttributes.runtimeContextAttributes(t.runtimeContext)},links:o===void 0||o.traceId===n.context.traceId?void 0:[{attributes:{"eve.link.type":`workflow.delivery`},context:o}]},r));s.addEvent(`step.started`);let c=trace.setSpan(r,s);a.set(t.scope,{context:c,span:s}),i.set(t.scope.attemptId,t.scope)},onStepTerminal=async e=>{let t=i.get(e.scope.attemptId)??e.scope;r.delete(t),drainOpenSpans({...e,scope:t}),l.drain(e.scope.attemptId,e.type===`step.attempt.failed`?{error:e.error}:void 0),e.type===`step.attempt.failed`&&await s.failForAttempt(t,e.error),i.delete(e.scope.attemptId);let n=a.get(t);n!==void 0&&(n.span.addEvent(e.type===`step.attempt.completed`?`step.completed`:`step.failed`),e.type===`step.attempt.failed`&&recordAgentSpanError(n.span,e.error),n.span.end(),a.delete(t))},onTurnTerminal=async t=>{await e.stateStore.updateTurn(t.sessionId,t.turnId,e=>({...e,terminal:t.type===`turn.failed`?{error:t.error,type:t.type}:{type:t.type}}))},onSessionTransition=async t=>{if(await s.flushForSessionTransition(t),t.type===`session.failed`&&t.turnId!==void 0&&await e.stateStore.updateTurn(t.sessionId,t.turnId,e=>({...e,terminal:e.terminal??{error:t.error,type:`turn.failed`}})),t.turnId!==void 0){let n=await e.stateStore.getTurn(t.sessionId,t.turnId);if(n!==void 0){let r=await e.stateStore.getSession(t.sessionId);if(isSampledTrace(n.context)){let i=r?.agentName??n.subagentName,a=withChannelAudience(ROOT_CONTEXT,r?.channelAudience),startSpan=()=>e.tracer.startSpan(agentInvocationSpanName(i),{attributes:runtimeAttributes.agentActivationAttributes({agentName:i,frameworkVersion:e.frameworkVersion,sessionId:t.sessionId,turnId:t.turnId,turn:n}),kind:SpanKind.INTERNAL,links:agentActivationLinks(n),root:!0,startTime:n.startTimeMs},a),o=e.idGenerator.withSpanId(n.context.spanId,()=>e.idGenerator.withTraceId(n.context.traceId,startSpan));setAgentInvocationUsage(o,n.modelUsage),o.addEvent(`turn.started`,void 0,n.startTimeMs),n.terminal!==void 0&&(o.setAttribute(`agent.turn.outcome`,n.terminal.type===`turn.completed`?`completed`:n.terminal.type===`turn.cancelled`?`cancelled`:`failed`),o.addEvent(n.terminal.type),n.terminal.type===`turn.failed`&&recordAgentSpanError(o,n.terminal.error)),o.end()}await e.stateStore.deleteTurn(t.sessionId,t.turnId)}}(t.type===`session.completed`||t.type===`session.failed`)&&(await s.deleteForSession(t.sessionId),await e.stateStore.deleteSession(t.sessionId))},onModelCallStarted=n=>{let r=a.get(n.scope);if(r===void 0)return;r.span.setAttribute(`agent.model.id`,n.model.modelId),r.span.setAttribute(`agent.model.provider`,n.model.provider);let i=e.tracer.startSpan(modelSpanName(n.model.modelId),{attributes:{"gen_ai.agent.name":n.scope.functionId,"gen_ai.operation.name":`chat`,"gen_ai.provider.name":n.model.provider,"gen_ai.request.model":n.model.modelId,...agentSpanNamingAttributes(modelSpanName(n.model.modelId),`chat`),...agentTraceIdentityAttributes({rootSessionId:n.scope.rootSessionId??n.scope.sessionId,sessionId:n.scope.sessionId}),...runtimeAttributes.runtimeContextAttributes(n.runtimeContext)},kind:SpanKind.CLIENT},r.context);if(t&&n.input!==void 0){let e=messagesContentAttribute(n.input.messages);e!==void 0&&i.setAttribute(`ai.prompt.messages`,e);let t=genAiInputMessagesAttribute(n.input.messages);t!==void 0&&i.setAttribute(`gen_ai.input.messages`,t);let r=systemPromptAttribute(n.input.instructions);r!==void 0&&i.setAttribute(`ai.prompt.system`,r);let a=genAiSystemInstructionsAttribute(n.input.instructions);a!==void 0&&i.setAttribute(`gen_ai.system_instructions`,a)}let s={context:trace.setSpan(r.context,i),span:i};getExecutionContexts(n.scope).set(n.idempotencyKey,s.context),getSpanStates(o,n.scope).set(n.idempotencyKey,s)},onModelCallTerminal=async e=>{r.get(e.scope)?.delete(e.idempotencyKey);let t=takeSpanState(o,e.scope,e.idempotencyKey);if(t!==void 0){if(e.type===`model.call.failed`)recordAgentSpanError(t.span,e.error);else{await recordTurnUsage(e),setGenAiUsage(t.span,e.usage),e.responseId!==void 0&&t.span.setAttribute(`gen_ai.response.id`,e.responseId),t.span.setAttribute(`gen_ai.response.finish_reasons`,[e.finishReason]);let r=a.get(e.scope);if(r!==void 0&&setAgentUsage(r.span,e.usage),n){t.span.setAttribute(`ai.response.finish_reason`,e.finishReason);let n=e.content;if(n===void 0){t.span.end();return}let r=genAiOutputMessagesAttribute(n,e.finishReason);r!==void 0&&t.span.setAttribute(`gen_ai.output.messages`,r);let i=textContentAttribute(n.filter(e=>e.type===`reasoning`).map(e=>e.text).filter(e=>e.trim().length>0).join(`
2
- `));i!==void 0&&t.span.setAttribute(`ai.response.reasoning`,i);let a=textContentAttribute(n.filter(e=>e.type===`text`).map(e=>e.text).join(``));a!==void 0&&t.span.setAttribute(`ai.response.text`,a);let o=n.filter(e=>e.type===`tool-call`).map(e=>({callId:e.callId,input:e.input,toolName:e.toolName}));if(o.length>0){let e=contentAttribute(o,!1);e!==void 0&&t.span.setAttribute(`ai.response.tool_calls`,e)}let s=n.filter(e=>e.type===`tool-result`||e.type===`tool-error`).map(e=>e.type===`tool-result`?{callId:e.callId,input:e.input,output:e.output,toolName:e.toolName}:{callId:e.callId,error:errorText(e.error),input:e.input,toolName:e.toolName});if(s.length>0){let e=toolResultsContentAttribute(s);e!==void 0&&t.span.setAttribute(`ai.response.tool_results`,e)}}}t.span.end()}},recordTurnUsage=async t=>{(t.usage.inputTokens!==void 0||t.usage.outputTokens!==void 0)&&await e.stateStore.updateTurn(t.scope.sessionId,t.scope.turnId,e=>({...e,modelUsage:{inputTokens:t.usage.inputTokens===void 0?e.modelUsage?.inputTokens:(e.modelUsage?.inputTokens??0)+t.usage.inputTokens,outputTokens:t.usage.outputTokens===void 0?e.modelUsage?.outputTokens:(e.modelUsage?.outputTokens??0)+t.usage.outputTokens}}))},p=createAgentChannelDeliveryInstrumentation({ensureSessionContext:u,recordInputs:t,stateStore:e.stateStore}),onStepMetadata=e=>{let t=a.get(e.scope);if(t===void 0)return;let n=readGatewayCost(e.providerMetadata);if(n!==void 0)for(let[e,r]of Object.entries(n))t.span.setAttribute(e,r)};return{hook:{flush:s.flushSettledInvocations,events:{...p,"action.completed":s.events[`action.completed`],"action.failed":s.events[`action.failed`],async"action.started"(e,t){await s.events[`action.started`](e,t),await l.actionStarted(e)},...c,"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,...l.events,"turn.cancelled":onTurnTerminal,"turn.completed":onTurnTerminal,"turn.failed":onTurnTerminal,"turn.started":onTurnStarted},name:`eve.otel`,projectEvent,tracePolicy:()=>({emit:!0,recordInputs:t,recordOutputs:n})},prepareSessionTrace:d,prepareTurnTrace:f,async runInContext(t,a){let o=i.get(t.scope.attemptId)??t.scope,s=r.get(o),c=t.type===`model.call`?s?.get(t.idempotencyKey):l.contextFor(t.scope.attemptId,t.idempotencyKey);if(c===void 0){let n=await e.stateStore.getTurn(t.scope.sessionId,t.scope.turnId);n!==void 0&&(c=withChannelAudience(contextFromSpanContext(n.context),t.scope.channelAudience),isSampledTrace(n.context)||(c=suppressTracing(c)))}let u=await e.stateStore.getSession(t.scope.sessionId),d=resolveForwardedTraceSeed(contextStorage.getStore()?.get(SessionTraceSeedKey)),f=d?.decision??u?.decision,p=f===void 0?void 0:applyLiveDeliveryAudienceCeiling(f,normalizeChannelAudience(t.scope.channelAudience),d?.forwardedTracePolicy);return c===void 0?a():context.with(markAgentTraceContext(withErrorContent(c,n&&p?.action===`record`&&p.recordOutputs)),a)}};function getExecutionContexts(e){let t=r.get(e);return t===void 0&&(t=new Map,r.set(e,t)),t}function drainOpenSpans(e){for(let t of o.get(e.scope)?.values()??[])e.type===`step.attempt.failed`&&recordAgentSpanError(t.span,e.error),t.span.end();o.delete(e.scope)}}function agentActivationLinks(e){let t=[];return e.caller!==void 0&&t.push({context:e.caller,attributes:{"eve.link.type":`agent.dispatch`}}),e.channelDelivery?.requestTraceContext!==void 0&&t.push({context:e.channelDelivery.requestTraceContext,attributes:{"eve.link.type":`channel.request`}}),t.length===0?void 0:t}function sessionIdForEvent(e){return`scope`in e?e.scope.sessionId:e.sessionId}function audienceForEvent(e,t){return`delivery`in e?normalizeChannelAudience(e.delivery.channelAudience):`scope`in e&&e.scope.channelAudience!==void 0?normalizeChannelAudience(e.scope.channelAudience):e.type===`session.started`?normalizeChannelAudience(e.channelAudience):normalizeChannelAudience(t)}function getSpanStates(e,t){let n=e.get(t);return n===void 0&&(n=new Map,e.set(t,n)),n}function takeSpanState(e,t,n){let r=e.get(t),i=r?.get(n);if(r!==void 0)return r.delete(n),r.size===0&&e.delete(t),i}function contextFromSpanContext(e){return trace.setSpan(ROOT_CONTEXT,trace.wrapSpanContext(e))}function modelSpanName(e){return`chat ${e}`}function errorText(e){return e instanceof Error?e.message:e}export{createAgentOtelInstrumentation};
1
+ import{normalizeChannelAudience}from"#shared/channel-audience.js";import{contextStorage}from"#context/container.js";import{SessionTraceSeedKey}from"#context/keys.js";import{AGENT_SPAN_NAMES,agentInvocationSpanName}from"#tracing/agent-span-contract.js";import{applyLiveDeliveryAudienceCeiling,resolveForwardedTraceSeed}from"#shared/forwarded-trace-policy.js";import{isSampledTrace,resolveTracePolicyDecision}from"#tracing/sampled-trace.js";import{ROOT_CONTEXT,SpanKind,context,trace}from"#compiled/@opentelemetry/api/index.js";import{markAgentTraceContext}from"#tracing/agent-trace-context.js";import{attemptIdempotencyKey}from"#instrumentation/lifecycle.js";import{withoutInstrumentationContent}from"#instrumentation/content.js";import{withErrorContent}from"#tracing/error-content-context.js";import{readInstrumentationDecision}from"#shared/instrumentation-decision.js";import{agentSpanNamingAttributes}from"#tracing/agent-span-naming.js";import{agentTraceIdentityAttributes}from"#tracing/agent-otel-attributes.js";import{contentAttribute,genAiInputMessagesAttribute,genAiOutputMessagesAttribute,genAiSystemInstructionsAttribute,systemPromptAttribute,textContentAttribute,toolResultsContentAttribute}from"#tracing/agent-otel-content.js";import{readGatewayCost,setAgentInvocationUsage,setAgentUsage,setGenAiUsage}from"#tracing/agent-otel-usage.js";import{withChannelAudience}from"#tracing/channel-audience-context.js";import{recordAgentSpanError}from"#tracing/agent-span-error.js";import{suppressTracing}from"#tracing/suppress-tracing.js";import{instrumentationEventForTraceDecision}from"#instrumentation/content-policy.js";import{createAgentActionInstrumentation}from"#tracing/agent-action-instrumentation.js";import{createAgentApprovalInstrumentation}from"#tracing/agent-approval-instrumentation.js";import{createAgentChannelDeliveryInstrumentation}from"#tracing/agent-channel-delivery-instrumentation.js";import{createAgentToolInstrumentation}from"#tracing/agent-tool-instrumentation.js";import*as runtimeAttributes from"#tracing/agent-otel-runtime-context.js";import{createAgentMemoryInstrumentation}from"#tracing/agent-memory-instrumentation.js";import{createAgentOtelSessionContext}from"#tracing/agent-otel-session-context.js";function createAgentOtelInstrumentation(e){let t=e.recordInputs??!1,n=e.recordOutputs??!1,r=new WeakMap,i=new Map,a=new WeakMap,o=new WeakMap,s=createAgentActionInstrumentation({frameworkVersion:e.frameworkVersion,idGenerator:e.idGenerator,recordInputs:t,recordOutputs:n,resolveTraceContext:async t=>(await e.stateStore.getTurn(t.scope.sessionId,t.scope.turnId))?.context,stateStore:e.stateStore,tracer:e.tracer}),c=createAgentApprovalInstrumentation({actionContextFor:s.contextFor,frameworkVersion:e.frameworkVersion,idGenerator:e.idGenerator,tracer:e.tracer}),l=createAgentToolInstrumentation({actionContextFor:s.contextFor,idGenerator:e.idGenerator,recordInputs:t,recordOutputs:n,resolveFallback:e=>{let t=i.get(e.scope.attemptId)??e.scope,n=a.get(t);return n===void 0?void 0:{context:n.context,spanContext:n.span.spanContext()}},tracer:e.tracer}),u=createAgentMemoryInstrumentation({recordOutputs:n,stateStore:e.stateStore,tracer:e.tracer}),{ensureSessionContext:d,prepareSessionTrace:f,prepareTurnTrace:p}=createAgentOtelSessionContext(e),projectEvent=async r=>{let i=await e.stateStore.getSession(sessionIdForEvent(r)),a=audienceForEvent(r,i?.channelAudience),o=`traceSeed`in r?r.traceSeed:void 0,s=contextStorage.getStore()?.get(SessionTraceSeedKey),c=resolveForwardedTraceSeed(s),l=resolveForwardedTraceSeed(o,c?.forwardedTracePolicy),u=l?.decision??c?.decision??readInstrumentationDecision(i?.decision)??(o===void 0?s===void 0?i===void 0?void 0:resolveTracePolicyDecision(isSampledTrace(i.context),a):resolveTracePolicyDecision(isSampledTrace(s),a):resolveTracePolicyDecision(isSampledTrace(o),a));if(u===void 0)return withoutInstrumentationContent(r);let d=l===void 0||!(`traceSeed`in r)||r.traceSeed===void 0?r:{...r,traceSeed:{...r.traceSeed,decision:l.decision,traceFlags:l.traceFlags}};return instrumentationEventForTraceDecision(d,applyLiveDeliveryAudienceCeiling(u.action===`drop`?u:{action:`record`,recordInputs:t&&u.recordInputs,recordOutputs:n&&u.recordOutputs},a,l?.forwardedTracePolicy??c?.forwardedTracePolicy),a,{applyAudienceCeiling:!1})},onSessionStarted=async e=>{await f(e)},onTurnStarted=async e=>{await p(e)},onStepStarted=async t=>{let n=await e.stateStore.getTurn(t.scope.sessionId,t.scope.turnId);if(n===void 0||!isSampledTrace(n.context))return;let r=withChannelAudience(contextFromSpanContext(n.context),t.scope.channelAudience),o=trace.getSpan(context.active())?.spanContext(),s=e.idGenerator.withSpanId(e.idGenerator.deriveSpanId(attemptIdempotencyKey(t.scope)),()=>e.tracer.startSpan(AGENT_SPAN_NAMES.step,{attributes:{"agent.framework.name":`eve`,"agent.framework.version":e.frameworkVersion,"agent.step.attempt":t.scope.attemptIndex,"agent.step.index":t.scope.stepIndex,"agent.turn.id":t.scope.turnId,"agent.name":t.scope.functionId,...agentSpanNamingAttributes(`agent.step`),...agentTraceIdentityAttributes({rootSessionId:t.scope.rootSessionId??t.scope.sessionId,sessionId:t.scope.sessionId}),...runtimeAttributes.runtimeContextAttributes(t.runtimeContext)},links:o===void 0||o.traceId===n.context.traceId?void 0:[{attributes:{"eve.link.type":`workflow.delivery`},context:o}]},r));s.addEvent(`step.started`);let c=trace.setSpan(r,s);a.set(t.scope,{context:c,span:s}),i.set(t.scope.attemptId,t.scope)},onStepTerminal=async e=>{let t=i.get(e.scope.attemptId)??e.scope;r.delete(t),drainOpenSpans({...e,scope:t}),l.drain(e.scope.attemptId,e.type===`step.attempt.failed`?{error:e.error}:void 0),e.type===`step.attempt.failed`&&await s.failForAttempt(t,e.error),i.delete(e.scope.attemptId);let n=a.get(t);n!==void 0&&(n.span.addEvent(e.type===`step.attempt.completed`?`step.completed`:`step.failed`),e.type===`step.attempt.failed`&&recordAgentSpanError(n.span,e.error),n.span.end(),a.delete(t))},onTurnTerminal=async t=>{await e.stateStore.updateTurn(t.sessionId,t.turnId,e=>({...e,terminal:t.type===`turn.failed`?{error:t.error,type:t.type}:{type:t.type}}))},onSessionTransition=async t=>{if(await s.flushForSessionTransition(t),t.type===`session.failed`&&t.turnId!==void 0&&await e.stateStore.updateTurn(t.sessionId,t.turnId,e=>({...e,terminal:e.terminal??{error:t.error,type:`turn.failed`}})),t.turnId!==void 0){let n=await e.stateStore.getTurn(t.sessionId,t.turnId);if(n!==void 0){let r=await e.stateStore.getSession(t.sessionId);if(isSampledTrace(n.context)){let i=r?.agentName??n.subagentName,a=withChannelAudience(ROOT_CONTEXT,r?.channelAudience),startSpan=()=>e.tracer.startSpan(agentInvocationSpanName(i),{attributes:runtimeAttributes.agentActivationAttributes({agentName:i,frameworkVersion:e.frameworkVersion,sessionId:t.sessionId,turnId:t.turnId,turn:n}),kind:SpanKind.INTERNAL,links:agentActivationLinks(n),root:!0,startTime:n.startTimeMs},a),o=e.idGenerator.withSpanId(n.context.spanId,()=>e.idGenerator.withTraceId(n.context.traceId,startSpan));setAgentInvocationUsage(o,n.modelUsage),o.addEvent(`turn.started`,void 0,n.startTimeMs),n.terminal!==void 0&&(o.setAttribute(`agent.turn.outcome`,n.terminal.type===`turn.completed`?`completed`:n.terminal.type===`turn.cancelled`?`cancelled`:`failed`),o.addEvent(n.terminal.type),n.terminal.type===`turn.failed`&&recordAgentSpanError(o,n.terminal.error)),o.end()}await e.stateStore.deleteTurn(t.sessionId,t.turnId)}}(t.type===`session.completed`||t.type===`session.failed`)&&(await s.deleteForSession(t.sessionId),await e.stateStore.deleteSession(t.sessionId))},onModelCallStarted=n=>{let r=a.get(n.scope);if(r===void 0)return;r.span.setAttribute(`agent.model.id`,n.model.modelId),r.span.setAttribute(`agent.model.provider`,n.model.provider);let i=e.tracer.startSpan(modelSpanName(n.model.modelId),{attributes:{"gen_ai.agent.name":n.scope.functionId,"gen_ai.operation.name":`chat`,"gen_ai.provider.name":n.model.provider,"gen_ai.request.model":n.model.modelId,...agentSpanNamingAttributes(modelSpanName(n.model.modelId),`chat`),...agentTraceIdentityAttributes({rootSessionId:n.scope.rootSessionId??n.scope.sessionId,sessionId:n.scope.sessionId}),...runtimeAttributes.runtimeContextAttributes(n.runtimeContext)},kind:SpanKind.CLIENT},r.context);if(t&&n.input!==void 0){let e=genAiInputMessagesAttribute(n.input.messages);e!==void 0&&i.setAttribute(`gen_ai.input.messages`,e);let t=systemPromptAttribute(n.input.instructions);t!==void 0&&i.setAttribute(`ai.prompt.system`,t);let r=genAiSystemInstructionsAttribute(n.input.instructions);r!==void 0&&i.setAttribute(`gen_ai.system_instructions`,r)}let s={context:trace.setSpan(r.context,i),span:i};getExecutionContexts(n.scope).set(n.idempotencyKey,s.context),getSpanStates(o,n.scope).set(n.idempotencyKey,s)},onModelCallTerminal=async e=>{r.get(e.scope)?.delete(e.idempotencyKey);let t=takeSpanState(o,e.scope,e.idempotencyKey);if(t!==void 0){if(e.type===`model.call.failed`)recordAgentSpanError(t.span,e.error);else{await recordTurnUsage(e),setGenAiUsage(t.span,e.usage),e.responseId!==void 0&&t.span.setAttribute(`gen_ai.response.id`,e.responseId),t.span.setAttribute(`gen_ai.response.finish_reasons`,[e.finishReason]);let r=a.get(e.scope);if(r!==void 0&&setAgentUsage(r.span,e.usage),n){t.span.setAttribute(`ai.response.finish_reason`,e.finishReason);let n=e.content;if(n===void 0){t.span.end();return}let r=genAiOutputMessagesAttribute(n,e.finishReason);r!==void 0&&t.span.setAttribute(`gen_ai.output.messages`,r);let i=textContentAttribute(n.filter(e=>e.type===`reasoning`).map(e=>e.text).filter(e=>e.trim().length>0).join(`
2
+ `));i!==void 0&&t.span.setAttribute(`ai.response.reasoning`,i);let a=textContentAttribute(n.filter(e=>e.type===`text`).map(e=>e.text).join(``));a!==void 0&&t.span.setAttribute(`ai.response.text`,a);let o=n.filter(e=>e.type===`tool-call`).map(e=>({callId:e.callId,input:e.input,toolName:e.toolName}));if(o.length>0){let e=contentAttribute(o);e!==void 0&&t.span.setAttribute(`ai.response.tool_calls`,e)}let s=n.filter(e=>e.type===`tool-result`||e.type===`tool-error`).map(e=>e.type===`tool-result`?{callId:e.callId,input:e.input,output:e.output,toolName:e.toolName}:{callId:e.callId,error:errorText(e.error),input:e.input,toolName:e.toolName});if(s.length>0){let e=toolResultsContentAttribute(s);e!==void 0&&t.span.setAttribute(`ai.response.tool_results`,e)}}}t.span.end()}},recordTurnUsage=async t=>{(t.usage.inputTokens!==void 0||t.usage.outputTokens!==void 0)&&await e.stateStore.updateTurn(t.scope.sessionId,t.scope.turnId,e=>({...e,modelUsage:{inputTokens:t.usage.inputTokens===void 0?e.modelUsage?.inputTokens:(e.modelUsage?.inputTokens??0)+t.usage.inputTokens,outputTokens:t.usage.outputTokens===void 0?e.modelUsage?.outputTokens:(e.modelUsage?.outputTokens??0)+t.usage.outputTokens}}))},m=createAgentChannelDeliveryInstrumentation({ensureSessionContext:d,recordInputs:t,stateStore:e.stateStore}),onStepMetadata=e=>{let t=a.get(e.scope);if(t===void 0)return;let n=readGatewayCost(e.providerMetadata);if(n!==void 0)for(let[e,r]of Object.entries(n))t.span.setAttribute(e,r)};return{hook:{flush:s.flushSettledInvocations,events:{...m,"action.completed":s.events[`action.completed`],"action.failed":s.events[`action.failed`],async"action.started"(e,t){await s.events[`action.started`](e,t),await l.actionStarted(e)},...c,...u.events,"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,...l.events,"turn.cancelled":onTurnTerminal,"turn.completed":onTurnTerminal,"turn.failed":onTurnTerminal,"turn.started":onTurnStarted},name:`eve.otel`,projectEvent,tracePolicy:()=>({emit:!0,recordInputs:t,recordOutputs:n})},prepareSessionTrace:f,prepareTurnTrace:p,async runInContext(t,a){if(t.type===`memory.operation`)return u.runInContext(t,a);let o=i.get(t.scope.attemptId)??t.scope,s=r.get(o),c=t.type===`model.call`?s?.get(t.idempotencyKey):l.contextFor(t.scope.attemptId,t.idempotencyKey);if(c===void 0){let n=await e.stateStore.getTurn(t.scope.sessionId,t.scope.turnId);n!==void 0&&(c=withChannelAudience(contextFromSpanContext(n.context),t.scope.channelAudience),isSampledTrace(n.context)||(c=suppressTracing(c)))}let d=await e.stateStore.getSession(t.scope.sessionId),f=resolveForwardedTraceSeed(contextStorage.getStore()?.get(SessionTraceSeedKey)),p=f?.decision??d?.decision,m=p===void 0?void 0:applyLiveDeliveryAudienceCeiling(p,normalizeChannelAudience(t.scope.channelAudience),f?.forwardedTracePolicy);return c===void 0?a():context.with(markAgentTraceContext(withErrorContent(c,n&&m?.action===`record`&&m.recordOutputs)),a)}};function getExecutionContexts(e){let t=r.get(e);return t===void 0&&(t=new Map,r.set(e,t)),t}function drainOpenSpans(e){for(let t of o.get(e.scope)?.values()??[])e.type===`step.attempt.failed`&&recordAgentSpanError(t.span,e.error),t.span.end();o.delete(e.scope)}}function agentActivationLinks(e){let t=[];return e.caller!==void 0&&t.push({context:e.caller,attributes:{"eve.link.type":`agent.dispatch`}}),e.channelDelivery?.requestTraceContext!==void 0&&t.push({context:e.channelDelivery.requestTraceContext,attributes:{"eve.link.type":`channel.request`}}),t.length===0?void 0:t}function sessionIdForEvent(e){return`scope`in e?e.scope.sessionId:e.sessionId}function audienceForEvent(e,t){return`delivery`in e?normalizeChannelAudience(e.delivery.channelAudience):`scope`in e&&e.scope.channelAudience!==void 0?normalizeChannelAudience(e.scope.channelAudience):e.type===`session.started`?normalizeChannelAudience(e.channelAudience):normalizeChannelAudience(t)}function getSpanStates(e,t){let n=e.get(t);return n===void 0&&(n=new Map,e.set(t,n)),n}function takeSpanState(e,t,n){let r=e.get(t),i=r?.get(n);if(r!==void 0)return r.delete(n),r.size===0&&e.delete(t),i}function contextFromSpanContext(e){return trace.setSpan(ROOT_CONTEXT,trace.wrapSpanContext(e))}function modelSpanName(e){return`chat ${e}`}function errorText(e){return e instanceof Error?e.message:e}export{createAgentOtelInstrumentation};
@@ -12,6 +12,7 @@ export declare const AGENT_USAGE_ATTRIBUTES: {
12
12
  readonly cacheWriteTokens: "agent.usage.cache_write_tokens";
13
13
  };
14
14
  export declare function agentInvocationSpanName(agentName: string | undefined): string;
15
+ export declare function workflowInvocationSpanName(workflowName: string): string;
15
16
  export interface AgentSamplingOperation {
16
17
  readonly name: string;
17
18
  readonly attributes?: Readonly<Record<string, string | number | boolean | undefined>>;
@@ -1 +1 @@
1
- const AGENT_TRACE_SCHEMA_VERSION=4,AGENT_SPAN_NAMES={action:`agent.action`,approval:`agent.approval`,channelRequest:`agent.channel.request`,step:`agent.step`},AGENT_USAGE_ATTRIBUTES={inputTokens:`agent.usage.input_tokens`,outputTokens:`agent.usage.output_tokens`,cacheReadTokens:`agent.usage.cache_read_tokens`,cacheWriteTokens:`agent.usage.cache_write_tokens`};function agentInvocationSpanName(e){return e===void 0?`invoke_agent`:`invoke_agent ${e}`}function isAgentActivationSpan(e){return e.name===`agent.turn`||e.attributes[`gen_ai.operation.name`]===`invoke_agent`&&e.attributes[`agent.invocation.role`]!==`caller`&&typeof e.attributes[`agent.turn.id`]==`string`}function agentTurnIdentity(e){let t=e.attributes[`gen_ai.conversation.id`],n=e.attributes[`agent.turn.id`];return typeof n==`string`?`${typeof t==`string`?t:``}\0${n}`:void 0}export{AGENT_SPAN_NAMES,AGENT_TRACE_SCHEMA_VERSION,AGENT_USAGE_ATTRIBUTES,agentInvocationSpanName,agentTurnIdentity,isAgentActivationSpan};
1
+ const AGENT_TRACE_SCHEMA_VERSION=4,AGENT_SPAN_NAMES={action:`agent.action`,approval:`agent.approval`,channelRequest:`agent.channel.request`,step:`agent.step`},AGENT_USAGE_ATTRIBUTES={inputTokens:`agent.usage.input_tokens`,outputTokens:`agent.usage.output_tokens`,cacheReadTokens:`agent.usage.cache_read_tokens`,cacheWriteTokens:`agent.usage.cache_write_tokens`};function agentInvocationSpanName(e){return e===void 0?`invoke_agent`:`invoke_agent ${e}`}function workflowInvocationSpanName(e){return`invoke_workflow ${e}`}function isAgentActivationSpan(e){return e.name===`agent.turn`||e.attributes[`gen_ai.operation.name`]===`invoke_agent`&&e.attributes[`agent.invocation.role`]!==`caller`&&typeof e.attributes[`agent.turn.id`]==`string`}function agentTurnIdentity(e){let t=e.attributes[`gen_ai.conversation.id`],n=e.attributes[`agent.turn.id`];return typeof n==`string`?`${typeof t==`string`?t:``}\0${n}`:void 0}export{AGENT_SPAN_NAMES,AGENT_TRACE_SCHEMA_VERSION,AGENT_USAGE_ATTRIBUTES,agentInvocationSpanName,agentTurnIdentity,isAgentActivationSpan,workflowInvocationSpanName};
@@ -1 +1 @@
1
- import{ROOT_CONTEXT,SpanKind,trace}from"#compiled/@opentelemetry/api/index.js";import{actionIdempotencyKey}from"#instrumentation/lifecycle.js";import{agentSpanNamingAttributes}from"#tracing/agent-span-naming.js";import{agentTraceIdentityAttributes}from"#tracing/agent-otel-attributes.js";import{contentAttribute}from"#tracing/agent-otel-content.js";import{withChannelAudience}from"#tracing/channel-audience-context.js";import{recordAgentSpanError}from"#tracing/agent-span-error.js";function createAgentToolInstrumentation(e){let t=new Map,n=new Map,onStarted=async t=>{let n=actionIdempotencyKey(t.scope.sessionId,t.scope.turnId,t.callId),r=e.resolveFallback(t),i=r===void 0?void 0:reserve(t,n,r),a=await e.actionContextFor(t.scope.sessionId,t.scope.turnId,t.callId);if(i===void 0){if(a===void 0)return;i=reserve(t,n,a)}a!==void 0&&startSpan(i,a.context)},onTerminal=async t=>{let r=n.get(t.scope.attemptId)?.get(t.idempotencyKey);if(r!==void 0){if(r.terminal=t,r.span===void 0){let t=await e.actionContextFor(r.event.scope.sessionId,r.event.scope.turnId,r.event.callId);t!==void 0&&startSpan(r,t.context)}finishIfReady(r)}};return{async actionStarted(n){let r=t.get(n.idempotencyKey);if(r===void 0||r.span!==void 0||r.finished===!0)return;let i=await e.actionContextFor(n.scope.sessionId,n.scope.turnId,n.callId);i!==void 0&&(startSpan(r,i.context),finishIfReady(r))},contextFor:(e,t)=>n.get(e)?.get(t)?.context,drain(e,t){let r=n.get(e);if(r!==void 0){for(let e of r.values())e.finished!==!0&&(e.span===void 0&&startSpan(e,e.fallbackParent),finish(e,t));n.delete(e)}},events:{"tool.call.completed":onTerminal,"tool.call.failed":onTerminal,"tool.call.started":onStarted}};function getAttemptStates(e){let t=n.get(e);return t===void 0&&(t=new Map,n.set(e,t)),t}function reserve(n,r,i){let a=e.idGenerator.deriveSpanId(`tool:${n.idempotencyKey}`),o={actionKey:r,attemptId:n.scope.attemptId,context:withChannelAudience(contextFromSpanContext({isRemote:!1,spanId:a,traceFlags:i.spanContext.traceFlags,traceId:i.spanContext.traceId}),n.scope.channelAudience),event:n,fallbackParent:i.context,idempotencyKey:n.idempotencyKey,spanId:a,startTimeMs:Date.now()};return getAttemptStates(n.scope.attemptId).set(n.idempotencyKey,o),t.set(r,o),o}function startSpan(t,n){if(t.span===void 0&&t.finished!==!0&&(t.span=e.idGenerator.withSpanId(t.spanId,()=>e.tracer.startSpan(`execute_tool ${t.event.toolName}`,{attributes:toolAttributes(t.event),kind:SpanKind.INTERNAL,startTime:t.startTimeMs},n)),e.recordInputs)){let e=contentAttribute(t.event.input,!1);e!==void 0&&t.span.setAttribute(`gen_ai.tool.call.arguments`,e)}}function finishIfReady(e){e.span!==void 0&&e.terminal!==void 0&&finish(e)}function finish(r,i){let a=r.span;if(a===void 0||r.finished===!0)return;r.finished=!0;let o=r.terminal;if(i!==void 0)recordAgentSpanError(a,i.error);else if(o?.type===`tool.call.failed`)recordAgentSpanError(a,o.error);else if(o?.output.type===`error`)recordAgentSpanError(a,o.output.error);else if(o!==void 0&&e.recordOutputs){let e=contentAttribute(o.output.output,!1);e!==void 0&&a.setAttribute(`gen_ai.tool.call.result`,e)}a.end(),t.delete(r.actionKey);let s=n.get(r.attemptId);s?.delete(r.idempotencyKey),s?.size===0&&n.delete(r.attemptId)}}function toolAttributes(e){return{"gen_ai.operation.name":`execute_tool`,"gen_ai.tool.call.id":e.callId,"gen_ai.tool.name":e.toolName,"gen_ai.tool.type":`function`,...agentSpanNamingAttributes(`execute_tool ${e.toolName}`,`execute_tool`),...agentTraceIdentityAttributes({rootSessionId:e.scope.rootSessionId??e.scope.sessionId,sessionId:e.scope.sessionId})}}function contextFromSpanContext(e){return trace.setSpan(ROOT_CONTEXT,trace.wrapSpanContext(e))}export{createAgentToolInstrumentation};
1
+ import{ROOT_CONTEXT,SpanKind,trace}from"#compiled/@opentelemetry/api/index.js";import{actionIdempotencyKey}from"#instrumentation/lifecycle.js";import{agentSpanNamingAttributes}from"#tracing/agent-span-naming.js";import{agentTraceIdentityAttributes}from"#tracing/agent-otel-attributes.js";import{contentAttribute}from"#tracing/agent-otel-content.js";import{withChannelAudience}from"#tracing/channel-audience-context.js";import{recordAgentSpanError}from"#tracing/agent-span-error.js";function createAgentToolInstrumentation(e){let t=new Map,n=new Map,onStarted=async t=>{let n=actionIdempotencyKey(t.scope.sessionId,t.scope.turnId,t.callId),r=e.resolveFallback(t),i=r===void 0?void 0:reserve(t,n,r),a=await e.actionContextFor(t.scope.sessionId,t.scope.turnId,t.callId);if(i===void 0){if(a===void 0)return;i=reserve(t,n,a)}a!==void 0&&startSpan(i,a.context)},onTerminal=async t=>{let r=n.get(t.scope.attemptId)?.get(t.idempotencyKey);if(r!==void 0){if(r.terminal=t,r.span===void 0){let t=await e.actionContextFor(r.event.scope.sessionId,r.event.scope.turnId,r.event.callId);t!==void 0&&startSpan(r,t.context)}finishIfReady(r)}};return{async actionStarted(n){let r=t.get(n.idempotencyKey);if(r===void 0||r.span!==void 0||r.finished===!0)return;let i=await e.actionContextFor(n.scope.sessionId,n.scope.turnId,n.callId);i!==void 0&&(startSpan(r,i.context),finishIfReady(r))},contextFor:(e,t)=>n.get(e)?.get(t)?.context,drain(e,t){let r=n.get(e);if(r!==void 0){for(let e of r.values())e.finished!==!0&&(e.span===void 0&&startSpan(e,e.fallbackParent),finish(e,t));n.delete(e)}},events:{"tool.call.completed":onTerminal,"tool.call.failed":onTerminal,"tool.call.started":onStarted}};function getAttemptStates(e){let t=n.get(e);return t===void 0&&(t=new Map,n.set(e,t)),t}function reserve(n,r,i){let a=e.idGenerator.deriveSpanId(`tool:${n.idempotencyKey}`),o={actionKey:r,attemptId:n.scope.attemptId,context:withChannelAudience(contextFromSpanContext({isRemote:!1,spanId:a,traceFlags:i.spanContext.traceFlags,traceId:i.spanContext.traceId}),n.scope.channelAudience),event:n,fallbackParent:i.context,idempotencyKey:n.idempotencyKey,spanId:a,startTimeMs:Date.now()};return getAttemptStates(n.scope.attemptId).set(n.idempotencyKey,o),t.set(r,o),o}function startSpan(t,n){if(t.span===void 0&&t.finished!==!0&&(t.span=e.idGenerator.withSpanId(t.spanId,()=>e.tracer.startSpan(`execute_tool ${t.event.toolName}`,{attributes:toolAttributes(t.event),kind:SpanKind.INTERNAL,startTime:t.startTimeMs},n)),e.recordInputs)){let e=contentAttribute(t.event.input);e!==void 0&&t.span.setAttribute(`gen_ai.tool.call.arguments`,e)}}function finishIfReady(e){e.span!==void 0&&e.terminal!==void 0&&finish(e)}function finish(r,i){let a=r.span;if(a===void 0||r.finished===!0)return;r.finished=!0;let o=r.terminal;if(i!==void 0)recordAgentSpanError(a,i.error);else if(o?.type===`tool.call.failed`)recordAgentSpanError(a,o.error);else if(o?.output.type===`error`)recordAgentSpanError(a,o.output.error);else if(o!==void 0&&e.recordOutputs){let e=contentAttribute(o.output.output);e!==void 0&&a.setAttribute(`gen_ai.tool.call.result`,e)}a.end(),t.delete(r.actionKey);let s=n.get(r.attemptId);s?.delete(r.idempotencyKey),s?.size===0&&n.delete(r.attemptId)}}function toolAttributes(e){return{"gen_ai.operation.name":`execute_tool`,"gen_ai.tool.call.id":e.callId,"gen_ai.tool.name":e.toolName,"gen_ai.tool.type":`function`,...agentSpanNamingAttributes(`execute_tool ${e.toolName}`,`execute_tool`),...agentTraceIdentityAttributes({rootSessionId:e.scope.rootSessionId??e.scope.sessionId,sessionId:e.scope.sessionId})}}function contextFromSpanContext(e){return trace.setSpan(ROOT_CONTEXT,trace.wrapSpanContext(e))}export{createAgentToolInstrumentation};
@@ -1 +1 @@
1
- import{normalizeChannelAudience}from"#shared/channel-audience.js";import{isInstrumentationPrincipalType}from"#instrumentation/lifecycle.js";import{boundedPrincipalId}from"#tracing/telemetry-budget.js";import{readInstrumentationDecision}from"#shared/instrumentation-decision.js";import{boundedTraceError}from"#tracing/bounded-error.js";const AGENT_TRACE_CONTEXT_KEY=`eve.harness.agentTrace`;function emptyAgentTraceContextState(){return{actionAnchors:{},actions:{},invocations:{},sessions:{},turns:{}}}function serializeAgentTraceContextState(e){return{actionAnchors:e.actionAnchors,actions:e.actions,invocations:Object.fromEntries(Object.entries(e.invocations).map(([e,t])=>[e,{...t,terminal:t.terminal===void 0?void 0:{...t.terminal,error:t.recordOutputs===!0?serializeError(t.terminal.error):void 0}}])),sessions:Object.fromEntries(Object.entries(e.sessions).map(([e,t])=>[e,{...t,context:serializeSpanContext(t.context)}])),turns:Object.fromEntries(Object.entries(e.turns).map(([e,t])=>[e,{...t,caller:t.caller===void 0?void 0:serializeSpanContext(t.caller),channelDelivery:t.channelDelivery===void 0?void 0:{...t.channelDelivery,requestTraceContext:t.channelDelivery.requestTraceContext===void 0?void 0:serializeSpanContext(t.channelDelivery.requestTraceContext)},context:serializeSpanContext(t.context),terminal:t.terminal===void 0?void 0:t.terminal.type===`turn.failed`?{error:serializeError(t.terminal.error),type:t.terminal.type}:{type:t.terminal.type}}]))}}function deserializeAgentTraceContextState(e){return isRecord(e)?{actionAnchors:deserializeRecord(e.actionAnchors,deserializeAction),actions:deserializeRecord(e.actions,deserializeAction),invocations:deserializeRecord(e.invocations,deserializeInvocation),sessions:deserializeRecord(e.sessions,deserializeSession),turns:deserializeRecord(e.turns,deserializeTurn)}:emptyAgentTraceContextState()}function deserializeSession(e){if(isRecord(e)&&isSpanContext(e.context))return{agentName:typeof e.agentName==`string`?e.agentName:void 0,channelAudience:normalizeChannelAudience(e.channelAudience),channelKind:typeof e.channelKind==`string`?e.channelKind:void 0,context:e.context,decision:readInstrumentationDecision(e.decision),parentLineage:deserializeParentLineage(e.parentLineage),rootSessionId:typeof e.rootSessionId==`string`?e.rootSessionId:``}}function deserializeTurn(e){if(isRecord(e)&&isSpanContext(e.context)&&typeof e.startTimeMs==`number`)return{caller:isSpanContext(e.caller)?e.caller:void 0,channelDelivery:deserializeTurnChannelDelivery(e.channelDelivery),context:e.context,currentPrincipal:deserializePrincipalSummary(e.currentPrincipal),initiatorPrincipal:deserializePrincipalSummary(e.initiatorPrincipal),modelUsage:deserializeModelUsage(e.modelUsage),parentLineage:deserializeParentLineage(e.parentLineage),rootSessionId:typeof e.rootSessionId==`string`?e.rootSessionId:``,sequence:typeof e.sequence==`number`?e.sequence:0,startTimeMs:e.startTimeMs,subagentName:typeof e.subagentName==`string`?e.subagentName:void 0,terminal:deserializeTurnTerminal(e.terminal)}}function deserializeTurnChannelDelivery(e){if(isRecord(e)&&typeof e.channelKind==`string`&&typeof e.channelName==`string`&&typeof e.deliveryId==`string`)return{channelKind:e.channelKind,channelName:e.channelName,deliveryId:e.deliveryId,inputAttribute:typeof e.inputAttribute==`string`?e.inputAttribute:void 0,requestId:typeof e.requestId==`string`?e.requestId:void 0,requestTraceContext:isSpanContext(e.requestTraceContext)?e.requestTraceContext:void 0}}function deserializePrincipalSummary(e){if(!isRecord(e)||!isInstrumentationPrincipalType(e.type))return;let t=e.type===`none`?void 0:boundedPrincipalId(e.id);return t===void 0?{type:e.type}:{id:t,type:e.type}}function deserializeAction(e){if(isRecord(e)&&typeof e.attemptIndex==`number`&&typeof e.callId==`string`&&isActionKind(e.kind)&&typeof e.name==`string`&&isSpanContext(e.parent)&&typeof e.rootSessionId==`string`&&typeof e.sessionId==`string`&&typeof e.spanId==`string`&&typeof e.startTimeMs==`number`&&typeof e.stepIndex==`number`&&typeof e.turnId==`string`)return{attemptIndex:e.attemptIndex,callId:e.callId,channelAudience:normalizeChannelAudience(e.channelAudience),inputAttribute:typeof e.inputAttribute==`string`?e.inputAttribute:void 0,kind:e.kind,name:e.name,parent:e.parent,rootSessionId:e.rootSessionId,sessionId:e.sessionId,spanId:e.spanId,startTimeMs:e.startTimeMs,stepIndex:e.stepIndex,turnId:e.turnId}}function deserializeInvocation(e){let t=deserializeAction(e);if(!(t===void 0||t.kind!==`subagent-call`&&t.kind!==`remote-agent-call`||!isRecord(e)||typeof e.parentActionCallId!=`string`))return{attemptIndex:t.attemptIndex,callId:t.callId,channelAudience:t.channelAudience,kind:t.kind,name:t.name,parent:t.parent,parentActionCallId:e.parentActionCallId,recordOutputs:e.recordOutputs===!0,rootSessionId:t.rootSessionId,sessionId:t.sessionId,spanId:t.spanId,startTimeMs:t.startTimeMs,stepIndex:t.stepIndex,terminal:deserializeActionTerminal(e.terminal),turnId:t.turnId}}function deserializeActionTerminal(e){if(isRecord(e)&&isActionOutcome(e.outcome))return{acceptedAtMs:typeof e.acceptedAtMs==`number`?e.acceptedAtMs:void 0,error:deserializeError(e.error),outcome:e.outcome,usage:isRecord(e.usage)?e.usage:void 0}}function deserializeModelUsage(e){if(!isRecord(e))return;let t=typeof e.inputTokens==`number`?e.inputTokens:void 0,n=typeof e.outputTokens==`number`?e.outputTokens:void 0;return t===void 0&&n===void 0?void 0:{inputTokens:t,outputTokens:n}}function deserializeParentLineage(e){if(isRecord(e)&&typeof e.callId==`string`&&typeof e.sessionId==`string`&&typeof e.turnId==`string`)return{callId:e.callId,sessionId:e.sessionId,subagentName:typeof e.subagentName==`string`?e.subagentName:void 0,turnId:e.turnId}}function deserializeTurnTerminal(e){if(isRecord(e)&&isTurnTerminalType(e.type))return e.type===`turn.failed`?{error:deserializeError(e.error),type:e.type}:{type:e.type}}function deserializeRecord(e,t){if(!isRecord(e))return{};let n={};for(let[r,i]of Object.entries(e)){let e=t(i);e!==void 0&&(n[r]=e)}return n}function serializeSpanContext(e){return{isRemote:e.isRemote,spanId:e.spanId,traceFlags:e.traceFlags,traceId:e.traceId}}function serializeError(e){if(!(e instanceof Error))return;let t=boundedTraceError(e);return{message:t.message,name:t.name,stack:t.stack}}function deserializeError(e){if(!isRecord(e)||typeof e.message!=`string`)return;let t=Error(e.message);return typeof e.name==`string`&&(t.name=e.name),typeof e.stack==`string`&&(t.stack=e.stack),t}function isActionKind(e){return e===`load-skill`||e===`remote-agent-call`||e===`subagent-call`||e===`tool-call`}function isActionOutcome(e){return e===`abandoned`||e===`cancelled`||e===`completed`||e===`failed`||e===`rejected`}function isTurnTerminalType(e){return e===`turn.cancelled`||e===`turn.completed`||e===`turn.failed`}function isSpanContext(e){return isRecord(e)&&typeof e.spanId==`string`&&typeof e.traceFlags==`number`&&typeof e.traceId==`string`}function isRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}export{AGENT_TRACE_CONTEXT_KEY,deserializeAgentTraceContextState,emptyAgentTraceContextState,serializeAgentTraceContextState};
1
+ import{normalizeChannelAudience}from"#shared/channel-audience.js";import{isInstrumentationPrincipalType}from"#instrumentation/lifecycle.js";import{boundedPrincipalId}from"#tracing/telemetry-budget.js";import{readInstrumentationDecision}from"#shared/instrumentation-decision.js";import{boundedTraceError}from"#tracing/bounded-error.js";const AGENT_TRACE_CONTEXT_KEY=`eve.harness.agentTrace`;function emptyAgentTraceContextState(){return{actionAnchors:{},actions:{},invocations:{},sessions:{},turns:{}}}function serializeAgentTraceContextState(e){return{actionAnchors:e.actionAnchors,actions:e.actions,invocations:Object.fromEntries(Object.entries(e.invocations).map(([e,t])=>[e,{...t,terminal:t.terminal===void 0?void 0:{...t.terminal,error:t.recordOutputs===!0?serializeError(t.terminal.error):void 0}}])),sessions:Object.fromEntries(Object.entries(e.sessions).map(([e,t])=>[e,{...t,context:serializeSpanContext(t.context)}])),turns:Object.fromEntries(Object.entries(e.turns).map(([e,t])=>[e,{...t,caller:t.caller===void 0?void 0:serializeSpanContext(t.caller),channelDelivery:t.channelDelivery===void 0?void 0:{...t.channelDelivery,requestTraceContext:t.channelDelivery.requestTraceContext===void 0?void 0:serializeSpanContext(t.channelDelivery.requestTraceContext)},context:serializeSpanContext(t.context),terminal:t.terminal===void 0?void 0:t.terminal.type===`turn.failed`?{error:serializeError(t.terminal.error),type:t.terminal.type}:{type:t.terminal.type}}]))}}function deserializeAgentTraceContextState(e){return isRecord(e)?{actionAnchors:deserializeRecord(e.actionAnchors,deserializeAction),actions:deserializeRecord(e.actions,deserializeAction),invocations:deserializeRecord(e.invocations,deserializeInvocation),sessions:deserializeRecord(e.sessions,deserializeSession),turns:deserializeRecord(e.turns,deserializeTurn)}:emptyAgentTraceContextState()}function deserializeSession(e){if(isRecord(e)&&isSpanContext(e.context))return{agentName:typeof e.agentName==`string`?e.agentName:void 0,channelAudience:normalizeChannelAudience(e.channelAudience),channelKind:typeof e.channelKind==`string`?e.channelKind:void 0,context:e.context,decision:readInstrumentationDecision(e.decision),parentLineage:deserializeParentLineage(e.parentLineage),rootSessionId:typeof e.rootSessionId==`string`?e.rootSessionId:``}}function deserializeTurn(e){if(isRecord(e)&&isSpanContext(e.context)&&typeof e.startTimeMs==`number`)return{caller:isSpanContext(e.caller)?e.caller:void 0,channelDelivery:deserializeTurnChannelDelivery(e.channelDelivery),context:e.context,currentPrincipal:deserializePrincipalSummary(e.currentPrincipal),initiatorPrincipal:deserializePrincipalSummary(e.initiatorPrincipal),modelUsage:deserializeModelUsage(e.modelUsage),parentLineage:deserializeParentLineage(e.parentLineage),rootSessionId:typeof e.rootSessionId==`string`?e.rootSessionId:``,sequence:typeof e.sequence==`number`?e.sequence:0,startTimeMs:e.startTimeMs,subagentName:typeof e.subagentName==`string`?e.subagentName:void 0,terminal:deserializeTurnTerminal(e.terminal)}}function deserializeTurnChannelDelivery(e){if(isRecord(e)&&typeof e.channelKind==`string`&&typeof e.channelName==`string`&&typeof e.deliveryId==`string`)return{channelKind:e.channelKind,channelName:e.channelName,deliveryId:e.deliveryId,inputAttribute:typeof e.inputAttribute==`string`?e.inputAttribute:void 0,requestId:typeof e.requestId==`string`?e.requestId:void 0,requestTraceContext:isSpanContext(e.requestTraceContext)?e.requestTraceContext:void 0}}function deserializePrincipalSummary(e){if(!isRecord(e)||!isInstrumentationPrincipalType(e.type))return;let t=e.type===`none`?void 0:boundedPrincipalId(e.id);return t===void 0?{type:e.type}:{id:t,type:e.type}}function deserializeAction(e){if(isRecord(e)&&typeof e.attemptIndex==`number`&&typeof e.callId==`string`&&isActionKind(e.kind)&&typeof e.name==`string`&&isSpanContext(e.parent)&&typeof e.rootSessionId==`string`&&typeof e.sessionId==`string`&&typeof e.spanId==`string`&&typeof e.startTimeMs==`number`&&typeof e.stepIndex==`number`&&typeof e.turnId==`string`)return{attemptIndex:e.attemptIndex,callId:e.callId,channelAudience:normalizeChannelAudience(e.channelAudience),inputAttribute:typeof e.inputAttribute==`string`?e.inputAttribute:void 0,isWorkflowTool:e.isWorkflowTool===!0||void 0,kind:e.kind,name:e.name,parent:e.parent,rootSessionId:e.rootSessionId,sessionId:e.sessionId,spanId:e.spanId,startTimeMs:e.startTimeMs,stepIndex:e.stepIndex,turnId:e.turnId,workflowName:typeof e.workflowName==`string`?e.workflowName:void 0}}function deserializeInvocation(e){let t=deserializeAction(e);if(!(t===void 0||t.kind!==`subagent-call`&&t.kind!==`remote-agent-call`||!isRecord(e)||typeof e.parentActionCallId!=`string`))return{attemptIndex:t.attemptIndex,callId:t.callId,channelAudience:t.channelAudience,kind:t.kind,name:t.name,parent:t.parent,parentActionCallId:e.parentActionCallId,recordOutputs:e.recordOutputs===!0,rootSessionId:t.rootSessionId,sessionId:t.sessionId,spanId:t.spanId,startTimeMs:t.startTimeMs,stepIndex:t.stepIndex,terminal:deserializeActionTerminal(e.terminal),turnId:t.turnId}}function deserializeActionTerminal(e){if(isRecord(e)&&isActionOutcome(e.outcome))return{acceptedAtMs:typeof e.acceptedAtMs==`number`?e.acceptedAtMs:void 0,error:deserializeError(e.error),outcome:e.outcome,usage:isRecord(e.usage)?e.usage:void 0}}function deserializeModelUsage(e){if(!isRecord(e))return;let t=typeof e.inputTokens==`number`?e.inputTokens:void 0,n=typeof e.outputTokens==`number`?e.outputTokens:void 0;return t===void 0&&n===void 0?void 0:{inputTokens:t,outputTokens:n}}function deserializeParentLineage(e){if(isRecord(e)&&typeof e.callId==`string`&&typeof e.sessionId==`string`&&typeof e.turnId==`string`)return{callId:e.callId,sessionId:e.sessionId,subagentName:typeof e.subagentName==`string`?e.subagentName:void 0,turnId:e.turnId}}function deserializeTurnTerminal(e){if(isRecord(e)&&isTurnTerminalType(e.type))return e.type===`turn.failed`?{error:deserializeError(e.error),type:e.type}:{type:e.type}}function deserializeRecord(e,t){if(!isRecord(e))return{};let n={};for(let[r,i]of Object.entries(e)){let e=t(i);e!==void 0&&(n[r]=e)}return n}function serializeSpanContext(e){return{isRemote:e.isRemote,spanId:e.spanId,traceFlags:e.traceFlags,traceId:e.traceId}}function serializeError(e){if(!(e instanceof Error))return;let t=boundedTraceError(e);return{message:t.message,name:t.name,stack:t.stack}}function deserializeError(e){if(!isRecord(e)||typeof e.message!=`string`)return;let t=Error(e.message);return typeof e.name==`string`&&(t.name=e.name),typeof e.stack==`string`&&(t.stack=e.stack),t}function isActionKind(e){return e===`load-skill`||e===`remote-agent-call`||e===`subagent-call`||e===`tool-call`}function isActionOutcome(e){return e===`abandoned`||e===`cancelled`||e===`completed`||e===`failed`||e===`rejected`}function isTurnTerminalType(e){return e===`turn.cancelled`||e===`turn.completed`||e===`turn.failed`}function isSpanContext(e){return isRecord(e)&&typeof e.spanId==`string`&&typeof e.traceFlags==`number`&&typeof e.traceId==`string`}function isRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}export{AGENT_TRACE_CONTEXT_KEY,deserializeAgentTraceContextState,emptyAgentTraceContextState,serializeAgentTraceContextState};
@@ -1 +1 @@
1
- import{createLogger}from"#internal/logging.js";import{contextStorage,loadContext}from"#context/container.js";import{SessionTraceSeedKey}from"#context/keys.js";import{ContextKey}from"#context/key.js";import{decisionToTraceContentCeiling,resolveForwardedTraceSeed}from"#shared/forwarded-trace-policy.js";import{getWorkflowToolRuns}from"#harness/workflow-tool-runs.js";import{getSessionTaskIndex}from"#tasks/session-index.js";import{deriveTaskId}from"#tasks/task-id.js";import{actionIdempotencyKey}from"#instrumentation/lifecycle.js";import{AGENT_TRACE_CONTEXT_KEY,deserializeAgentTraceContextState,emptyAgentTraceContextState,serializeAgentTraceContextState}from"#tracing/agent-trace-context-codec.js";const AgentTraceContextKey=new ContextKey(AGENT_TRACE_CONTEXT_KEY,{codec:{deserialize:deserializeAgentTraceContextState,serialize:serializeAgentTraceContextState}});function pruneAgentTraceState(e,t,n){try{pruneTraceOwnership(e,t,n)}catch(e){createLogger(`tracing.retention`).warn(`could not reconcile trace ownership; preserving trace state`,{error:e})}}function pruneTraceOwnership(e,t,n){let r=e.get(AgentTraceContextKey);if(r===void 0)return;let i=new Set(getWorkflowToolRuns(n).map(e=>e.callId)),a=new Set(getSessionTaskIndex(n).filter(e=>e.terminalView===void 0).map(e=>e.taskId)),o=Object.fromEntries(Object.entries(r.actionAnchors).filter(([e,n])=>n.sessionId!==t||r.actions[e]!==void 0||i.has(n.callId)||a.has(deriveTaskId({callId:n.callId,parentSessionId:t,parentTurnId:n.turnId})))),s=new Set(Object.values(o).filter(e=>e.sessionId===t).map(e=>e.callId)),c=Object.fromEntries(Object.entries(r.invocations).filter(([,e])=>e.sessionId!==t||e.terminal!==void 0||s.has(e.parentActionCallId)));e.set(AgentTraceContextKey,{...r,actionAnchors:o,invocations:c})}function readCurrentSessionTraceDecision(e){let t=contextStorage.getStore();return t===void 0?void 0:readSessionTraceDecision(t,e)}function readSessionTraceDecision(e,t){return e.get(AgentTraceContextKey)?.sessions[t]?.decision}function preserveSerializedAgentTraceState(e,t){let n=t[AgentTraceContextKey.name];return n===void 0?e:{...e,[AgentTraceContextKey.name]:n}}function readTurnTraceContext(e,t,n){let r=e[AgentTraceContextKey.name];if(r===void 0)return;let i=deserializeAgentTraceContextState(r),a=i.turns[turnKey(t,n)];return a===void 0?void 0:withTraceDecision(e,a.context,i.sessions[t]?.decision)}function readActionTraceContext(e,t,n,r){let i=e[AgentTraceContextKey.name];if(i===void 0)return;let a=deserializeAgentTraceContextState(i),o=actionIdempotencyKey(t,n,r),s=a.invocations[o]??a.actions[o]??a.actionAnchors[o];if(s!==void 0)return withTraceDecision(e,{isRemote:!1,spanId:s.spanId,traceFlags:s.parent.traceFlags,traceId:s.parent.traceId},a.sessions[s.sessionId]?.decision)}function readTaskActionTrace(e,t,n){let r=deserializeAgentTraceContextState(e[AgentTraceContextKey.name]);return Object.values(r.actionAnchors).find(e=>e.sessionId===t&&deriveTaskId({callId:e.callId,parentSessionId:t,parentTurnId:e.turnId})===n)}function recordNestedAgentInvocation(e){let t=e.serializedContext[AgentTraceContextKey.name];if(t===void 0)return e.serializedContext;let n=deserializeAgentTraceContextState(t),r=actionIdempotencyKey(e.sessionId,e.turnId,e.outerCallId),i=n.actions[r]??n.actionAnchors[r];if(i===void 0)return e.serializedContext;let a=actionIdempotencyKey(e.sessionId,e.turnId,e.callId);if(n.invocations[a]!==void 0)return e.serializedContext;let o={attemptIndex:i.attemptIndex,callId:e.callId,channelAudience:i.channelAudience,kind:e.kind,name:e.name,parent:{spanId:i.spanId,traceFlags:i.parent.traceFlags,traceId:i.parent.traceId},parentActionCallId:e.outerCallId,recordOutputs:e.recordOutputs===!0,rootSessionId:i.rootSessionId,sessionId:i.sessionId,spanId:e.spanId,startTimeMs:e.startTimeMs,stepIndex:i.stepIndex,turnId:i.turnId};return{...e.serializedContext,[AgentTraceContextKey.name]:serializeAgentTraceContextState({...n,invocations:{...n.invocations,[a]:o}})}}function recordActionInvocationKind(e){let t=e.serializedContext[AgentTraceContextKey.name];if(t===void 0)return e.serializedContext;let n=deserializeAgentTraceContextState(t),update=t=>t.sessionId===e.sessionId&&t.turnId===e.turnId&&t.callId===e.callId?{...t,kind:e.kind}:t;return{...e.serializedContext,[AgentTraceContextKey.name]:serializeAgentTraceContextState({...n,actionAnchors:Object.fromEntries(Object.entries(n.actionAnchors).map(([e,t])=>[e,update(t)])),actions:Object.fromEntries(Object.entries(n.actions).map(([e,t])=>[e,update(t)]))})}}function withTraceDecision(e,t,n){let r=e[SessionTraceSeedKey.name],i=resolveForwardedTraceSeed({decision:n??r?.decision,forwardedTracePolicy:r?.forwardedTracePolicy,traceFlags:t.traceFlags}),a=i.decision,o=i.forwardedTracePolicy,s=decisionToTraceContentCeiling(a),c={...t,traceFlags:i.traceFlags};if(o===void 0)return a===void 0?c:{...c,decision:a};let l=s===void 0?o:{...o,ceiling:s};return a===void 0?{...c,forwardedTracePolicy:l}:{...c,decision:a,forwardedTracePolicy:l}}var ContextAgentTraceStateStore=class{deleteAction(e){updateState(t=>{let n={...t.actions};return delete n[e],{...t,actions:n}})}deleteActionAnchors(e){updateState(t=>({...t,actionAnchors:Object.fromEntries(Object.entries(t.actionAnchors).filter(([,t])=>t.sessionId!==e))}))}deleteActions(e,t){updateState(n=>{let r={...n.actions};for(let[n,i]of Object.entries(r))i.sessionId===e&&(t===void 0||i.turnId===t)&&delete r[n];return{...n,actions:r}})}deleteInvocation(e){updateState(t=>{let n={...t.invocations};return delete n[e],{...t,invocations:n}})}deleteInvocations(e,t){updateState(n=>({...n,invocations:Object.fromEntries(Object.entries(n.invocations).filter(([,n])=>n.sessionId!==e||t!==void 0&&n.turnId!==t))}))}deleteSession(e){updateState(t=>{let n={...t.sessions};return delete n[e],{...t,sessions:n}})}deleteTurn(e,t){updateState(n=>{let r={...n.turns};return delete r[turnKey(e,t)],{...n,turns:r}})}findAction(e,t){return Object.values(contextStorage.getStore()?.get(AgentTraceContextKey)?.actions??{}).find(n=>n.sessionId===e&&n.callId===t)}findActionAnchor(e,t,n){return Object.values(contextStorage.getStore()?.get(AgentTraceContextKey)?.actionAnchors??{}).find(r=>r.sessionId===e&&r.turnId===t&&r.callId===n)}findInvocations(e,t,n){return Object.values(contextStorage.getStore()?.get(AgentTraceContextKey)?.invocations??{}).filter(r=>(e===void 0||r.sessionId===e)&&(t===void 0||r.turnId===t)&&(n===void 0||r.parentActionCallId===n))}getAction(e){return contextStorage.getStore()?.get(AgentTraceContextKey)?.actions[e]}getSession(e){return contextStorage.getStore()?.get(AgentTraceContextKey)?.sessions[e]}getTurn(e,t){return contextStorage.getStore()?.get(AgentTraceContextKey)?.turns[turnKey(e,t)]}setAction(e,t){updateState(n=>({...n,actions:{...n.actions,[e]:t}}))}setActionAnchor(e,t){updateState(n=>({...n,actionAnchors:{...n.actionAnchors,[e]:t}}))}setInvocation(e,t){updateState(n=>({...n,invocations:{...n.invocations,[e]:t}}))}setSession(e,t){updateState(n=>({...n,sessions:{...n.sessions,[e]:t}}))}setTurn(e,t,n){updateState(r=>({...r,turns:{...r.turns,[turnKey(e,t)]:n}}))}updateTurn(e,t,n){updateState(r=>{let i=turnKey(e,t),a=r.turns[i];return a===void 0?r:{...r,turns:{...r.turns,[i]:n(a)}}})}};function updateState(e){loadContext().set(AgentTraceContextKey,t=>e(t??emptyAgentTraceContextState()))}function turnKey(e,t){return`${e}\0${t}`}export{ContextAgentTraceStateStore,preserveSerializedAgentTraceState,pruneAgentTraceState,readActionTraceContext,readCurrentSessionTraceDecision,readSessionTraceDecision,readTaskActionTrace,readTurnTraceContext,recordActionInvocationKind,recordNestedAgentInvocation};
1
+ import{createLogger}from"#internal/logging.js";import{contextStorage,loadContext}from"#context/container.js";import{SessionTraceSeedKey}from"#context/keys.js";import{ContextKey}from"#context/key.js";import{decisionToTraceContentCeiling,resolveForwardedTraceSeed}from"#shared/forwarded-trace-policy.js";import{getWorkflowToolRuns}from"#harness/workflow-tool-runs.js";import{getSessionTaskIndex}from"#tasks/session-index.js";import{deriveTaskId}from"#tasks/task-id.js";import{actionIdempotencyKey}from"#instrumentation/lifecycle.js";import{AGENT_TRACE_CONTEXT_KEY,deserializeAgentTraceContextState,emptyAgentTraceContextState,serializeAgentTraceContextState}from"#tracing/agent-trace-context-codec.js";const AgentTraceContextKey=new ContextKey(AGENT_TRACE_CONTEXT_KEY,{codec:{deserialize:deserializeAgentTraceContextState,serialize:serializeAgentTraceContextState}});function pruneAgentTraceState(e,t,n){try{pruneTraceOwnership(e,t,n)}catch(e){createLogger(`tracing.retention`).warn(`could not reconcile trace ownership; preserving trace state`,{error:e})}}function pruneTraceOwnership(e,t,n){let r=e.get(AgentTraceContextKey);if(r===void 0)return;let i=new Set(getWorkflowToolRuns(n).map(e=>e.callId)),a=new Set(getSessionTaskIndex(n).filter(e=>e.terminalView===void 0).map(e=>e.taskId)),o=Object.fromEntries(Object.entries(r.actionAnchors).filter(([e,n])=>n.sessionId!==t||r.actions[e]!==void 0||i.has(n.callId)||a.has(deriveTaskId({callId:n.callId,parentSessionId:t,parentTurnId:n.turnId})))),s=new Set(Object.values(o).filter(e=>e.sessionId===t).map(e=>e.callId)),c=Object.fromEntries(Object.entries(r.invocations).filter(([,e])=>e.sessionId!==t||e.terminal!==void 0||s.has(e.parentActionCallId)));e.set(AgentTraceContextKey,{...r,actionAnchors:o,invocations:c})}function readCurrentSessionTraceDecision(e){let t=contextStorage.getStore();return t===void 0?void 0:readSessionTraceDecision(t,e)}function readSessionTraceDecision(e,t){return e.get(AgentTraceContextKey)?.sessions[t]?.decision}function preserveSerializedAgentTraceState(e,t){let n=t[AgentTraceContextKey.name];return n===void 0?e:{...e,[AgentTraceContextKey.name]:n}}function readTurnTraceContext(e,t,n){let r=e[AgentTraceContextKey.name];if(r===void 0)return;let i=deserializeAgentTraceContextState(r),a=i.turns[turnKey(t,n)];return a===void 0?void 0:withTraceDecision(e,a.context,i.sessions[t]?.decision)}function readActionTraceContext(e,t,n,r){let i=e[AgentTraceContextKey.name];if(i===void 0)return;let a=deserializeAgentTraceContextState(i),o=actionIdempotencyKey(t,n,r),s=a.invocations[o]??a.actions[o]??a.actionAnchors[o];if(s!==void 0)return withTraceDecision(e,{isRemote:!1,spanId:s.spanId,traceFlags:s.parent.traceFlags,traceId:s.parent.traceId},a.sessions[s.sessionId]?.decision)}function readTaskActionTrace(e,t,n){let r=deserializeAgentTraceContextState(e[AgentTraceContextKey.name]);return Object.values(r.actionAnchors).find(e=>e.sessionId===t&&deriveTaskId({callId:e.callId,parentSessionId:t,parentTurnId:e.turnId})===n)}function recordNestedAgentInvocation(e){let t=e.serializedContext[AgentTraceContextKey.name];if(t===void 0)return e.serializedContext;let n=deserializeAgentTraceContextState(t),r=actionIdempotencyKey(e.sessionId,e.turnId,e.outerCallId),i=n.actions[r]??n.actionAnchors[r];if(i===void 0)return e.serializedContext;let a=actionIdempotencyKey(e.sessionId,e.turnId,e.callId),promote=e=>e.isWorkflowTool===!0&&e.kind===`tool-call`?{...e,workflowName:e.name}:e,o=n.actions[r]===void 0?n.actions:{...n.actions,[r]:promote(n.actions[r])},s=n.actionAnchors[r]===void 0?n.actionAnchors:{...n.actionAnchors,[r]:promote(n.actionAnchors[r])};if(n.invocations[a]!==void 0)return{...e.serializedContext,[AgentTraceContextKey.name]:serializeAgentTraceContextState({...n,actionAnchors:s,actions:o})};let c={attemptIndex:i.attemptIndex,callId:e.callId,channelAudience:i.channelAudience,kind:e.kind,name:e.name,parent:{spanId:i.spanId,traceFlags:i.parent.traceFlags,traceId:i.parent.traceId},parentActionCallId:e.outerCallId,recordOutputs:e.recordOutputs===!0,rootSessionId:i.rootSessionId,sessionId:i.sessionId,spanId:e.spanId,startTimeMs:e.startTimeMs,stepIndex:i.stepIndex,turnId:i.turnId};return{...e.serializedContext,[AgentTraceContextKey.name]:serializeAgentTraceContextState({...n,actionAnchors:s,actions:o,invocations:{...n.invocations,[a]:c}})}}function recordActionInvocationKind(e){let t=e.serializedContext[AgentTraceContextKey.name];if(t===void 0)return e.serializedContext;let n=deserializeAgentTraceContextState(t),update=t=>t.sessionId===e.sessionId&&t.turnId===e.turnId&&t.callId===e.callId?{...t,isWorkflowTool:void 0,kind:e.kind,workflowName:void 0}:t;return{...e.serializedContext,[AgentTraceContextKey.name]:serializeAgentTraceContextState({...n,actionAnchors:Object.fromEntries(Object.entries(n.actionAnchors).map(([e,t])=>[e,update(t)])),actions:Object.fromEntries(Object.entries(n.actions).map(([e,t])=>[e,update(t)]))})}}function withTraceDecision(e,t,n){let r=e[SessionTraceSeedKey.name],i=resolveForwardedTraceSeed({decision:n??r?.decision,forwardedTracePolicy:r?.forwardedTracePolicy,traceFlags:t.traceFlags}),a=i.decision,o=i.forwardedTracePolicy,s=decisionToTraceContentCeiling(a),c={...t,traceFlags:i.traceFlags};if(o===void 0)return a===void 0?c:{...c,decision:a};let l=s===void 0?o:{...o,ceiling:s};return a===void 0?{...c,forwardedTracePolicy:l}:{...c,decision:a,forwardedTracePolicy:l}}var ContextAgentTraceStateStore=class{deleteAction(e){updateState(t=>{let n={...t.actions};return delete n[e],{...t,actions:n}})}deleteActionAnchors(e){updateState(t=>({...t,actionAnchors:Object.fromEntries(Object.entries(t.actionAnchors).filter(([,t])=>t.sessionId!==e))}))}deleteActions(e,t){updateState(n=>{let r={...n.actions};for(let[n,i]of Object.entries(r))i.sessionId===e&&(t===void 0||i.turnId===t)&&delete r[n];return{...n,actions:r}})}deleteInvocation(e){updateState(t=>{let n={...t.invocations};return delete n[e],{...t,invocations:n}})}deleteInvocations(e,t){updateState(n=>({...n,invocations:Object.fromEntries(Object.entries(n.invocations).filter(([,n])=>n.sessionId!==e||t!==void 0&&n.turnId!==t))}))}deleteSession(e){updateState(t=>{let n={...t.sessions};return delete n[e],{...t,sessions:n}})}deleteTurn(e,t){updateState(n=>{let r={...n.turns};return delete r[turnKey(e,t)],{...n,turns:r}})}findAction(e,t){return Object.values(contextStorage.getStore()?.get(AgentTraceContextKey)?.actions??{}).find(n=>n.sessionId===e&&n.callId===t)}findActionAnchor(e,t,n){return Object.values(contextStorage.getStore()?.get(AgentTraceContextKey)?.actionAnchors??{}).find(r=>r.sessionId===e&&r.turnId===t&&r.callId===n)}findInvocations(e,t,n){return Object.values(contextStorage.getStore()?.get(AgentTraceContextKey)?.invocations??{}).filter(r=>(e===void 0||r.sessionId===e)&&(t===void 0||r.turnId===t)&&(n===void 0||r.parentActionCallId===n))}getAction(e){return contextStorage.getStore()?.get(AgentTraceContextKey)?.actions[e]}getSession(e){return contextStorage.getStore()?.get(AgentTraceContextKey)?.sessions[e]}getTurn(e,t){return contextStorage.getStore()?.get(AgentTraceContextKey)?.turns[turnKey(e,t)]}setAction(e,t){updateState(n=>({...n,actions:{...n.actions,[e]:t}}))}setActionAnchor(e,t){updateState(n=>({...n,actionAnchors:{...n.actionAnchors,[e]:t}}))}setInvocation(e,t){updateState(n=>({...n,invocations:{...n.invocations,[e]:t}}))}setSession(e,t){updateState(n=>({...n,sessions:{...n.sessions,[e]:t}}))}setTurn(e,t,n){updateState(r=>({...r,turns:{...r.turns,[turnKey(e,t)]:n}}))}updateTurn(e,t,n){updateState(r=>{let i=turnKey(e,t),a=r.turns[i];return a===void 0?r:{...r,turns:{...r.turns,[i]:n(a)}}})}};function updateState(e){loadContext().set(AgentTraceContextKey,t=>e(t??emptyAgentTraceContextState()))}function turnKey(e,t){return`${e}\0${t}`}export{ContextAgentTraceStateStore,preserveSerializedAgentTraceState,pruneAgentTraceState,readActionTraceContext,readCurrentSessionTraceDecision,readSessionTraceDecision,readTaskActionTrace,readTurnTraceContext,recordActionInvocationKind,recordNestedAgentInvocation};
@@ -46,6 +46,7 @@ export interface AgentActionTraceState {
46
46
  readonly callId: string;
47
47
  readonly channelAudience?: ChannelAudience;
48
48
  readonly inputAttribute?: string;
49
+ readonly isWorkflowTool?: boolean;
49
50
  readonly kind: InstrumentationActionKind;
50
51
  readonly name: string;
51
52
  readonly parent: InstrumentationTraceContext;
@@ -55,8 +56,9 @@ export interface AgentActionTraceState {
55
56
  readonly startTimeMs: number;
56
57
  readonly stepIndex: number;
57
58
  readonly turnId: string;
59
+ readonly workflowName?: string;
58
60
  }
59
- export interface AgentInvocationTraceState extends Omit<AgentActionTraceState, "inputAttribute" | "kind"> {
61
+ export interface AgentInvocationTraceState extends Omit<AgentActionTraceState, "inputAttribute" | "isWorkflowTool" | "kind" | "workflowName"> {
60
62
  readonly kind: "remote-agent-call" | "subagent-call";
61
63
  readonly parentActionCallId: string;
62
64
  readonly recordOutputs?: boolean;
@@ -1 +1 @@
1
- const INPUT_CONTENT_ATTRIBUTES=new Set([`agent.channel.delivery.input`,`agent.approval.request`,`ai.documents`,`ai.prompt`,`ai.prompt.messages`,`ai.prompt.system`,`ai.prompt.toolChoice`,`ai.prompt.tools`,`ai.value`,`ai.values`,`gen_ai.input.messages`,`gen_ai.system_instructions`,`gen_ai.tool.call.arguments`,`gen_ai.tool.definitions`]),OUTPUT_CONTENT_ATTRIBUTES=new Set([`agent.approval.response`,`ai.embedding`,`ai.embeddings`,`ai.ranking`,`ai.response.files`,`ai.response.object`,`ai.response.reasoning`,`ai.response.text`,`ai.response.toolCalls`,`ai.response.tool_calls`,`ai.response.tool_results`,`ai.toolCall.args`,`ai.toolCall.result`,`gen_ai.output.messages`,`gen_ai.tool.call.result`]);function isDeclined(e,t){return!t.recordInputs&&INPUT_CONTENT_ATTRIBUTES.has(e)?!0:!t.recordOutputs&&OUTPUT_CONTENT_ATTRIBUTES.has(e)}function withoutDeclinedContent(e,t){let n=Object.keys(e);if(!n.some(e=>isDeclined(e,t)))return;let r={};for(let i of n)isDeclined(i,t)||(r[i]=e[i]);return r}export{withoutDeclinedContent};
1
+ const INPUT_CONTENT_ATTRIBUTES=new Set([`agent.channel.delivery.input`,`agent.approval.request`,`ai.documents`,`ai.prompt`,`ai.prompt.system`,`ai.prompt.toolChoice`,`ai.prompt.tools`,`ai.value`,`ai.values`,`gen_ai.input.messages`,`gen_ai.memory.records`,`gen_ai.system_instructions`,`gen_ai.tool.call.arguments`,`gen_ai.tool.definitions`]),OUTPUT_CONTENT_ATTRIBUTES=new Set([`agent.approval.response`,`ai.embedding`,`ai.embeddings`,`ai.ranking`,`ai.response.files`,`ai.response.object`,`ai.response.reasoning`,`ai.response.text`,`ai.response.toolCalls`,`ai.response.tool_calls`,`ai.response.tool_results`,`ai.toolCall.args`,`ai.toolCall.result`,`gen_ai.output.messages`,`gen_ai.tool.call.result`]);function isDeclined(e,t){return!t.recordInputs&&INPUT_CONTENT_ATTRIBUTES.has(e)?!0:!t.recordOutputs&&OUTPUT_CONTENT_ATTRIBUTES.has(e)}function withoutDeclinedContent(e,t){let n=Object.keys(e);if(!n.some(e=>isDeclined(e,t)))return;let r={};for(let i of n)isDeclined(i,t)||(r[i]=e[i]);return r}export{withoutDeclinedContent};
@@ -1 +1 @@
1
- import{createLogger,formatError}from"#internal/logging.js";import{contextStorage}from"#context/container.js";import{ConversationIdKey}from"#context/keys.js";import{readConversationId}from"#tracing/conversation-context.js";import{ContextAgentTraceStateStore}from"#tracing/agent-trace-context-store.js";import{registerInstrumentationRuntime}from"#instrumentation/runtime.js";import{trace}from"#compiled/@opentelemetry/api/index.js";import{createInstrumentationHooks}from"#instrumentation/lifecycle.js";import{AgentSpanIdGenerator}from"#tracing/agent-span-id-generator.js";import{hasConversationRelease}from"#tracing/local-traces.js";import{createAgentOtelInstrumentation}from"#tracing/agent-otel-provider.js";import{registerOtelPipeline}from"#tracing/otel-registration.js";const log=createLogger(`tracing.install-instrumentation-runtime`);function installInstrumentationRuntime(e){let t=[],n=[],r,flushSettledInvocations,i,a,runInContext=(e,t)=>t();if(e.collected.declared){r=registerOtelPipeline({pipeline:e.collected.pipeline,serviceName:e.serviceName});let o=createAgentOtelInstrumentation({frameworkVersion:e.frameworkVersion,idGenerator:r.idGenerator,recordInputs:e.collected.settings.recordInputs,recordOutputs:e.collected.settings.recordOutputs,samplesTrace:r.samplesTrace,stateStore:new ContextAgentTraceStateStore,tracer:trace.getTracer(`eve.agent`,e.frameworkVersion),tracePolicy:e.collected.settings.tracePolicy});t.push({...o.hook,stateNamespace:`internal:otel`}),flushSettledInvocations=async()=>{await o.hook.flush?.()},i=o.prepareSessionTrace,a=o.prepareTurnTrace,runInContext=o.runInContext;let s=e.collected.pipeline.spanProcessors.filter(isSpanProcessor).filter(hasConversationRelease);s.length>0&&n.push(sessionReleaseProvider(s))}let o=[...t,...e.providers,...n],s;return registerInstrumentationRuntime({flushSettledInvocations,forceFlush:async()=>{await settleAll(o.map(e=>()=>e.flush?.())),await settleAll(r===void 0?[]:[r.forceFlush])},hooks:createInstrumentationHooks({parallel:e.providers,serialAfter:n,serialBefore:t}),idGenerator:r?.idGenerator??new AgentSpanIdGenerator,instrumentationProviders:e.instrumentationProviders,otelSettings:e.collected.declared?e.collected.settings:void 0,ownsAgentSpans:r!==void 0,prepareSessionTrace:i,prepareTurnTrace:a,runtimeContextResolvers:e.runtimeContextResolvers,runInContext,samplesTrace:r?.samplesTrace,shutdown:()=>(s??=(async()=>{await settleAll(o.map(e=>()=>e.shutdown?.())),await settleAll(r===void 0?[]:[r.shutdown])})(),s)})}function isSpanProcessor(e){return e!==`auto`}function sessionReleaseProvider(e){let release=async t=>{let n=readConversationId(contextStorage.getStore()?.get(ConversationIdKey))??t.sessionId;n===t.sessionId&&await Promise.all(e.map(e=>e.releaseConversation(n)))};return{events:{"session.completed":release,"session.failed":release},name:`eve.conversation-release`,stateNamespace:`internal:conversation-release`}}async function settleAll(e){let t=await Promise.allSettled(e.map(async e=>e()));for(let e of t)e.status===`rejected`&&log.warn(`instrumentation drain failed`,{error:formatError(e.reason)})}export{installInstrumentationRuntime};
1
+ import{createLogger,formatError}from"#internal/logging.js";import{contextStorage}from"#context/container.js";import{ConversationIdKey}from"#context/keys.js";import{readConversationId}from"#tracing/conversation-context.js";import{ContextAgentTraceStateStore}from"#tracing/agent-trace-context-store.js";import{registerInstrumentationRuntime}from"#instrumentation/runtime.js";import{trace}from"#compiled/@opentelemetry/api/index.js";import{createInstrumentationHooks}from"#instrumentation/lifecycle.js";import{AgentSpanIdGenerator}from"#tracing/agent-span-id-generator.js";import{hasConversationRelease}from"#tracing/local-traces.js";import{createAgentOtelInstrumentation}from"#tracing/agent-otel-provider.js";import{registerOtelPipeline}from"#tracing/otel-registration.js";const log=createLogger(`tracing.install-instrumentation-runtime`);function installInstrumentationRuntime(e){let t=[],n=[],r,flushSettledInvocations,i,a,runInContext=(e,t)=>t();if(e.collected.declared){r=registerOtelPipeline({pipeline:e.collected.pipeline,serviceName:e.serviceName});let o=createAgentOtelInstrumentation({frameworkVersion:e.frameworkVersion,idGenerator:r.idGenerator,recordInputs:e.collected.settings.recordInputs,recordOutputs:e.collected.settings.recordOutputs,samplesTrace:r.samplesTrace,stateStore:new ContextAgentTraceStateStore,tracer:trace.getTracer(`eve.agent`,e.frameworkVersion),tracePolicy:e.collected.settings.tracePolicy});t.push({...o.hook,stateNamespace:`internal:otel`}),flushSettledInvocations=async()=>{await o.hook.flush?.()},i=o.prepareSessionTrace,a=o.prepareTurnTrace,runInContext=o.runInContext;let s=e.collected.pipeline.spanProcessors.filter(isSpanProcessor).filter(hasConversationRelease);s.length>0&&n.push(sessionReleaseProvider(s))}let o=[...t,...e.providers,...n],s;return registerInstrumentationRuntime({flushSettledInvocations,forceFlush:async()=>{await settleAll(o.map(e=>()=>e.flush?.())),await settleAll(r===void 0?[]:[r.forceFlush])},hooks:createInstrumentationHooks({parallel:e.providers,serialAfter:n,serialBefore:t}),idGenerator:r?.idGenerator??new AgentSpanIdGenerator,instrumentationProviders:e.instrumentationProviders,memoryOperations:r!==void 0||e.providers.some(hasMemoryOperationHandler),otelSettings:e.collected.declared?e.collected.settings:void 0,ownsAgentSpans:r!==void 0,prepareSessionTrace:i,prepareTurnTrace:a,runtimeContextResolvers:e.runtimeContextResolvers,runInContext,samplesTrace:r?.samplesTrace,shutdown:()=>(s??=(async()=>{await settleAll(o.map(e=>()=>e.shutdown?.())),await settleAll(r===void 0?[]:[r.shutdown])})(),s)})}function hasMemoryOperationHandler(e){return e.events?.[`memory.operation.started`]!==void 0||e.events?.[`memory.operation.completed`]!==void 0||e.events?.[`memory.operation.failed`]!==void 0}function isSpanProcessor(e){return e!==`auto`}function sessionReleaseProvider(e){let release=async t=>{let n=readConversationId(contextStorage.getStore()?.get(ConversationIdKey))??t.sessionId;n===t.sessionId&&await Promise.all(e.map(e=>e.releaseConversation(n)))};return{events:{"session.completed":release,"session.failed":release},name:`eve.conversation-release`,stateNamespace:`internal:conversation-release`}}async function settleAll(e){let t=await Promise.allSettled(e.map(async e=>e()));for(let e of t)e.status===`rejected`&&log.warn(`instrumentation drain failed`,{error:formatError(e.reason)})}export{installInstrumentationRuntime};
@@ -1,3 +1,3 @@
1
- import { n as defaultMessageReducer, t as useEveAgent } from "../chunks/use-eve-agent-BR8EpIOX.js";
1
+ import { n as defaultMessageReducer, t as useEveAgent } from "../chunks/use-eve-agent-CxPlg0KL.js";
2
2
 
3
3
  export { defaultMessageReducer, useEveAgent };
@@ -1,3 +1,3 @@
1
- import { t as useEveAgent } from "../chunks/use-eve-agent-BR8EpIOX.js";
1
+ import { t as useEveAgent } from "../chunks/use-eve-agent-CxPlg0KL.js";
2
2
 
3
3
  export { useEveAgent };
@@ -319,26 +319,6 @@ import { disableTool } from "eve/tools";
319
319
  export default disableTool();
320
320
  ```
321
321
 
322
- ### `task_update`
323
-
324
- `task_update` lets a background task report progress to its parent. It appears only in delegated task sessions.
325
-
326
- ```sh
327
- eve add tool/task_update
328
- ```
329
-
330
- ```ts title="agent/tools/task_update.ts"
331
- export { default } from "eve/tools/task_update";
332
- ```
333
-
334
- The framework behavior cannot be overridden. Re-export the definition above to restore it, or disable it:
335
-
336
- ```ts title="agent/tools/task_update.ts"
337
- import { disableTool } from "eve/tools";
338
-
339
- export default disableTool();
340
- ```
341
-
342
322
  ### `load_skill`
343
323
 
344
324
  `load_skill` pulls an on-demand [skill](../skills)'s instructions into the current turn. It appears only when the agent declares skills and adds no execution surface by itself.
@@ -97,10 +97,18 @@ Note: consider the privacy, confidentiality, and user-experience implications fo
97
97
 
98
98
  When a task explicitly requires conditional delivery and there is nothing new to report, the agent can finish with exactly `<eve-empty-delivery/>`. eve emits `message.completed` with `message: null` for that intentional silence. The marker must be the entire response, apart from surrounding whitespace; the HTML-escaped form `&lt;eve-empty-delivery/&gt;` is also accepted. A response that quotes the marker in prose or code is delivered normally.
99
99
 
100
- A delegated subagent publishes progress on its own child-session stream. The parent emits `subagent.called` with a `childSessionId`, which a client uses to attach. `subagent.completed` carries a working task receipt after admission; later updates and outcomes arrive as task-triggered `message.received` notifications.
100
+ A delegated subagent publishes progress on its own child-session stream. The parent emits `subagent.called` with a `childSessionId`, which a client uses to attach. `subagent.completed` carries a working task receipt after admission; terminal outcomes arrive as task-triggered `message.received` notifications.
101
101
 
102
102
  `step.failed` and `turn.failed` carry `{ code, message, details? }` for the failed fragment or turn, and `session.failed` is the terminal session-level variant. `turn.cancelled` is not a failure: the cancelled turn ends without any failure event, `session.waiting` follows, and the session accepts the next message normally. Whatever the turn streamed before cancellation stays on the stream. Durable history keeps the accepted user input and previously settled work, but discards incomplete assistant output and unfinished tool state. When a turn requested an output schema, the finalized payload lands on `result.completed` as `data.result` before the turn boundary. `authorization.required` carries the sign-in challenge (`data.authorization` may include `url`, `userCode`, `expiresAt`, `instructions`), and `authorization.completed` carries `data.outcome` (`"authorized" | "declined" | "failed" | "timed-out"`).
103
103
 
104
+ A provider response ending with `content-filter` fails with `MODEL_CALL_FAILED`,
105
+ `details.semanticErrorId: "model-response-content-filtered"`, and
106
+ `details.finishReason: "content-filter"`. Details also include the Gateway
107
+ `generationId` when available. eve does not retry the filtered response or emit
108
+ `message.completed` for its partial text; deltas already streamed remain visible.
109
+ Conversation sessions wait for another user message, while task-mode runs return
110
+ a failed result.
111
+
104
112
  ## The event envelope
105
113
 
106
114
  Alongside `type` and `data`, every event carries a `meta` envelope:
@@ -87,7 +87,7 @@ Most chat UIs only need `data.messages` and `status`. Drop down to `events` when
87
87
 
88
88
  `data.messages` are eve-owned `EveMessage[]`. Common text, reasoning, file, and dynamic-tool parts follow the [AI SDK `UIMessage`](https://ai-sdk.dev/docs/reference/ai-sdk-core/ui-message) rendering convention, but the types are not interchangeable. eve also exposes authorization and HITL metadata, and a file part's URL can be absent. Adapt those parts before passing messages to an API typed as `UIMessage[]`.
89
89
 
90
- When the root agent delegates, its stream emits `subagent.called` with the child's `childSessionId`, then `subagent.completed` after admission with a working task receipt. Later task notifications wake the parent with updates or the final result. Detailed child progress lives on the child session's stream instead of being flattened into the root `data.messages`. Use the lower-level [TypeScript client](../client/overview#sessions) to attach to that ID when your UI needs live subagent activity. See [What the parent sees](../../subagents#what-the-parent-sees) for the complete contract.
90
+ When the root agent delegates, its stream emits `subagent.called` with the child's `childSessionId`, then `subagent.completed` after admission with a working task receipt. Later task notifications wake the parent with completion, failure, or cancellation. Detailed child progress lives on the child session's stream instead of being flattened into the root `data.messages`. Use the lower-level [TypeScript client](../client/overview#sessions) to attach to that ID when your UI needs live subagent activity. See [What the parent sees](../../subagents#what-the-parent-sees) for the complete contract.
91
91
 
92
92
  ## Sending and streaming
93
93