dd-trace 6.15.0 → 6.17.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 (378) hide show
  1. package/README.md +15 -0
  2. package/ci/diagnose.js +0 -23
  3. package/ci/test-optimization-validation/approval-artifacts.js +0 -3
  4. package/ci/test-optimization-validation/approval.js +0 -6
  5. package/ci/test-optimization-validation/artifact-id.js +0 -1
  6. package/ci/test-optimization-validation/bounded-json.js +0 -1
  7. package/ci/test-optimization-validation/cli.js +0 -12
  8. package/ci/test-optimization-validation/command-output-policy.js +0 -1
  9. package/ci/test-optimization-validation/command-runner.js +0 -3
  10. package/ci/test-optimization-validation/environment.js +0 -4
  11. package/ci/test-optimization-validation/executable-approval.js +0 -1
  12. package/ci/test-optimization-validation/executable.js +0 -5
  13. package/ci/test-optimization-validation/framework-adapters/cucumber.js +4 -8
  14. package/ci/test-optimization-validation/framework-adapters/cypress.js +0 -3
  15. package/ci/test-optimization-validation/framework-adapters/playwright.js +0 -6
  16. package/ci/test-optimization-validation/framework-adapters/vitest.js +0 -4
  17. package/ci/test-optimization-validation/generated-test-contract.js +0 -5
  18. package/ci/test-optimization-validation/generated-verifier.js +0 -1
  19. package/ci/test-optimization-validation/literal-environment.js +0 -1
  20. package/ci/test-optimization-validation/manifest-scaffold.js +0 -17
  21. package/ci/test-optimization-validation/manifest-schema.js +0 -21
  22. package/ci/test-optimization-validation/offline-fixtures.js +0 -4
  23. package/ci/test-optimization-validation/package-check.js +4 -1
  24. package/ci/test-optimization-validation/plan-writer.js +0 -11
  25. package/ci/test-optimization-validation/preflight-runner.js +0 -1
  26. package/ci/test-optimization-validation/redaction.js +0 -4
  27. package/ci/test-optimization-validation/report-writer.js +0 -16
  28. package/ci/test-optimization-validation/runner-command.js +0 -3
  29. package/ci/test-optimization-validation/runner-contract.js +0 -4
  30. package/ci/test-optimization-validation/safe-files.js +0 -1
  31. package/ci/test-optimization-validation/scenarios/basic-reporting.js +0 -1
  32. package/ci/test-optimization-validation/scenarios/ci-wiring.js +1 -2
  33. package/ci/test-optimization-validation/source-text.js +0 -3
  34. package/ci/vitest-no-worker-init-setup.mjs +41 -16
  35. package/index.d.ts +169 -0
  36. package/next.d.ts +27 -0
  37. package/next.js +3 -0
  38. package/package.json +28 -23
  39. package/packages/datadog-esbuild/index.js +14 -1
  40. package/packages/datadog-esbuild/src/resolver.js +284 -0
  41. package/packages/datadog-esbuild/src/utils.js +162 -120
  42. package/packages/datadog-instrumentations/src/aerospike.js +28 -6
  43. package/packages/datadog-instrumentations/src/ai.js +39 -97
  44. package/packages/datadog-instrumentations/src/anthropic.js +76 -134
  45. package/packages/datadog-instrumentations/src/aws-durable-execution-sdk-js.js +1 -3
  46. package/packages/datadog-instrumentations/src/aws-sdk.js +0 -2
  47. package/packages/datadog-instrumentations/src/azure-cosmos.js +1 -1
  48. package/packages/datadog-instrumentations/src/azure-durable-functions.js +23 -9
  49. package/packages/datadog-instrumentations/src/azure-functions.js +48 -0
  50. package/packages/datadog-instrumentations/src/bullmq.js +1 -1
  51. package/packages/datadog-instrumentations/src/claude-agent-sdk.js +1 -3
  52. package/packages/datadog-instrumentations/src/console.js +97 -0
  53. package/packages/datadog-instrumentations/src/cucumber.js +72 -12
  54. package/packages/datadog-instrumentations/src/cypress-config.js +0 -23
  55. package/packages/datadog-instrumentations/src/dd-trace-api.js +2 -2
  56. package/packages/datadog-instrumentations/src/graphql.js +1 -1
  57. package/packages/datadog-instrumentations/src/helpers/bundler-register.js +39 -14
  58. package/packages/datadog-instrumentations/src/helpers/channel.js +0 -2
  59. package/packages/datadog-instrumentations/src/helpers/graphql-jit-runtime.js +0 -5
  60. package/packages/datadog-instrumentations/src/helpers/hooks.js +8 -0
  61. package/packages/datadog-instrumentations/src/helpers/instrument.js +25 -8
  62. package/packages/datadog-instrumentations/src/helpers/instrumentation-utils.js +69 -0
  63. package/packages/datadog-instrumentations/src/helpers/pool-acquire.js +0 -6
  64. package/packages/datadog-instrumentations/src/helpers/register.js +13 -64
  65. package/packages/datadog-instrumentations/src/helpers/rewriter/index.js +109 -29
  66. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentation-registry.js +39 -0
  67. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/azure-durable-functions.js +17 -0
  68. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/index.js +3 -16
  69. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/playwright.js +12 -0
  70. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/postgres.js +36 -0
  71. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/supabase.js +128 -0
  72. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/webdriverio.js +6 -7
  73. package/packages/datadog-instrumentations/src/helpers/rewriter/targets.json +17 -0
  74. package/packages/datadog-instrumentations/src/helpers/rewriter/transforms/postgres.js +388 -0
  75. package/packages/datadog-instrumentations/src/helpers/rewriter/transforms.js +99 -75
  76. package/packages/datadog-instrumentations/src/helpers/router-helper.js +0 -1
  77. package/packages/datadog-instrumentations/src/jest.js +141 -51
  78. package/packages/datadog-instrumentations/src/knex.js +0 -1
  79. package/packages/datadog-instrumentations/src/langchain.js +1 -1
  80. package/packages/datadog-instrumentations/src/langgraph.js +1 -1
  81. package/packages/datadog-instrumentations/src/mariadb-bundle.js +0 -24
  82. package/packages/datadog-instrumentations/src/mariadb.js +0 -2
  83. package/packages/datadog-instrumentations/src/mercurius.js +1 -1
  84. package/packages/datadog-instrumentations/src/mocha/common.js +0 -1
  85. package/packages/datadog-instrumentations/src/mocha/main.js +22 -25
  86. package/packages/datadog-instrumentations/src/mocha/utils.js +119 -49
  87. package/packages/datadog-instrumentations/src/mocha/webdriverio-protocol.js +0 -6
  88. package/packages/datadog-instrumentations/src/mocha/worker.js +14 -17
  89. package/packages/datadog-instrumentations/src/modelcontextprotocol-sdk.js +1 -1
  90. package/packages/datadog-instrumentations/src/mysql2.js +0 -2
  91. package/packages/datadog-instrumentations/src/openai-agents.js +1 -1
  92. package/packages/datadog-instrumentations/src/openai-realtime/audio-accumulator.js +241 -0
  93. package/packages/datadog-instrumentations/src/openai-realtime/events.js +76 -0
  94. package/packages/datadog-instrumentations/src/openai-realtime/index.js +301 -0
  95. package/packages/datadog-instrumentations/src/openai-realtime/session.js +998 -0
  96. package/packages/datadog-instrumentations/src/openai-realtime/turns.js +211 -0
  97. package/packages/datadog-instrumentations/src/openai.js +97 -80
  98. package/packages/datadog-instrumentations/src/oracledb.js +9 -3
  99. package/packages/datadog-instrumentations/src/playwright-reporter.js +3 -16
  100. package/packages/datadog-instrumentations/src/playwright.js +238 -55
  101. package/packages/datadog-instrumentations/src/postgres.js +7 -0
  102. package/packages/datadog-instrumentations/src/router.js +0 -2
  103. package/packages/datadog-instrumentations/src/rum-browser-scripts.js +0 -2
  104. package/packages/datadog-instrumentations/src/sequelize.js +0 -1
  105. package/packages/datadog-instrumentations/src/supabase.js +15 -0
  106. package/packages/datadog-instrumentations/src/vitest-main-no-worker-init.js +18 -18
  107. package/packages/datadog-instrumentations/src/vitest-main.js +37 -17
  108. package/packages/datadog-instrumentations/src/vitest-util.js +7 -1
  109. package/packages/datadog-instrumentations/src/vitest-worker.js +56 -23
  110. package/packages/datadog-instrumentations/src/webdriverio.js +23 -42
  111. package/packages/datadog-instrumentations/src/ws.js +0 -1
  112. package/packages/datadog-plugin-ai/src/utils.js +0 -2
  113. package/packages/datadog-plugin-aws-durable-execution-sdk-js/src/trace-checkpoint.js +0 -1
  114. package/packages/datadog-plugin-aws-durable-execution-sdk-js/src/util.js +0 -2
  115. package/packages/datadog-plugin-aws-sdk/src/base.js +0 -1
  116. package/packages/datadog-plugin-aws-sdk/src/services/bedrockruntime/utils.js +7 -2
  117. package/packages/datadog-plugin-aws-sdk/src/services/eventbridge.js +0 -1
  118. package/packages/datadog-plugin-aws-sdk/src/util.js +0 -1
  119. package/packages/datadog-plugin-azure-cosmos/src/index.js +1 -1
  120. package/packages/datadog-plugin-azure-durable-functions/src/index.js +95 -1
  121. package/packages/datadog-plugin-cucumber/src/index.js +10 -0
  122. package/packages/datadog-plugin-cypress/src/cypress-plugin.js +171 -75
  123. package/packages/datadog-plugin-cypress/src/finalization.js +0 -3
  124. package/packages/datadog-plugin-cypress/src/source-map-utils.js +0 -4
  125. package/packages/datadog-plugin-cypress/src/support.js +52 -7
  126. package/packages/datadog-plugin-google-cloud-pubsub/src/consumer.js +2 -24
  127. package/packages/datadog-plugin-google-cloud-pubsub/src/pubsub-push-subscription.js +2 -36
  128. package/packages/datadog-plugin-google-cloud-pubsub/src/pubsub-request-context.js +31 -0
  129. package/packages/datadog-plugin-graphql/src/resolve-error.js +32 -11
  130. package/packages/datadog-plugin-graphql/src/utils.js +0 -5
  131. package/packages/datadog-plugin-jest/src/index.js +13 -0
  132. package/packages/datadog-plugin-kafkajs/src/producer.js +0 -1
  133. package/packages/datadog-plugin-mocha/src/index.js +39 -11
  134. package/packages/datadog-plugin-mongodb-core/src/query.js +0 -1
  135. package/packages/datadog-plugin-openai/src/index.js +16 -1
  136. package/packages/datadog-plugin-openai/src/realtime.js +144 -0
  137. package/packages/datadog-plugin-openai-agents/src/integration.js +0 -4
  138. package/packages/datadog-plugin-openai-agents/src/util.js +0 -1
  139. package/packages/datadog-plugin-playwright/src/index.js +76 -9
  140. package/packages/datadog-plugin-postgres/src/index.js +167 -0
  141. package/packages/datadog-plugin-prisma/src/datadog-tracing-helper.js +0 -1
  142. package/packages/datadog-plugin-redis/src/index.js +15 -1
  143. package/packages/datadog-plugin-supabase/src/error.js +18 -0
  144. package/packages/datadog-plugin-supabase/src/index.js +21 -0
  145. package/packages/datadog-plugin-supabase/src/supabase-auth-js-gotrueclient-getuser.js +69 -0
  146. package/packages/datadog-plugin-supabase/src/supabase-functions-js-functionsclient-invoke.js +70 -0
  147. package/packages/datadog-plugin-supabase/src/supabase-postgrest-js-postgrestbuilder-then.js +122 -0
  148. package/packages/datadog-plugin-supabase/src/supabase-realtime-js-realtimechannel-send.js +66 -0
  149. package/packages/datadog-plugin-supabase/src/supabase-storage-js-handle-request.js +93 -0
  150. package/packages/datadog-plugin-supabase/src/url.js +17 -0
  151. package/packages/datadog-plugin-vitest/src/index.js +10 -0
  152. package/packages/datadog-plugin-ws/src/util.js +0 -4
  153. package/packages/datadog-turbopack/index.js +206 -0
  154. package/packages/datadog-turbopack/src/constants.js +5 -0
  155. package/packages/datadog-turbopack/src/loader.js +484 -0
  156. package/packages/datadog-webpack/src/loader.js +0 -1
  157. package/packages/dd-trace/src/aiguard/client.js +2 -3
  158. package/packages/dd-trace/src/aiguard/evaluation.js +6 -12
  159. package/packages/dd-trace/src/aiguard/index.js +3 -2
  160. package/packages/dd-trace/src/aiguard/integrations/anthropic.js +53 -25
  161. package/packages/dd-trace/src/aiguard/integrations/evaluate.js +49 -25
  162. package/packages/dd-trace/src/aiguard/integrations/index.js +4 -3
  163. package/packages/dd-trace/src/aiguard/integrations/openai.js +132 -29
  164. package/packages/dd-trace/src/aiguard/integrations/vercel-ai.js +116 -42
  165. package/packages/dd-trace/src/aiguard/messages/anthropic.js +0 -2
  166. package/packages/dd-trace/src/aiguard/messages/openai.js +64 -1
  167. package/packages/dd-trace/src/aiguard/messages/utils.js +29 -2
  168. package/packages/dd-trace/src/aiguard/messages/vercel-ai.js +25 -0
  169. package/packages/dd-trace/src/aiguard/redaction.js +0 -1
  170. package/packages/dd-trace/src/aiguard/sdk.js +1 -1
  171. package/packages/dd-trace/src/appsec/activation.js +1 -1
  172. package/packages/dd-trace/src/appsec/api_security/normalized-route.js +0 -5
  173. package/packages/dd-trace/src/appsec/api_security/sampler.js +0 -4
  174. package/packages/dd-trace/src/appsec/blocking/index.js +3 -3
  175. package/packages/dd-trace/src/appsec/downstream_requests.js +1 -4
  176. package/packages/dd-trace/src/appsec/iast/index.js +1 -1
  177. package/packages/dd-trace/src/appsec/iast/overhead-controller.js +5 -5
  178. package/packages/dd-trace/src/appsec/iast/taint-tracking/index.js +1 -1
  179. package/packages/dd-trace/src/appsec/iast/taint-tracking/plugin.js +1 -1
  180. package/packages/dd-trace/src/appsec/iast/taint-tracking/rewriter.js +3 -3
  181. package/packages/dd-trace/src/appsec/iast/vulnerabilities-formatter/evidence-redaction/sensitive-analyzers/sql-sensitive-analyzer.js +8 -10
  182. package/packages/dd-trace/src/appsec/iast/vulnerabilities-formatter/evidence-redaction/sensitive-analyzers/url-sensitive-analyzer.js +2 -2
  183. package/packages/dd-trace/src/appsec/iast/vulnerabilities-formatter/evidence-redaction/sensitive-handler.js +2 -2
  184. package/packages/dd-trace/src/appsec/iast/vulnerabilities-formatter/utils.js +4 -1
  185. package/packages/dd-trace/src/appsec/iast/vulnerability-reporter.js +7 -7
  186. package/packages/dd-trace/src/appsec/index.js +2 -2
  187. package/packages/dd-trace/src/appsec/lambda.js +71 -2
  188. package/packages/dd-trace/src/appsec/rasp/utils.js +5 -1
  189. package/packages/dd-trace/src/appsec/remote_config.js +8 -6
  190. package/packages/dd-trace/src/appsec/reporter.js +10 -6
  191. package/packages/dd-trace/src/appsec/rule_manager.js +3 -3
  192. package/packages/dd-trace/src/appsec/sdk/track_event.js +0 -2
  193. package/packages/dd-trace/src/appsec/telemetry/api_security.js +1 -3
  194. package/packages/dd-trace/src/appsec/telemetry/common.js +4 -0
  195. package/packages/dd-trace/src/appsec/telemetry/index.js +23 -5
  196. package/packages/dd-trace/src/appsec/telemetry/rasp.js +1 -20
  197. package/packages/dd-trace/src/appsec/telemetry/user.js +1 -3
  198. package/packages/dd-trace/src/appsec/telemetry/waf.js +1 -20
  199. package/packages/dd-trace/src/appsec/waf/index.js +2 -2
  200. package/packages/dd-trace/src/appsec/waf/waf_manager.js +8 -5
  201. package/packages/dd-trace/src/carrier.js +0 -5
  202. package/packages/dd-trace/src/ci-visibility/dynamic-atr-retries.js +104 -0
  203. package/packages/dd-trace/src/ci-visibility/dynamic-instrumentation/worker/index.js +0 -2
  204. package/packages/dd-trace/src/ci-visibility/efd-retry-policy.js +34 -3
  205. package/packages/dd-trace/src/ci-visibility/exporters/agentless/coverage-writer.js +0 -1
  206. package/packages/dd-trace/src/ci-visibility/exporters/agentless/di-logs-writer.js +0 -1
  207. package/packages/dd-trace/src/ci-visibility/exporters/agentless/writer.js +0 -1
  208. package/packages/dd-trace/src/ci-visibility/exporters/ci-validation/index.js +0 -4
  209. package/packages/dd-trace/src/ci-visibility/exporters/ci-validation/msgpack-to-json.js +0 -1
  210. package/packages/dd-trace/src/ci-visibility/exporters/ci-validation/sink.js +0 -2
  211. package/packages/dd-trace/src/ci-visibility/exporters/ci-visibility-exporter.js +37 -15
  212. package/packages/dd-trace/src/ci-visibility/exporters/git/git_metadata.js +0 -3
  213. package/packages/dd-trace/src/ci-visibility/exporters/request.js +0 -11
  214. package/packages/dd-trace/src/ci-visibility/exporters/settings-cache-key.js +0 -1
  215. package/packages/dd-trace/src/ci-visibility/intelligent-test-runner/get-skippable-suites.js +0 -1
  216. package/packages/dd-trace/src/ci-visibility/requests/fs-cache.js +0 -6
  217. package/packages/dd-trace/src/ci-visibility/requests/get-library-configuration.js +2 -2
  218. package/packages/dd-trace/src/ci-visibility/requests/rate-limit.js +0 -1
  219. package/packages/dd-trace/src/ci-visibility/requests/upload-test-screenshot.js +0 -5
  220. package/packages/dd-trace/src/ci-visibility/requests/video-request.js +0 -1
  221. package/packages/dd-trace/src/ci-visibility/telemetry.js +13 -0
  222. package/packages/dd-trace/src/ci-visibility/test-optimization-cache.js +0 -1
  223. package/packages/dd-trace/src/ci-visibility/test-screenshot.js +0 -2
  224. package/packages/dd-trace/src/ci-visibility/test-video.js +0 -1
  225. package/packages/dd-trace/src/config/defaults.js +3 -2
  226. package/packages/dd-trace/src/config/generated-config-types.d.ts +74 -66
  227. package/packages/dd-trace/src/config/helper.js +9 -2
  228. package/packages/dd-trace/src/config/index.js +44 -29
  229. package/packages/dd-trace/src/config/parsers.js +34 -6
  230. package/packages/dd-trace/src/config/remote_config.js +25 -109
  231. package/packages/dd-trace/src/config/supported-configurations.json +146 -9
  232. package/packages/dd-trace/src/datastreams/encoding.js +0 -1
  233. package/packages/dd-trace/src/datastreams/pathway.js +0 -1
  234. package/packages/dd-trace/src/debugger/constants.js +10 -0
  235. package/packages/dd-trace/src/debugger/devtools_client/breakpoints.js +76 -17
  236. package/packages/dd-trace/src/debugger/devtools_client/config.js +2 -0
  237. package/packages/dd-trace/src/debugger/devtools_client/guardrail-metrics.js +15 -0
  238. package/packages/dd-trace/src/debugger/devtools_client/index.js +103 -27
  239. package/packages/dd-trace/src/debugger/devtools_client/json-buffer.js +50 -7
  240. package/packages/dd-trace/src/debugger/devtools_client/log.js +3 -1
  241. package/packages/dd-trace/src/debugger/devtools_client/probe_sampler.js +34 -8
  242. package/packages/dd-trace/src/debugger/devtools_client/send.js +40 -14
  243. package/packages/dd-trace/src/debugger/devtools_client/snapshot/index.js +53 -13
  244. package/packages/dd-trace/src/debugger/devtools_client/snapshot/processor.js +118 -71
  245. package/packages/dd-trace/src/debugger/devtools_client/snapshot-pruner.js +0 -3
  246. package/packages/dd-trace/src/debugger/devtools_client/status.js +20 -6
  247. package/packages/dd-trace/src/debugger/guardrail-metrics.js +167 -0
  248. package/packages/dd-trace/src/debugger/index.js +50 -2
  249. package/packages/dd-trace/src/debugger/inspect-segment.js +0 -3
  250. package/packages/dd-trace/src/debugger/probe_sampler.js +133 -9
  251. package/packages/dd-trace/src/debugger/probe_sampler_constants.js +31 -1
  252. package/packages/dd-trace/src/dogstatsd.js +0 -23
  253. package/packages/dd-trace/src/encode/0.4-cross-payload.js +0 -3
  254. package/packages/dd-trace/src/encode/0.4.js +0 -7
  255. package/packages/dd-trace/src/encode/0.5.js +0 -2
  256. package/packages/dd-trace/src/encode/tags-processors.js +0 -1
  257. package/packages/dd-trace/src/evp_proxy/discovery.js +3 -5
  258. package/packages/dd-trace/src/evp_proxy/path.js +11 -4
  259. package/packages/dd-trace/src/exporters/agent/writer.js +0 -1
  260. package/packages/dd-trace/src/exporters/agentless/index.js +0 -1
  261. package/packages/dd-trace/src/exporters/agentless/intake.js +0 -1
  262. package/packages/dd-trace/src/exporters/agentless/writer.js +0 -3
  263. package/packages/dd-trace/src/exporters/common/docker.js +4 -1
  264. package/packages/dd-trace/src/exporters/common/final-flush-request-tracker.js +0 -6
  265. package/packages/dd-trace/src/exporters/common/proxy.js +3 -0
  266. package/packages/dd-trace/src/exporters/common/request.js +1 -0
  267. package/packages/dd-trace/src/exporters/common/url.js +0 -2
  268. package/packages/dd-trace/src/exporters/common/writer.js +0 -2
  269. package/packages/dd-trace/src/id.js +0 -11
  270. package/packages/dd-trace/src/llmobs/audio-codec.js +192 -0
  271. package/packages/dd-trace/src/llmobs/audio-utils.js +121 -0
  272. package/packages/dd-trace/src/llmobs/constants/audio.js +35 -0
  273. package/packages/dd-trace/src/llmobs/constants/prompts.js +14 -0
  274. package/packages/dd-trace/src/llmobs/constants/tags.js +17 -0
  275. package/packages/dd-trace/src/llmobs/eval-metric.js +0 -6
  276. package/packages/dd-trace/src/llmobs/experiments/dataset.js +0 -4
  277. package/packages/dd-trace/src/llmobs/experiments/experiment.js +0 -3
  278. package/packages/dd-trace/src/llmobs/experiments/index.js +7 -6
  279. package/packages/dd-trace/src/llmobs/experiments/util.js +1 -11
  280. package/packages/dd-trace/src/llmobs/index.js +1 -3
  281. package/packages/dd-trace/src/llmobs/noop.js +10 -0
  282. package/packages/dd-trace/src/llmobs/plugins/ai/util.js +0 -4
  283. package/packages/dd-trace/src/llmobs/plugins/anthropic/util.js +0 -1
  284. package/packages/dd-trace/src/llmobs/plugins/genai/util.js +0 -4
  285. package/packages/dd-trace/src/llmobs/plugins/modelcontextprotocol-sdk/utils.js +0 -2
  286. package/packages/dd-trace/src/llmobs/plugins/openai/constants.js +0 -2
  287. package/packages/dd-trace/src/llmobs/plugins/openai/index.js +4 -6
  288. package/packages/dd-trace/src/llmobs/plugins/openai/realtime.js +285 -0
  289. package/packages/dd-trace/src/llmobs/plugins/openai/utils.js +16 -3
  290. package/packages/dd-trace/src/llmobs/prompts/cache.js +272 -0
  291. package/packages/dd-trace/src/llmobs/prompts/manager.js +639 -0
  292. package/packages/dd-trace/src/llmobs/prompts/noop.js +29 -0
  293. package/packages/dd-trace/src/llmobs/prompts/prompt.js +92 -0
  294. package/packages/dd-trace/src/llmobs/sdk.js +21 -6
  295. package/packages/dd-trace/src/llmobs/span_processor.js +81 -2
  296. package/packages/dd-trace/src/llmobs/tagger.js +30 -7
  297. package/packages/dd-trace/src/llmobs/telemetry.js +36 -4
  298. package/packages/dd-trace/src/llmobs/util.js +0 -34
  299. package/packages/dd-trace/src/llmobs/writers/base.js +0 -1
  300. package/packages/dd-trace/src/llmobs/writers/util.js +1 -2
  301. package/packages/dd-trace/src/log/channels.js +3 -0
  302. package/packages/dd-trace/src/log/index.js +23 -5
  303. package/packages/dd-trace/src/log-submission/log-submission-plugin.js +74 -6
  304. package/packages/dd-trace/src/msgpack/chunk.js +0 -1
  305. package/packages/dd-trace/src/openfeature/agentless_configuration_source.js +0 -12
  306. package/packages/dd-trace/src/openfeature/encoding.js +0 -2
  307. package/packages/dd-trace/src/openfeature/eval-metrics-hook.js +0 -1
  308. package/packages/dd-trace/src/openfeature/index.js +0 -4
  309. package/packages/dd-trace/src/openfeature/span-enrichment-hook.js +0 -1
  310. package/packages/dd-trace/src/openfeature/span-enrichment.js +0 -4
  311. package/packages/dd-trace/src/openfeature/writers/base.js +0 -6
  312. package/packages/dd-trace/src/openfeature/writers/exposures.js +0 -5
  313. package/packages/dd-trace/src/openfeature/writers/util.js +0 -4
  314. package/packages/dd-trace/src/opentelemetry/logs/logger.js +0 -1
  315. package/packages/dd-trace/src/opentelemetry/logs/logger_provider.js +0 -1
  316. package/packages/dd-trace/src/opentelemetry/logs/otlp_http_log_exporter.js +0 -1
  317. package/packages/dd-trace/src/opentelemetry/logs/otlp_transformer.js +0 -2
  318. package/packages/dd-trace/src/opentelemetry/metrics/index.js +1 -1
  319. package/packages/dd-trace/src/opentelemetry/metrics/meter_provider.js +4 -4
  320. package/packages/dd-trace/src/opentelemetry/metrics/otlp_span_stats_transformer.js +0 -1
  321. package/packages/dd-trace/src/opentelemetry/metrics/otlp_transformer.js +0 -1
  322. package/packages/dd-trace/src/opentelemetry/metrics/periodic_metric_reader.js +103 -35
  323. package/packages/dd-trace/src/opentelemetry/metrics/time.js +0 -1
  324. package/packages/dd-trace/src/opentelemetry/otlp/otlp_http_exporter_base.js +36 -13
  325. package/packages/dd-trace/src/opentelemetry/otlp/otlp_transformer_base.js +0 -1
  326. package/packages/dd-trace/src/opentelemetry/span-helpers.js +0 -1
  327. package/packages/dd-trace/src/opentelemetry/trace/otlp_http_trace_exporter.js +0 -1
  328. package/packages/dd-trace/src/opentelemetry/trace/otlp_transformer.js +0 -3
  329. package/packages/dd-trace/src/opentracing/propagation/text_map.js +0 -6
  330. package/packages/dd-trace/src/opentracing/span_context.js +0 -1
  331. package/packages/dd-trace/src/otel-thread-ctx.js +38 -11
  332. package/packages/dd-trace/src/payload-tagging/tagging.js +15 -3
  333. package/packages/dd-trace/src/plugin_manager.js +9 -3
  334. package/packages/dd-trace/src/plugins/ci_plugin.js +0 -1
  335. package/packages/dd-trace/src/plugins/database.js +2 -6
  336. package/packages/dd-trace/src/plugins/index.js +8 -0
  337. package/packages/dd-trace/src/plugins/plugin.js +0 -4
  338. package/packages/dd-trace/src/plugins/tracing.js +1 -1
  339. package/packages/dd-trace/src/plugins/util/git.js +1 -3
  340. package/packages/dd-trace/src/plugins/util/http-otel-semantics.js +0 -1
  341. package/packages/dd-trace/src/plugins/util/llm.js +0 -2
  342. package/packages/dd-trace/src/plugins/util/status-validator.js +0 -1
  343. package/packages/dd-trace/src/plugins/util/test.js +25 -21
  344. package/packages/dd-trace/src/plugins/util/url.js +0 -5
  345. package/packages/dd-trace/src/priority_sampler.js +0 -6
  346. package/packages/dd-trace/src/process-tags/index.js +0 -1
  347. package/packages/dd-trace/src/profiler.js +132 -35
  348. package/packages/dd-trace/src/profiling/exporters/event_serializer.js +0 -1
  349. package/packages/dd-trace/src/profiling/profiler.js +101 -41
  350. package/packages/dd-trace/src/profiling/ssi-heuristics.js +29 -15
  351. package/packages/dd-trace/src/propagation-hash/index.js +0 -1
  352. package/packages/dd-trace/src/proxy.js +21 -45
  353. package/packages/dd-trace/src/random_sampler.js +0 -4
  354. package/packages/dd-trace/src/rate_limiter.js +0 -4
  355. package/packages/dd-trace/src/remote_config/capabilities.js +1 -9
  356. package/packages/dd-trace/src/remote_config/index.js +0 -1
  357. package/packages/dd-trace/src/runtime_metrics/otlp_runtime_metrics.js +0 -3
  358. package/packages/dd-trace/src/sampler.js +0 -4
  359. package/packages/dd-trace/src/sampling_rule.js +0 -7
  360. package/packages/dd-trace/src/serverless/vercel.js +0 -1
  361. package/packages/dd-trace/src/serverless.js +0 -1
  362. package/packages/dd-trace/src/service-naming/index.js +0 -1
  363. package/packages/dd-trace/src/service-naming/schemas/util.js +0 -1
  364. package/packages/dd-trace/src/service-naming/schemas/v0/storage.js +7 -0
  365. package/packages/dd-trace/src/service-naming/schemas/v1/storage.js +5 -0
  366. package/packages/dd-trace/src/span_processor.js +2 -2
  367. package/packages/dd-trace/src/span_sampler.js +0 -1
  368. package/packages/dd-trace/src/standalone/product.js +2 -2
  369. package/packages/dd-trace/src/standalone/tracesource.js +0 -1
  370. package/packages/dd-trace/src/startup-log.js +1 -1
  371. package/packages/dd-trace/src/telemetry/endpoints.js +0 -8
  372. package/packages/dd-trace/src/telemetry/logs/index.js +16 -5
  373. package/packages/dd-trace/src/telemetry/logs/log-collector.js +16 -6
  374. package/packages/dd-trace/src/telemetry/metrics.js +0 -2
  375. package/packages/dd-trace/src/telemetry/telemetry.js +4 -1
  376. package/packages/dd-trace/src/util.js +13 -1
  377. package/vendor/dist/@datadog/openfeature-node-server/index.js +1 -1
  378. package/packages/dd-trace/src/llmobs/plugins/claude-agent-sdk/utils.js +0 -10
