shield360 1.0.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 (520) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +310 -0
  3. package/dist/__tests__/manual-trace.test.d.ts +1 -0
  4. package/dist/__tests__/manual-trace.test.js +118 -0
  5. package/dist/__tests__/manual-trace.test.js.map +1 -0
  6. package/dist/__tests__/register.test.d.ts +0 -0
  7. package/dist/__tests__/register.test.js +90 -0
  8. package/dist/__tests__/register.test.js.map +1 -0
  9. package/dist/config.d.ts +28 -0
  10. package/dist/config.js +22 -0
  11. package/dist/config.js.map +1 -0
  12. package/dist/constant.d.ts +6 -0
  13. package/dist/constant.js +14 -0
  14. package/dist/constant.js.map +1 -0
  15. package/dist/evals/__tests__/offline.test.d.ts +1 -0
  16. package/dist/evals/__tests__/offline.test.js +427 -0
  17. package/dist/evals/__tests__/offline.test.js.map +1 -0
  18. package/dist/evals/index.d.ts +2 -0
  19. package/dist/evals/index.js +15 -0
  20. package/dist/evals/index.js.map +1 -0
  21. package/dist/evals/offline.d.ts +6 -0
  22. package/dist/evals/offline.js +350 -0
  23. package/dist/evals/offline.js.map +1 -0
  24. package/dist/evals/types.d.ts +74 -0
  25. package/dist/evals/types.js +23 -0
  26. package/dist/evals/types.js.map +1 -0
  27. package/dist/features/__tests__/rule-engine.test.d.ts +1 -0
  28. package/dist/features/__tests__/rule-engine.test.js +146 -0
  29. package/dist/features/__tests__/rule-engine.test.js.map +1 -0
  30. package/dist/features/base.d.ts +8 -0
  31. package/dist/features/base.js +15 -0
  32. package/dist/features/base.js.map +1 -0
  33. package/dist/features/prompt-hub.d.ts +4 -0
  34. package/dist/features/prompt-hub.js +66 -0
  35. package/dist/features/prompt-hub.js.map +1 -0
  36. package/dist/features/rule-engine.d.ts +6 -0
  37. package/dist/features/rule-engine.js +60 -0
  38. package/dist/features/rule-engine.js.map +1 -0
  39. package/dist/features/vault.d.ts +4 -0
  40. package/dist/features/vault.js +63 -0
  41. package/dist/features/vault.js.map +1 -0
  42. package/dist/guard/__tests__/findings.test.d.ts +1 -0
  43. package/dist/guard/__tests__/findings.test.js +79 -0
  44. package/dist/guard/__tests__/findings.test.js.map +1 -0
  45. package/dist/guard/__tests__/integration.test.d.ts +1 -0
  46. package/dist/guard/__tests__/integration.test.js +215 -0
  47. package/dist/guard/__tests__/integration.test.js.map +1 -0
  48. package/dist/guard/__tests__/pii.test.d.ts +1 -0
  49. package/dist/guard/__tests__/pii.test.js +131 -0
  50. package/dist/guard/__tests__/pii.test.js.map +1 -0
  51. package/dist/guard/__tests__/pipeline.test.d.ts +1 -0
  52. package/dist/guard/__tests__/pipeline.test.js +162 -0
  53. package/dist/guard/__tests__/pipeline.test.js.map +1 -0
  54. package/dist/guard/__tests__/prompt-injection.test.d.ts +1 -0
  55. package/dist/guard/__tests__/prompt-injection.test.js +92 -0
  56. package/dist/guard/__tests__/prompt-injection.test.js.map +1 -0
  57. package/dist/guard/__tests__/report.test.d.ts +1 -0
  58. package/dist/guard/__tests__/report.test.js +50 -0
  59. package/dist/guard/__tests__/report.test.js.map +1 -0
  60. package/dist/guard/base.d.ts +79 -0
  61. package/dist/guard/base.js +136 -0
  62. package/dist/guard/base.js.map +1 -0
  63. package/dist/guard/custom.d.ts +19 -0
  64. package/dist/guard/custom.js +46 -0
  65. package/dist/guard/custom.js.map +1 -0
  66. package/dist/guard/findings.d.ts +31 -0
  67. package/dist/guard/findings.js +156 -0
  68. package/dist/guard/findings.js.map +1 -0
  69. package/dist/guard/index.d.ts +24 -0
  70. package/dist/guard/index.js +42 -0
  71. package/dist/guard/index.js.map +1 -0
  72. package/dist/guard/integration.d.ts +44 -0
  73. package/dist/guard/integration.js +363 -0
  74. package/dist/guard/integration.js.map +1 -0
  75. package/dist/guard/moderation.d.ts +18 -0
  76. package/dist/guard/moderation.js +61 -0
  77. package/dist/guard/moderation.js.map +1 -0
  78. package/dist/guard/pii.d.ts +17 -0
  79. package/dist/guard/pii.js +114 -0
  80. package/dist/guard/pii.js.map +1 -0
  81. package/dist/guard/pipeline.d.ts +26 -0
  82. package/dist/guard/pipeline.js +139 -0
  83. package/dist/guard/pipeline.js.map +1 -0
  84. package/dist/guard/prompt-injection.d.ts +21 -0
  85. package/dist/guard/prompt-injection.js +70 -0
  86. package/dist/guard/prompt-injection.js.map +1 -0
  87. package/dist/guard/report.d.ts +34 -0
  88. package/dist/guard/report.js +182 -0
  89. package/dist/guard/report.js.map +1 -0
  90. package/dist/guard/schema.d.ts +20 -0
  91. package/dist/guard/schema.js +99 -0
  92. package/dist/guard/schema.js.map +1 -0
  93. package/dist/guard/sensitive-topic.d.ts +23 -0
  94. package/dist/guard/sensitive-topic.js +89 -0
  95. package/dist/guard/sensitive-topic.js.map +1 -0
  96. package/dist/guard/topic-restriction.d.ts +22 -0
  97. package/dist/guard/topic-restriction.js +54 -0
  98. package/dist/guard/topic-restriction.js.map +1 -0
  99. package/dist/helpers.d.ts +246 -0
  100. package/dist/helpers.js +903 -0
  101. package/dist/helpers.js.map +1 -0
  102. package/dist/index.d.ts +71 -0
  103. package/dist/index.js +234 -0
  104. package/dist/index.js.map +1 -0
  105. package/dist/instrumentation/__tests__/ai21-rag-trace-comparison.test.d.ts +13 -0
  106. package/dist/instrumentation/__tests__/ai21-rag-trace-comparison.test.js +176 -0
  107. package/dist/instrumentation/__tests__/ai21-rag-trace-comparison.test.js.map +1 -0
  108. package/dist/instrumentation/__tests__/ai21-trace-comparison.test.d.ts +10 -0
  109. package/dist/instrumentation/__tests__/ai21-trace-comparison.test.js +203 -0
  110. package/dist/instrumentation/__tests__/ai21-trace-comparison.test.js.map +1 -0
  111. package/dist/instrumentation/__tests__/anthropic-wrapper.test.d.ts +1 -0
  112. package/dist/instrumentation/__tests__/anthropic-wrapper.test.js +284 -0
  113. package/dist/instrumentation/__tests__/anthropic-wrapper.test.js.map +1 -0
  114. package/dist/instrumentation/__tests__/assemblyai-wrapper.test.d.ts +1 -0
  115. package/dist/instrumentation/__tests__/assemblyai-wrapper.test.js +284 -0
  116. package/dist/instrumentation/__tests__/assemblyai-wrapper.test.js.map +1 -0
  117. package/dist/instrumentation/__tests__/astra-trace-comparison.test.d.ts +7 -0
  118. package/dist/instrumentation/__tests__/astra-trace-comparison.test.js +160 -0
  119. package/dist/instrumentation/__tests__/astra-trace-comparison.test.js.map +1 -0
  120. package/dist/instrumentation/__tests__/base-wrapper.test.d.ts +1 -0
  121. package/dist/instrumentation/__tests__/base-wrapper.test.js +171 -0
  122. package/dist/instrumentation/__tests__/base-wrapper.test.js.map +1 -0
  123. package/dist/instrumentation/__tests__/bedrock-trace-comparison.test.d.ts +1 -0
  124. package/dist/instrumentation/__tests__/bedrock-trace-comparison.test.js +422 -0
  125. package/dist/instrumentation/__tests__/bedrock-trace-comparison.test.js.map +1 -0
  126. package/dist/instrumentation/__tests__/browser-use-wrapper.test.d.ts +1 -0
  127. package/dist/instrumentation/__tests__/browser-use-wrapper.test.js +284 -0
  128. package/dist/instrumentation/__tests__/browser-use-wrapper.test.js.map +1 -0
  129. package/dist/instrumentation/__tests__/cache-pricing.test.d.ts +15 -0
  130. package/dist/instrumentation/__tests__/cache-pricing.test.js +155 -0
  131. package/dist/instrumentation/__tests__/cache-pricing.test.js.map +1 -0
  132. package/dist/instrumentation/__tests__/chroma-trace-comparison.test.d.ts +18 -0
  133. package/dist/instrumentation/__tests__/chroma-trace-comparison.test.js +209 -0
  134. package/dist/instrumentation/__tests__/chroma-trace-comparison.test.js.map +1 -0
  135. package/dist/instrumentation/__tests__/cohere-wrapper.test.d.ts +1 -0
  136. package/dist/instrumentation/__tests__/cohere-wrapper.test.js +256 -0
  137. package/dist/instrumentation/__tests__/cohere-wrapper.test.js.map +1 -0
  138. package/dist/instrumentation/__tests__/elevenlabs-wrapper.test.d.ts +1 -0
  139. package/dist/instrumentation/__tests__/elevenlabs-wrapper.test.js +282 -0
  140. package/dist/instrumentation/__tests__/elevenlabs-wrapper.test.js.map +1 -0
  141. package/dist/instrumentation/__tests__/firecrawl-wrapper.test.d.ts +1 -0
  142. package/dist/instrumentation/__tests__/firecrawl-wrapper.test.js +238 -0
  143. package/dist/instrumentation/__tests__/firecrawl-wrapper.test.js.map +1 -0
  144. package/dist/instrumentation/__tests__/google-ai-trace-comparison.test.d.ts +4 -0
  145. package/dist/instrumentation/__tests__/google-ai-trace-comparison.test.js +229 -0
  146. package/dist/instrumentation/__tests__/google-ai-trace-comparison.test.js.map +1 -0
  147. package/dist/instrumentation/__tests__/gpu-collector.test.d.ts +1 -0
  148. package/dist/instrumentation/__tests__/gpu-collector.test.js +247 -0
  149. package/dist/instrumentation/__tests__/gpu-collector.test.js.map +1 -0
  150. package/dist/instrumentation/__tests__/gradient-trace-comparison.test.d.ts +11 -0
  151. package/dist/instrumentation/__tests__/gradient-trace-comparison.test.js +391 -0
  152. package/dist/instrumentation/__tests__/gradient-trace-comparison.test.js.map +1 -0
  153. package/dist/instrumentation/__tests__/groq-trace-comparison.test.d.ts +7 -0
  154. package/dist/instrumentation/__tests__/groq-trace-comparison.test.js +687 -0
  155. package/dist/instrumentation/__tests__/groq-trace-comparison.test.js.map +1 -0
  156. package/dist/instrumentation/__tests__/helpers-genai.test.d.ts +14 -0
  157. package/dist/instrumentation/__tests__/helpers-genai.test.js +347 -0
  158. package/dist/instrumentation/__tests__/helpers-genai.test.js.map +1 -0
  159. package/dist/instrumentation/__tests__/huggingface-trace-comparison.test.d.ts +7 -0
  160. package/dist/instrumentation/__tests__/huggingface-trace-comparison.test.js +529 -0
  161. package/dist/instrumentation/__tests__/huggingface-trace-comparison.test.js.map +1 -0
  162. package/dist/instrumentation/__tests__/langchain-role-map.test.d.ts +1 -0
  163. package/dist/instrumentation/__tests__/langchain-role-map.test.js +19 -0
  164. package/dist/instrumentation/__tests__/langchain-role-map.test.js.map +1 -0
  165. package/dist/instrumentation/__tests__/langchain-wrapper.test.d.ts +1 -0
  166. package/dist/instrumentation/__tests__/langchain-wrapper.test.js +282 -0
  167. package/dist/instrumentation/__tests__/langchain-wrapper.test.js.map +1 -0
  168. package/dist/instrumentation/__tests__/letta-wrapper.test.d.ts +1 -0
  169. package/dist/instrumentation/__tests__/letta-wrapper.test.js +285 -0
  170. package/dist/instrumentation/__tests__/letta-wrapper.test.js.map +1 -0
  171. package/dist/instrumentation/__tests__/mem0-trace-comparison.test.d.ts +13 -0
  172. package/dist/instrumentation/__tests__/mem0-trace-comparison.test.js +208 -0
  173. package/dist/instrumentation/__tests__/mem0-trace-comparison.test.js.map +1 -0
  174. package/dist/instrumentation/__tests__/milvus-trace-comparison.test.d.ts +17 -0
  175. package/dist/instrumentation/__tests__/milvus-trace-comparison.test.js +206 -0
  176. package/dist/instrumentation/__tests__/milvus-trace-comparison.test.js.map +1 -0
  177. package/dist/instrumentation/__tests__/mistral-trace-comparison.test.d.ts +1 -0
  178. package/dist/instrumentation/__tests__/mistral-trace-comparison.test.js +345 -0
  179. package/dist/instrumentation/__tests__/mistral-trace-comparison.test.js.map +1 -0
  180. package/dist/instrumentation/__tests__/openai-wrapper.test.d.ts +1 -0
  181. package/dist/instrumentation/__tests__/openai-wrapper.test.js +179 -0
  182. package/dist/instrumentation/__tests__/openai-wrapper.test.js.map +1 -0
  183. package/dist/instrumentation/__tests__/pg-trace-comparison.test.d.ts +21 -0
  184. package/dist/instrumentation/__tests__/pg-trace-comparison.test.js +455 -0
  185. package/dist/instrumentation/__tests__/pg-trace-comparison.test.js.map +1 -0
  186. package/dist/instrumentation/__tests__/qdrant-trace-comparison.test.d.ts +17 -0
  187. package/dist/instrumentation/__tests__/qdrant-trace-comparison.test.js +182 -0
  188. package/dist/instrumentation/__tests__/qdrant-trace-comparison.test.js.map +1 -0
  189. package/dist/instrumentation/__tests__/replicate-trace-comparison.test.d.ts +8 -0
  190. package/dist/instrumentation/__tests__/replicate-trace-comparison.test.js +346 -0
  191. package/dist/instrumentation/__tests__/replicate-trace-comparison.test.js.map +1 -0
  192. package/dist/instrumentation/__tests__/together-trace-comparison.test.d.ts +4 -0
  193. package/dist/instrumentation/__tests__/together-trace-comparison.test.js +289 -0
  194. package/dist/instrumentation/__tests__/together-trace-comparison.test.js.map +1 -0
  195. package/dist/instrumentation/__tests__/trace-comparison-utils.d.ts +67 -0
  196. package/dist/instrumentation/__tests__/trace-comparison-utils.js +255 -0
  197. package/dist/instrumentation/__tests__/trace-comparison-utils.js.map +1 -0
  198. package/dist/instrumentation/__tests__/transformers-trace-comparison.test.d.ts +11 -0
  199. package/dist/instrumentation/__tests__/transformers-trace-comparison.test.js +214 -0
  200. package/dist/instrumentation/__tests__/transformers-trace-comparison.test.js.map +1 -0
  201. package/dist/instrumentation/__tests__/vercel-ai-trace-comparison.test.d.ts +8 -0
  202. package/dist/instrumentation/__tests__/vercel-ai-trace-comparison.test.js +446 -0
  203. package/dist/instrumentation/__tests__/vercel-ai-trace-comparison.test.js.map +1 -0
  204. package/dist/instrumentation/__tests__/vertexai-trace-comparison.test.d.ts +6 -0
  205. package/dist/instrumentation/__tests__/vertexai-trace-comparison.test.js +409 -0
  206. package/dist/instrumentation/__tests__/vertexai-trace-comparison.test.js.map +1 -0
  207. package/dist/instrumentation/__tests__/vllm-trace-comparison.test.d.ts +1 -0
  208. package/dist/instrumentation/__tests__/vllm-trace-comparison.test.js +519 -0
  209. package/dist/instrumentation/__tests__/vllm-trace-comparison.test.js.map +1 -0
  210. package/dist/instrumentation/ai21/index.d.ts +11 -0
  211. package/dist/instrumentation/ai21/index.js +67 -0
  212. package/dist/instrumentation/ai21/index.js.map +1 -0
  213. package/dist/instrumentation/ai21/wrapper.d.ts +54 -0
  214. package/dist/instrumentation/ai21/wrapper.js +511 -0
  215. package/dist/instrumentation/ai21/wrapper.js.map +1 -0
  216. package/dist/instrumentation/anthropic/index.d.ts +11 -0
  217. package/dist/instrumentation/anthropic/index.js +45 -0
  218. package/dist/instrumentation/anthropic/index.js.map +1 -0
  219. package/dist/instrumentation/anthropic/wrapper.d.ts +34 -0
  220. package/dist/instrumentation/anthropic/wrapper.js +426 -0
  221. package/dist/instrumentation/anthropic/wrapper.js.map +1 -0
  222. package/dist/instrumentation/assemblyai/index.d.ts +12 -0
  223. package/dist/instrumentation/assemblyai/index.js +91 -0
  224. package/dist/instrumentation/assemblyai/index.js.map +1 -0
  225. package/dist/instrumentation/assemblyai/wrapper.d.ts +35 -0
  226. package/dist/instrumentation/assemblyai/wrapper.js +238 -0
  227. package/dist/instrumentation/assemblyai/wrapper.js.map +1 -0
  228. package/dist/instrumentation/astra/index.d.ts +11 -0
  229. package/dist/instrumentation/astra/index.js +87 -0
  230. package/dist/instrumentation/astra/index.js.map +1 -0
  231. package/dist/instrumentation/astra/wrapper.d.ts +39 -0
  232. package/dist/instrumentation/astra/wrapper.js +349 -0
  233. package/dist/instrumentation/astra/wrapper.js.map +1 -0
  234. package/dist/instrumentation/azure-ai-inference/index.d.ts +11 -0
  235. package/dist/instrumentation/azure-ai-inference/index.js +76 -0
  236. package/dist/instrumentation/azure-ai-inference/index.js.map +1 -0
  237. package/dist/instrumentation/azure-ai-inference/wrapper.d.ts +55 -0
  238. package/dist/instrumentation/azure-ai-inference/wrapper.js +580 -0
  239. package/dist/instrumentation/azure-ai-inference/wrapper.js.map +1 -0
  240. package/dist/instrumentation/base-wrapper.d.ts +16 -0
  241. package/dist/instrumentation/base-wrapper.js +139 -0
  242. package/dist/instrumentation/base-wrapper.js.map +1 -0
  243. package/dist/instrumentation/bedrock/index.d.ts +11 -0
  244. package/dist/instrumentation/bedrock/index.js +52 -0
  245. package/dist/instrumentation/bedrock/index.js.map +1 -0
  246. package/dist/instrumentation/bedrock/wrapper.d.ts +41 -0
  247. package/dist/instrumentation/bedrock/wrapper.js +494 -0
  248. package/dist/instrumentation/bedrock/wrapper.js.map +1 -0
  249. package/dist/instrumentation/browser-use/index.d.ts +11 -0
  250. package/dist/instrumentation/browser-use/index.js +98 -0
  251. package/dist/instrumentation/browser-use/index.js.map +1 -0
  252. package/dist/instrumentation/browser-use/wrapper.d.ts +12 -0
  253. package/dist/instrumentation/browser-use/wrapper.js +706 -0
  254. package/dist/instrumentation/browser-use/wrapper.js.map +1 -0
  255. package/dist/instrumentation/chroma/index.d.ts +11 -0
  256. package/dist/instrumentation/chroma/index.js +70 -0
  257. package/dist/instrumentation/chroma/index.js.map +1 -0
  258. package/dist/instrumentation/chroma/wrapper.d.ts +10 -0
  259. package/dist/instrumentation/chroma/wrapper.js +127 -0
  260. package/dist/instrumentation/chroma/wrapper.js.map +1 -0
  261. package/dist/instrumentation/claude-agent-sdk/index.d.ts +23 -0
  262. package/dist/instrumentation/claude-agent-sdk/index.js +83 -0
  263. package/dist/instrumentation/claude-agent-sdk/index.js.map +1 -0
  264. package/dist/instrumentation/claude-agent-sdk/wrapper.d.ts +13 -0
  265. package/dist/instrumentation/claude-agent-sdk/wrapper.js +1123 -0
  266. package/dist/instrumentation/claude-agent-sdk/wrapper.js.map +1 -0
  267. package/dist/instrumentation/cohere/index.d.ts +11 -0
  268. package/dist/instrumentation/cohere/index.js +53 -0
  269. package/dist/instrumentation/cohere/index.js.map +1 -0
  270. package/dist/instrumentation/cohere/wrapper.d.ts +50 -0
  271. package/dist/instrumentation/cohere/wrapper.js +452 -0
  272. package/dist/instrumentation/cohere/wrapper.js.map +1 -0
  273. package/dist/instrumentation/cursor-sdk/index.d.ts +21 -0
  274. package/dist/instrumentation/cursor-sdk/index.js +58 -0
  275. package/dist/instrumentation/cursor-sdk/index.js.map +1 -0
  276. package/dist/instrumentation/cursor-sdk/wrapper.d.ts +17 -0
  277. package/dist/instrumentation/cursor-sdk/wrapper.js +789 -0
  278. package/dist/instrumentation/cursor-sdk/wrapper.js.map +1 -0
  279. package/dist/instrumentation/elevenlabs/index.d.ts +12 -0
  280. package/dist/instrumentation/elevenlabs/index.js +92 -0
  281. package/dist/instrumentation/elevenlabs/index.js.map +1 -0
  282. package/dist/instrumentation/elevenlabs/wrapper.d.ts +34 -0
  283. package/dist/instrumentation/elevenlabs/wrapper.js +280 -0
  284. package/dist/instrumentation/elevenlabs/wrapper.js.map +1 -0
  285. package/dist/instrumentation/firecrawl/index.d.ts +13 -0
  286. package/dist/instrumentation/firecrawl/index.js +115 -0
  287. package/dist/instrumentation/firecrawl/index.js.map +1 -0
  288. package/dist/instrumentation/firecrawl/wrapper.d.ts +22 -0
  289. package/dist/instrumentation/firecrawl/wrapper.js +378 -0
  290. package/dist/instrumentation/firecrawl/wrapper.js.map +1 -0
  291. package/dist/instrumentation/google-adk/index.d.ts +57 -0
  292. package/dist/instrumentation/google-adk/index.js +371 -0
  293. package/dist/instrumentation/google-adk/index.js.map +1 -0
  294. package/dist/instrumentation/google-adk/utils.d.ts +45 -0
  295. package/dist/instrumentation/google-adk/utils.js +663 -0
  296. package/dist/instrumentation/google-adk/utils.js.map +1 -0
  297. package/dist/instrumentation/google-adk/wrapper.d.ts +11 -0
  298. package/dist/instrumentation/google-adk/wrapper.js +391 -0
  299. package/dist/instrumentation/google-adk/wrapper.js.map +1 -0
  300. package/dist/instrumentation/google-ai/index.d.ts +11 -0
  301. package/dist/instrumentation/google-ai/index.js +48 -0
  302. package/dist/instrumentation/google-ai/index.js.map +1 -0
  303. package/dist/instrumentation/google-ai/wrapper.d.ts +52 -0
  304. package/dist/instrumentation/google-ai/wrapper.js +466 -0
  305. package/dist/instrumentation/google-ai/wrapper.js.map +1 -0
  306. package/dist/instrumentation/gpu/index.d.ts +38 -0
  307. package/dist/instrumentation/gpu/index.js +233 -0
  308. package/dist/instrumentation/gpu/index.js.map +1 -0
  309. package/dist/instrumentation/gradient/index.d.ts +12 -0
  310. package/dist/instrumentation/gradient/index.js +74 -0
  311. package/dist/instrumentation/gradient/index.js.map +1 -0
  312. package/dist/instrumentation/gradient/utils.d.ts +14 -0
  313. package/dist/instrumentation/gradient/utils.js +119 -0
  314. package/dist/instrumentation/gradient/utils.js.map +1 -0
  315. package/dist/instrumentation/gradient/wrapper.d.ts +76 -0
  316. package/dist/instrumentation/gradient/wrapper.js +584 -0
  317. package/dist/instrumentation/gradient/wrapper.js.map +1 -0
  318. package/dist/instrumentation/groq/index.d.ts +11 -0
  319. package/dist/instrumentation/groq/index.js +43 -0
  320. package/dist/instrumentation/groq/index.js.map +1 -0
  321. package/dist/instrumentation/groq/wrapper.d.ts +35 -0
  322. package/dist/instrumentation/groq/wrapper.js +442 -0
  323. package/dist/instrumentation/groq/wrapper.js.map +1 -0
  324. package/dist/instrumentation/huggingface/index.d.ts +13 -0
  325. package/dist/instrumentation/huggingface/index.js +110 -0
  326. package/dist/instrumentation/huggingface/index.js.map +1 -0
  327. package/dist/instrumentation/huggingface/wrapper.d.ts +54 -0
  328. package/dist/instrumentation/huggingface/wrapper.js +514 -0
  329. package/dist/instrumentation/huggingface/wrapper.js.map +1 -0
  330. package/dist/instrumentation/index.d.ts +7 -0
  331. package/dist/instrumentation/index.js +176 -0
  332. package/dist/instrumentation/index.js.map +1 -0
  333. package/dist/instrumentation/langchain/index.d.ts +16 -0
  334. package/dist/instrumentation/langchain/index.js +91 -0
  335. package/dist/instrumentation/langchain/index.js.map +1 -0
  336. package/dist/instrumentation/langchain/wrapper.d.ts +41 -0
  337. package/dist/instrumentation/langchain/wrapper.js +1235 -0
  338. package/dist/instrumentation/langchain/wrapper.js.map +1 -0
  339. package/dist/instrumentation/langgraph/index.d.ts +12 -0
  340. package/dist/instrumentation/langgraph/index.js +99 -0
  341. package/dist/instrumentation/langgraph/index.js.map +1 -0
  342. package/dist/instrumentation/langgraph/wrapper.d.ts +20 -0
  343. package/dist/instrumentation/langgraph/wrapper.js +620 -0
  344. package/dist/instrumentation/langgraph/wrapper.js.map +1 -0
  345. package/dist/instrumentation/letta/index.d.ts +10 -0
  346. package/dist/instrumentation/letta/index.js +122 -0
  347. package/dist/instrumentation/letta/index.js.map +1 -0
  348. package/dist/instrumentation/letta/utils.d.ts +24 -0
  349. package/dist/instrumentation/letta/utils.js +343 -0
  350. package/dist/instrumentation/letta/utils.js.map +1 -0
  351. package/dist/instrumentation/letta/wrapper.d.ts +37 -0
  352. package/dist/instrumentation/letta/wrapper.js +180 -0
  353. package/dist/instrumentation/letta/wrapper.js.map +1 -0
  354. package/dist/instrumentation/llamaindex/index.d.ts +36 -0
  355. package/dist/instrumentation/llamaindex/index.js +221 -0
  356. package/dist/instrumentation/llamaindex/index.js.map +1 -0
  357. package/dist/instrumentation/llamaindex/wrapper.d.ts +36 -0
  358. package/dist/instrumentation/llamaindex/wrapper.js +811 -0
  359. package/dist/instrumentation/llamaindex/wrapper.js.map +1 -0
  360. package/dist/instrumentation/mcp/index.d.ts +20 -0
  361. package/dist/instrumentation/mcp/index.js +282 -0
  362. package/dist/instrumentation/mcp/index.js.map +1 -0
  363. package/dist/instrumentation/mcp/wrapper.d.ts +72 -0
  364. package/dist/instrumentation/mcp/wrapper.js +571 -0
  365. package/dist/instrumentation/mcp/wrapper.js.map +1 -0
  366. package/dist/instrumentation/mem0/index.d.ts +17 -0
  367. package/dist/instrumentation/mem0/index.js +113 -0
  368. package/dist/instrumentation/mem0/index.js.map +1 -0
  369. package/dist/instrumentation/mem0/wrapper.d.ts +37 -0
  370. package/dist/instrumentation/mem0/wrapper.js +298 -0
  371. package/dist/instrumentation/mem0/wrapper.js.map +1 -0
  372. package/dist/instrumentation/milvus/index.d.ts +11 -0
  373. package/dist/instrumentation/milvus/index.js +67 -0
  374. package/dist/instrumentation/milvus/index.js.map +1 -0
  375. package/dist/instrumentation/milvus/wrapper.d.ts +15 -0
  376. package/dist/instrumentation/milvus/wrapper.js +219 -0
  377. package/dist/instrumentation/milvus/wrapper.js.map +1 -0
  378. package/dist/instrumentation/mistral/index.d.ts +11 -0
  379. package/dist/instrumentation/mistral/index.js +66 -0
  380. package/dist/instrumentation/mistral/index.js.map +1 -0
  381. package/dist/instrumentation/mistral/wrapper.d.ts +49 -0
  382. package/dist/instrumentation/mistral/wrapper.js +482 -0
  383. package/dist/instrumentation/mistral/wrapper.js.map +1 -0
  384. package/dist/instrumentation/ollama/index.d.ts +11 -0
  385. package/dist/instrumentation/ollama/index.js +72 -0
  386. package/dist/instrumentation/ollama/index.js.map +1 -0
  387. package/dist/instrumentation/ollama/wrapper.d.ts +73 -0
  388. package/dist/instrumentation/ollama/wrapper.js +629 -0
  389. package/dist/instrumentation/ollama/wrapper.js.map +1 -0
  390. package/dist/instrumentation/openai/index.d.ts +11 -0
  391. package/dist/instrumentation/openai/index.js +79 -0
  392. package/dist/instrumentation/openai/index.js.map +1 -0
  393. package/dist/instrumentation/openai/wrapper.d.ts +80 -0
  394. package/dist/instrumentation/openai/wrapper.js +1121 -0
  395. package/dist/instrumentation/openai/wrapper.js.map +1 -0
  396. package/dist/instrumentation/openai-agents/index.d.ts +20 -0
  397. package/dist/instrumentation/openai-agents/index.js +174 -0
  398. package/dist/instrumentation/openai-agents/index.js.map +1 -0
  399. package/dist/instrumentation/openai-agents/processor.d.ts +35 -0
  400. package/dist/instrumentation/openai-agents/processor.js +249 -0
  401. package/dist/instrumentation/openai-agents/processor.js.map +1 -0
  402. package/dist/instrumentation/openai-agents/utils.d.ts +20 -0
  403. package/dist/instrumentation/openai-agents/utils.js +624 -0
  404. package/dist/instrumentation/openai-agents/utils.js.map +1 -0
  405. package/dist/instrumentation/pg/index.d.ts +20 -0
  406. package/dist/instrumentation/pg/index.js +74 -0
  407. package/dist/instrumentation/pg/index.js.map +1 -0
  408. package/dist/instrumentation/pg/wrapper.d.ts +66 -0
  409. package/dist/instrumentation/pg/wrapper.js +441 -0
  410. package/dist/instrumentation/pg/wrapper.js.map +1 -0
  411. package/dist/instrumentation/pinecone/index.d.ts +11 -0
  412. package/dist/instrumentation/pinecone/index.js +79 -0
  413. package/dist/instrumentation/pinecone/index.js.map +1 -0
  414. package/dist/instrumentation/pinecone/wrapper.d.ts +14 -0
  415. package/dist/instrumentation/pinecone/wrapper.js +198 -0
  416. package/dist/instrumentation/pinecone/wrapper.js.map +1 -0
  417. package/dist/instrumentation/qdrant/index.d.ts +11 -0
  418. package/dist/instrumentation/qdrant/index.js +67 -0
  419. package/dist/instrumentation/qdrant/index.js.map +1 -0
  420. package/dist/instrumentation/qdrant/wrapper.d.ts +14 -0
  421. package/dist/instrumentation/qdrant/wrapper.js +213 -0
  422. package/dist/instrumentation/qdrant/wrapper.js.map +1 -0
  423. package/dist/instrumentation/replicate/index.d.ts +11 -0
  424. package/dist/instrumentation/replicate/index.js +57 -0
  425. package/dist/instrumentation/replicate/index.js.map +1 -0
  426. package/dist/instrumentation/replicate/wrapper.d.ts +28 -0
  427. package/dist/instrumentation/replicate/wrapper.js +242 -0
  428. package/dist/instrumentation/replicate/wrapper.js.map +1 -0
  429. package/dist/instrumentation/strands/index.d.ts +21 -0
  430. package/dist/instrumentation/strands/index.js +83 -0
  431. package/dist/instrumentation/strands/index.js.map +1 -0
  432. package/dist/instrumentation/strands/processor.d.ts +51 -0
  433. package/dist/instrumentation/strands/processor.js +625 -0
  434. package/dist/instrumentation/strands/processor.js.map +1 -0
  435. package/dist/instrumentation/strands/utils.d.ts +24 -0
  436. package/dist/instrumentation/strands/utils.js +373 -0
  437. package/dist/instrumentation/strands/utils.js.map +1 -0
  438. package/dist/instrumentation/together/index.d.ts +11 -0
  439. package/dist/instrumentation/together/index.js +43 -0
  440. package/dist/instrumentation/together/index.js.map +1 -0
  441. package/dist/instrumentation/together/wrapper.d.ts +48 -0
  442. package/dist/instrumentation/together/wrapper.js +409 -0
  443. package/dist/instrumentation/together/wrapper.js.map +1 -0
  444. package/dist/instrumentation/transformers/index.d.ts +35 -0
  445. package/dist/instrumentation/transformers/index.js +119 -0
  446. package/dist/instrumentation/transformers/index.js.map +1 -0
  447. package/dist/instrumentation/transformers/wrapper.d.ts +49 -0
  448. package/dist/instrumentation/transformers/wrapper.js +472 -0
  449. package/dist/instrumentation/transformers/wrapper.js.map +1 -0
  450. package/dist/instrumentation/vercel-ai/index.d.ts +10 -0
  451. package/dist/instrumentation/vercel-ai/index.js +59 -0
  452. package/dist/instrumentation/vercel-ai/index.js.map +1 -0
  453. package/dist/instrumentation/vercel-ai/wrapper.d.ts +50 -0
  454. package/dist/instrumentation/vercel-ai/wrapper.js +539 -0
  455. package/dist/instrumentation/vercel-ai/wrapper.js.map +1 -0
  456. package/dist/instrumentation/vertexai/index.d.ts +11 -0
  457. package/dist/instrumentation/vertexai/index.js +70 -0
  458. package/dist/instrumentation/vertexai/index.js.map +1 -0
  459. package/dist/instrumentation/vertexai/wrapper.d.ts +67 -0
  460. package/dist/instrumentation/vertexai/wrapper.js +530 -0
  461. package/dist/instrumentation/vertexai/wrapper.js.map +1 -0
  462. package/dist/instrumentation/vllm/index.d.ts +13 -0
  463. package/dist/instrumentation/vllm/index.js +67 -0
  464. package/dist/instrumentation/vllm/index.js.map +1 -0
  465. package/dist/instrumentation/vllm/wrapper.d.ts +60 -0
  466. package/dist/instrumentation/vllm/wrapper.js +482 -0
  467. package/dist/instrumentation/vllm/wrapper.js.map +1 -0
  468. package/dist/llm/anthropic.d.ts +5 -0
  469. package/dist/llm/anthropic.js +39 -0
  470. package/dist/llm/anthropic.js.map +1 -0
  471. package/dist/llm/index.d.ts +10 -0
  472. package/dist/llm/index.js +93 -0
  473. package/dist/llm/index.js.map +1 -0
  474. package/dist/llm/openai.d.ts +6 -0
  475. package/dist/llm/openai.js +52 -0
  476. package/dist/llm/openai.js.map +1 -0
  477. package/dist/llm/providers.d.ts +7 -0
  478. package/dist/llm/providers.js +10 -0
  479. package/dist/llm/providers.js.map +1 -0
  480. package/dist/manual-trace.d.ts +40 -0
  481. package/dist/manual-trace.js +103 -0
  482. package/dist/manual-trace.js.map +1 -0
  483. package/dist/otel/__tests__/metrics.test.d.ts +1 -0
  484. package/dist/otel/__tests__/metrics.test.js +40 -0
  485. package/dist/otel/__tests__/metrics.test.js.map +1 -0
  486. package/dist/otel/events.d.ts +11 -0
  487. package/dist/otel/events.js +74 -0
  488. package/dist/otel/events.js.map +1 -0
  489. package/dist/otel/metrics.d.ts +35 -0
  490. package/dist/otel/metrics.js +219 -0
  491. package/dist/otel/metrics.js.map +1 -0
  492. package/dist/otel/tracing.d.ts +12 -0
  493. package/dist/otel/tracing.js +93 -0
  494. package/dist/otel/tracing.js.map +1 -0
  495. package/dist/otel/utils.d.ts +11 -0
  496. package/dist/otel/utils.js +34 -0
  497. package/dist/otel/utils.js.map +1 -0
  498. package/dist/pricing.json +951 -0
  499. package/dist/prompt-hub.d.ts +4 -0
  500. package/dist/prompt-hub.js +66 -0
  501. package/dist/prompt-hub.js.map +1 -0
  502. package/dist/register.d.ts +4 -0
  503. package/dist/register.js +52 -0
  504. package/dist/register.js.map +1 -0
  505. package/dist/score/__tests__/score.test.d.ts +1 -0
  506. package/dist/score/__tests__/score.test.js +143 -0
  507. package/dist/score/__tests__/score.test.js.map +1 -0
  508. package/dist/score/index.d.ts +2 -0
  509. package/dist/score/index.js +6 -0
  510. package/dist/score/index.js.map +1 -0
  511. package/dist/score/score.d.ts +15 -0
  512. package/dist/score/score.js +135 -0
  513. package/dist/score/score.js.map +1 -0
  514. package/dist/semantic-convention.d.ts +555 -0
  515. package/dist/semantic-convention.js +630 -0
  516. package/dist/semantic-convention.js.map +1 -0
  517. package/dist/types.d.ts +131 -0
  518. package/dist/types.js +3 -0
  519. package/dist/types.js.map +1 -0
  520. package/package.json +136 -0
