autotel-genai 0.2.1 → 0.3.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.
Files changed (95) hide show
  1. package/dist/agent/index.cjs +18 -1
  2. package/dist/agent/index.d.cts +3 -2
  3. package/dist/agent/index.d.ts +3 -2
  4. package/dist/agent/index.js +3 -2
  5. package/dist/{agent-CiG_LZL8.cjs → agent-2GmZ6vDV.cjs} +139 -66
  6. package/dist/agent-2GmZ6vDV.cjs.map +1 -0
  7. package/dist/agent-security-BhUTos0B.cjs +282 -0
  8. package/dist/agent-security-BhUTos0B.cjs.map +1 -0
  9. package/dist/agent-security-ChL0rIh-.js +181 -0
  10. package/dist/agent-security-ChL0rIh-.js.map +1 -0
  11. package/dist/agent-security-N6nE3V3A.d.cts +108 -0
  12. package/dist/agent-security-N6nE3V3A.d.cts.map +1 -0
  13. package/dist/agent-security-N6nE3V3A.d.ts +108 -0
  14. package/dist/agent-security-N6nE3V3A.d.ts.map +1 -0
  15. package/dist/{agent-DZL-uNAc.js → agent-yHB-GF6g.js} +111 -62
  16. package/dist/agent-yHB-GF6g.js.map +1 -0
  17. package/dist/guard.cjs +0 -0
  18. package/dist/guard.cjs.map +1 -1
  19. package/dist/guard.d.cts.map +1 -1
  20. package/dist/guard.d.ts.map +1 -1
  21. package/dist/guard.js +0 -0
  22. package/dist/guard.js.map +1 -1
  23. package/dist/{index-B-_TnylZ.d.cts → index-CGHFYLGQ.d.cts} +34 -2
  24. package/dist/index-CGHFYLGQ.d.cts.map +1 -0
  25. package/dist/{index-BI9B5CkX.d.ts → index-CIkLg2LA.d.ts} +34 -2
  26. package/dist/index-CIkLg2LA.d.ts.map +1 -0
  27. package/dist/{index-CedOJ0OP.d.ts → index-Dxt0bm0M.d.ts} +51 -11
  28. package/dist/index-Dxt0bm0M.d.ts.map +1 -0
  29. package/dist/{index-DMz730Z-.d.cts → index-DyghHy5i.d.cts} +51 -11
  30. package/dist/index-DyghHy5i.d.cts.map +1 -0
  31. package/dist/index.cjs +2 -2
  32. package/dist/index.d.cts +3 -2
  33. package/dist/index.d.ts +3 -2
  34. package/dist/index.js +2 -2
  35. package/dist/observer/index.cjs +1 -1
  36. package/dist/observer/index.d.cts +1 -1
  37. package/dist/observer/index.d.ts +1 -1
  38. package/dist/observer/index.js +1 -1
  39. package/dist/{observer-B4uWN5eC.js → observer-50RGrqzo.js} +38 -1
  40. package/dist/observer-50RGrqzo.js.map +1 -0
  41. package/dist/{observer-CJG83iQz.cjs → observer-BbhXgZBA.cjs} +38 -1
  42. package/dist/observer-BbhXgZBA.cjs.map +1 -0
  43. package/package.json +3 -4
  44. package/dist/agent-CiG_LZL8.cjs.map +0 -1
  45. package/dist/agent-DZL-uNAc.js.map +0 -1
  46. package/dist/index-B-_TnylZ.d.cts.map +0 -1
  47. package/dist/index-BI9B5CkX.d.ts.map +0 -1
  48. package/dist/index-CedOJ0OP.d.ts.map +0 -1
  49. package/dist/index-DMz730Z-.d.cts.map +0 -1
  50. package/dist/observer-B4uWN5eC.js.map +0 -1
  51. package/dist/observer-CJG83iQz.cjs.map +0 -1
  52. package/src/agent/agent.test.ts +0 -874
  53. package/src/agent/attributes.ts +0 -162
  54. package/src/agent/constants.ts +0 -1
  55. package/src/agent/context.ts +0 -125
  56. package/src/agent/delegation.ts +0 -98
  57. package/src/agent/hash.ts +0 -44
  58. package/src/agent/identity-registry.ts +0 -188
  59. package/src/agent/index.ts +0 -45
  60. package/src/agent/metadata.ts +0 -254
  61. package/src/agent/non-repudiation.ts +0 -70
  62. package/src/agent/privacy.ts +0 -128
  63. package/src/agent/runtime.ts +0 -294
  64. package/src/agent/scoped-tool.ts +0 -221
  65. package/src/agent/session.ts +0 -66
  66. package/src/agent/types.ts +0 -311
  67. package/src/ai-sdk-bridge.test.ts +0 -96
  68. package/src/ai-sdk-bridge.ts +0 -209
  69. package/src/attributes.test.ts +0 -148
  70. package/src/attributes.ts +0 -265
  71. package/src/cost.test.ts +0 -92
  72. package/src/cost.ts +0 -196
  73. package/src/events.test.ts +0 -139
  74. package/src/events.ts +0 -290
  75. package/src/guard.test.ts +0 -273
  76. package/src/guard.ts +0 -732
  77. package/src/index.ts +0 -260
  78. package/src/metrics.test.ts +0 -60
  79. package/src/metrics.ts +0 -128
  80. package/src/observer/ai-sdk.test.ts +0 -130
  81. package/src/observer/ai-sdk.ts +0 -200
  82. package/src/observer/index.ts +0 -39
  83. package/src/observer/langchain.test.ts +0 -203
  84. package/src/observer/langchain.ts +0 -289
  85. package/src/observer/observer.test.ts +0 -315
  86. package/src/observer/observer.ts +0 -276
  87. package/src/observer/span-registry.test.ts +0 -81
  88. package/src/observer/span-registry.ts +0 -64
  89. package/src/observer/types.ts +0 -153
  90. package/src/semconv.test.ts +0 -88
  91. package/src/semconv.ts +0 -296
  92. package/src/streaming.test.ts +0 -118
  93. package/src/streaming.ts +0 -238
  94. package/src/trace.test.ts +0 -167
  95. package/src/trace.ts +0 -181
@@ -1,7 +1,11 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- const require_agent = require('../agent-CiG_LZL8.cjs');
2
+ const require_agent_security = require('../agent-security-BhUTos0B.cjs');
3
+ const require_agent = require('../agent-2GmZ6vDV.cjs');
3
4
 
4
5
  exports.AGENT_AUDIT_SCHEMA_VERSION = require_agent.AGENT_AUDIT_SCHEMA_VERSION;
6
+ exports.AGENT_PLAN_RISK_ATTR = require_agent.AGENT_PLAN_RISK_ATTR;
7
+ exports.AGENT_SECURITY_ATTR = require_agent_security.AGENT_SECURITY_ATTR;
8
+ exports.agentContextFromSpan = require_agent_security.agentContextFromSpan;
5
9
  exports.canonicalizeForHash = require_agent.canonicalizeForHash;
6
10
  exports.createAgentAuditMetadata = require_agent.createAgentAuditMetadata;
7
11
  exports.createAgentIdentityRegistry = require_agent.createAgentIdentityRegistry;
@@ -9,14 +13,27 @@ exports.createSignedEventEnvelope = require_agent.createSignedEventEnvelope;
9
13
  exports.defineAgentAction = require_agent.defineAgentAction;
10
14
  exports.defineAgentToolCall = require_agent.defineAgentToolCall;
11
15
  exports.delegateToAgent = require_agent.delegateToAgent;
16
+ exports.deriveActionRiskClass = require_agent_security.deriveActionRiskClass;
12
17
  exports.flattenAgentAttributes = require_agent.flattenAgentAttributes;
13
18
  exports.hashPayload = require_agent.hashPayload;
19
+ exports.heuristicPlanRiskClassifier = require_agent.heuristicPlanRiskClassifier;
20
+ exports.recordActionRiskClass = require_agent_security.recordActionRiskClass;
21
+ exports.recordActiveScopes = require_agent_security.recordActiveScopes;
14
22
  exports.recordAgentHandoff = require_agent.recordAgentHandoff;
23
+ exports.recordControllerId = require_agent_security.recordControllerId;
15
24
  exports.recordDecisionBasis = require_agent.recordDecisionBasis;
25
+ exports.recordHumanApproval = require_agent_security.recordHumanApproval;
26
+ exports.recordInputProvenance = require_agent_security.recordInputProvenance;
27
+ exports.recordMemoryAccess = require_agent_security.recordMemoryAccess;
28
+ exports.recordPlanRiskAssessment = require_agent.recordPlanRiskAssessment;
29
+ exports.recordPlanStep = require_agent_security.recordPlanStep;
16
30
  exports.recordPolicyDecision = require_agent.recordPolicyDecision;
31
+ exports.recordRenderOutput = require_agent_security.recordRenderOutput;
17
32
  exports.resolvePrivacyProfile = require_agent.resolvePrivacyProfile;
33
+ exports.runAgentPlanClassifier = require_agent.runAgentPlanClassifier;
18
34
  exports.sanitizeAuditPayload = require_agent.sanitizeAuditPayload;
19
35
  exports.setAgentAttributes = require_agent.setAgentAttributes;
36
+ exports.tryRecordHumanApproval = require_agent_security.tryRecordHumanApproval;
20
37
  exports.verifyEventEnvelopeHash = require_agent.verifyEventEnvelopeHash;
21
38
  exports.withAgentAction = require_agent.withAgentAction;
22
39
  exports.withAgentSession = require_agent.withAgentSession;
@@ -1,3 +1,4 @@
1
- import { $ as ToolCallMetadata, A as AgentAuditEventEnvelope, B as AgentSessionActionMetadata, C as flattenAgentAttributes, D as AgentActionMetadata, E as AgentActionFactory, F as AgentIdentityRecord, G as AiLifecycleStage, H as AgentSessionStatus, I as AgentIdentityRegistry, J as PolicyDecision, K as DelegationContext, L as AgentIdentityStatus, M as AgentEventKind, N as AgentHandler, O as AgentActionOptions, P as AgentIdentity, Q as ScopedToolDefinition, R as AgentMetadataInput, S as recordAgentHandoff, T as createAgentAuditMetadata, U as AgentToolCallActionMetadata, V as AgentSessionMetadata, W as AgentToolCallOptions, X as PrivacyProfile, Y as PolicyMetadata, Z as PrivacyProfileName, _ as withAgentAction, a as PrivacyProfileInput, at as AGENT_AUDIT_SCHEMA_VERSION, b as RecordAgentHandoffMetadata, c as ProvisionAgentIdentityInput, d as createAgentIdentityRegistry, et as ToolStatus, f as withAgentSession, g as recordPolicyDecision, h as recordDecisionBasis, i as verifyEventEnvelopeHash, it as hashPayload, j as AgentDecisionMetadata, k as AgentAiMetadata, l as RevokeAgentIdentityInput, m as defineAgentToolCall, n as CreateSignedEventEnvelopeOptions, nt as HashPayloadOptions, o as resolvePrivacyProfile, p as defineAgentAction, q as GovernanceMetadata, r as createSignedEventEnvelope, rt as canonicalizeForHash, s as sanitizeAuditPayload, t as withScopedTool, tt as AgentContext, u as RotateAgentIdentityInput, v as withAgentToolCall, w as setAgentAttributes, x as delegateToAgent, y as DelegateToAgentInput, z as AgentOutcome } from "../index-DMz730Z-.cjs";
1
+ import { $ as AgentToolCallOptions, A as delegateToAgent, B as AgentDecisionMetadata, C as defineAgentToolCall, D as withAgentToolCall, E as withAgentAction, F as AgentActionFactory, G as AgentIdentityRegistry, H as AgentHandler, I as AgentActionMetadata, J as AgentOutcome, K as AgentIdentityStatus, L as AgentActionOptions, M as flattenAgentAttributes, N as setAgentAttributes, O as DelegateToAgentInput, P as createAgentAuditMetadata, Q as AgentToolCallActionMetadata, R as AgentAiMetadata, S as defineAgentAction, T as recordPolicyDecision, U as AgentIdentity, V as AgentEventKind, W as AgentIdentityRecord, X as AgentSessionMetadata, Y as AgentSessionActionMetadata, Z as AgentSessionStatus, _ as ProvisionAgentIdentityInput, a as AgentPlanRiskVerdict, at as PrivacyProfile, b as createAgentIdentityRegistry, c as recordPlanRiskAssessment, ct as ToolCallMetadata, d as CreateSignedEventEnvelopeOptions, dt as canonicalizeForHash, et as AiLifecycleStage, f as createSignedEventEnvelope, ft as hashPayload, g as sanitizeAuditPayload, h as resolvePrivacyProfile, i as AgentPlanClassifierResult, it as PolicyMetadata, j as recordAgentHandoff, k as RecordAgentHandoffMetadata, l as runAgentPlanClassifier, lt as ToolStatus, m as PrivacyProfileInput, n as AgentPlanClassifier, nt as GovernanceMetadata, o as RecordPlanRiskAssessmentOptions, ot as PrivacyProfileName, p as verifyEventEnvelopeHash, pt as AGENT_AUDIT_SCHEMA_VERSION, q as AgentMetadataInput, r as AgentPlanClassifierInput, rt as PolicyDecision, s as heuristicPlanRiskClassifier, st as ScopedToolDefinition, t as AGENT_PLAN_RISK_ATTR, tt as DelegationContext, u as withScopedTool, ut as HashPayloadOptions, v as RevokeAgentIdentityInput, w as recordDecisionBasis, x as withAgentSession, y as RotateAgentIdentityInput, z as AgentAuditEventEnvelope } from "../index-DyghHy5i.cjs";
2
2
  import { a as TokenUsage, i as ModelPricing } from "../cost-DXTkBUUW.cjs";
