dd-trace 5.135.0 → 5.136.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 (250) hide show
  1. package/ci/init.js +2 -22
  2. package/ext/exporters.js +0 -1
  3. package/index.d.ts +105 -5
  4. package/initialize.mjs +5 -2
  5. package/lambda.d.ts +39 -0
  6. package/lambda.js +3 -0
  7. package/package.json +11 -9
  8. package/packages/datadog-esbuild/index.js +8 -55
  9. package/packages/datadog-instrumentations/src/aws-lambda.js +88 -0
  10. package/packages/datadog-instrumentations/src/cucumber.js +5 -2
  11. package/packages/datadog-instrumentations/src/elevenlabs/activity.js +114 -0
  12. package/packages/datadog-instrumentations/src/elevenlabs/audio.js +104 -0
  13. package/packages/datadog-instrumentations/src/elevenlabs/index.js +288 -0
  14. package/packages/datadog-instrumentations/src/elevenlabs/session.js +444 -0
  15. package/packages/datadog-instrumentations/src/graphql.js +20 -17
  16. package/packages/{datadog-esbuild/src/utils.js → datadog-instrumentations/src/helpers/bundler-esm-exports.js} +282 -40
  17. package/packages/datadog-instrumentations/src/helpers/bundler-transform.js +573 -0
  18. package/packages/datadog-instrumentations/src/helpers/bundler-utils.js +104 -0
  19. package/packages/datadog-instrumentations/src/helpers/hook.js +29 -1
  20. package/packages/datadog-instrumentations/src/helpers/hooks.js +3 -7
  21. package/packages/datadog-instrumentations/src/helpers/lambda-handler.js +189 -0
  22. package/packages/datadog-instrumentations/src/helpers/rewriter/index.js +2 -0
  23. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentation-registry.js +18 -1
  24. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/async-mutex.js +41 -0
  25. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/elevenlabs.js +25 -0
  26. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/graphql.js +0 -36
  27. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/next.js +40 -0
  28. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/openai-agents-realtime.js +23 -0
  29. package/packages/datadog-instrumentations/src/helpers/rewriter/instrumentations/trpc.js +148 -0
  30. package/packages/datadog-instrumentations/src/helpers/rewriter/target-patterns.json +50 -0
  31. package/packages/datadog-instrumentations/src/helpers/rewriter/targets.json +17 -3
  32. package/packages/datadog-instrumentations/src/helpers/rewriter/transforms.js +59 -2
  33. package/packages/datadog-instrumentations/src/ioredis.js +101 -3
  34. package/packages/datadog-instrumentations/src/next.js +19 -6
  35. package/packages/datadog-instrumentations/src/openai-agents-realtime.js +149 -0
  36. package/packages/datadog-instrumentations/src/openai-realtime/audio-accumulator.js +27 -0
  37. package/packages/datadog-instrumentations/src/openai-realtime/index.js +17 -6
  38. package/packages/datadog-instrumentations/src/openai-realtime/server-playback.js +887 -0
  39. package/packages/datadog-instrumentations/src/openai-realtime/session.js +150 -25
  40. package/packages/datadog-instrumentations/src/openai-realtime/turns.js +29 -2
  41. package/packages/datadog-instrumentations/src/otel-sdk-trace.js +11 -9
  42. package/packages/datadog-instrumentations/src/webdriverio.js +12 -12
  43. package/packages/datadog-plugin-async-mutex/src/index.js +50 -0
  44. package/packages/datadog-plugin-aws-lambda/src/index.js +106 -0
  45. package/packages/datadog-plugin-cypress/src/cypress-plugin.js +22 -11
  46. package/packages/datadog-plugin-elevenlabs/src/index.js +69 -0
  47. package/packages/datadog-plugin-google-cloud-pubsub/src/consumer.js +10 -7
  48. package/packages/datadog-plugin-google-cloud-pubsub/src/producer.js +19 -52
  49. package/packages/datadog-plugin-google-cloud-pubsub/src/pubsub-push-subscription.js +4 -2
  50. package/packages/datadog-plugin-google-cloud-pubsub/src/pubsub-request-context.js +25 -4
  51. package/packages/datadog-plugin-http/src/client.js +32 -9
  52. package/packages/datadog-plugin-http2/src/client.js +38 -13
  53. package/packages/datadog-plugin-next/src/index.js +112 -14
  54. package/packages/datadog-plugin-prisma/src/datadog-tracing-helper.js +5 -3
  55. package/packages/datadog-plugin-trpc/src/index.js +15 -0
  56. package/packages/datadog-plugin-trpc/src/procedure.js +48 -0
  57. package/packages/datadog-plugin-trpc/src/request.js +81 -0
  58. package/packages/datadog-plugin-undici/src/index.js +22 -7
  59. package/packages/datadog-turbopack/index.js +4 -28
  60. package/packages/datadog-turbopack/src/loader.js +14 -452
  61. package/packages/datadog-webpack/index.js +3 -55
  62. package/packages/dd-trace/src/aiguard/evaluation.js +62 -1
  63. package/packages/dd-trace/src/aiguard/sdk.js +8 -2
  64. package/packages/dd-trace/src/aiguard/tags.js +2 -0
  65. package/packages/dd-trace/src/appsec/blocking/index.js +4 -0
  66. package/packages/dd-trace/src/appsec/graphql.js +91 -6
  67. package/packages/dd-trace/src/appsec/recommended.json +1287 -90
  68. package/packages/dd-trace/src/before-exit.js +32 -0
  69. package/packages/dd-trace/src/bootstrap.js +5 -3
  70. package/packages/dd-trace/src/ci-visibility/early-flake-detection/get-known-tests.js +15 -2
  71. package/packages/dd-trace/src/ci-visibility/exporters/ci-visibility-exporter.js +12 -34
  72. package/packages/dd-trace/src/ci-visibility/exporters/git/git_metadata.js +41 -13
  73. package/packages/dd-trace/src/ci-visibility/exporters/request.js +2 -3
  74. package/packages/dd-trace/src/ci-visibility/intelligent-test-runner/get-skippable-suites.js +1 -2
  75. package/packages/dd-trace/src/ci-visibility/requests/get-library-configuration.js +1 -1
  76. package/packages/dd-trace/src/ci-visibility/telemetry.js +6 -0
  77. package/packages/dd-trace/src/ci-visibility/test-management/get-test-management-tests.js +1 -1
  78. package/packages/dd-trace/src/ci-visibility/test-optimization-http-cache-schema.js +9 -134
  79. package/packages/dd-trace/src/ci-visibility/test-optimization-http-cache.js +11 -156
  80. package/packages/dd-trace/src/config/config-types.d.ts +3 -0
  81. package/packages/dd-trace/src/config/defaults.js +5 -0
  82. package/packages/dd-trace/src/config/generated-config-types.d.ts +42 -2
  83. package/packages/dd-trace/src/config/index.js +17 -5
  84. package/packages/dd-trace/src/config/parsers.js +9 -0
  85. package/packages/dd-trace/src/config/supported-configurations.json +158 -4
  86. package/packages/dd-trace/src/constants.js +1 -0
  87. package/packages/dd-trace/src/debugger/pause-duration-histogram.js +2 -1
  88. package/packages/dd-trace/src/exporter.js +0 -11
  89. package/packages/dd-trace/src/exporters/common/request.js +81 -48
  90. package/packages/dd-trace/src/exporters/common/retry.js +12 -7
  91. package/packages/dd-trace/src/exporters/common/url.js +1 -1
  92. package/packages/dd-trace/src/id.js +1 -1
  93. package/packages/dd-trace/src/lambda/facade.js +74 -0
  94. package/packages/dd-trace/src/lambda/handler.js +3 -41
  95. package/packages/dd-trace/src/lambda/index.js +38 -15
  96. package/packages/dd-trace/src/lambda/runtime/patch.js +19 -3
  97. package/packages/dd-trace/src/lambda/wrap.js +44 -0
  98. package/packages/dd-trace/src/llmobs/constants/tags.js +2 -0
  99. package/packages/dd-trace/src/llmobs/experiments/experiment.js +10 -5
  100. package/packages/dd-trace/src/llmobs/plugins/elevenlabs.js +96 -0
  101. package/packages/dd-trace/src/llmobs/plugins/genai/util.js +19 -6
  102. package/packages/dd-trace/src/llmobs/plugins/openai/realtime.js +38 -11
  103. package/packages/dd-trace/src/llmobs/plugins/vertexai.js +10 -2
  104. package/packages/dd-trace/src/llmobs/sdk.js +19 -0
  105. package/packages/dd-trace/src/llmobs/span_processor.js +9 -0
  106. package/packages/dd-trace/src/llmobs/tagger.js +22 -0
  107. package/packages/dd-trace/src/log/channels.js +4 -0
  108. package/packages/dd-trace/src/log/writer.js +6 -1
  109. package/packages/dd-trace/src/openfeature/agentless_configuration_source.js +4 -0
  110. package/packages/dd-trace/src/openfeature/configuration_source.js +35 -27
  111. package/packages/dd-trace/src/openfeature/flag-selection.js +152 -0
  112. package/packages/dd-trace/src/openfeature/flagging_provider.js +19 -1
  113. package/packages/dd-trace/src/openfeature/writers/base.js +1 -3
  114. package/packages/dd-trace/src/opentelemetry/logs/index.js +11 -0
  115. package/packages/dd-trace/src/opentelemetry/logs/otlp_http_log_exporter.js +1 -1
  116. package/packages/dd-trace/src/opentelemetry/metrics/index.js +7 -1
  117. package/packages/dd-trace/src/opentelemetry/metrics/otlp_http_metric_exporter.js +1 -1
  118. package/packages/dd-trace/src/opentelemetry/metrics/otlp_span_stats_exporter.js +4 -1
  119. package/packages/dd-trace/src/opentelemetry/otlp/otlp_http_exporter_base.js +19 -1
  120. package/packages/dd-trace/src/opentelemetry/span-ending-hook.js +5 -1
  121. package/packages/dd-trace/src/opentelemetry/span-helpers.js +6 -1
  122. package/packages/dd-trace/src/opentelemetry/span.js +2 -2
  123. package/packages/dd-trace/src/opentelemetry/startup-config.js +174 -0
  124. package/packages/dd-trace/src/opentelemetry/trace/otlp_http_trace_exporter.js +1 -1
  125. package/packages/dd-trace/src/opentelemetry/trace/otlp_transformer.js +7 -1
  126. package/packages/dd-trace/src/opentracing/propagation/tracestate.js +77 -23
  127. package/packages/dd-trace/src/opentracing/tracer.js +24 -0
  128. package/packages/dd-trace/src/otel-thread-ctx.js +28 -31
  129. package/packages/dd-trace/src/plugin_manager.js +34 -7
  130. package/packages/dd-trace/src/plugins/ci_plugin.js +41 -10
  131. package/packages/dd-trace/src/plugins/index.js +6 -0
  132. package/packages/dd-trace/src/plugins/plugin.js +4 -2
  133. package/packages/dd-trace/src/plugins/tracing.js +1 -1
  134. package/packages/dd-trace/src/plugins/util/ci.js +18 -1
  135. package/packages/dd-trace/src/plugins/util/git-cache.js +4 -4
  136. package/packages/dd-trace/src/plugins/util/git.js +263 -82
  137. package/packages/dd-trace/src/plugins/util/http-otel-semantics.js +75 -46
  138. package/packages/dd-trace/src/plugins/util/inferred_proxy.js +12 -4
  139. package/packages/dd-trace/src/plugins/util/status-validator.js +23 -10
  140. package/packages/dd-trace/src/plugins/util/tags.js +6 -0
  141. package/packages/dd-trace/src/plugins/util/test.js +64 -39
  142. package/packages/dd-trace/src/plugins/util/url.js +10 -2
  143. package/packages/dd-trace/src/plugins/util/user-provided-git.js +2 -2
  144. package/packages/dd-trace/src/plugins/util/web.js +65 -10
  145. package/packages/dd-trace/src/profiling/webspan-utils.js +6 -5
  146. package/packages/dd-trace/src/proxy.js +33 -53
  147. package/packages/dd-trace/src/span_processor.js +20 -0
  148. package/packages/dd-trace/src/startup-log.js +8 -6
  149. package/packages/dd-trace/src/telemetry/metrics.js +2 -1
  150. package/packages/dd-trace/src/tracer.js +0 -2
  151. package/packages/dd-trace/src/web-tags-cache.js +8 -9
  152. package/register.js +2 -1
  153. package/vendor/dist/@apm-js-collab/code-transformer/LICENSE +489 -0
  154. package/vendor/dist/@datadog/flagging-core/LICENSE +221 -0
  155. package/vendor/dist/@datadog/flagging-core/index.js +1 -0
  156. package/vendor/dist/@datadog/openfeature-node-server/LICENSE +21 -1
  157. package/vendor/dist/@datadog/openfeature-node-server/rules-based/LICENSE +3 -1
  158. package/vendor/dist/@datadog/sketches-js/LICENSE +263 -0
  159. package/vendor/dist/@datadog/source-map/LICENSE +1 -0
  160. package/vendor/dist/@isaacs/ttlcache/LICENSE +13 -0
  161. package/vendor/dist/@opentelemetry/core/LICENSE +209 -1
  162. package/vendor/dist/crypto-randomuuid/LICENSE +3 -0
  163. package/vendor/dist/escape-string-regexp/LICENSE +13 -0
  164. package/vendor/dist/esquery/LICENSE +2 -0
  165. package/vendor/dist/https-proxy-agent/LICENSE +80 -1
  166. package/vendor/dist/istanbul-lib-coverage/LICENSE +2 -0
  167. package/vendor/dist/jest-docblock/LICENSE +16 -0
  168. package/vendor/dist/jsonpath-plus/LICENSE +13 -0
  169. package/vendor/dist/limiter/LICENSE +2 -0
  170. package/vendor/dist/lodash.sortby/LICENSE +2 -0
  171. package/vendor/dist/lru-cache/LICENSE +13 -0
  172. package/vendor/dist/meriyah/LICENSE +13 -0
  173. package/vendor/dist/module-details-from-path/LICENSE +2 -0
  174. package/vendor/dist/mutexify/promise/LICENSE +28 -0
  175. package/vendor/dist/pprof-format/LICENSE +13 -0
  176. package/vendor/dist/pprof-format/index.js +1 -1
  177. package/vendor/dist/protobufjs/LICENSE +219 -0
  178. package/vendor/dist/protobufjs/minimal/LICENSE +219 -0
  179. package/vendor/dist/proxy-from-env/LICENSE +13 -0
  180. package/vendor/dist/retry/LICENSE +2 -0
  181. package/vendor/dist/rfdc/LICENSE +2 -0
  182. package/vendor/dist/semifies/LICENSE +3 -1
  183. package/vendor/dist/shell-quote/LICENSE +3 -1
  184. package/vendor/dist/source-map/LICENSE +1 -0
  185. package/vendor/dist/source-map/lib/util/LICENSE +1 -0
  186. package/vendor/dist/tlhunter-sorted-set/LICENSE +2 -0
  187. package/vendor/dist/ttl-set/LICENSE +28 -0
  188. package/ci/diagnose.js +0 -2215
  189. package/ci/runbook.md +0 -299
  190. package/ci/test-optimization-validation/approval-artifacts.js +0 -175
  191. package/ci/test-optimization-validation/approval.js +0 -386
  192. package/ci/test-optimization-validation/artifact-id.js +0 -18
  193. package/ci/test-optimization-validation/blocker-category.js +0 -24
  194. package/ci/test-optimization-validation/bounded-json.js +0 -120
  195. package/ci/test-optimization-validation/ci-command-candidate.js +0 -77
  196. package/ci/test-optimization-validation/ci-discovery.js +0 -192
  197. package/ci/test-optimization-validation/ci-package-scripts.js +0 -169
  198. package/ci/test-optimization-validation/ci-remediation.js +0 -283
  199. package/ci/test-optimization-validation/cli.js +0 -954
  200. package/ci/test-optimization-validation/command-blocker.js +0 -377
  201. package/ci/test-optimization-validation/command-output-policy.js +0 -188
  202. package/ci/test-optimization-validation/command-runner.js +0 -649
  203. package/ci/test-optimization-validation/environment.js +0 -88
  204. package/ci/test-optimization-validation/executable-approval.js +0 -47
  205. package/ci/test-optimization-validation/executable.js +0 -244
  206. package/ci/test-optimization-validation/execution-lock.js +0 -70
  207. package/ci/test-optimization-validation/framework-adapters/cucumber-validation.json +0 -3
  208. package/ci/test-optimization-validation/framework-adapters/cucumber.js +0 -767
  209. package/ci/test-optimization-validation/framework-adapters/cypress.js +0 -99
  210. package/ci/test-optimization-validation/framework-adapters/playwright.js +0 -175
  211. package/ci/test-optimization-validation/framework-adapters/vitest.js +0 -513
  212. package/ci/test-optimization-validation/generated-file-policy.js +0 -63
  213. package/ci/test-optimization-validation/generated-files.js +0 -425
  214. package/ci/test-optimization-validation/generated-test-contract.js +0 -284
  215. package/ci/test-optimization-validation/generated-verifier.js +0 -235
  216. package/ci/test-optimization-validation/literal-environment.js +0 -56
  217. package/ci/test-optimization-validation/literal-glob.js +0 -52
  218. package/ci/test-optimization-validation/manifest-loader.js +0 -116
  219. package/ci/test-optimization-validation/manifest-scaffold.js +0 -1276
  220. package/ci/test-optimization-validation/manifest-schema.js +0 -695
  221. package/ci/test-optimization-validation/offline-fixtures.js +0 -335
  222. package/ci/test-optimization-validation/offline-output.js +0 -406
  223. package/ci/test-optimization-validation/package-check.js +0 -97
  224. package/ci/test-optimization-validation/payload-normalizer.js +0 -72
  225. package/ci/test-optimization-validation/plan-writer.js +0 -541
  226. package/ci/test-optimization-validation/preflight-runner.js +0 -186
  227. package/ci/test-optimization-validation/project-build-artifact.js +0 -31
  228. package/ci/test-optimization-validation/redaction.js +0 -319
  229. package/ci/test-optimization-validation/report-writer.js +0 -666
  230. package/ci/test-optimization-validation/result-semantics.js +0 -103
  231. package/ci/test-optimization-validation/runner-command.js +0 -264
  232. package/ci/test-optimization-validation/runner-contract.js +0 -695
  233. package/ci/test-optimization-validation/safe-files.js +0 -202
  234. package/ci/test-optimization-validation/scenarios/auto-test-retries.js +0 -171
  235. package/ci/test-optimization-validation/scenarios/basic-reporting.js +0 -407
  236. package/ci/test-optimization-validation/scenarios/ci-wiring.js +0 -666
  237. package/ci/test-optimization-validation/scenarios/early-flake-detection.js +0 -142
  238. package/ci/test-optimization-validation/scenarios/helpers.js +0 -621
  239. package/ci/test-optimization-validation/scenarios/test-management.js +0 -219
  240. package/ci/test-optimization-validation/source-text.js +0 -84
  241. package/ci/test-optimization-validation/static-diagnosis.js +0 -166
  242. package/ci/test-optimization-validation/test-output.js +0 -120
  243. package/ci/test-optimization-validation/validation-blocker.js +0 -21
  244. package/ci/validate-test-optimization.js +0 -3
  245. package/packages/datadog-esbuild/src/resolver.js +0 -284
  246. package/packages/dd-trace/src/ci-visibility/exporters/ci-validation/index.js +0 -156
  247. package/packages/dd-trace/src/ci-visibility/exporters/ci-validation/msgpack-to-json.js +0 -287
  248. package/packages/dd-trace/src/ci-visibility/exporters/ci-validation/payload-projection.js +0 -84
  249. package/packages/dd-trace/src/ci-visibility/exporters/ci-validation/sink.js +0 -368
  250. package/packages/dd-trace/src/ci-visibility/exporters/ci-validation/writer.js +0 -59
