autotel-genai 0.15.3 → 0.16.0

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/README.md CHANGED
@@ -610,6 +610,81 @@ session-level latency are ordinary queries. This is the same hierarchy vendor
610
610
  LLM-analytics products sell as `$ai_session_id`; here it is spec, so it works
611
611
  wherever the spans land.
612
612
 
613
+ ### Signals: model judgments on requests (experimental)
614
+
615
+ `autotel-genai/signals` asks an evaluation model questions about finished
616
+ requests and records the answer as a typed attribute with a confidence:
617
+ `signals.fault.value = 'upstream'`, `signals.fault.confidence = 0.93`. Group by
618
+ it, alert on it, or use it to keep requests sampling would drop. It is built on
619
+ the AI SDK's `experimental_evaluate` model contract, so it is experimental.
620
+
621
+ You bring the model. There is no default model or provider and no key handling:
622
+ pass any AI SDK evaluation model (`EvaluationModelV4`), configured the way that
623
+ provider documents.
624
+
625
+ ```ts
626
+ import { init } from 'autotel';
627
+ import { createSignals, defineSignal } from 'autotel-genai/signals';
628
+
629
+ const fault = defineSignal({
630
+ name: 'fault',
631
+ when: (e) => (e.status ?? 0) >= 500,
632
+ ask: 'Who is responsible for this failure?',
633
+ choice: {
634
+ client: 'Bad input, expired session, client mistake',
635
+ app: 'Our own code or configuration',
636
+ upstream: 'A third-party dependency failed',
637
+ },
638
+ cacheKey: (e) => String(e['error.type'] ?? e.name),
639
+ });
640
+
641
+ const silentFailure = defineSignal({
642
+ name: 'silent_failure',
643
+ when: (e) => e.status === 200 && e.name === 'POST /api/checkout',
644
+ ask: 'Returned 200, but the customer did not get what they came for',
645
+ keep: (v) => v.value && v.confidence > 0.8,
646
+ });
647
+
648
+ init({
649
+ service: 'shop',
650
+ spanEnrichers: [
651
+ createSignals({
652
+ model: evaluationModel, // any AI SDK evaluation model
653
+ signals: [fault, silentFailure],
654
+ budget: { perMinute: 600 },
655
+ }),
656
+ ],
657
+ });
658
+ ```
659
+
660
+ - **Register it in `spanEnrichers`,** not `spanProcessors`: autotel drains
661
+ enrichers before its exporters shut down, so answers still pending at exit
662
+ are exported. With your own `NodeSDK`, keep that order with
663
+ `new EnrichedSpanProcessor([signals], [exportProcessor])` from `autotel`.
664
+ - **What is judged:** request spans, meaning spans with no parent or a remote
665
+ one. A signal's `when` sees the span's attributes plus `name`, `status`
666
+ (`http.response.status_code`), `error` and `durationMs`. All signals due for
667
+ one request go into one model call.
668
+ - **Where answers land:** a span is immutable once it ends and a model call is
669
+ async, so fresh answers go on a `signals {request}` child span in the same
670
+ trace, which also parents the traced `evaluate` call. Answers served from
671
+ `cacheKey` are known at once and go on the request span itself.
672
+ - **`keep`:** tail sampling decides per span when the span ends. A cached answer
673
+ that keeps marks the request span kept before tail sampling reads it. A fresh
674
+ answer arrives after that, so the request span and its children may already
675
+ be dropped; the signals span always exports, and when `keep` holds on a
676
+ dropped request it carries the request's attributes as `signals.event.*`.
677
+ Use `cacheKey` on keep signals that should promote the request span itself.
678
+ - **What leaves the process:** the request's attributes, after
679
+ `redact` (default: the `default` redaction preset, because request spans reach
680
+ this processor before the export pipeline's redactor). Use `state` to send
681
+ only the fields a question needs, and `maxStateChars` to skip large requests.
682
+ - **Failure:** over budget, during the cooldown after a failed call, or past
683
+ `timeoutMs` (default 2s), requests go unjudged and pass through unchanged.
684
+ `stats()` counts calls, skipped, errors, cached and kept.
685
+ - **Tests:** `scriptedEvaluationModel((name, question, state) => answer)` stands
686
+ in for a provider and records every call.
687
+
613
688
  ### Sending the same spans to PostHog
614
689
 
615
690
  PostHog ingests plain OTLP: `PostHogSpanProcessor` from `@posthog/ai/otel`
@@ -1,4 +1,4 @@
1
- import { $ as withScopedTool, A as TOOL_CALL_ID_LABEL, B as HoneyTokenToolOptions, C as SEQUENCE_RULES, Ct as hashPayload, D as SequenceSecurityEvent, E as SequenceRule, F as spansToSequenceEvents, G as CrossAgentMonitor, H as EVAL_IDENTITY_ATTR, I as EvalIncidentQueryResult, J as CrossAgentEvent, K as CrossAgentMonitorOptions, L as querySpansForEvalIncident, M as detectSequences, N as emitSequenceDetections, O as SequenceSeverity, P as sequenceDetectionsToSecurityEvents, Q as detectCrossAgentPattern, R as spansToCrossAgentEvents, S as POLICY_DECISION_LABEL, St as canonicalizeForHash, T as SequenceEvent, U as RecordEvalRunIdentityInput, V as createHoneyTokenTool, W as recordEvalRunIdentity, X as DetectCrossAgentPatternOptions, Y as CrossAgentSecurityEvent, Z as crossAgentDetectionsToSecurityEvents, _ as sequenceRulesToSigma, _t as recordAgentHandoff, a as AgentPlanRiskVerdict, at as RotateAgentIdentityInput, b as DETECTION_EVENT, bt as createAgentAuditMetadata, c as recordPlanRiskAssessment, ct as defineAgentAction, d as DETECTION_DISPOSITION_EVENT, dt as recordPolicyDecision, et as CreateSignedEventEnvelopeOptions, f as DetectionDispositionStatus, ft as withAgentAction, g as sequenceRuleToSigma, gt as delegateToAgent, h as SigmaDocument, ht as RecordAgentHandoffMetadata, i as AgentPlanClassifierResult, it as RevokeAgentIdentityInput, j as TOOL_NAME_LABEL, k as SequenceSpanLike, l as runAgentPlanClassifier, lt as defineAgentToolCall, m as recordDetectionDisposition, mt as DelegateToAgentInput, n as AgentPlanClassifier, nt as verifyEventEnvelopeHash, o as RecordPlanRiskAssessmentOptions, ot as createAgentIdentityRegistry, p as RecordDetectionDispositionInput, pt as withAgentToolCall, q as CrossAgentDetection, r as AgentPlanClassifierInput, rt as ProvisionAgentIdentityInput, s as heuristicPlanRiskClassifier, st as withAgentSession, t as AGENT_PLAN_RISK_ATTR, tt as createSignedEventEnvelope, u as DETECTION_DISPOSITION_ATTR, ut as recordDecisionBasis, v as AGENT_OUTCOME_LABEL, vt as flattenAgentAttributes, w as SequenceDetection, wt as AGENT_AUDIT_SCHEMA_VERSION, x as EmitSequenceDetectionsOptions, xt as HashPayloadOptions, y as DETECTION_ATTR, yt as setAgentAttributes, z as HoneyTokenToolDefinition } from "../index-Dg6xJssP.cjs";
1
+ import { $ as withScopedTool, A as TOOL_CALL_ID_LABEL, B as HoneyTokenToolOptions, C as SEQUENCE_RULES, Ct as hashPayload, D as SequenceSecurityEvent, E as SequenceRule, F as spansToSequenceEvents, G as CrossAgentMonitor, H as EVAL_IDENTITY_ATTR, I as EvalIncidentQueryResult, J as CrossAgentEvent, K as CrossAgentMonitorOptions, L as querySpansForEvalIncident, M as detectSequences, N as emitSequenceDetections, O as SequenceSeverity, P as sequenceDetectionsToSecurityEvents, Q as detectCrossAgentPattern, R as spansToCrossAgentEvents, S as POLICY_DECISION_LABEL, St as canonicalizeForHash, T as SequenceEvent, U as RecordEvalRunIdentityInput, V as createHoneyTokenTool, W as recordEvalRunIdentity, X as DetectCrossAgentPatternOptions, Y as CrossAgentSecurityEvent, Z as crossAgentDetectionsToSecurityEvents, _ as sequenceRulesToSigma, _t as recordAgentHandoff, a as AgentPlanRiskVerdict, at as RotateAgentIdentityInput, b as DETECTION_EVENT, bt as createAgentAuditMetadata, c as recordPlanRiskAssessment, ct as defineAgentAction, d as DETECTION_DISPOSITION_EVENT, dt as recordPolicyDecision, et as CreateSignedEventEnvelopeOptions, f as DetectionDispositionStatus, ft as withAgentAction, g as sequenceRuleToSigma, gt as delegateToAgent, h as SigmaDocument, ht as RecordAgentHandoffMetadata, i as AgentPlanClassifierResult, it as RevokeAgentIdentityInput, j as TOOL_NAME_LABEL, k as SequenceSpanLike, l as runAgentPlanClassifier, lt as defineAgentToolCall, m as recordDetectionDisposition, mt as DelegateToAgentInput, n as AgentPlanClassifier, nt as verifyEventEnvelopeHash, o as RecordPlanRiskAssessmentOptions, ot as createAgentIdentityRegistry, p as RecordDetectionDispositionInput, pt as withAgentToolCall, q as CrossAgentDetection, r as AgentPlanClassifierInput, rt as ProvisionAgentIdentityInput, s as heuristicPlanRiskClassifier, st as withAgentSession, t as AGENT_PLAN_RISK_ATTR, tt as createSignedEventEnvelope, u as DETECTION_DISPOSITION_ATTR, ut as recordDecisionBasis, v as AGENT_OUTCOME_LABEL, vt as flattenAgentAttributes, w as SequenceDetection, wt as AGENT_AUDIT_SCHEMA_VERSION, x as EmitSequenceDetectionsOptions, xt as HashPayloadOptions, y as DETECTION_ATTR, yt as setAgentAttributes, z as HoneyTokenToolDefinition } from "../index-BjaNCZv3.cjs";
2
2
  import { i as ModelPricing, s as TokenUsage } from "../cost-B8rIvXTK.cjs";
3
3
  import { $ as PrivacyProfileName, A as AgentAiMetadata, B as AgentOutcome, C as recordMemoryAccess, D as AgentActionFactory, E as tryRecordHumanApproval, F as AgentIdentity, G as AgentToolCallOptions, H as AgentSessionMetadata, I as AgentIdentityRecord, K as AiLifecycleStage, L as AgentIdentityRegistry, M as AgentDecisionMetadata, N as AgentEventKind, O as AgentActionMetadata, P as AgentHandler, Q as PrivacyProfile, R as AgentIdentityStatus, S as recordInputProvenance, T as recordRenderOutput, U as AgentSessionStatus, V as AgentSessionActionMetadata, W as AgentToolCallActionMetadata, X as PolicyDecision, Y as GovernanceMetadata, Z as PolicyMetadata, _ as deriveActionRiskClass, a as AgentConsentOutcome, at as resolvePrivacyProfile, b as recordControllerId, c as AgentOutputFormat, ct as AgentContext, d as RecordControllerInput, et as ScopedToolDefinition, f as RecordHumanApprovalInput, g as RecordRenderOutputInput, h as RecordPlanStepInput, i as AgentConsentEvidence, it as SanitizationEvidence, j as AgentAuditEventEnvelope, k as AgentActionOptions, l as AgentSecurityRecordOptions, lt as agentContextFromSpan, m as RecordMemoryAccessInput, n as ActionRiskHints, nt as ToolStatus, o as AgentInputProvenance, ot as sanitizeAuditPayload, p as RecordInputProvenanceInput, q as DelegationContext, r as AgentActionRiskClass, rt as PrivacyProfileInput, s as AgentMemoryOperation, st as sanitizeAuditPayloadWithEvidence, t as AGENT_SECURITY_ATTR, tt as ToolCallMetadata, u as RecordActiveScopesInput, v as recordActionRiskClass, w as recordPlanStep, x as recordHumanApproval, y as recordActiveScopes, z as AgentMetadataInput } from "../agent-security-Bw7YX5sg.cjs";
4
4
  export { AGENT_AUDIT_SCHEMA_VERSION, AGENT_OUTCOME_LABEL, AGENT_PLAN_RISK_ATTR, AGENT_SECURITY_ATTR, type ActionRiskHints, type AgentActionFactory, type AgentActionMetadata, type AgentActionOptions, type AgentActionRiskClass, type AgentAiMetadata, type AgentAuditEventEnvelope, type AgentConsentEvidence, type AgentConsentOutcome, type AgentContext, type AgentDecisionMetadata, type AgentEventKind, type AgentHandler, type AgentIdentity, type AgentIdentityRecord, type AgentIdentityRegistry, type AgentIdentityStatus, type AgentInputProvenance, type AgentMemoryOperation, type AgentMetadataInput, type AgentOutcome, type AgentOutputFormat, type AgentPlanClassifier, type AgentPlanClassifierInput, type AgentPlanClassifierResult, type AgentPlanRiskVerdict, type AgentSecurityRecordOptions, type AgentSessionActionMetadata, type AgentSessionMetadata, type AgentSessionStatus, type AgentToolCallActionMetadata, type AgentToolCallOptions, type AiLifecycleStage, type CreateSignedEventEnvelopeOptions, type CrossAgentDetection, type CrossAgentEvent, CrossAgentMonitor, type CrossAgentMonitorOptions, type CrossAgentSecurityEvent, DETECTION_ATTR, DETECTION_DISPOSITION_ATTR, DETECTION_DISPOSITION_EVENT, DETECTION_EVENT, type DelegateToAgentInput, type DelegationContext, type DetectCrossAgentPatternOptions, type DetectionDispositionStatus, EVAL_IDENTITY_ATTR, type EmitSequenceDetectionsOptions, type EvalIncidentQueryResult, type GovernanceMetadata, type HashPayloadOptions, type HoneyTokenToolDefinition, type HoneyTokenToolOptions, type ModelPricing, POLICY_DECISION_LABEL, type PolicyDecision, type PolicyMetadata, type PrivacyProfile, type PrivacyProfileInput, type PrivacyProfileName, type ProvisionAgentIdentityInput, type RecordActiveScopesInput, type RecordAgentHandoffMetadata, type RecordControllerInput, type RecordDetectionDispositionInput, type RecordEvalRunIdentityInput, type RecordHumanApprovalInput, type RecordInputProvenanceInput, type RecordMemoryAccessInput, type RecordPlanRiskAssessmentOptions, type RecordPlanStepInput, type RecordRenderOutputInput, type RevokeAgentIdentityInput, type RotateAgentIdentityInput, SEQUENCE_RULES, type SanitizationEvidence, type ScopedToolDefinition, type SequenceDetection, type SequenceEvent, type SequenceRule, type SequenceSecurityEvent, type SequenceSeverity, type SequenceSpanLike, type SigmaDocument, TOOL_CALL_ID_LABEL, TOOL_NAME_LABEL, type TokenUsage, type ToolCallMetadata, type ToolStatus, agentContextFromSpan, canonicalizeForHash, createAgentAuditMetadata, createAgentIdentityRegistry, createHoneyTokenTool, createSignedEventEnvelope, crossAgentDetectionsToSecurityEvents, defineAgentAction, defineAgentToolCall, delegateToAgent, deriveActionRiskClass, detectCrossAgentPattern, detectSequences, emitSequenceDetections, flattenAgentAttributes, hashPayload, heuristicPlanRiskClassifier, querySpansForEvalIncident, recordActionRiskClass, recordActiveScopes, recordAgentHandoff, recordControllerId, recordDecisionBasis, recordDetectionDisposition, recordEvalRunIdentity, recordHumanApproval, recordInputProvenance, recordMemoryAccess, recordPlanRiskAssessment, recordPlanStep, recordPolicyDecision, recordRenderOutput, resolvePrivacyProfile, runAgentPlanClassifier, sanitizeAuditPayload, sanitizeAuditPayloadWithEvidence, sequenceDetectionsToSecurityEvents, sequenceRuleToSigma, sequenceRulesToSigma, setAgentAttributes, spansToCrossAgentEvents, spansToSequenceEvents, tryRecordHumanApproval, verifyEventEnvelopeHash, withAgentAction, withAgentSession, withAgentToolCall, withScopedTool };
@@ -1,4 +1,4 @@
1
- import { $ as withScopedTool, A as TOOL_CALL_ID_LABEL, B as HoneyTokenToolOptions, C as SEQUENCE_RULES, Ct as hashPayload, D as SequenceSecurityEvent, E as SequenceRule, F as spansToSequenceEvents, G as CrossAgentMonitor, H as EVAL_IDENTITY_ATTR, I as EvalIncidentQueryResult, J as CrossAgentEvent, K as CrossAgentMonitorOptions, L as querySpansForEvalIncident, M as detectSequences, N as emitSequenceDetections, O as SequenceSeverity, P as sequenceDetectionsToSecurityEvents, Q as detectCrossAgentPattern, R as spansToCrossAgentEvents, S as POLICY_DECISION_LABEL, St as canonicalizeForHash, T as SequenceEvent, U as RecordEvalRunIdentityInput, V as createHoneyTokenTool, W as recordEvalRunIdentity, X as DetectCrossAgentPatternOptions, Y as CrossAgentSecurityEvent, Z as crossAgentDetectionsToSecurityEvents, _ as sequenceRulesToSigma, _t as recordAgentHandoff, a as AgentPlanRiskVerdict, at as RotateAgentIdentityInput, b as DETECTION_EVENT, bt as createAgentAuditMetadata, c as recordPlanRiskAssessment, ct as defineAgentAction, d as DETECTION_DISPOSITION_EVENT, dt as recordPolicyDecision, et as CreateSignedEventEnvelopeOptions, f as DetectionDispositionStatus, ft as withAgentAction, g as sequenceRuleToSigma, gt as delegateToAgent, h as SigmaDocument, ht as RecordAgentHandoffMetadata, i as AgentPlanClassifierResult, it as RevokeAgentIdentityInput, j as TOOL_NAME_LABEL, k as SequenceSpanLike, l as runAgentPlanClassifier, lt as defineAgentToolCall, m as recordDetectionDisposition, mt as DelegateToAgentInput, n as AgentPlanClassifier, nt as verifyEventEnvelopeHash, o as RecordPlanRiskAssessmentOptions, ot as createAgentIdentityRegistry, p as RecordDetectionDispositionInput, pt as withAgentToolCall, q as CrossAgentDetection, r as AgentPlanClassifierInput, rt as ProvisionAgentIdentityInput, s as heuristicPlanRiskClassifier, st as withAgentSession, t as AGENT_PLAN_RISK_ATTR, tt as createSignedEventEnvelope, u as DETECTION_DISPOSITION_ATTR, ut as recordDecisionBasis, v as AGENT_OUTCOME_LABEL, vt as flattenAgentAttributes, w as SequenceDetection, wt as AGENT_AUDIT_SCHEMA_VERSION, x as EmitSequenceDetectionsOptions, xt as HashPayloadOptions, y as DETECTION_ATTR, yt as setAgentAttributes, z as HoneyTokenToolDefinition } from "../index-C7NU4O3l.js";
1
+ import { $ as withScopedTool, A as TOOL_CALL_ID_LABEL, B as HoneyTokenToolOptions, C as SEQUENCE_RULES, Ct as hashPayload, D as SequenceSecurityEvent, E as SequenceRule, F as spansToSequenceEvents, G as CrossAgentMonitor, H as EVAL_IDENTITY_ATTR, I as EvalIncidentQueryResult, J as CrossAgentEvent, K as CrossAgentMonitorOptions, L as querySpansForEvalIncident, M as detectSequences, N as emitSequenceDetections, O as SequenceSeverity, P as sequenceDetectionsToSecurityEvents, Q as detectCrossAgentPattern, R as spansToCrossAgentEvents, S as POLICY_DECISION_LABEL, St as canonicalizeForHash, T as SequenceEvent, U as RecordEvalRunIdentityInput, V as createHoneyTokenTool, W as recordEvalRunIdentity, X as DetectCrossAgentPatternOptions, Y as CrossAgentSecurityEvent, Z as crossAgentDetectionsToSecurityEvents, _ as sequenceRulesToSigma, _t as recordAgentHandoff, a as AgentPlanRiskVerdict, at as RotateAgentIdentityInput, b as DETECTION_EVENT, bt as createAgentAuditMetadata, c as recordPlanRiskAssessment, ct as defineAgentAction, d as DETECTION_DISPOSITION_EVENT, dt as recordPolicyDecision, et as CreateSignedEventEnvelopeOptions, f as DetectionDispositionStatus, ft as withAgentAction, g as sequenceRuleToSigma, gt as delegateToAgent, h as SigmaDocument, ht as RecordAgentHandoffMetadata, i as AgentPlanClassifierResult, it as RevokeAgentIdentityInput, j as TOOL_NAME_LABEL, k as SequenceSpanLike, l as runAgentPlanClassifier, lt as defineAgentToolCall, m as recordDetectionDisposition, mt as DelegateToAgentInput, n as AgentPlanClassifier, nt as verifyEventEnvelopeHash, o as RecordPlanRiskAssessmentOptions, ot as createAgentIdentityRegistry, p as RecordDetectionDispositionInput, pt as withAgentToolCall, q as CrossAgentDetection, r as AgentPlanClassifierInput, rt as ProvisionAgentIdentityInput, s as heuristicPlanRiskClassifier, st as withAgentSession, t as AGENT_PLAN_RISK_ATTR, tt as createSignedEventEnvelope, u as DETECTION_DISPOSITION_ATTR, ut as recordDecisionBasis, v as AGENT_OUTCOME_LABEL, vt as flattenAgentAttributes, w as SequenceDetection, wt as AGENT_AUDIT_SCHEMA_VERSION, x as EmitSequenceDetectionsOptions, xt as HashPayloadOptions, y as DETECTION_ATTR, yt as setAgentAttributes, z as HoneyTokenToolDefinition } from "../index-tyJsMeaN.js";
2
2
  import { i as ModelPricing, s as TokenUsage } from "../cost-B8rIvXTK.js";
3
3
  import { $ as PrivacyProfileName, A as AgentAiMetadata, B as AgentOutcome, C as recordMemoryAccess, D as AgentActionFactory, E as tryRecordHumanApproval, F as AgentIdentity, G as AgentToolCallOptions, H as AgentSessionMetadata, I as AgentIdentityRecord, K as AiLifecycleStage, L as AgentIdentityRegistry, M as AgentDecisionMetadata, N as AgentEventKind, O as AgentActionMetadata, P as AgentHandler, Q as PrivacyProfile, R as AgentIdentityStatus, S as recordInputProvenance, T as recordRenderOutput, U as AgentSessionStatus, V as AgentSessionActionMetadata, W as AgentToolCallActionMetadata, X as PolicyDecision, Y as GovernanceMetadata, Z as PolicyMetadata, _ as deriveActionRiskClass, a as AgentConsentOutcome, at as resolvePrivacyProfile, b as recordControllerId, c as AgentOutputFormat, ct as AgentContext, d as RecordControllerInput, et as ScopedToolDefinition, f as RecordHumanApprovalInput, g as RecordRenderOutputInput, h as RecordPlanStepInput, i as AgentConsentEvidence, it as SanitizationEvidence, j as AgentAuditEventEnvelope, k as AgentActionOptions, l as AgentSecurityRecordOptions, lt as agentContextFromSpan, m as RecordMemoryAccessInput, n as ActionRiskHints, nt as ToolStatus, o as AgentInputProvenance, ot as sanitizeAuditPayload, p as RecordInputProvenanceInput, q as DelegationContext, r as AgentActionRiskClass, rt as PrivacyProfileInput, s as AgentMemoryOperation, st as sanitizeAuditPayloadWithEvidence, t as AGENT_SECURITY_ATTR, tt as ToolCallMetadata, u as RecordActiveScopesInput, v as recordActionRiskClass, w as recordPlanStep, x as recordHumanApproval, y as recordActiveScopes, z as AgentMetadataInput } from "../agent-security-D3ZjviBy.js";
4
4
  export { AGENT_AUDIT_SCHEMA_VERSION, AGENT_OUTCOME_LABEL, AGENT_PLAN_RISK_ATTR, AGENT_SECURITY_ATTR, type ActionRiskHints, type AgentActionFactory, type AgentActionMetadata, type AgentActionOptions, type AgentActionRiskClass, type AgentAiMetadata, type AgentAuditEventEnvelope, type AgentConsentEvidence, type AgentConsentOutcome, type AgentContext, type AgentDecisionMetadata, type AgentEventKind, type AgentHandler, type AgentIdentity, type AgentIdentityRecord, type AgentIdentityRegistry, type AgentIdentityStatus, type AgentInputProvenance, type AgentMemoryOperation, type AgentMetadataInput, type AgentOutcome, type AgentOutputFormat, type AgentPlanClassifier, type AgentPlanClassifierInput, type AgentPlanClassifierResult, type AgentPlanRiskVerdict, type AgentSecurityRecordOptions, type AgentSessionActionMetadata, type AgentSessionMetadata, type AgentSessionStatus, type AgentToolCallActionMetadata, type AgentToolCallOptions, type AiLifecycleStage, type CreateSignedEventEnvelopeOptions, type CrossAgentDetection, type CrossAgentEvent, CrossAgentMonitor, type CrossAgentMonitorOptions, type CrossAgentSecurityEvent, DETECTION_ATTR, DETECTION_DISPOSITION_ATTR, DETECTION_DISPOSITION_EVENT, DETECTION_EVENT, type DelegateToAgentInput, type DelegationContext, type DetectCrossAgentPatternOptions, type DetectionDispositionStatus, EVAL_IDENTITY_ATTR, type EmitSequenceDetectionsOptions, type EvalIncidentQueryResult, type GovernanceMetadata, type HashPayloadOptions, type HoneyTokenToolDefinition, type HoneyTokenToolOptions, type ModelPricing, POLICY_DECISION_LABEL, type PolicyDecision, type PolicyMetadata, type PrivacyProfile, type PrivacyProfileInput, type PrivacyProfileName, type ProvisionAgentIdentityInput, type RecordActiveScopesInput, type RecordAgentHandoffMetadata, type RecordControllerInput, type RecordDetectionDispositionInput, type RecordEvalRunIdentityInput, type RecordHumanApprovalInput, type RecordInputProvenanceInput, type RecordMemoryAccessInput, type RecordPlanRiskAssessmentOptions, type RecordPlanStepInput, type RecordRenderOutputInput, type RevokeAgentIdentityInput, type RotateAgentIdentityInput, SEQUENCE_RULES, type SanitizationEvidence, type ScopedToolDefinition, type SequenceDetection, type SequenceEvent, type SequenceRule, type SequenceSecurityEvent, type SequenceSeverity, type SequenceSpanLike, type SigmaDocument, TOOL_CALL_ID_LABEL, TOOL_NAME_LABEL, type TokenUsage, type ToolCallMetadata, type ToolStatus, agentContextFromSpan, canonicalizeForHash, createAgentAuditMetadata, createAgentIdentityRegistry, createHoneyTokenTool, createSignedEventEnvelope, crossAgentDetectionsToSecurityEvents, defineAgentAction, defineAgentToolCall, delegateToAgent, deriveActionRiskClass, detectCrossAgentPattern, detectSequences, emitSequenceDetections, flattenAgentAttributes, hashPayload, heuristicPlanRiskClassifier, querySpansForEvalIncident, recordActionRiskClass, recordActiveScopes, recordAgentHandoff, recordControllerId, recordDecisionBasis, recordDetectionDisposition, recordEvalRunIdentity, recordHumanApproval, recordInputProvenance, recordMemoryAccess, recordPlanRiskAssessment, recordPlanStep, recordPolicyDecision, recordRenderOutput, resolvePrivacyProfile, runAgentPlanClassifier, sanitizeAuditPayload, sanitizeAuditPayloadWithEvidence, sequenceDetectionsToSecurityEvents, sequenceRuleToSigma, sequenceRulesToSigma, setAgentAttributes, spansToCrossAgentEvents, spansToSequenceEvents, tryRecordHumanApproval, verifyEventEnvelopeHash, withAgentAction, withAgentSession, withAgentToolCall, withScopedTool };
@@ -0,0 +1,75 @@
1
+ import { n as recordEvaluationResult } from "./events-KJTZlo22.js";
2
+ import { recordGenAiResponse, recordGenAiUsage, traceGenAI } from "./trace.js";
3
+ import { normalizeAiSdkProvider } from "./ai-sdk-bridge.js";
4
+
5
+ //#region src/ai-sdk-evaluate.ts
6
+ /** `gen_ai.operation.name` for an evaluation call; not yet in the semconv registry. */
7
+ const GEN_AI_OPERATION_EVALUATE = "evaluate";
8
+ /** Score value and label for the `gen_ai.evaluation.result` event of one answer. */
9
+ function evaluationScore(answer, options = {}) {
10
+ switch (answer.type) {
11
+ case "choice": {
12
+ return {
13
+ scoreLabel: answer.choice,
14
+ scoreValue: answer.probabilities?.[answer.choice]
15
+ };
16
+ }
17
+ case "score": {
18
+ return { scoreValue: answer.score };
19
+ }
20
+ case "boolean": {
21
+ const threshold = options.name === undefined ? undefined : options.booleanThresholds?.[options.name];
22
+ return {
23
+ scoreValue: answer.probability,
24
+ ...threshold === undefined ? {} : { scoreLabel: answer.probability >= threshold ? "yes" : "no" }
25
+ };
26
+ }
27
+ }
28
+ }
29
+ /**
30
+ * Wrap an AI SDK evaluation model so each call is traced. Returns a model with
31
+ * the same contract, so it drops into `experimental_evaluate({ model })`.
32
+ *
33
+ * @example
34
+ * ```ts
35
+ * const model = wrapEvaluationModel(typeSafeAi.evaluationModel('jev-latest'));
36
+ * const { answers } = await evaluate({ model, state, questions });
37
+ * ```
38
+ */
39
+ function wrapEvaluationModel(model, options = {}) {
40
+ const traced = traceGenAI({
41
+ operation: GEN_AI_OPERATION_EVALUATE,
42
+ provider: normalizeAiSdkProvider(model.provider),
43
+ model: model.modelId,
44
+ attributes: options.attributes,
45
+ metrics: options.metrics
46
+ })((ctx) => async (call) => {
47
+ const result = await model.doEvaluate(call);
48
+ const seen = result;
49
+ recordGenAiResponse(ctx, {
50
+ model: seen.response?.modelId,
51
+ id: seen.response?.id
52
+ });
53
+ if (seen.usage) {
54
+ recordGenAiUsage(ctx, model.modelId, seen.usage, options.cost);
55
+ }
56
+ for (const [name, answer] of Object.entries(seen.answers)) {
57
+ recordEvaluationResult(ctx, {
58
+ name,
59
+ ...evaluationScore(answer, {
60
+ name,
61
+ booleanThresholds: options.booleanThresholds
62
+ }),
63
+ responseId: seen.response?.id
64
+ });
65
+ }
66
+ return result;
67
+ });
68
+ return Object.create(model, { doEvaluate: {
69
+ value: traced,
70
+ enumerable: true
71
+ } });
72
+ }
73
+
74
+ //#endregion
75
+ export { evaluationScore as n, wrapEvaluationModel as r, GEN_AI_OPERATION_EVALUATE as t };
@@ -0,0 +1,74 @@
1
+ import { t as EstimateCostOptions } from "./cost-B8rIvXTK.js";
2
+ import { n as GenAiAttributeMap } from "./attributes-DAYkQi4W.js";
3
+ //#region src/ai-sdk-evaluate.d.ts
4
+ /** `gen_ai.operation.name` for an evaluation call; not yet in the semconv registry. */
5
+ declare const GEN_AI_OPERATION_EVALUATE = "evaluate";
6
+ /** One answer from `EvaluationModelV4Result.answers`, in the shape the AI SDK returns. */
7
+ type AiSdkEvaluationAnswer = {
8
+ type: 'choice';
9
+ choice: string;
10
+ probabilities?: Record<string, number>;
11
+ } | {
12
+ type: 'score';
13
+ score: number;
14
+ probabilities?: Record<string, number>;
15
+ } | {
16
+ type: 'boolean';
17
+ probability: number;
18
+ };
19
+ /** The parts of `EvaluationModelV4Result` this module reads. */
20
+ interface AiSdkEvaluationResult {
21
+ answers: Record<string, AiSdkEvaluationAnswer>;
22
+ usage?: {
23
+ inputTokens?: number;
24
+ outputTokens?: number;
25
+ };
26
+ response?: {
27
+ id?: string;
28
+ modelId?: string;
29
+ };
30
+ }
31
+ /** The parts of `EvaluationModelV4` this module needs; structural so `ai` is not a dependency. */
32
+ interface AiSdkEvaluationModel {
33
+ readonly provider: string;
34
+ readonly modelId: string;
35
+ doEvaluate(options: never): PromiseLike<AiSdkEvaluationResult>;
36
+ }
37
+ interface WrapEvaluationModelOptions {
38
+ /** Pricing lookup for `gen_ai.usage.cost.usd`; `recordCost: false` skips it. */
39
+ cost?: EstimateCostOptions & {
40
+ recordCost?: boolean;
41
+ };
42
+ /** Extra attributes for every evaluation span. */
43
+ attributes?: GenAiAttributeMap;
44
+ /** Record `gen_ai.client.*` metrics alongside the span (default on). */
45
+ metrics?: boolean;
46
+ /**
47
+ * Per-question P(true) cutoffs for boolean answers. When a threshold is set
48
+ * for an answer's name, `gen_ai.evaluation.score.label` becomes `yes` or `no`.
49
+ */
50
+ booleanThresholds?: Record<string, number>;
51
+ }
52
+ interface EvaluationScoreOptions {
53
+ /** Question id; used with {@link WrapEvaluationModelOptions.booleanThresholds}. */
54
+ name?: string;
55
+ booleanThresholds?: Record<string, number>;
56
+ }
57
+ /** Score value and label for the `gen_ai.evaluation.result` event of one answer. */
58
+ declare function evaluationScore(answer: AiSdkEvaluationAnswer, options?: EvaluationScoreOptions): {
59
+ scoreValue?: number;
60
+ scoreLabel?: string;
61
+ };
62
+ /**
63
+ * Wrap an AI SDK evaluation model so each call is traced. Returns a model with
64
+ * the same contract, so it drops into `experimental_evaluate({ model })`.
65
+ *
66
+ * @example
67
+ * ```ts
68
+ * const model = wrapEvaluationModel(typeSafeAi.evaluationModel('jev-latest'));
69
+ * const { answers } = await evaluate({ model, state, questions });
70
+ * ```
71
+ */
72
+ declare function wrapEvaluationModel<M extends AiSdkEvaluationModel>(model: M, options?: WrapEvaluationModelOptions): M;
73
+ //#endregion
74
+ export { GEN_AI_OPERATION_EVALUATE as a, wrapEvaluationModel as c, EvaluationScoreOptions as i, AiSdkEvaluationModel as n, WrapEvaluationModelOptions as o, AiSdkEvaluationResult as r, evaluationScore as s, AiSdkEvaluationAnswer as t };
@@ -0,0 +1,74 @@
1
+ import { t as EstimateCostOptions } from "./cost-B8rIvXTK.cjs";
2
+ import { n as GenAiAttributeMap } from "./attributes-DAOZehAi.cjs";
3
+ //#region src/ai-sdk-evaluate.d.ts
4
+ /** `gen_ai.operation.name` for an evaluation call; not yet in the semconv registry. */
5
+ declare const GEN_AI_OPERATION_EVALUATE = "evaluate";
6
+ /** One answer from `EvaluationModelV4Result.answers`, in the shape the AI SDK returns. */
7
+ type AiSdkEvaluationAnswer = {
8
+ type: 'choice';
9
+ choice: string;
10
+ probabilities?: Record<string, number>;
11
+ } | {
12
+ type: 'score';
13
+ score: number;
14
+ probabilities?: Record<string, number>;
15
+ } | {
16
+ type: 'boolean';
17
+ probability: number;
18
+ };
19
+ /** The parts of `EvaluationModelV4Result` this module reads. */
20
+ interface AiSdkEvaluationResult {
21
+ answers: Record<string, AiSdkEvaluationAnswer>;
22
+ usage?: {
23
+ inputTokens?: number;
24
+ outputTokens?: number;
25
+ };
26
+ response?: {
27
+ id?: string;
28
+ modelId?: string;
29
+ };
30
+ }
31
+ /** The parts of `EvaluationModelV4` this module needs; structural so `ai` is not a dependency. */
32
+ interface AiSdkEvaluationModel {
33
+ readonly provider: string;
34
+ readonly modelId: string;
35
+ doEvaluate(options: never): PromiseLike<AiSdkEvaluationResult>;
36
+ }
37
+ interface WrapEvaluationModelOptions {
38
+ /** Pricing lookup for `gen_ai.usage.cost.usd`; `recordCost: false` skips it. */
39
+ cost?: EstimateCostOptions & {
40
+ recordCost?: boolean;
41
+ };
42
+ /** Extra attributes for every evaluation span. */
43
+ attributes?: GenAiAttributeMap;
44
+ /** Record `gen_ai.client.*` metrics alongside the span (default on). */
45
+ metrics?: boolean;
46
+ /**
47
+ * Per-question P(true) cutoffs for boolean answers. When a threshold is set
48
+ * for an answer's name, `gen_ai.evaluation.score.label` becomes `yes` or `no`.
49
+ */
50
+ booleanThresholds?: Record<string, number>;
51
+ }
52
+ interface EvaluationScoreOptions {
53
+ /** Question id; used with {@link WrapEvaluationModelOptions.booleanThresholds}. */
54
+ name?: string;
55
+ booleanThresholds?: Record<string, number>;
56
+ }
57
+ /** Score value and label for the `gen_ai.evaluation.result` event of one answer. */
58
+ declare function evaluationScore(answer: AiSdkEvaluationAnswer, options?: EvaluationScoreOptions): {
59
+ scoreValue?: number;
60
+ scoreLabel?: string;
61
+ };
62
+ /**
63
+ * Wrap an AI SDK evaluation model so each call is traced. Returns a model with
64
+ * the same contract, so it drops into `experimental_evaluate({ model })`.
65
+ *
66
+ * @example
67
+ * ```ts
68
+ * const model = wrapEvaluationModel(typeSafeAi.evaluationModel('jev-latest'));
69
+ * const { answers } = await evaluate({ model, state, questions });
70
+ * ```
71
+ */
72
+ declare function wrapEvaluationModel<M extends AiSdkEvaluationModel>(model: M, options?: WrapEvaluationModelOptions): M;
73
+ //#endregion
74
+ export { GEN_AI_OPERATION_EVALUATE as a, wrapEvaluationModel as c, EvaluationScoreOptions as i, AiSdkEvaluationModel as n, WrapEvaluationModelOptions as o, AiSdkEvaluationResult as r, evaluationScore as s, AiSdkEvaluationAnswer as t };
@@ -0,0 +1,92 @@
1
+ const require_events = require('./events-CfLvw5tV.cjs');
2
+ const require_trace = require('./trace.cjs');
3
+ const require_ai_sdk_bridge = require('./ai-sdk-bridge.cjs');
4
+
5
+ //#region src/ai-sdk-evaluate.ts
6
+ /** `gen_ai.operation.name` for an evaluation call; not yet in the semconv registry. */
7
+ const GEN_AI_OPERATION_EVALUATE = "evaluate";
8
+ /** Score value and label for the `gen_ai.evaluation.result` event of one answer. */
9
+ function evaluationScore(answer, options = {}) {
10
+ switch (answer.type) {
11
+ case "choice": {
12
+ return {
13
+ scoreLabel: answer.choice,
14
+ scoreValue: answer.probabilities?.[answer.choice]
15
+ };
16
+ }
17
+ case "score": {
18
+ return { scoreValue: answer.score };
19
+ }
20
+ case "boolean": {
21
+ const threshold = options.name === undefined ? undefined : options.booleanThresholds?.[options.name];
22
+ return {
23
+ scoreValue: answer.probability,
24
+ ...threshold === undefined ? {} : { scoreLabel: answer.probability >= threshold ? "yes" : "no" }
25
+ };
26
+ }
27
+ }
28
+ }
29
+ /**
30
+ * Wrap an AI SDK evaluation model so each call is traced. Returns a model with
31
+ * the same contract, so it drops into `experimental_evaluate({ model })`.
32
+ *
33
+ * @example
34
+ * ```ts
35
+ * const model = wrapEvaluationModel(typeSafeAi.evaluationModel('jev-latest'));
36
+ * const { answers } = await evaluate({ model, state, questions });
37
+ * ```
38
+ */
39
+ function wrapEvaluationModel(model, options = {}) {
40
+ const traced = require_trace.traceGenAI({
41
+ operation: GEN_AI_OPERATION_EVALUATE,
42
+ provider: require_ai_sdk_bridge.normalizeAiSdkProvider(model.provider),
43
+ model: model.modelId,
44
+ attributes: options.attributes,
45
+ metrics: options.metrics
46
+ })((ctx) => async (call) => {
47
+ const result = await model.doEvaluate(call);
48
+ const seen = result;
49
+ require_trace.recordGenAiResponse(ctx, {
50
+ model: seen.response?.modelId,
51
+ id: seen.response?.id
52
+ });
53
+ if (seen.usage) {
54
+ require_trace.recordGenAiUsage(ctx, model.modelId, seen.usage, options.cost);
55
+ }
56
+ for (const [name, answer] of Object.entries(seen.answers)) {
57
+ require_events.recordEvaluationResult(ctx, {
58
+ name,
59
+ ...evaluationScore(answer, {
60
+ name,
61
+ booleanThresholds: options.booleanThresholds
62
+ }),
63
+ responseId: seen.response?.id
64
+ });
65
+ }
66
+ return result;
67
+ });
68
+ return Object.create(model, { doEvaluate: {
69
+ value: traced,
70
+ enumerable: true
71
+ } });
72
+ }
73
+
74
+ //#endregion
75
+ Object.defineProperty(exports, 'GEN_AI_OPERATION_EVALUATE', {
76
+ enumerable: true,
77
+ get: function () {
78
+ return GEN_AI_OPERATION_EVALUATE;
79
+ }
80
+ });
81
+ Object.defineProperty(exports, 'evaluationScore', {
82
+ enumerable: true,
83
+ get: function () {
84
+ return evaluationScore;
85
+ }
86
+ });
87
+ Object.defineProperty(exports, 'wrapEvaluationModel', {
88
+ enumerable: true,
89
+ get: function () {
90
+ return wrapEvaluationModel;
91
+ }
92
+ });