3
- export { AGENT_AUDIT_SCHEMA_VERSION, type AgentActionFactory, type AgentActionMetadata, type AgentActionOptions, type AgentAiMetadata, type AgentAuditEventEnvelope, type AgentContext, type AgentDecisionMetadata, type AgentEventKind, type AgentHandler, type AgentIdentity, type AgentIdentityRecord, type AgentIdentityRegistry, type AgentIdentityStatus, type AgentMetadataInput, type AgentOutcome, type AgentSessionActionMetadata, type AgentSessionMetadata, type AgentSessionStatus, type AgentToolCallActionMetadata, type AgentToolCallOptions, type AiLifecycleStage, type CreateSignedEventEnvelopeOptions, type DelegateToAgentInput, type DelegationContext, type GovernanceMetadata, type HashPayloadOptions, type ModelPricing, type PolicyDecision, type PolicyMetadata, type PrivacyProfile, type PrivacyProfileInput, type PrivacyProfileName, type ProvisionAgentIdentityInput, type RecordAgentHandoffMetadata, type RevokeAgentIdentityInput, type RotateAgentIdentityInput, type ScopedToolDefinition, type TokenUsage, type ToolCallMetadata, type ToolStatus, canonicalizeForHash, createAgentAuditMetadata, createAgentIdentityRegistry, createSignedEventEnvelope, defineAgentAction, defineAgentToolCall, delegateToAgent, flattenAgentAttributes, hashPayload, recordAgentHandoff, recordDecisionBasis, recordPolicyDecision, resolvePrivacyProfile, sanitizeAuditPayload, setAgentAttributes, verifyEventEnvelopeHash, withAgentAction, withAgentSession, withAgentToolCall, withScopedTool };
3
+ import { C as recordPlanStep, D as agentContextFromSpan, E as AgentContext, S as recordMemoryAccess, T as tryRecordHumanApproval, _ as recordActionRiskClass, a as AgentInputProvenance, b as recordHumanApproval, c as AgentSecurityRecordOptions, d as RecordHumanApprovalInput, f as RecordInputProvenanceInput, g as deriveActionRiskClass, h as RecordRenderOutputInput, i as AgentConsentOutcome, l as RecordActiveScopesInput, m as RecordPlanStepInput, n as ActionRiskHints, o as AgentMemoryOperation, p as RecordMemoryAccessInput, r as AgentActionRiskClass, s as AgentOutputFormat, t as AGENT_SECURITY_ATTR, u as RecordControllerInput, v as recordActiveScopes, w as recordRenderOutput, x as recordInputProvenance, y as recordControllerId } from "../agent-security-N6nE3V3A.cjs";
4
+ export { AGENT_AUDIT_SCHEMA_VERSION, AGENT_PLAN_RISK_ATTR, AGENT_SECURITY_ATTR, type ActionRiskHints, type AgentActionFactory, type AgentActionMetadata, type AgentActionOptions, type AgentActionRiskClass, type AgentAiMetadata, type AgentAuditEventEnvelope, 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 DelegateToAgentInput, type DelegationContext, type GovernanceMetadata, type HashPayloadOptions, type ModelPricing, type PolicyDecision, type PolicyMetadata, type PrivacyProfile, type PrivacyProfileInput, type PrivacyProfileName, type ProvisionAgentIdentityInput, type RecordActiveScopesInput, type RecordAgentHandoffMetadata, type RecordControllerInput, type RecordHumanApprovalInput, type RecordInputProvenanceInput, type RecordMemoryAccessInput, type RecordPlanRiskAssessmentOptions, type RecordPlanStepInput, type RecordRenderOutputInput, type RevokeAgentIdentityInput, type RotateAgentIdentityInput, type ScopedToolDefinition, type TokenUsage, type ToolCallMetadata, type ToolStatus, agentContextFromSpan, canonicalizeForHash, createAgentAuditMetadata, createAgentIdentityRegistry, createSignedEventEnvelope, defineAgentAction, defineAgentToolCall, delegateToAgent, deriveActionRiskClass, flattenAgentAttributes, hashPayload, heuristicPlanRiskClassifier, recordActionRiskClass, recordActiveScopes, recordAgentHandoff, recordControllerId, recordDecisionBasis, recordHumanApproval, recordInputProvenance, recordMemoryAccess, recordPlanRiskAssessment, recordPlanStep, recordPolicyDecision, recordRenderOutput, resolvePrivacyProfile, runAgentPlanClassifier, sanitizeAuditPayload, setAgentAttributes, tryRecordHumanApproval, verifyEventEnvelopeHash, withAgentAction, withAgentSession, withAgentToolCall, withScopedTool };
@@ -1,3 +1,4 @@
1
- import { $ as ToolCallMetadata, A as AgentAuditEventEnvelope, B as AgentSessionActionMetadata, C as flattenAgentAttributes, D as AgentActionMetadata, E as AgentActionFactory, F as AgentIdentityRecord, G as AiLifecycleStage, H as AgentSessionStatus, I as AgentIdentityRegistry, J as PolicyDecision, K as DelegationContext, L as AgentIdentityStatus, M as AgentEventKind, N as AgentHandler, O as AgentActionOptions, P as AgentIdentity, Q as ScopedToolDefinition, R as AgentMetadataInput, S as recordAgentHandoff, T as createAgentAuditMetadata, U as AgentToolCallActionMetadata, V as AgentSessionMetadata, W as AgentToolCallOptions, X as PrivacyProfile, Y as PolicyMetadata, Z as PrivacyProfileName, _ as withAgentAction, a as PrivacyProfileInput, at as AGENT_AUDIT_SCHEMA_VERSION, b as RecordAgentHandoffMetadata, c as ProvisionAgentIdentityInput, d as createAgentIdentityRegistry, et as ToolStatus, f as withAgentSession, g as recordPolicyDecision, h as recordDecisionBasis, i as verifyEventEnvelopeHash, it as hashPayload, j as AgentDecisionMetadata, k as AgentAiMetadata, l as RevokeAgentIdentityInput, m as defineAgentToolCall, n as CreateSignedEventEnvelopeOptions, nt as HashPayloadOptions, o as resolvePrivacyProfile, p as defineAgentAction, q as GovernanceMetadata, r as createSignedEventEnvelope, rt as canonicalizeForHash, s as sanitizeAuditPayload, t as withScopedTool, tt as AgentContext, u as RotateAgentIdentityInput, v as withAgentToolCall, w as setAgentAttributes, x as delegateToAgent, y as DelegateToAgentInput, z as AgentOutcome } from "../index-CedOJ0OP.js";
1
+ import { $ as AgentToolCallOptions, A as delegateToAgent, B as AgentDecisionMetadata, C as defineAgentToolCall, D as withAgentToolCall, E as withAgentAction, F as AgentActionFactory, G as AgentIdentityRegistry, H as AgentHandler, I as AgentActionMetadata, J as AgentOutcome, K as AgentIdentityStatus, L as AgentActionOptions, M as flattenAgentAttributes, N as setAgentAttributes, O as DelegateToAgentInput, P as createAgentAuditMetadata, Q as AgentToolCallActionMetadata, R as AgentAiMetadata, S as defineAgentAction, T as recordPolicyDecision, U as AgentIdentity, V as AgentEventKind, W as AgentIdentityRecord, X as AgentSessionMetadata, Y as AgentSessionActionMetadata, Z as AgentSessionStatus, _ as ProvisionAgentIdentityInput, a as AgentPlanRiskVerdict, at as PrivacyProfile, b as createAgentIdentityRegistry, c as recordPlanRiskAssessment, ct as ToolCallMetadata, d as CreateSignedEventEnvelopeOptions, dt as canonicalizeForHash, et as AiLifecycleStage, f as createSignedEventEnvelope, ft as hashPayload, g as sanitizeAuditPayload, h as resolvePrivacyProfile, i as AgentPlanClassifierResult, it as PolicyMetadata, j as recordAgentHandoff, k as RecordAgentHandoffMetadata, l as runAgentPlanClassifier, lt as ToolStatus, m as PrivacyProfileInput, n as AgentPlanClassifier, nt as GovernanceMetadata, o as RecordPlanRiskAssessmentOptions, ot as PrivacyProfileName, p as verifyEventEnvelopeHash, pt as AGENT_AUDIT_SCHEMA_VERSION, q as AgentMetadataInput, r as AgentPlanClassifierInput, rt as PolicyDecision, s as heuristicPlanRiskClassifier, st as ScopedToolDefinition, t as AGENT_PLAN_RISK_ATTR, tt as DelegationContext, u as withScopedTool, ut as HashPayloadOptions, v as RevokeAgentIdentityInput, w as recordDecisionBasis, x as withAgentSession, y as RotateAgentIdentityInput, z as AgentAuditEventEnvelope } from "../index-Dxt0bm0M.js";
2
2
  import { a as TokenUsage, i as ModelPricing } from "../cost-DXTkBUUW.js";
3
- export { AGENT_AUDIT_SCHEMA_VERSION, type AgentActionFactory, type AgentActionMetadata, type AgentActionOptions, type AgentAiMetadata, type AgentAuditEventEnvelope, type AgentContext, type AgentDecisionMetadata, type AgentEventKind, type AgentHandler, type AgentIdentity, type AgentIdentityRecord, type AgentIdentityRegistry, type AgentIdentityStatus, type AgentMetadataInput, type AgentOutcome, type AgentSessionActionMetadata, type AgentSessionMetadata, type AgentSessionStatus, type AgentToolCallActionMetadata, type AgentToolCallOptions, type AiLifecycleStage, type CreateSignedEventEnvelopeOptions, type DelegateToAgentInput, type DelegationContext, type GovernanceMetadata, type HashPayloadOptions, type ModelPricing, type PolicyDecision, type PolicyMetadata, type PrivacyProfile, type PrivacyProfileInput, type PrivacyProfileName, type ProvisionAgentIdentityInput, type RecordAgentHandoffMetadata, type RevokeAgentIdentityInput, type RotateAgentIdentityInput, type ScopedToolDefinition, type TokenUsage, type ToolCallMetadata, type ToolStatus, canonicalizeForHash, createAgentAuditMetadata, createAgentIdentityRegistry, createSignedEventEnvelope, defineAgentAction, defineAgentToolCall, delegateToAgent, flattenAgentAttributes, hashPayload, recordAgentHandoff, recordDecisionBasis, recordPolicyDecision, resolvePrivacyProfile, sanitizeAuditPayload, setAgentAttributes, verifyEventEnvelopeHash, withAgentAction, withAgentSession, withAgentToolCall, withScopedTool };
3
+ import { C as recordPlanStep, D as agentContextFromSpan, E as AgentContext, S as recordMemoryAccess, T as tryRecordHumanApproval, _ as recordActionRiskClass, a as AgentInputProvenance, b as recordHumanApproval, c as AgentSecurityRecordOptions, d as RecordHumanApprovalInput, f as RecordInputProvenanceInput, g as deriveActionRiskClass, h as RecordRenderOutputInput, i as AgentConsentOutcome, l as RecordActiveScopesInput, m as RecordPlanStepInput, n as ActionRiskHints, o as AgentMemoryOperation, p as RecordMemoryAccessInput, r as AgentActionRiskClass, s as AgentOutputFormat, t as AGENT_SECURITY_ATTR, u as RecordControllerInput, v as recordActiveScopes, w as recordRenderOutput, x as recordInputProvenance, y as recordControllerId } from "../agent-security-N6nE3V3A.js";
4
+ export { AGENT_AUDIT_SCHEMA_VERSION, AGENT_PLAN_RISK_ATTR, AGENT_SECURITY_ATTR, type ActionRiskHints, type AgentActionFactory, type AgentActionMetadata, type AgentActionOptions, type AgentActionRiskClass, type AgentAiMetadata, type AgentAuditEventEnvelope, 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 DelegateToAgentInput, type DelegationContext, type GovernanceMetadata, type HashPayloadOptions, type ModelPricing, type PolicyDecision, type PolicyMetadata, type PrivacyProfile, type PrivacyProfileInput, type PrivacyProfileName, type ProvisionAgentIdentityInput, type RecordActiveScopesInput, type RecordAgentHandoffMetadata, type RecordControllerInput, type RecordHumanApprovalInput, type RecordInputProvenanceInput, type RecordMemoryAccessInput, type RecordPlanRiskAssessmentOptions, type RecordPlanStepInput, type RecordRenderOutputInput, type RevokeAgentIdentityInput, type RotateAgentIdentityInput, type ScopedToolDefinition, type TokenUsage, type ToolCallMetadata, type ToolStatus, agentContextFromSpan, canonicalizeForHash, createAgentAuditMetadata, createAgentIdentityRegistry, createSignedEventEnvelope, defineAgentAction, defineAgentToolCall, delegateToAgent, deriveActionRiskClass, flattenAgentAttributes, hashPayload, heuristicPlanRiskClassifier, recordActionRiskClass, recordActiveScopes, recordAgentHandoff, recordControllerId, recordDecisionBasis, recordHumanApproval, recordInputProvenance, recordMemoryAccess, recordPlanRiskAssessment, recordPlanStep, recordPolicyDecision, recordRenderOutput, resolvePrivacyProfile, runAgentPlanClassifier, sanitizeAuditPayload, setAgentAttributes, tryRecordHumanApproval, verifyEventEnvelopeHash, withAgentAction, withAgentSession, withAgentToolCall, withScopedTool };
@@ -1,3 +1,4 @@
1
- import { _ as setAgentAttributes, a as sanitizeAuditPayload, b as hashPayload, c as delegateToAgent, d as defineAgentToolCall, f as recordDecisionBasis, g as flattenAgentAttributes, h as withAgentToolCall, i as resolvePrivacyProfile, l as recordAgentHandoff, m as withAgentAction, n as createSignedEventEnvelope, o as createAgentIdentityRegistry, p as recordPolicyDecision, r as verifyEventEnvelopeHash, s as withAgentSession, t as withScopedTool, u as defineAgentAction, v as createAgentAuditMetadata, x as AGENT_AUDIT_SCHEMA_VERSION, y as canonicalizeForHash } from "../agent-DZL-uNAc.js";
1
+ import { a as recordControllerId, c as recordMemoryAccess, d as tryRecordHumanApproval, i as recordActiveScopes, l as recordPlanStep, n as deriveActionRiskClass, o as recordHumanApproval, p as agentContextFromSpan, r as recordActionRiskClass, s as recordInputProvenance, t as AGENT_SECURITY_ATTR, u as recordRenderOutput } from "../agent-security-ChL0rIh-.js";
2
+ import { C as canonicalizeForHash, S as createAgentAuditMetadata, T as AGENT_AUDIT_SCHEMA_VERSION, _ as recordPolicyDecision, a as withScopedTool, b as flattenAgentAttributes, c as resolvePrivacyProfile, d as withAgentSession, f as delegateToAgent, g as recordDecisionBasis, h as defineAgentToolCall, i as runAgentPlanClassifier, l as sanitizeAuditPayload, m as defineAgentAction, n as heuristicPlanRiskClassifier, o as createSignedEventEnvelope, p as recordAgentHandoff, r as recordPlanRiskAssessment, s as verifyEventEnvelopeHash, t as AGENT_PLAN_RISK_ATTR, u as createAgentIdentityRegistry, v as withAgentAction, w as hashPayload, x as setAgentAttributes, y as withAgentToolCall } from "../agent-yHB-GF6g.js";
2
3
 
