eve 0.53.1 → 0.54.2
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.
- package/CHANGELOG.md +32 -0
- package/dist/src/channel/types.d.ts +2 -0
- package/dist/src/chunks/{use-eve-agent-BR8EpIOX.js → use-eve-agent-CxPlg0KL.js} +0 -1
- package/dist/src/chunks/{use-eve-agent-XnfjQt1Z.js → use-eve-agent-D-KQzzyW.js} +0 -1
- package/dist/src/cli/commands/trace-detail.js +1 -1
- package/dist/src/cli/commands/trace.d.ts +2 -2
- package/dist/src/cli/commands/trace.js +3 -3
- package/dist/src/cli/dev/tui/runner.js +1 -1
- package/dist/src/cli/dev/tui/tool-presentation.js +1 -1
- package/dist/src/cli/dev/tui/traces/trace-content.d.ts +1 -3
- package/dist/src/cli/dev/tui/traces/trace-content.js +2 -2
- package/dist/src/cli/dev/tui/traces/trace-conversation.d.ts +5 -5
- package/dist/src/cli/dev/tui/traces/trace-conversation.js +1 -1
- package/dist/src/cli/dev/tui/traces/trace-view.js +1 -1
- package/dist/src/cli/dev/tui/traces/trace-viewer-session.js +1 -1
- package/dist/src/client/agent-info-schema.d.ts +0 -1
- package/dist/src/client/agent-info-schema.js +1 -1
- package/dist/src/compiled/.vendor-stamp.json +1 -1
- package/dist/src/compiled/@opentelemetry/api/index.d.ts +1 -0
- package/dist/src/compiler/default-tool-policy.js +1 -1
- package/dist/src/compiler/extension-compatibility.d.ts +4 -4
- package/dist/src/compiler/extension-compatibility.js +1 -1
- package/dist/src/compiler/manifest.js +1 -1
- package/dist/src/context/dynamic-instruction-lifecycle.d.ts +2 -1
- package/dist/src/context/dynamic-instruction-lifecycle.js +1 -1
- package/dist/src/context/keys.d.ts +3 -1
- package/dist/src/context/keys.js +1 -1
- package/dist/src/context/memory-event-lifecycle.d.ts +2 -0
- package/dist/src/context/memory-event-lifecycle.js +1 -1
- package/dist/src/context/memory-lifecycle.d.ts +5 -0
- package/dist/src/context/memory-lifecycle.js +1 -1
- package/dist/src/eve-channel/index.js +1 -1
- package/dist/src/execution/cancelled-model-call-batch.js +1 -1
- package/dist/src/execution/cancelled-turn-message.js +1 -1
- package/dist/src/execution/compaction.d.ts +2 -2
- package/dist/src/execution/coordination-dispatch-shared.d.ts +0 -1
- package/dist/src/execution/coordination-dispatch-shared.js +1 -1
- package/dist/src/execution/coordination-dispatch-step.js +1 -1
- package/dist/src/execution/create-session-step.js +1 -1
- package/dist/src/execution/durable-session-store.d.ts +2 -2
- package/dist/src/execution/eve-workflow-attributes.d.ts +3 -3
- package/dist/src/execution/next-driver-action.d.ts +2 -0
- package/dist/src/execution/parked-delivery-wait.js +1 -1
- package/dist/src/execution/route-child-delivery.js +1 -1
- package/dist/src/execution/runtime-context.js +1 -1
- package/dist/src/execution/session.d.ts +0 -2
- package/dist/src/execution/session.js +2 -2
- package/dist/src/execution/tasks/parent/dispatch.d.ts +1 -12
- package/dist/src/execution/tasks/parent/dispatch.js +1 -1
- package/dist/src/execution/tasks/parent/hitl-proxy-steps.d.ts +5 -1
- package/dist/src/execution/tasks/parent/hitl-proxy-steps.js +1 -1
- package/dist/src/execution/tasks/parent/tool-execution.js +1 -1
- package/dist/src/execution/tools/sleep-workflow.js +1 -1
- package/dist/src/execution/tools/subagent/invoke-agent.d.ts +1 -2
- package/dist/src/execution/tools/subagent/invoke-agent.js +1 -1
- package/dist/src/execution/tools/subagent/invoke-step.d.ts +4 -0
- package/dist/src/execution/tools/subagent/invoke-step.js +1 -1
- package/dist/src/execution/tools/subagent/start.d.ts +2 -2
- package/dist/src/execution/tools/subagent/start.js +1 -1
- package/dist/src/execution/tools/subagent/task-agent-requests.js +1 -1
- package/dist/src/execution/tools/tasks.d.ts +1 -8
- package/dist/src/execution/tools/tasks.js +1 -1
- package/dist/src/execution/tools/todo.d.ts +2 -2
- package/dist/src/execution/tools/todo.js +2 -2
- package/dist/src/execution/turn-workflow.js +1 -1
- package/dist/src/execution/workflow-runtime.js +1 -1
- package/dist/src/execution/workflow-steps.js +1 -1
- package/dist/src/framework/sources/registry.js +1 -1
- package/dist/src/harness/compaction.js +1 -1
- package/dist/src/harness/coordination.js +1 -1
- package/dist/src/harness/current-messages.d.ts +7 -6
- package/dist/src/harness/current-messages.js +1 -1
- package/dist/src/harness/emission.js +1 -1
- package/dist/src/harness/execute-tool.d.ts +2 -4
- package/dist/src/harness/messages.d.ts +36 -0
- package/dist/src/harness/messages.js +1 -1
- package/dist/src/harness/model-call-error.d.ts +5 -0
- package/dist/src/harness/model-call-error.js +1 -1
- package/dist/src/harness/semantic-errors/rules/model-provider.js +1 -1
- package/dist/src/harness/session-limit-enforcement.d.ts +2 -15
- package/dist/src/harness/step-hooks.d.ts +2 -1
- package/dist/src/harness/step-hooks.js +1 -1
- package/dist/src/harness/tool-loop.js +2 -2
- package/dist/src/harness/types.d.ts +6 -4
- package/dist/src/instrumentation/ai-sdk-hook-bridge.js +1 -1
- package/dist/src/instrumentation/background-task-runtime.d.ts +18 -0
- package/dist/src/instrumentation/background-task-runtime.js +1 -0
- package/dist/src/instrumentation/channel-delivery.js +1 -1
- package/dist/src/instrumentation/content.js +1 -1
- package/dist/src/instrumentation/dispatch.js +1 -1
- package/dist/src/instrumentation/lifecycle.d.ts +19 -2
- package/dist/src/instrumentation/lifecycle.js +1 -1
- package/dist/src/instrumentation/memory.d.ts +72 -0
- package/dist/src/instrumentation/memory.js +1 -0
- package/dist/src/instrumentation/native-events.d.ts +7 -0
- package/dist/src/instrumentation/native-events.js +1 -1
- package/dist/src/instrumentation/parent-lineage.d.ts +2 -2
- package/dist/src/instrumentation/parent-lineage.js +1 -1
- package/dist/src/instrumentation/prepare-trace-context.d.ts +3 -11
- package/dist/src/instrumentation/prepare-trace-context.js +1 -1
- package/dist/src/instrumentation/principal-summary.d.ts +11 -0
- package/dist/src/instrumentation/principal-summary.js +1 -0
- package/dist/src/instrumentation/provider.d.ts +1 -0
- package/dist/src/instrumentation/runtime.d.ts +11 -7
- package/dist/src/instrumentation/runtime.js +1 -1
- package/dist/src/instrumentation/session-context.d.ts +22 -0
- package/dist/src/instrumentation/session-context.js +1 -0
- package/dist/src/instrumentation/state.d.ts +7 -2
- package/dist/src/instrumentation/state.js +1 -1
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/internal/logging.js +1 -1
- package/dist/src/internal/nitro/routes/channel-dispatch.js +1 -1
- package/dist/src/internal/nitro/routes/channel-request-instrumentation.d.ts +4 -5
- package/dist/src/internal/nitro/routes/channel-request-instrumentation.js +1 -1
- package/dist/src/protocol/baggage.d.ts +15 -2
- package/dist/src/protocol/baggage.js +1 -1
- package/dist/src/public/instrumentation/index.d.ts +5 -4
- package/dist/src/runtime/agent/bootstrap.d.ts +2 -2
- package/dist/src/runtime/agent/bootstrap.js +1 -1
- package/dist/src/self-modification/agent.js +1 -1
- package/dist/src/self-modification/extension/instructions.js +21 -20
- package/dist/src/self-modification/extension/tools/edit_file.js +1 -1
- package/dist/src/self-modification/extension/tools/search_registry.d.ts +1 -1
- package/dist/src/self-modification/extension/tools/search_registry.js +1 -1
- package/dist/src/setup/integrations/self-modification/setup.js +1 -1
- package/dist/src/setup/scaffold/create/project.js +1 -1
- package/dist/src/shared/action-types.d.ts +4 -0
- package/dist/src/shared/action-types.js +1 -1
- package/dist/src/shared/dispatch-action.d.ts +1 -1
- package/dist/src/shared/memory-state.js +1 -1
- package/dist/src/shared/serialized-observability-state.d.ts +12 -0
- package/dist/src/shared/serialized-observability-state.js +1 -0
- package/dist/src/subagents/callback-route.js +1 -1
- package/dist/src/subagents/callback-step.d.ts +0 -8
- package/dist/src/subagents/callback-step.js +1 -1
- package/dist/src/subagents/invocation.d.ts +9 -0
- package/dist/src/subagents/remote-dispatch.d.ts +3 -3
- package/dist/src/subagents/remote-dispatch.js +1 -1
- package/dist/src/subagents/start-local.d.ts +2 -6
- package/dist/src/subagents/start-local.js +1 -1
- package/dist/src/subagents/start-remote.d.ts +2 -8
- package/dist/src/subagents/start-remote.js +1 -1
- package/dist/src/subagents/tool.d.ts +3 -13
- package/dist/src/subagents/tool.js +1 -1
- package/dist/src/svelte/index.js +1 -1
- package/dist/src/svelte/use-eve-agent.js +1 -1
- package/dist/src/tasks/delivery-context.d.ts +12 -3
- package/dist/src/tasks/delivery-context.js +2 -2
- package/dist/src/tasks/session-index.d.ts +6 -3
- package/dist/src/tasks/session-index.js +1 -1
- package/dist/src/tasks/session-task-cohorts.d.ts +10 -2
- package/dist/src/tasks/session-task-cohorts.js +1 -1
- package/dist/src/tools/behavior.d.ts +1 -3
- package/dist/src/tools/framework/task-contract.d.ts +0 -4
- package/dist/src/tools/framework/task-contract.js +1 -1
- package/dist/src/tracing/agent-action-instrumentation.d.ts +3 -2
- package/dist/src/tracing/agent-action-instrumentation.js +1 -1
- package/dist/src/tracing/agent-approval-instrumentation.js +1 -1
- package/dist/src/tracing/agent-channel-delivery-instrumentation.d.ts +1 -6
- package/dist/src/tracing/agent-channel-delivery-instrumentation.js +1 -1
- package/dist/src/tracing/agent-invocation-coordinator.d.ts +28 -0
- package/dist/src/tracing/agent-invocation-coordinator.js +1 -0
- package/dist/src/tracing/agent-invocation-terminal.d.ts +18 -0
- package/dist/src/tracing/agent-invocation-terminal.js +1 -0
- package/dist/src/tracing/agent-memory-instrumentation.d.ts +13 -0
- package/dist/src/tracing/agent-memory-instrumentation.js +1 -0
- package/dist/src/tracing/agent-otel-attributes.d.ts +4 -0
- package/dist/src/tracing/agent-otel-attributes.js +1 -0
- package/dist/src/tracing/agent-otel-content.d.ts +4 -12
- package/dist/src/tracing/agent-otel-content.js +3 -3
- package/dist/src/tracing/agent-otel-provider.d.ts +4 -6
- package/dist/src/tracing/agent-otel-provider.js +2 -2
- package/dist/src/tracing/agent-otel-runtime-context.d.ts +9 -0
- package/dist/src/tracing/agent-otel-runtime-context.js +1 -1
- package/dist/src/tracing/agent-otel-session-context.d.ts +4 -3
- package/dist/src/tracing/agent-otel-session-context.js +1 -1
- package/dist/src/tracing/agent-otel-usage.d.ts +4 -10
- package/dist/src/tracing/agent-otel-usage.js +1 -1
- package/dist/src/tracing/agent-span-contract.d.ts +26 -0
- package/dist/src/tracing/agent-span-contract.js +1 -0
- package/dist/src/tracing/agent-span-error.d.ts +3 -0
- package/dist/src/tracing/agent-span-error.js +1 -0
- package/dist/src/tracing/agent-span-id-generator.d.ts +3 -0
- package/dist/src/tracing/agent-span-id-generator.js +1 -1
- package/dist/src/tracing/agent-tool-instrumentation.js +1 -1
- package/dist/src/tracing/agent-trace-context-codec.d.ts +12 -0
- package/dist/src/tracing/agent-trace-context-codec.js +1 -0
- package/dist/src/tracing/agent-trace-context-store.d.ts +35 -8
- package/dist/src/tracing/agent-trace-context-store.js +1 -1
- package/dist/src/tracing/agent-trace-span-processor.d.ts +5 -7
- package/dist/src/tracing/agent-trace-span-processor.js +1 -1
- package/dist/src/tracing/agent-trace-state.d.ts +43 -3
- package/dist/src/tracing/agent-trace-state.js +1 -1
- package/dist/src/tracing/bounded-error.d.ts +1 -0
- package/dist/src/tracing/bounded-error.js +1 -0
- package/dist/src/tracing/content-attributes.js +1 -1
- package/dist/src/tracing/content-span-processor.js +1 -1
- package/dist/src/tracing/conversation-context.d.ts +4 -0
- package/dist/src/tracing/conversation-context.js +1 -0
- package/dist/src/tracing/error-content-context.d.ts +3 -0
- package/dist/src/tracing/error-content-context.js +1 -0
- package/dist/src/tracing/install-instrumentation-runtime.js +1 -1
- package/dist/src/tracing/local-trace-reader.d.ts +6 -6
- package/dist/src/tracing/local-trace-reader.js +1 -1
- package/dist/src/tracing/local-traces.d.ts +6 -8
- package/dist/src/tracing/local-traces.js +1 -1
- package/dist/src/tracing/otel-declaration.d.ts +5 -3
- package/dist/src/tracing/otel-registration.d.ts +2 -1
- package/dist/src/tracing/otel-registration.js +1 -1
- package/dist/src/tracing/telemetry-budget.d.ts +4 -0
- package/dist/src/tracing/telemetry-budget.js +1 -0
- package/dist/src/vue/index.js +1 -1
- package/dist/src/vue/use-eve-agent.js +1 -1
- package/docs/concepts/built-in-tools.md +0 -20
- package/docs/concepts/sessions-runs-and-streaming.md +9 -1
- package/docs/guides/frontend/overview.mdx +1 -1
- package/docs/guides/instrumentation-providers.md +5 -0
- package/docs/guides/instrumentation.md +179 -23
- package/docs/guides/remote-agents.md +11 -0
- package/docs/reference/cli.md +16 -14
- package/docs/subagents/index.mdx +15 -10
- package/package.json +1 -6
- package/dist/src/execution/tasks/child/update-step.d.ts +0 -6
- package/dist/src/execution/tasks/child/update-step.js +0 -1
- package/dist/src/execution/tasks/child/update.d.ts +0 -8
- package/dist/src/execution/tasks/child/update.js +0 -1
- package/dist/src/public/tools/task-update.d.ts +0 -1
- package/dist/src/public/tools/task-update.js +0 -1
- package/dist/src/tools/framework/task-update.d.ts +0 -5
- package/dist/src/tools/framework/task-update.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{contextStorage}from"#context/container.js";import{rememberInstrumentationActionScope,rememberInstrumentationInputScope,takeInstrumentationActionScopeForCall,takeInstrumentationInputScope}from"#instrumentation/state.js";import{RuntimeActionSettlementTimesKey}from"#harness/runtime-action-settlement-state.js";import{actionIdempotencyKey,inputIdempotencyKey,sessionIdempotencyKey,turnIdempotencyKey}from"#instrumentation/lifecycle.js";import{instrumentChannelDelivery}from"#instrumentation/channel-delivery.js";function createInstrumentationHandleEvent(e){if(e.hooks===void 0)return e.handleEvent;if(e.handleEvent===void 0)return;let t=e.handleEvent,n=e.hooks,r=new Set,i=new Set,a=e.turnId;return async(o,s)=>{await t(o,s);let c=toLifecycleEvent(o,e,a);if(o.type===`turn.started`&&(a=o.data.turnId),o.type===`turn.cancelled`||o.type===`turn.completed`||o.type===`turn.failed`||o.type===`session.completed`||o.type===`session.failed`){let e=contextStorage.getStore();e!==void 0&&await instrumentChannelDelivery({ctx:e,error:o.type===`turn.failed`||o.type===`session.failed`?Error(o.data.message):void 0,errorCode:o.type===`turn.failed`||o.type===`session.failed`?o.data.code:void 0,hooks:n,includeTurn:o.type===`turn.cancelled`||o.type===`turn.completed`||o.type===`turn.failed`,outcome:o.type===`turn.failed`||o.type===`session.failed`?`failed`:o.type===`turn.cancelled`?`cancelled`:`completed`})}c!==void 0&&await n.publish(c),o.type===`actions.requested`?await publishActionStarts(o,e,n,r):o.type===`action.result`?await publishActionTerminal(o,e,n):o.type===`input.requested`&&await publishInputStarts(o,e,n,i)}}async function publishInputStarts(e,t,n,r){let i=t.getAttemptScope?.();if(i===void 0)return;let a=n.capturesOutputs??n.capturesContent;for(let o of e.data.requests){let s=inputIdempotencyKey(t.sessionId,e.data.turnId,o.requestId);r.has(s)||(r.add(s),rememberInstrumentationInputScope(s,i),await n.publish(Object.freeze({action:Object.freeze({callId:o.action.callId,name:o.action.toolName}),idempotencyKey:s,kind:o.kind,request:a?Object.freeze({allowFreeform:o.allowFreeform,display:o.display,options:o.options,prompt:o.prompt}):void 0,requestId:o.requestId,scope:i,type:`input.requested`})))}}async function publishInputResolutions(e){let t=e.hooks.capturesInputs??e.hooks.capturesContent;for(let n of e.batch.inputs){let r=inputIdempotencyKey(e.sessionId,e.batch.event.turnId,n.request.requestId),i=takeInstrumentationInputScope(r);i!==void 0&&await e.hooks.publish(Object.freeze({idempotencyKey:r,kind:n.request.kind,outcome:n.outcome,requestId:n.request.requestId,response:!t||n.response===void 0?void 0:Object.freeze({optionId:n.response.optionId,text:n.response.text}),scope:i,type:`input.resolved`}))}}async function publishActionStarts(e,t,n,r){let i=t.getAttemptScope?.();if(i===void 0)return;let a=n.capturesInputs??n.capturesContent;for(let o of e.data.actions){let s=actionIdempotencyKey(t.sessionId,e.data.turnId,o.callId);r.has(s)||(r.add(s),rememberInstrumentationActionScope(s,i),await n.publish(Object.freeze({callId:o.callId,idempotencyKey:s,input:a?o.input:void 0,kind:o.kind===`workflow-tool-call`?`tool-call`:o.kind,name:actionName(o),scope:i,type:`action.started`})))}}async function publishActionTerminal(e,t,n){let r=
|
|
1
|
+
import{contextStorage}from"#context/container.js";import{findInstrumentationActionScopeForCall,rememberInstrumentationActionScope,rememberInstrumentationInputScope,takeInstrumentationActionScopeForCall,takeInstrumentationActionScopeForTask,takeInstrumentationInputScope}from"#instrumentation/state.js";import{deriveTaskId}from"#tasks/task-id.js";import{isRuntimeWorkflowToolAction}from"#shared/action-types.js";import{RuntimeActionSettlementTimesKey}from"#harness/runtime-action-settlement-state.js";import{actionIdempotencyKey,inputIdempotencyKey,sessionIdempotencyKey,turnIdempotencyKey}from"#instrumentation/lifecycle.js";import{instrumentChannelDelivery}from"#instrumentation/channel-delivery.js";function createInstrumentationHandleEvent(e){if(e.hooks===void 0)return e.handleEvent;if(e.handleEvent===void 0)return;let t=e.handleEvent,n=e.hooks,r=new Set,i=new Set,a=e.turnId;return async(o,s)=>{await t(o,s);let c=toLifecycleEvent(o,e,a);if(o.type===`turn.started`&&(a=o.data.turnId),o.type===`turn.cancelled`||o.type===`turn.completed`||o.type===`turn.failed`||o.type===`session.completed`||o.type===`session.failed`){let e=contextStorage.getStore();e!==void 0&&await instrumentChannelDelivery({ctx:e,error:o.type===`turn.failed`||o.type===`session.failed`?Error(o.data.message):void 0,errorCode:o.type===`turn.failed`||o.type===`session.failed`?o.data.code:void 0,hooks:n,includeTurn:o.type===`turn.cancelled`||o.type===`turn.completed`||o.type===`turn.failed`||o.type===`session.failed`,outcome:o.type===`turn.failed`||o.type===`session.failed`?`failed`:o.type===`turn.cancelled`?`cancelled`:`completed`})}c!==void 0&&await n.publish(c),o.type===`actions.requested`?await publishActionStarts(o,e,n,r):o.type===`action.result`?await publishActionTerminal(o,e,n):o.type===`input.requested`&&await publishInputStarts(o,e,n,i)}}async function publishInputStarts(e,t,n,r){let i=t.getAttemptScope?.();if(i===void 0)return;let a=n.capturesOutputs??n.capturesContent;for(let o of e.data.requests){let s=inputIdempotencyKey(t.sessionId,e.data.turnId,o.requestId);r.has(s)||(r.add(s),rememberInstrumentationInputScope(s,i),await n.publish(Object.freeze({action:Object.freeze({callId:o.action.callId,name:o.action.toolName}),idempotencyKey:s,kind:o.kind,request:a?Object.freeze({allowFreeform:o.allowFreeform,display:o.display,options:o.options,prompt:o.prompt}):void 0,requestId:o.requestId,scope:i,type:`input.requested`})))}}async function publishInputResolutions(e){let t=e.hooks.capturesInputs??e.hooks.capturesContent;for(let n of e.batch.inputs){let r=inputIdempotencyKey(e.sessionId,e.batch.event.turnId,n.request.requestId),i=takeInstrumentationInputScope(r);i!==void 0&&await e.hooks.publish(Object.freeze({idempotencyKey:r,kind:n.request.kind,outcome:n.outcome,requestId:n.request.requestId,response:!t||n.response===void 0?void 0:Object.freeze({optionId:n.response.optionId,text:n.response.text}),scope:i,type:`input.resolved`}))}}async function publishActionStarts(e,t,n,r){let i=t.getAttemptScope?.();if(i===void 0)return;let a=n.capturesInputs??n.capturesContent;for(let o of e.data.actions){let s=actionIdempotencyKey(t.sessionId,e.data.turnId,o.callId);r.has(s)||(r.add(s),rememberInstrumentationActionScope(s,i),await n.publish(Object.freeze({callId:o.callId,idempotencyKey:s,input:a?o.input:void 0,...isRuntimeWorkflowToolAction(o)?{isWorkflowTool:!0}:void 0,kind:o.kind===`workflow-tool-call`?`tool-call`:o.kind,name:actionName(o),scope:i,type:`action.started`})))}}async function publishActionTerminal(e,t,n){let r=findInstrumentationActionScopeForCall(t.sessionId,e.data.result.callId);if(r===void 0)return;let i=readBackgroundTaskReceipt(e.data.result,r);if(e.data.status===`completed`&&i!==void 0)return;takeInstrumentationActionScopeForCall(t.sessionId,e.data.result.callId);let{idempotencyKey:a,scope:o}=r,s=n.capturesOutputs??n.capturesContent;if(e.data.status===`completed`){await n.publish(Object.freeze({acceptedAtMs:contextStorage.getStore()?.get(RuntimeActionSettlementTimesKey)?.[e.data.result.callId],idempotencyKey:a,outcome:`completed`,output:Object.freeze(s?{output:e.data.result.output,type:`result`}:{type:`result`}),scope:o,type:`action.completed`,usage:actionUsage(e.data.result)}));return}let c=s?e.data.error===void 0?e.data.result.output:Object.assign(Error(e.data.error.message),{code:e.data.error.code}):void 0;await n.publish(Object.freeze({acceptedAtMs:contextStorage.getStore()?.get(RuntimeActionSettlementTimesKey)?.[e.data.result.callId],error:c,errorCode:e.data.error?.code,idempotencyKey:a,outcome:e.data.status,scope:o,type:`action.failed`}))}async function publishBackgroundTaskSettlements(e){let t=e.hooks.capturesOutputs??e.hooks.capturesContent,n=e.acceptedAtMs??Date.now();for(let r of e.views){if(r.status!==`completed`&&r.status!==`failed`&&r.status!==`cancelled`)continue;let i=takeInstrumentationActionScopeForTask(r.taskId);if(i!==void 0){if(r.status===`completed`){await e.hooks.publish(Object.freeze({acceptedAtMs:n,idempotencyKey:i.idempotencyKey,outcome:`completed`,output:Object.freeze(t?{output:r.lastOutput.data,type:`result`}:{type:`result`}),scope:i.scope,type:`action.completed`,usage:instrumentationUsage(r.usage)}));continue}await e.hooks.publish(Object.freeze({acceptedAtMs:n,error:r.status===`failed`?t?r.lastOutput.data:void 0:Error(`The background task was cancelled.`),errorCode:r.status===`failed`?`BACKGROUND_TASK_FAILED`:`BACKGROUND_TASK_CANCELLED`,idempotencyKey:i.idempotencyKey,outcome:r.status,scope:i.scope,type:`action.failed`}))}}}function readBackgroundTaskReceipt(e,t){let n=e.output;if(typeof n!=`object`||!n||Array.isArray(n)||Reflect.get(n,`status`)!==`working`)return;let r=Reflect.get(n,`taskId`);return typeof r==`string`&&r===deriveTaskId({callId:e.callId,parentSessionId:t.scope.sessionId,parentTurnId:t.scope.turnId})?{taskId:r}:void 0}function instrumentationUsage(e){if(e!==void 0)return{inputTokenDetails:{cacheReadTokens:e.cacheReadTokens,cacheWriteTokens:e.cacheWriteTokens},inputTokens:e.inputTokens,outputTokens:e.outputTokens}}function actionUsage(e){if(e.kind===`subagent-result`&&e.origin===`child`&&e.usage!==void 0)return{inputTokenDetails:{cacheReadTokens:e.usage.cacheReadTokens,cacheWriteTokens:e.usage.cacheWriteTokens},inputTokens:e.usage.inputTokens,outputTokens:e.usage.outputTokens}}function actionName(e){return e.kind===`tool-call`||e.kind===`workflow-tool-call`?e.toolName:e.kind===`load-skill`?`load_skill`:e.name}function toLifecycleEvent(e,t,n){switch(e.type){case`session.started`:return{agentName:t.agentName,channelAudience:t.channelAudience,channelKind:t.channelKind,idempotencyKey:sessionIdempotencyKey(t.sessionId),parentLineage:t.parentLineage,parentTraceContext:t.parentTraceContext,rootSessionId:t.rootSessionId??t.sessionId,sessionId:t.sessionId,type:`session.started`};case`session.completed`:case`session.waiting`:return{idempotencyKey:sessionIdempotencyKey(t.sessionId),sessionId:t.sessionId,turnId:n,type:e.type};case`session.failed`:return{error:Error(e.data.message),idempotencyKey:sessionIdempotencyKey(t.sessionId),sessionId:t.sessionId,turnId:n,type:`session.failed`};case`turn.started`:return{idempotencyKey:turnIdempotencyKey(t.sessionId,e.data.turnId),parentLineage:t.parentLineage,parentTraceContext:t.parentTraceContext,rootSessionId:t.rootSessionId??t.sessionId,sequence:e.data.sequence,sessionId:t.sessionId,turnId:e.data.turnId,type:`turn.started`};case`turn.completed`:case`turn.cancelled`:return{idempotencyKey:turnIdempotencyKey(t.sessionId,e.data.turnId),sessionId:t.sessionId,turnId:e.data.turnId,type:e.type};case`turn.failed`:return{error:Error(e.data.message),idempotencyKey:turnIdempotencyKey(t.sessionId,e.data.turnId),sessionId:t.sessionId,turnId:e.data.turnId,type:`turn.failed`};default:return}}export{createInstrumentationHandleEvent,publishBackgroundTaskSettlements,publishInputResolutions};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { SessionParent } from "#channel/types.js";
|
|
1
|
+
import type { SessionCallback, SessionParent } from "#channel/types.js";
|
|
2
2
|
import type { InstrumentationParentLineage } from "#instrumentation/lifecycle.js";
|
|
3
3
|
/**
|
|
4
4
|
* Resolves the dispatch that created the running session, if any. Dispatch
|
|
@@ -8,4 +8,4 @@ import type { InstrumentationParentLineage } from "#instrumentation/lifecycle.js
|
|
|
8
8
|
*/
|
|
9
9
|
export declare function resolveParentLineage(parent: SessionParent | undefined, adapter: {
|
|
10
10
|
readonly state?: unknown;
|
|
11
|
-
} | undefined): InstrumentationParentLineage | undefined;
|
|
11
|
+
} | undefined, callback?: SessionCallback): InstrumentationParentLineage | undefined;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isSubagentAdapterState}from"#subagents/adapter-state.js";function resolveParentLineage(e,t){if(e===void 0)return;let
|
|
1
|
+
import{isSubagentAdapterState}from"#subagents/adapter-state.js";function resolveParentLineage(e,t,n){if(e===void 0)return;let r=t?.state,i=isSubagentAdapterState(r)?r:void 0;return{callId:n?.callId??i?.callId??e.callId,sessionId:e.sessionId,subagentName:i?.subagentName,turnId:e.turn.id}}export{resolveParentLineage};
|
|
@@ -1,24 +1,16 @@
|
|
|
1
1
|
import type { RuntimeTraceContext } from "#protocol/message.js";
|
|
2
|
-
import type {
|
|
3
|
-
import type { ChannelAudience } from "#shared/channel-audience.js";
|
|
4
|
-
import { type SessionTraceSeed } from "#context/keys.js";
|
|
2
|
+
import type { InstrumentationSessionStartedEvent, InstrumentationTraceSeed, InstrumentationTurnStartedEvent } from "#instrumentation/lifecycle.js";
|
|
5
3
|
/** Prepares native session/turn tracing before their durable stream events. */
|
|
6
4
|
export interface PrepareTurnTraceContextInput {
|
|
7
|
-
readonly agentName?: string;
|
|
8
|
-
readonly channelAudience?: ChannelAudience;
|
|
9
|
-
readonly channelType?: string;
|
|
10
5
|
readonly instrumentation?: {
|
|
11
6
|
readonly prepareSessionTrace?: (event: InstrumentationSessionStartedEvent) => Promise<InstrumentationTraceSeed>;
|
|
12
7
|
readonly prepareTurnTrace?: (event: InstrumentationTurnStartedEvent) => Promise<InstrumentationTraceSeed>;
|
|
13
8
|
};
|
|
14
|
-
readonly
|
|
15
|
-
readonly
|
|
16
|
-
readonly rootSessionId: string;
|
|
9
|
+
readonly session: Omit<InstrumentationSessionStartedEvent, "idempotencyKey" | "type">;
|
|
10
|
+
readonly principals?: Pick<InstrumentationTurnStartedEvent, "currentPrincipal" | "initiatorPrincipal">;
|
|
17
11
|
readonly sequence: number;
|
|
18
|
-
readonly sessionId: string;
|
|
19
12
|
readonly sessionStarted: boolean;
|
|
20
13
|
readonly traceContext?: RuntimeTraceContext;
|
|
21
|
-
readonly traceSeed?: SessionTraceSeed;
|
|
22
14
|
readonly turnId: string;
|
|
23
15
|
}
|
|
24
16
|
export declare function prepareTurnTraceContext(input: PrepareTurnTraceContextInput): Promise<RuntimeTraceContext | undefined>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createLogger,formatError}from"#internal/logging.js";import{contextStorage}from"#context/container.js";import{SessionTraceSeedKey}from"#context/keys.js";import{sessionIdempotencyKey,turnIdempotencyKey}from"#instrumentation/lifecycle.js";const log=createLogger(`harness.prepare-trace-context`);async function prepareTurnTraceContext(e){let t;if(!e.sessionStarted&&e.instrumentation?.prepareSessionTrace!==void 0)try{t=await e.instrumentation.prepareSessionTrace({
|
|
1
|
+
import{createLogger,formatError}from"#internal/logging.js";import{contextStorage}from"#context/container.js";import{SessionTraceSeedKey}from"#context/keys.js";import{sessionIdempotencyKey,turnIdempotencyKey}from"#instrumentation/lifecycle.js";const log=createLogger(`harness.prepare-trace-context`);async function prepareTurnTraceContext(e){let t,{channelAudience:n,channelKind:r,channelType:i,traceSeed:a,...o}=e.session;if(!e.sessionStarted&&e.instrumentation?.prepareSessionTrace!==void 0)try{t=await e.instrumentation.prepareSessionTrace({...o,channelAudience:n,channelKind:r,channelType:i,idempotencyKey:sessionIdempotencyKey(o.sessionId),traceSeed:a,type:`session.started`})}catch(e){warn(`session.started`,e)}if(e.instrumentation?.prepareTurnTrace!==void 0)try{t=await e.instrumentation.prepareTurnTrace({...o,...e.principals,idempotencyKey:turnIdempotencyKey(o.sessionId,e.turnId),sequence:e.sequence,turnId:e.turnId,type:`turn.started`})}catch(e){warn(`turn.started`,e)}return a===void 0&&t?.decision!==void 0&&contextStorage.getStore()?.set(SessionTraceSeedKey,t),e.traceContext??t}function warn(e,t){log.warn(`instrumentation trace preparation failed`,{boundary:e,error:formatError(t)})}export{prepareTurnTraceContext};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { SessionAuthContext } from "#channel/types.js";
|
|
2
|
+
import type { ContextReader } from "#context/key.js";
|
|
3
|
+
import { type InstrumentationPrincipalSummary } from "#instrumentation/lifecycle.js";
|
|
4
|
+
import type { ChannelAudience } from "#shared/channel-audience.js";
|
|
5
|
+
import type { InstrumentationDecision } from "#shared/instrumentation-decision.js";
|
|
6
|
+
export declare function summarizeInstrumentationPrincipal(principal: SessionAuthContext | null | undefined, audience: ChannelAudience): InstrumentationPrincipalSummary | undefined;
|
|
7
|
+
export declare function applyPrincipalTraceDecision(principal: InstrumentationPrincipalSummary | undefined, decision: InstrumentationDecision | undefined): InstrumentationPrincipalSummary | undefined;
|
|
8
|
+
export declare function readInstrumentationPrincipals(context: ContextReader, audience: ChannelAudience, decision?: InstrumentationDecision): {
|
|
9
|
+
readonly currentPrincipal?: InstrumentationPrincipalSummary;
|
|
10
|
+
readonly initiatorPrincipal?: InstrumentationPrincipalSummary;
|
|
11
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{AuthKey,InitiatorAuthKey}from"#context/keys.js";import{shouldCaptureInstrumentationContent}from"#shared/instrumentation-content.js";import{isInstrumentationPrincipalType}from"#instrumentation/lifecycle.js";import{resolveTracePolicyDecision}from"#shared/trace-policy.js";import{boundedPrincipalId}from"#tracing/telemetry-budget.js";function summarizeInstrumentationPrincipal(e,t){if(e===void 0)return;if(e===null)return{type:`none`};let n=isInstrumentationPrincipalType(e.principalType)&&e.principalType!==`none`?e.principalType:`other`,r=shouldCaptureInstrumentationContent(t)?boundedPrincipalId(e.principalId):void 0;return r===void 0?{type:n}:{id:r,type:n}}function applyPrincipalTraceDecision(e,t){if(e!==void 0)return e.type!==`none`&&t?.action===`record`&&t.recordInputs&&t.recordOutputs?e:{type:e.type}}function readInstrumentationPrincipals(e,t,n=resolveTracePolicyDecision(!0,t)){return{currentPrincipal:applyPrincipalTraceDecision(summarizeInstrumentationPrincipal(e.get(AuthKey),t),n),initiatorPrincipal:applyPrincipalTraceDecision(summarizeInstrumentationPrincipal(e.get(InitiatorAuthKey),t),n)}}export{applyPrincipalTraceDecision,readInstrumentationPrincipals,summarizeInstrumentationPrincipal};
|
|
@@ -9,6 +9,7 @@ import type { JsonValue } from "#shared/json.js";
|
|
|
9
9
|
import type { InstrumentationCapture, TraceCapturePolicy } from "#shared/trace-policy.js";
|
|
10
10
|
export type { JsonValue } from "#shared/json.js";
|
|
11
11
|
export type { InstrumentationActionCompletedEvent, InstrumentationActionFailedEvent, InstrumentationActionKind, InstrumentationActionOutcome, InstrumentationActionOutput, InstrumentationActionStartedEvent, InstrumentationAttemptScope, InstrumentationChannelDeliveryInput, InstrumentationChannelDeliveryOutcome, InstrumentationChannelDeliveryRef, InstrumentationChannelDeliveryStartedEvent, InstrumentationChannelDeliveryTerminalEvent, InstrumentationContentPart, InstrumentationEvent, InstrumentationInputKind, InstrumentationInputOption, InstrumentationInputOutcome, InstrumentationInputRequest, InstrumentationInputRequestedEvent, InstrumentationInputResolvedEvent, InstrumentationInputResponse, InstrumentationModelCallCompletedEvent, InstrumentationModelCallFailedEvent, InstrumentationModelCallStartedEvent, InstrumentationModelRef, InstrumentationOperationRef, InstrumentationParentLineage, InstrumentationSessionFailedEvent, InstrumentationSessionSettledEvent, InstrumentationSessionStartedEvent, InstrumentationSessionTransitionEvent, InstrumentationStepAttemptMetadataEvent, InstrumentationStepAttemptCompletedEvent, InstrumentationStepAttemptFailedEvent, InstrumentationStepAttemptStartedEvent, InstrumentationStepAttemptTerminalEvent, InstrumentationToolCallCompletedEvent, InstrumentationToolCallFailedEvent, InstrumentationToolCallStartedEvent, InstrumentationToolOutput, InstrumentationTraceContext, InstrumentationTurnFailedEvent, InstrumentationTurnSettledEvent, InstrumentationTurnStartedEvent, InstrumentationTurnTerminalEvent, InstrumentationUsage, } from "#instrumentation/lifecycle.js";
|
|
12
|
+
export type { InstrumentationMemoryOperation, InstrumentationMemoryOperationCompletedEvent, InstrumentationMemoryOperationEvent, InstrumentationMemoryOperationFailedEvent, InstrumentationMemoryOperationName, InstrumentationMemoryOperationStartedEvent, InstrumentationMemoryOperationTerminalEvent, InstrumentationMemoryRecord, } from "#instrumentation/memory.js";
|
|
12
13
|
export type { InstrumentationCapture, TraceCaptureContext, TraceCapturePolicy, TracePolicyDecision, } from "#shared/trace-policy.js";
|
|
13
14
|
/**
|
|
14
15
|
* Marks a value as having come from `defineInstrumentation` or a built-in
|
|
@@ -3,15 +3,17 @@ import type { InstrumentationEvents } from "#public/instrumentation/index.js";
|
|
|
3
3
|
import type { InstrumentationAttemptScope, InstrumentationContextRunner, InstrumentationHooks, InstrumentationSessionStartedEvent, InstrumentationTraceContext, InstrumentationTraceSeed, InstrumentationTurnStartedEvent } from "#instrumentation/lifecycle.js";
|
|
4
4
|
import { type BuildTelemetryRuntimeContextInput } from "#instrumentation/runtime-context.js";
|
|
5
5
|
import { type CreateInstrumentationHandleEventInput } from "#instrumentation/native-events.js";
|
|
6
|
+
import { type BackgroundTaskInstrumentation } from "#instrumentation/background-task-runtime.js";
|
|
6
7
|
import type { ResolvedInputBatch } from "#harness/input-requests.js";
|
|
7
8
|
import type { HandleEventFn } from "#harness/types.js";
|
|
8
9
|
import { type ChannelDeliveryStartInstrumentation, type ChannelDeliveryTerminalInstrumentation } from "#instrumentation/channel-delivery.js";
|
|
9
10
|
import { type PrepareTurnTraceContextInput } from "#instrumentation/prepare-trace-context.js";
|
|
10
11
|
import type { RuntimeTraceContext } from "#protocol/message.js";
|
|
11
|
-
import
|
|
12
|
+
import { AgentSpanIdGenerator } from "#tracing/agent-span-id-generator.js";
|
|
12
13
|
import type { OtelHarnessSettings, RuntimeContextResolver } from "#tracing/otel-declaration.js";
|
|
13
14
|
import { type ContextContainer } from "#context/container.js";
|
|
14
|
-
import type
|
|
15
|
+
import { type MemoryInstrumentation } from "#instrumentation/memory.js";
|
|
16
|
+
import type { AgentSamplingOperation } from "#tracing/agent-span-contract.js";
|
|
15
17
|
interface InstrumentedStepSession {
|
|
16
18
|
readonly sessionId: string;
|
|
17
19
|
readonly state?: Readonly<Record<string, unknown>>;
|
|
@@ -24,7 +26,7 @@ export interface InstrumentationStepScope<TSession> {
|
|
|
24
26
|
readonly stepIndex: number;
|
|
25
27
|
readonly turnId: string;
|
|
26
28
|
}) => PreparedInstrumentationAttempt;
|
|
27
|
-
readonly preparePreamble: (input: Omit<PrepareTurnTraceContextInput, "
|
|
29
|
+
readonly preparePreamble: (input: Omit<PrepareTurnTraceContextInput, "instrumentation" | "principals" | "session">) => Promise<RuntimeTraceContext | undefined>;
|
|
28
30
|
readonly publishInputResolutions: (input: {
|
|
29
31
|
readonly batch: ResolvedInputBatch;
|
|
30
32
|
readonly sessionId: string;
|
|
@@ -50,10 +52,13 @@ export interface BoundInstrumentationSession {
|
|
|
50
52
|
}
|
|
51
53
|
/** Process-wide runtime consumed by every harness execution surface. */
|
|
52
54
|
export interface InstrumentationRuntime {
|
|
55
|
+
/** Materializes settled invocation spans without draining the exporter pipeline. */
|
|
56
|
+
readonly flushSettledInvocations?: () => Promise<void>;
|
|
53
57
|
readonly forceFlush: () => Promise<void>;
|
|
54
58
|
readonly hooks: InstrumentationHooks;
|
|
55
59
|
readonly idGenerator?: AgentSpanIdGenerator;
|
|
56
60
|
readonly instrumentationProviders?: boolean;
|
|
61
|
+
readonly memoryOperations?: boolean;
|
|
57
62
|
readonly ownsAgentSpans?: boolean;
|
|
58
63
|
readonly prepareSessionTrace?: (event: InstrumentationSessionStartedEvent) => Promise<InstrumentationTraceSeed>;
|
|
59
64
|
readonly prepareTurnTrace?: (event: InstrumentationTurnStartedEvent) => Promise<InstrumentationTraceSeed>;
|
|
@@ -61,7 +66,7 @@ export interface InstrumentationRuntime {
|
|
|
61
66
|
readonly runtimeContextResolvers?: readonly RuntimeContextResolver[];
|
|
62
67
|
readonly runInContext: InstrumentationContextRunner;
|
|
63
68
|
/** Whether the installed OTel sampler would record a trace with this id. */
|
|
64
|
-
readonly samplesTrace?: (traceId: string) => boolean;
|
|
69
|
+
readonly samplesTrace?: (traceId: string, operation?: AgentSamplingOperation) => boolean;
|
|
65
70
|
readonly shutdown: () => Promise<void>;
|
|
66
71
|
stepStartedRuntimeContextResolver?: InstrumentationEvents["step.started"];
|
|
67
72
|
}
|
|
@@ -74,13 +79,14 @@ export interface SessionInstrumentation {
|
|
|
74
79
|
readonly session: TSession;
|
|
75
80
|
}, execute: (scope: InstrumentationStepScope<TSession>) => Promise<TResult>) => Promise<TResult>;
|
|
76
81
|
}
|
|
77
|
-
export interface ExecutionInstrumentation {
|
|
82
|
+
export interface ExecutionInstrumentation extends BackgroundTaskInstrumentation {
|
|
78
83
|
readonly createHandleEvent: (input: {
|
|
79
84
|
readonly handleEvent?: HandleEventFn;
|
|
80
85
|
readonly turnId?: string;
|
|
81
86
|
}) => HandleEventFn | undefined;
|
|
82
87
|
readonly flush: () => Promise<void>;
|
|
83
88
|
readonly instrumentChannelDelivery: (input: Omit<ChannelDeliveryStartInstrumentation, "hooks" | "policyAgentName"> | Omit<ChannelDeliveryTerminalInstrumentation, "hooks">) => Promise<void>;
|
|
89
|
+
readonly memory?: MemoryInstrumentation;
|
|
84
90
|
readonly prepareExecution: () => SessionInstrumentation;
|
|
85
91
|
readonly preparePreamble: InstrumentationStepScope<never>["preparePreamble"];
|
|
86
92
|
}
|
|
@@ -94,10 +100,8 @@ export declare function bindSessionInstrumentation(input: {
|
|
|
94
100
|
export declare function initializeSessionInstrumentation(input: {
|
|
95
101
|
readonly agentName: string;
|
|
96
102
|
readonly ctx: ContextContainer;
|
|
97
|
-
readonly parentTraceContext?: SessionTraceContext;
|
|
98
103
|
}): void;
|
|
99
104
|
/** Registers the process instrumentation runtime before agent execution begins. */
|
|
100
105
|
export declare function registerInstrumentationRuntime(runtime: InstrumentationRuntime): InstrumentationRuntime;
|
|
101
|
-
/** Returns the process instrumentation runtime, when one was installed. */
|
|
102
106
|
export declare function getInstrumentationRuntime(): InstrumentationRuntime | undefined;
|
|
103
107
|
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createLogger,recordErrorOnSpan}from"#internal/logging.js";import{normalizeChannelAudience}from"#shared/channel-audience.js";import{contextStorage}from"#context/container.js";import{ChannelInstrumentationKey,OtelTraceEnabledKey,ParentSessionKey,ParentTraceContextKey,SessionTraceSeedKey}from"#context/keys.js";import{ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{applyLiveDeliveryAudienceCeiling,formatTraceContentCeiling,readForwardedTraceAssertion,resolveForwardedTraceSeed,traceContentCeilingToDecision}from"#shared/forwarded-trace-policy.js";import{readSessionTraceDecision}from"#tracing/agent-trace-context-store.js";import{shouldCaptureInstrumentationContent}from"#shared/instrumentation-content.js";import{isSampledTrace,resolveTracePolicy,resolveTracePolicyDecision}from"#tracing/sampled-trace.js";import{context,trace}from"#compiled/@opentelemetry/api/index.js";import{attemptIdempotencyKey}from"#instrumentation/lifecycle.js";import{instrumentChannelDelivery}from"#instrumentation/channel-delivery.js";import{buildTelemetryRuntimeContext,snapshotInstrumentationRuntimeContext}from"#instrumentation/runtime-context.js";import{ensureOtelIntegration,getRegisteredTelemetryIntegrations}from"#instrumentation/ai-sdk-telemetry.js";import{createAiSdkHookBridge}from"#instrumentation/ai-sdk-hook-bridge.js";import{createInstrumentationHandleEvent,publishInputResolutions}from"#instrumentation/native-events.js";import{prepareTurnTraceContext}from"#instrumentation/prepare-trace-context.js";import{resolveParentLineage}from"#instrumentation/parent-lineage.js";import{intersectInstrumentationDecisions,readInstrumentationDecision}from"#shared/instrumentation-decision.js";const INSTRUMENTATION_RUNTIME_KEY=Symbol.for(`eve.instrumentation-runtime`),TURN_TRACE_STATE_KEY=`eve.harness.turnTrace`,log=createLogger(`instrumentation.runtime`);function bindInstrumentationRuntime(e,t,n){if(e===void 0)return;let r=e.hooks,readSessionContext=()=>{let e=contextStorage.getStore()??t,n=e.get(SessionTraceSeedKey),r=resolveForwardedTraceSeed(n),i=n===void 0||r===void 0?void 0:{...n,...r},a=e.get(ParentTraceContextKey);return{channel:e.get(ChannelKey),context:e,instrumentation:e.get(ChannelInstrumentationKey),forwardedTracePolicy:readForwardedTraceAssertion(i?.forwardedTracePolicy),parent:e.get(ParentSessionKey),parentTraceContext:a,traceSeed:i}},bindHooks=e=>{let t=e.instrumentation;return r.forTrace?.({agentName:n.agentName,audience:normalizeChannelAudience(t?.metadata.audience),channelType:t?.channelType})??r},captureExecutionRuntime=()=>{let t=e.otelSettings,n=e.ownsAgentSpans===!0;return t!==void 0&&!n&&ensureOtelIntegration(),{ownsAgentSpans:n,otelSettings:t,runtimeContextResolvers:e.runtimeContextResolvers,stepStartedRuntimeContextResolver:e.stepStartedRuntimeContextResolver,tracer:t===void 0?void 0:trace.getTracer(`eve`)}},preparePreamble=(t,r)=>{let i=r.instrumentation,a=normalizeChannelAudience(i?.metadata.audience);return prepareTurnTraceContext({...t,agentName:n.agentName,channelAudience:a,channelType:i?.channelType,instrumentation:e,parentLineage:resolveParentLineage(r.parent,r.channel),parentTraceContext:r.parentTraceContext,rootSessionId:r.parent?.rootSessionId??n.rootSessionId,sessionId:n.sessionId,traceSeed:r.traceSeed})};return{createHandleEvent:e=>{let t=readSessionContext();return createInstrumentationHandleEvent({agentName:n.agentName,channelKind:t.instrumentation?.kind,handleEvent:e.handleEvent,hooks:bindHooks(t),sessionId:n.sessionId,turnId:e.turnId})},flush:e.forceFlush,instrumentChannelDelivery:e=>instrumentChannelDelivery({...e,hooks:r,policyAgentName:n.agentName}),prepareExecution:()=>{let t=captureExecutionRuntime();return{runStep:async(r,i)=>{let a=readSessionContext(),o=bindHooks(a),s=t.otelSettings,c=resolveStepInstrumentationDecision(s,n.agentName,a.instrumentation,a.traceSeed,readSessionTraceDecision(a.context,n.sessionId)),l=t.tracer,u={"eve.environment":r.environment,"eve.session.id":r.session.sessionId,"eve.version":r.eveVersion},d=s?.functionId??n.agentName;d&&(u[`ai.telemetry.functionId`]=d);let f=l!==void 0&&!t.ownsAgentSpans&&c?.action!==`drop`&&r.hasInput?l.startSpan(`ai.eve.turn`,{attributes:u}):void 0,p=f?.spanContext(),m=p===void 0?r.session:{...r.session,state:{...r.session.state,[TURN_TRACE_STATE_KEY]:{spanId:p.spanId,traceFlags:p.traceFlags,traceId:p.traceId}}},h=f===void 0?void 0:trace.setSpan(context.active(),f);if(h===void 0&&l!==void 0){let e=r.session.state?.[TURN_TRACE_STATE_KEY];e!==void 0&&(h=trace.setSpan(context.active(),trace.wrapSpanContext({...e,isRemote:!0})))}let g=readSessionContext(),_=snapshotInstrumentationRuntimeContext(g.context),v=g.instrumentation,y=normalizeChannelAudience(v?.metadata.audience),b=shouldCaptureInstrumentationContent(y),x=c===void 0?c:applyLiveDeliveryAudienceCeiling(c,y,g.forwardedTracePolicy),S=x===void 0?b:x.action===`record`&&x.recordInputs,C=c?.action===`drop`,w={recordInputs:!C&&(x?.action===`record`?x.recordInputs:b)&&(s?.recordInputs??!1),recordOutputs:!C&&(x?.action===`record`?x.recordOutputs:b)&&(s?.recordOutputs??!1)},telemetry=e=>{if(s===void 0&&e.bridgeIntegration===void 0)return;let r={};for(let t of Object.keys(e.runtimeContext??{}))r[t]=!0;let i=s!==void 0&&!(w.recordInputs&&w.recordOutputs),integrations=()=>getRegisteredTelemetryIntegrations({...t.ownsAgentSpans?{excludeEveOtelIntegration:!0}:void 0,sanitizeEveOtelErrors:i});return{functionId:s?.functionId??n.agentName,includeRuntimeContext:r,integrations:e.bridgeIntegration===void 0?i?[...integrations()]:void 0:[e.bridgeIntegration,...integrations()],isEnabled:!0,recordInputs:w.recordInputs,recordOutputs:w.recordOutputs}},run=()=>i({createHandleEvent:e=>createInstrumentationHandleEvent({...e,agentName:n.agentName,channelAudience:y,channelKind:v?.kind,hooks:o,parentLineage:resolveParentLineage(g.parent,g.channel),parentTraceContext:g.parentTraceContext,rootSessionId:g.parent?.rootSessionId,sessionId:n.sessionId}),prepareAttempt:t=>{let r={attemptId:`${n.sessionId}:${t.turnId}:${t.stepIndex}:${t.attemptIndex}`,attemptIndex:t.attemptIndex,channelAudience:y,functionId:s?.functionId??n.agentName,rootSessionId:g.parent?.rootSessionId??n.sessionId,sessionId:n.sessionId,stepIndex:t.stepIndex,turnId:t.turnId},i=createAiSdkHookBridge(r,o,e.runInContext,t.runtimeContext);return{complete:()=>o.publish({idempotencyKey:attemptIdempotencyKey(r),scope:r,type:`step.attempt.completed`}),fail:e=>o.publish({error:e,idempotencyKey:attemptIdempotencyKey(r),scope:r,type:`step.attempt.failed`}),scope:r,telemetry:telemetry({bridgeIntegration:i,runtimeContext:t.runtimeContext})}},preparePreamble:e=>preparePreamble(e,g),publishInputResolutions:e=>publishInputResolutions({...e,hooks:o}),recordError:e=>{f!==void 0&&recordErrorOnSpan(f,e)},resolveRuntimeContext:e=>buildTelemetryRuntimeContext({...e,capturesContent:S,context:_,providerResolvers:t.runtimeContextResolvers,stepStartedResolver:t.stepStartedRuntimeContextResolver}),session:m,setTurnId:e=>f?.setAttribute(`eve.turn.id`,e),telemetry:()=>telemetry({}),traceContext:p===void 0||!isValidSpanContext(p)?void 0:{spanId:p.spanId,traceFlags:p.traceFlags,traceId:p.traceId}});try{return h===void 0?await run():await context.with(h,run)}finally{f?.end(),f=void 0}}}},preparePreamble:e=>preparePreamble(e,readSessionContext())}}function bindSessionInstrumentation(e){return bindInstrumentationRuntime(getInstrumentationRuntime(),e.ctx,{agentName:e.agentName,rootSessionId:e.rootSessionId,sessionId:e.sessionId})}function initializeSessionInstrumentation(e){let t=getInstrumentationRuntime(),n=e.ctx.get(ChannelInstrumentationKey),r=readForwardedTraceAssertion(e.parentTraceContext?.forwardedTracePolicy),i=r?.originAudience??normalizeChannelAudience(n?.metadata.audience),a=allocateSessionTraceSeed({agentName:e.agentName,audience:i,channelType:n?.channelType,forwardedTracePolicy:r,parentTraceContext:e.parentTraceContext,runtime:t});if(a!==void 0&&(e.ctx.set(SessionTraceSeedKey,a),r!==void 0&&log.info(`resolved forwarded trace policy`,{ceilingEffective:a.decision?.action===`record`?formatTraceContentCeiling(a.decision):`drop`,ceilingIn:formatTraceContentCeiling(r.ceiling),originAudience:r.originAudience}),r!==void 0&&e.parentTraceContext!==void 0)){let t={...e.parentTraceContext,...a};delete t.forwardedTracePolicy,e.ctx.set(ParentTraceContextKey,t)}e.ctx.set(OtelTraceEnabledKey,t?.prepareSessionTrace!==void 0)}function allocateSessionTraceSeed(e){if(e.parentTraceContext!==void 0){let t=e.forwardedTracePolicy?traceContentCeilingToDecision(e.forwardedTracePolicy.ceiling):void 0,n=readInstrumentationDecision(e.parentTraceContext.decision),r=t?n===void 0?t:intersectInstrumentationDecisions(t,n):n??resolveTracePolicyDecision(isSampledTrace(e.parentTraceContext),e.audience),i=e.forwardedTracePolicy?intersectInstrumentationDecisions(r,resolveTracePolicy(e.runtime?.otelSettings?.tracePolicy,{agentName:e.agentName,audience:e.audience,channelType:e.channelType})):r;return{decision:i,forwardedTracePolicy:e.forwardedTracePolicy,spanId:e.parentTraceContext.spanId,traceFlags:e.forwardedTracePolicy!==void 0&&i.action===`drop`?e.parentTraceContext.traceFlags&-2:e.parentTraceContext.traceFlags,traceId:e.parentTraceContext.traceId}}if(e.runtime?.prepareSessionTrace===void 0||e.runtime.idGenerator===void 0)return;let t=resolveTracePolicy(e.runtime.otelSettings?.tracePolicy,{agentName:e.agentName,audience:e.audience,channelType:e.channelType}),n=e.runtime.idGenerator.generateTraceId(),r=t.action===`record`&&(e.runtime.samplesTrace?.(n)??!0);return{decision:t,spanId:e.runtime.idGenerator.allocateSpanId(),traceFlags:+!!r,traceId:n}}function resolveStepInstrumentationDecision(e,t,n,r,i){if(e===void 0)return;if(r?.decision!==void 0)return readInstrumentationDecision(r.decision);if(i!==void 0)return i;let a=normalizeChannelAudience(n?.metadata.audience);return r===void 0?resolveTracePolicy(e.tracePolicy,{agentName:t,audience:a,channelType:n?.channelType}):resolveTracePolicyDecision(isSampledTrace(r),a)}function isValidSpanContext(e){return/^[0-9a-f]{32}$/u.test(e.traceId)&&e.traceId!==`00000000000000000000000000000000`&&/^[0-9a-f]{16}$/u.test(e.spanId)&&e.spanId!==`0000000000000000`}const globalRuntime=globalThis;function registerInstrumentationRuntime(e){let t=globalRuntime[INSTRUMENTATION_RUNTIME_KEY];return t===void 0?(globalRuntime[INSTRUMENTATION_RUNTIME_KEY]=e,e):(t.otelSettings=e.otelSettings,t)}function getInstrumentationRuntime(){return globalRuntime[INSTRUMENTATION_RUNTIME_KEY]}export{bindInstrumentationRuntime,bindSessionInstrumentation,getInstrumentationRuntime,initializeSessionInstrumentation,registerInstrumentationRuntime};
|
|
1
|
+
import{createLogger,recordErrorOnSpan}from"#internal/logging.js";import{normalizeChannelAudience}from"#shared/channel-audience.js";import{contextStorage}from"#context/container.js";import{ChannelInstrumentationKey,ConversationIdKey,OtelTraceEnabledKey,ParentSessionKey,ParentTraceContextKey,SessionTraceSeedKey}from"#context/keys.js";import{createMemoryInstrumentation}from"#instrumentation/memory.js";import{readConversationId}from"#tracing/conversation-context.js";import{applyLiveDeliveryAudienceCeiling,formatTraceContentCeiling,readForwardedTraceAssertion,traceContentCeilingToDecision}from"#shared/forwarded-trace-policy.js";import{readSessionTraceDecision}from"#tracing/agent-trace-context-store.js";import{shouldCaptureInstrumentationContent}from"#shared/instrumentation-content.js";import{isSampledTrace,resolveTracePolicy,resolveTracePolicyDecision}from"#tracing/sampled-trace.js";import{context,trace}from"#compiled/@opentelemetry/api/index.js";import{attemptIdempotencyKey}from"#instrumentation/lifecycle.js";import{createInstrumentationHandleEvent,publishInputResolutions}from"#instrumentation/native-events.js";import{instrumentChannelDelivery}from"#instrumentation/channel-delivery.js";import{buildTelemetryRuntimeContext,snapshotInstrumentationRuntimeContext}from"#instrumentation/runtime-context.js";import{ensureOtelIntegration,getRegisteredTelemetryIntegrations}from"#instrumentation/ai-sdk-telemetry.js";import{createAiSdkHookBridge}from"#instrumentation/ai-sdk-hook-bridge.js";import{createBackgroundTaskInstrumentation}from"#instrumentation/background-task-runtime.js";import{prepareTurnTraceContext}from"#instrumentation/prepare-trace-context.js";import{AgentSpanIdGenerator}from"#tracing/agent-span-id-generator.js";import{withErrorContent}from"#tracing/error-content-context.js";import{readInstrumentationSessionContext}from"#instrumentation/session-context.js";import{intersectInstrumentationDecisions,readInstrumentationDecision}from"#shared/instrumentation-decision.js";const INSTRUMENTATION_RUNTIME_KEY=Symbol.for(`eve.instrumentation-runtime`),TURN_TRACE_STATE_KEY=`eve.harness.turnTrace`,log=createLogger(`instrumentation.runtime`);function bindInstrumentationRuntime(e,t,n){if(readConversationId(t.get(ConversationIdKey))===void 0&&t.set(ConversationIdKey,t.get(ParentSessionKey)?.rootSessionId??n.rootSessionId),e===void 0)return;let r=e.hooks,readSessionContext=()=>readInstrumentationSessionContext(contextStorage.getStore()??t),bindHooks=e=>{let t=e.instrumentation;return r.forTrace?.({agentName:n.agentName,audience:e.audience,channelType:t?.channelType})??r},captureExecutionRuntime=()=>{let t=e.otelSettings,n=e.ownsAgentSpans===!0;return t!==void 0&&!n&&ensureOtelIntegration(),{ownsAgentSpans:n,otelSettings:t,runtimeContextResolvers:e.runtimeContextResolvers,stepStartedRuntimeContextResolver:e.stepStartedRuntimeContextResolver,tracer:t===void 0?void 0:trace.getTracer(`eve`)}},preparePreamble=(t,r)=>{let i=r.instrumentation;return prepareTurnTraceContext({...t,instrumentation:e,principals:r.principals,session:{agentName:n.agentName,channelAudience:r.audience,channelType:i?.channelType,parentLineage:r.parentLineage,parentTraceContext:r.parentTraceContext,rootSessionId:r.parent?.rootSessionId??n.rootSessionId,sessionId:n.sessionId,traceSeed:r.traceSeed}})},i=e.memoryOperations===!0?createMemoryInstrumentation({resolveContext:()=>{let e=readSessionContext();return{hooks:bindHooks(e),rootSessionId:e.parent?.rootSessionId??n.rootSessionId}},runInContext:e.runInContext,sessionId:n.sessionId}):void 0,prepareExecution=()=>{let t=captureExecutionRuntime();return{runStep:async(r,i)=>{let a=readSessionContext(),o=bindHooks(a),s=t.otelSettings,c=resolveStepInstrumentationDecision(s,n.agentName,a.instrumentation,a.traceSeed,readSessionTraceDecision(a.context,n.sessionId)),l=t.tracer,u={"eve.environment":r.environment,"eve.session.id":r.session.sessionId,"eve.version":r.eveVersion},d=s?.functionId??n.agentName;d&&(u[`ai.telemetry.functionId`]=d);let f=l!==void 0&&!t.ownsAgentSpans&&c?.action!==`drop`&&r.hasInput?l.startSpan(`ai.eve.turn`,{attributes:u}):void 0,p=f?.spanContext(),m=p===void 0?r.session:{...r.session,state:{...r.session.state,[TURN_TRACE_STATE_KEY]:{spanId:p.spanId,traceFlags:p.traceFlags,traceId:p.traceId}}},h=f===void 0?void 0:trace.setSpan(context.active(),f);if(h===void 0&&l!==void 0){let e=r.session.state?.[TURN_TRACE_STATE_KEY];e!==void 0&&(h=trace.setSpan(context.active(),trace.wrapSpanContext({...e,isRemote:!0})))}let g=readSessionContext(),_=snapshotInstrumentationRuntimeContext(g.context),v=g.instrumentation,y=normalizeChannelAudience(v?.metadata.audience),b=shouldCaptureInstrumentationContent(y),x=c===void 0?c:applyLiveDeliveryAudienceCeiling(c,y,g.forwardedTracePolicy),S=x===void 0?b:x.action===`record`&&x.recordInputs,C=c?.action===`drop`,w={recordInputs:!C&&(x?.action===`record`?x.recordInputs:b)&&(s?.recordInputs??!1),recordOutputs:!C&&(x?.action===`record`?x.recordOutputs:b)&&(s?.recordOutputs??!1)},telemetry=e=>{if(s===void 0&&e.bridgeIntegration===void 0)return;let r={};for(let t of Object.keys(e.runtimeContext??{}))r[t]=!0;let i=s!==void 0&&!(w.recordInputs&&w.recordOutputs),integrations=()=>getRegisteredTelemetryIntegrations({...t.ownsAgentSpans?{excludeEveOtelIntegration:!0}:void 0,sanitizeEveOtelErrors:i});return{functionId:s?.functionId??n.agentName,includeRuntimeContext:r,integrations:e.bridgeIntegration===void 0?i?[...integrations()]:void 0:[e.bridgeIntegration,...integrations()],isEnabled:!0,recordInputs:w.recordInputs,recordOutputs:w.recordOutputs}},run=()=>i({createHandleEvent:e=>createInstrumentationHandleEvent({...e,agentName:n.agentName,channelAudience:y,channelKind:v?.kind,hooks:o,parentLineage:g.parentLineage,parentTraceContext:g.parentTraceContext,rootSessionId:g.parent?.rootSessionId,sessionId:n.sessionId}),prepareAttempt:t=>{let r={attemptId:`${n.sessionId}:${t.turnId}:${t.stepIndex}:${t.attemptIndex}`,attemptIndex:t.attemptIndex,channelAudience:y,functionId:s?.functionId??n.agentName,rootSessionId:g.parent?.rootSessionId??n.sessionId,sessionId:n.sessionId,stepIndex:t.stepIndex,turnId:t.turnId},i=createAiSdkHookBridge(r,o,e.runInContext,t.runtimeContext);return{complete:()=>o.publish({idempotencyKey:attemptIdempotencyKey(r),scope:r,type:`step.attempt.completed`}),fail:e=>o.publish({error:e,idempotencyKey:attemptIdempotencyKey(r),scope:r,type:`step.attempt.failed`}),scope:r,telemetry:telemetry({bridgeIntegration:i,runtimeContext:t.runtimeContext})}},preparePreamble:e=>preparePreamble(e,g),publishInputResolutions:e=>publishInputResolutions({...e,hooks:o}),recordError:e=>{f!==void 0&&recordErrorOnSpan(f,e)},resolveRuntimeContext:e=>buildTelemetryRuntimeContext({...e,capturesContent:S,context:_,providerResolvers:t.runtimeContextResolvers,stepStartedResolver:t.stepStartedRuntimeContextResolver}),session:m,setTurnId:e=>f?.setAttribute(`eve.turn.id`,e),telemetry:()=>telemetry({}),traceContext:p===void 0||!isValidSpanContext(p)?void 0:{spanId:p.spanId,traceFlags:p.traceFlags,traceId:p.traceId}});try{return await context.with(withErrorContent(h??context.active(),w.recordOutputs),run)}finally{f?.end(),f=void 0}}}};return{...createBackgroundTaskInstrumentation({ctx:t,hooks:()=>bindHooks(readSessionContext()),sessionId:n.sessionId}),createHandleEvent:e=>{let t=readSessionContext();return createInstrumentationHandleEvent({agentName:n.agentName,channelKind:t.instrumentation?.kind,handleEvent:e.handleEvent,hooks:bindHooks(t),sessionId:n.sessionId,turnId:e.turnId})},flush:e.forceFlush,instrumentChannelDelivery:e=>instrumentChannelDelivery({...e,hooks:r,policyAgentName:n.agentName}),memory:i,prepareExecution,preparePreamble:e=>preparePreamble(e,readSessionContext())}}function bindSessionInstrumentation(e){return bindInstrumentationRuntime(getInstrumentationRuntime(),e.ctx,{agentName:e.agentName,rootSessionId:e.rootSessionId,sessionId:e.sessionId})}function initializeSessionInstrumentation(e){let t=getInstrumentationRuntime(),n=e.ctx.get(ChannelInstrumentationKey),r=e.ctx.get(ParentTraceContextKey),i=readForwardedTraceAssertion(r?.forwardedTracePolicy),a=i?.originAudience??normalizeChannelAudience(n?.metadata.audience),o=allocateSessionTraceSeed({agentName:e.agentName,audience:a,channelType:n?.channelType,forwardedTracePolicy:i,parentTraceContext:r,runtime:t});if(o!==void 0&&(e.ctx.set(SessionTraceSeedKey,o),i!==void 0&&log.info(`resolved forwarded trace policy`,{ceilingEffective:o.decision?.action===`record`?formatTraceContentCeiling(o.decision):`drop`,ceilingIn:formatTraceContentCeiling(i.ceiling),originAudience:i.originAudience}),i!==void 0&&r!==void 0)){let t={...r,decision:o.decision,traceFlags:o.traceFlags};delete t.forwardedTracePolicy,e.ctx.set(ParentTraceContextKey,t)}e.ctx.set(OtelTraceEnabledKey,t?.prepareSessionTrace!==void 0)}function allocateSessionTraceSeed(e){let localDecision=()=>resolveTracePolicy(e.runtime?.otelSettings?.tracePolicy,{agentName:e.agentName,audience:e.audience,channelType:e.channelType});if(e.parentTraceContext!==void 0){let t=e.forwardedTracePolicy?traceContentCeilingToDecision(e.forwardedTracePolicy.ceiling):void 0,n=readInstrumentationDecision(e.parentTraceContext.decision),r=isSampledTrace(e.parentTraceContext)?t?n===void 0?t:intersectInstrumentationDecisions(t,n):n??resolveTracePolicyDecision(isSampledTrace(e.parentTraceContext),e.audience):{action:`drop`},i=e.forwardedTracePolicy?intersectInstrumentationDecisions(r,localDecision()):r,a=e.runtime?.idGenerator??new AgentSpanIdGenerator;return{decision:i,...e.forwardedTracePolicy===void 0?void 0:{forwardedTracePolicy:e.forwardedTracePolicy},spanId:a.allocateSpanId(),traceFlags:i.action===`drop`?0:e.parentTraceContext.traceFlags,traceId:a.generateTraceId()}}if(e.runtime?.prepareSessionTrace===void 0||e.runtime.idGenerator===void 0)return;let t=localDecision(),n=e.runtime.idGenerator.generateTraceId(),r=t.action===`record`;return{decision:t,spanId:e.runtime.idGenerator.allocateSpanId(),traceFlags:+!!r,traceId:n}}function resolveStepInstrumentationDecision(e,t,n,r,i){if(e===void 0)return;if(r?.decision!==void 0)return readInstrumentationDecision(r.decision);if(i!==void 0)return i;let a=normalizeChannelAudience(n?.metadata.audience);return r===void 0?resolveTracePolicy(e.tracePolicy,{agentName:t,audience:a,channelType:n?.channelType}):resolveTracePolicyDecision(isSampledTrace(r),a)}function isValidSpanContext(e){return/^[0-9a-f]{32}$/u.test(e.traceId)&&e.traceId!==`00000000000000000000000000000000`&&/^[0-9a-f]{16}$/u.test(e.spanId)&&e.spanId!==`0000000000000000`}const globalRuntime=globalThis;function registerInstrumentationRuntime(e){let t=globalRuntime[INSTRUMENTATION_RUNTIME_KEY];return t===void 0?(globalRuntime[INSTRUMENTATION_RUNTIME_KEY]=e,e):(t.otelSettings=e.otelSettings,t)}function getInstrumentationRuntime(){return globalRuntime[INSTRUMENTATION_RUNTIME_KEY]}export{bindInstrumentationRuntime,bindSessionInstrumentation,getInstrumentationRuntime,initializeSessionInstrumentation,registerInstrumentationRuntime};
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { AlsContext } from "#context/container.js";
|
|
2
|
+
export declare function readInstrumentationSessionContext(context: AlsContext): {
|
|
3
|
+
audience: "private" | "public" | "unknown";
|
|
4
|
+
channel: import("../channel/adapter.ts").ChannelAdapter | undefined;
|
|
5
|
+
context: AlsContext;
|
|
6
|
+
forwardedTracePolicy: import("#shared/forwarded-trace-policy.js").ForwardedTraceAssertion | undefined;
|
|
7
|
+
instrumentation: import("../channel/instrumentation.ts").ChannelInstrumentationProjection | undefined;
|
|
8
|
+
parent: import("#context/keys.js").SessionParent | undefined;
|
|
9
|
+
parentLineage: import("./lifecycle.ts").InstrumentationParentLineage | undefined;
|
|
10
|
+
parentTraceContext: import("../channel/types.ts").SessionTraceContext | undefined;
|
|
11
|
+
principals: {
|
|
12
|
+
readonly currentPrincipal?: import("./lifecycle.ts").InstrumentationPrincipalSummary;
|
|
13
|
+
readonly initiatorPrincipal?: import("./lifecycle.ts").InstrumentationPrincipalSummary;
|
|
14
|
+
};
|
|
15
|
+
traceSeed: {
|
|
16
|
+
traceFlags: number;
|
|
17
|
+
decision?: import("../shared/instrumentation-decision.ts").InstrumentationDecision;
|
|
18
|
+
forwardedTracePolicy?: import("#shared/forwarded-trace-policy.js").ForwardedTraceAssertion;
|
|
19
|
+
spanId: string;
|
|
20
|
+
traceId: string;
|
|
21
|
+
} | undefined;
|
|
22
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{normalizeChannelAudience}from"#shared/channel-audience.js";import{ChannelInstrumentationKey,ParentSessionKey,ParentTraceContextKey,SessionCallbackKey,SessionTraceSeedKey}from"#context/keys.js";import{ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{readForwardedTraceAssertion,resolveForwardedTraceSeed}from"#shared/forwarded-trace-policy.js";import{resolveParentLineage}from"#instrumentation/parent-lineage.js";import{readInstrumentationPrincipals}from"#instrumentation/principal-summary.js";function readInstrumentationSessionContext(e){let t=e.get(SessionTraceSeedKey),n=resolveForwardedTraceSeed(t),r=t===void 0||n===void 0?void 0:{...t,...n},i=e.get(ParentSessionKey),a=e.get(ChannelKey),o=e.get(ChannelInstrumentationKey),s=normalizeChannelAudience(o?.metadata.audience);return{audience:s,channel:a,context:e,forwardedTracePolicy:readForwardedTraceAssertion(r?.forwardedTracePolicy),instrumentation:o,parent:i,parentLineage:resolveParentLineage(i,a,e.get(SessionCallbackKey)),parentTraceContext:e.get(ParentTraceContextKey),principals:readInstrumentationPrincipals(e,s,r?.decision),traceSeed:r}}export{readInstrumentationSessionContext};
|
|
@@ -1,12 +1,11 @@
|
|
|
1
1
|
import { type JsonValue } from "#shared/json.js";
|
|
2
2
|
import type { InstrumentationAttemptScope } from "#instrumentation/lifecycle.js";
|
|
3
|
+
export { preserveSerializedInstrumentationState } from "#shared/serialized-observability-state.js";
|
|
3
4
|
export interface InstrumentationStateOwner {
|
|
4
5
|
readonly attemptId?: string;
|
|
5
6
|
readonly sessionId?: string;
|
|
6
7
|
readonly turnId?: string;
|
|
7
8
|
}
|
|
8
|
-
/** Keeps only provider state needed to settle an interrupted operation. */
|
|
9
|
-
export declare function preserveSerializedInstrumentationState(original: Record<string, unknown>, interrupted: Record<string, unknown>): Record<string, unknown>;
|
|
10
9
|
/** One provider's view of its own state for one operation. */
|
|
11
10
|
export interface InstrumentationStateSlot {
|
|
12
11
|
get(): JsonValue | undefined;
|
|
@@ -43,8 +42,14 @@ export interface InstrumentationActionCorrelation {
|
|
|
43
42
|
readonly idempotencyKey: string;
|
|
44
43
|
readonly scope: InstrumentationAttemptScope;
|
|
45
44
|
}
|
|
45
|
+
/** Binds an admitted background task to the action that started it. */
|
|
46
|
+
export declare function rememberInstrumentationBackgroundTask(taskId: string, correlation: InstrumentationActionCorrelation): void;
|
|
47
|
+
/** Binds a background task when its executor admits the originating call. */
|
|
48
|
+
export declare function rememberInstrumentationBackgroundTaskForCall(sessionId: string, callId: string, taskId: string): void;
|
|
46
49
|
export declare function findInstrumentationActionScopeForCall(sessionId: string, callId: string): InstrumentationActionCorrelation | undefined;
|
|
47
50
|
/** Reads and releases one durable runtime action's originating scope. */
|
|
48
51
|
export declare function takeInstrumentationActionScopeForCall(sessionId: string, callId: string): InstrumentationActionCorrelation | undefined;
|
|
52
|
+
/** Reads and releases the action correlation owned by a terminal background task. */
|
|
53
|
+
export declare function takeInstrumentationActionScopeForTask(taskId: string): InstrumentationActionCorrelation | undefined;
|
|
49
54
|
/** Takes every still-open action owned by one session or turn. */
|
|
50
55
|
export declare function takeInstrumentationActionScopes(sessionId: string, turnId?: string): readonly InstrumentationActionCorrelation[];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{contextStorage,loadContext}from"#context/container.js";import{
|
|
1
|
+
import{contextStorage,loadContext}from"#context/container.js";import{parseJsonValue}from"#shared/json.js";import{ContextKey}from"#context/key.js";import{SERIALIZED_INSTRUMENTATION_STATE_KEYS,preserveSerializedInstrumentationState}from"#shared/serialized-observability-state.js";const InstrumentationStateKey=new ContextKey(SERIALIZED_INSTRUMENTATION_STATE_KEYS.providerState,{codec:{deserialize:deserializeState,serialize:e=>e}}),InstrumentationActionStateKey=new ContextKey(SERIALIZED_INSTRUMENTATION_STATE_KEYS.actionScopes,{codec:{deserialize:deserializeActionStates,serialize:e=>e}}),InstrumentationInputScopeKey=new ContextKey(SERIALIZED_INSTRUMENTATION_STATE_KEYS.inputScopes,{codec:{deserialize:deserializeScopes,serialize:e=>e}});function instrumentationStateSlot(e,t,n={}){let r=stateKey(e,t),i=!0;return{get:()=>{if(!i)return;let e=contextStorage.getStore()?.get(InstrumentationStateKey)?.[r]?.value;return e===void 0?void 0:cloneAndFreezeJson(e)},revoke:()=>{i=!1},set:e=>{if(!i)return;let t=e===void 0?void 0:cloneAndFreezeJson(parseJsonValue(e));writeInstrumentationState(e=>{if(t===void 0)return writeSlot(e,r,void 0);let i=e[r],a={value:t};return i?.abandoned===!0&&(a.abandoned=!0),assignOwner(a,n),writeSlot(e,r,a)})}}}function abandonInstrumentationState(e,t,n={}){let r=stateKey(e,t);writeInstrumentationState(e=>{let t=e[r],i={attemptId:n.attemptId??t?.attemptId,sessionId:n.sessionId??t?.sessionId,turnId:n.turnId??t?.turnId},a={abandoned:!0};return assignOwner(a,i),t?.value!==void 0&&(a.value=t.value),writeSlot(e,r,a)})}function isInstrumentationStateAbandoned(e,t){return contextStorage.getStore()?.get(InstrumentationStateKey)?.[stateKey(e,t)]?.abandoned===!0}function releaseAllInstrumentationState(e){let t=`\0${e}`;releaseMatchingInstrumentationState(e=>e.endsWith(t))}function releaseAllInstrumentationAttemptState(e){releaseMatchingInstrumentationState((t,n)=>n.attemptId===e)}function releaseAllInstrumentationTurnState(e,t){let n=t===void 0?new Set:backgroundActionKeys(e,t);releaseMatchingInstrumentationState((r,i)=>i.sessionId===e&&(t===void 0||i.turnId===t)&&!n.has(instrumentationStateOperationId(r)))}function releaseMatchingInstrumentationState(e){let t=contextStorage.getStore()?.get(InstrumentationStateKey);t!==void 0&&Object.entries(t).some(([t,n])=>e(t,n))&&writeInstrumentationState(t=>{let n={...t};for(let[r,i]of Object.entries(t))e(r,i)&&delete n[r];return n})}function rememberInstrumentationActionScope(e,t){writeContextKey(InstrumentationActionStateKey,n=>{let r=n[e]?.taskId;return{...n,[e]:r===void 0?{scope:t}:{scope:t,taskId:r}}})}function rememberInstrumentationInputScope(e,t){writeContextKey(InstrumentationInputScopeKey,n=>({...n,[e]:t}))}function takeInstrumentationInputScope(e){let t=contextStorage.getStore()?.get(InstrumentationInputScopeKey)?.[e];if(t!==void 0)return writeContextKey(InstrumentationInputScopeKey,t=>{let n={...t};return delete n[e],n}),t}function rememberInstrumentationBackgroundTask(e,t){writeContextKey(InstrumentationActionStateKey,n=>({...n,[t.idempotencyKey]:{scope:n[t.idempotencyKey]?.scope??t.scope,taskId:e}}))}function rememberInstrumentationBackgroundTaskForCall(e,t,n){let r=findInstrumentationActionScopeForCall(e,t);r!==void 0&&rememberInstrumentationBackgroundTask(n,r)}function findInstrumentationActionScopeForCall(e,t){let n=contextStorage.getStore()?.get(InstrumentationActionStateKey);if(n!==void 0)for(let r of Object.values(n)){let i=`action:${e}:${r.scope.turnId}:${t}`,a=n[i];if(a!==void 0)return{idempotencyKey:i,scope:a.scope}}}function takeInstrumentationActionScopeForCall(e,t){let n=findInstrumentationActionScopeForCall(e,t);if(n!==void 0)return releaseInstrumentationActionCorrelation(n.idempotencyKey),n}function takeInstrumentationActionScopeForTask(e){let t=contextStorage.getStore()?.get(InstrumentationActionStateKey);if(t!==void 0){for(let[n,r]of Object.entries(t))if(r.taskId===e)return releaseInstrumentationActionCorrelation(n),{idempotencyKey:n,scope:r.scope}}}function takeInstrumentationActionScopes(e,t){let n=contextStorage.getStore()?.get(InstrumentationActionStateKey);if(n===void 0)return[];let r=Object.entries(n).filter(([,n])=>n.scope.sessionId===e&&(t===void 0||n.scope.turnId===t)&&(t===void 0||n.taskId===void 0)).map(([e,t])=>({idempotencyKey:e,scope:t.scope}));if(r.length===0)return[];let i=new Set(r.map(e=>e.idempotencyKey));return writeContextKey(InstrumentationActionStateKey,e=>{let t={...e};for(let e of i)delete t[e];return t}),r}function releaseInstrumentationActionCorrelation(e){writeContextKey(InstrumentationActionStateKey,t=>{let n={...t};return delete n[e],n})}function backgroundActionKeys(e,t){let n=contextStorage.getStore()?.get(InstrumentationActionStateKey);return n===void 0?new Set:new Set(Object.entries(n).flatMap(([n,r])=>r.taskId!==void 0&&r.scope.sessionId===e&&r.scope.turnId===t?[n]:[]))}function writeSlot(e,t,n){if(n===void 0){let n={...e};return delete n[t],n}return{...e,[t]:n}}function writeInstrumentationState(e){writeContextKey(InstrumentationStateKey,e)}function assignOwner(e,t){t.attemptId!==void 0&&(e.attemptId=t.attemptId),t.sessionId!==void 0&&(e.sessionId=t.sessionId),t.turnId!==void 0&&(e.turnId=t.turnId)}function writeContextKey(e,t){contextStorage.getStore()!==void 0&&loadContext().set(e,e=>t(e??{}))}function stateKey(e,t){return`${e}\0${t}`}function instrumentationStateOperationId(e){return e.slice(e.indexOf(`\0`)+1)}function deserializeState(e){if(typeof e!=`object`||!e||Array.isArray(e))return{};let t={};for(let[n,r]of Object.entries(e)){if(typeof r!=`object`||!r||Array.isArray(r))continue;let e=r,i=typeof e.attemptId==`string`?e.attemptId:void 0,a=typeof e.sessionId==`string`?e.sessionId:void 0,o=typeof e.turnId==`string`?e.turnId:void 0,s={};e.abandoned===!0&&(s.abandoned=!0),i!==void 0&&(s.attemptId=i),a!==void 0&&(s.sessionId=a),o!==void 0&&(s.turnId=o),e.value!==void 0&&(s.value=cloneAndFreezeJson(e.value)),t[n]=s}return t}function cloneAndFreezeJson(e){if(Array.isArray(e))return Object.freeze(e.map(e=>cloneAndFreezeJson(e)));if(typeof e!=`object`||!e)return e;let t={};for(let[n,r]of Object.entries(e))t[n]=cloneAndFreezeJson(r);return Object.freeze(t)}function deserializeScopes(e){return typeof e!=`object`||!e||Array.isArray(e)?{}:e}function deserializeActionStates(e){if(typeof e!=`object`||!e||Array.isArray(e))return{};let t={};for(let[n,r]of Object.entries(e)){if(typeof r!=`object`||!r||Array.isArray(r))continue;let e=r,i=typeof e.scope==`object`&&e.scope!==null&&!Array.isArray(e.scope)?e.scope:r,a=typeof e.taskId==`string`?e.taskId:void 0;t[n]=a===void 0?{scope:i}:{scope:i,taskId:a}}return t}export{abandonInstrumentationState,findInstrumentationActionScopeForCall,instrumentationStateSlot,isInstrumentationStateAbandoned,preserveSerializedInstrumentationState,releaseAllInstrumentationAttemptState,releaseAllInstrumentationState,releaseAllInstrumentationTurnState,rememberInstrumentationActionScope,rememberInstrumentationBackgroundTask,rememberInstrumentationBackgroundTaskForCall,rememberInstrumentationInputScope,takeInstrumentationActionScopeForCall,takeInstrumentationActionScopeForTask,takeInstrumentationActionScopes,takeInstrumentationInputScope};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createRequire}from"node:module";import{basename,dirname,join}from"node:path";import{existsSync,readFileSync,realpathSync}from"node:fs";import{fileURLToPath}from"node:url";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";let cachedPackageInfo,cachedPackageLocation;const BUNDLED_FALLBACK_PACKAGE_VERSION=`0.
|
|
1
|
+
import{createRequire}from"node:module";import{basename,dirname,join}from"node:path";import{existsSync,readFileSync,realpathSync}from"node:fs";import{fileURLToPath}from"node:url";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";let cachedPackageInfo,cachedPackageLocation;const BUNDLED_FALLBACK_PACKAGE_VERSION=`0.54.2`,WORKFLOW_MODULE_ALIASES={"workflow/errors":`src/compiled/@workflow/errors/index.js`,"workflow/internal/private":`src/compiled/@workflow/core/private.js`};function resolveFallbackPackageVersion(){return BUNDLED_FALLBACK_PACKAGE_VERSION.startsWith(`__`)?`0.0.0`:BUNDLED_FALLBACK_PACKAGE_VERSION}const FALLBACK_PACKAGE_INFO={name:EVE_PACKAGE_NAME,version:resolveFallbackPackageVersion()};function resolveCurrentModulePath(){return typeof __filename==`string`?__filename:resolveCurrentModulePathFromStack()}function resolveCurrentModulePathFromStack(){let e=Error.prepareStackTrace;try{Error.prepareStackTrace=(e,t)=>t;let e=Error().stack?.[0]?.getFileName();if(typeof e!=`string`||e.length===0)throw Error(`Failed to resolve the current module path from the stack trace.`);return e.startsWith(`file:`)?fileURLToPath(e):e}finally{Error.prepareStackTrace=e}}const require=createRequire(resolveCurrentModulePath());function tryResolveVerifiedPackageRoot(e){try{let t=realpathSync.native(e);return tryReadInstalledPackageInfo(t,EVE_PACKAGE_NAME)===void 0?void 0:dirname(t)}catch{return}}function findNearestVerifiedPackageRoot(e){let t=e;for(;;){let e=tryResolveVerifiedPackageRoot(join(t,`package.json`));if(e!==void 0)return e;let n=dirname(t);if(n===t)return;t=n}}function tryResolveDirectBuildLocation(e){let t=dirname(e);for(;;){if(basename(t)===`dist`){let e=tryResolveVerifiedPackageRoot(join(dirname(t),`package.json`));if(e!==void 0)return{packageBuildRoot:t,packageRoot:e}}let e=dirname(t);if(e===t)return;t=e}}function isSourceCheckout(e){return existsSync(join(e,`src`,`internal`,`application`,`package.ts`))}function tryCreatePackageLocation(e){if(isSourceCheckout(e))return{packageBuildRoot:null,packageRoot:e};let t=join(e,`dist`);if(existsSync(t))return{packageBuildRoot:t,packageRoot:e}}function resolveSelfPackageJsonPath(e){return createRequire(e).resolve(`${EVE_PACKAGE_NAME}/package.json`)}function resolvePackageLocationFromModulePath(e,t=resolveSelfPackageJsonPath){let n=realpathSync.native(e),r=tryResolveDirectBuildLocation(n);if(r!==void 0)return r;let i=findNearestVerifiedPackageRoot(dirname(n));if(i!==void 0&&isSourceCheckout(i))return{packageBuildRoot:null,packageRoot:i};try{let e=tryResolveVerifiedPackageRoot(t(n)),r=e===void 0?void 0:tryCreatePackageLocation(e);if(r!==void 0)return r}catch{}let a=i===void 0?void 0:tryCreatePackageLocation(i);if(a!==void 0)return a;throw Error(`Failed to resolve the eve package root from "${e}".`)}function resolvePackageLocation(){return cachedPackageLocation??=resolvePackageLocationFromModulePath(resolveCurrentModulePath()),cachedPackageLocation}function resolvePackageBuildRoot(){return resolvePackageLocation().packageBuildRoot}function resolvePackageRoot(){return resolvePackageLocation().packageRoot}function tryResolvePackageRoot(){try{return resolvePackageRoot()}catch{return}}function rewriteSourceFilePathForBuild(e){return e.replace(/\.[cm]?tsx?$/,`.js`)}function resolvePackageSourceFilePath(e){let t=resolvePackageBuildRoot();return t===null?join(resolvePackageRoot(),e):join(t,rewriteSourceFilePathForBuild(e))}function resolvePackageSourceDirectoryPath(e){let t=resolvePackageBuildRoot();return join(t===null?resolvePackageRoot():t,e)}function resolvePackageDependencyPath(e){return require.resolve(e)}function resolvePackageCompiledFilePath(e){let t=resolvePackageBuildRoot();return t===null?join(resolvePackageRoot(),`.generated`,`compiled`,e.replace(/^src\/compiled\//,``)):join(t,e)}function normalizeInstalledPackageInfo(e){let t=e;if(typeof t.name==`string`&&typeof t.version==`string`)return{name:t.name,version:t.version}}function tryReadInstalledPackageInfo(e,t){let n=normalizeInstalledPackageInfo(JSON.parse(readFileSync(e,`utf8`)));if(n?.name===t)return n}function resolveInstalledPackageInfo(){if(cachedPackageInfo)return cachedPackageInfo;let e=tryResolvePackageRoot(),t=e===void 0?void 0:tryReadInstalledPackageInfo(join(e,`package.json`),EVE_PACKAGE_NAME);if(t)return cachedPackageInfo=t,cachedPackageInfo;try{let e=tryReadInstalledPackageInfo(require.resolve(`${EVE_PACKAGE_NAME}/package.json`),EVE_PACKAGE_NAME);if(e)return cachedPackageInfo=e,cachedPackageInfo}catch{}return cachedPackageInfo={...FALLBACK_PACKAGE_INFO},cachedPackageInfo}function readWorkflowVersionFromManifest(e){let t=e;for(let e of[t.devDependencies,t.dependencies,t.peerDependencies]){let t=e?.[`@workflow/core`];if(typeof t==`string`&&t.trim().length>0)return t}}function resolveExpectedWorkflowVersion(){let e=tryResolvePackageRoot();if(e!==void 0)try{return readWorkflowVersionFromManifest(JSON.parse(readFileSync(join(e,`package.json`),`utf8`)))}catch{}try{return readWorkflowVersionFromManifest(JSON.parse(readFileSync(require.resolve(`${EVE_PACKAGE_NAME}/package.json`),`utf8`)))}catch{return}}function resolveWorkflowModulePath(e){if(e===`workflow`)return resolvePackageSourceFilePath(`src/internal/workflow/index.ts`);if(e===`workflow/api`||e===`workflow/runtime`)return resolvePackageSourceFilePath(`src/internal/workflow/runtime.ts`);if(e===`workflow/internal/builtins`)return resolvePackageSourceFilePath(`src/internal/workflow/builtins.ts`);let t=WORKFLOW_MODULE_ALIASES[e];return t===void 0?require.resolve(e):resolvePackageCompiledFilePath(t)}export{resolveExpectedWorkflowVersion,resolveInstalledPackageInfo,resolvePackageCompiledFilePath,resolvePackageDependencyPath,resolvePackageLocationFromModulePath,resolvePackageRoot,resolvePackageSourceDirectoryPath,resolvePackageSourceFilePath,resolveWorkflowModulePath};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{inspect}from"node:util";import{isNonEmptyString,isObject}from"#shared/guards.js";import{SpanStatusCode,trace}from"#compiled/@opentelemetry/api/index.js";import{getErrorMessage}from"#compiled/@ai-sdk/provider/index.js";const LEVEL_SEVERITY={debug:10,info:20,warn:30,error:40};function createLogger(e){return{debug(t,n){write(`debug`,e,t,n)},info(t,n){write(`info`,e,t,n)},warn(t,n){write(`warn`,e,t,n)},error(t,n){write(`error`,e,t,n),recordOnActiveSpan(t,n)}}}function logError(e,t,n,r){let i=formatError(n);return e.error(t,{...r,error:i}),typeof i.errorId==`string`?i.errorId:createErrorId()}function createErrorId(){return crypto.randomUUID()}function formatError(e,t){let n={errorId:t??createErrorId(),message:extractErrorMessage(e)},r=extractErrorName(e);return r!==void 0&&(n.name=r),n.detail=inspectError(e),n}function extractErrorName(e){if(e instanceof Error)return e.name===`Error`?void 0:e.name;if(isObject(e)&&isNonEmptyString(e.name)&&e.name!==`Error`)return e.name}function extractErrorMessage(e){return isObject(e)&&!(e instanceof Error)&&typeof e.message==`string`?e.message:getErrorMessage(e)}function extractErrorId(e){if(isObject(e))return isNonEmptyString(e.errorId)?e.errorId:void 0}function formatErrorHint(e){let t=isObject(e.details)?e.details.name:void 0,n=isNonEmptyString(t)?t:void 0,r=typeof e.message==`string`?e.message.trim():``;return n&&r.length>0?` (${n}: ${truncateForDisplay(r)})`:n?` (${n})`:r.length>0?` (${truncateForDisplay(r)})`:``}function truncateForDisplay(e,t=160){return e.length<=t?e:`${e.slice(0,t-1).trimEnd()}…`}function recordErrorOnSpan(e,t){let n=t instanceof Error?t.message:getErrorMessage(t),r=t instanceof Error?t.name:`Error`;e.setStatus({code:SpanStatusCode.ERROR,message:n}),e.recordException({message:n,name:r,stack:inspectError(t)})}function resolveThreshold(){let e=process.env.EVE_LOG_LEVEL?.toLowerCase();return e===`debug`||e===`info`||e===`warn`||e===`error`?LEVEL_SEVERITY[e]:LEVEL_SEVERITY.info}function isLogLevelEnabled(e){return LEVEL_SEVERITY[e]>=resolveThreshold()}let logRecordSubscriber;function setLogRecordSubscriber(e){logRecordSubscriber=e}function write(e,t,n,r){if(LEVEL_SEVERITY[e]<resolveThreshold())return;let i=logRecordSubscriber;if(i!==void 0)try{i(r===void 0?{level:e,namespace:t,message:n}:{level:e,namespace:t,message:n,fields:renderFields(r)});return}catch{}let a=e===`error`?console.error:e===`warn`?console.warn:console.log,o=`[eve:${t}] ${n}`;if(r===void 0){a(o);return}a(o,renderFields(r))}function renderFields(e){let t={};for(let[n,r]of Object.entries(e))if(r!==void 0){if(r instanceof Error){t[n]=formatError(r);continue}t[n]=r}return t}function recordOnActiveSpan(e,t){let n=trace.getActiveSpan();if(n===void 0)return;let r=t?.error;if(r instanceof Error){recordErrorOnSpan(n,r);return}if(isFormattedError(r)){n.setStatus({code:SpanStatusCode.ERROR,message:
|
|
1
|
+
import{inspect}from"node:util";import{isNonEmptyString,isObject}from"#shared/guards.js";import{SpanStatusCode,trace}from"#compiled/@opentelemetry/api/index.js";import{truncateTelemetryText}from"#tracing/telemetry-budget.js";import{capturesErrorContent}from"#tracing/error-content-context.js";import{getErrorMessage}from"#compiled/@ai-sdk/provider/index.js";const LEVEL_SEVERITY={debug:10,info:20,warn:30,error:40};function createLogger(e){return{debug(t,n){write(`debug`,e,t,n)},info(t,n){write(`info`,e,t,n)},warn(t,n){write(`warn`,e,t,n)},error(t,n){write(`error`,e,t,n),recordOnActiveSpan(t,n)}}}function logError(e,t,n,r){let i=formatError(n);return e.error(t,{...r,error:i}),typeof i.errorId==`string`?i.errorId:createErrorId()}function createErrorId(){return crypto.randomUUID()}function formatError(e,t){let n={errorId:t??createErrorId(),message:extractErrorMessage(e)},r=extractErrorName(e);return r!==void 0&&(n.name=r),n.detail=inspectError(e),n}function extractErrorName(e){if(e instanceof Error)return e.name===`Error`?void 0:e.name;if(isObject(e)&&isNonEmptyString(e.name)&&e.name!==`Error`)return e.name}function extractErrorMessage(e){return isObject(e)&&!(e instanceof Error)&&typeof e.message==`string`?e.message:getErrorMessage(e)}function extractErrorId(e){if(isObject(e))return isNonEmptyString(e.errorId)?e.errorId:void 0}function formatErrorHint(e){let t=isObject(e.details)?e.details.name:void 0,n=isNonEmptyString(t)?t:void 0,r=typeof e.message==`string`?e.message.trim():``;return n&&r.length>0?` (${n}: ${truncateForDisplay(r)})`:n?` (${n})`:r.length>0?` (${truncateForDisplay(r)})`:``}function truncateForDisplay(e,t=160){return e.length<=t?e:`${e.slice(0,t-1).trimEnd()}…`}function recordErrorOnSpan(e,t){if(!capturesErrorContent()){e.setStatus({code:SpanStatusCode.ERROR});return}let n=truncateTelemetryText(t instanceof Error?t.message:getErrorMessage(t),4096),r=t instanceof Error?truncateTelemetryText(t.name,128):`Error`;e.setStatus({code:SpanStatusCode.ERROR,message:n}),e.recordException({message:n,name:r,stack:inspectError(t)})}function resolveThreshold(){let e=process.env.EVE_LOG_LEVEL?.toLowerCase();return e===`debug`||e===`info`||e===`warn`||e===`error`?LEVEL_SEVERITY[e]:LEVEL_SEVERITY.info}function isLogLevelEnabled(e){return LEVEL_SEVERITY[e]>=resolveThreshold()}let logRecordSubscriber;function setLogRecordSubscriber(e){logRecordSubscriber=e}function write(e,t,n,r){if(LEVEL_SEVERITY[e]<resolveThreshold())return;let i=logRecordSubscriber;if(i!==void 0)try{i(r===void 0?{level:e,namespace:t,message:n}:{level:e,namespace:t,message:n,fields:renderFields(r)});return}catch{}let a=e===`error`?console.error:e===`warn`?console.warn:console.log,o=`[eve:${t}] ${n}`;if(r===void 0){a(o);return}a(o,renderFields(r))}function renderFields(e){let t={};for(let[n,r]of Object.entries(e))if(r!==void 0){if(r instanceof Error){t[n]=formatError(r);continue}t[n]=r}return t}function recordOnActiveSpan(e,t){let n=trace.getActiveSpan();if(n===void 0)return;let r=t?.error;if(!capturesErrorContent()){(r instanceof Error||isFormattedError(r))&&n.setStatus({code:SpanStatusCode.ERROR});return}if(r instanceof Error){recordErrorOnSpan(n,r);return}if(isFormattedError(r)){let e=truncateTelemetryText(r.message,4096);n.setStatus({code:SpanStatusCode.ERROR,message:e}),n.recordException({message:e,name:typeof r.name==`string`?truncateTelemetryText(r.name,128):`Error`,stack:typeof r.detail==`string`?truncateTelemetryText(r.detail,8192):void 0});return}n.addEvent(e,t?renderFields(t):void 0)}function isFormattedError(e){return isObject(e)&&typeof e.errorId==`string`&&typeof e.message==`string`}function inspectError(e){return truncate(inspect(e,{breakLength:1/0,compact:!1,depth:10,maxStringLength:8192}),16384)}function truncate(e,t){if(Buffer.byteLength(e,`utf8`)<=t)return e;let n=e.slice(0,t);for(;Buffer.byteLength(n,`utf8`)>t&&n.length>0;)n=n.slice(0,-1);return`${n}<…truncated>`}export{createErrorId,createLogger,extractErrorId,formatError,formatErrorHint,inspectError,isLogLevelEnabled,logError,recordErrorOnSpan,setLogRecordSubscriber};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createAttachSessionFn}from"#channel/session.js";import{createLogger,logError}from"#internal/logging.js";import{createChannelDeliveryMetadata}from"#channel/delivery-metadata.js";import{createChannelOperations}from"#channel/channel-operations.js";import{getChannelInstrumentationKind}from"#channel/compiled-channel.js";import{createCrossChannelToFn,toCrossChannelTargets}from"#channel/cross-channel-receive.js";import{attachAgentInfoRouteResponse,attachHomeRouteMetadata,attachRemoteAgentStreamHeadersResolver,attachRouteChannelName,attachRouteSessionCreator}from"#internal/nitro/routes/channel-route-context.js";import{DEVELOPMENT_WORKFLOW_SECRET_ENV}from"#internal/workflow/development-world-protocol.js";import{readTrustedDevelopmentClientAddress}from"#internal/nitro/dev-client-address.js";import{withLocalDevRequestScope}from"#runtime/local-dev-capability.js";import{traceChannelRequest}from"#internal/nitro/routes/channel-request-instrumentation.js";import{resolveNitroChannelRuntimeBundle}from"#internal/nitro/routes/runtime-stack.js";import{readVercelProjectLink}from"#internal/vercel/project-link.js";import{withVercelOidcProjectResolver}from"#channel/auth/vercel-oidc-project.js";const log=createLogger(`channel.dispatch`);async function dispatchChannelRequest(e,t,n){return await traceChannelRequest({request:e.req,routeKey:t},async r=>{let i=await resolveNitroChannelRuntimeBundle(n),a
|
|
1
|
+
import{createAttachSessionFn}from"#channel/session.js";import{createLogger,logError}from"#internal/logging.js";import{createChannelDeliveryMetadata}from"#channel/delivery-metadata.js";import{createChannelOperations}from"#channel/channel-operations.js";import{getChannelInstrumentationKind}from"#channel/compiled-channel.js";import{createCrossChannelToFn,toCrossChannelTargets}from"#channel/cross-channel-receive.js";import{attachAgentInfoRouteResponse,attachHomeRouteMetadata,attachRemoteAgentStreamHeadersResolver,attachRouteChannelName,attachRouteSessionCreator}from"#internal/nitro/routes/channel-route-context.js";import{context,trace}from"#compiled/@opentelemetry/api/index.js";import{DEVELOPMENT_WORKFLOW_SECRET_ENV}from"#internal/workflow/development-world-protocol.js";import{readTrustedDevelopmentClientAddress}from"#internal/nitro/dev-client-address.js";import{withLocalDevRequestScope}from"#runtime/local-dev-capability.js";import{traceChannelRequest}from"#internal/nitro/routes/channel-request-instrumentation.js";import{resolveNitroChannelRuntimeBundle}from"#internal/nitro/routes/runtime-stack.js";import{readVercelProjectLink}from"#internal/vercel/project-link.js";import{withVercelOidcProjectResolver}from"#channel/auth/vercel-oidc-project.js";const log=createLogger(`channel.dispatch`);async function dispatchChannelRequest(e,t,n){return await traceChannelRequest({request:e.req,routeKey:t},async r=>{let i=r?.spanContext()??trace.getSpan(context.active())?.spanContext(),a=await resolveNitroChannelRuntimeBundle(n),o=a.channels.find(e=>`${e.method.toUpperCase()} ${e.urlPath}`===t);if(o===void 0)return Response.json({error:`No matching channel for this request.`,ok:!1},{status:404});r?.setAttribute(`eve.channel.name`,o.name);let s=getChannelInstrumentationKind(o.definition)??o.adapter?.kind;s!==void 0&&r?.setAttribute(`eve.channel.kind`,s);let c=buildRouteArgs(e,a,o.name,s??`channel`,n,i),l;try{l=await withDevelopmentVercelOidcContext(n,e.req,async()=>{if(o.handler)return await o.handler(e.req,c.args);let t={waitUntil:c.args.waitUntil,params:c.args.params,requestIp:c.args.requestIp};return await o.fetch(e.req,t)})}catch(n){let r=logError(log,`channel handler threw`,n,{routeKey:t,channel:o.name});return flushBackgroundTasks(e,c.backgroundTasks,t,o.name),Response.json({error:`Channel handler failed.`,errorId:r,ok:!1},{status:500})}return flushBackgroundTasks(e,c.backgroundTasks,t,o.name),l})}async function dispatchChannelWebSocketRequest(e,t,n){let r=await resolveNitroChannelRuntimeBundle(n),i=r.channels.find(e=>`${e.method.toUpperCase()} ${e.urlPath}`===t);if(i===void 0||i.websocket===void 0)return rejectWebSocketUpgrade({error:`No matching websocket channel for this request.`,ok:!1},404);let a=i.websocket,o=getChannelInstrumentationKind(i.definition)??i.adapter?.kind??`channel`,s=buildRouteArgs(e,r,i.name,o,n,void 0);try{let r=await withDevelopmentVercelOidcContext(n,e.req,async()=>await a(e.req,s.args));return flushBackgroundTasks(e,s.backgroundTasks,t,i.name),r}catch(n){let r=logError(log,`channel websocket handler threw`,n,{routeKey:t,channel:i.name});return flushBackgroundTasks(e,s.backgroundTasks,t,i.name),rejectWebSocketUpgrade({error:`Channel websocket handler failed.`,errorId:r,ok:!1},500)}}async function withDevelopmentVercelOidcContext(e,t,n){return e.kind===`development`?await withLocalDevRequestScope(t,async()=>await withVercelOidcProjectResolver({request:t,resolveCurrentProject:async()=>{let t=await readVercelProjectLink(e.appRoot);return t===void 0?void 0:{environment:`development`,projectId:t.projectId}}},n)):await n()}function buildRouteArgs(e,t,n,r,i,a){let o=readVercelRequestId(e.req.headers),s=extractRequestIp(e,i),c=[],l=e.context.params??{},u={};for(let[e,t]of Object.entries(l))u[e]=decodeURIComponent(t);let waitUntil=e=>{c.push(e)},d=t.channels.find(e=>e.name===n),f=d?.adapter??{kind:`channel`},p={acceptedDeploymentId:process.env.VERCEL_DEPLOYMENT_ID?.trim()||void 0,channelKind:r,channelName:n,requestId:o,requestTraceContext:a===void 0?void 0:{spanId:a.spanId,traceFlags:a.traceFlags,traceId:a.traceId}},m=createChannelOperations({adapter:f,channelName:n,metadata:p,runtime:t.runtime,turnPolicy:d?.turnPolicy}),h=createAttachSessionFn(t.runtime,{...p,turnPolicy:d?.turnPolicy}),g=createCrossChannelToFn(t.runtime,toCrossChannelTargets(t.channels)),_=attachRouteSessionCreator(attachHomeRouteMetadata(attachRouteChannelName(attachAgentInfoRouteResponse({attachSession:h,...m,params:u,requestIp:s,to:g,waitUntil},async()=>{let{handleAgentInfoRequest:e}=await import(`#internal/nitro/routes/info.js`);return await e(i)}),n),{agentName:t.agentName}),async e=>await t.runtime.createSession({...e,adapter:f,channelName:n,continuationToken:e.continuationToken===void 0?void 0:`${n}:${e.continuationToken}`,delivery:createChannelDeliveryMetadata(p),requestId:o}));return t.resolveRemoteAgentStreamHeaders!==void 0&&attachRemoteAgentStreamHeadersResolver(_,t.resolveRemoteAgentStreamHeaders),{args:_,backgroundTasks:c}}function readVercelRequestId(e){let t=e.get(`x-vercel-id`)?.trim();return t===``?void 0:t}function rejectWebSocketUpgrade(e,t){return{upgrade(){throw Response.json(e,{status:t})}}}function flushBackgroundTasks(e,t,n,r){t.length!==0&&e.waitUntil(Promise.allSettled(t).then(e=>{for(let t of e)t.status===`rejected`&&logError(log,`channel background task failed`,t.reason,{routeKey:n,channel:r})}))}function extractRequestIp(e,t){if(t.kind===`development`){let t=readTrustedDevelopmentClientAddress(e.req.headers,process.env[DEVELOPMENT_WORKFLOW_SECRET_ENV]);if(t!==void 0)return t}return extractSocketIp(e)}function extractSocketIp(e){let t=e.req.ip;return typeof t==`string`&&t.length>0?t:null}export{dispatchChannelRequest,dispatchChannelWebSocketRequest};
|
|
@@ -16,15 +16,14 @@ export interface TraceChannelRequestInput {
|
|
|
16
16
|
*
|
|
17
17
|
* The handler runs inside the span's active context. When it returns, the
|
|
18
18
|
* response status is recorded and a `>= 500` status marks the span as an
|
|
19
|
-
* error. A thrown handler
|
|
20
|
-
*
|
|
21
|
-
* are recorded by `logError` against this active span, so they are not
|
|
22
|
-
* recorded a second time here. The span always ends in `finally`, without
|
|
19
|
+
* error. A thrown handler marks failure status and is rethrown; request
|
|
20
|
+
* spans never record exception content. The span always ends in `finally`, without
|
|
23
21
|
* waiting for `event.waitUntil()` work or streamed response bodies.
|
|
24
22
|
*
|
|
25
23
|
* Emitting these spans is opt-in: unless authored instrumentation enables it
|
|
26
24
|
* via `traceChannelRequests: true`, the handler runs with no span (`undefined`)
|
|
27
|
-
* and no
|
|
25
|
+
* and performs no header extraction. The channel dispatcher can still use an
|
|
26
|
+
* already-active platform span for the activation's cross-trace link.
|
|
28
27
|
*
|
|
29
28
|
* This is observability-only: it never changes the response and performs no
|
|
30
29
|
* synchronous span export in the request path, adding only minimal in-process
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{AGENT_SPAN_NAMES}from"#tracing/agent-span-contract.js";import{getInstrumentationRuntime}from"#instrumentation/runtime.js";import{SpanKind,SpanStatusCode,context,propagation,trace}from"#compiled/@opentelemetry/api/index.js";import{markAgentTraceContext}from"#tracing/agent-trace-context.js";import{withErrorContent}from"#tracing/error-content-context.js";import{agentSpanNamingAttributes}from"#tracing/agent-span-naming.js";const headersGetter={get(e,t){return e.get(t)??void 0},keys(e){return[...e.keys()]}};async function traceChannelRequest(e,t){if(getInstrumentationRuntime()?.otelSettings?.traceChannelRequests!==!0)return await t(void 0);let{request:n,routeKey:r}=e,i=propagation.extract(context.active(),n.headers,headersGetter),a=getInstrumentationRuntime()?.instrumentationProviders===!0?AGENT_SPAN_NAMES.channelRequest:r,o=trace.getTracer(`eve.channel`).startSpan(a,{attributes:{...baseAttributes(n,r),...a===`agent.channel.request`?agentSpanNamingAttributes(a):void 0},kind:SpanKind.SERVER},i),s=markAgentTraceContext(withErrorContent(trace.setSpan(i,o),!1));try{let e=await context.with(s,()=>t(o));return o.setAttribute(`http.response.status_code`,e.status),e.status>=500&&o.setStatus({code:SpanStatusCode.ERROR}),e}catch(e){throw o.setStatus({code:SpanStatusCode.ERROR}),e}finally{o.end()}}function baseAttributes(e,t){let n={"http.request.method":e.method,"http.route":routeTemplate(t)},r=parseRequestUrl(e.url);return r!==void 0&&(n[`url.scheme`]=r.protocol.replace(/:$/,``),n[`server.address`]=r.hostname),n}function routeTemplate(e){let t=e.indexOf(` `);return t===-1?e:e.slice(t+1)}function parseRequestUrl(e){try{return new URL(e)}catch{return}}export{traceChannelRequest};
|
|
@@ -1,6 +1,19 @@
|
|
|
1
1
|
import type { ForwardedTraceAssertion } from "#shared/forwarded-trace-policy.js";
|
|
2
|
+
interface BaggageProperty {
|
|
3
|
+
readonly key: string;
|
|
4
|
+
readonly value?: string;
|
|
5
|
+
}
|
|
6
|
+
interface BaggageMember {
|
|
7
|
+
readonly value: string;
|
|
8
|
+
readonly properties: readonly BaggageProperty[];
|
|
9
|
+
}
|
|
2
10
|
export type ForwardedTraceBaggage = "absent" | "malformed" | ForwardedTraceAssertion;
|
|
3
|
-
/** Reads
|
|
11
|
+
/** Reads eve's audience member without interpreting unrelated baggage. */
|
|
4
12
|
export declare function readForwardedAudienceBaggage(value: string | null): ForwardedTraceBaggage;
|
|
5
|
-
/** Replaces any authored
|
|
13
|
+
/** Replaces any authored eve audience member while preserving unrelated baggage entries. */
|
|
6
14
|
export declare function writeForwardedAudienceBaggage(value: string | undefined, assertion: ForwardedTraceAssertion | undefined): string | undefined;
|
|
15
|
+
/** Recognized members are singular; malformed or oversized input fails closed. */
|
|
16
|
+
export declare function readBaggageMember(value: string | null, key: string): BaggageMember | "absent" | "malformed";
|
|
17
|
+
/** Replaces a member with an encoded value and optional properties; undefined removes it. */
|
|
18
|
+
export declare function replaceBaggageMember(value: string | undefined, key: string, member: string | undefined): string | undefined;
|
|
19
|
+
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{formatTraceContentCeiling}from"#shared/forwarded-trace-policy.js";const EVE_AUDIENCE_KEY=`eve.audience`,CEILING_PROPERTY_KEY=`ceiling
|
|
1
|
+
import{formatTraceContentCeiling}from"#shared/forwarded-trace-policy.js";const EVE_AUDIENCE_KEY=`eve.audience`,CEILING_PROPERTY_KEY=`ceiling`,MAX_BAGGAGE_BYTES=8192,encoder=new TextEncoder,decoder=new TextDecoder(`utf-8`,{ignoreBOM:!0});function readForwardedAudienceBaggage(e){let t=readBaggageMember(e,EVE_AUDIENCE_KEY);if(typeof t==`string`)return t;let n=t.value;if(n!==`public`&&n!==`private`&&n!==`unknown`)return`malformed`;let r=t.properties[0];if(t.properties.length!==1||r?.key!==CEILING_PROPERTY_KEY)return`malformed`;let i=r.value===void 0?void 0:parseCeiling(r.value);return i===void 0?`malformed`:{ceiling:i,originAudience:n}}function writeForwardedAudienceBaggage(e,t){return replaceBaggageMember(e,EVE_AUDIENCE_KEY,t===void 0?void 0:`${t.originAudience};${CEILING_PROPERTY_KEY}=${formatTraceContentCeiling(t.ceiling)}`)}function readBaggageMember(e,t){if(e===null)return`absent`;if(e.length>MAX_BAGGAGE_BYTES||encoder.encode(e).byteLength>MAX_BAGGAGE_BYTES)return`malformed`;let n=baggageMembers(e).filter(e=>baggageKey(e)===t);if(n.length===0)return`absent`;if(n.length!==1)return`malformed`;let[r,...i]=n[0].split(`;`),a=parsePair(r);if(a?.value===void 0)return`malformed`;let o=[];for(let e of i){let t=parsePair(e);if(t===void 0)return`malformed`;o.push(t)}return{value:a.value,properties:o}}function replaceBaggageMember(e,t,n){let r=baggageMembers(e??``).filter(e=>baggageKey(e)!==t);if(n!==void 0){let e=[...r,`${t}=${n}`].join(`,`);if(encoder.encode(e).byteLength>MAX_BAGGAGE_BYTES)throw Error(`Cannot forward baggage: header exceeds 8192 bytes. Reduce remote.headers.baggage.`);return e}return r.join(`,`)||void 0}function baggageMembers(e){return e.split(`,`).map(trimOws).filter(Boolean)}function parsePair(e){let t=e.indexOf(`=`),n=trimOws(t<0?e:e.slice(0,t));if(!/^[!#$%&'*+\-.^_`|~\w]+$/u.test(n))return;if(t<0)return{key:n};let r=trimOws(e.slice(t+1));if(!/^[\x21\x23-\x2b\x2d-\x3a\x3c-\x5b\x5d-\x7e]*$/u.test(r)||/%(?![\da-f]{2})/iu.test(r))return;let i=Uint8Array.from(r.match(/%[\da-f]{2}|./giu)??[],e=>e.startsWith(`%`)?Number.parseInt(e.slice(1),16):e.charCodeAt(0));return{key:n,value:decoder.decode(i)}}function parseCeiling(e){let t=/^i([01])o([01])$/u.exec(e);return t===null?void 0:{recordInputs:t[1]===`1`,recordOutputs:t[2]===`1`}}function trimOws(e){return e.replace(/^[\t ]+|[\t ]+$/gu,``)}function baggageKey(e){let t=e.split(`;`,1)[0],n=t.indexOf(`=`);return(n<0?t:t.slice(0,n)).trim()}export{readBaggageMember,readForwardedAudienceBaggage,replaceBaggageMember,writeForwardedAudienceBaggage};
|
|
@@ -138,10 +138,11 @@ export interface InstrumentationDefinition {
|
|
|
138
138
|
*/
|
|
139
139
|
readonly recordOutputs?: boolean;
|
|
140
140
|
/**
|
|
141
|
-
* Whether to emit
|
|
142
|
-
* request
|
|
143
|
-
*
|
|
144
|
-
*
|
|
141
|
+
* Whether to emit an eve-owned HTTP `SERVER` span around each channel
|
|
142
|
+
* request. In the authored hierarchy, this span parents the turn trace. In
|
|
143
|
+
* the provider layout, a one-to-one activation remains a separate trace
|
|
144
|
+
* root and links to this span; when disabled, it links to any already-active
|
|
145
|
+
* upstream request or function span instead. Defaults to `false`.
|
|
145
146
|
*/
|
|
146
147
|
readonly traceChannelRequests?: boolean;
|
|
147
148
|
/**
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { HarnessModelMessage } from "#harness/messages.js";
|
|
2
2
|
import type { PreparedRuntimeTool } from "#runtime/sessions/turn.js";
|
|
3
3
|
import type { ResolvedAgent, ResolvedAgentDefinition } from "#runtime/types.js";
|
|
4
4
|
import type { WorkspaceRuntimeSpec } from "#runtime/workspace/types.js";
|
|
@@ -27,7 +27,7 @@ interface RuntimeTurnAgentBase {
|
|
|
27
27
|
readonly availableSkills?: readonly AvailableSkillDescription[];
|
|
28
28
|
readonly id: string;
|
|
29
29
|
readonly instructions: readonly string[];
|
|
30
|
-
readonly initialMessages?: readonly
|
|
30
|
+
readonly initialMessages?: readonly HarnessModelMessage[];
|
|
31
31
|
/**
|
|
32
32
|
* Optional model used only for compaction summaries.
|
|
33
33
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{composeRuntimeBasePrompt}from"#runtime/prompt/compose.js";const BOOTSTRAP_RUNTIME_MODEL_ID=`eve-bootstrap-model`,BOOTSTRAP_RUNTIME_SYSTEM_PROMPT=`You are the eve bootstrap agent. Be concise, stay grounded in the current conversation, and do not assume tools are available unless the runtime provides them.`;function createResolvedRuntimeTurnAgent(e){let t=e.agent,n=t.config,r=e.id??n?.name;if(r===void 0)throw Error(`Expected a path-derived agent id while resolving agent resources.`);let i=e.tools.some(e=>e.kind===`subagent`||e.kind===`remote`),a=e.tools.some(e=>e.behavior?.handling?.kind===`dispatch`&&e.behavior.handling.target.kind===`self-agent-call`),o={availableSkills:t.skills.map(e=>({description:e.description,name:e.name})),id:r,initialMessages:t.instructions.filter(e=>e.role===`user`&&e.content.trim().length>0).map(e=>(
|
|
1
|
+
import{createFrameworkUserMessage}from"#harness/messages.js";import{composeRuntimeBasePrompt}from"#runtime/prompt/compose.js";const BOOTSTRAP_RUNTIME_MODEL_ID=`eve-bootstrap-model`,BOOTSTRAP_RUNTIME_SYSTEM_PROMPT=`You are the eve bootstrap agent. Be concise, stay grounded in the current conversation, and do not assume tools are available unless the runtime provides them.`;function createResolvedRuntimeTurnAgent(e){let t=e.agent,n=t.config,r=e.id??n?.name;if(r===void 0)throw Error(`Expected a path-derived agent id while resolving agent resources.`);let i=e.tools.some(e=>e.kind===`subagent`||e.kind===`remote`),a=e.tools.some(e=>e.behavior?.handling?.kind===`dispatch`&&e.behavior.handling.target.kind===`self-agent-call`),o={availableSkills:t.skills.map(e=>({description:e.description,name:e.name})),id:r,initialMessages:t.instructions.filter(e=>e.role===`user`&&e.content.trim().length>0).map(e=>createFrameworkUserMessage(`context.instruction`,e.content.trim())),instructions:composeRuntimeBasePrompt({connections:t.connections,instructions:t.instructions,subagentsAvailable:e.dynamicSubagentsAvailable===!0||i||a,toolsAvailable:e.tools.length>0,workspaceSpec:t.workspaceSpec}),compactionModel:n?.compaction?.model,nodeId:e.nodeId,outputSchema:n?.outputSchema,reasoning:n?.reasoning,tools:[...e.tools],workspaceSpec:t.workspaceSpec};return n===void 0?{...o,configResolver:!0}:n.dynamicModel===void 0?{...o,model:n.model}:{...o,dynamicModel:n.dynamicModel}}export{BOOTSTRAP_RUNTIME_MODEL_ID,BOOTSTRAP_RUNTIME_SYSTEM_PROMPT,createResolvedRuntimeTurnAgent};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{resolveSelfModificationConfig}from"./config.js";import{hasGitHubCredential}from"./credentials.js";import{resolveSelfModificationMode}from"./mode.js";import{defineAgent,defineDynamic}from"#public/index.js";const DEFAULT_SELF_MODIFICATION_MODEL=`anthropic/claude-sonnet-5`;function defineSelfModificationAgent(e={}){let t=e.model??`anthropic/claude-sonnet-5`,n=resolveSelfModificationConfig(e.config),resolve=async(e,r)=>{let i=resolveSelfModificationMode(n)
|
|
1
|
+
import{resolveSelfModificationConfig}from"./config.js";import{hasGitHubCredential}from"./credentials.js";import{resolveSelfModificationMode}from"./mode.js";import{defineAgent,defineDynamic}from"#public/index.js";const DEFAULT_SELF_MODIFICATION_MODEL=`anthropic/claude-sonnet-5`;function renderDescription(e){return e.filter(e=>e.length>0).join(` `)}function defineSelfModificationAgent(e={}){let t=e.model??`anthropic/claude-sonnet-5`,n=resolveSelfModificationConfig(e.config),resolve=async(e,r)=>{let i=resolveSelfModificationMode(n),a=renderDescription([`Delegate here when the user asks to change this eve agent or its authored source.`,`If the requested change references a tool or skill, include the exact identifier. Do not infer source paths; let the child resolve the appropriate file under /source. Delegate the requested change and existing constraints without adding unrequested features, implementation steps, or reporting requirements.`,`Treat requests for persistent changes to future behavior or capabilities as source-modification requests, even when the requester does not mention files or source code. Infer persistence from the request and conversation rather than waiting for phrases such as “modify your source.” For example, asking the agent to stop always doing something, add a capability, or change future responses calls for inspecting and editing the authored source instead of providing a one-turn workaround.`,i===`local`?`Delegate questions about which integrations, channels, connections, or capabilities are available to add: the subagent searches the eve registry and reports exact item addresses instead of guessing them.`:`Delegate requests to add integrations, channels, connections, or capabilities: the subagent searches the official eve registry and can install source changes into the draft proposal. Setup may require non-secret answers or an external action, and secret binding remains separate.`,i===`local`?`Delegate requests to investigate, diagnose, or optimize the agent's behavior from local traces to this subagent: it can inspect the invoking session's trace and make persistent source changes when warranted.`:``,`Resolve short follow-ups such as “yes” or “do it” against the preceding conversation. If whether the requested change should persist is genuinely ambiguous, ask one concise clarifying question.`,i===`local`?`Source edits do not affect the caller’s current turn. After this subagent reports changes, do not invoke edited tools or attempt runtime verification until a new user turn.`:`Source edits do not affect the caller’s current turn. The subagent can publish only a draft pull request, and changes become effective only after review, merge, and redeployment.`]);if(i===`local`)return defineAgent({description:a,model:t});if(i!==`deployed`||n.deployed===void 0||n.deployed.credentials.kind===`pat`&&!hasGitHubCredential())return null;try{if(!await n.deployed.authorize({channel:r.channel,principal:r.session.auth.current}))return null}catch{return null}return defineAgent({description:a,model:t})};return defineDynamic({events:{"session.started":resolve,"turn.started":resolve}})}var agent_default=defineSelfModificationAgent();export{DEFAULT_SELF_MODIFICATION_MODEL,agent_default as default,defineSelfModificationAgent};
|