@@ -0,0 +1,1123 @@
1
+ "use strict";
2
+ /**
3
+ * Claude Agent SDK wrapper — OTel GenAI semantic convention compliant.
4
+ *
5
+ * Wraps the `query()` async generator to produce `invoke_agent`, `execute_tool`,
6
+ * and `chat` child spans. Tool spans are created via SDK hooks (PreToolUse /
7
+ * PostToolUse / PostToolUseFailure). A message-based fallback handles cases
8
+ * where hooks cannot be injected.
9
+ *
10
+ * Mirrors the Python SDK instrumentation in
11
+ * sdk/python/src/shield360/instrumentation/claude_agent_sdk/.
12
+ */
13
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
14
+ if (k2 === undefined) k2 = k;
15
+ var desc = Object.getOwnPropertyDescriptor(m, k);
16
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
17
+ desc = { enumerable: true, get: function() { return m[k]; } };
18
+ }
19
+ Object.defineProperty(o, k2, desc);
20
+ }) : (function(o, m, k, k2) {
21
+ if (k2 === undefined) k2 = k;
22
+ o[k2] = m[k];
23
+ }));
24
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
25
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
26
+ }) : function(o, v) {
27
+ o["default"] = v;
28
+ });
29
+ var __importStar = (this && this.__importStar) || (function () {
30
+ var ownKeys = function(o) {
31
+ ownKeys = Object.getOwnPropertyNames || function (o) {
32
+ var ar = [];
33
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
34
+ return ar;
35
+ };
36
+ return ownKeys(o);
37
+ };
38
+ return function (mod) {
39
+ if (mod && mod.__esModule) return mod;
40
+ var result = {};
41
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
42
+ __setModuleDefault(result, mod);
43
+ return result;
44
+ };
45
+ })();
46
+ var __importDefault = (this && this.__importDefault) || function (mod) {
47
+ return (mod && mod.__esModule) ? mod : { "default": mod };
48
+ };
49
+ Object.defineProperty(exports, "__esModule", { value: true });
50
+ exports.patchQuery = patchQuery;
51
+ const api_1 = require("@opentelemetry/api");
52
+ const semantic_conventions_1 = require("@opentelemetry/semantic-conventions");
53
+ const semantic_convention_1 = __importDefault(require("../../semantic-convention"));
54
+ const config_1 = __importDefault(require("../../config"));
55
+ const helpers_1 = __importStar(require("../../helpers"));
56
+ const constant_1 = require("../../constant");
57
+ const metrics_1 = __importDefault(require("../../otel/metrics"));
58
+ // ---------------------------------------------------------------------------
59
+ // Constants
60
+ // ---------------------------------------------------------------------------
61
+ const [SERVER_ADDRESS, SERVER_PORT] = (0, helpers_1.getServerAddressForProvider)('anthropic');
62
+ const GEN_AI_SYSTEM_ATTR = 'gen_ai.system';
63
+ const GEN_AI_SYSTEM_VALUE = 'anthropic';
64
+ const ANTHROPIC_FINISH_REASON_MAP = {
65
+ end_turn: 'stop',
66
+ max_tokens: 'length',
67
+ stop_sequence: 'stop',
68
+ tool_use: 'tool_call',
69
+ };
70
+ const OPERATION_MAP = {
71
+ query: semantic_convention_1.default.GEN_AI_OPERATION_TYPE_AGENT,
72
+ execute_tool: semantic_convention_1.default.GEN_AI_OPERATION_TYPE_TOOLS,
73
+ subagent: semantic_convention_1.default.GEN_AI_OPERATION_TYPE_AGENT,
74
+ chat: semantic_convention_1.default.GEN_AI_OPERATION_TYPE_CHAT,
75
+ create_agent: semantic_convention_1.default.GEN_AI_OPERATION_TYPE_CREATE_AGENT,
76
+ };
77
+ // ---------------------------------------------------------------------------
78
+ // Helpers
79
+ // ---------------------------------------------------------------------------
80
+ function truncateContent(content) {
81
+ const maxLen = config_1.default.maxContentLength;
82
+ if (maxLen != null && maxLen > 0 && content.length > maxLen) {
83
+ return content.slice(0, maxLen);
84
+ }
85
+ return content;
86
+ }
87
+ function mapFinishReason(rawReason) {
88
+ if (!rawReason)
89
+ return 'stop';
90
+ return ANTHROPIC_FINISH_REASON_MAP[rawReason] || rawReason;
91
+ }
92
+ function resolveAgentName(options) {
93
+ if (!options)
94
+ return null;
95
+ for (const key of ['agent_name', 'agentName', 'name']) {
96
+ const val = options[key];
97
+ if (val && typeof val === 'string' && val.trim())
98
+ return val.trim();
99
+ }
100
+ return null;
101
+ }
102
+ function generateSpanName(endpoint, entityName) {
103
+ const operation = OPERATION_MAP[endpoint] || semantic_convention_1.default.GEN_AI_OPERATION_TYPE_AGENT;
104
+ if (entityName)
105
+ return `${operation} ${entityName}`;
106
+ return operation;
107
+ }
108
+ /**
109
+ * Stamp `shield360.agent.version_hash` (auto) and `gen_ai.agent.version`
110
+ * (user override, if set) on the span and return the same attributes so
111
+ * the caller can merge them into the inference event extras.
112
+ */
113
+ function stampAgentVersion(span, args) {
114
+ const out = {};
115
+ try {
116
+ const versionHash = helpers_1.default.computeAgentVersionHash({
117
+ systemInstructions: args.systemInstructionsJson ?? null,
118
+ toolDefinitions: args.toolDefinitionsJson ?? null,
119
+ primaryModel: args.primaryModel ?? null,
120
+ runtimeConfig: {
121
+ temperature: args.temperature ?? null,
122
+ top_p: args.top_p ?? null,
123
+ max_tokens: args.max_tokens ?? null,
124
+ provider: semantic_convention_1.default.GEN_AI_SYSTEM_CLAUDE_AGENT_SDK,
125
+ },
126
+ providers: [semantic_convention_1.default.GEN_AI_SYSTEM_CLAUDE_AGENT_SDK],
127
+ });
128
+ if (versionHash) {
129
+ out[semantic_convention_1.default.SHIELD360_AGENT_VERSION_HASH] = versionHash;
130
+ span.setAttribute(semantic_convention_1.default.SHIELD360_AGENT_VERSION_HASH, versionHash);
131
+ }
132
+ }
133
+ catch {
134
+ // Hash computation must never fail the wrapped call.
135
+ }
136
+ const versionLabel = (0, helpers_1.getCurrentAgentVersion)();
137
+ if (versionLabel) {
138
+ out[semantic_convention_1.default.GEN_AI_AGENT_VERSION] = versionLabel;
139
+ span.setAttribute(semantic_convention_1.default.GEN_AI_AGENT_VERSION, versionLabel);
140
+ }
141
+ return out;
142
+ }
143
+ function extractUsage(usage) {
144
+ const attrs = {};
145
+ if (!usage)
146
+ return attrs;
147
+ const rawInput = parseInt(usage.input_tokens, 10) || 0;
148
+ const outputTokens = parseInt(usage.output_tokens, 10);
149
+ if (!isNaN(outputTokens)) {
150
+ attrs[semantic_convention_1.default.GEN_AI_USAGE_OUTPUT_TOKENS] = outputTokens;
151
+ }
152
+ let cacheReadInt = 0;
153
+ const cacheRead = usage.cache_read_input_tokens;
154
+ if (cacheRead != null) {
155
+ cacheReadInt = parseInt(cacheRead, 10) || 0;
156
+ if (cacheReadInt) {
157
+ attrs[semantic_convention_1.default.GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS] = cacheReadInt;
158
+ }
159
+ }
160
+ let cacheCreationInt = 0;
161
+ const cacheCreation = usage.cache_creation_input_tokens ?? usage.cache_write_input_tokens;
162
+ if (cacheCreation != null) {
163
+ cacheCreationInt = parseInt(cacheCreation, 10) || 0;
164
+ if (cacheCreationInt) {
165
+ attrs[semantic_convention_1.default.GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS] = cacheCreationInt;
166
+ }
167
+ }
168
+ attrs[semantic_convention_1.default.GEN_AI_USAGE_INPUT_TOKENS] = rawInput + cacheReadInt + cacheCreationInt;
169
+ return attrs;
170
+ }
171
+ // ---------------------------------------------------------------------------
172
+ // ToolSpanTracker — manages in-flight tool spans created by SDK hooks
173
+ // ---------------------------------------------------------------------------
174
+ class ToolSpanTracker {
175
+ constructor(tracer, parentSpan, captureContent) {
176
+ this._inFlight = new Map();
177
+ this._completed = new Set();
178
+ this._tracer = tracer;
179
+ this._parentSpan = parentSpan;
180
+ this._captureContent = captureContent;
181
+ }
182
+ startTool(toolName, toolInput, toolUseId) {
183
+ const spanName = generateSpanName('execute_tool', toolName);
184
+ const parentCtx = api_1.trace.setSpan(api_1.context.active(), this._parentSpan);
185
+ const span = this._tracer.startSpan(spanName, {
186
+ kind: api_1.SpanKind.INTERNAL,
187
+ attributes: {
188
+ [semantic_convention_1.default.GEN_AI_OPERATION]: semantic_convention_1.default.GEN_AI_OPERATION_TYPE_TOOLS,
189
+ [semantic_convention_1.default.GEN_AI_PROVIDER_NAME_OTEL]: semantic_convention_1.default.GEN_AI_SYSTEM_CLAUDE_AGENT_SDK,
190
+ },
191
+ }, parentCtx);
192
+ setToolSpanAttributes(span, toolName, toolInput, toolUseId, this._captureContent);
193
+ this._inFlight.set(toolUseId, span);
194
+ }
195
+ endTool(toolUseId, toolResponse) {
196
+ const span = this._inFlight.get(toolUseId);
197
+ if (!span)
198
+ return;
199
+ this._inFlight.delete(toolUseId);
200
+ finalizeToolSpan(span, toolResponse, this._captureContent);
201
+ span.end();
202
+ this._completed.add(toolUseId);
203
+ }
204
+ endToolError(toolUseId, error) {
205
+ const span = this._inFlight.get(toolUseId);
206
+ if (!span)
207
+ return;
208
+ this._inFlight.delete(toolUseId);
209
+ finalizeToolSpan(span, null, this._captureContent, true, error);
210
+ span.end();
211
+ this._completed.add(toolUseId);
212
+ }
213
+ endAll() {
214
+ for (const [_toolUseId, span] of this._inFlight) {
215
+ finalizeToolSpan(span, null, this._captureContent, true, 'abandoned');
216
+ span.end();
217
+ }
218
+ this._inFlight.clear();
219
+ }
220
+ }
221
+ // ---------------------------------------------------------------------------
222
+ // SubagentSpanTracker — manages subagent spans for Task tool
223
+ // ---------------------------------------------------------------------------
224
+ class SubagentSpanTracker {
225
+ constructor(tracer, toolTracker) {
226
+ this._inFlight = new Map();
227
+ this._toolUseToTask = new Map();
228
+ this._tracer = tracer;
229
+ this._toolTracker = toolTracker;
230
+ }
231
+ startSubagent(taskId, description, toolUseId) {
232
+ const name = description || taskId || 'subagent';
233
+ const spanName = generateSpanName('subagent', name);
234
+ if (toolUseId) {
235
+ this._toolUseToTask.set(toolUseId, taskId);
236
+ }
237
+ let parentSpan;
238
+ if (toolUseId) {
239
+ parentSpan = this._toolTracker._inFlight.get(toolUseId);
240
+ }
241
+ const ctx = parentSpan ? api_1.trace.setSpan(api_1.context.active(), parentSpan) : undefined;
242
+ const span = this._tracer.startSpan(spanName, {
243
+ kind: api_1.SpanKind.INTERNAL,
244
+ attributes: {
245
+ [semantic_convention_1.default.GEN_AI_OPERATION]: semantic_convention_1.default.GEN_AI_OPERATION_TYPE_AGENT,
246
+ [semantic_convention_1.default.GEN_AI_PROVIDER_NAME_OTEL]: semantic_convention_1.default.GEN_AI_SYSTEM_CLAUDE_AGENT_SDK,
247
+ },
248
+ }, ctx);
249
+ span.setAttribute(GEN_AI_SYSTEM_ATTR, GEN_AI_SYSTEM_VALUE);
250
+ span.setAttribute(semantic_convention_1.default.GEN_AI_AGENT_NAME, String(name));
251
+ span.setAttribute(semantic_convention_1.default.ATTR_DEPLOYMENT_ENVIRONMENT, config_1.default.environment ?? 'default');
252
+ span.setAttribute(semantic_conventions_1.ATTR_SERVICE_NAME, config_1.default.applicationName ?? 'default');
253
+ span.setAttribute(semantic_convention_1.default.GEN_AI_SDK_VERSION, constant_1.SDK_VERSION);
254
+ this._inFlight.set(taskId, span);
255
+ }
256
+ endSubagent(taskId, isError = false, errorMessage, usage) {
257
+ const span = this._inFlight.get(taskId);
258
+ if (!span)
259
+ return;
260
+ this._inFlight.delete(taskId);
261
+ if (usage) {
262
+ if (usage.total_tokens != null) {
263
+ span.setAttribute(semantic_convention_1.default.GEN_AI_USAGE_INPUT_TOKENS, Number(usage.total_tokens) || 0);
264
+ }
265
+ if (usage.tool_uses != null) {
266
+ span.setAttribute('gen_ai.agent.tool_uses', Number(usage.tool_uses) || 0);
267
+ }
268
+ if (usage.duration_ms != null) {
269
+ span.setAttribute('gen_ai.agent.duration_ms', Number(usage.duration_ms) || 0);
270
+ }
271
+ }
272
+ if (isError) {
273
+ const err = errorMessage ? String(errorMessage) : 'task failed';
274
+ span.setAttribute(semantic_convention_1.default.ERROR_TYPE, 'SubagentError');
275
+ span.setStatus({ code: api_1.SpanStatusCode.ERROR, message: err });
276
+ }
277
+ else {
278
+ span.setStatus({ code: api_1.SpanStatusCode.OK });
279
+ }
280
+ span.end();
281
+ }
282
+ getSpanForToolUseId(toolUseId) {
283
+ const taskId = this._toolUseToTask.get(toolUseId);
284
+ return taskId ? this._inFlight.get(taskId) : undefined;
285
+ }
286
+ endAll() {
287
+ for (const taskId of this._inFlight.keys()) {
288
+ this.endSubagent(taskId, true, 'abandoned');
289
+ }
290
+ }
291
+ }
292
+ // ---------------------------------------------------------------------------
293
+ // Tool span attributes
294
+ // ---------------------------------------------------------------------------
295
+ function setToolSpanAttributes(span, toolName, toolInput, toolUseId, captureContent) {
296
+ span.setAttribute(GEN_AI_SYSTEM_ATTR, GEN_AI_SYSTEM_VALUE);
297
+ span.setAttribute(semantic_convention_1.default.GEN_AI_TOOL_NAME, String(toolName));
298
+ const toolType = String(toolName).startsWith('mcp__') ? 'extension' : 'function';
299
+ span.setAttribute(semantic_convention_1.default.GEN_AI_TOOL_TYPE, toolType);
300
+ if (toolUseId) {
301
+ span.setAttribute(semantic_convention_1.default.GEN_AI_TOOL_CALL_ID, String(toolUseId));
302
+ }
303
+ span.setAttribute(semantic_convention_1.default.SERVER_ADDRESS, SERVER_ADDRESS);
304
+ span.setAttribute(semantic_convention_1.default.SERVER_PORT, SERVER_PORT);
305
+ span.setAttribute(semantic_convention_1.default.ATTR_DEPLOYMENT_ENVIRONMENT, config_1.default.environment ?? 'default');
306
+ span.setAttribute(semantic_conventions_1.ATTR_SERVICE_NAME, config_1.default.applicationName ?? 'default');
307
+ span.setAttribute(semantic_convention_1.default.GEN_AI_SDK_VERSION, constant_1.SDK_VERSION);
308
+ if (captureContent && toolInput != null) {
309
+ try {
310
+ const argsStr = typeof toolInput === 'string' ? toolInput : JSON.stringify(toolInput);
311
+ span.setAttribute(semantic_convention_1.default.GEN_AI_TOOL_CALL_ARGUMENTS, truncateContent(argsStr));
312
+ }
313
+ catch { /* ignore */ }
314
+ }
315
+ (0, helpers_1.applyCustomSpanAttributes)(span);
316
+ }
317
+ function finalizeToolSpan(span, toolResponse, captureContent, isError = false, errorMessage) {
318
+ if (isError) {
319
+ const errMsg = errorMessage ? String(errorMessage) : 'tool execution failed';
320
+ span.setAttribute(semantic_convention_1.default.ERROR_TYPE, 'ToolExecutionError');
321
+ span.setStatus({ code: api_1.SpanStatusCode.ERROR, message: errMsg });
322
+ }
323
+ else {
324
+ if (captureContent && toolResponse != null) {
325
+ span.setAttribute(semantic_convention_1.default.GEN_AI_TOOL_CALL_RESULT, truncateContent(String(toolResponse)));
326
+ }
327
+ span.setStatus({ code: api_1.SpanStatusCode.OK });
328
+ }
329
+ }
330
+ // ---------------------------------------------------------------------------
331
+ // Hook injection — merges Shield360 hooks into user-provided options
332
+ // ---------------------------------------------------------------------------
333
+ function injectHooks(options, toolTracker, subagentTracker) {
334
+ if (!options.hooks) {
335
+ options.hooks = {};
336
+ }
337
+ const preToolUse = async (input, toolUseId) => {
338
+ try {
339
+ const toolName = input.tool_name || 'unknown';
340
+ const toolInput = input.tool_input;
341
+ const id = toolUseId || input.tool_use_id;
342
+ if (id)
343
+ toolTracker.startTool(toolName, toolInput, id);
344
+ }
345
+ catch { /* swallow */ }
346
+ return {};
347
+ };
348
+ const postToolUse = async (input, toolUseId) => {
349
+ try {
350
+ const toolResponse = input.tool_response;
351
+ const id = toolUseId || input.tool_use_id;
352
+ if (id)
353
+ toolTracker.endTool(id, toolResponse);
354
+ }
355
+ catch { /* swallow */ }
356
+ return {};
357
+ };
358
+ const postToolUseFailure = async (input, toolUseId) => {
359
+ try {
360
+ const error = input.error || 'unknown error';
361
+ const id = toolUseId || input.tool_use_id;
362
+ if (id)
363
+ toolTracker.endToolError(id, error);
364
+ }
365
+ catch { /* swallow */ }
366
+ return {};
367
+ };
368
+ const subagentStart = async (input, toolUseId) => {
369
+ try {
370
+ const agentId = input.agent_id;
371
+ if (agentId) {
372
+ const description = input.description || agentId;
373
+ subagentTracker.startSubagent(agentId, description, toolUseId ?? undefined);
374
+ }
375
+ }
376
+ catch { /* swallow */ }
377
+ return {};
378
+ };
379
+ const subagentStop = async (input) => {
380
+ try {
381
+ const agentId = input.agent_id;
382
+ if (!agentId)
383
+ return {};
384
+ const error = input.error;
385
+ subagentTracker.endSubagent(agentId, !!error, error);
386
+ }
387
+ catch { /* swallow */ }
388
+ return {};
389
+ };
390
+ const hookPairs = [
391
+ ['PreToolUse', preToolUse],
392
+ ['PostToolUse', postToolUse],
393
+ ['PostToolUseFailure', postToolUseFailure],
394
+ ['SubagentStart', subagentStart],
395
+ ['SubagentStop', subagentStop],
396
+ ];
397
+ for (const [event, callback] of hookPairs) {
398
+ const matcher = { hooks: [callback] };
399
+ if (options.hooks[event]) {
400
+ options.hooks[event].push(matcher);
401
+ }
402
+ else {
403
+ options.hooks[event] = [matcher];
404
+ }
405
+ }
406
+ }
407
+ function hasLlmCallData(msg) {
408
+ return msg.message?.model != null && msg.message?.usage != null;
409
+ }
410
+ function bufferChatMessage(sdkMsg, chatState) {
411
+ if (!hasLlmCallData(sdkMsg))
412
+ return;
413
+ chatState.pendingChatMsg = sdkMsg;
414
+ chatState.pendingChatMsgId = sdkMsg.message?.id;
415
+ chatState.pendingStartMs = chatState.lastBoundaryMs;
416
+ chatState.pendingEndMs = Date.now();
417
+ }
418
+ function flushPendingChat(tracer, parentSpan, chatState, captureContent, subagentTracker) {
419
+ const sdkMsg = chatState.pendingChatMsg;
420
+ if (!sdkMsg)
421
+ return;
422
+ delete chatState.pendingChatMsg;
423
+ delete chatState.pendingChatMsgId;
424
+ const endMs = chatState.pendingEndMs ?? Date.now();
425
+ const savedStartMs = chatState.pendingStartMs;
426
+ delete chatState.pendingStartMs;
427
+ delete chatState.pendingEndMs;
428
+ const betaMessage = sdkMsg.message;
429
+ const model = String(betaMessage?.model || 'unknown');
430
+ const spanName = generateSpanName('chat', model);
431
+ let effectiveParent = parentSpan;
432
+ const parentToolUseId = sdkMsg.parent_tool_use_id;
433
+ if (parentToolUseId) {
434
+ const subagentSpan = subagentTracker.getSpanForToolUseId(parentToolUseId);
435
+ if (subagentSpan)
436
+ effectiveParent = subagentSpan;
437
+ }
438
+ const parentCtx = api_1.trace.setSpan(api_1.context.active(), effectiveParent);
439
+ const startMs = savedStartMs ?? chatState.lastBoundaryMs ?? endMs;
440
+ const chatSpan = tracer.startSpan(spanName, {
441
+ kind: api_1.SpanKind.CLIENT,
442
+ attributes: {
443
+ [semantic_convention_1.default.GEN_AI_OPERATION]: semantic_convention_1.default.GEN_AI_OPERATION_TYPE_CHAT,
444
+ [semantic_convention_1.default.GEN_AI_PROVIDER_NAME_OTEL]: semantic_convention_1.default.GEN_AI_SYSTEM_ANTHROPIC,
445
+ },
446
+ startTime: new Date(startMs),
447
+ }, parentCtx);
448
+ const inputMessages = chatState.pendingInput;
449
+ delete chatState.pendingInput;
450
+ setChatSpanAttributes(chatSpan, sdkMsg, captureContent, inputMessages, chatState.systemInstructionsJson, chatState.toolDefinitionsJson);
451
+ chatSpan.end(new Date(endMs));
452
+ chatState.lastBoundaryMs = endMs;
453
+ }
454
+ // ---------------------------------------------------------------------------
455
+ // Chat span attributes
456
+ // ---------------------------------------------------------------------------
457
+ function setChatSpanAttributes(span, sdkMsg, captureContent, inputMessages, systemInstructionsJson, toolDefinitionsJson) {
458
+ try {
459
+ const betaMessage = sdkMsg.message;
460
+ const model = betaMessage?.model ? String(betaMessage.model) : null;
461
+ span.setAttribute(GEN_AI_SYSTEM_ATTR, GEN_AI_SYSTEM_VALUE);
462
+ span.setAttribute(semantic_convention_1.default.SERVER_ADDRESS, SERVER_ADDRESS);
463
+ span.setAttribute(semantic_convention_1.default.SERVER_PORT, SERVER_PORT);
464
+ span.setAttribute(semantic_conventions_1.ATTR_TELEMETRY_SDK_NAME, constant_1.SDK_NAME);
465
+ span.setAttribute(semantic_convention_1.default.ATTR_DEPLOYMENT_ENVIRONMENT, config_1.default.environment ?? 'default');
466
+ span.setAttribute(semantic_conventions_1.ATTR_SERVICE_NAME, config_1.default.applicationName ?? 'default');
467
+ span.setAttribute(semantic_convention_1.default.GEN_AI_SDK_VERSION, constant_1.SDK_VERSION);
468
+ if (model) {
469
+ span.setAttribute(semantic_convention_1.default.GEN_AI_REQUEST_MODEL, model);
470
+ span.setAttribute(semantic_convention_1.default.GEN_AI_RESPONSE_MODEL, model);
471
+ }
472
+ const usage = betaMessage?.usage;
473
+ const usageAttrs = usage ? extractUsage(usage) : {};
474
+ for (const [key, value] of Object.entries(usageAttrs)) {
475
+ span.setAttribute(key, value);
476
+ }
477
+ let stopReason = betaMessage?.stop_reason;
478
+ if (!stopReason) {
479
+ const content = betaMessage?.content;
480
+ if (Array.isArray(content)) {
481
+ for (const block of content) {
482
+ if (block.type === 'tool_use') {
483
+ stopReason = 'tool_use';
484
+ break;
485
+ }
486
+ }
487
+ }
488
+ }
489
+ const mappedReason = mapFinishReason(stopReason);
490
+ span.setAttribute(semantic_convention_1.default.GEN_AI_RESPONSE_FINISH_REASON, [mappedReason]);
491
+ const messageId = betaMessage?.id;
492
+ if (messageId) {
493
+ span.setAttribute(semantic_convention_1.default.GEN_AI_RESPONSE_ID, String(messageId));
494
+ }
495
+ const sessionId = sdkMsg.session_id;
496
+ if (sessionId) {
497
+ span.setAttribute(semantic_convention_1.default.GEN_AI_CONVERSATION_ID, String(sessionId));
498
+ }
499
+ const inputTokens = usageAttrs[semantic_convention_1.default.GEN_AI_USAGE_INPUT_TOKENS] ?? 0;
500
+ const outputTokens = usageAttrs[semantic_convention_1.default.GEN_AI_USAGE_OUTPUT_TOKENS] ?? 0;
501
+ // extractUsage builds an inclusive input total (uncached + cache-read +
502
+ // cache-creation), so re-price cache tokens with promptTokensIncludeCache.
503
+ const cacheReadTokens = usageAttrs[semantic_convention_1.default.GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS] ?? 0;
504
+ const cacheCreationTokens = usageAttrs[semantic_convention_1.default.GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS] ?? 0;
505
+ const pricingInfo = config_1.default.pricingInfo || {};
506
+ const cost = model
507
+ ? helpers_1.default.getChatModelCost(model, pricingInfo, inputTokens, outputTokens, cacheReadTokens, cacheCreationTokens, true)
508
+ : 0;
509
+ span.setAttribute(semantic_convention_1.default.GEN_AI_USAGE_COST, cost);
510
+ let outputMessages = null;
511
+ if (captureContent) {
512
+ if (inputMessages) {
513
+ span.setAttribute(semantic_convention_1.default.GEN_AI_INPUT_MESSAGES, JSON.stringify(inputMessages));
514
+ }
515
+ outputMessages = buildOutputMessages(betaMessage, mappedReason);
516
+ if (outputMessages) {
517
+ span.setAttribute(semantic_convention_1.default.GEN_AI_OUTPUT_MESSAGES, JSON.stringify(outputMessages));
518
+ }
519
+ }
520
+ const versionExtras = stampAgentVersion(span, {
521
+ systemInstructionsJson,
522
+ toolDefinitionsJson,
523
+ primaryModel: model ?? undefined,
524
+ temperature: null,
525
+ top_p: null,
526
+ max_tokens: null,
527
+ });
528
+ (0, helpers_1.applyCustomSpanAttributes)(span);
529
+ span.setStatus({ code: api_1.SpanStatusCode.OK });
530
+ if (captureContent) {
531
+ emitChatInferenceEvent(span, model, messageId, sessionId, mappedReason, usageAttrs, inputMessages, outputMessages, versionExtras);
532
+ }
533
+ if (!config_1.default.disableMetrics) {
534
+ recordChatMetrics(model, inputTokens, outputTokens, cost);
535
+ }
536
+ }
537
+ catch { /* swallow */ }
538
+ }
539
+ // ---------------------------------------------------------------------------
540
+ // Build OTel-compliant output messages from BetaMessage content blocks
541
+ // ---------------------------------------------------------------------------
542
+ function buildOutputMessages(betaMessage, mappedFinishReason) {
543
+ try {
544
+ const content = betaMessage?.content;
545
+ if (!content || !Array.isArray(content))
546
+ return null;
547
+ const parts = [];
548
+ for (const block of content) {
549
+ if (block.type === 'text') {
550
+ if (block.text) {
551
+ parts.push({ type: 'text', content: truncateContent(String(block.text)) });
552
+ }
553
+ }
554
+ else if (block.type === 'thinking') {
555
+ if (block.thinking) {
556
+ parts.push({ type: 'reasoning', content: truncateContent(String(block.thinking)) });
557
+ }
558
+ }
559
+ else if (block.type === 'tool_use') {
560
+ let toolInput = block.input || {};
561
+ if (typeof toolInput !== 'object') {
562
+ try {
563
+ toolInput = JSON.parse(String(toolInput));
564
+ }
565
+ catch {
566
+ toolInput = {};
567
+ }
568
+ }
569
+ parts.push({
570
+ type: 'tool_call',
571
+ id: String(block.id || ''),
572
+ name: String(block.name || 'unknown'),
573
+ arguments: toolInput,
574
+ });
575
+ }
576
+ }
577
+ if (parts.length === 0)
578
+ return null;
579
+ return [{ role: 'assistant', parts, finish_reason: mappedFinishReason }];
580
+ }
581
+ catch {
582
+ return null;
583
+ }
584
+ }
585
+ // ---------------------------------------------------------------------------
586
+ // Build OTel input from UserMessage tool results
587
+ // ---------------------------------------------------------------------------
588
+ function buildInputFromToolResults(sdkMsg) {
589
+ try {
590
+ const messageParam = sdkMsg.message;
591
+ const content = messageParam?.content;
592
+ if (!content || !Array.isArray(content))
593
+ return null;
594
+ const parts = [];
595
+ for (const block of content) {
596
+ if (block.type === 'tool_result') {
597
+ const toolUseId = block.tool_use_id;
598
+ let resultContent = block.content;
599
+ if (Array.isArray(resultContent)) {
600
+ resultContent = resultContent.map((c) => c.text || JSON.stringify(c)).join('');
601
+ }
602
+ parts.push({
603
+ type: 'tool_call_response',
604
+ id: toolUseId ? String(toolUseId) : '',
605
+ response: resultContent ? truncateContent(String(resultContent)) : '',
606
+ });
607
+ }
608
+ }
609
+ if (parts.length === 0)
610
+ return null;
611
+ return [{ role: 'user', parts }];
612
+ }
613
+ catch {
614
+ return null;
615
+ }
616
+ }
617
+ // ---------------------------------------------------------------------------
618
+ // Emit gen_ai.client.inference.operation.details event for chat spans
619
+ // ---------------------------------------------------------------------------
620
+ function emitChatInferenceEvent(span, model, messageId, sessionId, mappedReason, usageAttrs, inputMessages, outputMessages, versionExtras) {
621
+ if (config_1.default.disableEvents)
622
+ return;
623
+ try {
624
+ const attributes = {
625
+ [semantic_convention_1.default.GEN_AI_OPERATION]: semantic_convention_1.default.GEN_AI_OPERATION_TYPE_CHAT,
626
+ [semantic_convention_1.default.SERVER_ADDRESS]: SERVER_ADDRESS,
627
+ [semantic_convention_1.default.SERVER_PORT]: SERVER_PORT,
628
+ };
629
+ if (model) {
630
+ attributes[semantic_convention_1.default.GEN_AI_REQUEST_MODEL] = model;
631
+ attributes[semantic_convention_1.default.GEN_AI_RESPONSE_MODEL] = model;
632
+ }
633
+ if (messageId) {
634
+ attributes[semantic_convention_1.default.GEN_AI_RESPONSE_ID] = String(messageId);
635
+ }
636
+ if (sessionId) {
637
+ attributes[semantic_convention_1.default.GEN_AI_CONVERSATION_ID] = String(sessionId);
638
+ }
639
+ if (mappedReason) {
640
+ attributes[semantic_convention_1.default.GEN_AI_RESPONSE_FINISH_REASON] = [mappedReason];
641
+ }
642
+ for (const [key, value] of Object.entries(usageAttrs)) {
643
+ attributes[key] = value;
644
+ }
645
+ if (inputMessages != null) {
646
+ attributes[semantic_convention_1.default.GEN_AI_INPUT_MESSAGES] = inputMessages;
647
+ }
648
+ if (outputMessages != null) {
649
+ attributes[semantic_convention_1.default.GEN_AI_OUTPUT_MESSAGES] = outputMessages;
650
+ }
651
+ if (versionExtras) {
652
+ Object.assign(attributes, versionExtras);
653
+ }
654
+ helpers_1.default.emitInferenceEvent(span, attributes);
655
+ }
656
+ catch { /* swallow */ }
657
+ }
658
+ // ---------------------------------------------------------------------------
659
+ // Chat metrics
660
+ // ---------------------------------------------------------------------------
661
+ function recordChatMetrics(model, inputTokens, outputTokens, cost) {
662
+ try {
663
+ const attributes = {
664
+ [semantic_conventions_1.ATTR_TELEMETRY_SDK_NAME]: constant_1.SDK_NAME,
665
+ [semantic_conventions_1.ATTR_SERVICE_NAME]: config_1.default.applicationName ?? 'default',
666
+ [semantic_convention_1.default.ATTR_DEPLOYMENT_ENVIRONMENT]: config_1.default.environment ?? 'default',
667
+ [semantic_convention_1.default.GEN_AI_PROVIDER_NAME_OTEL]: semantic_convention_1.default.GEN_AI_SYSTEM_ANTHROPIC,
668
+ [semantic_convention_1.default.GEN_AI_OPERATION]: semantic_convention_1.default.GEN_AI_OPERATION_TYPE_CHAT,
669
+ [semantic_convention_1.default.SERVER_ADDRESS]: SERVER_ADDRESS,
670
+ [semantic_convention_1.default.SERVER_PORT]: SERVER_PORT,
671
+ };
672
+ if (model) {
673
+ attributes[semantic_convention_1.default.GEN_AI_REQUEST_MODEL] = model;
674
+ }
675
+ if (inputTokens && metrics_1.default.genaiClientUsageTokens) {
676
+ metrics_1.default.genaiClientUsageTokens.record(inputTokens, {
677
+ ...attributes,
678
+ [semantic_convention_1.default.GEN_AI_TOKEN_TYPE]: semantic_convention_1.default.GEN_AI_TOKEN_TYPE_INPUT,
679
+ });
680
+ }
681
+ if (outputTokens && metrics_1.default.genaiClientUsageTokens) {
682
+ metrics_1.default.genaiClientUsageTokens.record(outputTokens, {
683
+ ...attributes,
684
+ [semantic_convention_1.default.GEN_AI_TOKEN_TYPE]: semantic_convention_1.default.GEN_AI_TOKEN_TYPE_OUTPUT,
685
+ });
686
+ }
687
+ if (cost && metrics_1.default.genaiCost) {
688
+ metrics_1.default.genaiCost.record(cost, attributes);
689
+ }
690
+ }
691
+ catch { /* swallow */ }
692
+ }
693
+ // ---------------------------------------------------------------------------
694
+ // Process result message — finalize root span with usage/cost data
695
+ // ---------------------------------------------------------------------------
696
+ function processResultMessage(span, sdkMsg, captureContent) {
697
+ const resultUsage = { inputTokens: 0, outputTokens: 0 };
698
+ try {
699
+ const sessionId = sdkMsg.session_id;
700
+ if (sessionId) {
701
+ span.setAttribute(semantic_convention_1.default.GEN_AI_CONVERSATION_ID, String(sessionId));
702
+ }
703
+ const usage = sdkMsg.usage;
704
+ if (usage) {
705
+ const usageAttrs = extractUsage(usage);
706
+ for (const [key, value] of Object.entries(usageAttrs)) {
707
+ span.setAttribute(key, value);
708
+ }
709
+ resultUsage.inputTokens = usageAttrs[semantic_convention_1.default.GEN_AI_USAGE_INPUT_TOKENS] ?? 0;
710
+ resultUsage.outputTokens = usageAttrs[semantic_convention_1.default.GEN_AI_USAGE_OUTPUT_TOKENS] ?? 0;
711
+ }
712
+ const totalCost = sdkMsg.total_cost_usd;
713
+ if (totalCost != null) {
714
+ span.setAttribute(semantic_convention_1.default.GEN_AI_USAGE_COST, Number(totalCost) || 0);
715
+ }
716
+ const modelUsage = sdkMsg.modelUsage;
717
+ if (modelUsage && typeof modelUsage === 'object') {
718
+ const modelNames = Object.keys(modelUsage);
719
+ if (modelNames.length > 0) {
720
+ span.setAttribute(semantic_convention_1.default.GEN_AI_RESPONSE_MODEL, String(modelNames[0]));
721
+ }
722
+ }
723
+ if (sdkMsg.num_turns != null) {
724
+ span.setAttribute('gen_ai.agent.num_turns', Number(sdkMsg.num_turns) || 0);
725
+ }
726
+ if (sdkMsg.duration_ms != null) {
727
+ span.setAttribute('gen_ai.agent.duration_ms', Number(sdkMsg.duration_ms) || 0);
728
+ }
729
+ if (sdkMsg.duration_api_ms != null) {
730
+ span.setAttribute('gen_ai.agent.duration_api_ms', Number(sdkMsg.duration_api_ms) || 0);
731
+ }
732
+ if (sdkMsg.is_error) {
733
+ const errResult = sdkMsg.errors?.join('; ') || sdkMsg.result || 'unknown error';
734
+ span.setAttribute(semantic_convention_1.default.ERROR_TYPE, 'AgentError');
735
+ span.setStatus({ code: api_1.SpanStatusCode.ERROR, message: String(errResult) });
736
+ }
737
+ else {
738
+ span.setStatus({ code: api_1.SpanStatusCode.OK });
739
+ }
740
+ if (captureContent) {
741
+ const result = sdkMsg.result;
742
+ if (result) {
743
+ span.setAttribute(semantic_convention_1.default.GEN_AI_OUTPUT_MESSAGES, JSON.stringify([{
744
+ role: 'assistant',
745
+ parts: [{ type: 'text', content: truncateContent(String(result)) }],
746
+ }]));
747
+ }
748
+ }
749
+ }
750
+ catch { /* swallow */ }
751
+ return resultUsage;
752
+ }
753
+ // ---------------------------------------------------------------------------
754
+ // Message stream processor
755
+ // ---------------------------------------------------------------------------
756
+ function processMessage(sdkMsg, span, toolTracker, subagentTracker, captureContent, tracer, chatState) {
757
+ const msgType = sdkMsg.type;
758
+ let resultUsage = null;
759
+ if (msgType === 'assistant') {
760
+ updateRootFromAssistant(span, sdkMsg);
761
+ if (hasLlmCallData(sdkMsg)) {
762
+ const newMsgId = sdkMsg.message?.id;
763
+ const pendingMsgId = chatState.pendingChatMsgId;
764
+ if (pendingMsgId != null && newMsgId !== pendingMsgId) {
765
+ flushPendingChat(tracer, span, chatState, captureContent, subagentTracker);
766
+ }
767
+ bufferChatMessage(sdkMsg, chatState);
768
+ }
769
+ }
770
+ else if (msgType === 'user') {
771
+ flushPendingChat(tracer, span, chatState, captureContent, subagentTracker);
772
+ if (captureContent) {
773
+ const toolInput = buildInputFromToolResults(sdkMsg);
774
+ if (toolInput) {
775
+ chatState.pendingInput = toolInput;
776
+ }
777
+ }
778
+ }
779
+ else if (msgType === 'result') {
780
+ flushPendingChat(tracer, span, chatState, captureContent, subagentTracker);
781
+ resultUsage = processResultMessage(span, sdkMsg, captureContent);
782
+ }
783
+ else if (msgType === 'system' && sdkMsg.subtype === 'task_started') {
784
+ flushPendingChat(tracer, span, chatState, captureContent, subagentTracker);
785
+ try {
786
+ const taskId = sdkMsg.task_id;
787
+ const description = sdkMsg.description;
788
+ const toolUseId = sdkMsg.tool_use_id;
789
+ if (taskId) {
790
+ subagentTracker.startSubagent(taskId, description, toolUseId);
791
+ }
792
+ }
793
+ catch { /* swallow */ }
794
+ }
795
+ else if (msgType === 'system' && sdkMsg.subtype === 'task_notification') {
796
+ flushPendingChat(tracer, span, chatState, captureContent, subagentTracker);
797
+ try {
798
+ const taskId = sdkMsg.task_id;
799
+ const status = sdkMsg.status;
800
+ const isError = status === 'failed' || status === 'stopped';
801
+ const errorMsg = isError ? sdkMsg.summary : null;
802
+ const taskUsage = sdkMsg.usage;
803
+ if (taskId) {
804
+ subagentTracker.endSubagent(taskId, isError, errorMsg, taskUsage);
805
+ }
806
+ }
807
+ catch { /* swallow */ }
808
+ }
809
+ chatState.lastBoundaryMs = Date.now();
810
+ return resultUsage;
811
+ }
812
+ function updateRootFromAssistant(span, sdkMsg) {
813
+ try {
814
+ const model = sdkMsg.message?.model;
815
+ if (model) {
816
+ span.setAttribute(semantic_convention_1.default.GEN_AI_REQUEST_MODEL, String(model));
817
+ span.setAttribute(semantic_convention_1.default.GEN_AI_RESPONSE_MODEL, String(model));
818
+ }
819
+ const sessionId = sdkMsg.session_id;
820
+ if (sessionId) {
821
+ span.setAttribute(semantic_convention_1.default.GEN_AI_CONVERSATION_ID, String(sessionId));
822
+ }
823
+ }
824
+ catch { /* swallow */ }
825
+ }
826
+ // ---------------------------------------------------------------------------
827
+ // Message-based tool span fallback (when hooks don't fire)
828
+ // ---------------------------------------------------------------------------
829
+ function processToolBlocksFromMessages(sdkMsg, toolTracker, subagentTracker) {
830
+ const msgType = sdkMsg.type;
831
+ if (msgType === 'assistant') {
832
+ const content = sdkMsg.message?.content;
833
+ if (!content || !Array.isArray(content))
834
+ return;
835
+ const parentToolUseId = sdkMsg.parent_tool_use_id;
836
+ let effectiveParent;
837
+ if (parentToolUseId) {
838
+ effectiveParent = subagentTracker.getSpanForToolUseId(parentToolUseId);
839
+ }
840
+ for (const block of content) {
841
+ if (block.type === 'tool_use') {
842
+ const toolName = block.name || 'unknown';
843
+ const toolInput = block.input;
844
+ const toolId = block.id;
845
+ if (toolId && !toolTracker._inFlight.has(toolId) && !toolTracker._completed.has(toolId)) {
846
+ if (effectiveParent) {
847
+ const spanName = generateSpanName('execute_tool', toolName);
848
+ const parentCtx = api_1.trace.setSpan(api_1.context.active(), effectiveParent);
849
+ const span = toolTracker['_tracer'].startSpan(spanName, {
850
+ kind: api_1.SpanKind.INTERNAL,
851
+ attributes: {
852
+ [semantic_convention_1.default.GEN_AI_OPERATION]: semantic_convention_1.default.GEN_AI_OPERATION_TYPE_TOOLS,
853
+ [semantic_convention_1.default.GEN_AI_PROVIDER_NAME_OTEL]: semantic_convention_1.default.GEN_AI_SYSTEM_CLAUDE_AGENT_SDK,
854
+ },
855
+ }, parentCtx);
856
+ setToolSpanAttributes(span, toolName, toolInput, toolId, config_1.default.captureMessageContent ?? true);
857
+ toolTracker._inFlight.set(toolId, span);
858
+ }
859
+ else {
860
+ toolTracker.startTool(toolName, toolInput, toolId);
861
+ }
862
+ }
863
+ }
864
+ }
865
+ }
866
+ else if (msgType === 'user') {
867
+ const content = sdkMsg.message?.content;
868
+ if (!content || !Array.isArray(content))
869
+ return;
870
+ for (const block of content) {
871
+ if (block.type === 'tool_result') {
872
+ const toolUseId = block.tool_use_id;
873
+ const isError = block.is_error;
874
+ const resultContent = block.content;
875
+ if (toolUseId && toolTracker._inFlight.has(toolUseId)) {
876
+ if (isError) {
877
+ toolTracker.endToolError(toolUseId, resultContent);
878
+ }
879
+ else {
880
+ toolTracker.endTool(toolUseId, resultContent);
881
+ }
882
+ }
883
+ }
884
+ }
885
+ }
886
+ }
887
+ // ---------------------------------------------------------------------------
888
+ // Set initial span attributes on the root invoke_agent span
889
+ // ---------------------------------------------------------------------------
890
+ function setInitialSpanAttributes(span, options, prompt, captureContent) {
891
+ try {
892
+ span.setAttribute(semantic_convention_1.default.GEN_AI_OPERATION, semantic_convention_1.default.GEN_AI_OPERATION_TYPE_AGENT);
893
+ span.setAttribute(semantic_convention_1.default.GEN_AI_PROVIDER_NAME_OTEL, semantic_convention_1.default.GEN_AI_SYSTEM_CLAUDE_AGENT_SDK);
894
+ span.setAttribute(GEN_AI_SYSTEM_ATTR, GEN_AI_SYSTEM_VALUE);
895
+ span.setAttribute(semantic_conventions_1.ATTR_TELEMETRY_SDK_NAME, constant_1.SDK_NAME);
896
+ span.setAttribute(semantic_convention_1.default.ATTR_DEPLOYMENT_ENVIRONMENT, config_1.default.environment ?? 'default');
897
+ span.setAttribute(semantic_conventions_1.ATTR_SERVICE_NAME, config_1.default.applicationName ?? 'default');
898
+ span.setAttribute(semantic_convention_1.default.GEN_AI_SDK_VERSION, constant_1.SDK_VERSION);
899
+ span.setAttribute(semantic_convention_1.default.SERVER_ADDRESS, SERVER_ADDRESS);
900
+ span.setAttribute(semantic_convention_1.default.SERVER_PORT, SERVER_PORT);
901
+ const agentName = resolveAgentName(options);
902
+ if (agentName) {
903
+ span.setAttribute(semantic_convention_1.default.GEN_AI_AGENT_NAME, agentName);
904
+ }
905
+ const model = options?.model;
906
+ if (model) {
907
+ span.setAttribute(semantic_convention_1.default.GEN_AI_REQUEST_MODEL, String(model));
908
+ }
909
+ if (captureContent) {
910
+ const systemPrompt = options?.systemPrompt;
911
+ if (systemPrompt && typeof systemPrompt === 'string') {
912
+ span.setAttribute(semantic_convention_1.default.GEN_AI_SYSTEM_INSTRUCTIONS, JSON.stringify([{ type: 'text', content: truncateContent(systemPrompt) }]));
913
+ }
914
+ if (prompt && typeof prompt === 'string') {
915
+ span.setAttribute(semantic_convention_1.default.GEN_AI_INPUT_MESSAGES, JSON.stringify([{
916
+ role: 'user',
917
+ parts: [{ type: 'text', content: truncateContent(prompt) }],
918
+ }]));
919
+ }
920
+ }
921
+ // gen_ai.tool.definitions — surface tool schemas declared on the agent's
922
+ // `options.tools`. Supports both the OpenAI/Anthropic-style array shape
923
+ // (handled directly by buildToolDefinitions) and the Claude Agent SDK's
924
+ // MCP-style object map of `{ name: { description, input_schema } }`.
925
+ const optionTools = options?.tools;
926
+ let normalizedTools = optionTools;
927
+ if (optionTools && !Array.isArray(optionTools) && typeof optionTools === 'object') {
928
+ normalizedTools = Object.entries(optionTools).map(([name, def]) => ({
929
+ name,
930
+ description: def?.description ?? '',
931
+ parameters: def?.parameters ?? def?.input_schema ?? def?.inputSchema ?? {},
932
+ }));
933
+ }
934
+ const toolDefinitionsJson = helpers_1.default.buildToolDefinitions(normalizedTools);
935
+ if (toolDefinitionsJson) {
936
+ span.setAttribute(semantic_convention_1.default.GEN_AI_TOOL_DEFINITIONS, toolDefinitionsJson);
937
+ }
938
+ (0, helpers_1.applyCustomSpanAttributes)(span);
939
+ }
940
+ catch { /* swallow */ }
941
+ }
942
+ // ---------------------------------------------------------------------------
943
+ // Finalize root span — record duration and token usage metrics
944
+ // ---------------------------------------------------------------------------
945
+ function finalizeSpan(span, startTime, inputTokens, outputTokens) {
946
+ try {
947
+ const duration = (Date.now() / 1000) - startTime;
948
+ span.setAttribute(semantic_convention_1.default.GEN_AI_CLIENT_OPERATION_DURATION, duration);
949
+ if (!config_1.default.disableMetrics) {
950
+ const attributes = {
951
+ [semantic_conventions_1.ATTR_TELEMETRY_SDK_NAME]: constant_1.SDK_NAME,
952
+ [semantic_conventions_1.ATTR_SERVICE_NAME]: config_1.default.applicationName ?? 'default',
953
+ [semantic_convention_1.default.ATTR_DEPLOYMENT_ENVIRONMENT]: config_1.default.environment ?? 'default',
954
+ [semantic_convention_1.default.GEN_AI_PROVIDER_NAME_OTEL]: semantic_convention_1.default.GEN_AI_SYSTEM_CLAUDE_AGENT_SDK,
955
+ [semantic_convention_1.default.GEN_AI_OPERATION]: semantic_convention_1.default.GEN_AI_OPERATION_TYPE_AGENT,
956
+ [GEN_AI_SYSTEM_ATTR]: GEN_AI_SYSTEM_VALUE,
957
+ [semantic_convention_1.default.SERVER_ADDRESS]: SERVER_ADDRESS,
958
+ [semantic_convention_1.default.SERVER_PORT]: SERVER_PORT,
959
+ };
960
+ if (metrics_1.default.genaiClientOperationDuration) {
961
+ metrics_1.default.genaiClientOperationDuration.record(duration, attributes);
962
+ }
963
+ if (inputTokens && metrics_1.default.genaiClientUsageTokens) {
964
+ metrics_1.default.genaiClientUsageTokens.record(inputTokens, {
965
+ ...attributes,
966
+ [semantic_convention_1.default.GEN_AI_TOKEN_TYPE]: semantic_convention_1.default.GEN_AI_TOKEN_TYPE_INPUT,
967
+ });
968
+ }
969
+ if (outputTokens && metrics_1.default.genaiClientUsageTokens) {
970
+ metrics_1.default.genaiClientUsageTokens.record(outputTokens, {
971
+ ...attributes,
972
+ [semantic_convention_1.default.GEN_AI_TOKEN_TYPE]: semantic_convention_1.default.GEN_AI_TOKEN_TYPE_OUTPUT,
973
+ });
974
+ }
975
+ }
976
+ }
977
+ catch { /* swallow */ }
978
+ }
979
+ // ---------------------------------------------------------------------------
980
+ // patchQuery — wraps the `query()` export from @anthropic-ai/claude-agent-sdk
981
+ // ---------------------------------------------------------------------------
982
+ function patchQuery(tracer) {
983
+ return (originalQuery) => {
984
+ return function wrappedQuery(params) {
985
+ const captureContent = config_1.default.captureMessageContent ?? true;
986
+ const prompt = params.prompt;
987
+ const userOptions = params.options;
988
+ const options = userOptions ? { ...userOptions } : {};
989
+ const agentName = resolveAgentName(options);
990
+ const spanName = generateSpanName('query', agentName);
991
+ const span = tracer.startSpan(spanName, {
992
+ kind: api_1.SpanKind.INTERNAL,
993
+ attributes: {
994
+ [semantic_convention_1.default.GEN_AI_OPERATION]: semantic_convention_1.default.GEN_AI_OPERATION_TYPE_AGENT,
995
+ [semantic_convention_1.default.GEN_AI_PROVIDER_NAME_OTEL]: semantic_convention_1.default.GEN_AI_SYSTEM_CLAUDE_AGENT_SDK,
996
+ },
997
+ });
998
+ const spanContext = api_1.trace.setSpan(api_1.context.active(), span);
999
+ const startTime = Date.now() / 1000;
1000
+ const chatState = { lastBoundaryMs: Date.now() };
1001
+ const toolTracker = new ToolSpanTracker(tracer, span, captureContent);
1002
+ const subagentTracker = new SubagentSpanTracker(tracer, toolTracker);
1003
+ const aggregateUsage = { inputTokens: 0, outputTokens: 0 };
1004
+ if (prompt && typeof prompt === 'string' && captureContent) {
1005
+ chatState.pendingInput = [{
1006
+ role: 'user',
1007
+ parts: [{ type: 'text', content: truncateContent(prompt) }],
1008
+ }];
1009
+ }
1010
+ // Capture system instructions and tool definitions once per query so
1011
+ // each chat span can stamp the same `shield360.agent.version_hash`.
1012
+ try {
1013
+ const systemPrompt = options?.systemPrompt;
1014
+ if (systemPrompt && typeof systemPrompt === 'string') {
1015
+ chatState.systemInstructionsJson = JSON.stringify([
1016
+ { type: 'text', content: systemPrompt },
1017
+ ]);
1018
+ }
1019
+ const optionTools = options?.tools;
1020
+ let normalizedTools = optionTools;
1021
+ if (optionTools && !Array.isArray(optionTools) && typeof optionTools === 'object') {
1022
+ normalizedTools = Object.entries(optionTools).map(([name, def]) => ({
1023
+ name,
1024
+ description: def?.description ?? '',
1025
+ parameters: def?.parameters ?? def?.input_schema ?? def?.inputSchema ?? {},
1026
+ }));
1027
+ }
1028
+ const toolDefs = helpers_1.default.buildToolDefinitions(normalizedTools);
1029
+ if (toolDefs)
1030
+ chatState.toolDefinitionsJson = toolDefs;
1031
+ }
1032
+ catch { /* swallow */ }
1033
+ injectHooks(options, toolTracker, subagentTracker);
1034
+ setInitialSpanAttributes(span, options, prompt, captureContent);
1035
+ (0, helpers_1.setFrameworkLlmActive)();
1036
+ let query;
1037
+ try {
1038
+ query = api_1.context.with(spanContext, () => {
1039
+ return originalQuery.call(this, { prompt, options });
1040
+ });
1041
+ }
1042
+ catch (e) {
1043
+ (0, helpers_1.resetFrameworkLlmActive)();
1044
+ helpers_1.default.handleException(span, e);
1045
+ span.end();
1046
+ throw e;
1047
+ }
1048
+ let done = false;
1049
+ const cleanup = () => {
1050
+ if (done)
1051
+ return;
1052
+ done = true;
1053
+ (0, helpers_1.resetFrameworkLlmActive)();
1054
+ subagentTracker.endAll();
1055
+ toolTracker.endAll();
1056
+ finalizeSpan(span, startTime, aggregateUsage.inputTokens, aggregateUsage.outputTokens);
1057
+ span.end();
1058
+ };
1059
+ const originalNext = query.next.bind(query);
1060
+ const originalReturn = query.return?.bind(query);
1061
+ const originalThrow = query.throw?.bind(query);
1062
+ return new Proxy(query, {
1063
+ get(target, prop, receiver) {
1064
+ if (prop === 'next') {
1065
+ return async function (...args) {
1066
+ try {
1067
+ const result = await originalNext(...args);
1068
+ if (result.done) {
1069
+ if (!done) {
1070
+ flushPendingChat(tracer, span, chatState, captureContent, subagentTracker);
1071
+ if (aggregateUsage.inputTokens === 0 && aggregateUsage.outputTokens === 0) {
1072
+ span.setStatus({ code: api_1.SpanStatusCode.OK });
1073
+ }
1074
+ }
1075
+ cleanup();
1076
+ return result;
1077
+ }
1078
+ const sdkMsg = result.value;
1079
+ try {
1080
+ const msgUsage = processMessage(sdkMsg, span, toolTracker, subagentTracker, captureContent, tracer, chatState);
1081
+ if (msgUsage) {
1082
+ aggregateUsage.inputTokens = msgUsage.inputTokens;
1083
+ aggregateUsage.outputTokens = msgUsage.outputTokens;
1084
+ }
1085
+ processToolBlocksFromMessages(sdkMsg, toolTracker, subagentTracker);
1086
+ }
1087
+ catch { /* swallow processing errors */ }
1088
+ return result;
1089
+ }
1090
+ catch (e) {
1091
+ if (!done) {
1092
+ helpers_1.default.handleException(span, e);
1093
+ }
1094
+ cleanup();
1095
+ throw e;
1096
+ }
1097
+ };
1098
+ }
1099
+ if (prop === 'return') {
1100
+ return async function (value) {
1101
+ cleanup();
1102
+ return originalReturn ? originalReturn(value) : { done: true, value };
1103
+ };
1104
+ }
1105
+ if (prop === 'throw') {
1106
+ return async function (e) {
1107
+ if (!done) {
1108
+ helpers_1.default.handleException(span, e instanceof Error ? e : new Error(String(e)));
1109
+ }
1110
+ cleanup();
1111
+ return originalThrow ? originalThrow(e) : { done: true, value: undefined };
1112
+ };
1113
+ }
1114
+ if (prop === Symbol.asyncIterator) {
1115
+ return function () { return receiver; };
1116
+ }
1117
+ return Reflect.get(target, prop, receiver);
1118
+ },
1119
+ });
1120
+ };
1121
+ };
1122
+ }
1123
+ //# sourceMappingURL=wrapper.js.map