3
- export { AGENT_AUDIT_SCHEMA_VERSION, canonicalizeForHash, createAgentAuditMetadata, createAgentIdentityRegistry, createSignedEventEnvelope, defineAgentAction, defineAgentToolCall, delegateToAgent, flattenAgentAttributes, hashPayload, recordAgentHandoff, recordDecisionBasis, recordPolicyDecision, resolvePrivacyProfile, sanitizeAuditPayload, setAgentAttributes, verifyEventEnvelopeHash, withAgentAction, withAgentSession, withAgentToolCall, withScopedTool };
4
+ export { AGENT_AUDIT_SCHEMA_VERSION, AGENT_PLAN_RISK_ATTR, AGENT_SECURITY_ATTR, agentContextFromSpan, canonicalizeForHash, createAgentAuditMetadata, createAgentIdentityRegistry, createSignedEventEnvelope, defineAgentAction, defineAgentToolCall, delegateToAgent, deriveActionRiskClass, flattenAgentAttributes, hashPayload, heuristicPlanRiskClassifier, recordActionRiskClass, recordActiveScopes, recordAgentHandoff, recordControllerId, recordDecisionBasis, recordHumanApproval, recordInputProvenance, recordMemoryAccess, recordPlanRiskAssessment, recordPlanStep, recordPolicyDecision, recordRenderOutput, resolvePrivacyProfile, runAgentPlanClassifier, sanitizeAuditPayload, setAgentAttributes, tryRecordHumanApproval, verifyEventEnvelopeHash, withAgentAction, withAgentSession, withAgentToolCall, withScopedTool };
@@ -1,8 +1,9 @@
1
1
  const require_cost = require('./cost.cjs');
2
2
  const require_attributes = require('./attributes-dxuRzqXC.cjs');
3
+ const require_agent_security = require('./agent-security-BhUTos0B.cjs');
3
4
  let autotel = require("autotel");
4
- let node_crypto = require("node:crypto");
5
5
  let autotel_audit = require("autotel-audit");
6
+ let node_crypto = require("node:crypto");
6
7
 
7
8
  //#region src/agent/constants.ts
8
9
  const AGENT_AUDIT_SCHEMA_VERSION = "1.1.0";
@@ -159,68 +160,10 @@ function buildLifecycleUpdateContext(metadata) {
159
160
  };
160
161
  }
161
162
 
162
- //#endregion
163
- //#region src/agent/context.ts
164
- const MISSING_CONTEXT_MESSAGE = "[autotel-genai] No active trace context. Wrap the call in trace()/instrument(), pass options.ctx, or set options.onMissingContext to \"warn\"/\"skip\" to degrade gracefully instead of throwing.";
165
- /**
166
- * Resolve an agent context without throwing. Returns `null` when no trace context
167
- * is available, so callers can degrade gracefully (best-effort instrumentation).
168
- */
169
- const INVALID_TRACE_ID = "00000000000000000000000000000000";
170
- function resolveContextSafe(ctx) {
171
- if (ctx) return ctx;
172
- const span = autotel.otelTrace.getActiveSpan();
173
- if (!span) return null;
174
- const ids = (0, autotel.getTraceContext)();
175
- const sc = span.spanContext();
176
- const traceId = ids?.traceId ?? sc.traceId;
177
- if (!traceId || traceId === INVALID_TRACE_ID) return null;
178
- return {
179
- traceId,
180
- spanId: ids?.spanId ?? sc.spanId,
181
- correlationId: ids?.correlationId ?? traceId.slice(0, 16),
182
- setAttribute: (key, value) => span.setAttribute(key, value),
183
- setAttributes: (attrs) => span.setAttributes(attrs)
184
- };
185
- }
186
- function resolveContext(ctx) {
187
- const resolved = resolveContextSafe(ctx);
188
- if (resolved) return resolved;
189
- throw new Error(MISSING_CONTEXT_MESSAGE);
190
- }
191
- const warnedMissingContext = /* @__PURE__ */ new Set();
192
- /** Warn (once per action) that an agent action is running without a trace context. */
193
- function warnMissingContextOnce(action) {
194
- if (warnedMissingContext.has(action)) return;
195
- warnedMissingContext.add(action);
196
- console.warn(`[autotel-genai] No active trace context for "${action}" — running un-audited. Wrap the call in trace()/instrument() or pass options.ctx to capture agent audit telemetry. (set options.onMissingContext: "throw" to fail fast, or "skip" to silence this warning)`);
197
- }
198
- function toAttributeValue(value) {
199
- if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") return value;
200
- if (Array.isArray(value)) {
201
- if (value.every((entry) => typeof entry === "string")) return value;
202
- if (value.every((entry) => typeof entry === "number")) return value;
203
- if (value.every((entry) => typeof entry === "boolean")) return value;
204
- try {
205
- return JSON.stringify(value);
206
- } catch {
207
- return "<serialization-failed>";
208
- }
209
- }
210
- if (value instanceof Date) return value.toISOString();
211
- if (typeof value === "bigint") return value.toString(10);
212
- if (value === null || value === void 0) return;
213
- try {
214
- return JSON.stringify(value);
215
- } catch {
216
- return "<serialization-failed>";
217
- }
218
- }
219
-
220
163
  //#endregion
221
164
  //#region src/agent/attributes.ts
222
165
  function setIfPresent(target, key, value) {
223
- const attr = toAttributeValue(value);
166
+ const attr = require_agent_security.toAttributeValue(value);
224
167
  if (attr !== void 0) target[key] = attr;
225
168
  }
