dd-trace 6.24.0 → 6.25.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,444 @@
1
+ 'use strict'
2
+
3
+ const { randomUUID } = require('node:crypto')
4
+
5
+ const { AudioBuffer, RAW_LIMIT } = require('./audio')
6
+
7
+ const AUDIO_PREFIX = '{"user_audio_chunk":"'
8
+ const MAX_TOOL_ID_CHARS = 1024
9
+ const MAX_TOOL_NAME_CHARS = 1024
10
+
11
+ const EVENT_FIELDS = {
12
+ user_transcript: 'user_transcription_event',
13
+ audio: 'audio_event',
14
+ agent_response: 'agent_response_event',
15
+ agent_response_correction: 'agent_response_correction_event',
16
+ agent_chat_response_part: 'text_response_part',
17
+ client_tool_call: 'client_tool_call',
18
+ context_usage: 'context_usage_event',
19
+ agent_tool_response_full_payload: 'agent_tool_response_full_payload',
20
+ }
21
+
22
+ /** @param {unknown} value */
23
+ function rateOf (value) {
24
+ if (typeof value !== 'string' || !/^pcm_\d+$/.test(value)) return 0
25
+ const rate = Number(value.slice(4))
26
+ return rate >= 8000 && rate <= 48_000 ? rate : 0
27
+ }
28
+
29
+ /** @param {unknown} value */
30
+ function eventId (value) {
31
+ if (typeof value === 'string' && /^\d{1,100}$/.test(value)) return BigInt(value)
32
+ return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? BigInt(value) : undefined
33
+ }
34
+
35
+ /**
36
+ * @param {unknown} value
37
+ * @param {number} [limit]
38
+ */
39
+ function textOf (value, limit = 100_000) {
40
+ if (typeof value === 'string') return value.slice(0, limit)
41
+ return ''
42
+ }
43
+
44
+ /** @param {unknown} value */
45
+ function toolIdOf (value) {
46
+ return typeof value === 'string' && value.length <= MAX_TOOL_ID_CHARS ? value : undefined
47
+ }
48
+
49
+ /**
50
+ * @typedef {{runInContext?: <T>(fn: () => T) => T}} Scope
51
+ * @typedef {{
52
+ * id: bigint, input: AudioBuffer, output: AudioBuffer, userText: string,
53
+ * responses: Map<string, string>, completed: Set<string>, calls: Map<string, object>,
54
+ * results: Map<string, object>, tools: Set<object>, model?: string, start: number,
55
+ * responseTime: number, toolEnd: number, retired: boolean, playbackEnd?: number, interrupted: boolean,
56
+ * failed: boolean, metadata: Record<string, unknown>, scope: Scope, root?: object, llm?: object,
57
+ * boundaryResponse?: boolean, closed?: boolean, text?: string, sessionId?: string,
58
+ * inputRate?: number, outputRate?: number, argumentsSize: number, argumentSizes: Map<string, number>,
59
+ * }} Turn
60
+ * @typedef {{
61
+ * begin: (turn: Turn) => void, finish: (turn: Turn) => void,
62
+ * retain: () => boolean, agentId: string,
63
+ * }} Options
64
+ */
65
+
66
+ class Session {
67
+ /** @type {{runInContext?: <T>(fn: () => T) => T}} */
68
+ scope = {}
69
+ /** @type {object | undefined} */
70
+ socket = undefined
71
+ /** @type {(failed: boolean) => void} */
72
+ finalize = () => {}
73
+ /** @type {Map<bigint, Turn>} */
74
+ turns = new Map()
75
+ pending = new AudioBuffer()
76
+ pendingText = ''
77
+ /** @type {number | undefined} */
78
+ #pendingTextStart = undefined
79
+ early = []
80
+ earlySize = 0
81
+ earlyOverflow = false
82
+ negotiated = false
83
+ inputRate = 0
84
+ outputRate = 0
85
+ /** @type {string} */
86
+ sessionId = randomUUID()
87
+ lastInterrupt = -1n
88
+ lastFinalized = -1n
89
+ /** @type {bigint | undefined} */
90
+ filteredAudioId = undefined
91
+ closed = false
92
+ #waiting = false
93
+ /** @type {Map<bigint, string>} */
94
+ #models = new Map()
95
+
96
+ /** @param {Options} options */
97
+ constructor (options) { this.options = options }
98
+
99
+ /**
100
+ * @param {bigint} id
101
+ * @param {number} now
102
+ */
103
+ turn (id, now) {
104
+ if (this.closed) return
105
+ const known = this.turns.get(id)
106
+ if (known) return known
107
+ // The server uses the interruption ID for the replacement response. Only lower
108
+ // unknown IDs are stale; treating the boundary as stale steals the next input.
109
+ if (id < this.lastInterrupt || id <= this.lastFinalized) return
110
+ while (this.turns.size >= 2) this.finish(/** @type {Turn} */ (this.turns.values().next().value))
111
+ for (const previous of this.turns.values()) previous.retired = true
112
+ const input = this.pending
113
+ this.pending = new AudioBuffer()
114
+ this.pending.activity = input.activity.continueAt(input.duration(this.inputRate))
115
+ /** @type {Turn} */
116
+ const turn = {
117
+ id,
118
+ input,
119
+ output: new AudioBuffer(),
120
+ userText: this.pendingText,
121
+ argumentsSize: 0,
122
+ argumentSizes: new Map(),
123
+ responses: new Map(),
124
+ completed: new Set(),
125
+ calls: new Map(),
126
+ results: new Map(),
127
+ tools: new Set(),
128
+ start: Math.min(input.start ?? now, this.#pendingTextStart ?? now),
129
+ responseTime: now,
130
+ toolEnd: now,
131
+ retired: false,
132
+ interrupted: false,
133
+ boundaryResponse: id === this.lastInterrupt,
134
+ model: this.#models.get(id),
135
+ failed: false,
136
+ scope: {},
137
+ metadata: {
138
+ agent_id: this.options.agentId,
139
+ ttfa_eligible: false,
140
+ audio_timing_source: 'sdk_transport',
141
+ audio_playback: 'estimated',
142
+ event_id: String(id),
143
+ },
144
+ }
145
+ if (id === this.filteredAudioId) {
146
+ turn.output.present = true
147
+ turn.output.omit()
148
+ turn.metadata.output_audio_omitted_reason = 'sdk_interruption_filter'
149
+ }
150
+ this.pendingText = ''
151
+ this.#pendingTextStart = undefined
152
+ this.#models.delete(id)
153
+ this.turns.set(id, turn)
154
+ this.options.begin(turn)
155
+ return turn
156
+ }
157
+
158
+ /**
159
+ * @param {string} raw
160
+ * @param {number} now
161
+ */
162
+ sendRaw (raw, now) {
163
+ // The SDK emits this single-field envelope for every microphone frame. Other JSON shapes,
164
+ // additional fields, and escaped values still use the normal parser.
165
+ if (raw.startsWith(AUDIO_PREFIX) && raw.endsWith('"}') &&
166
+ raw.indexOf('"', AUDIO_PREFIX.length) === raw.length - 2 &&
167
+ !raw.includes('\\', AUDIO_PREFIX.length)) {
168
+ this.send({ user_audio_chunk: raw.slice(AUDIO_PREFIX.length, -2) }, now)
169
+ } else {
170
+ this.send(JSON.parse(raw), now)
171
+ }
172
+ }
173
+
174
+ /**
175
+ * @param {object} event
176
+ * @param {number} now
177
+ */
178
+ send (event, now) {
179
+ if (this.closed || !event || typeof event !== 'object') return
180
+ if (typeof event.user_audio_chunk === 'string') {
181
+ const encoded = event.user_audio_chunk
182
+ if (this.inputRate) this.pending.append(encoded, now, this.inputRate, true, this.options.retain())
183
+ else if (this.negotiated) {
184
+ this.pending.present = true
185
+ this.pending.omit()
186
+ } else if (!this.earlyOverflow) {
187
+ this.earlySize += encoded.length
188
+ if (this.early.length < 256 && this.earlySize <= RAW_LIMIT * 4 / 3 && this.options.retain()) {
189
+ this.early.push([encoded, now])
190
+ } else {
191
+ this.early = []
192
+ this.earlyOverflow = true
193
+ }
194
+ }
195
+ } else if (event.type === 'user_message') {
196
+ this.#pendingTextStart ??= now
197
+ this.pendingText = textOf(this.pendingText ? `${this.pendingText}\n${textOf(event.text)}` : textOf(event.text))
198
+ } else if (event.type === 'client_tool_result') {
199
+ const id = toolIdOf(event.tool_call_id)
200
+ if (id === undefined) return
201
+ for (const turn of this.turns.values()) {
202
+ if (turn.calls.has(id)) this.toolResult(turn, id, event.result)
203
+ }
204
+ }
205
+ }
206
+
207
+ /**
208
+ * @param {object} event
209
+ * @param {number} now
210
+ * @param {boolean} [audioAccepted] Whether the SDK delivered this audio to its output interface.
211
+ */
212
+ receive (event, now, audioAccepted = true) {
213
+ if (this.closed || !event || typeof event !== 'object') return
214
+ const kind = event.type
215
+ if (kind === 'conversation_initiation_metadata') {
216
+ const data = event.conversation_initiation_metadata_event
217
+ if (!data || typeof data !== 'object') return
218
+ this.sessionId = textOf(data.conversation_id) || this.sessionId
219
+ this.negotiated = true
220
+ this.inputRate = rateOf(data.user_input_audio_format)
221
+ this.outputRate = rateOf(data.agent_output_audio_format)
222
+ if (this.earlyOverflow || (!this.inputRate && this.early.length)) {
223
+ this.pending.present = true
224
+ this.pending.omit()
225
+ }
226
+ for (const [encoded, sent] of this.early) {
227
+ this.pending.append(encoded, sent, this.inputRate, true, this.options.retain())
228
+ }
229
+ this.early = []
230
+ this.earlySize = 0
231
+ this.earlyOverflow = false
232
+ return
233
+ }
234
+ if (kind === 'queue_status') {
235
+ const status = event.queue_status_event?.status
236
+ if (status === 'admitted') this.#waiting = false
237
+ else if (status === 'waiting' || status === 'timed_out') this.#waiting = true
238
+ return
239
+ }
240
+ if (kind === 'audio' && this.#waiting) return
241
+ if (kind === 'interruption') {
242
+ const id = eventId(event.interruption_event?.event_id)
243
+ if (id === undefined) return
244
+ if (id > this.lastInterrupt) {
245
+ this.lastInterrupt = id
246
+ this.filteredAudioId = undefined
247
+ }
248
+ for (const turn of this.turns.values()) {
249
+ if (turn.id <= id && (!this.responseFinished(turn, now) || (turn.playbackEnd ?? 0) > now)) {
250
+ turn.interrupted = true
251
+ this.trimOutput(turn, now)
252
+ }
253
+ }
254
+ return
255
+ }
256
+ if (kind === 'vad_score') {
257
+ if (this.inputRate && this.options.retain()) {
258
+ this.pending.activity.observe(event.vad_score_event?.vad_score, this.pending.duration(this.inputRate), now)
259
+ }
260
+ return
261
+ }
262
+ if (!Object.hasOwn(EVENT_FIELDS, kind)) return
263
+ const data = event[EVENT_FIELDS[kind]]
264
+ if (!data || typeof data !== 'object') return
265
+ const id = eventId(data.event_id)
266
+ if (id === undefined) return
267
+ if (kind === 'audio' && !audioAccepted) {
268
+ if (id === this.lastInterrupt) {
269
+ this.filteredAudioId = id
270
+ const rejected = this.turns.get(id)
271
+ if (rejected?.boundaryResponse) {
272
+ rejected.output.present = true
273
+ rejected.output.omit()
274
+ rejected.metadata.output_audio_omitted_reason = 'sdk_interruption_filter'
275
+ }
276
+ }
277
+ return
278
+ }
279
+ if (kind === 'audio' && id < this.lastInterrupt) return
280
+ if (kind === 'context_usage') {
281
+ const model = textOf(data.model)
282
+ if (!model) return
283
+ const known = this.turns.get(id)
284
+ if (known) known.model = model
285
+ else if (id >= this.lastInterrupt && id > this.lastFinalized) {
286
+ this.#models.delete(id)
287
+ this.#models.set(id, model)
288
+ while (this.#models.size > 2) this.#models.delete(/** @type {bigint} */ (this.#models.keys().next().value))
289
+ }
290
+ return
291
+ }
292
+ const lookupOnly = kind === 'agent_tool_response_full_payload'
293
+ const turn = lookupOnly ? this.turns.get(id) : this.turn(id, now)
294
+ if (!turn) return
295
+ switch (kind) {
296
+ case 'user_transcript': turn.userText = textOf(data.user_transcript); break
297
+ case 'audio': {
298
+ const previousDuration = turn.output.duration(this.outputRate)
299
+ turn.output.append(data.audio_base_64, now, this.outputRate, false, this.options.retain())
300
+ const duration = turn.output.duration(this.outputRate) - previousDuration
301
+ if (duration > 0) turn.playbackEnd = Math.max(turn.playbackEnd ?? now, now) + duration
302
+ this.boundAudio(turn)
303
+ break
304
+ }
305
+ case 'client_tool_call': {
306
+ const id = toolIdOf(data.tool_call_id)
307
+ if (id === undefined || (!turn.calls.has(id) && turn.calls.size >= 64)) {
308
+ turn.metadata.tool_calls_omitted = true
309
+ break
310
+ }
311
+ const argumentsJson = JSON.stringify(data.parameters || {})
312
+ const used = turn.argumentsSize - (turn.argumentSizes.get(id) || 0)
313
+ const argumentsFit = argumentsJson.length + used <= 100_000
314
+ if (!argumentsFit) turn.metadata.tool_arguments_truncated = true
315
+ const size = argumentsFit ? argumentsJson.length : 2 // omitted arguments retain the empty object
316
+ turn.argumentSizes.set(id, size)
317
+ turn.argumentsSize = used + size
318
+ // The 64-call limit also bounds retained names to 65,536 characters per turn.
319
+ const name = textOf(data.tool_name, MAX_TOOL_NAME_CHARS)
320
+ if (typeof data.tool_name === 'string' && data.tool_name.length > MAX_TOOL_NAME_CHARS) {
321
+ turn.metadata.tool_names_truncated = true
322
+ }
323
+ turn.calls.set(id, {
324
+ name,
325
+ arguments: argumentsFit ? data.parameters || {} : {},
326
+ toolId: id,
327
+ type: 'tool',
328
+ })
329
+ break
330
+ }
331
+ case 'agent_tool_response_full_payload':
332
+ if (toolIdOf(data.tool_call_id) !== undefined && turn.calls.has(data.tool_call_id)) {
333
+ this.toolResult(turn, data.tool_call_id, data.full_tool_result)
334
+ }
335
+ break
336
+ default: this.response(turn, kind, data, now)
337
+ }
338
+ return turn
339
+ }
340
+
341
+ /**
342
+ * @param {Turn} turn
343
+ * @param {string} kind
344
+ * @param {object} data
345
+ * @param {number} now
346
+ */
347
+ response (turn, kind, data, now) {
348
+ const key = textOf(data.response_id)
349
+ if (!turn.responses.has(key) && turn.responses.size >= 64) return
350
+ if (kind === 'agent_chat_response_part') {
351
+ if (turn.completed.has(key)) return
352
+ const prefix = data.type === 'start' ? '' : (turn.responses.get(key) || '')
353
+ turn.responses.set(key, textOf(prefix + textOf(data.text)))
354
+ if (data.type === 'stop') turn.completed.add(key)
355
+ } else {
356
+ const field = kind === 'agent_response_correction' ? 'corrected_agent_response' : 'agent_response'
357
+ turn.responses.set(key, textOf(data[field]))
358
+ turn.completed.add(key)
359
+ }
360
+ turn.responseTime = now
361
+ }
362
+
363
+ /**
364
+ * @param {Turn} turn
365
+ * @param {string} id
366
+ * @param {unknown} result
367
+ */
368
+ toolResult (turn, id, result) {
369
+ if (turn.closed || toolIdOf(id) === undefined) return ''
370
+ let remaining = 100_000
371
+ for (const [key, item] of turn.results) if (key !== id) remaining -= item.result.length
372
+ let text = typeof result === 'string' ? result : JSON.stringify(result) ?? ''
373
+ if (text.length > remaining) {
374
+ text = text.slice(0, remaining)
375
+ turn.metadata.tool_results_truncated = true
376
+ }
377
+ turn.results.set(id, { toolId: id, result: text, type: 'tool_result' })
378
+ return text
379
+ }
380
+
381
+ /**
382
+ * Completion remains estimated: final text plus the observed playback queue, or retirement by a
383
+ * newer response. A text event alone cannot prove that audio delivery has finished.
384
+ * @param {Turn} turn
385
+ * @param {number} now
386
+ */
387
+ responseFinished (turn, now) {
388
+ return turn.retired || (turn.responses.size > 0 && turn.completed.size === turn.responses.size &&
389
+ turn.tools.size === 0 && turn.playbackEnd !== undefined && now >= turn.playbackEnd)
390
+ }
391
+
392
+ /**
393
+ * @param {Turn} turn
394
+ * @param {number} now
395
+ */
396
+ trimOutput (turn, now) {
397
+ turn.output.trim(now, this.outputRate, turn.playbackEnd)
398
+ // Discarded queued samples must not be subtracted again by another interruption or close.
399
+ if (turn.playbackEnd !== undefined) turn.playbackEnd = Math.min(turn.playbackEnd, now)
400
+ }
401
+
402
+ /** @param {Turn} turn */
403
+ boundAudio (turn) { if (turn.input.size + turn.output.size > RAW_LIMIT) turn.output.omit() }
404
+
405
+ /** @param {Turn} turn */
406
+ finish (turn) {
407
+ if (turn.closed) return
408
+ this.turns.delete(turn.id)
409
+ turn.metadata.interrupted = turn.interrupted
410
+ if (turn.model) turn.metadata.configured_llm = turn.model
411
+ if (turn.input.overflow || turn.output.overflow) turn.metadata.audio_omitted = true
412
+ this.options.finish(turn)
413
+ turn.closed = true
414
+ turn.input.chunks = []
415
+ turn.output.chunks = []
416
+ if (turn.id > this.lastFinalized) this.lastFinalized = turn.id
417
+ }
418
+
419
+ /**
420
+ * @param {number} now
421
+ * @param {boolean} failed
422
+ */
423
+ close (now, failed) {
424
+ if (this.closed) return
425
+ this.closed = true
426
+ const last = [...this.turns.values()].at(-1)
427
+ if (last) {
428
+ last.input.extend(this.pending, this.inputRate)
429
+ this.boundAudio(last)
430
+ }
431
+ this.pending = new AudioBuffer()
432
+ this.pendingText = ''
433
+ this.#pendingTextStart = undefined
434
+ this.early = []
435
+ this.#models.clear()
436
+ for (const turn of this.turns.values()) {
437
+ if (failed && !this.responseFinished(turn, now) && !turn.interrupted) turn.failed = true
438
+ this.trimOutput(turn, now)
439
+ this.finish(turn)
440
+ }
441
+ }
442
+ }
443
+
444
+ module.exports = Session
@@ -33,20 +33,23 @@ addRewriterHooks('graphql-jit')
33
33
  // (read lazily inside each callback so agent.load() between mocha suites can
34
34
  // rebind globalThis[dd-trace] without us stashing a stale reference).
35
35
 
36
- addHook({ name: 'graphql', file: 'language/printer.js', versions: ['>=0.10'] }, printer => {
37
- const ddGlobal = globalThis[Symbol.for('dd-trace')]
38
- if (ddGlobal) ddGlobal.graphql_printer = printer
39
- return printer
40
- })
41
-
42
- addHook({ name: 'graphql', file: 'language/visitor.js', versions: ['>=0.10'] }, visitor => {
43
- const ddGlobal = globalThis[Symbol.for('dd-trace')]
44
- if (ddGlobal) ddGlobal.graphql_visitor = visitor
45
- return visitor
46
- })
47
-
48
- addHook({ name: 'graphql', file: 'utilities/index.js', versions: ['>=0.10'] }, utilities => {
49
- const ddGlobal = globalThis[Symbol.for('dd-trace')]
50
- if (ddGlobal) ddGlobal.graphql_utilities = utilities
51
- return utilities
52
- })
36
+ // Capture ESM namespace exports through module hooks: __module_export__ only matches CommonJS exports.
37
+ for (const extension of ['js', 'mjs']) {
38
+ addHook({ name: 'graphql', file: `language/printer.${extension}`, versions: ['>=0.10'] }, printer => {
39
+ const ddGlobal = globalThis[Symbol.for('dd-trace')]
40
+ if (ddGlobal) ddGlobal.graphql_printer = printer
41
+ return printer
42
+ })
43
+
44
+ addHook({ name: 'graphql', file: `language/visitor.${extension}`, versions: ['>=0.10'] }, visitor => {
45
+ const ddGlobal = globalThis[Symbol.for('dd-trace')]
46
+ if (ddGlobal) ddGlobal.graphql_visitor = visitor
47
+ return visitor
48
+ })
49
+
50
+ addHook({ name: 'graphql', file: `utilities/index.${extension}`, versions: ['>=0.10'] }, utilities => {
51
+ const ddGlobal = globalThis[Symbol.for('dd-trace')]
52
+ if (ddGlobal) ddGlobal.graphql_utilities = utilities
53
+ return utilities
54
+ })
55
+ }