@@ -0,0 +1,114 @@
1
+ 'use strict'
2
+
3
+ // Silence is inferred only between recent provider observations. Unknown samples stay active.
4
+ class SpeechActivity {
5
+ #silence = []
6
+ /** @type {number | undefined} */
7
+ #lastOffset = undefined
8
+ /** @type {number | undefined} */
9
+ #lastReceived = undefined
10
+ #speaking = true
11
+ #overflow = false
12
+
13
+ /**
14
+ * @param {number} start
15
+ * @param {number} end
16
+ */
17
+ addSilence (start, end) {
18
+ start = Math.max(0, start)
19
+ if (end <= start || this.#overflow) return
20
+ const last = this.#silence.at(-1)
21
+ if (last && start <= last[1]) last[1] = Math.max(end, last[1])
22
+ else if (this.#silence.length < 128) this.#silence.push([start, end])
23
+ else {
24
+ this.#silence = []
25
+ this.#overflow = true
26
+ }
27
+ }
28
+
29
+ /**
30
+ * @param {unknown} score
31
+ * @param {number} offset
32
+ * @param {number} now
33
+ */
34
+ observe (score, offset, now) {
35
+ if (typeof score !== 'number' || !Number.isFinite(score) || score < 0 || score > 1) return
36
+ if (this.#lastOffset !== undefined && this.#lastReceived !== undefined) {
37
+ if (offset < this.#lastOffset || now < this.#lastReceived) return
38
+ if (!this.#speaking && now - this.#lastReceived <= 500) {
39
+ this.addSilence(this.#lastOffset, Math.min(offset, this.#lastOffset + 500))
40
+ }
41
+ if (offset - this.#lastOffset > 500 || now - this.#lastReceived > 500) this.#speaking = true
42
+ }
43
+ this.#lastOffset = offset
44
+ this.#lastReceived = now
45
+ if (score >= 0.5) this.#speaking = true
46
+ else if (score <= 0.35) this.#speaking = false
47
+ }
48
+
49
+ /** @param {number} duration */
50
+ continueAt (duration) {
51
+ const next = new SpeechActivity()
52
+ if (this.#lastOffset !== undefined && this.#lastReceived !== undefined) {
53
+ next.#lastOffset = this.#lastOffset - duration
54
+ next.#lastReceived = this.#lastReceived
55
+ next.#speaking = this.#speaking
56
+ }
57
+ return next
58
+ }
59
+
60
+ /**
61
+ * @param {number} duration
62
+ * @param {number | undefined} lastAudio
63
+ */
64
+ extendSilence (duration, lastAudio) {
65
+ if (!this.#speaking && this.#lastOffset !== undefined && this.#lastReceived !== undefined &&
66
+ lastAudio !== undefined &&
67
+ lastAudio - this.#lastReceived <= 500) {
68
+ this.addSilence(this.#lastOffset, Math.min(duration, this.#lastOffset + 500))
69
+ }
70
+ }
71
+
72
+ /**
73
+ * @param {SpeechActivity} other
74
+ * @param {number} duration
75
+ * @param {number | undefined} lastAudio
76
+ */
77
+ extend (other, duration, lastAudio) {
78
+ this.extendSilence(duration, lastAudio)
79
+ for (const [start, end] of other.#silence) this.addSilence(start + duration, end + duration)
80
+ if (other.#lastOffset !== undefined) {
81
+ this.#lastOffset = other.#lastOffset + duration
82
+ this.#lastReceived = other.#lastReceived
83
+ this.#speaking = other.#speaking
84
+ }
85
+ this.#overflow ||= other.#overflow
86
+ }
87
+
88
+ /**
89
+ * @param {number} duration
90
+ * @param {number | undefined} lastAudio
91
+ */
92
+ metadata (duration, lastAudio) {
93
+ if (this.#lastOffset === undefined || this.#overflow || duration <= 0) return
94
+ this.extendSilence(duration, lastAudio)
95
+ const intervals = []
96
+ let cursor = 0
97
+ for (const [from, to] of this.#silence) {
98
+ const start = Math.min(duration, from)
99
+ if (start > cursor) intervals.push([Math.floor(cursor), Math.ceil(start)])
100
+ cursor = Math.max(cursor, Math.min(duration, to))
101
+ }
102
+ if (cursor < duration) intervals.push([Math.floor(cursor), Math.ceil(duration)])
103
+ const merged = []
104
+ for (const [start, end] of intervals) {
105
+ const last = merged.at(-1)
106
+ if (last && start <= last[1]) last[1] = Math.max(end, last[1])
107
+ else merged.push([start, end])
108
+ }
109
+ if (merged.length > 128) return
110
+ return { version: 1, source: 'elevenlabs_vad', timing: 'estimated', intervals_ms: merged }
111
+ }
112
+ }
113
+
114
+ module.exports = SpeechActivity
@@ -0,0 +1,104 @@
1
+ 'use strict'
2
+
3
+ const { LLMOBS_AUDIO_ACCUMULATE_MAX_BYTES } = require('../../../dd-trace/src/llmobs/constants/audio')
4
+ const SpeechActivity = require('./activity')
5
+
6
+ // Leave space for both WAV headers before spending the shared encoded event budget.
7
+ const RAW_LIMIT = LLMOBS_AUDIO_ACCUMULATE_MAX_BYTES - 128
8
+ const BASE64 = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/
9
+
10
+ class AudioBuffer {
11
+ chunks = []
12
+ size = 0
13
+ total = 0
14
+ /** @type {number | undefined} */
15
+ start = undefined
16
+ /** @type {number | undefined} */
17
+ lastAudio = undefined
18
+ overflow = false
19
+ present = false
20
+ activity = new SpeechActivity()
21
+
22
+ /**
23
+ * @param {unknown} encoded
24
+ * @param {number} now
25
+ * @param {number} rate
26
+ * @param {boolean} input
27
+ * @param {boolean} retain
28
+ */
29
+ append (encoded, now, rate, input, retain) {
30
+ this.present = true
31
+ if (!rate || typeof encoded !== 'string' || !encoded.length) return
32
+ // Bound before validating/decoding an attacker-controlled string.
33
+ if (encoded.length > Math.ceil(RAW_LIMIT / 3) * 4) {
34
+ this.omit()
35
+ return
36
+ }
37
+ if (!BASE64.test(encoded)) return
38
+ const size = encoded.length / 4 * 3 - (encoded.endsWith('==') ? 2 : encoded.endsWith('=') ? 1 : 0)
39
+ if (size % 2) return
40
+ this.start ??= input ? now - size / (2 * rate) * 1000 : now
41
+ this.total += size
42
+ this.lastAudio = now
43
+ if (!retain) {
44
+ this.omit()
45
+ return
46
+ }
47
+ if (this.overflow || this.size + size > RAW_LIMIT) this.omit()
48
+ else {
49
+ if (this.chunks.length >= 1024) this.chunks = [this.bytes()]
50
+ this.chunks.push(Buffer.from(encoded, 'base64'))
51
+ this.size += size
52
+ }
53
+ }
54
+
55
+ omit () {
56
+ this.chunks = []
57
+ this.size = 0
58
+ this.overflow = true
59
+ }
60
+
61
+ /** @param {number} rate */
62
+ duration (rate) { return rate ? this.total / (2 * rate) * 1000 : 0 }
63
+
64
+ /** @param {number} rate */
65
+ end (rate) { return this.start === undefined ? undefined : this.start + this.duration(rate) }
66
+
67
+ /**
68
+ * @param {number} now
69
+ * @param {number} rate
70
+ * @param {number} [playbackEnd] Estimated end of the queued PCM, including delivery gaps.
71
+ */
72
+ trim (now, rate, playbackEnd) {
73
+ if (this.start === undefined || !rate) return
74
+ const end = playbackEnd ?? this.start + this.duration(rate)
75
+ const remaining = Math.max(0, end - now) * rate / 1000
76
+ const size = Math.max(0, Math.floor(this.total / 2 - remaining)) * 2
77
+ this.total = size
78
+ if (!this.overflow && this.size > size) {
79
+ this.chunks = [this.bytes().subarray(0, size)]
80
+ this.size = size
81
+ }
82
+ }
83
+
84
+ /**
85
+ * @param {AudioBuffer} other
86
+ * @param {number} rate
87
+ */
88
+ extend (other, rate) {
89
+ this.activity.extend(other.activity, this.duration(rate), this.lastAudio)
90
+ this.start ??= other.start
91
+ this.total += other.total
92
+ this.lastAudio = other.lastAudio ?? this.lastAudio
93
+ this.present ||= other.present
94
+ if (this.overflow || other.overflow || this.size + other.size > RAW_LIMIT) this.omit()
95
+ else {
96
+ this.chunks.push(...other.chunks)
97
+ this.size += other.size
98
+ }
99
+ }
100
+
101
+ bytes () { return Buffer.concat(this.chunks, this.size) }
102
+ }
103
+
104
+ module.exports = { AudioBuffer, RAW_LIMIT }
@@ -0,0 +1,288 @@
1
+ 'use strict'
2
+
3
+ const dc = require('dc-polyfill')
4
+
5
+ const log = require('../../../dd-trace/src/log')
6
+ const { addBeforeExitFinalizer } = require('../../../dd-trace/src/before-exit')
7
+ const shimmer = require('../../../datadog-shimmer')
8
+ const Session = require('./session')
9
+
10
+ const spanCh = dc.tracingChannel('apm:elevenlabs:span')
11
+ const finishCh = dc.channel('apm:elevenlabs:finish')
12
+ const captureCh = dc.channel('dd-trace:elevenlabs:capture-context')
13
+ const audioCh = dc.channel('dd-trace:elevenlabs:audio')
14
+ const sessions = new WeakMap()
15
+ const tools = new WeakMap()
16
+ const emitters = new WeakSet()
17
+ const audioInterfaces = new WeakMap()
18
+ const live = new Set()
19
+ const collected = new FinalizationRegistry(reference => live.delete(reference))
20
+ let handling
21
+
22
+ /** @param {() => unknown} fn */
23
+ function observe (fn) {
24
+ try { fn() } catch (error) { log.debug('ElevenLabs instrumentation: %s', error?.message) }
25
+ }
26
+
27
+ /**
28
+ * @param {object} scope
29
+ * @param {() => unknown} fn
30
+ */
31
+ function run (scope, fn) { return scope.runInContext ? scope.runInContext(fn) : fn() }
32
+
33
+ /**
34
+ * @param {Session} session
35
+ * @param {import('./session').Turn} turn
36
+ */
37
+ function begin (session, turn) {
38
+ run(session.scope, () => {
39
+ turn.root = {
40
+ session,
41
+ turn,
42
+ kind: 'workflow',
43
+ name: 'elevenlabs audio turn',
44
+ startTime: turn.start,
45
+ deferred: true,
46
+ }
47
+ spanCh.traceSync(() => {
48
+ captureCh.publish(turn.scope)
49
+ turn.llm = { session, turn, kind: 'llm', name: 'elevenlabs response', startTime: Date.now(), deferred: true }
50
+ spanCh.traceSync(() => {}, turn.llm)
51
+ }, turn.root)
52
+ })
53
+ }
54
+
55
+ /**
56
+ * @param {Session} session
57
+ * @param {import('./session').Turn} turn
58
+ */
59
+ function finish (session, turn) {
60
+ const text = [...turn.responses.values()].filter(Boolean).join('\n').slice(0, 100_000)
61
+ turn.text = text
62
+ turn.sessionId = session.sessionId
63
+ turn.inputRate = session.inputRate
64
+ turn.outputRate = session.outputRate
65
+ run(turn.scope, () => {
66
+ for (const ctx of turn.tools) {
67
+ turn.metadata.tool_execution_incomplete = true
68
+ ctx.finishTime = Date.now()
69
+ turn.toolEnd = Math.max(turn.toolEnd, ctx.finishTime)
70
+ finishCh.publish(ctx)
71
+ }
72
+ turn.tools.clear()
73
+ /** @type {[string, import('./audio').AudioBuffer, number, string][]} */
74
+ const phases = [
75
+ ['user speech', turn.input, session.inputRate, turn.userText],
76
+ ['agent speech', turn.output, session.outputRate, text],
77
+ ]
78
+ for (const [name, audio, rate, transcript] of phases) {
79
+ const end = name === 'agent speech' ? turn.playbackEnd : audio.end(rate)
80
+ if (audio.start === undefined || end === undefined || !(end > audio.start)) continue
81
+ const activity = name === 'user speech' && !audio.overflow
82
+ ? audio.activity.metadata(audio.duration(rate), audio.lastAudio)
83
+ : undefined
84
+ spanCh.traceSync(() => {}, {
85
+ session, turn, kind: 'workflow', name, startTime: audio.start, finishTime: end, transcript, activity,
86
+ })
87
+ }
88
+ turn.llm.finishTime = Math.max(turn.llm.startTime, turn.responseTime)
89
+ finishCh.publish(turn.llm)
90
+ turn.root.finishTime = Math.max(turn.start, turn.responseTime, turn.toolEnd,
91
+ turn.input.end(session.inputRate) || 0, turn.playbackEnd || 0)
92
+ finishCh.publish(turn.root)
93
+ })
94
+ }
95
+
96
+ /** @param {object} conversation */
97
+ function create (conversation) {
98
+ const session = new Session({
99
+ agentId: conversation.agentId,
100
+ begin: turn => begin(session, turn),
101
+ finish: turn => finish(session, turn),
102
+ retain: () => audioCh.hasSubscribers,
103
+ })
104
+ session.scope = {}
105
+ captureCh.publish(session.scope)
106
+ const reference = new WeakRef(session)
107
+ live.add(reference)
108
+ collected.register(session, reference, reference)
109
+ session.finalize = failed => {
110
+ live.delete(reference)
111
+ collected.unregister(reference)
112
+ session.close(Date.now(), failed)
113
+ session.scope = {}
114
+ }
115
+ sessions.set(conversation, session)
116
+ if (!emitters.has(conversation)) {
117
+ emitters.add(conversation)
118
+ // emit is inherited from Node's EventEmitter, outside the SDK's rewriteable source.
119
+ // Observe only this runtime instance; an error listener would change unhandled-error behavior.
120
+ shimmer.wrap(conversation, 'emit', emit => function (event) {
121
+ if (event === 'error') observe(() => sessions.get(this)?.finalize(true))
122
+ return emit.apply(this, arguments)
123
+ })
124
+ }
125
+ return session
126
+ }
127
+
128
+ /** @param {{output: (audio: Buffer) => unknown}} audio */
129
+ function attachAudio (audio) {
130
+ if (!audio || audioInterfaces.get(audio) === audio.output) return
131
+ // Customer audio implementations are runtime objects outside the SDK's source. Observing their
132
+ // output entrypoint follows both the released and corrected SDK without duplicating its filter.
133
+ shimmer.wrap(audio, 'output', output => function () {
134
+ const reception = handling?.reception
135
+ const result = output.apply(this, arguments)
136
+ if (reception && !reception.accepted) {
137
+ reception.accepted = true
138
+ observe(() => reception.session.receive(reception.event, reception.receivedAt))
139
+ }
140
+ return result
141
+ })
142
+ audioInterfaces.set(audio, audio.output)
143
+ }
144
+
145
+ /**
146
+ * @param {Session} session
147
+ * @param {object} socket
148
+ */
149
+ function attach (session, socket) {
150
+ if (!socket || session.socket === socket) return
151
+ session.socket = socket
152
+ // Custom factories produce runtime socket instances; rewriting ws would miss these and
153
+ // instrument unrelated connections. Observe only this conversation's accepted sends.
154
+ shimmer.wrap(socket, 'send', send => function (data) {
155
+ const result = send.apply(this, arguments)
156
+ observe(() => {
157
+ if (typeof data === 'string') session.sendRaw(data, Date.now())
158
+ })
159
+ return result
160
+ })
161
+ }
162
+
163
+ /** @param {string} method */
164
+ function channel (method) { return dc.tracingChannel(`orchestrion:@elevenlabs/elevenlabs-js:${method}`) }
165
+
166
+ channel('startSession').subscribe({
167
+ start (ctx) {
168
+ if (!spanCh.start.hasSubscribers || ctx.self.ws) return
169
+ observe(() => { ctx.session = create(ctx.self) })
170
+ },
171
+ error (ctx) { if (ctx.session) observe(() => ctx.session.finalize(true)) },
172
+ })
173
+ channel('_onWebSocketOpen').start.subscribe(ctx => {
174
+ observe(() => {
175
+ const session = sessions.get(ctx.self)
176
+ if (session) attach(session, ctx.self.ws)
177
+ })
178
+ })
179
+ channel('_handleMessage').subscribe({
180
+ start (ctx) {
181
+ ctx.previous = handling
182
+ handling = undefined
183
+ observe(() => {
184
+ const session = sessions.get(ctx.self)
185
+ if (!session || ctx.self.shouldStop) return
186
+ const event = ctx.arguments[0]
187
+ const receivedAt = Date.now()
188
+ if (event?.type === 'audio') {
189
+ attachAudio(ctx.self.audioInterface)
190
+ ctx.reception = { session, event, receivedAt, accepted: false }
191
+ handling = { reception: ctx.reception }
192
+ return
193
+ }
194
+ const turn = session.receive(event, receivedAt)
195
+ handling = turn ? { session, turn } : undefined
196
+ })
197
+ },
198
+ end (ctx) {
199
+ const reception = ctx.reception
200
+ if (reception && !reception.accepted) {
201
+ observe(() => reception.session.receive(reception.event, reception.receivedAt, false))
202
+ }
203
+ handling = ctx.previous
204
+ },
205
+ })
206
+ channel('endSession').end.subscribe(ctx => {
207
+ observe(() => sessions.get(ctx.self)?.finalize(Boolean(ctx.error)))
208
+ })
209
+ channel('_onWebSocketOpen').error.subscribe(ctx => {
210
+ observe(() => sessions.get(ctx.self)?.finalize(true))
211
+ })
212
+ channel('_onWebSocketClose').start.subscribe(ctx => {
213
+ const code = ctx.arguments[0]
214
+ observe(() => sessions.get(ctx.self)?.finalize(!ctx.self.shouldStop && ![1000, 1001, 1005].includes(code)))
215
+ })
216
+ channel('executeToolAsync').start.subscribe(ctx => {
217
+ if (handling?.turn && ctx.arguments[1] && typeof ctx.arguments[1] === 'object') {
218
+ const { session, turn } = handling
219
+ // Preserve this dispatch's bounded input even if another message reuses its call ID.
220
+ const call = turn.calls.get(ctx.arguments[1].tool_call_id)
221
+ if (!call) return
222
+ const owner = {
223
+ session,
224
+ turn,
225
+ call,
226
+ /** @type {object | undefined} */
227
+ tool: undefined,
228
+ }
229
+ tools.set(ctx.arguments[1], owner)
230
+ // The SDK callback serializes and sends the result. Read our parsed wire copy afterward,
231
+ // so telemetry never invokes a handler result's toJSON or property getters itself.
232
+ ctx.arguments[2] = shimmer.wrapCallback(ctx.arguments[2], callback => function (response) {
233
+ const tool = owner.tool
234
+ if (tool && !tool.finished) {
235
+ tool.finishTime ??= Date.now()
236
+ turn.toolEnd = Math.max(turn.toolEnd, tool.finishTime)
237
+ }
238
+ const previous = turn.results.get(call.toolId)
239
+ const result = callback.apply(this, arguments)
240
+ observe(() => {
241
+ owner.tool = undefined
242
+ if (!tool || tool.finished) return
243
+ const recorded = turn.results.get(tool.id)
244
+ tool.output = recorded === previous ? undefined : recorded?.result
245
+ if (response.is_error && !tool.error) tool.error = new Error(tool.output || 'Client tool failed')
246
+ turn.tools.delete(tool)
247
+ finishCh.publish(tool)
248
+ })
249
+ return result
250
+ })
251
+ }
252
+ })
253
+ channel('register').start.subscribe(ctx => {
254
+ const handler = ctx.arguments[1]
255
+ if (typeof handler !== 'function') return
256
+ if (ctx.arguments[2] === undefined) ctx.arguments[2] = handler.constructor.name === 'AsyncFunction'
257
+ // Customer handlers are created at runtime and have no matchable SDK source function.
258
+ ctx.arguments[1] = shimmer.wrapCallback(handler, original => function (parameters) {
259
+ const owner = tools.get(parameters)
260
+ if (!owner || owner.turn.closed || !spanCh.start.hasSubscribers) return original.apply(this, arguments)
261
+ const { session, turn, call } = owner
262
+ const id = parameters.tool_call_id
263
+ if (turn.tools.size >= 64) {
264
+ turn.metadata.tool_spans_omitted = true
265
+ return run(turn.scope, () => original.apply(this, arguments))
266
+ }
267
+ const tool = {
268
+ session,
269
+ turn,
270
+ kind: 'tool',
271
+ name: call.name,
272
+ id,
273
+ parameters: call.arguments,
274
+ startTime: Date.now(),
275
+ deferred: true,
276
+ }
277
+ owner.tool = tool
278
+ turn.tools.add(tool)
279
+ // Preserve the original result. The SDK alone assimilates thenables; its completion callback
280
+ // records the execution end before serialization and finishes the span from the wire result.
281
+ return run(turn.scope, () => spanCh.traceSync(() => original.apply(this, arguments), tool))
282
+ })
283
+ })
284
+
285
+ addBeforeExitFinalizer(() => {
286
+ for (const reference of live) observe(() => reference.deref()?.finalize(true))
287
+ live.clear()
288
+ })