@@ -1,13 +1,13 @@
1
1
  'use strict'
2
2
 
3
3
  // The content of this file is copied from the `import-in-the-middle` package with minor modifications (https://www.npmjs.com/package/import-in-the-middle)
4
- const { pathToFileURL, fileURLToPath } = require('node:url')
5
4
  const fs = require('node:fs')
6
5
  const path = require('node:path')
7
- const { NODE_MAJOR, NODE_MINOR } = require('../../../version.js')
6
+ const { fileURLToPath, pathToFileURL } = require('node:url')
8
7
 
9
- const LOAD_OPERATION = 0
10
- const RESOLVE_OPERATION = 1
8
+ const { createEsmResolver, driveGetExportsGenerator } = require('./resolver')
9
+
10
+ /** @typedef {ReturnType<typeof createEsmResolver>} EsmResolver */
11
11
 
12
12
  const getExportsImporting = (url) => import(url).then(Object.keys)
13
13
  let getExportsModulePromise
@@ -19,16 +19,33 @@ const loadGetExportsModule = () => {
19
19
  return getExportsModulePromise
20
20
  }
21
21
 
22
- const getExports = NODE_MAJOR >= 20 || (NODE_MAJOR === 18 && NODE_MINOR >= 19)
23
- ? async (srcUrl, context, getSource) => {
24
- const mod = await loadGetExportsModule()
25
- const exportNames = mod.getExports(srcUrl, context, getSource)
26
- if (exportNames?.next) {
27
- return driveGetExportsGenerator(exportNames, getSource)
28
- }
29
- return exportNames
22
+ /**
23
+ * @param {URL} srcUrl
24
+ * @param {object} context
25
+ * @param {(url: URL, context: object) => { source: string, format: string }} getSource
26
+ * @param {EsmResolver} resolver
27
+ * @returns {Promise<{
28
+ * exportNames: Iterable<string>,
29
+ * hasModuleExportsCJSDefault: boolean,
30
+ * starReexports?: Array<{ specifier: string, parentURL: string }>
31
+ * }>}
32
+ */
33
+ const getExports = async (srcUrl, context, getSource, resolver) => {
34
+ const mod = await loadGetExportsModule()
35
+ const exportsGenerator = mod.getExports(srcUrl, context, getSource)
36
+ /**
37
+ * @param {string} specifier
38
+ * @param {{ parentURL: URL }} operationContext
39
+ * @returns {Promise<{ format: string, url: URL }>}
40
+ */
41
+ const resolve = (specifier, operationContext) => resolveModule(specifier, operationContext, resolver)
42
+ const result = await driveGetExportsGenerator(exportsGenerator, getSource, resolve)
43
+ return {
44
+ exportNames: result.exportNames,
45
+ hasModuleExportsCJSDefault: mod.hasModuleExportsCJSDefault,
46
+ starReexports: result.starReexports,
30
47
  }
31
- : getExportsImporting
48
+ }
32
49
 
33
50
  function isStarExportLine (line) {
34
51
  return /^\* from /.test(line)
@@ -58,82 +75,36 @@ function isBareSpecifier (specifier) {
58
75
  }
59
76
  }
60
77
 
61
- function resolve (specifier, context) {
62
- // This comes from an import, that is why import makes preference
63
- const conditions = ['import']
64
-
65
- if (specifier.startsWith('file://')) {
66
- specifier = fileURLToPath(specifier)
67
- }
68
-
69
- const resolved = require.resolve(specifier, {
70
- paths: [fileURLToPath(context.parentURL)],
71
- // @ts-expect-error - Node.js 22+ unofficially supports a conditions option
72
- conditions,
73
- })
74
-
75
- return {
76
- url: pathToFileURL(resolved),
77
- format: isESMFile(resolved) ? 'module' : 'commonjs',
78
- }
79
- }
80
-
81
- function getSource (url, { format }) {
82
- return {
83
- source: fs.readFileSync(fileURLToPath(url), 'utf8'),
84
- format,
85
- }
86
- }
87
-
88
78
  /**
89
- * @typedef {[typeof LOAD_OPERATION, URL, object] | [typeof RESOLVE_OPERATION, string, object]} GetExportsOperation
90
- */
91
-
92
- /**
93
- * @typedef {{ done: false, value: GetExportsOperation } | { done: true, value: Set<string> }} GetExportsResult
94
- */
95
-
96
- /**
97
- * @typedef {{
98
- * next: (value?: unknown) => GetExportsResult,
99
- * throw: (error?: unknown) => GetExportsResult,
100
- * }} GetExportsGenerator
79
+ * @param {string} modulePath
80
+ * @param {string} format
101
81
  */
82
+ function getModuleFormat (modulePath, format) {
83
+ if (modulePath.endsWith('.mts')) return 'module-typescript'
84
+ if (modulePath.endsWith('.cts')) return 'commonjs-typescript'
85
+ if (modulePath.endsWith('.ts')) return `${format}-typescript`
86
+ return format
87
+ }
102
88
 
103
89
  /**
104
- * Drives the generator returned by import-in-the-middle >=3.1.0 export discovery.
90
+ * Resolves a module with the import conditions used by ESM instrumentation.
105
91
  *
106
- * @param {GetExportsGenerator} exportsGenerator Generator returned by getExports
107
- * @param {(url: URL, context: object) => { source: string, format: string }} getSource
108
- * Function that loads module source
109
- * @returns {Set<string>}
92
+ * @param {string} specifier
93
+ * @param {{ parentURL: URL }} context
94
+ * @param {EsmResolver} resolver
95
+ * @returns {Promise<{ format: string, url: URL }>}
110
96
  */
111
- function driveGetExportsGenerator (exportsGenerator, getSource) {
112
- let next = exportsGenerator.next()
113
- while (next.done === false) {
114
- let result
115
- let error
116
- let threw = false
117
-
118
- try {
119
- const operation = next.value
120
- const operationType = operation[0]
121
-
122
- if (operationType === LOAD_OPERATION) {
123
- result = getSource(operation[1], operation[2])
124
- } else if (operationType === RESOLVE_OPERATION) {
125
- result = resolve(operation[1], operation[2])
126
- } else {
127
- throw new Error(`Unsupported import-in-the-middle getExports operation: ${operationType}`)
128
- }
129
- } catch (err) {
130
- threw = true
131
- error = err
132
- }
133
-
134
- next = threw ? exportsGenerator.throw(error) : exportsGenerator.next(result)
97
+ async function resolveModule (specifier, context, resolver) {
98
+ const url = new URL(await resolver.resolve(specifier, context.parentURL))
99
+ if (url.protocol === 'node:') return { format: 'builtin', url }
100
+ if (url.protocol !== 'file:') throw new Error(`Unsupported ESM resolution URL: ${url.href}`)
101
+
102
+ const resolved = fileURLToPath(url)
103
+ if (resolved.endsWith('.node')) {
104
+ throw new Error(`Unsupported ESM analysis target: ${resolved}`)
135
105
  }
136
- return next.value
106
+ const format = isESMFile(resolved) ? 'module' : 'commonjs'
107
+ return { format, url }
137
108
  }
138
109
 
139
110
  /**
@@ -144,16 +115,72 @@ function driveGetExportsGenerator (exportsGenerator, getSource) {
144
115
  * @param {boolean} [moduleData.internal]
145
116
  * @param {object} moduleData.context
146
117
  * @param {boolean} [moduleData.excludeDefault]
118
+ * @param {Map<string, string>} [moduleData.moduleSources]
119
+ * @param {EsmResolver} [moduleData.resolver]
120
+ * @param {(source: string, options: { loader: 'ts' }) => { code: string }} [moduleData.transform]
121
+ * @param {Set<string>} [activeModules]
147
122
  * @returns {Promise<Map>}
148
123
  */
149
- async function processModule ({ path, internal = false, context, excludeDefault = false }) {
150
- let exportNames, srcUrl
124
+ async function processModule (
125
+ { path, internal = false, context, excludeDefault = false, moduleSources = new Map(), resolver, transform },
126
+ activeModules
127
+ ) {
128
+ const ownsResolver = resolver === undefined
129
+ resolver ??= createEsmResolver()
130
+ try {
131
+ return await processModuleWithResolver(
132
+ { path, internal, context, excludeDefault, moduleSources, transform },
133
+ activeModules,
134
+ resolver
135
+ )
136
+ } finally {
137
+ if (ownsResolver) await resolver.close()
138
+ }
139
+ }
140
+
141
+ /**
142
+ * @param {object} moduleData
143
+ * @param {string} moduleData.path
144
+ * @param {boolean} moduleData.internal
145
+ * @param {object} moduleData.context
146
+ * @param {boolean} moduleData.excludeDefault
147
+ * @param {Map<string, string>} moduleData.moduleSources
148
+ * @param {(source: string, options: { loader: 'ts' }) => { code: string }} [moduleData.transform]
149
+ * @param {Set<string>} [activeModules]
150
+ * @param {EsmResolver} resolver
151
+ * @returns {Promise<Map>}
152
+ */
153
+ async function processModuleWithResolver (
154
+ { path, internal, context, excludeDefault, moduleSources, transform },
155
+ activeModules,
156
+ resolver
157
+ ) {
158
+ let moduleExports, srcUrl
151
159
  if (internal) {
152
160
  // we can not read and parse of internal modules
153
- exportNames = await getExportsImporting(path)
161
+ moduleExports = { exportNames: await getExportsImporting(path) }
154
162
  } else {
163
+ context = { ...context, format: getModuleFormat(path, context.format) }
155
164
  srcUrl = pathToFileURL(path)
156
- exportNames = await getExports(srcUrl, context, getSource)
165
+ const readSource = (url) => {
166
+ const modulePath = fileURLToPath(url)
167
+ let source = moduleSources.get(modulePath)
168
+ if (source === undefined) {
169
+ source = fs.readFileSync(modulePath, 'utf8')
170
+ moduleSources.set(modulePath, source)
171
+ }
172
+ return source
173
+ }
174
+ const loadSource = (url, { format }) => {
175
+ let source = readSource(url)
176
+ if (transform && (format === 'module-typescript' || format === 'commonjs-typescript')) {
177
+ source = transform(source, { loader: 'ts' }).code
178
+ format = format === 'module-typescript' ? 'module' : 'commonjs'
179
+ }
180
+ return { format, source }
181
+ }
182
+ readSource(srcUrl)
183
+ moduleExports = await getExports(srcUrl, context, loadSource, resolver)
157
184
  }
158
185
 
159
186
  const starExports = new Set()
@@ -186,43 +213,31 @@ async function processModule ({ path, internal = false, context, excludeDefault
186
213
  }
187
214
  }
188
215
 
189
- for (const n of exportNames) {
190
- if (n === 'default' && excludeDefault) continue
216
+ let starReexports = moduleExports.starReexports
217
+ for (const n of moduleExports.exportNames) {
218
+ const isDefault = n === 'default' || (
219
+ n === 'module.exports' &&
220
+ moduleExports.hasModuleExportsCJSDefault &&
221
+ (context.format === 'commonjs' || context.format === 'commonjs-typescript')
222
+ )
223
+ if (isDefault && excludeDefault) continue
191
224
 
192
225
  if (isStarExportLine(n)) {
193
- // export * from 'wherever'
194
- const [, modFile] = n.split('* from ')
195
-
196
- // Relative paths need to be resolved relative to the parent module
197
- const newSpecifier = isBareSpecifier(modFile) ? modFile : new URL(modFile, srcUrl).href
198
- // We need to call `parentResolve` to resolve bare specifiers to a full
199
- // URL. We also need to call `parentResolve` for all sub-modules to get
200
- // the `format`. We can't rely on the parents `format` to know if this
201
- // sub-module is ESM or CJS!
226
+ starReexports ??= []
227
+ starReexports.push({ parentURL: srcUrl.href, specifier: n.slice('* from '.length) })
228
+ continue
229
+ }
202
230
 
203
- const result = resolve(newSpecifier, { parentURL: srcUrl })
231
+ const variableName = `$dd${Buffer.from(n).toString('hex')}`
232
+ const objectKey = JSON.stringify(n)
233
+ const reExportedName = n === 'default' ? n : objectKey
204
234
 
205
- // eslint-disable-next-line no-await-in-loop
206
- const subSetters = await processModule({
207
- path: fileURLToPath(result.url),
208
- context: { ...context, format: result.format },
209
- excludeDefault: true,
210
- })
211
-
212
- for (const [name, setter] of subSetters.entries()) {
213
- addSetter(name, setter, true)
214
- }
215
- } else {
216
- const variableName = `$${n.replaceAll(/[^a-zA-Z0-9_$]/g, '_')}`
217
- const objectKey = JSON.stringify(n)
218
- const reExportedName = n === 'default' ? n : objectKey
219
-
220
- addSetter(n, `
235
+ addSetter(n, `
221
236
  let ${variableName}
222
237
  try {
223
238
  ${variableName} = _[${objectKey}] = namespace[${objectKey}]
224
- } catch (err) {
225
- if (!(err instanceof ReferenceError)) throw err
239
+ } catch (error) {
240
+ if (!(error instanceof ReferenceError)) throw error
226
241
  }
227
242
  export { ${variableName} as ${reExportedName} }
228
243
  set[${objectKey}] = (v) => {
@@ -231,6 +246,34 @@ async function processModule ({ path, internal = false, context, excludeDefault
231
246
  }
232
247
  get[${objectKey}] = () => ${variableName}
233
248
  `)
249
+ }
250
+
251
+ if (starReexports) {
252
+ for (const { parentURL, specifier } of starReexports) {
253
+ const baseUrl = new URL(parentURL)
254
+ const resolvedSpecifier = isBareSpecifier(specifier) ? specifier : new URL(specifier, baseUrl).href
255
+ // The runtime's import conditions and the declaring module's URL own star-export resolution.
256
+ // eslint-disable-next-line no-await-in-loop
257
+ const result = await resolveModule(resolvedSpecifier, { parentURL: baseUrl }, resolver)
258
+
259
+ activeModules ??= new Set([srcUrl.href])
260
+ if (activeModules.has(result.url.href)) continue
261
+ activeModules.add(result.url.href)
262
+
263
+ // eslint-disable-next-line no-await-in-loop
264
+ const subSetters = await processModuleWithResolver({
265
+ path: result.format === 'builtin' ? result.url.href : fileURLToPath(result.url),
266
+ internal: result.format === 'builtin',
267
+ context: { ...context, format: result.format },
268
+ excludeDefault: true,
269
+ moduleSources,
270
+ transform,
271
+ }, activeModules, resolver)
272
+ activeModules.delete(result.url.href)
273
+
274
+ for (const [name, setter] of subSetters.entries()) {
275
+ addSetter(name, setter, true)
276
+ }
234
277
  }
235
278
  }
236
279
 
@@ -243,11 +286,10 @@ async function processModule ({ path, internal = false, context, excludeDefault
243
286
  * @param {string} fullPathToModule File to analize
244
287
  * @param {string} [modulePackageJsonPath] Path of the package.json
245
288
  * @param {object} [packageJson] The content of the module package.json
246
- * @returns {boolean}
247
289
  */
248
290
  function isESMFile (fullPathToModule, modulePackageJsonPath, packageJson = {}) {
249
- if (fullPathToModule.endsWith('.mjs')) return true
250
- if (fullPathToModule.endsWith('.cjs')) return false
291
+ if (fullPathToModule.endsWith('.mjs') || fullPathToModule.endsWith('.mts')) return true
292
+ if (fullPathToModule.endsWith('.cjs') || fullPathToModule.endsWith('.cts')) return false
251
293
 
252
294
  const pathParts = fullPathToModule.split(path.sep)
253
295
  do {
@@ -271,6 +313,6 @@ function isESMFile (fullPathToModule, modulePackageJsonPath, packageJson = {}) {
271
313
  }
272
314
 
273
315
  module.exports = {
274
- processModule,
275
316
  isESMFile,
317
+ processModule,
276
318
  }
@@ -8,6 +8,7 @@ const {
8
8
  } = require('./helpers/instrument')
9
9
 
10
10
  const ch = tracingChannel('apm:aerospike:command')
11
+ const kTracingCallbackCommand = Symbol('datadog.aerospike.tracing_callback_command')
11
12
 
12
13
  function wrapCreateCommand (createCommand) {
13
14
  if (typeof createCommand !== 'function') return createCommand
@@ -17,27 +18,48 @@ function wrapCreateCommand (createCommand) {
17
18
 
18
19
  if (!CommandClass) return CommandClass
19
20
 
21
+ shimmer.wrap(CommandClass.prototype, 'executeWithCallback', wrapExecuteWithCallback)
20
22
  shimmer.wrap(CommandClass.prototype, 'process', wrapProcess)
21
23
 
22
24
  return CommandClass
23
25
  }
24
26
  }
25
27
 
26
- function wrapProcess (process) {
28
+ function wrapExecuteWithCallback (executeWithCallback) {
27
29
  return function (...args) {
28
30
  const cb = args[0]
29
- if (typeof cb !== 'function') return process.apply(this, args)
31
+ if (!ch.start.hasSubscribers || typeof cb !== 'function') return executeWithCallback.apply(this, args)
30
32
 
31
- const ctx = {
32
- commandName: this.constructor.name,
33
- commandArgs: this.args,
34
- clientConfig: this.client.config,
33
+ this[kTracingCallbackCommand] = true
34
+ try {
35
+ return ch.traceCallback(executeWithCallback, 0, getContext(this), this, ...args)
36
+ } finally {
37
+ this[kTracingCallbackCommand] = false
35
38
  }
39
+ }
40
+ }
41
+
42
+ function wrapProcess (process) {
43
+ return function (...args) {
44
+ const cb = args[0]
45
+ if (!ch.start.hasSubscribers || typeof cb !== 'function') return process.apply(this, args)
46
+
47
+ if (this[kTracingCallbackCommand]) return process.apply(this, args)
48
+
49
+ const ctx = getContext(this)
36
50
 
37
51
  return ch.traceCallback(process, -1, ctx, this, ...args)
38
52
  }
39
53
  }
40
54
 
55
+ function getContext (command) {
56
+ return {
57
+ commandName: command.constructor.name,
58
+ commandArgs: command.args,
59
+ clientConfig: command.client.config,
60
+ }
61
+ }
62
+
41
63
  addHook({
42
64
  name: 'aerospike',
43
65
  file: 'lib/commands/command.js',
@@ -6,112 +6,48 @@ const { addHook, getHooks } = require('./helpers/instrument')
6
6
 
7
7
  const vercelAiTracingChannel = tracingChannel('dd-trace:vercel-ai')
8
8
  const vercelAiSpanSetAttributesChannel = channel('dd-trace:vercel-ai:span:setAttributes')
9
- const doGenerateBeforeChannel = channel('dd-trace:vercel-ai:doGenerate:before')
10
- const doGenerateAfterChannel = channel('dd-trace:vercel-ai:doGenerate:after')
11
- const doStreamBeforeChannel = channel('dd-trace:vercel-ai:doStream:before')
12
- const doStreamAfterChannel = channel('dd-trace:vercel-ai:doStream:after')
13
9
 
14
- const tracers = new WeakSet()
15
- const wrappedModels = new WeakSet()
10
+ // Published synchronously per model call with the native call data. A subscriber may set either
11
+ // callback and this instrumentation applies it, so the wrapping stays here and only the policy
12
+ // lives outside:
13
+ // beforeResult () => Promise<void>|undefined holds the result back until it settles
14
+ // onResult (result) => unknown|Promise<unknown> inspects or replaces the delivered result
15
+ const modelInterceptChannel = channel('dd-trace:vercel-ai:model:intercept')
16
16
 
17
- /**
18
- * Publishes a provider-native lifecycle payload to a cancelable lifecycle channel.
19
- *
20
- * Subscribers push async work into `pending` synchronously during publication and
21
- * abort `abortController` with an error before the pushed promise resolves to block.
22
- *
23
- * @param {object} lifecycleChannel
24
- * @param {object} payload
25
- * @returns {Promise<void>}
26
- */
27
- function publishLifecycle (lifecycleChannel, payload) {
28
- const abortController = new AbortController()
29
- const ctx = { ...payload, abortController, pending: [] }
17
+ const INTERCEPTED_MODEL_METHODS = ['doGenerate', 'doStream']
30
18
 
31
- lifecycleChannel.publish(ctx)
32
-
33
- return Promise.all(ctx.pending).then(() => {
34
- if (abortController.signal.aborted) {
35
- throw abortController.signal.reason
36
- }
37
- })
38
- }
19
+ const tracers = new WeakSet()
20
+ const wrappedModels = new WeakSet()
39
21
 
40
22
  /**
41
- * Wraps a Vercel AI language model's doGenerate and doStream lifecycle methods.
23
+ * Wraps a language model's call methods so subscribers can interpose on each call.
42
24
  *
43
- * @param {object} model - A Vercel AI language model instance
25
+ * @param {object} model
44
26
  */
45
- function wrapModelWithLifecycle (model) {
27
+ function wrapModel (model) {
46
28
  if (!model || wrappedModels.has(model)) return
47
29
  wrappedModels.add(model)
48
30
 
49
- if (typeof model.doGenerate === 'function') {
50
- shimmer.wrap(model, 'doGenerate', function (original) {
51
- return function (options) {
52
- const originalResult = original.call(this, options)
31
+ for (const method of INTERCEPTED_MODEL_METHODS) {
32
+ if (typeof model[method] !== 'function') continue
53
33
 
54
- if (!doGenerateBeforeChannel.hasSubscribers && !doGenerateAfterChannel.hasSubscribers) return originalResult
55
- if (!options.prompt?.length) return originalResult
34
+ shimmer.wrap(model, method, original => function (...args) {
35
+ const result = original.apply(this, args)
36
+ if (!modelInterceptChannel.hasSubscribers) return result
56
37
 
57
- const beforeEvaluation = doGenerateBeforeChannel.hasSubscribers
58
- ? publishLifecycle(doGenerateBeforeChannel, { prompt: options.prompt, options })
59
- : Promise.resolve()
38
+ const interceptCtx = { method, arguments: args }
39
+ modelInterceptChannel.publish(interceptCtx)
60
40
 
61
- return Promise.all([beforeEvaluation, originalResult])
62
- .then(([, result]) => {
63
- if (!doGenerateAfterChannel.hasSubscribers || !result.content?.length) return result
64
- const payload = { prompt: options.prompt, options, result }
65
- return publishLifecycle(doGenerateAfterChannel, payload).then(() => result)
66
- })
67
- }
68
- })
69
- }
41
+ if (!interceptCtx.beforeResult && !interceptCtx.onResult) return result
70
42
 
71
- if (typeof model.doStream === 'function') {
72
- shimmer.wrap(model, 'doStream', function (original) {
73
- return function (options) {
74
- const originalResult = original.call(this, options)
75
-
76
- if (!doStreamBeforeChannel.hasSubscribers && !doStreamAfterChannel.hasSubscribers) return originalResult
77
- if (!options.prompt?.length) return originalResult
78
-
79
- const beforeEvaluation = doStreamBeforeChannel.hasSubscribers
80
- ? publishLifecycle(doStreamBeforeChannel, { prompt: options.prompt, options })
81
- : Promise.resolve()
82
-
83
- return Promise.all([beforeEvaluation, originalResult])
84
- .then(([, result]) => {
85
- if (!doStreamAfterChannel.hasSubscribers) return result
86
-
87
- const chunks = []
88
- const reader = result.stream.getReader()
89
-
90
- function readAll () {
91
- return reader.read().then(({ done, value }) => {
92
- if (done) return
93
- chunks.push(value)
94
- return readAll()
95
- })
96
- }
97
-
98
- return readAll().then(() => {
99
- return publishLifecycle(doStreamAfterChannel, { prompt: options.prompt, options, chunks })
100
- .then(() => {
101
- // eslint-disable-next-line n/no-unsupported-features/node-builtins
102
- const stream = new ReadableStream({
103
- start (controller) {
104
- for (const chunk of chunks) {
105
- controller.enqueue(chunk)
106
- }
107
- controller.close()
108
- },
109
- })
110
- return { ...result, stream }
111
- })
112
- })
113
- })
114
- }
43
+ // A model may return any thenable, so normalize before attaching handlers.
44
+ const settled = Promise.resolve(result)
45
+ // The interceptor's rejection wins over an earlier SDK rejection.
46
+ settled.catch(() => {})
47
+
48
+ return Promise.resolve(interceptCtx.beforeResult?.())
49
+ .then(() => settled)
50
+ .then(value => (interceptCtx.onResult ? interceptCtx.onResult(value) : value))
115
51
  })
116
52
  }
117
53
  }
@@ -209,7 +145,9 @@ function wrapTracer (tracer) {
209
145
  })
210
146
  }
211
147
 
212
- for (const hook of getHooks('ai')) {
148
+ let orchestrionSubscribed = false
149
+
150
+ for (const hook of getHooks('ai').values()) {
213
151
  if (hook.file === 'dist/index.js') {
214
152
  // if not removed, the below hook will never match correctly
215
153
  // however, it is still needed in the orchestrion definition
@@ -217,6 +155,9 @@ for (const hook of getHooks('ai')) {
217
155
  }
218
156
 
219
157
  addHook(hook, exports => {
158
+ if (orchestrionSubscribed) return exports
159
+ orchestrionSubscribed = true
160
+
220
161
  const getTracerChannel = tracingChannel('orchestrion:ai:getTracer')
221
162
  getTracerChannel.subscribe({
222
163
  end (ctx) {
@@ -258,11 +199,14 @@ for (const hook of getHooks('ai')) {
258
199
  tracingChannel('orchestrion:ai:resolveLanguageModel').subscribe({
259
200
  end (ctx) {
260
201
  const model = ctx.arguments[0]
202
+
203
+ // The SDK builds a model from a string id, in which case only the resolved instance is
204
+ // worth wrapping; when the caller passed an instance, that is the one the SDK calls.
261
205
  if (typeof model !== 'string' && model !== ctx.result) {
262
- wrapModelWithLifecycle(model)
206
+ wrapModel(model)
263
207
  wrappedModels.add(ctx.result)
264
208
  } else {
265
- wrapModelWithLifecycle(ctx.result)
209
+ wrapModel(ctx.result)
266
210
  }
267
211
  },
268
212
  })
@@ -315,5 +259,3 @@ addHook({ name: 'ai', versions: ['>=7.0.0'] }, exports => {
315
259
 
316
260
  return exports
317
261
  })
318
-
319
- module.exports = { wrapModelWithLifecycle }