226
169
  function appendIdentityAttributes(attrs, agent) {
@@ -307,7 +250,7 @@ function flattenAgentAttributes(metadata) {
307
250
  return attrs;
308
251
  }
309
252
  function setAgentAttributes(metadata, ctx) {
310
- resolveContext(ctx).setAttributes(flattenAgentAttributes(metadata));
253
+ require_agent_security.resolveContext(ctx).setAttributes(flattenAgentAttributes(metadata));
311
254
  }
312
255
  /**
313
256
  * Stamp only the terminal outcome on the active span. Used by lifecycle
@@ -315,7 +258,7 @@ function setAgentAttributes(metadata, ctx) {
315
258
  * nested step already wrote — e.g. a tool call's `tool.status=complete`.
316
259
  */
317
260
  function setAgentOutcome(outcome, ctx) {
318
- resolveContext(ctx).setAttribute("agent.outcome", outcome);
261
+ require_agent_security.resolveContext(ctx).setAttribute("agent.outcome", outcome);
319
262
  }
320
263
 
321
264
  //#endregion
@@ -374,11 +317,11 @@ async function withAgentAction(metadata, fn, options = {}) {
374
317
  }
375
318
  function recordPolicyDecision(metadata, options = {}) {
376
319
  const normalized = normalizeMetadata(metadata);
377
- const traceCtx = resolveContextSafe(options.ctx);
320
+ const traceCtx = require_agent_security.resolveContextSafe(options.ctx);
378
321
  if (!traceCtx) {
379
322
  const mode = options.onMissingContext ?? "warn";
380
- if (mode === "throw") throw new Error(MISSING_CONTEXT_MESSAGE);
381
- if (mode === "warn") warnMissingContextOnce(normalized.action);
323
+ if (mode === "throw") throw new Error(require_agent_security.MISSING_CONTEXT_MESSAGE);
324
+ if (mode === "warn") require_agent_security.warnMissingContextOnce(normalized.action);
382
325
  return;
383
326
  }
384
327
  const logger = options.logger ?? (0, autotel.getRequestLoggerSafe)() ?? (0, autotel.createNoopRequestLogger)();
@@ -906,6 +849,19 @@ async function withScopedTool(definition, input, fn, options = {}) {
906
849
  governance,
907
850
  decision: buildDecision(input, definition.decision, definition.privacyProfile)
908
851
  }, options);
852
+ (0, autotel_audit.securityEvent)({
853
+ name: "llm.tool_call.denied",
854
+ category: "llm",
855
+ outcome: "denied",
856
+ severity: "warning",
857
+ reason: denial.reason,
858
+ targetType: "tool",
859
+ targetId: definition.tool.name,
860
+ policyId: definition.policyId
861
+ }, {
862
+ ctx: options.ctx,
863
+ onMissingContext: options.onMissingContext ?? "warn"
864
+ });
909
865
  throw (0, autotel.createStructuredError)({
910
866
  status: 403,
911
867
  code: "AGENT_SCOPE_DENIED",
@@ -946,6 +902,99 @@ async function withScopedTool(definition, input, fn, options = {}) {
946
902
  }, fn, options);
947
903
  }
948
904
 
905
+ //#endregion
906
+ //#region src/agent/agent-plan-classifier.ts
907
+ /** Canonical plan-risk attribute keys (Google SAIF plan-risk predictor aligned). */
908
+ const AGENT_PLAN_RISK_ATTR = {
909
+ verdict: "agent.plan.risk.verdict",
910
+ score: "agent.plan.risk.score",
911
+ categories: "agent.plan.risk.categories",
912
+ toolSequence: "agent.plan.risk.tool_sequence"
913
+ };
914
+ function setPlanRiskAttrs(ctx, attrs) {
915
+ const traceCtx = require_agent_security.resolveContext(ctx);
916
+ const mapped = {};
917
+ for (const [key, value] of Object.entries(attrs)) {
918
+ const attr = require_agent_security.toAttributeValue(value);
919
+ if (attr !== void 0) mapped[key] = attr;
920
+ }
921
+ if (Object.keys(mapped).length > 0) traceCtx.setAttributes(mapped);
922
+ }
923
+ /**
924
+ * Stamp plan-risk assessment attrs on the active span.
925
+ */
926
+ function recordPlanRiskAssessment(options) {
927
+ const { assessment, toolSequence } = options;
928
+ setPlanRiskAttrs(options.ctx, {
929
+ [AGENT_PLAN_RISK_ATTR.verdict]: assessment.verdict,
930
+ ...assessment.score !== void 0 && { [AGENT_PLAN_RISK_ATTR.score]: assessment.score },
931
+ ...assessment.categories?.length && { [AGENT_PLAN_RISK_ATTR.categories]: assessment.categories },
932
+ ...toolSequence?.length && { [AGENT_PLAN_RISK_ATTR.toolSequence]: toolSequence },
933
+ ...assessment.reason !== void 0 && { "decision.summary": assessment.reason }
934
+ });
935
+ if (options.emitSecurityEvent && assessment.verdict !== "low") (0, autotel_audit.securityEvent)({
936
+ name: "llm.plan.risk.elevated",
937
+ category: "llm",
938
+ outcome: assessment.verdict === "critical" ? "blocked" : "denied",
939
+ severity: assessment.verdict === "critical" ? "critical" : assessment.verdict === "high" ? "error" : "warning",
940
+ reason: assessment.reason ?? assessment.verdict,
941
+ ...assessment.score !== void 0 && { score: assessment.score },
942
+ ...assessment.categories?.length && { categories: assessment.categories.join(",") }
943
+ }, { ctx: options.ctx });
944
+ }
945
+ /**
946
+ * Run a pluggable plan-risk classifier and record its verdict on the span.
947
+ * Classifier failures degrade quietly (no assessment recorded).
948
+ */
949
+ async function runAgentPlanClassifier(classifier, input, options = {}) {
950
+ let assessment;
951
+ try {
952
+ assessment = await classifier(input);
953
+ } catch {
954
+ return;
955
+ }
956
+ if (!assessment) return void 0;
957
+ recordPlanRiskAssessment({
958
+ ...options,
959
+ assessment,
960
+ toolSequence: input.toolSequence
961
+ });
962
+ return assessment;
963
+ }
964
+ const DESTRUCTIVE_TOOL = /\b(delete|remove|send|post|transfer|pay|upload|execute)\b/i;
965
+ const UNTRUSTED_READ = /\b(read|fetch|get|search|load|parse|inbox|email|web|scrape)\b/i;
966
+ /**
967
+ * Dependency-free first-pass plan-risk heuristic. Opt-in — pass as
968
+ * `AgentPlanClassifier` or wrap your own Model Armor / Llama Guard adapter.
969
+ */
970
+ function heuristicPlanRiskClassifier() {
971
+ return ({ toolSequence }) => {
972
+ if (toolSequence.length === 0) return {
973
+ verdict: "low",
974
+ score: 0
975
+ };
976
+ const normalized = toolSequence.map((name) => name.replaceAll("_", " "));
977
+ const hasDestructive = normalized.some((name) => DESTRUCTIVE_TOOL.test(name));
978
+ const hasUntrustedRead = normalized.some((name) => UNTRUSTED_READ.test(name));
979
+ if (hasDestructive && hasUntrustedRead) return {
980
+ verdict: "high",
981
+ score: .85,
982
+ categories: ["untrusted_to_destructive_chain"],
983
+ reason: "mixed_untrusted_and_destructive_tools"
984
+ };
985
+ if (toolSequence.length >= 8) return {
986
+ verdict: "medium",
987
+ score: .55,
988
+ categories: ["long_tool_chain"],
989
+ reason: "long_tool_sequence"
990
+ };
991
+ return {
992
+ verdict: "low",
993
+ score: .1
994
+ };
995
+ };
996
+ }
997
+
949
998
  //#endregion
950
999
  Object.defineProperty(exports, 'AGENT_AUDIT_SCHEMA_VERSION', {
951
1000
  enumerable: true,
@@ -953,6 +1002,12 @@ Object.defineProperty(exports, 'AGENT_AUDIT_SCHEMA_VERSION', {
953
1002
  return AGENT_AUDIT_SCHEMA_VERSION;
954
1003
  }
955
1004
  });
1005
+ Object.defineProperty(exports, 'AGENT_PLAN_RISK_ATTR', {
1006
+ enumerable: true,
1007
+ get: function () {
1008
+ return AGENT_PLAN_RISK_ATTR;
1009
+ }
1010
+ });
956
1011
  Object.defineProperty(exports, 'canonicalizeForHash', {
957
1012
  enumerable: true,
958
1013
  get: function () {
@@ -1007,6 +1062,12 @@ Object.defineProperty(exports, 'hashPayload', {
1007
1062
  return hashPayload;
1008
1063
  }
1009
1064
  });
1065
+ Object.defineProperty(exports, 'heuristicPlanRiskClassifier', {
1066
+ enumerable: true,
1067
+ get: function () {
1068
+ return heuristicPlanRiskClassifier;
1069
+ }
1070
+ });
1010
1071
  Object.defineProperty(exports, 'recordAgentHandoff', {
1011
1072
  enumerable: true,
1012
1073
  get: function () {
@@ -1019,6 +1080,12 @@ Object.defineProperty(exports, 'recordDecisionBasis', {
1019
1080
  return recordDecisionBasis;
1020
1081
  }
1021
1082
  });
1083
+ Object.defineProperty(exports, 'recordPlanRiskAssessment', {
1084
+ enumerable: true,
1085
+ get: function () {
1086
+ return recordPlanRiskAssessment;
1087
+ }
1088
+ });
1022
1089
  Object.defineProperty(exports, 'recordPolicyDecision', {
1023
1090
  enumerable: true,
1024
1091
  get: function () {
@@ -1031,6 +1098,12 @@ Object.defineProperty(exports, 'resolvePrivacyProfile', {
1031
1098
  return resolvePrivacyProfile;
1032
1099
  }
1033
1100
  });
1101
+ Object.defineProperty(exports, 'runAgentPlanClassifier', {
1102
+ enumerable: true,
1103
+ get: function () {
1104
+ return runAgentPlanClassifier;
1105
+ }
1106
+ });
1034
1107
  Object.defineProperty(exports, 'sanitizeAuditPayload', {
1035
1108
  enumerable: true,
1036
1109
  get: function () {
@@ -1073,4 +1146,4 @@ Object.defineProperty(exports, 'withScopedTool', {
1073
1146
  return withScopedTool;
1074
1147
  }
1075
1148
  });
1076
- //# sourceMappingURL=agent-CiG_LZL8.cjs.map
1149
+ //# sourceMappingURL=agent-2GmZ6vDV.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agent-2GmZ6vDV.cjs","names":["toAttributeValue","resolveContext","genAiRequestAttributes","genAiResponseAttributes","estimateLLMCost","genAiUsageAttributes","resolveContextSafe","MISSING_CONTEXT_MESSAGE","toIsoString","toIsoString","normalizeScopes","resolveContext","toAttributeValue"],"sources":["../src/agent/constants.ts","../src/agent/hash.ts","../src/agent/metadata.ts","../src/agent/attributes.ts","../src/agent/runtime.ts","../src/agent/delegation.ts","../src/agent/session.ts","../src/agent/identity-registry.ts","../src/agent/privacy.ts","../src/agent/non-repudiation.ts","../src/agent/scoped-tool.ts","../src/agent/agent-plan-classifier.ts"],"sourcesContent":["export const AGENT_AUDIT_SCHEMA_VERSION = '1.1.0';\n","import { createHash } from 'node:crypto';\n\nexport interface HashPayloadOptions {\n algorithm?: 'sha256';\n}\n\nfunction canonicalize(value: unknown): unknown {\n if (value instanceof Date) {\n return value.toISOString();\n }\n\n if (typeof value === 'bigint') {\n return value.toString(10);\n }\n\n if (Array.isArray(value)) {\n return value.map((entry) => canonicalize(entry));\n }\n\n if (value && typeof value === 'object') {\n // `toSorted()` would need ES2023 lib types; keep runtime output ES2022-friendly.\n const entries = Object.entries(value as Record<string, unknown>);\n entries.sort(([left], [right]) => left.localeCompare(right));\n return Object.fromEntries(\n entries.map(([key, entryValue]) => [key, canonicalize(entryValue)]),\n );\n }\n\n return value;\n}\n\nexport function canonicalizeForHash(value: unknown): string {\n return JSON.stringify(canonicalize(value));\n}\n\nexport function hashPayload(\n value: unknown,\n options: HashPayloadOptions = {},\n): string {\n const algorithm = options.algorithm ?? 'sha256';\n const canonical = canonicalizeForHash(value);\n const digest = createHash(algorithm).update(canonical).digest('hex');\n return `${algorithm}:${digest}`;\n}\n","import { AGENT_AUDIT_SCHEMA_VERSION } from './constants.js';\nimport { hashPayload } from './hash.js';\nimport type {\n AgentActionMetadata,\n AgentDecisionMetadata,\n AgentEventKind,\n GovernanceMetadata,\n ToolCallMetadata,\n} from './types.js';\n\ninterface AuditMetadataLike {\n action: string;\n resource?: string;\n actorId?: string;\n category?: string;\n outcome?: string;\n [key: string]: unknown;\n}\n\nexport function defaultEventKind(\n metadata: AgentActionMetadata,\n): AgentEventKind {\n if (metadata.eventKind) return metadata.eventKind;\n if (metadata.tool) return 'tool_call';\n if (metadata.policy) return 'policy_decision';\n return 'action';\n}\n\nexport function normalizeTool(\n tool?: ToolCallMetadata,\n): ToolCallMetadata | undefined {\n if (!tool) return undefined;\n\n return {\n name: tool.name,\n ...(tool.callId !== undefined && { callId: tool.callId }),\n inputHash:\n tool.input === undefined\n ? tool.inputHash\n : (tool.inputHash ?? hashPayload(tool.input)),\n outputHash:\n tool.output === undefined\n ? tool.outputHash\n : (tool.outputHash ?? hashPayload(tool.output)),\n ...(tool.status !== undefined && { status: tool.status }),\n ...(tool.executionMs !== undefined && { executionMs: tool.executionMs }),\n };\n}\n\nexport function sanitizeTool(\n tool?: ToolCallMetadata,\n): ToolCallMetadata | undefined {\n if (!tool) return undefined;\n\n return {\n name: tool.name,\n ...(tool.callId !== undefined && { callId: tool.callId }),\n ...(tool.inputHash !== undefined && { inputHash: tool.inputHash }),\n ...(tool.outputHash !== undefined && { outputHash: tool.outputHash }),\n ...(tool.status !== undefined && { status: tool.status }),\n ...(tool.executionMs !== undefined && { executionMs: tool.executionMs }),\n };\n}\n\nexport function sanitizeGovernance(\n governance?: GovernanceMetadata,\n): GovernanceMetadata | undefined {\n if (!governance) return undefined;\n return {\n ...(governance.reviewRequired !== undefined && {\n reviewRequired: governance.reviewRequired,\n }),\n ...(governance.reviewerId !== undefined && {\n reviewerId: governance.reviewerId,\n }),\n ...(governance.controlId !== undefined && {\n controlId: governance.controlId,\n }),\n ...(governance.documentationUrl !== undefined && {\n documentationUrl: governance.documentationUrl,\n }),\n ...(governance.lifecycleStage !== undefined && {\n lifecycleStage: governance.lifecycleStage,\n }),\n ...(governance.framework !== undefined && {\n framework: governance.framework,\n }),\n };\n}\n\nfunction normalizeDecision(\n decision?: AgentDecisionMetadata,\n reasoningSummary?: string,\n): AgentDecisionMetadata | undefined {\n if (decision) {\n return {\n ...decision,\n summary: decision.summary ?? reasoningSummary ?? '',\n };\n }\n\n if (reasoningSummary === undefined) return undefined;\n\n return {\n summary: reasoningSummary,\n };\n}\n\nexport function createAgentAuditMetadata(\n metadata: AgentActionMetadata,\n): AgentActionMetadata {\n const eventKind = defaultEventKind(metadata);\n\n if (eventKind === 'tool_call' && !metadata.tool) {\n throw new Error(\n '[autotel-genai] eventKind \"tool_call\" requires metadata.tool.',\n );\n }\n\n if (eventKind === 'policy_decision' && !metadata.policy) {\n throw new Error(\n '[autotel-genai] eventKind \"policy_decision\" requires metadata.policy.',\n );\n }\n\n if (eventKind === 'handoff' && !metadata.delegation) {\n throw new Error(\n '[autotel-genai] eventKind \"handoff\" requires metadata.delegation.',\n );\n }\n\n const delegation =\n metadata.delegation &&\n (\n metadata.delegation.authorityLineageHash === undefined ||\n metadata.delegation.depth === undefined\n )\n ? {\n ...metadata.delegation,\n ...(metadata.delegation.authorityLineage && {\n authorityLineageHash:\n metadata.delegation.authorityLineageHash ??\n hashPayload(metadata.delegation.authorityLineage),\n depth:\n metadata.delegation.depth ??\n Math.max(metadata.delegation.authorityLineage.length - 1, 0),\n }),\n }\n : metadata.delegation;\n\n return {\n ...metadata,\n schemaVersion: metadata.schemaVersion ?? AGENT_AUDIT_SCHEMA_VERSION,\n eventKind,\n decision: normalizeDecision(metadata.decision, metadata.reasoningSummary),\n ...(delegation !== undefined && { delegation }),\n };\n}\n\nexport function normalizeMetadata(\n metadata: AgentActionMetadata,\n): AgentActionMetadata {\n const normalized = createAgentAuditMetadata(metadata);\n return {\n ...normalized,\n tool: normalizeTool(normalized.tool),\n };\n}\n\nexport function buildAuditMetadata(\n metadata: AgentActionMetadata,\n): AuditMetadataLike {\n return {\n action: metadata.action,\n ...(metadata.resource !== undefined && { resource: metadata.resource }),\n actorId:\n metadata.actorId ??\n metadata.delegation?.parentIdentity ??\n metadata.agent.id,\n category: metadata.category ?? 'agent',\n ...(metadata.outcome !== undefined && { outcome: metadata.outcome }),\n agentId: metadata.agent.id,\n agentEventKind: metadata.eventKind,\n agentAuditVersion: metadata.schemaVersion,\n ...(metadata.agent.version !== undefined && {\n agentVersion: metadata.agent.version,\n }),\n ...(metadata.tool?.name !== undefined && { toolName: metadata.tool.name }),\n ...(metadata.policy?.decision !== undefined && {\n policyDecision: metadata.policy.decision,\n }),\n ...(metadata.session?.status !== undefined && {\n sessionStatus: metadata.session.status,\n }),\n };\n}\n\nexport function buildLoggerContext(\n metadata: AgentActionMetadata,\n): Record<string, unknown> {\n const tool = sanitizeTool(metadata.tool);\n const governance = sanitizeGovernance(metadata.governance);\n\n const context: Record<string, unknown> = {\n agent: {\n ...metadata.agent,\n ...(metadata.resource !== undefined && { resource: metadata.resource }),\n ...(metadata.outcome !== undefined && { outcome: metadata.outcome }),\n ...(metadata.reasoningSummary !== undefined && {\n reasoningSummary: metadata.reasoningSummary,\n }),\n schemaVersion: metadata.schemaVersion ?? AGENT_AUDIT_SCHEMA_VERSION,\n eventKind: metadata.eventKind ?? defaultEventKind(metadata),\n },\n ...(metadata.delegation !== undefined && {\n delegation: metadata.delegation,\n }),\n ...(tool !== undefined && { tool }),\n ...(metadata.policy !== undefined && { policy: metadata.policy }),\n ...(governance !== undefined && { governance }),\n ...(metadata.session !== undefined && { session: metadata.session }),\n ...(metadata.decision !== undefined && { decision: metadata.decision }),\n };\n\n // Hand the request logger an independent copy. `logger.set()` deep-merges and\n // intentionally *concatenates* array fields across calls (autotel wide-event\n // semantics). Agent lifecycles call `.set()` more than once per action with\n // the same `delegation`/`decision` objects, so sharing references would let\n // the merge mutate arrays (e.g. `authority_lineage`) in place — which would\n // then leak onto the span via `setAgentAttributes`. Cloning keeps the\n // span-bound metadata pristine.\n return structuredClone(context);\n}\n\n/**\n * Context for the *completion* `logger.set()` of a specialized lifecycle\n * wrapper. Carries only the domain state that finished mutating — tool or\n * session status. Outcome is owned by `withAgentAction`, which wraps every\n * variant and stamps it on both span and log. This deliberately omits the\n * request-level `delegation`/`decision` blocks: those were set once at the\n * start, and re-sending them would concatenate their array fields into the\n * wide event (see `buildLoggerContext`).\n */\nexport function buildLifecycleUpdateContext(\n metadata: AgentActionMetadata,\n): Record<string, unknown> {\n const tool = sanitizeTool(metadata.tool);\n return {\n ...(tool !== undefined && { tool }),\n ...(metadata.session !== undefined && {\n session: structuredClone(metadata.session),\n }),\n };\n}\n","import { AGENT_AUDIT_SCHEMA_VERSION } from './constants.js';\nimport { resolveContext, toAttributeValue, type AgentContext } from './context.js';\nimport { defaultEventKind, normalizeMetadata } from './metadata.js';\nimport type {\n AgentActionMetadata,\n AgentDecisionMetadata,\n AgentIdentity,\n AgentSessionMetadata,\n DelegationContext,\n GovernanceMetadata,\n PolicyMetadata,\n ToolCallMetadata,\n} from './types.js';\n\ntype AttributeValue =\n | string\n | number\n | boolean\n | string[]\n | number[]\n | boolean[];\n\ntype AttributeMap = Record<string, AttributeValue>;\n\nfunction setIfPresent(target: AttributeMap, key: string, value: unknown): void {\n const attr = toAttributeValue(value);\n if (attr !== undefined) {\n target[key] = attr;\n }\n}\n\nfunction appendIdentityAttributes(attrs: AttributeMap, agent: AgentIdentity): void {\n setIfPresent(attrs, 'agent.id', agent.id);\n setIfPresent(attrs, 'agent.version', agent.version);\n setIfPresent(attrs, 'agent.framework', agent.framework);\n setIfPresent(attrs, 'agent.model', agent.model);\n setIfPresent(attrs, 'agent.role', agent.role);\n setIfPresent(attrs, 'agent.session.id', agent.sessionId);\n setIfPresent(attrs, 'agent.conversation.id', agent.conversationId);\n}\n\nfunction appendDelegationAttributes(\n attrs: AttributeMap,\n delegation?: DelegationContext,\n): void {\n if (!delegation) return;\n setIfPresent(attrs, 'delegation.parent_identity', delegation.parentIdentity);\n setIfPresent(attrs, 'delegation.scope', delegation.scope);\n setIfPresent(attrs, 'delegation.token_id', delegation.tokenId);\n setIfPresent(attrs, 'delegation.id', delegation.delegationId);\n setIfPresent(attrs, 'delegation.authority_lineage', delegation.authorityLineage);\n setIfPresent(\n attrs,\n 'delegation.authority_lineage_hash',\n delegation.authorityLineageHash,\n );\n setIfPresent(attrs, 'delegation.depth', delegation.depth);\n setIfPresent(attrs, 'delegation.issued_at', delegation.issuedAt);\n setIfPresent(attrs, 'delegation.expires_at', delegation.expiresAt);\n}\n\nfunction appendToolAttributes(attrs: AttributeMap, tool?: ToolCallMetadata): void {\n if (!tool) return;\n setIfPresent(attrs, 'tool.name', tool.name);\n setIfPresent(attrs, 'tool.call.id', tool.callId);\n setIfPresent(attrs, 'tool.input_hash', tool.inputHash);\n setIfPresent(attrs, 'tool.output_hash', tool.outputHash);\n setIfPresent(attrs, 'tool.status', tool.status);\n setIfPresent(attrs, 'tool.execution_ms', tool.executionMs);\n}\n\nfunction appendPolicyAttributes(attrs: AttributeMap, policy?: PolicyMetadata): void {\n if (!policy) return;\n setIfPresent(attrs, 'policy.decision', policy.decision);\n setIfPresent(attrs, 'policy.id', policy.policyId);\n setIfPresent(attrs, 'policy.risk_score', policy.riskScore);\n setIfPresent(attrs, 'policy.reason', policy.reason);\n}\n\nfunction appendGovernanceAttributes(\n attrs: AttributeMap,\n governance?: GovernanceMetadata,\n): void {\n if (!governance) return;\n setIfPresent(attrs, 'governance.review_required', governance.reviewRequired);\n setIfPresent(attrs, 'governance.reviewer_id', governance.reviewerId);\n setIfPresent(attrs, 'governance.control_id', governance.controlId);\n setIfPresent(attrs, 'governance.documentation_url', governance.documentationUrl);\n setIfPresent(attrs, 'governance.lifecycle_stage', governance.lifecycleStage);\n setIfPresent(attrs, 'governance.framework', governance.framework);\n}\n\nfunction appendSessionAttributes(\n attrs: AttributeMap,\n session?: AgentSessionMetadata,\n): void {\n if (!session) return;\n setIfPresent(attrs, 'agent.session.status', session.status);\n setIfPresent(attrs, 'agent.session.started_at', session.startedAt);\n setIfPresent(attrs, 'agent.session.ended_at', session.endedAt);\n setIfPresent(attrs, 'agent.session.delegated_by', session.delegatedBy);\n}\n\nfunction appendDecisionAttributes(\n attrs: AttributeMap,\n decision?: AgentDecisionMetadata,\n): void {\n if (!decision) return;\n setIfPresent(attrs, 'decision.summary', decision.summary);\n setIfPresent(attrs, 'decision.input_hash', decision.inputHash);\n setIfPresent(attrs, 'decision.policy_ids', decision.policyIds);\n setIfPresent(attrs, 'decision.justification_codes', decision.justificationCodes);\n setIfPresent(attrs, 'decision.evidence_ids', decision.evidenceIds);\n setIfPresent(attrs, 'decision.review_required', decision.reviewRequired);\n setIfPresent(attrs, 'decision.confidence', decision.confidence);\n}\n\nexport function flattenAgentAttributes(\n metadata: AgentActionMetadata,\n): AttributeMap {\n const normalized = normalizeMetadata(metadata);\n const attrs: AttributeMap = {\n 'autotel.agent': true,\n 'agent.action': normalized.action,\n 'agent.audit.version':\n normalized.schemaVersion ?? AGENT_AUDIT_SCHEMA_VERSION,\n 'agent.event.kind': normalized.eventKind ?? defaultEventKind(normalized),\n };\n\n setIfPresent(attrs, 'agent.resource', normalized.resource);\n setIfPresent(attrs, 'agent.outcome', normalized.outcome);\n setIfPresent(attrs, 'reasoning.summary', normalized.reasoningSummary);\n appendIdentityAttributes(attrs, normalized.agent);\n appendDelegationAttributes(attrs, normalized.delegation);\n appendToolAttributes(attrs, normalized.tool);\n appendPolicyAttributes(attrs, normalized.policy);\n appendGovernanceAttributes(attrs, normalized.governance);\n appendSessionAttributes(attrs, normalized.session);\n appendDecisionAttributes(attrs, normalized.decision);\n\n return attrs;\n}\n\nexport function setAgentAttributes(\n metadata: AgentActionMetadata,\n ctx?: AgentContext,\n): void {\n const traceCtx = resolveContext(ctx);\n traceCtx.setAttributes(flattenAgentAttributes(metadata));\n}\n\n/**\n * Stamp only the terminal outcome on the active span. Used by lifecycle\n * wrappers on completion so they don't re-flatten (and clobber) richer state a\n * nested step already wrote — e.g. a tool call's `tool.status=complete`.\n */\nexport function setAgentOutcome(\n outcome: AgentActionMetadata['outcome'] & string,\n ctx?: AgentContext,\n): void {\n resolveContext(ctx).setAttribute('agent.outcome', outcome);\n}\n","import {\n createNoopRequestLogger,\n getRequestLoggerSafe,\n type RequestLogger,\n} from 'autotel';\nimport { forceKeepAuditEvent, withAudit } from 'autotel-audit';\nimport { estimateLLMCost, type TokenUsage } from '../cost.js';\nimport {\n genAiRequestAttributes,\n genAiResponseAttributes,\n genAiUsageAttributes,\n type GenAiAttributeMap,\n} from '../attributes.js';\nimport { setAgentAttributes, setAgentOutcome } from './attributes.js';\nimport {\n buildLoggerContext,\n buildLifecycleUpdateContext,\n buildAuditMetadata,\n normalizeMetadata,\n} from './metadata.js';\nimport {\n MISSING_CONTEXT_MESSAGE,\n resolveContextSafe,\n warnMissingContextOnce,\n type AgentContext,\n} from './context.js';\nimport { hashPayload } from './hash.js';\nimport type {\n AgentActionFactory,\n AgentActionMetadata,\n AgentAiMetadata,\n AgentActionOptions,\n AgentHandler,\n AgentMetadataInput,\n AgentToolCallActionMetadata,\n AgentToolCallOptions,\n ToolCallMetadata,\n} from './types.js';\n\n/**\n * Record canonical OpenTelemetry GenAI semantic attributes for an LLM-backed\n * agent action, reusing the local cost model. Best-effort: anything unknown is\n * simply omitted. `gen_ai.request.model` is always recorded; token counts and\n * the estimated `gen_ai.usage.cost.usd` are recorded when `usage` is available\n * (up front via metadata, or post-call via `options.extractUsage`).\n *\n * Emits canonical v1.42.0 keys only — no `gen_ai.usage.total_tokens` (not a\n * registry attribute) and no legacy `gen.ai.*` names.\n */\nfunction recordAiTelemetry(\n ctx: AgentContext,\n ai: AgentAiMetadata,\n usage?: TokenUsage,\n): void {\n const attrs: GenAiAttributeMap = {\n ...genAiRequestAttributes({\n operation: ai.operation,\n provider: ai.provider,\n model: ai.model,\n }),\n ...genAiResponseAttributes({\n model: ai.responseModel,\n id: ai.responseId,\n finishReasons: ai.finishReasons,\n }),\n };\n if (usage) {\n const cost = estimateLLMCost(\n ai.model,\n usage,\n ai.pricing ? { pricing: ai.pricing } : undefined,\n );\n Object.assign(attrs, genAiUsageAttributes({ ...usage, costUsd: cost }));\n }\n ctx.setAttributes(attrs);\n}\n\nexport async function withAgentAction<T>(\n metadata: AgentActionMetadata,\n fn: AgentHandler<T>,\n options: AgentActionOptions = {},\n): Promise<T> {\n const normalized = normalizeMetadata(metadata);\n\n return withAudit(\n buildAuditMetadata(normalized),\n async (ctx: AgentContext, logger: RequestLogger) => {\n setAgentAttributes(normalized, ctx);\n logger.set(buildLoggerContext(normalized));\n\n try {\n const result = await fn(ctx as AgentContext, logger);\n const outcome = normalized.outcome ?? 'success';\n setAgentOutcome(outcome, ctx);\n logger.set({ agent: { outcome } });\n if (normalized.ai) {\n recordAiTelemetry(\n ctx,\n normalized.ai,\n options.extractUsage?.(result) ?? normalized.ai.usage,\n );\n }\n return result;\n } catch (error) {\n setAgentOutcome('failure', ctx);\n logger.set({ agent: { outcome: 'failure' } });\n if (normalized.ai) recordAiTelemetry(ctx, normalized.ai);\n throw error;\n }\n },\n options,\n );\n}\n\nexport function recordPolicyDecision(\n metadata: AgentActionMetadata,\n options: AgentActionOptions = {},\n): void {\n const normalized = normalizeMetadata(metadata);\n const traceCtx = resolveContextSafe(options.ctx);\n\n // No trace context: degrade per onMissingContext instead of throwing into\n // business logic. A policy decision we couldn't record is not worth a crash.\n if (!traceCtx) {\n const mode = options.onMissingContext ?? 'warn';\n if (mode === 'throw') {\n throw new Error(MISSING_CONTEXT_MESSAGE);\n }\n if (mode === 'warn') {\n warnMissingContextOnce(normalized.action);\n }\n return;\n }\n\n const logger =\n options.logger ?? getRequestLoggerSafe() ?? createNoopRequestLogger();\n\n if (options.forceKeep !== false) {\n forceKeepAuditEvent(traceCtx);\n }\n\n setAgentAttributes(normalized, traceCtx);\n logger.set(buildLoggerContext(normalized));\n\n if (options.emitNow) {\n logger.emitNow();\n }\n}\n\nexport function recordDecisionBasis(\n metadata: AgentActionMetadata,\n options: AgentActionOptions = {},\n): void {\n if (!metadata.decision && !metadata.reasoningSummary) {\n throw new Error(\n '[autotel-genai] recordDecisionBasis requires metadata.decision or metadata.reasoningSummary.',\n );\n }\n\n recordPolicyDecision(metadata, options);\n}\n\n/**\n * Define a reusable, instrumented agent action — the `trace()`-style factory\n * companion to `withAgentAction`. Declare it once at module scope and call the\n * returned function many times; each call opens its own audit scope.\n *\n * `metadata` may be a static object or a function of the call arguments, so\n * call-specific fields can be derived per invocation.\n *\n * @example\n * ```ts\n * const planTrip = defineAgentAction(\n * (req: TripRequest) => ({\n * action: 'agent.trip.plan',\n * agent: { id: 'planner' },\n * delegation: { parentIdentity: req.userId, scope: ['trip:plan'] },\n * }),\n * (ctx) => async (req: TripRequest) => planItinerary(req),\n * );\n *\n * await planTrip({ userId: 'usr_1', destination: 'Lisbon' });\n * ```\n */\nexport function defineAgentAction<TArgs extends unknown[], TResult>(\n metadata: AgentMetadataInput<TArgs, AgentActionMetadata>,\n factory: AgentActionFactory<TArgs, TResult>,\n options: AgentActionOptions = {},\n): (...args: TArgs) => Promise<TResult> {\n return (...args: TArgs): Promise<TResult> => {\n const resolved =\n typeof metadata === 'function' ? metadata(...args) : metadata;\n return withAgentAction(\n resolved,\n (ctx, logger) => factory(ctx, logger)(...args),\n options,\n );\n };\n}\n\n/**\n * Define a reusable, instrumented agent tool call — the `trace()`-style factory\n * companion to `withAgentToolCall`. Declare it once and call it per invocation;\n * tool inputs/results are hashed (never attached raw) on every call.\n *\n * Pass `metadata` as a function of the arguments when `tool.input` (or any other\n * field) depends on the call, so each invocation hashes its own input.\n *\n * @example\n * ```ts\n * const handleRefund = defineAgentToolCall(\n * (req: RefundRequest) => ({\n * action: 'agent.refund.tool_call',\n * resource: 'stripe_refund_v3',\n * agent: { id: 'refunds-specialist' },\n * tool: { name: 'stripe_refund_v3', input: { refundId: req.refundId } },\n * }),\n * (ctx) => async (req: RefundRequest) => stripe.refunds.create(req),\n * );\n *\n * await handleRefund({ refundId: 're_123' });\n * ```\n */\nexport function defineAgentToolCall<TArgs extends unknown[], TResult>(\n metadata: AgentMetadataInput<TArgs, AgentToolCallActionMetadata>,\n factory: AgentActionFactory<TArgs, TResult>,\n options: AgentToolCallOptions = {},\n): (...args: TArgs) => Promise<TResult> {\n return (...args: TArgs): Promise<TResult> => {\n const resolved =\n typeof metadata === 'function' ? metadata(...args) : metadata;\n return withAgentToolCall(\n resolved,\n (ctx, logger) => factory(ctx, logger)(...args),\n options,\n );\n };\n}\n\nexport async function withAgentToolCall<T>(\n metadata: AgentActionMetadata & { tool: ToolCallMetadata },\n fn: AgentHandler<T>,\n options: AgentToolCallOptions = {},\n): Promise<T> {\n const start = Date.now();\n const normalized = normalizeMetadata({\n ...metadata,\n tool: {\n ...metadata.tool,\n status: metadata.tool?.status ?? 'planned',\n } as ToolCallMetadata,\n });\n\n return withAgentAction(\n normalized,\n async (ctx, logger) => {\n try {\n const result = await fn(ctx, logger);\n const executionMs = Date.now() - start;\n const completed: AgentActionMetadata = {\n ...normalized,\n outcome: normalized.outcome ?? 'success',\n tool: {\n ...metadata.tool,\n inputHash: normalized.tool?.inputHash,\n outputHash:\n normalized.tool?.outputHash ??\n (options.hashResult === false ? undefined : hashPayload(result)),\n status: 'complete',\n executionMs,\n },\n };\n setAgentAttributes(completed, ctx);\n logger.set(buildLifecycleUpdateContext(normalizeMetadata(completed)));\n return result;\n } catch (error) {\n const failed: AgentActionMetadata = {\n ...normalized,\n outcome: 'failure',\n tool: {\n ...metadata.tool,\n inputHash: normalized.tool?.inputHash,\n status: 'error',\n executionMs: Date.now() - start,\n },\n };\n setAgentAttributes(failed, ctx);\n logger.set(buildLifecycleUpdateContext(normalizeMetadata(failed)));\n throw error;\n }\n },\n options,\n );\n}\n","import { hashPayload } from './hash.js';\nimport { recordPolicyDecision } from './runtime.js';\nimport type {\n AgentActionOptions,\n AgentIdentity,\n DelegationContext,\n GovernanceMetadata,\n} from './types.js';\n\nfunction buildAuthorityLineage(\n parentIdentity: string,\n agentId: string,\n existingLineage?: string[],\n): string[] {\n const lineage = existingLineage ? [...existingLineage] : [parentIdentity];\n if (lineage.at(-1) !== agentId) {\n lineage.push(agentId);\n }\n return lineage;\n}\n\nexport interface DelegateToAgentInput {\n parentIdentity: string;\n targetAgentId: string;\n scope?: string | string[];\n tokenId?: string;\n delegationId?: string;\n authorityLineage?: string[];\n issuedAt?: string | Date;\n expiresAt?: string | Date;\n}\n\nexport interface RecordAgentHandoffMetadata {\n action: string;\n fromAgent: AgentIdentity;\n toAgent: AgentIdentity;\n parentIdentity: string;\n resource?: string;\n scope?: string | string[];\n tokenId?: string;\n delegationId?: string;\n authorityLineage?: string[];\n governance?: GovernanceMetadata;\n}\n\nexport function delegateToAgent(input: DelegateToAgentInput): DelegationContext {\n const authorityLineage = buildAuthorityLineage(\n input.parentIdentity,\n input.targetAgentId,\n input.authorityLineage,\n );\n\n return {\n parentIdentity: input.parentIdentity,\n ...(input.scope !== undefined && { scope: input.scope }),\n ...(input.tokenId !== undefined && { tokenId: input.tokenId }),\n ...(input.delegationId !== undefined && { delegationId: input.delegationId }),\n authorityLineage,\n authorityLineageHash: hashPayload(authorityLineage),\n depth: Math.max(authorityLineage.length - 1, 0),\n issuedAt: input.issuedAt ?? new Date().toISOString(),\n ...(input.expiresAt !== undefined && { expiresAt: input.expiresAt }),\n };\n}\n\nexport function recordAgentHandoff(\n metadata: RecordAgentHandoffMetadata,\n options: AgentActionOptions = {},\n): void {\n // Seed the lineage with the source agent when the caller didn't supply one,\n // so the \"from\" side of the handoff is recorded in the canonical, queryable\n // `delegation.authority_lineage` (and its hash) rather than surviving only in\n // the free-text reasoningSummary.\n const authorityLineage =\n metadata.authorityLineage ?? [metadata.parentIdentity, metadata.fromAgent.id];\n\n const delegation = delegateToAgent({\n parentIdentity: metadata.parentIdentity,\n targetAgentId: metadata.toAgent.id,\n scope: metadata.scope,\n tokenId: metadata.tokenId,\n delegationId: metadata.delegationId,\n authorityLineage,\n });\n\n recordPolicyDecision(\n {\n action: metadata.action,\n resource: metadata.resource,\n eventKind: 'handoff',\n agent: metadata.toAgent,\n delegation,\n governance: metadata.governance,\n reasoningSummary: `Control passed from ${metadata.fromAgent.id} to ${metadata.toAgent.id}.`,\n },\n options,\n );\n}\n","import { buildLifecycleUpdateContext } from './metadata.js';\nimport { setAgentAttributes } from './attributes.js';\nimport { withAgentAction } from './runtime.js';\nimport type {\n AgentActionOptions,\n AgentHandler,\n AgentSessionActionMetadata,\n} from './types.js';\n\nfunction toIsoString(value?: string | Date): string {\n if (!value) return new Date().toISOString();\n return value instanceof Date ? value.toISOString() : value;\n}\n\nexport async function withAgentSession<T>(\n metadata: AgentSessionActionMetadata,\n fn: AgentHandler<T>,\n options: AgentActionOptions = {},\n): Promise<T> {\n const startedAt = toIsoString(metadata.session?.startedAt);\n\n return withAgentAction(\n {\n ...metadata,\n category: metadata.category ?? 'agent_session',\n session: {\n ...metadata.session,\n status: metadata.session?.status ?? 'active',\n startedAt,\n },\n },\n async (ctx, logger) => {\n try {\n const result = await fn(ctx, logger);\n const completed = {\n ...metadata,\n outcome: metadata.outcome ?? 'success',\n session: {\n ...metadata.session,\n status: 'completed' as const,\n startedAt,\n endedAt: new Date().toISOString(),\n },\n };\n setAgentAttributes(completed, ctx);\n logger.set(buildLifecycleUpdateContext(completed));\n return result;\n } catch (error) {\n const failed = {\n ...metadata,\n outcome: 'failure' as const,\n session: {\n ...metadata.session,\n status: 'failed' as const,\n startedAt,\n endedAt: new Date().toISOString(),\n },\n };\n setAgentAttributes(failed, ctx);\n logger.set(buildLifecycleUpdateContext(failed));\n throw error;\n }\n },\n options,\n );\n}\n","import { hashPayload } from './hash.js';\nimport { delegateToAgent } from './delegation.js';\nimport type {\n AgentIdentity,\n AgentIdentityRegistry,\n AgentIdentityRecord,\n AgentIdentityStatus,\n DelegationContext,\n} from './types.js';\n\nfunction toIsoString(value?: string | Date): string | undefined {\n if (!value) return undefined;\n return value instanceof Date ? value.toISOString() : value;\n}\n\nfunction normalizeScopes(scope?: string | string[]): string[] {\n if (!scope) return [];\n return Array.isArray(scope) ? [...scope] : [scope];\n}\n\nfunction isExpired(record: AgentIdentityRecord, at: string): boolean {\n return record.expiresAt !== undefined && record.expiresAt < at;\n}\n\nexport interface ProvisionAgentIdentityInput {\n agent: AgentIdentity;\n scopes?: string[];\n tokenId?: string;\n delegatedBy?: string;\n provisionedAt?: string | Date;\n expiresAt?: string | Date;\n metadata?: Record<string, unknown>;\n}\n\nexport interface RotateAgentIdentityInput {\n scopes?: string[];\n tokenId?: string;\n delegatedBy?: string;\n rotatedAt?: string | Date;\n expiresAt?: string | Date;\n metadata?: Record<string, unknown>;\n}\n\nexport interface RevokeAgentIdentityInput {\n reason: string;\n revokedAt?: string | Date;\n}\n\nexport function createAgentIdentityRegistry(\n initial: ProvisionAgentIdentityInput[] = [],\n): AgentIdentityRegistry {\n const records = new Map<string, AgentIdentityRecord>();\n\n const provisionIdentity = (\n input: ProvisionAgentIdentityInput,\n ): AgentIdentityRecord => {\n const now = toIsoString(input.provisionedAt) ?? new Date().toISOString();\n const record: AgentIdentityRecord = {\n agent: input.agent,\n scopes: input.scopes ?? [],\n status: 'active',\n tokenId: input.tokenId,\n tokenHash:\n input.tokenId === undefined ? undefined : hashPayload(input.tokenId),\n delegatedBy: input.delegatedBy,\n provisionedAt: now,\n expiresAt: toIsoString(input.expiresAt),\n metadata: input.metadata,\n };\n records.set(input.agent.id, record);\n return record;\n };\n\n for (const item of initial) {\n provisionIdentity(item);\n }\n\n return {\n provisionIdentity,\n rotateIdentity(agentId: string, input: RotateAgentIdentityInput = {}) {\n const existing = records.get(agentId);\n if (!existing) {\n throw new Error(\n `[autotel-genai] Cannot rotate unknown agent identity \"${agentId}\".`,\n );\n }\n\n const rotatedAt = toIsoString(input.rotatedAt) ?? new Date().toISOString();\n const record: AgentIdentityRecord = {\n ...existing,\n scopes: input.scopes ?? existing.scopes,\n status: 'rotated',\n tokenId: input.tokenId ?? existing.tokenId,\n tokenHash:\n input.tokenId === undefined\n ? existing.tokenHash\n : hashPayload(input.tokenId),\n delegatedBy: input.delegatedBy ?? existing.delegatedBy,\n rotatedAt,\n expiresAt: toIsoString(input.expiresAt) ?? existing.expiresAt,\n metadata: input.metadata ?? existing.metadata,\n };\n records.set(agentId, record);\n return record;\n },\n revokeIdentity(agentId: string, input: RevokeAgentIdentityInput) {\n const existing = records.get(agentId);\n if (!existing) {\n throw new Error(\n `[autotel-genai] Cannot revoke unknown agent identity \"${agentId}\".`,\n );\n }\n\n const revokedAt = toIsoString(input.revokedAt) ?? new Date().toISOString();\n const record: AgentIdentityRecord = {\n ...existing,\n status: 'revoked',\n revokedAt,\n revocationReason: input.reason,\n };\n records.set(agentId, record);\n return record;\n },\n getIdentity(agentId: string) {\n return records.get(agentId);\n },\n getIdentityStatus(agentId: string, at = new Date().toISOString()) {\n const record = records.get(agentId);\n if (!record) return;\n return isExpired(record, at) ? 'expired' : record.status;\n },\n assertUsable(agentId: string, at = new Date().toISOString()) {\n const record = records.get(agentId);\n if (!record) {\n throw new Error(\n `[autotel-genai] Unknown agent identity \"${agentId}\". Provision it before use.`,\n );\n }\n\n const status: AgentIdentityStatus = isExpired(record, at)\n ? 'expired'\n : record.status;\n\n if (status !== 'active' && status !== 'rotated') {\n throw new Error(\n `[autotel-genai] Agent identity \"${agentId}\" is ${status} and cannot execute delegated work.`,\n );\n }\n\n return record;\n },\n assertScopes(agentId: string, requiredScopes: string[]) {\n const record = this.assertUsable(agentId);\n const missing = requiredScopes.filter(\n (scope) => !record.scopes.includes(scope),\n );\n\n if (missing.length > 0) {\n throw new Error(\n `[autotel-genai] Agent identity \"${agentId}\" is missing delegated scopes: ${missing.join(', ')}.`,\n );\n }\n\n return record;\n },\n issueDelegation(agentId: string, input) {\n const record = this.assertUsable(agentId);\n const scope = normalizeScopes(input.scope);\n if (scope.length > 0) {\n this.assertScopes(agentId, scope);\n }\n\n return delegateToAgent({\n parentIdentity: input.parentIdentity,\n targetAgentId: record.agent.id,\n scope: input.scope ?? record.scopes,\n tokenId: input.tokenId ?? record.tokenId,\n delegationId: input.delegationId,\n authorityLineage: input.authorityLineage,\n issuedAt: input.issuedAt,\n expiresAt: input.expiresAt ?? record.expiresAt,\n }) satisfies DelegationContext;\n },\n list() {\n return [...records.values()];\n },\n };\n}\n","import { hashPayload } from './hash.js';\nimport type { PrivacyProfile, PrivacyProfileName } from './types.js';\n\nexport type PrivacyProfileInput = PrivacyProfileName | PrivacyProfile;\n\nconst PRIVACY_PROFILES: Record<PrivacyProfileName, PrivacyProfile> = {\n strict: {\n name: 'strict',\n hashKeys: [\n /email/i,\n /phone/i,\n /user_?id/i,\n /account/i,\n /customer/i,\n /card/i,\n /iban/i,\n /tax/i,\n ],\n dropKeys: [\n /secret/i,\n /token/i,\n /api[_-]?key/i,\n /authorization/i,\n /cookie/i,\n /password/i,\n /bearer/i,\n ],\n maskKeys: [/name/i, /address/i, /prompt/i, /message/i, /content/i],\n maxStringLength: 256,\n },\n pci: {\n name: 'pci',\n hashKeys: [/card/i, /pan/i, /account/i, /customer/i, /email/i],\n dropKeys: [/cvv/i, /cvc/i, /secret/i, /token/i, /api[_-]?key/i],\n maskKeys: [/name/i, /address/i],\n maxStringLength: 128,\n },\n healthcare: {\n name: 'healthcare',\n hashKeys: [/patient/i, /mrn/i, /member/i, /email/i, /phone/i],\n dropKeys: [/diagnosis/i, /notes/i, /secret/i, /token/i, /password/i],\n maskKeys: [/name/i, /address/i, /symptom/i],\n maxStringLength: 128,\n },\n};\n\nfunction maskValue(value: unknown): unknown {\n if (typeof value !== 'string') {\n return '<masked>';\n }\n\n if (value.length <= 6) return '***';\n return `${value.slice(0, 3)}***${value.slice(-3)}`;\n}\n\nfunction matches(patterns: RegExp[] | undefined, key: string): boolean {\n return patterns?.some((pattern) => pattern.test(key)) ?? false;\n}\n\nfunction truncateString(value: string, maxLength?: number): string {\n if (maxLength === undefined || value.length <= maxLength) {\n return value;\n }\n\n return `${value.slice(0, maxLength)}…`;\n}\n\nfunction sanitizeNode(\n value: unknown,\n profile: PrivacyProfile,\n keyPath: string,\n): unknown {\n if (value instanceof Date) {\n return value.toISOString();\n }\n\n const lowered = keyPath.toLowerCase();\n\n if (matches(profile.dropKeys, lowered)) {\n return '<redacted>';\n }\n\n if (matches(profile.hashKeys, lowered)) {\n return hashPayload(value);\n }\n\n if (matches(profile.maskKeys, lowered)) {\n return maskValue(value);\n }\n\n if (typeof value === 'string') {\n return truncateString(value, profile.maxStringLength);\n }\n\n if (Array.isArray(value)) {\n return value.map((entry, index) =>\n sanitizeNode(entry, profile, `${keyPath}[${index}]`),\n );\n }\n\n if (value && typeof value === 'object') {\n return Object.fromEntries(\n Object.entries(value as Record<string, unknown>).map(([key, entry]) => [\n key,\n sanitizeNode(entry, profile, keyPath ? `${keyPath}.${key}` : key),\n ]),\n );\n }\n\n if (typeof value === 'bigint') {\n return value.toString(10);\n }\n\n return value;\n}\n\nexport function resolvePrivacyProfile(\n profile: PrivacyProfileInput = 'strict',\n): PrivacyProfile {\n return typeof profile === 'string' ? PRIVACY_PROFILES[profile] : profile;\n}\n\nexport function sanitizeAuditPayload(\n value: unknown,\n profile: PrivacyProfileInput = 'strict',\n): unknown {\n return sanitizeNode(value, resolvePrivacyProfile(profile), '');\n}\n","import { AGENT_AUDIT_SCHEMA_VERSION } from './constants.js';\nimport { canonicalizeForHash, hashPayload } from './hash.js';\nimport { normalizeMetadata } from './metadata.js';\nimport { sanitizeAuditPayload, type PrivacyProfileInput } from './privacy.js';\nimport type {\n AgentActionMetadata,\n AgentAuditEventEnvelope,\n} from './types.js';\n\nfunction toIsoString(value?: string | Date): string {\n if (!value) return new Date().toISOString();\n return value instanceof Date ? value.toISOString() : value;\n}\n\nexport interface CreateSignedEventEnvelopeOptions {\n emittedAt?: string | Date;\n previousEventHash?: string;\n evidence?: unknown;\n privacyProfile?: PrivacyProfileInput;\n signer?: (serialized: string) => string | Promise<string>;\n}\n\nexport async function createSignedEventEnvelope(\n metadata: AgentActionMetadata,\n options: CreateSignedEventEnvelopeOptions = {},\n): Promise<AgentAuditEventEnvelope> {\n const normalized = normalizeMetadata(metadata);\n const envelopeBase = {\n schemaVersion: normalized.schemaVersion ?? AGENT_AUDIT_SCHEMA_VERSION,\n emittedAt: toIsoString(options.emittedAt),\n ...(options.previousEventHash !== undefined && {\n previousEventHash: options.previousEventHash,\n }),\n metadata: normalized,\n ...(options.evidence !== undefined && {\n evidence: sanitizeAuditPayload(\n options.evidence,\n options.privacyProfile ?? 'strict',\n ),\n }),\n };\n\n const eventHash = hashPayload(envelopeBase);\n const signature = options.signer\n ? await options.signer(canonicalizeForHash(envelopeBase))\n : undefined;\n\n return {\n ...envelopeBase,\n eventHash,\n ...(signature !== undefined && { signature }),\n };\n}\n\nexport function verifyEventEnvelopeHash(\n envelope: AgentAuditEventEnvelope,\n): boolean {\n const expected = hashPayload({\n schemaVersion: envelope.schemaVersion,\n emittedAt: envelope.emittedAt,\n ...(envelope.previousEventHash !== undefined && {\n previousEventHash: envelope.previousEventHash,\n }),\n metadata: envelope.metadata,\n ...(envelope.evidence !== undefined && {\n evidence: envelope.evidence,\n }),\n });\n return envelope.eventHash === expected;\n}\n","import { createStructuredError } from 'autotel';\nimport { securityEvent } from 'autotel-audit';\nimport { sanitizeAuditPayload, type PrivacyProfileInput } from './privacy.js';\nimport { recordDecisionBasis, recordPolicyDecision, withAgentToolCall } from './runtime.js';\nimport { hashPayload } from './hash.js';\nimport type {\n AgentActionOptions,\n AgentDecisionMetadata,\n AgentHandler,\n AgentToolCallOptions,\n DelegationContext,\n GovernanceMetadata,\n PolicyMetadata,\n ScopedToolDefinition,\n} from './types.js';\n\nfunction normalizeScopes(scope?: string | string[]): string[] {\n if (!scope) return [];\n return Array.isArray(scope) ? scope : [scope];\n}\n\nfunction missingScopes(\n delegated: string[],\n required: string[],\n): string[] {\n return required.filter((scope) => !delegated.includes(scope));\n}\n\ninterface ScopeDenial {\n scopes: string[];\n reason: string;\n why: string;\n}\n\n/**\n * Decide whether a scoped tool call must be denied.\n *\n * When the identity is registry-backed, the registry is authoritative: a\n * delegation may only *narrow* the stored grant, never widen it. Scopes a\n * caller claims that the registry never granted are a forged escalation and are\n * denied before any missing-scope check — otherwise passing an explicit\n * `delegation.scope` could grant access the registry record does not allow.\n */\nfunction resolveScopeDenial(\n claimedScopes: string[],\n requiredScopes: string[],\n registryScopes: string[] | undefined,\n): ScopeDenial | undefined {\n const unauthorized = registryScopes\n ? claimedScopes.filter((scope) => !registryScopes.includes(scope))\n : [];\n if (unauthorized.length > 0) {\n return {\n scopes: unauthorized,\n reason: `unauthorized_scope:${unauthorized.join(',')}`,\n why: `Delegation claims scopes the identity was never granted: ${unauthorized.join(', ')}`,\n };\n }\n\n const missing = missingScopes(claimedScopes, requiredScopes);\n if (missing.length > 0) {\n return {\n scopes: missing,\n reason: `missing_scope:${missing.join(',')}`,\n why: `Missing delegated scopes: ${missing.join(', ')}`,\n };\n }\n\n return undefined;\n}\n\nfunction resolveDelegation(\n definition: Pick<ScopedToolDefinition<unknown>, 'agent' | 'delegation' | 'identityRegistry'>,\n): DelegationContext | undefined {\n const registry = definition.identityRegistry;\n if (registry) {\n registry.assertUsable(definition.agent.id);\n }\n\n return definition.delegation;\n}\n\nfunction buildGovernance(\n governance: GovernanceMetadata | undefined,\n reviewRequired: boolean | undefined,\n): GovernanceMetadata | undefined {\n if (!governance && reviewRequired === undefined) return governance;\n return {\n ...governance,\n ...(reviewRequired !== undefined && { reviewRequired }),\n };\n}\n\nfunction buildDecision(\n input: unknown,\n decision: AgentDecisionMetadata | undefined,\n privacyProfile: PrivacyProfileInput | undefined,\n): AgentDecisionMetadata | undefined {\n if (!decision) return undefined;\n\n const sanitizedInput = sanitizeAuditPayload(input, privacyProfile ?? 'strict');\n return {\n ...decision,\n inputHash: decision.inputHash ?? hashPayload(sanitizedInput),\n };\n}\n\nexport async function withScopedTool<TInput, TOutput>(\n definition: ScopedToolDefinition<TInput>,\n input: TInput,\n fn: AgentHandler<TOutput>,\n options: AgentToolCallOptions & AgentActionOptions = {},\n): Promise<TOutput> {\n const requiredScopes = definition.requiredScopes ?? [];\n const delegation = resolveDelegation(definition);\n const registryScopes = definition.identityRegistry?.getIdentity(\n definition.agent.id,\n )?.scopes;\n const claimedScopes = normalizeScopes(delegation?.scope ?? registryScopes);\n const denial = resolveScopeDenial(\n claimedScopes,\n requiredScopes,\n registryScopes,\n );\n const policy: PolicyMetadata | undefined =\n definition.policyId || definition.riskScore !== undefined || denial\n ? {\n decision: denial ? 'deny' : 'permit',\n ...(definition.policyId !== undefined && {\n policyId: definition.policyId,\n }),\n ...(definition.riskScore !== undefined && {\n riskScore: definition.riskScore,\n }),\n ...(denial && { reason: denial.reason }),\n }\n : undefined;\n\n const governance = buildGovernance(\n definition.governance,\n definition.reviewRequired,\n );\n\n if (policy && policy.decision === 'deny' && denial) {\n recordPolicyDecision(\n {\n action: definition.action,\n resource: definition.resource ?? definition.tool.name,\n category: definition.category,\n agent: definition.agent,\n delegation,\n policy,\n governance,\n decision: buildDecision(\n input,\n definition.decision,\n definition.privacyProfile,\n ),\n },\n options,\n );\n\n securityEvent(\n {\n name: 'llm.tool_call.denied',\n category: 'llm',\n outcome: 'denied',\n severity: 'warning',\n reason: denial.reason,\n targetType: 'tool',\n targetId: definition.tool.name,\n policyId: definition.policyId,\n },\n { ctx: options.ctx, onMissingContext: options.onMissingContext ?? 'warn' },\n );\n\n throw createStructuredError({\n status: 403,\n code: 'AGENT_SCOPE_DENIED',\n message: `Agent \"${definition.agent.id}\" cannot invoke ${definition.tool.name}.`,\n why: denial.why,\n fix: 'Grant the missing scopes or route the task to an agent with the required delegation.',\n });\n }\n\n if (policy) {\n recordPolicyDecision(\n {\n action: `${definition.action}.policy`,\n resource: definition.resource ?? definition.tool.name,\n category: definition.category,\n agent: definition.agent,\n delegation,\n policy,\n governance,\n },\n options,\n );\n }\n\n if (definition.decision) {\n recordDecisionBasis(\n {\n action: `${definition.action}.decision`,\n resource: definition.resource ?? definition.tool.name,\n category: definition.category,\n agent: definition.agent,\n delegation,\n governance,\n decision: buildDecision(\n input,\n definition.decision,\n definition.privacyProfile,\n ),\n },\n options,\n );\n }\n\n return withAgentToolCall(\n {\n action: definition.action,\n resource: definition.resource ?? definition.tool.name,\n category: definition.category,\n agent: definition.agent,\n delegation,\n governance,\n tool: {\n ...definition.tool,\n input,\n },\n },\n fn,\n options,\n );\n}\n","import { securityEvent } from 'autotel-audit';\nimport { resolveContext, toAttributeValue, type AgentContext } from './context.js';\n\n/** Canonical plan-risk attribute keys (Google SAIF plan-risk predictor aligned). */\nexport const AGENT_PLAN_RISK_ATTR = {\n verdict: 'agent.plan.risk.verdict',\n score: 'agent.plan.risk.score',\n categories: 'agent.plan.risk.categories',\n toolSequence: 'agent.plan.risk.tool_sequence',\n} as const;\n\nexport type AgentPlanRiskVerdict = 'low' | 'medium' | 'high' | 'critical';\n\nexport interface AgentPlanClassifierInput {\n /** Proposed tool names in execution order. */\n toolSequence: string[];\n stepIndex?: number;\n summary?: string;\n policyIds?: string[];\n /** Extra context attrs (scopes, intents) — values are coerced for OTel. */\n context?: Record<string, unknown>;\n}\n\nexport interface AgentPlanClassifierResult {\n verdict: AgentPlanRiskVerdict;\n /** 0..1 risk score from the classifier. */\n score?: number;\n categories?: string[];\n reason?: string;\n}\n\nexport type AgentPlanClassifier = (\n input: AgentPlanClassifierInput,\n) =>\n | AgentPlanClassifierResult\n | undefined\n | Promise<AgentPlanClassifierResult | undefined>;\n\nexport interface RecordPlanRiskAssessmentOptions {\n ctx?: AgentContext;\n assessment: AgentPlanClassifierResult;\n toolSequence?: string[];\n /** Emit `llm.plan.risk.elevated` when verdict is not `low`. Default false. */\n emitSecurityEvent?: boolean;\n}\n\nfunction setPlanRiskAttrs(\n ctx: AgentContext | undefined,\n attrs: Record<string, unknown>,\n): void {\n const traceCtx = resolveContext(ctx);\n const mapped: Record<string, string | number | boolean | string[] | number[] | boolean[]> =\n {};\n for (const [key, value] of Object.entries(attrs)) {\n const attr = toAttributeValue(value);\n if (attr !== undefined) {\n mapped[key] = attr;\n }\n }\n if (Object.keys(mapped).length > 0) {\n traceCtx.setAttributes(mapped);\n }\n}\n\n/**\n * Stamp plan-risk assessment attrs on the active span.\n */\nexport function recordPlanRiskAssessment(\n options: RecordPlanRiskAssessmentOptions,\n): void {\n const { assessment, toolSequence } = options;\n setPlanRiskAttrs(options.ctx, {\n [AGENT_PLAN_RISK_ATTR.verdict]: assessment.verdict,\n ...(assessment.score !== undefined && {\n [AGENT_PLAN_RISK_ATTR.score]: assessment.score,\n }),\n ...(assessment.categories?.length && {\n [AGENT_PLAN_RISK_ATTR.categories]: assessment.categories,\n }),\n ...(toolSequence?.length && {\n [AGENT_PLAN_RISK_ATTR.toolSequence]: toolSequence,\n }),\n ...(assessment.reason !== undefined && { 'decision.summary': assessment.reason }),\n });\n\n if (\n options.emitSecurityEvent &&\n assessment.verdict !== 'low'\n ) {\n securityEvent(\n {\n name: 'llm.plan.risk.elevated',\n category: 'llm',\n outcome: assessment.verdict === 'critical' ? 'blocked' : 'denied',\n severity:\n assessment.verdict === 'critical'\n ? 'critical'\n : assessment.verdict === 'high'\n ? 'error'\n : 'warning',\n reason: assessment.reason ?? assessment.verdict,\n ...(assessment.score !== undefined && { score: assessment.score }),\n ...(assessment.categories?.length && {\n categories: assessment.categories.join(','),\n }),\n },\n { ctx: options.ctx },\n );\n }\n}\n\n/**\n * Run a pluggable plan-risk classifier and record its verdict on the span.\n * Classifier failures degrade quietly (no assessment recorded).\n */\nexport async function runAgentPlanClassifier(\n classifier: AgentPlanClassifier,\n input: AgentPlanClassifierInput,\n options: Omit<RecordPlanRiskAssessmentOptions, 'assessment'> = {},\n): Promise<AgentPlanClassifierResult | undefined> {\n let assessment: AgentPlanClassifierResult | undefined;\n try {\n assessment = await classifier(input);\n } catch {\n return undefined;\n }\n if (!assessment) return undefined;\n recordPlanRiskAssessment({\n ...options,\n assessment,\n toolSequence: input.toolSequence,\n });\n return assessment;\n}\n\nconst DESTRUCTIVE_TOOL = /\\b(delete|remove|send|post|transfer|pay|upload|execute)\\b/i;\nconst UNTRUSTED_READ = /\\b(read|fetch|get|search|load|parse|inbox|email|web|scrape)\\b/i;\n\n/**\n * Dependency-free first-pass plan-risk heuristic. Opt-in — pass as\n * `AgentPlanClassifier` or wrap your own Model Armor / Llama Guard adapter.\n */\nexport function heuristicPlanRiskClassifier(): AgentPlanClassifier {\n return ({ toolSequence }) => {\n if (toolSequence.length === 0) {\n return { verdict: 'low', score: 0 };\n }\n\n const normalized = toolSequence.map((name) => name.replaceAll('_', ' '));\n const hasDestructive = normalized.some((name) => DESTRUCTIVE_TOOL.test(name));\n const hasUntrustedRead = normalized.some((name) => UNTRUSTED_READ.test(name));\n\n if (hasDestructive && hasUntrustedRead) {\n return {\n verdict: 'high',\n score: 0.85,\n categories: ['untrusted_to_destructive_chain'],\n reason: 'mixed_untrusted_and_destructive_tools',\n };\n }\n\n if (toolSequence.length >= 8) {\n return {\n verdict: 'medium',\n score: 0.55,\n categories: ['long_tool_chain'],\n reason: 'long_tool_sequence',\n };\n }\n\n return { verdict: 'low', score: 0.1 };\n };\n}\n"],"mappings":";;;;;;;;AAAA,MAAa,6BAA6B;;;;ACM1C,SAAS,aAAa,OAAyB;CAC7C,IAAI,iBAAiB,MACnB,OAAO,MAAM,YAAY;CAG3B,IAAI,OAAO,UAAU,UACnB,OAAO,MAAM,SAAS,EAAE;CAG1B,IAAI,MAAM,QAAQ,KAAK,GACrB,OAAO,MAAM,KAAK,UAAU,aAAa,KAAK,CAAC;CAGjD,IAAI,SAAS,OAAO,UAAU,UAAU;EAEtC,MAAM,UAAU,OAAO,QAAQ,KAAgC;EAC/D,QAAQ,MAAM,CAAC,OAAO,CAAC,WAAW,KAAK,cAAc,KAAK,CAAC;EAC3D,OAAO,OAAO,YACZ,QAAQ,KAAK,CAAC,KAAK,gBAAgB,CAAC,KAAK,aAAa,UAAU,CAAC,CAAC,CACpE;CACF;CAEA,OAAO;AACT;AAEA,SAAgB,oBAAoB,OAAwB;CAC1D,OAAO,KAAK,UAAU,aAAa,KAAK,CAAC;AAC3C;AAEA,SAAgB,YACd,OACA,UAA8B,CAAC,GACvB;CACR,MAAM,YAAY,QAAQ,aAAa;CACvC,MAAM,YAAY,oBAAoB,KAAK;CAE3C,OAAO,GAAG,UAAU,+BADM,SAAS,CAAC,CAAC,OAAO,SAAS,CAAC,CAAC,OAAO,KAClC;AAC9B;;;;ACxBA,SAAgB,iBACd,UACgB;CAChB,IAAI,SAAS,WAAW,OAAO,SAAS;CACxC,IAAI,SAAS,MAAM,OAAO;CAC1B,IAAI,SAAS,QAAQ,OAAO;CAC5B,OAAO;AACT;AAEA,SAAgB,cACd,MAC8B;CAC9B,IAAI,C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