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,887 @@
1
+ 'use strict'
2
+
3
+ const { randomUUID } = require('node:crypto')
4
+
5
+ const {
6
+ bytesPerSecond,
7
+ realtimeAudioFormatToMime,
8
+ segmentDurationMs,
9
+ } = require('../../../dd-trace/src/llmobs/audio-codec')
10
+ const { LLMOBS_AUDIO_ACCUMULATE_MAX_BYTES } = require('../../../dd-trace/src/llmobs/constants/audio')
11
+ const log = require('../../../dd-trace/src/log')
12
+
13
+ /**
14
+ * @typedef {{
15
+ * id: string,
16
+ * turn: import('./turns').ResponseTurn,
17
+ * held: boolean,
18
+ * hasAudio: boolean,
19
+ * audioIncomplete: boolean,
20
+ * stopped: boolean,
21
+ * outOfBand: boolean,
22
+ * format: { mimeType: string, sampleRate: number },
23
+ * transcriptPending: boolean,
24
+ * cleared: boolean,
25
+ * truncated: boolean,
26
+ * ambiguous?: boolean,
27
+ * timer?: ReturnType<typeof setTimeout>,
28
+ * deadline?: number,
29
+ * phase?: "audio" | "queued" | "playback",
30
+ * playbackWindow?: PlaybackWindow,
31
+ * output: Map<string, { wanted: boolean, inFlight: boolean, parts: Map<number, { buffer?: Buffer }> }>,
32
+ * }} PlaybackEntry
33
+ * @typedef {{
34
+ * entries: PlaybackEntry[],
35
+ * startTime: number,
36
+ * finishTime: number,
37
+ * resolved: boolean,
38
+ * }} PlaybackWindow
39
+ */
40
+
41
+ const AUDIO_WAIT_MS = 5000
42
+ const PLAYBACK_WAIT_MS = 120_000
43
+ const INPUT_TRANSCRIPT_WAIT_MS = AUDIO_WAIT_MS / 2
44
+ const MAX_CACHED_AUDIO_BYTES = LLMOBS_AUDIO_ACCUMULATE_MAX_BYTES * 4
45
+ const AUDIO_CONTENT_TYPES = new Set(['audio', 'input_audio', 'output_audio'])
46
+ const MAX_TURNS = 16
47
+ const MAX_ITEMS = 256
48
+
49
+ /**
50
+ * Server-owned playback and stored-item audio for a RealtimeSession.
51
+ * Generation and span emission stay with the owner; this helper only holds completed
52
+ * turns until the playback/retrieval evidence is complete.
53
+ */
54
+ class ServerPlayback {
55
+ #shouldRetainAudio
56
+ #requestItem
57
+ #onReady
58
+ #onTranscript
59
+ #turns = new Map()
60
+ #items = new Map()
61
+ #inputs = new WeakMap()
62
+ #requests = new Map()
63
+ #active
64
+ #scheduled
65
+ #sequence = 0
66
+ #requestPrefix = 'ddtrace_realtime_audio_' + randomUUID() + '_'
67
+ #closed = false
68
+ #inputFormat = { mimeType: 'audio/pcm', sampleRate: 24_000 }
69
+ #outputFormat = { mimeType: 'audio/pcm', sampleRate: 24_000 }
70
+
71
+ /**
72
+ * @param {{ shouldRetainAudio: () => boolean, requestItem?: (itemId: string, eventId: string) => void,
73
+ * onTranscript?: (itemId: string, transcript: string, now: number) => void,
74
+ * onReady: (turn: import('./turns').ResponseTurn, now: number) => void }} options
75
+ */
76
+ constructor ({ shouldRetainAudio, requestItem, onReady, onTranscript }) {
77
+ this.#shouldRetainAudio = shouldRetainAudio
78
+ this.#requestItem = requestItem
79
+ this.#onReady = onReady
80
+ this.#onTranscript = onTranscript
81
+ }
82
+
83
+ /**
84
+ * @param {{ mimeType: string, sampleRate: number }} input
85
+ * @param {{ mimeType: string, sampleRate: number }} output
86
+ */
87
+ updateFormats (input, output) {
88
+ this.#inputFormat = input
89
+ this.#outputFormat = output
90
+ }
91
+
92
+ /**
93
+ * @param {import('./turns').InputTurn} input
94
+ * @param {boolean} [waitingForTranscript]
95
+ */
96
+ rememberInput (input, waitingForTranscript = false) {
97
+ if (input.itemId !== undefined) {
98
+ const previous = this.#inputs.get(input)
99
+ if (previous && previous.id !== input.itemId) {
100
+ this.forgetInput(input)
101
+ input.resetSpeech()
102
+ }
103
+ input.audio.present = true
104
+ const item = this.#bind(input.itemId, input, undefined, 'user')
105
+ if (item) {
106
+ item.waitingForTranscript = waitingForTranscript
107
+ this.#inputs.set(input, item)
108
+ }
109
+ }
110
+ }
111
+
112
+ /** @param {import('./turns').InputTurn} input */
113
+ forgetInput (input) {
114
+ const previous = this.#inputs.get(input)
115
+ if (!previous) return
116
+ this.#inputs.delete(input)
117
+ this.#clearInputWait(previous)
118
+ previous.parts.clear()
119
+ input.audio.clear()
120
+ this.#items.delete(previous.id)
121
+ for (const [id, item] of this.#requests) {
122
+ if (item === previous) this.#requests.delete(id)
123
+ }
124
+ }
125
+
126
+ /**
127
+ * @param {string} id
128
+ * @param {import('./turns').ResponseTurn} turn
129
+ * @param {object} [response]
130
+ */
131
+ start (id, turn, response) {
132
+ if (this.#closed) return
133
+ if (this.#turns.size >= MAX_TURNS && !this.#evictHeld(Date.now())) return
134
+ const format = response?.audio?.output?.format ?? response?.output_audio_format
135
+ const entry = {
136
+ id,
137
+ format: format
138
+ ? {
139
+ mimeType: realtimeAudioFormatToMime(format),
140
+ sampleRate: typeof format.rate === 'number' ? format.rate : this.#outputFormat.sampleRate,
141
+ }
142
+ : this.#outputFormat,
143
+ turn,
144
+ output: new Map(),
145
+ held: false,
146
+ transcriptPending: false,
147
+ hasAudio: false,
148
+ audioIncomplete: false,
149
+ outOfBand: response?.conversation_id === null,
150
+ stopped: false,
151
+ cleared: false,
152
+ truncated: false,
153
+ timer: undefined,
154
+ deadline: undefined,
155
+ phase: undefined,
156
+ playbackWindow: /** @type {PlaybackWindow | undefined} */ (undefined),
157
+ }
158
+ this.#turns.set(id, entry)
159
+ const input = this.#items.get(turn.input.itemId)
160
+ if (input) input.entry = entry
161
+ turn.serverSpeech = {}
162
+ }
163
+
164
+ /**
165
+ * @param {string} id
166
+ * @param {object} response
167
+ * @param {number} now
168
+ */
169
+ responseDone (id, response, now) {
170
+ const entry = this.#turns.get(id)
171
+ if (!entry || !response?.output) return
172
+ for (const item of response.output) {
173
+ if (item.id && item.type === 'message') this.#bindOutput(entry, item, now)
174
+ }
175
+ }
176
+
177
+ /**
178
+ * @param {import('./turns').ResponseTurn} turn
179
+ * @param {number} now
180
+ * @param {{ force?: boolean, transcriptPending?: boolean }} [options]
181
+ */
182
+ hold (turn, now, { force = false, transcriptPending = false } = {}) {
183
+ const entry = this.#find(turn)
184
+ if (!entry) return false
185
+ entry.held = true
186
+ entry.transcriptPending = transcriptPending
187
+ if (force) {
188
+ this.#discardUnheard(entry)
189
+ this.#remove(entry)
190
+ return false
191
+ }
192
+ if (entry.playbackWindow) this.#checkWindow(entry.playbackWindow, now, entry)
193
+ if (this.#ready(entry)) {
194
+ this.#remove(entry)
195
+ return false
196
+ }
197
+ this.#arm(entry)
198
+ return true
199
+ }
200
+
201
+ /** @param {object} event */
202
+ onClientEvent (event) {
203
+ if (event?.type !== 'conversation.item.retrieve') return
204
+ const item = this.#items.get(String(event.item_id))
205
+ if (!item) return
206
+ this.#clearInputWait(item)
207
+ item.inFlight = true
208
+ item.wanted = false
209
+ if (event.event_id) this.#requests.set(String(event.event_id), item)
210
+ }
211
+
212
+ /**
213
+ * @param {object} event
214
+ * @param {number} now
215
+ */
216
+ onServerEvent (event, now) {
217
+ const type = event.type
218
+ if (type === 'response.output_item.added' || type === 'response.output_item.done') {
219
+ const entry = this.#turns.get(String(event.response_id))
220
+ if (entry && event.item?.type === 'message') this.#bindOutput(entry, event.item, now)
221
+ } else if (type === 'conversation.item.done') {
222
+ const item = this.#items.get(String(event.item?.id))
223
+ if (item && this.#hasAudio(event.item)) {
224
+ this.#expectAudio(item, event.item)
225
+ this.#rebuild(item, now)
226
+ this.#want(item)
227
+ }
228
+ } else if (type === 'conversation.item.input_audio_transcription.completed' ||
229
+ type === 'conversation.item.input_audio_transcription.failed') {
230
+ const item = this.#items.get(String(event.item_id))
231
+ if (item) {
232
+ this.#clearInputWait(item)
233
+ // The SDK retrieves after completed transcription. Hold the turn while
234
+ // its synchronous handler sends, even when tracer retrieval is disabled.
235
+ if (type.endsWith('.completed') && this.#shouldRetainAudio() && !this.#hasRetrievedAudio(item)) {
236
+ item.wanted = true
237
+ this.#scheduleRequests()
238
+ }
239
+ this.#want(item)
240
+ }
241
+ } else if (type === 'conversation.item.retrieved') {
242
+ this.#retrieve(event.item, now)
243
+ } else if (type === 'conversation.item.truncated') {
244
+ const item = this.#items.get(String(event.item_id))
245
+ if (item) {
246
+ const endMs = event.audio_end_ms
247
+ if (typeof endMs === 'number' && Number.isFinite(endMs) && endMs >= 0) {
248
+ const index = event.content_index ?? 0
249
+ item.caps.set(index, Math.min(item.caps.get(index) ?? endMs, endMs))
250
+ if (item.entry) {
251
+ item.entry.truncated = true
252
+ let after = false
253
+ for (const output of item.entry.output.values()) {
254
+ if (after) {
255
+ output.lastContentIndex = -1
256
+ output.parts.clear()
257
+ output.wanted = false
258
+ }
259
+ if (output === item) {
260
+ output.lastContentIndex = Math.min(output.lastContentIndex, index)
261
+ after = true
262
+ }
263
+ }
264
+ }
265
+ this.#rebuild(item, now)
266
+ this.#want(item)
267
+ this.#check(item.entry, now)
268
+ }
269
+ }
270
+ } else if (type === 'output_audio_buffer.started') {
271
+ const entry = this.#turns.get(String(event.response_id))
272
+ if (entry) {
273
+ const active = this.#active
274
+ entry.hasAudio = true
275
+ entry.turn.serverSpeech.startTime ??= now
276
+ // Install the new dependency before finishing older turns: removing the old
277
+ // active turn must not shorten waits for responses still queued after this one.
278
+ this.#active = entry
279
+ for (const previous of this.#turns.values()) {
280
+ if (previous === entry) break
281
+ if (previous.held && previous.hasAudio &&
282
+ previous.turn.serverSpeech.startTime === undefined && !previous.stopped) {
283
+ this.#finish(previous, now, true)
284
+ }
285
+ }
286
+ if (active && active !== entry) {
287
+ // A response-specific start supplies the handoff boundary even when the
288
+ // shared output buffer never drains between a tool preamble and its answer.
289
+ active.stopped = true
290
+ active.turn.serverSpeech.finishTime = now
291
+ this.#check(active, now)
292
+ }
293
+ this.#check(entry, now)
294
+ }
295
+ } else if (type === 'output_audio_buffer.stopped' || type === 'output_audio_buffer.cleared') {
296
+ const entry = this.#turns.get(String(event.response_id))
297
+ if (type === 'output_audio_buffer.stopped' && this.#active && this.#active !== entry && entry) {
298
+ const window = this.#createWindow(this.#active, entry, now)
299
+ if (window) {
300
+ for (const member of window.entries) {
301
+ member.stopped = true
302
+ member.playbackWindow = window
303
+ member.turn.serverSpeech = {}
304
+ }
305
+ this.#active = undefined
306
+ this.#checkWindow(window, now)
307
+ this.#releaseQueuedWaits()
308
+ return
309
+ }
310
+ }
311
+ if (this.#active && this.#active !== entry) {
312
+ // A cleared or untracked window lacks enough evidence to place its clips.
313
+ const active = this.#active
314
+ active.ambiguous = true
315
+ active.stopped = true
316
+ active.cleared = type === 'output_audio_buffer.cleared'
317
+ active.turn.serverSpeech = {}
318
+ this.#check(active, now)
319
+ if (entry) entry.ambiguous = true
320
+ }
321
+ if (entry) {
322
+ entry.stopped = true
323
+ entry.cleared = type === 'output_audio_buffer.cleared'
324
+ if (entry.ambiguous) { entry.turn.serverSpeech = {} } else { entry.turn.serverSpeech.finishTime = now }
325
+ this.#check(entry, now)
326
+ }
327
+ this.#active = undefined
328
+ this.#releaseQueuedWaits()
329
+ } else if (type === 'error') {
330
+ const item = this.#requests.get(String(event.error?.event_id))
331
+ if (item) {
332
+ item.inFlight = item.wanted = false
333
+ item.failed = true
334
+ this.#check(item.entry, now)
335
+ }
336
+ }
337
+ }
338
+
339
+ /** @param {{ type?: string, error?: { event_id?: unknown } } | undefined} event */
340
+ isRetrievalError (event) {
341
+ if (event?.type !== 'error') return false
342
+ const id = event.error?.event_id
343
+ if (typeof id !== 'string' || !id.startsWith(this.#requestPrefix)) return false
344
+ const suffix = id.slice(this.#requestPrefix.length)
345
+ const sequence = Number(suffix)
346
+ return Number.isSafeInteger(sequence) && sequence > 0 && sequence <= this.#sequence && String(sequence) === suffix
347
+ }
348
+
349
+ /** @param {number} now */
350
+ finishSession (now) {
351
+ this.#closed = true
352
+ clearImmediate(this.#scheduled)
353
+ for (const entry of this.#turns.values()) this.#finish(entry, now, true)
354
+ for (const item of this.#items.values()) {
355
+ this.#clearInputWait(item)
356
+ item.parts.clear()
357
+ if (item.role === 'user') this.#inputs.delete(item.side)
358
+ }
359
+ this.#items.clear()
360
+ this.#requests.clear()
361
+ }
362
+
363
+ /** @param {object} message */
364
+ #hasAudio (message) {
365
+ return message?.content?.some(part => AUDIO_CONTENT_TYPES.has(part.type))
366
+ }
367
+
368
+ /**
369
+ * @param {object} entry
370
+ * @param {object} message
371
+ * @param {number} now
372
+ */
373
+ #bindOutput (entry, message, now) {
374
+ if (typeof message.id !== 'string' || !message.id) return
375
+ const hasAudio = this.#hasAudio(message)
376
+ if (hasAudio) {
377
+ entry.hasAudio = true
378
+ entry.turn.audio.present = true
379
+ }
380
+ const item = this.#bind(message.id, entry.turn, entry, 'assistant')
381
+ if (!item) {
382
+ if (hasAudio) {
383
+ entry.audioIncomplete = true
384
+ entry.turn.audio.clear()
385
+ entry.turn.audio.present = true
386
+ }
387
+ return
388
+ }
389
+ entry.output.set(item.id, item)
390
+ this.#expectAudio(item, message)
391
+ this.#rebuild(item, now)
392
+ if (hasAudio && message.status === 'completed') this.#want(item)
393
+ }
394
+
395
+ /**
396
+ * @param {{ expected: Set<number>, hasAudio: boolean }} item
397
+ * @param {{ content?: Array<{ type?: string }> }} message
398
+ */
399
+ #expectAudio (item, message) {
400
+ for (const [index, part] of (message.content || []).entries()) {
401
+ if (AUDIO_CONTENT_TYPES.has(part.type)) {
402
+ item.expected.add(index)
403
+ item.hasAudio = true
404
+ }
405
+ }
406
+ }
407
+
408
+ /**
409
+ * @param {string} id
410
+ * @param {object} side
411
+ * @param {object | undefined} entry
412
+ * @param {string} role
413
+ */
414
+ #bind (id, side, entry, role) {
415
+ let item = this.#items.get(id)
416
+ if (!item) {
417
+ while (this.#items.size >= MAX_ITEMS) {
418
+ if (!this.#evictHeld(Date.now())) break
419
+ }
420
+ if (this.#items.size >= MAX_ITEMS) {
421
+ let orphan
422
+ for (const candidate of this.#items.values()) {
423
+ if (!candidate.entry) { orphan = candidate; break }
424
+ }
425
+ if (!orphan) return
426
+ this.#clearInputWait(orphan)
427
+ orphan.parts.clear()
428
+ orphan.side.audio.clear()
429
+ orphan.side.audio.present = orphan.hasAudio
430
+ this.#inputs.delete(orphan.side)
431
+ this.#items.delete(orphan.id)
432
+ for (const [eventId, request] of this.#requests) {
433
+ if (request === orphan) this.#requests.delete(eventId)
434
+ }
435
+ }
436
+ item = {
437
+ id,
438
+ side,
439
+ entry,
440
+ role,
441
+ format: role === 'user' ? this.#inputFormat : entry.format,
442
+ lastContentIndex: role === 'assistant' && entry.truncated ? -1 : Infinity,
443
+ parts: new Map(),
444
+ expected: new Set(),
445
+ hasAudio: role === 'user',
446
+ caps: new Map(),
447
+ inFlight: false,
448
+ wanted: false,
449
+ attempts: 0,
450
+ failed: false,
451
+ retrievedComplete: false,
452
+ waitingForTranscript: false,
453
+ inputTimer: undefined,
454
+ }
455
+ this.#items.set(id, item)
456
+ }
457
+ if (entry) item.entry = entry
458
+ return item
459
+ }
460
+
461
+ /** @param {object} item */
462
+ #want (item) {
463
+ const requestItem = this.#requestItem
464
+ if (item.lastContentIndex < 0 || item.failed || item.attempts >= 2 ||
465
+ !this.#shouldRetainAudio() || !requestItem || item.inFlight || this.#hasRetrievedAudio(item)) return
466
+ item.wanted = true
467
+ if (item.waitingForTranscript) {
468
+ if (!item.inputTimer) {
469
+ // Leave half the existing audio wait for a fallback reply if transcription
470
+ // never arrives; normal completions let the SDK issue its own retrieval.
471
+ item.inputTimer = setTimeout(() => {
472
+ item.inputTimer = undefined
473
+ if (this.#closed || this.#items.get(item.id) !== item) return
474
+ item.waitingForTranscript = false
475
+ item.wanted = false
476
+ this.#want(item)
477
+ }, INPUT_TRANSCRIPT_WAIT_MS)
478
+ item.inputTimer.unref?.()
479
+ }
480
+ return
481
+ }
482
+ this.#scheduleRequests()
483
+ }
484
+
485
+ /**
486
+ * Let the SDK claim requests synchronously, then release passive waits when
487
+ * neither the SDK nor the tracer can send.
488
+ */
489
+ #scheduleRequests () {
490
+ const requestItem = this.#requestItem
491
+ if (this.#scheduled || this.#closed) return
492
+ this.#scheduled = setImmediate(() => {
493
+ this.#scheduled = undefined
494
+ for (const candidate of this.#items.values()) {
495
+ if (!candidate.wanted || candidate.inFlight || candidate.waitingForTranscript ||
496
+ candidate.lastContentIndex < 0) continue
497
+ candidate.wanted = false
498
+ if (!this.#shouldRetainAudio() || !requestItem || candidate.failed || candidate.attempts >= 2) {
499
+ this.#check(candidate.entry, Date.now())
500
+ continue
501
+ }
502
+ const eventId = this.#requestPrefix + (++this.#sequence)
503
+ candidate.inFlight = true
504
+ candidate.attempts++
505
+ this.#requests.set(eventId, candidate)
506
+ try {
507
+ requestItem(candidate.id, eventId)
508
+ } catch (error) {
509
+ candidate.inFlight = false
510
+ candidate.failed = true
511
+ log.debug('Error retrieving OpenAI realtime audio: %s', error?.message)
512
+ this.#check(candidate.entry, Date.now())
513
+ }
514
+ }
515
+ })
516
+ this.#scheduled.unref?.()
517
+ }
518
+
519
+ /**
520
+ * @param {object} message
521
+ * @param {number} now
522
+ */
523
+ #retrieve (message, now) {
524
+ const item = this.#items.get(String(message?.id))
525
+ if (!item) return
526
+ this.#clearInputWait(item)
527
+ item.inFlight = item.wanted = false
528
+ item.retrievedComplete = message.status === 'completed'
529
+ let receivedTranscript = false
530
+ if (message.content) {
531
+ const items = item.role === 'assistant' ? item.entry.output.values() : [item]
532
+ let total = 0
533
+ for (const owned of items) {
534
+ for (const [index, part] of owned.parts) {
535
+ if (index <= owned.lastContentIndex) total += part.bytes
536
+ }
537
+ }
538
+ const updates = []
539
+ let index = 0
540
+ for (const part of message.content) {
541
+ if (typeof part.audio === 'string' && index <= item.lastContentIndex) {
542
+ const fallback = item.format
543
+ const current = item.role === 'user' ? this.#inputFormat : this.#outputFormat
544
+ // The protocol does not say whether retrieval transcodes older clips.
545
+ // Without an explicit format, omit audio when the two possible codecs differ.
546
+ const knownFormat = part.format ||
547
+ (fallback.mimeType === current.mimeType && fallback.sampleRate === current.sampleRate)
548
+ const mimeType = part.format ? realtimeAudioFormatToMime(part.format) : fallback.mimeType
549
+ const sampleRate = typeof part.format?.rate === 'number' ? part.format.rate : fallback.sampleRate
550
+ const cap = item.caps.get(index)
551
+ const rate = bytesPerSecond(mimeType, sampleRate)
552
+ const count = Buffer.byteLength(part.audio, 'base64')
553
+ const bytes = cap === undefined || !rate ? count : Math.min(count, Math.floor(cap * rate / 1000))
554
+ total += bytes - (item.parts.get(index)?.bytes ?? 0)
555
+ updates.push({ index, audio: part.audio, bytes, mimeType, sampleRate, knownFormat })
556
+ item.expected.add(index)
557
+ item.hasAudio = true
558
+ }
559
+ if (item.role === 'user' && item.id === item.side.itemId &&
560
+ typeof part.transcript === 'string' && part.transcript) {
561
+ item.side.transcript ||= part.transcript
562
+ receivedTranscript = true
563
+ }
564
+ index++
565
+ }
566
+ // Credit replaced allocations only after both owners have released them.
567
+ if (updates.length) {
568
+ item.side.audio.clear()
569
+ for (const { index } of updates) item.parts.delete(index)
570
+ }
571
+ let incomingBytes = 0
572
+ for (const update of updates) if (update.knownFormat) incomingBytes += update.bytes
573
+ const retain = total <= LLMOBS_AUDIO_ACCUMULATE_MAX_BYTES && this.#shouldRetainAudio() &&
574
+ this.#cachedAudioBytes() + incomingBytes <= MAX_CACHED_AUDIO_BYTES
575
+ if (!retain && updates.length) this.#dropCachedAudio(item)
576
+ for (const { index, audio, bytes, mimeType, sampleRate, knownFormat } of updates) {
577
+ let buffer
578
+ if (retain && knownFormat) {
579
+ // Dedicated backing stores make cache accounting exact even after a
580
+ // truncation creates a shorter view. Never expose unwritten bytes.
581
+ const decoded = Buffer.allocUnsafeSlow(bytes)
582
+ const written = decoded.write(audio, 0, bytes, 'base64')
583
+ buffer = decoded.subarray(0, written)
584
+ }
585
+ item.parts.set(index, { bytes, buffer, mimeType, sampleRate })
586
+ }
587
+ }
588
+ this.#rebuild(item, now)
589
+ if (receivedTranscript) this.#onTranscript?.(item.id, item.side.transcript, now)
590
+ this.#check(item.entry, now)
591
+ }
592
+
593
+ /**
594
+ * @param {{ inputTimer?: ReturnType<typeof setTimeout>, waitingForTranscript: boolean }} item
595
+ */
596
+ #clearInputWait (item) {
597
+ clearTimeout(item.inputTimer)
598
+ item.inputTimer = undefined
599
+ item.waitingForTranscript = false
600
+ }
601
+
602
+ /**
603
+ * @param {{ retrievedComplete: boolean, expected: Set<number>, lastContentIndex: number,
604
+ * parts: Map<number, { buffer?: Buffer, bytes: number }> }} item
605
+ */
606
+ #hasRetrievedAudio (item) {
607
+ if (!item.retrievedComplete) return false
608
+ let hasAudio = false
609
+ for (const index of item.expected) {
610
+ if (index > item.lastContentIndex) continue
611
+ const part = item.parts.get(index)
612
+ if (!part?.buffer || part.buffer.length !== part.bytes) return false
613
+ hasAudio = true
614
+ }
615
+ return hasAudio
616
+ }
617
+
618
+ /** Count owned backing allocations, including the hidden tail of truncated views. */
619
+ #cachedAudioBytes () {
620
+ let total = 0
621
+ for (const item of this.#items.values()) {
622
+ for (const part of item.parts.values()) total += part.buffer?.buffer.byteLength ?? 0
623
+ }
624
+ return total
625
+ }
626
+
627
+ /**
628
+ * @param {{ role: string, entry?: PlaybackEntry, parts: Map<number, { buffer?: Buffer }>,
629
+ * side: { audio: import('./audio-accumulator') } }} item
630
+ */
631
+ #dropCachedAudio (item) {
632
+ if (item.role === 'assistant' && item.entry) {
633
+ for (const output of item.entry.output.values()) {
634
+ for (const part of output.parts.values()) part.buffer = undefined
635
+ }
636
+ } else {
637
+ for (const part of item.parts.values()) part.buffer = undefined
638
+ }
639
+ item.side.audio.clear()
640
+ }
641
+
642
+ /**
643
+ * @param {object} item
644
+ * @param {number} now
645
+ */
646
+ #rebuild (item, now) {
647
+ const items = item.role === 'assistant' ? item.entry.output.values() : [item]
648
+ const parts = []
649
+ let complete = !item.entry?.audioIncomplete
650
+ for (const owned of items) {
651
+ if (!owned.hasAudio || owned.lastContentIndex < 0) continue
652
+ if (owned.parts.size === 0) complete = false
653
+ for (const index of owned.expected) {
654
+ if (index <= owned.lastContentIndex && !owned.parts.has(index)) complete = false
655
+ }
656
+ for (const [index, part] of owned.parts) {
657
+ if (index > owned.lastContentIndex) {
658
+ owned.parts.delete(index)
659
+ continue
660
+ }
661
+ const cap = owned.caps.get(index)
662
+ const rate = bytesPerSecond(part.mimeType, part.sampleRate)
663
+ if (cap !== undefined && rate) {
664
+ part.bytes = Math.min(part.bytes, Math.floor(cap * rate / 1000))
665
+ if (part.buffer) part.buffer = part.buffer.subarray(0, part.bytes)
666
+ }
667
+ parts.push(part)
668
+ }
669
+ }
670
+ let total = 0
671
+ const first = parts[0]
672
+ for (const part of parts) {
673
+ total += part.bytes
674
+ if (part.buffer === undefined || part.mimeType !== first?.mimeType ||
675
+ part.sampleRate !== first?.sampleRate) complete = false
676
+ }
677
+ if (total > LLMOBS_AUDIO_ACCUMULATE_MAX_BYTES) {
678
+ for (const part of parts) part.buffer = undefined
679
+ complete = false
680
+ }
681
+ const buffers = []
682
+ if (complete) for (const part of parts) buffers.push(part.buffer)
683
+ item.side.audio.replaceBuffers(buffers, total, now,
684
+ first?.mimeType || '', first?.sampleRate || 0)
685
+ item.side.audio.present ||= item.role === 'assistant' ? item.entry.hasAudio : item.hasAudio
686
+ }
687
+
688
+ /**
689
+ * @param {PlaybackEntry} first
690
+ * @param {PlaybackEntry} last
691
+ * @param {number} now
692
+ */
693
+ #createWindow (first, last, now) {
694
+ const startTime = first.turn.serverSpeech?.startTime
695
+ if (startTime === undefined || now < startTime) return
696
+ const entries = []
697
+ let collecting = false
698
+ for (const entry of this.#turns.values()) {
699
+ if (entry === first) collecting = true
700
+ if (!collecting) continue
701
+ if (entry.stopped || entry.playbackWindow) return
702
+ entries.push(entry)
703
+ if (entry === last) return { entries, startTime, finishTime: now, resolved: false }
704
+ }
705
+ }
706
+
707
+ /** @param {PlaybackWindow} window */
708
+ #deriveWindow (window) {
709
+ if (window.resolved) return
710
+ for (const entry of window.entries) {
711
+ if (!entry.held) return
712
+ for (const item of entry.output.values()) {
713
+ if (item.wanted || item.inFlight) return
714
+ }
715
+ }
716
+ window.resolved = true
717
+ const durations = []
718
+ let total = 0
719
+ for (const entry of window.entries) {
720
+ if (!entry.hasAudio) { durations.push(0); continue }
721
+ const audio = entry.turn.audio
722
+ const duration = segmentDurationMs(audio.totalDecodedBytes, audio.mimeType, audio.sampleRate)
723
+ if (entry.audioIncomplete || audio.oversize || audio.chunks.length === 0 ||
724
+ duration === undefined || duration <= 0) return
725
+ durations.push(duration)
726
+ total += duration
727
+ }
728
+ // Arrival timestamps are rounded to milliseconds. Larger inconsistencies are
729
+ // not a consistent playback window and must leave its response boundaries unknown.
730
+ if (total > window.finishTime - window.startTime + 1) return
731
+ let end = window.finishTime
732
+ for (let index = window.entries.length - 1; index >= 0; index--) {
733
+ const duration = durations[index]
734
+ if (!duration) continue
735
+ const start = index === 0 ? window.startTime : Math.max(window.startTime, end - duration)
736
+ const finish = index === 0 ? Math.max(start, Math.min(end, start + duration)) : end
737
+ window.entries[index].turn.serverSpeech = { startTime: start, finishTime: finish, derived: true }
738
+ end = start
739
+ }
740
+ }
741
+
742
+ /**
743
+ * @param {PlaybackWindow} window
744
+ * @param {number} now
745
+ * @param {PlaybackEntry} [skip] - The owner of hold() must finalize its own turn.
746
+ */
747
+ #checkWindow (window, now, skip) {
748
+ this.#deriveWindow(window)
749
+ let index = 0
750
+ while (index < window.entries.length) {
751
+ const entry = window.entries[index]
752
+ if (entry === skip || !entry.held || !this.#turns.has(entry.id)) { index++; continue }
753
+ if (this.#ready(entry)) {
754
+ // Removal releases this member's buffers and shifts the next member into its slot.
755
+ this.#finish(entry, now)
756
+ } else {
757
+ this.#arm(entry)
758
+ index++
759
+ }
760
+ }
761
+ }
762
+
763
+ /** @param {object} entry */
764
+ #ready (entry) {
765
+ if (entry.playbackWindow && !entry.playbackWindow.resolved) return false
766
+ if (entry.transcriptPending || (entry.hasAudio && !entry.stopped) ||
767
+ (entry.cleared && !entry.truncated)) return false
768
+ if (!this.#shouldRetainAudio()) return true
769
+ const input = this.#items.get(entry.turn.input.itemId)
770
+ for (const item of [input, ...entry.output.values()]) {
771
+ if (item && item.lastContentIndex >= 0 && (item.wanted || item.inFlight)) return false
772
+ }
773
+ return true
774
+ }
775
+
776
+ /**
777
+ * @param {object | undefined} entry
778
+ * @param {number} now
779
+ */
780
+ #check (entry, now) {
781
+ if (entry?.playbackWindow) {
782
+ this.#checkWindow(entry.playbackWindow, now)
783
+ return
784
+ }
785
+ if (!entry?.held) return
786
+ if (this.#ready(entry)) this.#finish(entry, now)
787
+ else this.#arm(entry)
788
+ }
789
+
790
+ /** @param {object} entry */
791
+ #arm (entry) {
792
+ clearTimeout(entry.timer)
793
+ // A completed response without its own start can be queued behind the active
794
+ // response. Its playback evidence cannot arrive until that shared buffer drains.
795
+ const queued = !entry.outOfBand && entry.hasAudio && this.#active &&
796
+ this.#active !== entry && !this.#active.stopped
797
+ const phase = entry.stopped
798
+ ? 'audio'
799
+ : entry.turn.serverSpeech.startTime === undefined ? queued ? 'queued' : 'audio' : 'playback'
800
+ if (entry.phase !== phase) {
801
+ entry.phase = phase
802
+ entry.deadline = Date.now() + (phase === 'audio' ? AUDIO_WAIT_MS : PLAYBACK_WAIT_MS)
803
+ }
804
+ entry.timer = setTimeout(() => this.#finish(entry, Date.now(), true), Math.max(0, entry.deadline - Date.now()))
805
+ entry.timer.unref?.()
806
+ }
807
+
808
+ // An unstarted response loses its queue dependency when active playback ends.
809
+ #releaseQueuedWaits () {
810
+ if (this.#closed) return
811
+ for (const entry of this.#turns.values()) {
812
+ if (entry.held && entry.phase === 'queued' && entry.turn.serverSpeech.startTime === undefined) {
813
+ this.#arm(entry)
814
+ }
815
+ }
816
+ }
817
+
818
+ /** @param {number} now */
819
+ #evictHeld (now) {
820
+ for (const entry of this.#turns.values()) {
821
+ if (entry.held) {
822
+ this.#finish(entry, now, true)
823
+ return true
824
+ }
825
+ }
826
+ return false
827
+ }
828
+
829
+ /**
830
+ * @param {object} entry
831
+ * @param {number} now
832
+ * @param {boolean} [force]
833
+ */
834
+ #finish (entry, now, force = false) {
835
+ if (!entry || !this.#turns.has(entry.id)) return
836
+ if (force) this.#discardUnheard(entry)
837
+ this.#remove(entry)
838
+ this.#onReady(entry.turn, now)
839
+ }
840
+
841
+ /** @param {object} entry */
842
+ #discardUnheard (entry) {
843
+ if (!entry.stopped || (entry.cleared && !entry.truncated)) {
844
+ entry.turn.audio.clear()
845
+ entry.turn.audio.present = entry.hasAudio
846
+ }
847
+ if (!entry.stopped) entry.turn.serverSpeech = {}
848
+ }
849
+
850
+ /** @param {object} entry */
851
+ #remove (entry) {
852
+ const window = entry.playbackWindow
853
+ if (window && !window.resolved) {
854
+ window.resolved = true
855
+ for (const member of window.entries) member.turn.serverSpeech = {}
856
+ }
857
+ if (window) {
858
+ const index = window.entries.indexOf(entry)
859
+ if (index !== -1) window.entries.splice(index, 1)
860
+ entry.playbackWindow = undefined
861
+ }
862
+ clearTimeout(entry.timer)
863
+ this.#turns.delete(entry.id)
864
+ if (this.#active === entry) {
865
+ this.#active = undefined
866
+ this.#releaseQueuedWaits()
867
+ }
868
+ for (const [id, item] of this.#items) {
869
+ if (item.entry === entry) {
870
+ this.#clearInputWait(item)
871
+ item.parts.clear()
872
+ if (item.role === 'user') this.#inputs.delete(item.side)
873
+ this.#items.delete(id)
874
+ }
875
+ }
876
+ for (const [id, item] of this.#requests) {
877
+ if (item.entry === entry) this.#requests.delete(id)
878
+ }
879
+ }
880
+
881
+ /** @param {import('./turns').ResponseTurn} turn */
882
+ #find (turn) {
883
+ for (const entry of this.#turns.values()) if (entry.turn === turn) return entry
884
+ }
885
+ }
886
+
887
+ module.exports = ServerPlayback