@livekit/agents 1.1.0 → 1.2.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 (942) hide show
  1. package/dist/audio.cjs +89 -3
  2. package/dist/audio.cjs.map +1 -1
  3. package/dist/audio.d.cts +36 -1
  4. package/dist/audio.d.ts +36 -1
  5. package/dist/audio.d.ts.map +1 -1
  6. package/dist/audio.js +76 -2
  7. package/dist/audio.js.map +1 -1
  8. package/dist/beta/index.cjs +29 -0
  9. package/dist/beta/index.cjs.map +1 -0
  10. package/dist/beta/index.d.cts +2 -0
  11. package/dist/beta/index.d.ts +2 -0
  12. package/dist/beta/index.d.ts.map +1 -0
  13. package/dist/beta/index.js +7 -0
  14. package/dist/beta/index.js.map +1 -0
  15. package/dist/beta/workflows/index.cjs +29 -0
  16. package/dist/beta/workflows/index.cjs.map +1 -0
  17. package/dist/beta/workflows/index.d.cts +2 -0
  18. package/dist/beta/workflows/index.d.ts +2 -0
  19. package/dist/beta/workflows/index.d.ts.map +1 -0
  20. package/dist/beta/workflows/index.js +7 -0
  21. package/dist/beta/workflows/index.js.map +1 -0
  22. package/dist/beta/workflows/task_group.cjs +162 -0
  23. package/dist/beta/workflows/task_group.cjs.map +1 -0
  24. package/dist/beta/workflows/task_group.d.cts +32 -0
  25. package/dist/beta/workflows/task_group.d.ts +32 -0
  26. package/dist/beta/workflows/task_group.d.ts.map +1 -0
  27. package/dist/beta/workflows/task_group.js +138 -0
  28. package/dist/beta/workflows/task_group.js.map +1 -0
  29. package/dist/cli.cjs +44 -46
  30. package/dist/cli.cjs.map +1 -1
  31. package/dist/cli.d.cts +3 -3
  32. package/dist/cli.d.ts +3 -3
  33. package/dist/cli.d.ts.map +1 -1
  34. package/dist/cli.js +45 -47
  35. package/dist/cli.js.map +1 -1
  36. package/dist/connection_pool.cjs +242 -0
  37. package/dist/connection_pool.cjs.map +1 -0
  38. package/dist/connection_pool.d.cts +123 -0
  39. package/dist/connection_pool.d.ts +123 -0
  40. package/dist/connection_pool.d.ts.map +1 -0
  41. package/dist/connection_pool.js +218 -0
  42. package/dist/connection_pool.js.map +1 -0
  43. package/dist/connection_pool.test.cjs +256 -0
  44. package/dist/connection_pool.test.cjs.map +1 -0
  45. package/dist/connection_pool.test.js +255 -0
  46. package/dist/connection_pool.test.js.map +1 -0
  47. package/dist/constants.cjs +30 -0
  48. package/dist/constants.cjs.map +1 -1
  49. package/dist/constants.d.cts +10 -0
  50. package/dist/constants.d.ts +10 -0
  51. package/dist/constants.d.ts.map +1 -1
  52. package/dist/constants.js +20 -0
  53. package/dist/constants.js.map +1 -1
  54. package/dist/cpu.cjs +189 -0
  55. package/dist/cpu.cjs.map +1 -0
  56. package/dist/cpu.d.cts +24 -0
  57. package/dist/cpu.d.ts +24 -0
  58. package/dist/cpu.d.ts.map +1 -0
  59. package/dist/cpu.js +152 -0
  60. package/dist/cpu.js.map +1 -0
  61. package/dist/cpu.test.cjs +227 -0
  62. package/dist/cpu.test.cjs.map +1 -0
  63. package/dist/cpu.test.js +204 -0
  64. package/dist/cpu.test.js.map +1 -0
  65. package/dist/http_server.cjs +9 -6
  66. package/dist/http_server.cjs.map +1 -1
  67. package/dist/http_server.d.cts +5 -1
  68. package/dist/http_server.d.ts +5 -1
  69. package/dist/http_server.d.ts.map +1 -1
  70. package/dist/http_server.js +9 -6
  71. package/dist/http_server.js.map +1 -1
  72. package/dist/index.cjs +24 -9
  73. package/dist/index.cjs.map +1 -1
  74. package/dist/index.d.cts +15 -11
  75. package/dist/index.d.ts +15 -11
  76. package/dist/index.d.ts.map +1 -1
  77. package/dist/index.js +18 -9
  78. package/dist/index.js.map +1 -1
  79. package/dist/inference/api_protos.cjs +70 -2
  80. package/dist/inference/api_protos.cjs.map +1 -1
  81. package/dist/inference/api_protos.d.cts +373 -32
  82. package/dist/inference/api_protos.d.ts +373 -32
  83. package/dist/inference/api_protos.d.ts.map +1 -1
  84. package/dist/inference/api_protos.js +62 -2
  85. package/dist/inference/api_protos.js.map +1 -1
  86. package/dist/inference/index.cjs +8 -0
  87. package/dist/inference/index.cjs.map +1 -1
  88. package/dist/inference/index.d.cts +3 -4
  89. package/dist/inference/index.d.ts +3 -4
  90. package/dist/inference/index.d.ts.map +1 -1
  91. package/dist/inference/index.js +18 -3
  92. package/dist/inference/index.js.map +1 -1
  93. package/dist/inference/interruption/defaults.cjs +81 -0
  94. package/dist/inference/interruption/defaults.cjs.map +1 -0
  95. package/dist/inference/interruption/defaults.d.cts +19 -0
  96. package/dist/inference/interruption/defaults.d.ts +19 -0
  97. package/dist/inference/interruption/defaults.d.ts.map +1 -0
  98. package/dist/inference/interruption/defaults.js +46 -0
  99. package/dist/inference/interruption/defaults.js.map +1 -0
  100. package/dist/inference/interruption/errors.cjs +44 -0
  101. package/dist/inference/interruption/errors.cjs.map +1 -0
  102. package/dist/inference/interruption/errors.d.cts +12 -0
  103. package/dist/inference/interruption/errors.d.ts +12 -0
  104. package/dist/inference/interruption/errors.d.ts.map +1 -0
  105. package/dist/inference/interruption/errors.js +20 -0
  106. package/dist/inference/interruption/errors.js.map +1 -0
  107. package/dist/inference/interruption/http_transport.cjs +163 -0
  108. package/dist/inference/interruption/http_transport.cjs.map +1 -0
  109. package/dist/inference/interruption/http_transport.d.cts +63 -0
  110. package/dist/inference/interruption/http_transport.d.ts +63 -0
  111. package/dist/inference/interruption/http_transport.d.ts.map +1 -0
  112. package/dist/inference/interruption/http_transport.js +137 -0
  113. package/dist/inference/interruption/http_transport.js.map +1 -0
  114. package/dist/inference/interruption/interruption_cache_entry.cjs +58 -0
  115. package/dist/inference/interruption/interruption_cache_entry.cjs.map +1 -0
  116. package/dist/inference/interruption/interruption_cache_entry.d.cts +30 -0
  117. package/dist/inference/interruption/interruption_cache_entry.d.ts +30 -0
  118. package/dist/inference/interruption/interruption_cache_entry.d.ts.map +1 -0
  119. package/dist/inference/interruption/interruption_cache_entry.js +34 -0
  120. package/dist/inference/interruption/interruption_cache_entry.js.map +1 -0
  121. package/dist/inference/interruption/interruption_detector.cjs +198 -0
  122. package/dist/inference/interruption/interruption_detector.cjs.map +1 -0
  123. package/dist/inference/interruption/interruption_detector.d.cts +59 -0
  124. package/dist/inference/interruption/interruption_detector.d.ts +59 -0
  125. package/dist/inference/interruption/interruption_detector.d.ts.map +1 -0
  126. package/dist/inference/interruption/interruption_detector.js +164 -0
  127. package/dist/inference/interruption/interruption_detector.js.map +1 -0
  128. package/dist/inference/interruption/interruption_stream.cjs +368 -0
  129. package/dist/inference/interruption/interruption_stream.cjs.map +1 -0
  130. package/dist/inference/interruption/interruption_stream.d.cts +46 -0
  131. package/dist/inference/interruption/interruption_stream.d.ts +46 -0
  132. package/dist/inference/interruption/interruption_stream.d.ts.map +1 -0
  133. package/dist/inference/interruption/interruption_stream.js +344 -0
  134. package/dist/inference/interruption/interruption_stream.js.map +1 -0
  135. package/dist/inference/interruption/types.cjs +17 -0
  136. package/dist/inference/interruption/types.cjs.map +1 -0
  137. package/dist/inference/interruption/types.d.cts +66 -0
  138. package/dist/inference/interruption/types.d.ts +66 -0
  139. package/dist/inference/interruption/types.d.ts.map +1 -0
  140. package/dist/inference/interruption/types.js +1 -0
  141. package/dist/inference/interruption/types.js.map +1 -0
  142. package/dist/inference/interruption/utils.cjs +130 -0
  143. package/dist/inference/interruption/utils.cjs.map +1 -0
  144. package/dist/inference/interruption/utils.d.cts +41 -0
  145. package/dist/inference/interruption/utils.d.ts +41 -0
  146. package/dist/inference/interruption/utils.d.ts.map +1 -0
  147. package/dist/inference/interruption/utils.js +105 -0
  148. package/dist/inference/interruption/utils.js.map +1 -0
  149. package/dist/inference/interruption/utils.test.cjs +105 -0
  150. package/dist/inference/interruption/utils.test.cjs.map +1 -0
  151. package/dist/inference/interruption/utils.test.js +104 -0
  152. package/dist/inference/interruption/utils.test.js.map +1 -0
  153. package/dist/inference/interruption/ws_transport.cjs +342 -0
  154. package/dist/inference/interruption/ws_transport.cjs.map +1 -0
  155. package/dist/inference/interruption/ws_transport.d.cts +33 -0
  156. package/dist/inference/interruption/ws_transport.d.ts +33 -0
  157. package/dist/inference/interruption/ws_transport.d.ts.map +1 -0
  158. package/dist/inference/interruption/ws_transport.js +308 -0
  159. package/dist/inference/interruption/ws_transport.js.map +1 -0
  160. package/dist/inference/llm.cjs +106 -66
  161. package/dist/inference/llm.cjs.map +1 -1
  162. package/dist/inference/llm.d.cts +65 -43
  163. package/dist/inference/llm.d.ts +65 -43
  164. package/dist/inference/llm.d.ts.map +1 -1
  165. package/dist/inference/llm.js +100 -66
  166. package/dist/inference/llm.js.map +1 -1
  167. package/dist/inference/stt.cjs +319 -170
  168. package/dist/inference/stt.cjs.map +1 -1
  169. package/dist/inference/stt.d.cts +64 -15
  170. package/dist/inference/stt.d.ts +64 -15
  171. package/dist/inference/stt.d.ts.map +1 -1
  172. package/dist/inference/stt.js +319 -170
  173. package/dist/inference/stt.js.map +1 -1
  174. package/dist/inference/stt.test.cjs +218 -0
  175. package/dist/inference/stt.test.cjs.map +1 -0
  176. package/dist/inference/stt.test.js +217 -0
  177. package/dist/inference/stt.test.js.map +1 -0
  178. package/dist/inference/tts.cjs +249 -71
  179. package/dist/inference/tts.cjs.map +1 -1
  180. package/dist/inference/tts.d.cts +55 -16
  181. package/dist/inference/tts.d.ts +55 -16
  182. package/dist/inference/tts.d.ts.map +1 -1
  183. package/dist/inference/tts.js +249 -77
  184. package/dist/inference/tts.js.map +1 -1
  185. package/dist/inference/tts.test.cjs +233 -0
  186. package/dist/inference/tts.test.cjs.map +1 -0
  187. package/dist/inference/tts.test.js +232 -0
  188. package/dist/inference/tts.test.js.map +1 -0
  189. package/dist/inference/utils.cjs +26 -7
  190. package/dist/inference/utils.cjs.map +1 -1
  191. package/dist/inference/utils.d.cts +14 -1
  192. package/dist/inference/utils.d.ts +14 -1
  193. package/dist/inference/utils.d.ts.map +1 -1
  194. package/dist/inference/utils.js +18 -2
  195. package/dist/inference/utils.js.map +1 -1
  196. package/dist/ipc/inference_proc_executor.cjs +6 -3
  197. package/dist/ipc/inference_proc_executor.cjs.map +1 -1
  198. package/dist/ipc/inference_proc_executor.d.ts.map +1 -1
  199. package/dist/ipc/inference_proc_executor.js +6 -3
  200. package/dist/ipc/inference_proc_executor.js.map +1 -1
  201. package/dist/ipc/inference_proc_lazy_main.cjs +13 -1
  202. package/dist/ipc/inference_proc_lazy_main.cjs.map +1 -1
  203. package/dist/ipc/inference_proc_lazy_main.js +13 -1
  204. package/dist/ipc/inference_proc_lazy_main.js.map +1 -1
  205. package/dist/ipc/job_proc_executor.cjs +6 -1
  206. package/dist/ipc/job_proc_executor.cjs.map +1 -1
  207. package/dist/ipc/job_proc_executor.d.ts.map +1 -1
  208. package/dist/ipc/job_proc_executor.js +6 -1
  209. package/dist/ipc/job_proc_executor.js.map +1 -1
  210. package/dist/ipc/job_proc_lazy_main.cjs +89 -17
  211. package/dist/ipc/job_proc_lazy_main.cjs.map +1 -1
  212. package/dist/ipc/job_proc_lazy_main.js +68 -18
  213. package/dist/ipc/job_proc_lazy_main.js.map +1 -1
  214. package/dist/ipc/supervised_proc.cjs +34 -8
  215. package/dist/ipc/supervised_proc.cjs.map +1 -1
  216. package/dist/ipc/supervised_proc.d.cts +8 -0
  217. package/dist/ipc/supervised_proc.d.ts +8 -0
  218. package/dist/ipc/supervised_proc.d.ts.map +1 -1
  219. package/dist/ipc/supervised_proc.js +34 -8
  220. package/dist/ipc/supervised_proc.js.map +1 -1
  221. package/dist/ipc/supervised_proc.test.cjs +145 -0
  222. package/dist/ipc/supervised_proc.test.cjs.map +1 -0
  223. package/dist/ipc/supervised_proc.test.js +122 -0
  224. package/dist/ipc/supervised_proc.test.js.map +1 -0
  225. package/dist/job.cjs +109 -1
  226. package/dist/job.cjs.map +1 -1
  227. package/dist/job.d.cts +14 -0
  228. package/dist/job.d.ts +14 -0
  229. package/dist/job.d.ts.map +1 -1
  230. package/dist/job.js +99 -1
  231. package/dist/job.js.map +1 -1
  232. package/dist/language.cjs +394 -0
  233. package/dist/language.cjs.map +1 -0
  234. package/dist/language.d.cts +15 -0
  235. package/dist/language.d.ts +15 -0
  236. package/dist/language.d.ts.map +1 -0
  237. package/dist/language.js +363 -0
  238. package/dist/language.js.map +1 -0
  239. package/dist/language.test.cjs +43 -0
  240. package/dist/language.test.cjs.map +1 -0
  241. package/dist/language.test.js +49 -0
  242. package/dist/language.test.js.map +1 -0
  243. package/dist/llm/chat_context.cjs +274 -3
  244. package/dist/llm/chat_context.cjs.map +1 -1
  245. package/dist/llm/chat_context.d.cts +86 -2
  246. package/dist/llm/chat_context.d.ts +86 -2
  247. package/dist/llm/chat_context.d.ts.map +1 -1
  248. package/dist/llm/chat_context.js +273 -3
  249. package/dist/llm/chat_context.js.map +1 -1
  250. package/dist/llm/chat_context.test.cjs +574 -0
  251. package/dist/llm/chat_context.test.cjs.map +1 -1
  252. package/dist/llm/chat_context.test.js +574 -0
  253. package/dist/llm/chat_context.test.js.map +1 -1
  254. package/dist/llm/fallback_adapter.cjs +278 -0
  255. package/dist/llm/fallback_adapter.cjs.map +1 -0
  256. package/dist/llm/fallback_adapter.d.cts +73 -0
  257. package/dist/llm/fallback_adapter.d.ts +73 -0
  258. package/dist/llm/fallback_adapter.d.ts.map +1 -0
  259. package/dist/llm/fallback_adapter.js +254 -0
  260. package/dist/llm/fallback_adapter.js.map +1 -0
  261. package/dist/llm/fallback_adapter.test.cjs +176 -0
  262. package/dist/llm/fallback_adapter.test.cjs.map +1 -0
  263. package/dist/llm/fallback_adapter.test.js +175 -0
  264. package/dist/llm/fallback_adapter.test.js.map +1 -0
  265. package/dist/llm/index.cjs +9 -0
  266. package/dist/llm/index.cjs.map +1 -1
  267. package/dist/llm/index.d.cts +4 -3
  268. package/dist/llm/index.d.ts +4 -3
  269. package/dist/llm/index.d.ts.map +1 -1
  270. package/dist/llm/index.js +11 -1
  271. package/dist/llm/index.js.map +1 -1
  272. package/dist/llm/llm.cjs +65 -11
  273. package/dist/llm/llm.cjs.map +1 -1
  274. package/dist/llm/llm.d.cts +13 -2
  275. package/dist/llm/llm.d.ts +13 -2
  276. package/dist/llm/llm.d.ts.map +1 -1
  277. package/dist/llm/llm.js +65 -11
  278. package/dist/llm/llm.js.map +1 -1
  279. package/dist/llm/provider_format/google.cjs +6 -2
  280. package/dist/llm/provider_format/google.cjs.map +1 -1
  281. package/dist/llm/provider_format/google.d.cts +1 -1
  282. package/dist/llm/provider_format/google.d.ts +1 -1
  283. package/dist/llm/provider_format/google.d.ts.map +1 -1
  284. package/dist/llm/provider_format/google.js +6 -2
  285. package/dist/llm/provider_format/google.js.map +1 -1
  286. package/dist/llm/provider_format/google.test.cjs +48 -0
  287. package/dist/llm/provider_format/google.test.cjs.map +1 -1
  288. package/dist/llm/provider_format/google.test.js +54 -1
  289. package/dist/llm/provider_format/google.test.js.map +1 -1
  290. package/dist/llm/provider_format/index.cjs +2 -0
  291. package/dist/llm/provider_format/index.cjs.map +1 -1
  292. package/dist/llm/provider_format/index.d.cts +2 -2
  293. package/dist/llm/provider_format/index.d.ts +2 -2
  294. package/dist/llm/provider_format/index.d.ts.map +1 -1
  295. package/dist/llm/provider_format/index.js +6 -1
  296. package/dist/llm/provider_format/index.js.map +1 -1
  297. package/dist/llm/provider_format/openai.cjs +126 -24
  298. package/dist/llm/provider_format/openai.cjs.map +1 -1
  299. package/dist/llm/provider_format/openai.d.cts +1 -0
  300. package/dist/llm/provider_format/openai.d.ts +1 -0
  301. package/dist/llm/provider_format/openai.d.ts.map +1 -1
  302. package/dist/llm/provider_format/openai.js +124 -23
  303. package/dist/llm/provider_format/openai.js.map +1 -1
  304. package/dist/llm/provider_format/openai.test.cjs +393 -0
  305. package/dist/llm/provider_format/openai.test.cjs.map +1 -1
  306. package/dist/llm/provider_format/openai.test.js +400 -2
  307. package/dist/llm/provider_format/openai.test.js.map +1 -1
  308. package/dist/llm/provider_format/utils.cjs +5 -4
  309. package/dist/llm/provider_format/utils.cjs.map +1 -1
  310. package/dist/llm/provider_format/utils.d.ts.map +1 -1
  311. package/dist/llm/provider_format/utils.js +5 -4
  312. package/dist/llm/provider_format/utils.js.map +1 -1
  313. package/dist/llm/realtime.cjs +3 -0
  314. package/dist/llm/realtime.cjs.map +1 -1
  315. package/dist/llm/realtime.d.cts +15 -1
  316. package/dist/llm/realtime.d.ts +15 -1
  317. package/dist/llm/realtime.d.ts.map +1 -1
  318. package/dist/llm/realtime.js +3 -0
  319. package/dist/llm/realtime.js.map +1 -1
  320. package/dist/llm/remote_chat_context.cjs.map +1 -1
  321. package/dist/llm/remote_chat_context.d.cts +2 -0
  322. package/dist/llm/remote_chat_context.d.ts +2 -0
  323. package/dist/llm/remote_chat_context.d.ts.map +1 -1
  324. package/dist/llm/remote_chat_context.js.map +1 -1
  325. package/dist/llm/tool_context.cjs +50 -2
  326. package/dist/llm/tool_context.cjs.map +1 -1
  327. package/dist/llm/tool_context.d.cts +47 -11
  328. package/dist/llm/tool_context.d.ts +47 -11
  329. package/dist/llm/tool_context.d.ts.map +1 -1
  330. package/dist/llm/tool_context.js +48 -3
  331. package/dist/llm/tool_context.js.map +1 -1
  332. package/dist/llm/tool_context.test.cjs +197 -0
  333. package/dist/llm/tool_context.test.cjs.map +1 -1
  334. package/dist/llm/tool_context.test.js +175 -0
  335. package/dist/llm/tool_context.test.js.map +1 -1
  336. package/dist/llm/utils.cjs +18 -12
  337. package/dist/llm/utils.cjs.map +1 -1
  338. package/dist/llm/utils.d.cts +2 -3
  339. package/dist/llm/utils.d.ts +2 -3
  340. package/dist/llm/utils.d.ts.map +1 -1
  341. package/dist/llm/utils.js +18 -12
  342. package/dist/llm/utils.js.map +1 -1
  343. package/dist/llm/zod-utils.cjs +102 -0
  344. package/dist/llm/zod-utils.cjs.map +1 -0
  345. package/dist/llm/zod-utils.d.cts +65 -0
  346. package/dist/llm/zod-utils.d.ts +65 -0
  347. package/dist/llm/zod-utils.d.ts.map +1 -0
  348. package/dist/llm/zod-utils.js +64 -0
  349. package/dist/llm/zod-utils.js.map +1 -0
  350. package/dist/llm/zod-utils.test.cjs +472 -0
  351. package/dist/llm/zod-utils.test.cjs.map +1 -0
  352. package/dist/llm/zod-utils.test.js +455 -0
  353. package/dist/llm/zod-utils.test.js.map +1 -0
  354. package/dist/log.cjs +45 -14
  355. package/dist/log.cjs.map +1 -1
  356. package/dist/log.d.cts +8 -1
  357. package/dist/log.d.ts +8 -1
  358. package/dist/log.d.ts.map +1 -1
  359. package/dist/log.js +45 -15
  360. package/dist/log.js.map +1 -1
  361. package/dist/metrics/base.cjs.map +1 -1
  362. package/dist/metrics/base.d.cts +75 -19
  363. package/dist/metrics/base.d.ts +75 -19
  364. package/dist/metrics/base.d.ts.map +1 -1
  365. package/dist/metrics/index.cjs +5 -0
  366. package/dist/metrics/index.cjs.map +1 -1
  367. package/dist/metrics/index.d.cts +2 -1
  368. package/dist/metrics/index.d.ts +2 -1
  369. package/dist/metrics/index.d.ts.map +1 -1
  370. package/dist/metrics/index.js +6 -0
  371. package/dist/metrics/index.js.map +1 -1
  372. package/dist/metrics/model_usage.cjs +189 -0
  373. package/dist/metrics/model_usage.cjs.map +1 -0
  374. package/dist/metrics/model_usage.d.cts +92 -0
  375. package/dist/metrics/model_usage.d.ts +92 -0
  376. package/dist/metrics/model_usage.d.ts.map +1 -0
  377. package/dist/metrics/model_usage.js +164 -0
  378. package/dist/metrics/model_usage.js.map +1 -0
  379. package/dist/metrics/model_usage.test.cjs +474 -0
  380. package/dist/metrics/model_usage.test.cjs.map +1 -0
  381. package/dist/metrics/model_usage.test.js +476 -0
  382. package/dist/metrics/model_usage.test.js.map +1 -0
  383. package/dist/metrics/usage_collector.cjs +5 -2
  384. package/dist/metrics/usage_collector.cjs.map +1 -1
  385. package/dist/metrics/usage_collector.d.cts +10 -1
  386. package/dist/metrics/usage_collector.d.ts +10 -1
  387. package/dist/metrics/usage_collector.d.ts.map +1 -1
  388. package/dist/metrics/usage_collector.js +5 -2
  389. package/dist/metrics/usage_collector.js.map +1 -1
  390. package/dist/metrics/utils.cjs +23 -7
  391. package/dist/metrics/utils.cjs.map +1 -1
  392. package/dist/metrics/utils.d.ts.map +1 -1
  393. package/dist/metrics/utils.js +23 -7
  394. package/dist/metrics/utils.js.map +1 -1
  395. package/dist/stream/deferred_stream.cjs +31 -10
  396. package/dist/stream/deferred_stream.cjs.map +1 -1
  397. package/dist/stream/deferred_stream.d.cts +6 -1
  398. package/dist/stream/deferred_stream.d.ts +6 -1
  399. package/dist/stream/deferred_stream.d.ts.map +1 -1
  400. package/dist/stream/deferred_stream.js +31 -10
  401. package/dist/stream/deferred_stream.js.map +1 -1
  402. package/dist/stream/deferred_stream.test.cjs +2 -2
  403. package/dist/stream/deferred_stream.test.cjs.map +1 -1
  404. package/dist/stream/deferred_stream.test.js +2 -2
  405. package/dist/stream/deferred_stream.test.js.map +1 -1
  406. package/dist/stream/index.cjs +3 -0
  407. package/dist/stream/index.cjs.map +1 -1
  408. package/dist/stream/index.d.cts +1 -0
  409. package/dist/stream/index.d.ts +1 -0
  410. package/dist/stream/index.d.ts.map +1 -1
  411. package/dist/stream/index.js +2 -0
  412. package/dist/stream/index.js.map +1 -1
  413. package/dist/stream/multi_input_stream.cjs +139 -0
  414. package/dist/stream/multi_input_stream.cjs.map +1 -0
  415. package/dist/stream/multi_input_stream.d.cts +55 -0
  416. package/dist/stream/multi_input_stream.d.ts +55 -0
  417. package/dist/stream/multi_input_stream.d.ts.map +1 -0
  418. package/dist/stream/multi_input_stream.js +115 -0
  419. package/dist/stream/multi_input_stream.js.map +1 -0
  420. package/dist/stream/multi_input_stream.test.cjs +344 -0
  421. package/dist/stream/multi_input_stream.test.cjs.map +1 -0
  422. package/dist/stream/multi_input_stream.test.js +343 -0
  423. package/dist/stream/multi_input_stream.test.js.map +1 -0
  424. package/dist/stream/stream_channel.cjs +39 -1
  425. package/dist/stream/stream_channel.cjs.map +1 -1
  426. package/dist/stream/stream_channel.d.cts +5 -2
  427. package/dist/stream/stream_channel.d.ts +5 -2
  428. package/dist/stream/stream_channel.d.ts.map +1 -1
  429. package/dist/stream/stream_channel.js +39 -1
  430. package/dist/stream/stream_channel.js.map +1 -1
  431. package/dist/stream/stream_channel.test.cjs +27 -0
  432. package/dist/stream/stream_channel.test.cjs.map +1 -1
  433. package/dist/stream/stream_channel.test.js +27 -0
  434. package/dist/stream/stream_channel.test.js.map +1 -1
  435. package/dist/stt/stream_adapter.cjs +24 -9
  436. package/dist/stt/stream_adapter.cjs.map +1 -1
  437. package/dist/stt/stream_adapter.d.cts +7 -3
  438. package/dist/stt/stream_adapter.d.ts +7 -3
  439. package/dist/stt/stream_adapter.d.ts.map +1 -1
  440. package/dist/stt/stream_adapter.js +24 -9
  441. package/dist/stt/stream_adapter.js.map +1 -1
  442. package/dist/stt/stt.cjs +86 -19
  443. package/dist/stt/stt.cjs.map +1 -1
  444. package/dist/stt/stt.d.cts +60 -5
  445. package/dist/stt/stt.d.ts +60 -5
  446. package/dist/stt/stt.d.ts.map +1 -1
  447. package/dist/stt/stt.js +88 -21
  448. package/dist/stt/stt.js.map +1 -1
  449. package/dist/telemetry/index.cjs +72 -0
  450. package/dist/telemetry/index.cjs.map +1 -0
  451. package/dist/telemetry/index.d.cts +7 -0
  452. package/dist/telemetry/index.d.ts +7 -0
  453. package/dist/telemetry/index.d.ts.map +1 -0
  454. package/dist/telemetry/index.js +37 -0
  455. package/dist/telemetry/index.js.map +1 -0
  456. package/dist/telemetry/logging.cjs +65 -0
  457. package/dist/telemetry/logging.cjs.map +1 -0
  458. package/dist/telemetry/logging.d.cts +21 -0
  459. package/dist/telemetry/logging.d.ts +21 -0
  460. package/dist/telemetry/logging.d.ts.map +1 -0
  461. package/dist/telemetry/logging.js +40 -0
  462. package/dist/telemetry/logging.js.map +1 -0
  463. package/dist/telemetry/otel_http_exporter.cjs +166 -0
  464. package/dist/telemetry/otel_http_exporter.cjs.map +1 -0
  465. package/dist/telemetry/otel_http_exporter.d.cts +63 -0
  466. package/dist/telemetry/otel_http_exporter.d.ts +63 -0
  467. package/dist/telemetry/otel_http_exporter.d.ts.map +1 -0
  468. package/dist/telemetry/otel_http_exporter.js +142 -0
  469. package/dist/telemetry/otel_http_exporter.js.map +1 -0
  470. package/dist/telemetry/pino_otel_transport.cjs +217 -0
  471. package/dist/telemetry/pino_otel_transport.cjs.map +1 -0
  472. package/dist/telemetry/pino_otel_transport.d.cts +58 -0
  473. package/dist/telemetry/pino_otel_transport.d.ts +58 -0
  474. package/dist/telemetry/pino_otel_transport.d.ts.map +1 -0
  475. package/dist/telemetry/pino_otel_transport.js +189 -0
  476. package/dist/telemetry/pino_otel_transport.js.map +1 -0
  477. package/dist/telemetry/trace_types.cjs +233 -0
  478. package/dist/telemetry/trace_types.cjs.map +1 -0
  479. package/dist/telemetry/trace_types.d.cts +74 -0
  480. package/dist/telemetry/trace_types.d.ts +74 -0
  481. package/dist/telemetry/trace_types.d.ts.map +1 -0
  482. package/dist/telemetry/trace_types.js +141 -0
  483. package/dist/telemetry/trace_types.js.map +1 -0
  484. package/dist/telemetry/traces.cjs +484 -0
  485. package/dist/telemetry/traces.cjs.map +1 -0
  486. package/dist/telemetry/traces.d.cts +116 -0
  487. package/dist/telemetry/traces.d.ts +116 -0
  488. package/dist/telemetry/traces.d.ts.map +1 -0
  489. package/dist/telemetry/traces.js +449 -0
  490. package/dist/telemetry/traces.js.map +1 -0
  491. package/dist/telemetry/utils.cjs +86 -0
  492. package/dist/telemetry/utils.cjs.map +1 -0
  493. package/dist/telemetry/utils.d.cts +5 -0
  494. package/dist/telemetry/utils.d.ts +5 -0
  495. package/dist/telemetry/utils.d.ts.map +1 -0
  496. package/dist/telemetry/utils.js +51 -0
  497. package/dist/telemetry/utils.js.map +1 -0
  498. package/dist/tokenize/basic/sentence.cjs +3 -3
  499. package/dist/tokenize/basic/sentence.cjs.map +1 -1
  500. package/dist/tokenize/basic/sentence.js +3 -3
  501. package/dist/tokenize/basic/sentence.js.map +1 -1
  502. package/dist/tokenize/tokenizer.test.cjs +3 -1
  503. package/dist/tokenize/tokenizer.test.cjs.map +1 -1
  504. package/dist/tokenize/tokenizer.test.js +3 -1
  505. package/dist/tokenize/tokenizer.test.js.map +1 -1
  506. package/dist/transcription.cjs.map +1 -1
  507. package/dist/transcription.d.cts +6 -0
  508. package/dist/transcription.d.ts +6 -0
  509. package/dist/transcription.d.ts.map +1 -1
  510. package/dist/transcription.js.map +1 -1
  511. package/dist/tts/fallback_adapter.cjs +466 -0
  512. package/dist/tts/fallback_adapter.cjs.map +1 -0
  513. package/dist/tts/fallback_adapter.d.cts +110 -0
  514. package/dist/tts/fallback_adapter.d.ts +110 -0
  515. package/dist/tts/fallback_adapter.d.ts.map +1 -0
  516. package/dist/tts/fallback_adapter.js +442 -0
  517. package/dist/tts/fallback_adapter.js.map +1 -0
  518. package/dist/tts/index.cjs +3 -0
  519. package/dist/tts/index.cjs.map +1 -1
  520. package/dist/tts/index.d.cts +1 -0
  521. package/dist/tts/index.d.ts +1 -0
  522. package/dist/tts/index.d.ts.map +1 -1
  523. package/dist/tts/index.js +2 -0
  524. package/dist/tts/index.js.map +1 -1
  525. package/dist/tts/stream_adapter.cjs +25 -8
  526. package/dist/tts/stream_adapter.cjs.map +1 -1
  527. package/dist/tts/stream_adapter.d.cts +6 -3
  528. package/dist/tts/stream_adapter.d.ts +6 -3
  529. package/dist/tts/stream_adapter.d.ts.map +1 -1
  530. package/dist/tts/stream_adapter.js +25 -8
  531. package/dist/tts/stream_adapter.js.map +1 -1
  532. package/dist/tts/tts.cjs +189 -57
  533. package/dist/tts/tts.cjs.map +1 -1
  534. package/dist/tts/tts.d.cts +58 -6
  535. package/dist/tts/tts.d.ts +58 -6
  536. package/dist/tts/tts.d.ts.map +1 -1
  537. package/dist/tts/tts.js +191 -59
  538. package/dist/tts/tts.js.map +1 -1
  539. package/dist/types.cjs +24 -32
  540. package/dist/types.cjs.map +1 -1
  541. package/dist/types.d.cts +45 -10
  542. package/dist/types.d.ts +45 -10
  543. package/dist/types.d.ts.map +1 -1
  544. package/dist/types.js +20 -30
  545. package/dist/types.js.map +1 -1
  546. package/dist/utils.cjs +122 -26
  547. package/dist/utils.cjs.map +1 -1
  548. package/dist/utils.d.cts +41 -1
  549. package/dist/utils.d.ts +41 -1
  550. package/dist/utils.d.ts.map +1 -1
  551. package/dist/utils.js +117 -25
  552. package/dist/utils.js.map +1 -1
  553. package/dist/utils.test.cjs +73 -1
  554. package/dist/utils.test.cjs.map +1 -1
  555. package/dist/utils.test.js +74 -10
  556. package/dist/utils.test.js.map +1 -1
  557. package/dist/vad.cjs +35 -15
  558. package/dist/vad.cjs.map +1 -1
  559. package/dist/vad.d.cts +15 -5
  560. package/dist/vad.d.ts +15 -5
  561. package/dist/vad.d.ts.map +1 -1
  562. package/dist/vad.js +35 -15
  563. package/dist/vad.js.map +1 -1
  564. package/dist/version.cjs +1 -1
  565. package/dist/version.cjs.map +1 -1
  566. package/dist/version.d.cts +1 -1
  567. package/dist/version.d.ts +1 -1
  568. package/dist/version.d.ts.map +1 -1
  569. package/dist/version.js +1 -1
  570. package/dist/version.js.map +1 -1
  571. package/dist/voice/agent.cjs +258 -35
  572. package/dist/voice/agent.cjs.map +1 -1
  573. package/dist/voice/agent.d.cts +54 -13
  574. package/dist/voice/agent.d.ts +54 -13
  575. package/dist/voice/agent.d.ts.map +1 -1
  576. package/dist/voice/agent.js +254 -34
  577. package/dist/voice/agent.js.map +1 -1
  578. package/dist/voice/agent.test.cjs +314 -0
  579. package/dist/voice/agent.test.cjs.map +1 -1
  580. package/dist/voice/agent.test.js +316 -2
  581. package/dist/voice/agent.test.js.map +1 -1
  582. package/dist/voice/agent_activity.cjs +1116 -385
  583. package/dist/voice/agent_activity.cjs.map +1 -1
  584. package/dist/voice/agent_activity.d.cts +72 -11
  585. package/dist/voice/agent_activity.d.ts +72 -11
  586. package/dist/voice/agent_activity.d.ts.map +1 -1
  587. package/dist/voice/agent_activity.js +1119 -383
  588. package/dist/voice/agent_activity.js.map +1 -1
  589. package/dist/voice/agent_activity.test.cjs +135 -0
  590. package/dist/voice/agent_activity.test.cjs.map +1 -0
  591. package/dist/voice/agent_activity.test.js +134 -0
  592. package/dist/voice/agent_activity.test.js.map +1 -0
  593. package/dist/voice/agent_session.cjs +550 -90
  594. package/dist/voice/agent_session.cjs.map +1 -1
  595. package/dist/voice/agent_session.d.cts +185 -25
  596. package/dist/voice/agent_session.d.ts +185 -25
  597. package/dist/voice/agent_session.d.ts.map +1 -1
  598. package/dist/voice/agent_session.js +556 -91
  599. package/dist/voice/agent_session.js.map +1 -1
  600. package/dist/voice/audio_recognition.cjs +605 -46
  601. package/dist/voice/audio_recognition.cjs.map +1 -1
  602. package/dist/voice/audio_recognition.d.cts +96 -4
  603. package/dist/voice/audio_recognition.d.ts +96 -4
  604. package/dist/voice/audio_recognition.d.ts.map +1 -1
  605. package/dist/voice/audio_recognition.js +611 -47
  606. package/dist/voice/audio_recognition.js.map +1 -1
  607. package/dist/voice/audio_recognition_span.test.cjs +295 -0
  608. package/dist/voice/audio_recognition_span.test.cjs.map +1 -0
  609. package/dist/voice/audio_recognition_span.test.js +299 -0
  610. package/dist/voice/audio_recognition_span.test.js.map +1 -0
  611. package/dist/voice/avatar/datastream_io.cjs +7 -1
  612. package/dist/voice/avatar/datastream_io.cjs.map +1 -1
  613. package/dist/voice/avatar/datastream_io.d.cts +1 -0
  614. package/dist/voice/avatar/datastream_io.d.ts +1 -0
  615. package/dist/voice/avatar/datastream_io.d.ts.map +1 -1
  616. package/dist/voice/avatar/datastream_io.js +7 -1
  617. package/dist/voice/avatar/datastream_io.js.map +1 -1
  618. package/dist/voice/background_audio.cjs +367 -0
  619. package/dist/voice/background_audio.cjs.map +1 -0
  620. package/dist/voice/background_audio.d.cts +123 -0
  621. package/dist/voice/background_audio.d.ts +123 -0
  622. package/dist/voice/background_audio.d.ts.map +1 -0
  623. package/dist/voice/background_audio.js +343 -0
  624. package/dist/voice/background_audio.js.map +1 -0
  625. package/dist/voice/events.cjs +3 -0
  626. package/dist/voice/events.cjs.map +1 -1
  627. package/dist/voice/events.d.cts +16 -9
  628. package/dist/voice/events.d.ts +16 -9
  629. package/dist/voice/events.d.ts.map +1 -1
  630. package/dist/voice/events.js +3 -0
  631. package/dist/voice/events.js.map +1 -1
  632. package/dist/voice/generation.cjs +205 -41
  633. package/dist/voice/generation.cjs.map +1 -1
  634. package/dist/voice/generation.d.cts +21 -5
  635. package/dist/voice/generation.d.ts +21 -5
  636. package/dist/voice/generation.d.ts.map +1 -1
  637. package/dist/voice/generation.js +215 -43
  638. package/dist/voice/generation.js.map +1 -1
  639. package/dist/voice/generation_tools.test.cjs +236 -0
  640. package/dist/voice/generation_tools.test.cjs.map +1 -0
  641. package/dist/voice/generation_tools.test.js +235 -0
  642. package/dist/voice/generation_tools.test.js.map +1 -0
  643. package/dist/voice/index.cjs +33 -2
  644. package/dist/voice/index.cjs.map +1 -1
  645. package/dist/voice/index.d.cts +8 -2
  646. package/dist/voice/index.d.ts +8 -2
  647. package/dist/voice/index.d.ts.map +1 -1
  648. package/dist/voice/index.js +19 -2
  649. package/dist/voice/index.js.map +1 -1
  650. package/dist/voice/interruption_detection.test.cjs +114 -0
  651. package/dist/voice/interruption_detection.test.cjs.map +1 -0
  652. package/dist/voice/interruption_detection.test.js +113 -0
  653. package/dist/voice/interruption_detection.test.js.map +1 -0
  654. package/dist/voice/io.cjs +66 -6
  655. package/dist/voice/io.cjs.map +1 -1
  656. package/dist/voice/io.d.cts +67 -7
  657. package/dist/voice/io.d.ts +67 -7
  658. package/dist/voice/io.d.ts.map +1 -1
  659. package/dist/voice/io.js +62 -5
  660. package/dist/voice/io.js.map +1 -1
  661. package/dist/voice/recorder_io/index.cjs +23 -0
  662. package/dist/voice/recorder_io/index.cjs.map +1 -0
  663. package/dist/voice/recorder_io/index.d.cts +2 -0
  664. package/dist/voice/recorder_io/index.d.ts +2 -0
  665. package/dist/voice/recorder_io/index.d.ts.map +1 -0
  666. package/dist/voice/recorder_io/index.js +2 -0
  667. package/dist/voice/recorder_io/index.js.map +1 -0
  668. package/dist/voice/recorder_io/recorder_io.cjs +607 -0
  669. package/dist/voice/recorder_io/recorder_io.cjs.map +1 -0
  670. package/dist/voice/recorder_io/recorder_io.d.cts +106 -0
  671. package/dist/voice/recorder_io/recorder_io.d.ts +106 -0
  672. package/dist/voice/recorder_io/recorder_io.d.ts.map +1 -0
  673. package/dist/voice/recorder_io/recorder_io.js +573 -0
  674. package/dist/voice/recorder_io/recorder_io.js.map +1 -0
  675. package/dist/voice/remote_session.cjs +922 -0
  676. package/dist/voice/remote_session.cjs.map +1 -0
  677. package/dist/voice/remote_session.d.cts +108 -0
  678. package/dist/voice/remote_session.d.ts +108 -0
  679. package/dist/voice/remote_session.d.ts.map +1 -0
  680. package/dist/voice/remote_session.js +887 -0
  681. package/dist/voice/remote_session.js.map +1 -0
  682. package/dist/voice/report.cjs +88 -0
  683. package/dist/voice/report.cjs.map +1 -0
  684. package/dist/voice/report.d.cts +49 -0
  685. package/dist/voice/report.d.ts +49 -0
  686. package/dist/voice/report.d.ts.map +1 -0
  687. package/dist/voice/report.js +63 -0
  688. package/dist/voice/report.js.map +1 -0
  689. package/dist/voice/report.test.cjs +121 -0
  690. package/dist/voice/report.test.cjs.map +1 -0
  691. package/dist/voice/report.test.js +120 -0
  692. package/dist/voice/report.test.js.map +1 -0
  693. package/dist/voice/room_io/_input.cjs +40 -7
  694. package/dist/voice/room_io/_input.cjs.map +1 -1
  695. package/dist/voice/room_io/_input.d.cts +5 -2
  696. package/dist/voice/room_io/_input.d.ts +5 -2
  697. package/dist/voice/room_io/_input.d.ts.map +1 -1
  698. package/dist/voice/room_io/_input.js +41 -8
  699. package/dist/voice/room_io/_input.js.map +1 -1
  700. package/dist/voice/room_io/_output.cjs +19 -11
  701. package/dist/voice/room_io/_output.cjs.map +1 -1
  702. package/dist/voice/room_io/_output.d.cts +7 -4
  703. package/dist/voice/room_io/_output.d.ts +7 -4
  704. package/dist/voice/room_io/_output.d.ts.map +1 -1
  705. package/dist/voice/room_io/_output.js +20 -12
  706. package/dist/voice/room_io/_output.js.map +1 -1
  707. package/dist/voice/room_io/room_io.cjs +33 -6
  708. package/dist/voice/room_io/room_io.cjs.map +1 -1
  709. package/dist/voice/room_io/room_io.d.cts +29 -9
  710. package/dist/voice/room_io/room_io.d.ts +29 -9
  711. package/dist/voice/room_io/room_io.d.ts.map +1 -1
  712. package/dist/voice/room_io/room_io.js +33 -7
  713. package/dist/voice/room_io/room_io.js.map +1 -1
  714. package/dist/voice/speech_handle.cjs +22 -4
  715. package/dist/voice/speech_handle.cjs.map +1 -1
  716. package/dist/voice/speech_handle.d.cts +17 -2
  717. package/dist/voice/speech_handle.d.ts +17 -2
  718. package/dist/voice/speech_handle.d.ts.map +1 -1
  719. package/dist/voice/speech_handle.js +21 -4
  720. package/dist/voice/speech_handle.js.map +1 -1
  721. package/dist/voice/testing/fake_llm.cjs +127 -0
  722. package/dist/voice/testing/fake_llm.cjs.map +1 -0
  723. package/dist/voice/testing/fake_llm.d.cts +30 -0
  724. package/dist/voice/testing/fake_llm.d.ts +30 -0
  725. package/dist/voice/testing/fake_llm.d.ts.map +1 -0
  726. package/dist/voice/testing/fake_llm.js +103 -0
  727. package/dist/voice/testing/fake_llm.js.map +1 -0
  728. package/dist/voice/testing/index.cjs +57 -0
  729. package/dist/voice/testing/index.cjs.map +1 -0
  730. package/dist/voice/testing/index.d.cts +21 -0
  731. package/dist/voice/testing/index.d.ts +21 -0
  732. package/dist/voice/testing/index.d.ts.map +1 -0
  733. package/dist/voice/testing/index.js +35 -0
  734. package/dist/voice/testing/index.js.map +1 -0
  735. package/dist/voice/testing/run_result.cjs +817 -0
  736. package/dist/voice/testing/run_result.cjs.map +1 -0
  737. package/dist/voice/testing/run_result.d.cts +385 -0
  738. package/dist/voice/testing/run_result.d.ts +385 -0
  739. package/dist/voice/testing/run_result.d.ts.map +1 -0
  740. package/dist/voice/testing/run_result.js +790 -0
  741. package/dist/voice/testing/run_result.js.map +1 -0
  742. package/dist/voice/testing/types.cjs +46 -0
  743. package/dist/voice/testing/types.cjs.map +1 -0
  744. package/dist/voice/testing/types.d.cts +83 -0
  745. package/dist/voice/testing/types.d.ts +83 -0
  746. package/dist/voice/testing/types.d.ts.map +1 -0
  747. package/dist/voice/testing/types.js +19 -0
  748. package/dist/voice/testing/types.js.map +1 -0
  749. package/dist/voice/transcription/synchronizer.cjs +139 -15
  750. package/dist/voice/transcription/synchronizer.cjs.map +1 -1
  751. package/dist/voice/transcription/synchronizer.d.cts +35 -4
  752. package/dist/voice/transcription/synchronizer.d.ts +35 -4
  753. package/dist/voice/transcription/synchronizer.d.ts.map +1 -1
  754. package/dist/voice/transcription/synchronizer.js +143 -16
  755. package/dist/voice/transcription/synchronizer.js.map +1 -1
  756. package/dist/voice/transcription/synchronizer.test.cjs +151 -0
  757. package/dist/voice/transcription/synchronizer.test.cjs.map +1 -0
  758. package/dist/voice/transcription/synchronizer.test.js +150 -0
  759. package/dist/voice/transcription/synchronizer.test.js.map +1 -0
  760. package/dist/voice/turn_config/endpointing.cjs +33 -0
  761. package/dist/voice/turn_config/endpointing.cjs.map +1 -0
  762. package/dist/voice/turn_config/endpointing.d.cts +30 -0
  763. package/dist/voice/turn_config/endpointing.d.ts +30 -0
  764. package/dist/voice/turn_config/endpointing.d.ts.map +1 -0
  765. package/dist/voice/turn_config/endpointing.js +9 -0
  766. package/dist/voice/turn_config/endpointing.js.map +1 -0
  767. package/dist/voice/turn_config/interruption.cjs +37 -0
  768. package/dist/voice/turn_config/interruption.cjs.map +1 -0
  769. package/dist/voice/turn_config/interruption.d.cts +53 -0
  770. package/dist/voice/turn_config/interruption.d.ts +53 -0
  771. package/dist/voice/turn_config/interruption.d.ts.map +1 -0
  772. package/dist/voice/turn_config/interruption.js +13 -0
  773. package/dist/voice/turn_config/interruption.js.map +1 -0
  774. package/dist/voice/turn_config/turn_handling.cjs +35 -0
  775. package/dist/voice/turn_config/turn_handling.cjs.map +1 -0
  776. package/dist/voice/turn_config/turn_handling.d.cts +36 -0
  777. package/dist/voice/turn_config/turn_handling.d.ts +36 -0
  778. package/dist/voice/turn_config/turn_handling.d.ts.map +1 -0
  779. package/dist/voice/turn_config/turn_handling.js +11 -0
  780. package/dist/voice/turn_config/turn_handling.js.map +1 -0
  781. package/dist/voice/turn_config/utils.cjs +157 -0
  782. package/dist/voice/turn_config/utils.cjs.map +1 -0
  783. package/dist/voice/turn_config/utils.d.cts +37 -0
  784. package/dist/voice/turn_config/utils.d.ts +37 -0
  785. package/dist/voice/turn_config/utils.d.ts.map +1 -0
  786. package/dist/voice/turn_config/utils.js +131 -0
  787. package/dist/voice/turn_config/utils.js.map +1 -0
  788. package/dist/voice/turn_config/utils.test.cjs +128 -0
  789. package/dist/voice/turn_config/utils.test.cjs.map +1 -0
  790. package/dist/voice/turn_config/utils.test.js +127 -0
  791. package/dist/voice/turn_config/utils.test.js.map +1 -0
  792. package/dist/voice/utils.cjs +47 -0
  793. package/dist/voice/utils.cjs.map +1 -0
  794. package/dist/voice/utils.d.cts +4 -0
  795. package/dist/voice/utils.d.ts +4 -0
  796. package/dist/voice/utils.d.ts.map +1 -0
  797. package/dist/voice/utils.js +23 -0
  798. package/dist/voice/utils.js.map +1 -0
  799. package/dist/worker.cjs +44 -52
  800. package/dist/worker.cjs.map +1 -1
  801. package/dist/worker.d.cts +18 -8
  802. package/dist/worker.d.ts +18 -8
  803. package/dist/worker.d.ts.map +1 -1
  804. package/dist/worker.js +43 -43
  805. package/dist/worker.js.map +1 -1
  806. package/package.json +32 -12
  807. package/resources/NOTICE +2 -0
  808. package/resources/keyboard-typing.ogg +0 -0
  809. package/resources/keyboard-typing2.ogg +0 -0
  810. package/resources/office-ambience.ogg +0 -0
  811. package/src/audio.ts +132 -1
  812. package/src/beta/index.ts +9 -0
  813. package/src/beta/workflows/index.ts +9 -0
  814. package/src/beta/workflows/task_group.ts +194 -0
  815. package/src/cli.ts +57 -66
  816. package/src/connection_pool.test.ts +346 -0
  817. package/src/connection_pool.ts +307 -0
  818. package/src/constants.ts +14 -0
  819. package/src/cpu.test.ts +239 -0
  820. package/src/cpu.ts +173 -0
  821. package/src/http_server.ts +18 -6
  822. package/src/index.ts +15 -13
  823. package/src/inference/api_protos.ts +85 -2
  824. package/src/inference/index.ts +32 -4
  825. package/src/inference/interruption/defaults.ts +51 -0
  826. package/src/inference/interruption/errors.ts +25 -0
  827. package/src/inference/interruption/http_transport.ts +206 -0
  828. package/src/inference/interruption/interruption_cache_entry.ts +50 -0
  829. package/src/inference/interruption/interruption_detector.ts +204 -0
  830. package/src/inference/interruption/interruption_stream.ts +467 -0
  831. package/src/inference/interruption/types.ts +84 -0
  832. package/src/inference/interruption/utils.test.ts +132 -0
  833. package/src/inference/interruption/utils.ts +137 -0
  834. package/src/inference/interruption/ws_transport.ts +406 -0
  835. package/src/inference/llm.ts +214 -163
  836. package/src/inference/stt.test.ts +253 -0
  837. package/src/inference/stt.ts +449 -208
  838. package/src/inference/tts.test.ts +267 -0
  839. package/src/inference/tts.ts +377 -115
  840. package/src/inference/utils.ts +30 -2
  841. package/src/ipc/inference_proc_executor.ts +11 -3
  842. package/src/ipc/inference_proc_lazy_main.ts +13 -1
  843. package/src/ipc/job_proc_executor.ts +11 -1
  844. package/src/ipc/job_proc_lazy_main.ts +86 -20
  845. package/src/ipc/supervised_proc.test.ts +153 -0
  846. package/src/ipc/supervised_proc.ts +39 -10
  847. package/src/job.ts +120 -1
  848. package/src/language.test.ts +62 -0
  849. package/src/language.ts +380 -0
  850. package/src/llm/__snapshots__/zod-utils.test.ts.snap +559 -0
  851. package/src/llm/chat_context.test.ts +655 -0
  852. package/src/llm/chat_context.ts +412 -2
  853. package/src/llm/fallback_adapter.test.ts +238 -0
  854. package/src/llm/fallback_adapter.ts +391 -0
  855. package/src/llm/index.ts +11 -0
  856. package/src/llm/llm.ts +77 -12
  857. package/src/llm/provider_format/google.test.ts +72 -1
  858. package/src/llm/provider_format/google.ts +10 -6
  859. package/src/llm/provider_format/index.ts +7 -2
  860. package/src/llm/provider_format/openai.test.ts +480 -2
  861. package/src/llm/provider_format/openai.ts +152 -21
  862. package/src/llm/provider_format/utils.ts +11 -5
  863. package/src/llm/realtime.ts +23 -2
  864. package/src/llm/remote_chat_context.ts +2 -2
  865. package/src/llm/tool_context.test.ts +210 -1
  866. package/src/llm/tool_context.ts +115 -17
  867. package/src/llm/utils.ts +24 -16
  868. package/src/llm/zod-utils.test.ts +577 -0
  869. package/src/llm/zod-utils.ts +153 -0
  870. package/src/log.ts +71 -19
  871. package/src/metrics/base.ts +78 -19
  872. package/src/metrics/index.ts +12 -0
  873. package/src/metrics/model_usage.test.ts +545 -0
  874. package/src/metrics/model_usage.ts +262 -0
  875. package/src/metrics/usage_collector.ts +14 -3
  876. package/src/metrics/utils.ts +27 -7
  877. package/src/stream/deferred_stream.test.ts +3 -3
  878. package/src/stream/deferred_stream.ts +43 -11
  879. package/src/stream/index.ts +1 -0
  880. package/src/stream/multi_input_stream.test.ts +545 -0
  881. package/src/stream/multi_input_stream.ts +172 -0
  882. package/src/stream/stream_channel.test.ts +37 -0
  883. package/src/stream/stream_channel.ts +43 -3
  884. package/src/stt/stream_adapter.ts +30 -9
  885. package/src/stt/stt.ts +131 -22
  886. package/src/telemetry/index.ts +28 -0
  887. package/src/telemetry/logging.ts +55 -0
  888. package/src/telemetry/otel_http_exporter.ts +218 -0
  889. package/src/telemetry/pino_otel_transport.ts +265 -0
  890. package/src/telemetry/trace_types.ts +109 -0
  891. package/src/telemetry/traces.ts +673 -0
  892. package/src/telemetry/utils.ts +61 -0
  893. package/src/tokenize/basic/sentence.ts +3 -3
  894. package/src/tokenize/tokenizer.test.ts +4 -0
  895. package/src/transcription.ts +6 -0
  896. package/src/tts/fallback_adapter.ts +579 -0
  897. package/src/tts/index.ts +1 -0
  898. package/src/tts/stream_adapter.ts +38 -8
  899. package/src/tts/tts.ts +245 -62
  900. package/src/types.ts +62 -33
  901. package/src/utils.test.ts +90 -10
  902. package/src/utils.ts +176 -31
  903. package/src/vad.ts +42 -18
  904. package/src/version.ts +1 -1
  905. package/src/voice/agent.test.ts +347 -2
  906. package/src/voice/agent.ts +346 -44
  907. package/src/voice/agent_activity.test.ts +194 -0
  908. package/src/voice/agent_activity.ts +1457 -388
  909. package/src/voice/agent_session.ts +817 -112
  910. package/src/voice/audio_recognition.ts +845 -70
  911. package/src/voice/audio_recognition_span.test.ts +341 -0
  912. package/src/voice/avatar/datastream_io.ts +9 -1
  913. package/src/voice/background_audio.ts +494 -0
  914. package/src/voice/events.ts +27 -7
  915. package/src/voice/generation.ts +310 -56
  916. package/src/voice/generation_tools.test.ts +268 -0
  917. package/src/voice/index.ts +17 -3
  918. package/src/voice/interruption_detection.test.ts +151 -0
  919. package/src/voice/io.ts +115 -12
  920. package/src/voice/recorder_io/index.ts +4 -0
  921. package/src/voice/recorder_io/recorder_io.ts +783 -0
  922. package/src/voice/remote_session.ts +1083 -0
  923. package/src/voice/report.test.ts +136 -0
  924. package/src/voice/report.ts +140 -0
  925. package/src/voice/room_io/_input.ts +45 -10
  926. package/src/voice/room_io/_output.ts +26 -14
  927. package/src/voice/room_io/room_io.ts +67 -22
  928. package/src/voice/speech_handle.ts +38 -6
  929. package/src/voice/testing/fake_llm.ts +138 -0
  930. package/src/voice/testing/index.ts +52 -0
  931. package/src/voice/testing/run_result.ts +995 -0
  932. package/src/voice/testing/types.ts +118 -0
  933. package/src/voice/transcription/synchronizer.test.ts +206 -0
  934. package/src/voice/transcription/synchronizer.ts +204 -19
  935. package/src/voice/turn_config/endpointing.ts +33 -0
  936. package/src/voice/turn_config/interruption.ts +56 -0
  937. package/src/voice/turn_config/turn_handling.ts +45 -0
  938. package/src/voice/turn_config/utils.test.ts +148 -0
  939. package/src/voice/turn_config/utils.ts +167 -0
  940. package/src/voice/utils.ts +29 -0
  941. package/src/worker.ts +92 -78
  942. package/src/llm/__snapshots__/utils.test.ts.snap +0 -65
@@ -1,5 +1,5 @@
1
1
  import { AudioResampler } from "@livekit/rtc-node";
2
- import { ZodObject } from "zod";
2
+ import { context as otelContext } from "@opentelemetry/api";
3
3
  import {
4
4
  ChatMessage,
5
5
  FunctionCall,
@@ -10,10 +10,22 @@ import {
10
10
  isFunctionTool,
11
11
  isToolError
12
12
  } from "../llm/tool_context.js";
13
+ import { isZodSchema, parseZodSchema } from "../llm/zod-utils.js";
13
14
  import { log } from "../log.js";
14
15
  import { IdentityTransform } from "../stream/identity_transform.js";
15
- import { Future, Task, shortuuid, toError } from "../utils.js";
16
- import { asyncLocalStorage, isStopResponse } from "./agent.js";
16
+ import { traceTypes, tracer } from "../telemetry/index.js";
17
+ import { USERDATA_TIMED_TRANSCRIPT } from "../types.js";
18
+ import { Future, Task, shortuuid, toError, waitForAbort } from "../utils.js";
19
+ import {
20
+ _setActivityTaskInfo,
21
+ functionCallStorage,
22
+ isStopResponse
23
+ } from "./agent.js";
24
+ import {
25
+ AudioOutput,
26
+ createTimedString,
27
+ isTimedString
28
+ } from "./io.js";
17
29
  import { RunContext } from "./run_context.js";
18
30
  class _LLMGenerationData {
19
31
  constructor(textStream, toolCallStream) {
@@ -25,6 +37,7 @@ class _LLMGenerationData {
25
37
  generatedText = "";
26
38
  generatedToolCalls;
27
39
  id;
40
+ ttft;
28
41
  }
29
42
  class _ToolOutput {
30
43
  output;
@@ -283,29 +296,45 @@ function updateInstructions(options) {
283
296
  );
284
297
  }
285
298
  }
286
- function performLLMInference(node, chatCtx, toolCtx, modelSettings, controller) {
299
+ function performLLMInference(node, chatCtx, toolCtx, modelSettings, controller, model, provider) {
287
300
  const textStream = new IdentityTransform();
288
301
  const toolCallStream = new IdentityTransform();
289
302
  const textWriter = textStream.writable.getWriter();
290
303
  const toolCallWriter = toolCallStream.writable.getWriter();
291
304
  const data = new _LLMGenerationData(textStream.readable, toolCallStream.readable);
292
- const inferenceTask = async (signal) => {
305
+ const _performLLMInferenceImpl = async (signal, span) => {
306
+ span.setAttribute(
307
+ traceTypes.ATTR_CHAT_CTX,
308
+ JSON.stringify(chatCtx.toJSON({ excludeTimestamp: false }))
309
+ );
310
+ span.setAttribute(traceTypes.ATTR_FUNCTION_TOOLS, JSON.stringify(Object.keys(toolCtx)));
311
+ if (model) {
312
+ span.setAttribute(traceTypes.ATTR_GEN_AI_REQUEST_MODEL, model);
313
+ }
314
+ if (provider) {
315
+ span.setAttribute(traceTypes.ATTR_GEN_AI_PROVIDER_NAME, provider);
316
+ }
293
317
  let llmStreamReader = null;
294
318
  let llmStream = null;
319
+ const startTime = performance.now() / 1e3;
320
+ let firstTokenReceived = false;
295
321
  try {
296
322
  llmStream = await node(chatCtx, toolCtx, modelSettings);
297
323
  if (llmStream === null) {
298
324
  await textWriter.close();
299
325
  return;
300
326
  }
327
+ const abortPromise = waitForAbort(signal);
301
328
  llmStreamReader = llmStream.getReader();
302
329
  while (true) {
303
- if (signal.aborted) {
304
- break;
305
- }
306
- const { done, value: chunk } = await llmStreamReader.read();
307
- if (done) {
308
- break;
330
+ if (signal.aborted) break;
331
+ const result = await Promise.race([llmStreamReader.read(), abortPromise]);
332
+ if (result === void 0) break;
333
+ const { done, value: chunk } = result;
334
+ if (done) break;
335
+ if (!firstTokenReceived) {
336
+ firstTokenReceived = true;
337
+ data.ttft = performance.now() / 1e3 - startTime;
309
338
  }
310
339
  if (typeof chunk === "string") {
311
340
  data.generatedText += chunk;
@@ -320,7 +349,10 @@ function performLLMInference(node, chatCtx, toolCtx, modelSettings, controller)
320
349
  const toolCall = FunctionCall.create({
321
350
  callId: `${data.id}/fnc_${data.generatedToolCalls.length}`,
322
351
  name: tool.name,
323
- args: tool.args
352
+ args: tool.args,
353
+ // Preserve thought signature for Gemini 3+ thinking mode
354
+ thoughtSignature: tool.thoughtSignature,
355
+ extra: tool.extra || {}
324
356
  });
325
357
  data.generatedToolCalls.push(toolCall);
326
358
  await toolCallWriter.write(toolCall);
@@ -332,6 +364,10 @@ function performLLMInference(node, chatCtx, toolCtx, modelSettings, controller)
332
364
  }
333
365
  }
334
366
  }
367
+ span.setAttribute(traceTypes.ATTR_RESPONSE_TEXT, data.generatedText);
368
+ if (data.ttft !== void 0) {
369
+ span.setAttribute(traceTypes.ATTR_RESPONSE_TTFT, data.ttft);
370
+ }
335
371
  } catch (error) {
336
372
  if (error instanceof DOMException && error.name === "AbortError") {
337
373
  return;
@@ -344,34 +380,104 @@ function performLLMInference(node, chatCtx, toolCtx, modelSettings, controller)
344
380
  await toolCallWriter.close();
345
381
  }
346
382
  };
383
+ const currentContext = otelContext.active();
384
+ const inferenceTask = async (signal) => tracer.startActiveSpan(async (span) => _performLLMInferenceImpl(signal, span), {
385
+ name: "llm_node",
386
+ context: currentContext
387
+ });
347
388
  return [
348
389
  Task.from((controller2) => inferenceTask(controller2.signal), controller, "performLLMInference"),
349
390
  data
350
391
  ];
351
392
  }
352
- function performTTSInference(node, text, modelSettings, controller) {
393
+ function performTTSInference(node, text, modelSettings, controller, model, provider) {
353
394
  const audioStream = new IdentityTransform();
354
395
  const outputWriter = audioStream.writable.getWriter();
355
396
  const audioOutputStream = audioStream.readable;
356
- const inferenceTask = async (signal) => {
397
+ const timedTextsFut = new Future();
398
+ const timedTextsStream = new IdentityTransform();
399
+ const timedTextsWriter = timedTextsStream.writable.getWriter();
400
+ const textOnlyStream = new IdentityTransform();
401
+ const textOnlyWriter = textOnlyStream.writable.getWriter();
402
+ (async () => {
403
+ const reader = text.getReader();
404
+ try {
405
+ while (true) {
406
+ const { done, value } = await reader.read();
407
+ if (done) {
408
+ break;
409
+ }
410
+ const textValue = typeof value === "string" ? value : value.text;
411
+ await textOnlyWriter.write(textValue);
412
+ }
413
+ await textOnlyWriter.close();
414
+ } catch (e) {
415
+ await textOnlyWriter.abort(e);
416
+ } finally {
417
+ reader.releaseLock();
418
+ }
419
+ })();
420
+ let ttfb;
421
+ const genData = {
422
+ audioStream: audioOutputStream,
423
+ timedTextsFut,
424
+ ttfb: void 0
425
+ };
426
+ const _performTTSInferenceImpl = async (signal, span) => {
427
+ if (model) {
428
+ span.setAttribute(traceTypes.ATTR_GEN_AI_REQUEST_MODEL, model);
429
+ }
430
+ if (provider) {
431
+ span.setAttribute(traceTypes.ATTR_GEN_AI_PROVIDER_NAME, provider);
432
+ }
357
433
  let ttsStreamReader = null;
358
434
  let ttsStream = null;
435
+ let pushedDuration = 0;
436
+ const startTime = performance.now() / 1e3;
437
+ let firstByteReceived = false;
359
438
  try {
360
- ttsStream = await node(text, modelSettings);
439
+ ttsStream = await node(textOnlyStream.readable, modelSettings);
361
440
  if (ttsStream === null) {
441
+ timedTextsFut.resolve(null);
362
442
  await outputWriter.close();
443
+ await timedTextsWriter.close();
363
444
  return;
364
445
  }
446
+ if (!timedTextsFut.done) {
447
+ timedTextsFut.resolve(timedTextsStream.readable);
448
+ }
365
449
  ttsStreamReader = ttsStream.getReader();
450
+ const initialPushedDuration = pushedDuration;
366
451
  while (true) {
367
452
  if (signal.aborted) {
368
453
  break;
369
454
  }
370
- const { done, value: chunk } = await ttsStreamReader.read();
455
+ const { done, value: frame } = await ttsStreamReader.read();
371
456
  if (done) {
372
457
  break;
373
458
  }
374
- await outputWriter.write(chunk);
459
+ if (!firstByteReceived) {
460
+ firstByteReceived = true;
461
+ ttfb = performance.now() / 1e3 - startTime;
462
+ genData.ttfb = ttfb;
463
+ span.setAttribute(traceTypes.ATTR_RESPONSE_TTFB, ttfb);
464
+ }
465
+ await outputWriter.write(frame);
466
+ const timedTranscripts = frame.userdata[USERDATA_TIMED_TRANSCRIPT];
467
+ if (timedTranscripts && timedTranscripts.length > 0) {
468
+ for (const timedText of timedTranscripts) {
469
+ const adjustedTimedText = createTimedString({
470
+ text: timedText.text,
471
+ startTime: timedText.startTime !== void 0 ? timedText.startTime + initialPushedDuration : void 0,
472
+ endTime: timedText.endTime !== void 0 ? timedText.endTime + initialPushedDuration : void 0,
473
+ confidence: timedText.confidence,
474
+ startTimeOffset: timedText.startTimeOffset
475
+ });
476
+ await timedTextsWriter.write(adjustedTimedText);
477
+ }
478
+ }
479
+ const frameDuration = frame.samplesPerChannel / frame.sampleRate;
480
+ pushedDuration += frameDuration;
375
481
  }
376
482
  } catch (error) {
377
483
  if (error instanceof DOMException && error.name === "AbortError") {
@@ -379,14 +485,23 @@ function performTTSInference(node, text, modelSettings, controller) {
379
485
  }
380
486
  throw error;
381
487
  } finally {
488
+ if (!timedTextsFut.done) {
489
+ timedTextsFut.resolve(null);
490
+ }
382
491
  ttsStreamReader == null ? void 0 : ttsStreamReader.releaseLock();
383
492
  await (ttsStream == null ? void 0 : ttsStream.cancel());
384
493
  await outputWriter.close();
494
+ await timedTextsWriter.close();
385
495
  }
386
496
  };
497
+ const currentContext = otelContext.active();
498
+ const inferenceTask = async (signal) => tracer.startActiveSpan(async (span) => _performTTSInferenceImpl(signal, span), {
499
+ name: "tts_node",
500
+ context: currentContext
501
+ });
387
502
  return [
388
503
  Task.from((controller2) => inferenceTask(controller2.signal), controller, "performTTSInference"),
389
- audioOutputStream
504
+ genData
390
505
  ];
391
506
  }
392
507
  async function forwardText(source, out, signal, textOutput) {
@@ -398,7 +513,9 @@ async function forwardText(source, out, signal, textOutput) {
398
513
  }
399
514
  const { done, value: delta } = await reader.read();
400
515
  if (done) break;
401
- out.text += delta;
516
+ const deltaIsTimedString = isTimedString(delta);
517
+ const textDelta = deltaIsTimedString ? delta.text : delta;
518
+ out.text += textDelta;
402
519
  if (textOutput !== null) {
403
520
  await textOutput.captureText(delta);
404
521
  }
@@ -427,10 +544,17 @@ function performTextForwarding(source, controller, textOutput) {
427
544
  out
428
545
  ];
429
546
  }
430
- async function forwardAudio(ttsStream, audioOuput, out, signal) {
547
+ async function forwardAudio(ttsStream, audioOutput, out, signal) {
431
548
  const reader = ttsStream.getReader();
432
549
  let resampler = null;
550
+ const onPlaybackStarted = (ev) => {
551
+ if (!out.firstFrameFut.done) {
552
+ out.firstFrameFut.resolve(ev.createdAt);
553
+ }
554
+ };
433
555
  try {
556
+ audioOutput.on(AudioOutput.EVENT_PLAYBACK_STARTED, onPlaybackStarted);
557
+ audioOutput.resume();
434
558
  while (true) {
435
559
  if (signal == null ? void 0 : signal.aborted) {
436
560
  break;
@@ -438,28 +562,29 @@ async function forwardAudio(ttsStream, audioOuput, out, signal) {
438
562
  const { done, value: frame } = await reader.read();
439
563
  if (done) break;
440
564
  out.audio.push(frame);
441
- if (!out.firstFrameFut.done && audioOuput.sampleRate && audioOuput.sampleRate !== frame.sampleRate && !resampler) {
442
- resampler = new AudioResampler(frame.sampleRate, audioOuput.sampleRate, 1);
565
+ if (!out.firstFrameFut.done && audioOutput.sampleRate && audioOutput.sampleRate !== frame.sampleRate && !resampler) {
566
+ resampler = new AudioResampler(frame.sampleRate, audioOutput.sampleRate, 1);
443
567
  }
444
568
  if (resampler) {
445
569
  for (const f of resampler.push(frame)) {
446
- await audioOuput.captureFrame(f);
570
+ await audioOutput.captureFrame(f);
447
571
  }
448
572
  } else {
449
- await audioOuput.captureFrame(frame);
450
- }
451
- if (!out.firstFrameFut.done) {
452
- out.firstFrameFut.resolve();
573
+ await audioOutput.captureFrame(frame);
453
574
  }
454
575
  }
455
- } finally {
456
- reader == null ? void 0 : reader.releaseLock();
457
576
  if (resampler) {
458
577
  for (const f of resampler.flush()) {
459
- await audioOuput.captureFrame(f);
578
+ await audioOutput.captureFrame(f);
460
579
  }
461
580
  }
462
- audioOuput.flush();
581
+ } finally {
582
+ audioOutput.off(AudioOutput.EVENT_PLAYBACK_STARTED, onPlaybackStarted);
583
+ if (!out.firstFrameFut.done) {
584
+ out.firstFrameFut.reject(new Error("audio forwarding cancelled before playback started"));
585
+ }
586
+ reader == null ? void 0 : reader.releaseLock();
587
+ audioOutput.flush();
463
588
  }
464
589
  }
465
590
  function performAudioForwarding(ttsStream, audioOutput, controller) {
@@ -539,8 +664,13 @@ function performToolExecutions({
539
664
  let parsedArgs;
540
665
  try {
541
666
  const jsonArgs = JSON.parse(toolCall.args);
542
- if (tool.parameters instanceof ZodObject) {
543
- parsedArgs = tool.parameters.parse(jsonArgs);
667
+ if (isZodSchema(tool.parameters)) {
668
+ const result = await parseZodSchema(tool.parameters, jsonArgs);
669
+ if (result.success) {
670
+ parsedArgs = result.data;
671
+ } else {
672
+ throw result.error;
673
+ }
544
674
  } else {
545
675
  parsedArgs = jsonArgs;
546
676
  }
@@ -575,14 +705,9 @@ function performToolExecutions({
575
705
  },
576
706
  "Executing LLM tool call"
577
707
  );
578
- const toolExecution = asyncLocalStorage.run({ functionCall: toolCall }, async () => {
579
- return await tool.execute(parsedArgs, {
580
- ctx: new RunContext(session, speechHandle, toolCall),
581
- toolCallId: toolCall.callId,
582
- abortSignal: signal
583
- });
584
- });
585
- const tracableToolExecution = async (toolExecTask) => {
708
+ const _tracableToolExecutionImpl = async (toolExecTask, span) => {
709
+ span.setAttribute(traceTypes.ATTR_FUNCTION_TOOL_NAME, toolCall.name);
710
+ span.setAttribute(traceTypes.ATTR_FUNCTION_TOOL_ARGS, toolCall.args);
586
711
  let toolOutput2;
587
712
  try {
588
713
  const { result, isAborted } = await waitUntilAborted(toolExecTask, signal);
@@ -591,6 +716,16 @@ function performToolExecutions({
591
716
  exception: isAborted ? new Error("tool call was aborted") : void 0,
592
717
  output: isAborted ? void 0 : result
593
718
  });
719
+ if (toolOutput2.toolCallOutput) {
720
+ span.setAttribute(
721
+ traceTypes.ATTR_FUNCTION_TOOL_OUTPUT,
722
+ toolOutput2.toolCallOutput.output
723
+ );
724
+ span.setAttribute(
725
+ traceTypes.ATTR_FUNCTION_TOOL_IS_ERROR,
726
+ toolOutput2.toolCallOutput.isError
727
+ );
728
+ }
594
729
  } catch (rawError) {
595
730
  logger.error(
596
731
  {
@@ -604,14 +739,51 @@ function performToolExecutions({
604
739
  toolCall,
605
740
  exception: toError(rawError)
606
741
  });
742
+ if (toolOutput2.toolCallOutput) {
743
+ span.setAttribute(
744
+ traceTypes.ATTR_FUNCTION_TOOL_OUTPUT,
745
+ toolOutput2.toolCallOutput.output
746
+ );
747
+ span.setAttribute(traceTypes.ATTR_FUNCTION_TOOL_IS_ERROR, true);
748
+ }
607
749
  } finally {
608
750
  if (!toolOutput2) throw new Error("toolOutput is undefined");
609
751
  toolCompleted(toolOutput2);
610
752
  }
611
753
  };
612
- tasks.push(tracableToolExecution(toolExecution));
754
+ const tracableToolExecution = (toolExecTask) => tracer.startActiveSpan(async (span) => _tracableToolExecutionImpl(toolExecTask, span), {
755
+ name: "function_tool"
756
+ });
757
+ const toolTask = Task.from(
758
+ async () => {
759
+ const currentTask = Task.current();
760
+ if (currentTask) {
761
+ _setActivityTaskInfo(currentTask, {
762
+ speechHandle,
763
+ functionCall: toolCall,
764
+ inlineTask: true
765
+ });
766
+ }
767
+ const toolExecution = functionCallStorage.run({ functionCall: toolCall }, async () => {
768
+ return await tool.execute(parsedArgs, {
769
+ ctx: new RunContext(session, speechHandle, toolCall),
770
+ toolCallId: toolCall.callId,
771
+ abortSignal: signal
772
+ });
773
+ });
774
+ await tracableToolExecution(toolExecution);
775
+ },
776
+ controller2,
777
+ `performToolExecution:${toolCall.name}`
778
+ );
779
+ _setActivityTaskInfo(toolTask, {
780
+ speechHandle,
781
+ functionCall: toolCall,
782
+ inlineTask: true
783
+ });
784
+ tasks.push(toolTask);
613
785
  }
614
- await Promise.allSettled(tasks);
786
+ await Promise.allSettled(tasks.map((task) => task.result));
615
787
  if (toolOutput.output.length > 0) {
616
788
  logger.debug(
617
789
  {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/voice/generation.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2025 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport type { AudioFrame } from '@livekit/rtc-node';\nimport { AudioResampler } from '@livekit/rtc-node';\nimport type { ReadableStream, ReadableStreamDefaultReader } from 'stream/web';\nimport { ZodObject } from 'zod';\nimport {\n type ChatContext,\n ChatMessage,\n FunctionCall,\n FunctionCallOutput,\n} from '../llm/chat_context.js';\nimport type { ChatChunk } from '../llm/llm.js';\nimport {\n type ToolChoice,\n type ToolContext,\n isAgentHandoff,\n isFunctionTool,\n isToolError,\n} from '../llm/tool_context.js';\nimport { log } from '../log.js';\nimport { IdentityTransform } from '../stream/identity_transform.js';\nimport { Future, Task, shortuuid, toError } from '../utils.js';\nimport { type Agent, type ModelSettings, asyncLocalStorage, isStopResponse } from './agent.js';\nimport type { AgentSession } from './agent_session.js';\nimport type { AudioOutput, LLMNode, TTSNode, TextOutput } from './io.js';\nimport { RunContext } from './run_context.js';\nimport type { SpeechHandle } from './speech_handle.js';\n\n/* @internal */\nexport class _LLMGenerationData {\n generatedText: string = '';\n generatedToolCalls: FunctionCall[];\n id: string;\n\n constructor(\n public readonly textStream: ReadableStream<string>,\n public readonly toolCallStream: ReadableStream<FunctionCall>,\n ) {\n this.id = shortuuid('item_');\n this.generatedToolCalls = [];\n }\n}\n\n// TODO(brian): remove this class in favor of ToolOutput\nexport class _ToolOutput {\n output: _JsOutput[];\n firstToolFut: Future;\n\n constructor() {\n this.output = [];\n this.firstToolFut = new Future();\n }\n}\n\n// TODO(brian): remove this class in favor of ToolExecutionOutput\nexport class _SanitizedOutput {\n toolCall: FunctionCall;\n toolCallOutput?: FunctionCallOutput;\n replyRequired: boolean;\n agentTask?: Agent;\n\n constructor(\n toolCall: FunctionCall,\n toolCallOutput: FunctionCallOutput | undefined,\n replyRequired: boolean,\n agentTask: Agent | undefined,\n ) {\n this.toolCall = toolCall;\n this.toolCallOutput = toolCallOutput;\n this.replyRequired = replyRequired;\n this.agentTask = agentTask;\n }\n\n static create(params: {\n toolCall: FunctionCall;\n toolCallOutput?: FunctionCallOutput;\n replyRequired?: boolean;\n agentTask?: Agent;\n }) {\n const { toolCall, toolCallOutput, replyRequired = true, agentTask } = params;\n return new _SanitizedOutput(toolCall, toolCallOutput, replyRequired, agentTask);\n }\n}\n\nfunction isValidToolOutput(toolOutput: unknown): boolean {\n const validTypes = ['string', 'number', 'boolean'];\n\n if (validTypes.includes(typeof toolOutput)) {\n return true;\n }\n\n if (toolOutput === undefined || toolOutput === null) {\n return true;\n }\n\n if (Array.isArray(toolOutput)) {\n return toolOutput.every(isValidToolOutput);\n }\n\n if (toolOutput instanceof Set) {\n return Array.from(toolOutput).every(isValidToolOutput);\n }\n\n if (toolOutput instanceof Map) {\n return Array.from(toolOutput.values()).every(isValidToolOutput);\n }\n\n if (toolOutput instanceof Object) {\n return Object.entries(toolOutput).every(\n ([key, value]) => validTypes.includes(typeof key) && isValidToolOutput(value),\n );\n }\n\n return false;\n}\n\nexport class ToolExecutionOutput {\n constructor(\n public readonly toolCall: FunctionCall,\n public readonly toolCallOutput: FunctionCallOutput | undefined,\n public readonly agentTask: Agent | undefined,\n public readonly rawOutput: unknown,\n public readonly rawException: Error | undefined,\n public readonly replyRequired: boolean,\n ) {}\n\n static create(params: {\n toolCall: FunctionCall;\n toolCallOutput?: FunctionCallOutput;\n agentTask?: Agent;\n rawOutput: unknown;\n rawException?: Error;\n replyRequired?: boolean;\n }) {\n const {\n toolCall,\n toolCallOutput,\n agentTask,\n rawOutput,\n rawException,\n replyRequired = true,\n } = params;\n return new ToolExecutionOutput(\n toolCall,\n toolCallOutput,\n agentTask,\n rawOutput,\n rawException,\n replyRequired,\n );\n }\n}\n\nexport interface ToolOutput {\n output: ToolExecutionOutput[];\n firstToolStartedFuture: Future<void>;\n}\n\n// TODO(brian): remove this class in favor of ToolExecutionOutput\nexport class _JsOutput {\n toolCall: FunctionCall;\n output: unknown;\n exception?: Error;\n\n #logger = log();\n\n constructor(toolCall: FunctionCall, output: unknown, exception: Error | undefined) {\n this.toolCall = toolCall;\n this.output = output;\n this.exception = exception;\n }\n\n static create(params: { toolCall: FunctionCall; output?: unknown; exception?: Error }) {\n const { toolCall, output = undefined, exception = undefined } = params;\n return new _JsOutput(toolCall, output, exception);\n }\n\n sanitize(): _SanitizedOutput {\n if (isToolError(this.exception)) {\n return _SanitizedOutput.create({\n toolCall: FunctionCall.create({ ...this.toolCall }),\n toolCallOutput: FunctionCallOutput.create({\n name: this.toolCall.name,\n callId: this.toolCall.callId,\n output: this.exception.message,\n isError: true,\n }),\n });\n }\n\n if (isStopResponse(this.exception)) {\n return _SanitizedOutput.create({\n toolCall: FunctionCall.create({ ...this.toolCall }),\n });\n }\n\n if (this.exception !== undefined) {\n return _SanitizedOutput.create({\n toolCall: FunctionCall.create({ ...this.toolCall }),\n toolCallOutput: FunctionCallOutput.create({\n name: this.toolCall.name,\n callId: this.toolCall.callId,\n output: 'An internal error occurred while executing the tool.', // Don't send the actual error message, as it may contain sensitive information\n isError: true,\n }),\n });\n }\n\n let agentTask: Agent | undefined = undefined;\n let toolOutput: unknown = this.output;\n if (isAgentHandoff(this.output)) {\n agentTask = this.output.agent;\n toolOutput = this.output.returns;\n }\n\n if (!isValidToolOutput(toolOutput)) {\n this.#logger.error(\n {\n callId: this.toolCall.callId,\n function: this.toolCall.name,\n },\n `AI function ${this.toolCall.name} returned an invalid output`,\n );\n return _SanitizedOutput.create({\n toolCall: FunctionCall.create({ ...this.toolCall }),\n toolCallOutput: undefined,\n });\n }\n\n return _SanitizedOutput.create({\n toolCall: FunctionCall.create({ ...this.toolCall }),\n toolCallOutput: FunctionCallOutput.create({\n name: this.toolCall.name,\n callId: this.toolCall.callId,\n output: toolOutput !== undefined ? JSON.stringify(toolOutput) : '', // take the string representation of the output\n isError: false,\n }),\n replyRequired: toolOutput !== undefined, // require a reply if the tool returned an output\n agentTask,\n });\n }\n}\n\nexport function createToolOutput(params: {\n toolCall: FunctionCall;\n output?: unknown;\n exception?: Error;\n}): ToolExecutionOutput {\n const { toolCall, output, exception } = params;\n const logger = log();\n\n // support returning Exception instead of raising them (for devex purposes inside evals)\n let finalOutput = output;\n let finalException = exception;\n if (output instanceof Error) {\n finalException = output;\n finalOutput = undefined;\n }\n\n if (isToolError(finalException)) {\n return ToolExecutionOutput.create({\n toolCall: FunctionCall.create({ ...toolCall }),\n toolCallOutput: FunctionCallOutput.create({\n name: toolCall.name,\n callId: toolCall.callId,\n output: finalException.message,\n isError: true,\n }),\n rawOutput: finalOutput,\n rawException: finalException,\n });\n }\n\n if (isStopResponse(finalException)) {\n return ToolExecutionOutput.create({\n toolCall: FunctionCall.create({ ...toolCall }),\n rawOutput: finalOutput,\n rawException: finalException,\n });\n }\n\n if (finalException !== undefined) {\n return ToolExecutionOutput.create({\n toolCall: FunctionCall.create({ ...toolCall }),\n toolCallOutput: FunctionCallOutput.create({\n name: toolCall.name,\n callId: toolCall.callId,\n output: 'An internal error occurred', // Don't send the actual error message, as it may contain sensitive information\n isError: true,\n }),\n rawOutput: finalOutput,\n rawException: finalException,\n });\n }\n\n let agentTask: Agent | undefined = undefined;\n let toolOutput: unknown = finalOutput;\n if (isAgentHandoff(finalOutput)) {\n agentTask = finalOutput.agent;\n toolOutput = finalOutput.returns;\n }\n\n if (!isValidToolOutput(toolOutput)) {\n logger.error(\n {\n callId: toolCall.callId,\n output: finalOutput,\n },\n `AI function ${toolCall.name} returned an invalid output`,\n );\n return ToolExecutionOutput.create({\n toolCall: FunctionCall.create({ ...toolCall }),\n rawOutput: finalOutput,\n rawException: finalException,\n });\n }\n\n return ToolExecutionOutput.create({\n toolCall: FunctionCall.create({ ...toolCall }),\n toolCallOutput: FunctionCallOutput.create({\n name: toolCall.name,\n callId: toolCall.callId,\n output: toolOutput !== undefined ? JSON.stringify(toolOutput) : '', // take the string representation of the output\n isError: false,\n }),\n replyRequired: toolOutput !== undefined, // require a reply if the tool returned an output\n agentTask,\n rawOutput: finalOutput,\n rawException: finalException,\n });\n}\n\nconst INSTRUCTIONS_MESSAGE_ID = 'lk.agent_task.instructions';\n\n/**\n * Update the instruction message in the chat context or insert a new one if missing.\n *\n * This function looks for an existing instruction message in the chat context using the identifier\n * 'INSTRUCTIONS_MESSAGE_ID'.\n *\n * @param options - The options for updating the instructions.\n * @param options.chatCtx - The chat context to update.\n * @param options.instructions - The instructions to add.\n * @param options.addIfMissing - Whether to add the instructions if they are missing.\n */\nexport function updateInstructions(options: {\n chatCtx: ChatContext;\n instructions: string;\n addIfMissing: boolean;\n}) {\n const { chatCtx, instructions, addIfMissing } = options;\n\n const idx = chatCtx.indexById(INSTRUCTIONS_MESSAGE_ID);\n if (idx !== undefined) {\n if (chatCtx.items[idx]!.type === 'message') {\n // create a new instance to avoid mutating the original\n chatCtx.items[idx] = ChatMessage.create({\n id: INSTRUCTIONS_MESSAGE_ID,\n role: 'system',\n content: [instructions],\n createdAt: chatCtx.items[idx]!.createdAt,\n });\n } else {\n throw new Error('expected the instructions inside the chatCtx to be of type \"message\"');\n }\n } else if (addIfMissing) {\n // insert the instructions at the beginning of the chat context\n chatCtx.items.unshift(\n ChatMessage.create({\n id: INSTRUCTIONS_MESSAGE_ID,\n role: 'system',\n content: [instructions],\n }),\n );\n }\n}\n\nexport function performLLMInference(\n node: LLMNode,\n chatCtx: ChatContext,\n toolCtx: ToolContext,\n modelSettings: ModelSettings,\n controller: AbortController,\n): [Task<void>, _LLMGenerationData] {\n const textStream = new IdentityTransform<string>();\n const toolCallStream = new IdentityTransform<FunctionCall>();\n\n const textWriter = textStream.writable.getWriter();\n const toolCallWriter = toolCallStream.writable.getWriter();\n const data = new _LLMGenerationData(textStream.readable, toolCallStream.readable);\n\n const inferenceTask = async (signal: AbortSignal) => {\n let llmStreamReader: ReadableStreamDefaultReader<string | ChatChunk> | null = null;\n let llmStream: ReadableStream<string | ChatChunk> | null = null;\n\n try {\n llmStream = await node(chatCtx, toolCtx, modelSettings);\n if (llmStream === null) {\n await textWriter.close();\n return;\n }\n\n // TODO(brian): add support for dynamic tools\n\n llmStreamReader = llmStream.getReader();\n while (true) {\n if (signal.aborted) {\n break;\n }\n const { done, value: chunk } = await llmStreamReader.read();\n if (done) {\n break;\n }\n\n if (typeof chunk === 'string') {\n data.generatedText += chunk;\n await textWriter.write(chunk);\n // TODO(shubhra): better way to check??\n } else {\n if (chunk.delta === undefined) {\n continue;\n }\n\n if (chunk.delta.toolCalls) {\n for (const tool of chunk.delta.toolCalls) {\n if (tool.type !== 'function_call') continue;\n\n const toolCall = FunctionCall.create({\n callId: `${data.id}/fnc_${data.generatedToolCalls.length}`,\n name: tool.name,\n args: tool.args,\n });\n\n data.generatedToolCalls.push(toolCall);\n await toolCallWriter.write(toolCall);\n }\n }\n\n if (chunk.delta.content) {\n data.generatedText += chunk.delta.content;\n await textWriter.write(chunk.delta.content);\n }\n }\n\n // No need to check if chunk is of type other than ChatChunk or string like in\n // Python since chunk is defined in the type ChatChunk | string in TypeScript\n }\n } catch (error) {\n if (error instanceof DOMException && error.name === 'AbortError') {\n // Abort signal was triggered, handle gracefully\n return;\n }\n throw error;\n } finally {\n llmStreamReader?.releaseLock();\n await llmStream?.cancel();\n await textWriter.close();\n await toolCallWriter.close();\n }\n };\n\n return [\n Task.from((controller) => inferenceTask(controller.signal), controller, 'performLLMInference'),\n data,\n ];\n}\n\nexport function performTTSInference(\n node: TTSNode,\n text: ReadableStream<string>,\n modelSettings: ModelSettings,\n controller: AbortController,\n): [Task<void>, ReadableStream<AudioFrame>] {\n const audioStream = new IdentityTransform<AudioFrame>();\n const outputWriter = audioStream.writable.getWriter();\n const audioOutputStream = audioStream.readable;\n\n const inferenceTask = async (signal: AbortSignal) => {\n let ttsStreamReader: ReadableStreamDefaultReader<AudioFrame> | null = null;\n let ttsStream: ReadableStream<AudioFrame> | null = null;\n\n try {\n ttsStream = await node(text, modelSettings);\n if (ttsStream === null) {\n await outputWriter.close();\n return;\n }\n\n ttsStreamReader = ttsStream.getReader();\n while (true) {\n if (signal.aborted) {\n break;\n }\n const { done, value: chunk } = await ttsStreamReader.read();\n if (done) {\n break;\n }\n await outputWriter.write(chunk);\n }\n } catch (error) {\n if (error instanceof DOMException && error.name === 'AbortError') {\n // Abort signal was triggered, handle gracefully\n return;\n }\n throw error;\n } finally {\n ttsStreamReader?.releaseLock();\n await ttsStream?.cancel();\n await outputWriter.close();\n }\n };\n\n return [\n Task.from((controller) => inferenceTask(controller.signal), controller, 'performTTSInference'),\n audioOutputStream,\n ];\n}\n\nexport interface _TextOut {\n text: string;\n firstTextFut: Future;\n}\n\nasync function forwardText(\n source: ReadableStream<string>,\n out: _TextOut,\n signal: AbortSignal,\n textOutput: TextOutput | null,\n): Promise<void> {\n const reader = source.getReader();\n try {\n while (true) {\n if (signal.aborted) {\n break;\n }\n const { done, value: delta } = await reader.read();\n if (done) break;\n out.text += delta;\n if (textOutput !== null) {\n await textOutput.captureText(delta);\n }\n if (!out.firstTextFut.done) {\n out.firstTextFut.resolve();\n }\n }\n } finally {\n if (textOutput !== null) {\n textOutput.flush();\n }\n reader?.releaseLock();\n }\n}\n\nexport function performTextForwarding(\n source: ReadableStream<string>,\n controller: AbortController,\n textOutput: TextOutput | null,\n): [Task<void>, _TextOut] {\n const out = {\n text: '',\n firstTextFut: new Future(),\n };\n return [\n Task.from(\n (controller) => forwardText(source, out, controller.signal, textOutput),\n controller,\n 'performTextForwarding',\n ),\n out,\n ];\n}\n\nexport interface _AudioOut {\n audio: Array<AudioFrame>;\n firstFrameFut: Future;\n}\n\nasync function forwardAudio(\n ttsStream: ReadableStream<AudioFrame>,\n audioOuput: AudioOutput,\n out: _AudioOut,\n signal?: AbortSignal,\n): Promise<void> {\n const reader = ttsStream.getReader();\n let resampler: AudioResampler | null = null;\n\n try {\n while (true) {\n if (signal?.aborted) {\n break;\n }\n\n const { done, value: frame } = await reader.read();\n if (done) break;\n\n out.audio.push(frame);\n\n if (\n !out.firstFrameFut.done &&\n audioOuput.sampleRate &&\n audioOuput.sampleRate !== frame.sampleRate &&\n !resampler\n ) {\n resampler = new AudioResampler(frame.sampleRate, audioOuput.sampleRate, 1);\n }\n\n if (resampler) {\n for (const f of resampler.push(frame)) {\n await audioOuput.captureFrame(f);\n }\n } else {\n await audioOuput.captureFrame(frame);\n }\n\n // set the first frame future if not already set\n // (after completing the first frame)\n if (!out.firstFrameFut.done) {\n out.firstFrameFut.resolve();\n }\n }\n } finally {\n reader?.releaseLock();\n if (resampler) {\n for (const f of resampler.flush()) {\n await audioOuput.captureFrame(f);\n }\n }\n audioOuput.flush();\n }\n}\n\nexport function performAudioForwarding(\n ttsStream: ReadableStream<AudioFrame>,\n audioOutput: AudioOutput,\n controller: AbortController,\n): [Task<void>, _AudioOut] {\n const out = {\n audio: [],\n firstFrameFut: new Future(),\n };\n return [\n Task.from(\n (controller) => forwardAudio(ttsStream, audioOutput, out, controller.signal),\n controller,\n 'performAudioForwarding',\n ),\n out,\n ];\n}\n\nexport function performToolExecutions({\n session,\n speechHandle,\n toolCtx,\n toolChoice,\n toolCallStream,\n onToolExecutionStarted = () => {},\n onToolExecutionCompleted = () => {},\n controller,\n}: {\n session: AgentSession;\n speechHandle: SpeechHandle;\n toolCtx: ToolContext;\n toolChoice?: ToolChoice;\n toolCallStream: ReadableStream<FunctionCall>;\n onToolExecutionStarted?: (toolCall: FunctionCall) => void;\n onToolExecutionCompleted?: (toolExecutionOutput: ToolExecutionOutput) => void;\n controller: AbortController;\n}): [Task<void>, ToolOutput] {\n const logger = log();\n const toolOutput: ToolOutput = {\n output: [],\n firstToolStartedFuture: new Future(),\n };\n\n const toolCompleted = (out: ToolExecutionOutput) => {\n onToolExecutionCompleted(out);\n toolOutput.output.push(out);\n };\n\n const executeToolsTask = async (controller: AbortController) => {\n const signal = controller.signal;\n const reader = toolCallStream.getReader();\n\n const tasks: Promise<any>[] = [];\n while (!signal.aborted) {\n const { done, value: toolCall } = await reader.read();\n if (signal.aborted) break;\n if (done) break;\n\n if (toolChoice === 'none') {\n logger.error(\n {\n function: toolCall.name,\n speech_id: speechHandle.id,\n },\n \"received a tool call with toolChoice set to 'none', ignoring\",\n );\n continue;\n }\n\n // TODO(brian): assert other toolChoice values\n\n const tool = toolCtx[toolCall.name];\n if (!tool) {\n logger.warn(\n {\n function: toolCall.name,\n speech_id: speechHandle.id,\n },\n `unknown AI function ${toolCall.name}`,\n );\n continue;\n }\n\n if (!isFunctionTool(tool)) {\n logger.error(\n {\n function: toolCall.name,\n speech_id: speechHandle.id,\n },\n `unknown tool type: ${typeof tool}`,\n );\n continue;\n }\n\n let parsedArgs: object | undefined;\n\n // Ensure valid arguments\n try {\n const jsonArgs = JSON.parse(toolCall.args);\n\n if (tool.parameters instanceof ZodObject) {\n parsedArgs = tool.parameters.parse(jsonArgs);\n } else {\n parsedArgs = jsonArgs;\n }\n } catch (rawError) {\n const error = toError(rawError);\n logger.error(\n {\n function: toolCall.name,\n arguments: toolCall.args,\n speech_id: speechHandle.id,\n error: error.message,\n },\n `tried to call AI function ${toolCall.name} with invalid arguments`,\n );\n toolCompleted(\n createToolOutput({\n toolCall,\n exception: error,\n }),\n );\n continue;\n }\n\n if (!toolOutput.firstToolStartedFuture.done) {\n toolOutput.firstToolStartedFuture.resolve();\n }\n\n onToolExecutionStarted(toolCall);\n\n logger.info(\n {\n function: toolCall.name,\n arguments: parsedArgs,\n speech_id: speechHandle.id,\n },\n 'Executing LLM tool call',\n );\n\n const toolExecution = asyncLocalStorage.run({ functionCall: toolCall }, async () => {\n return await tool.execute(parsedArgs, {\n ctx: new RunContext(session, speechHandle, toolCall),\n toolCallId: toolCall.callId,\n abortSignal: signal,\n });\n });\n\n const tracableToolExecution = async (toolExecTask: Promise<unknown>) => {\n // TODO(brian): add tracing\n\n // await for task to complete, if task is aborted, set exception\n let toolOutput: ToolExecutionOutput | undefined;\n try {\n const { result, isAborted } = await waitUntilAborted(toolExecTask, signal);\n toolOutput = createToolOutput({\n toolCall,\n exception: isAborted ? new Error('tool call was aborted') : undefined,\n output: isAborted ? undefined : result,\n });\n } catch (rawError) {\n logger.error(\n {\n function: toolCall.name,\n speech_id: speechHandle.id,\n error: toError(rawError).message,\n },\n 'exception occurred while executing tool',\n );\n toolOutput = createToolOutput({\n toolCall,\n exception: toError(rawError),\n });\n } finally {\n if (!toolOutput) throw new Error('toolOutput is undefined');\n toolCompleted(toolOutput);\n }\n };\n\n // wait, not cancelling all tool calling tasks\n tasks.push(tracableToolExecution(toolExecution));\n }\n\n await Promise.allSettled(tasks);\n if (toolOutput.output.length > 0) {\n logger.debug(\n {\n speech_id: speechHandle.id,\n },\n 'tools execution completed',\n );\n }\n };\n\n return [Task.from(executeToolsTask, controller, 'performToolExecutions'), toolOutput];\n}\n\ntype Aborted<T> =\n | {\n result: T;\n isAborted: false;\n }\n | {\n result: undefined;\n isAborted: true;\n };\n\nasync function waitUntilAborted<T>(promise: Promise<T>, signal: AbortSignal): Promise<Aborted<T>> {\n const abortFut = new Future<Aborted<T>>();\n\n const resolveAbort = () => {\n if (!abortFut.done) {\n abortFut.resolve({ result: undefined, isAborted: true });\n }\n };\n\n signal.addEventListener('abort', resolveAbort);\n\n promise\n .then((r) => {\n if (!abortFut.done) {\n abortFut.resolve({ result: r, isAborted: false });\n }\n })\n .catch((e) => {\n if (!abortFut.done) {\n abortFut.reject(e);\n }\n })\n .finally(() => {\n signal.removeEventListener('abort', resolveAbort);\n });\n\n return await abortFut.await;\n}\n\nexport function removeInstructions(chatCtx: ChatContext) {\n // loop in case there are items with the same id (shouldn't happen!)\n while (true) {\n const idx = chatCtx.indexById(INSTRUCTIONS_MESSAGE_ID);\n if (idx !== undefined) {\n chatCtx.items.splice(idx, 1);\n } else {\n break;\n }\n }\n}\n"],"mappings":"AAIA,SAAS,sBAAsB;AAE/B,SAAS,iBAAiB;AAC1B;AAAA,EAEE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP;AAAA,EAGE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,WAAW;AACpB,SAAS,yBAAyB;AAClC,SAAS,QAAQ,MAAM,WAAW,eAAe;AACjD,SAAyC,mBAAmB,sBAAsB;AAGlF,SAAS,kBAAkB;AAIpB,MAAM,mBAAmB;AAAA,EAK9B,YACkB,YACA,gBAChB;AAFgB;AACA;AAEhB,SAAK,KAAK,UAAU,OAAO;AAC3B,SAAK,qBAAqB,CAAC;AAAA,EAC7B;AAAA,EAVA,gBAAwB;AAAA,EACxB;AAAA,EACA;AASF;AAGO,MAAM,YAAY;AAAA,EACvB;AAAA,EACA;AAAA,EAEA,cAAc;AACZ,SAAK,SAAS,CAAC;AACf,SAAK,eAAe,IAAI,OAAO;AAAA,EACjC;AACF;AAGO,MAAM,iBAAiB;AAAA,EAC5B;AAAA,EACA;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Y;AAAA,EAClD,CAAC;AAEH,SAAO,MAAM,SAAS;AACxB;AAEO,SAAS,mBAAmB,SAAsB;AAEvD,SAAO,MAAM;AACX,UAAM,MAAM,QAAQ,UAAU,uBAAuB;AACrD,QAAI,QAAQ,QAAW;AACrB,cAAQ,MAAM,OAAO,KAAK,CAAC;AAAA,IAC7B,OAAO;AACL;AAAA,IACF;AAAA,EACF;AACF;","names":["controller","toolOutput"]}
1
+ {"version":3,"sources":["../../src/voice/generation.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2025 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport type { AudioFrame } from '@livekit/rtc-node';\nimport { AudioResampler } from '@livekit/rtc-node';\nimport type { Span } from '@opentelemetry/api';\nimport { context as otelContext } from '@opentelemetry/api';\nimport type { ReadableStream, ReadableStreamDefaultReader } from 'stream/web';\nimport {\n type ChatContext,\n ChatMessage,\n FunctionCall,\n FunctionCallOutput,\n} from '../llm/chat_context.js';\nimport type { ChatChunk } from '../llm/llm.js';\nimport {\n type ToolChoice,\n type ToolContext,\n isAgentHandoff,\n isFunctionTool,\n isToolError,\n} from '../llm/tool_context.js';\nimport { isZodSchema, parseZodSchema } from '../llm/zod-utils.js';\nimport { log } from '../log.js';\nimport { IdentityTransform } from '../stream/identity_transform.js';\nimport { traceTypes, tracer } from '../telemetry/index.js';\nimport { USERDATA_TIMED_TRANSCRIPT } from '../types.js';\nimport { Future, Task, shortuuid, toError, waitForAbort } from '../utils.js';\nimport {\n type Agent,\n type ModelSettings,\n _setActivityTaskInfo,\n functionCallStorage,\n isStopResponse,\n} from './agent.js';\nimport type { AgentSession } from './agent_session.js';\nimport {\n AudioOutput,\n type LLMNode,\n type TTSNode,\n type TextOutput,\n type TimedString,\n createTimedString,\n isTimedString,\n} from './io.js';\nimport { RunContext } from './run_context.js';\nimport type { SpeechHandle } from './speech_handle.js';\n\n/** @internal */\nexport class _LLMGenerationData {\n generatedText: string = '';\n generatedToolCalls: FunctionCall[];\n id: string;\n ttft?: number;\n\n constructor(\n public readonly textStream: ReadableStream<string>,\n public readonly toolCallStream: ReadableStream<FunctionCall>,\n ) {\n this.id = shortuuid('item_');\n this.generatedToolCalls = [];\n }\n}\n\n/**\n * TTS generation data containing audio stream and optional timed transcripts.\n * @internal\n */\nexport interface _TTSGenerationData {\n /** Audio frame stream from TTS */\n audioStream: ReadableStream<AudioFrame>;\n /**\n * Future that resolves to a stream of timed transcripts, or null if TTS doesn't support it.\n */\n timedTextsFut: Future<ReadableStream<TimedString> | null>;\n /** Time to first byte (set when first audio frame is received) */\n ttfb?: number;\n}\n\n// TODO(brian): remove this class in favor of ToolOutput\nexport class _ToolOutput {\n output: _JsOutput[];\n firstToolFut: Future;\n\n constructor() {\n this.output = [];\n this.firstToolFut = new Future();\n }\n}\n\n// TODO(brian): remove this class in favor of ToolExecutionOutput\nexport class _SanitizedOutput {\n toolCall: FunctionCall;\n toolCallOutput?: FunctionCallOutput;\n replyRequired: boolean;\n agentTask?: Agent;\n\n constructor(\n toolCall: FunctionCall,\n toolCallOutput: FunctionCallOutput | undefined,\n replyRequired: boolean,\n agentTask: Agent | undefined,\n ) {\n this.toolCall = toolCall;\n this.toolCallOutput = toolCallOutput;\n this.replyRequired = replyRequired;\n this.agentTask = agentTask;\n }\n\n static create(params: {\n toolCall: FunctionCall;\n toolCallOutput?: FunctionCallOutput;\n replyRequired?: boolean;\n agentTask?: Agent;\n }) {\n const { toolCall, toolCallOutput, replyRequired = true, agentTask } = params;\n return new _SanitizedOutput(toolCall, toolCallOutput, replyRequired, agentTask);\n }\n}\n\nfunction isValidToolOutput(toolOutput: unknown): boolean {\n const validTypes = ['string', 'number', 'boolean'];\n\n if (validTypes.includes(typeof toolOutput)) {\n return true;\n }\n\n if (toolOutput === undefined || toolOutput === null) {\n return true;\n }\n\n if (Array.isArray(toolOutput)) {\n return toolOutput.every(isValidToolOutput);\n }\n\n if (toolOutput instanceof Set) {\n return Array.from(toolOutput).every(isValidToolOutput);\n }\n\n if (toolOutput instanceof Map) {\n return Array.from(toolOutput.values()).every(isValidToolOutput);\n }\n\n if (toolOutput instanceof Object) {\n return Object.entries(toolOutput).every(\n ([key, value]) => validTypes.includes(typeof key) && isValidToolOutput(value),\n );\n }\n\n return false;\n}\n\nexport class ToolExecutionOutput {\n constructor(\n public readonly toolCall: FunctionCall,\n public readonly toolCallOutput: FunctionCallOutput | undefined,\n public readonly agentTask: Agent | undefined,\n public readonly rawOutput: unknown,\n public readonly rawException: Error | undefined,\n public readonly replyRequired: boolean,\n ) {}\n\n static create(params: {\n toolCall: FunctionCall;\n toolCallOutput?: FunctionCallOutput;\n agentTask?: Agent;\n rawOutput: unknown;\n rawException?: Error;\n replyRequired?: boolean;\n }) {\n const {\n toolCall,\n toolCallOutput,\n agentTask,\n rawOutput,\n rawException,\n replyRequired = true,\n } = params;\n return new ToolExecutionOutput(\n toolCall,\n toolCallOutput,\n agentTask,\n rawOutput,\n rawException,\n replyRequired,\n );\n }\n}\n\nexport interface ToolOutput {\n output: ToolExecutionOutput[];\n firstToolStartedFuture: Future<void>;\n}\n\n// TODO(brian): remove this class in favor of ToolExecutionOutput\nexport class _JsOutput {\n toolCall: FunctionCall;\n output: unknown;\n exception?: Error;\n\n #logger = log();\n\n constructor(toolCall: FunctionCall, output: unknown, exception: Error | undefined) {\n this.toolCall = toolCall;\n this.output = output;\n this.exception = exception;\n }\n\n static create(params: { toolCall: FunctionCall; output?: unknown; exception?: Error }) {\n const { toolCall, output = undefined, exception = undefined } = params;\n return new _JsOutput(toolCall, output, exception);\n }\n\n sanitize(): _SanitizedOutput {\n if (isToolError(this.exception)) {\n return _SanitizedOutput.create({\n toolCall: FunctionCall.create({ ...this.toolCall }),\n toolCallOutput: FunctionCallOutput.create({\n name: this.toolCall.name,\n callId: this.toolCall.callId,\n output: this.exception.message,\n isError: true,\n }),\n });\n }\n\n if (isStopResponse(this.exception)) {\n return _SanitizedOutput.create({\n toolCall: FunctionCall.create({ ...this.toolCall }),\n });\n }\n\n if (this.exception !== undefined) {\n return _SanitizedOutput.create({\n toolCall: FunctionCall.create({ ...this.toolCall }),\n toolCallOutput: FunctionCallOutput.create({\n name: this.toolCall.name,\n callId: this.toolCall.callId,\n output: 'An internal error occurred while executing the tool.', // Don't send the actual error message, as it may contain sensitive information\n isError: true,\n }),\n });\n }\n\n let agentTask: Agent | undefined = undefined;\n let toolOutput: unknown = this.output;\n if (isAgentHandoff(this.output)) {\n agentTask = this.output.agent;\n toolOutput = this.output.returns;\n }\n\n if (!isValidToolOutput(toolOutput)) {\n this.#logger.error(\n {\n callId: this.toolCall.callId,\n function: this.toolCall.name,\n },\n `AI function ${this.toolCall.name} returned an invalid output`,\n );\n return _SanitizedOutput.create({\n toolCall: FunctionCall.create({ ...this.toolCall }),\n toolCallOutput: undefined,\n });\n }\n\n return _SanitizedOutput.create({\n toolCall: FunctionCall.create({ ...this.toolCall }),\n toolCallOutput: FunctionCallOutput.create({\n name: this.toolCall.name,\n callId: this.toolCall.callId,\n output: toolOutput !== undefined ? JSON.stringify(toolOutput) : '', // take the string representation of the output\n isError: false,\n }),\n replyRequired: toolOutput !== undefined, // require a reply if the tool returned an output\n agentTask,\n });\n }\n}\n\nexport function createToolOutput(params: {\n toolCall: FunctionCall;\n output?: unknown;\n exception?: Error;\n}): ToolExecutionOutput {\n const { toolCall, output, exception } = params;\n const logger = log();\n\n // support returning Exception instead of raising them (for devex purposes inside evals)\n let finalOutput = output;\n let finalException = exception;\n if (output instanceof Error) {\n finalException = output;\n finalOutput = undefined;\n }\n\n if (isToolError(finalException)) {\n return ToolExecutionOutput.create({\n toolCall: FunctionCall.create({ ...toolCall }),\n toolCallOutput: FunctionCallOutput.create({\n name: toolCall.name,\n callId: toolCall.callId,\n output: finalException.message,\n isError: true,\n }),\n rawOutput: finalOutput,\n rawException: finalException,\n });\n }\n\n if (isStopResponse(finalException)) {\n return ToolExecutionOutput.create({\n toolCall: FunctionCall.create({ ...toolCall }),\n rawOutput: finalOutput,\n rawException: finalException,\n });\n }\n\n if (finalException !== undefined) {\n return ToolExecutionOutput.create({\n toolCall: FunctionCall.create({ ...toolCall }),\n toolCallOutput: FunctionCallOutput.create({\n name: toolCall.name,\n callId: toolCall.callId,\n output: 'An internal error occurred', // Don't send the actual error message, as it may contain sensitive information\n isError: true,\n }),\n rawOutput: finalOutput,\n rawException: finalException,\n });\n }\n\n let agentTask: Agent | undefined = undefined;\n let toolOutput: unknown = finalOutput;\n if (isAgentHandoff(finalOutput)) {\n agentTask = finalOutput.agent;\n toolOutput = finalOutput.returns;\n }\n\n if (!isValidToolOutput(toolOutput)) {\n logger.error(\n {\n callId: toolCall.callId,\n output: finalOutput,\n },\n `AI function ${toolCall.name} returned an invalid output`,\n );\n return ToolExecutionOutput.create({\n toolCall: FunctionCall.create({ ...toolCall }),\n rawOutput: finalOutput,\n rawException: finalException,\n });\n }\n\n return ToolExecutionOutput.create({\n toolCall: FunctionCall.create({ ...toolCall }),\n toolCallOutput: FunctionCallOutput.create({\n name: toolCall.name,\n callId: toolCall.callId,\n output: toolOutput !== undefined ? JSON.stringify(toolOutput) : '', // take the string representation of the output\n isError: false,\n }),\n replyRequired: toolOutput !== undefined, // require a reply if the tool returned an output\n agentTask,\n rawOutput: finalOutput,\n rawException: finalException,\n });\n}\n\nconst INSTRUCTIONS_MESSAGE_ID = 'lk.agent_task.instructions';\n\n/**\n * Update the instruction message in the chat context or insert a new one if missing.\n *\n * This function looks for an existing instruction message in the chat context using the identifier\n * 'INSTRUCTIONS_MESSAGE_ID'.\n *\n * @param options - The options for updating the instructions.\n * @param options.chatCtx - The chat context to update.\n * @param options.instructions - The instructions to add.\n * @param options.addIfMissing - Whether to add the instructions if they are missing.\n */\nexport function updateInstructions(options: {\n chatCtx: ChatContext;\n instructions: string;\n addIfMissing: boolean;\n}) {\n const { chatCtx, instructions, addIfMissing } = options;\n\n const idx = chatCtx.indexById(INSTRUCTIONS_MESSAGE_ID);\n if (idx !== undefined) {\n if (chatCtx.items[idx]!.type === 'message') {\n // create a new instance to avoid mutating the original\n chatCtx.items[idx] = ChatMessage.create({\n id: INSTRUCTIONS_MESSAGE_ID,\n role: 'system',\n content: [instructions],\n createdAt: chatCtx.items[idx]!.createdAt,\n });\n } else {\n throw new Error('expected the instructions inside the chatCtx to be of type \"message\"');\n }\n } else if (addIfMissing) {\n // insert the instructions at the beginning of the chat context\n chatCtx.items.unshift(\n ChatMessage.create({\n id: INSTRUCTIONS_MESSAGE_ID,\n role: 'system',\n content: [instructions],\n }),\n );\n }\n}\n\nexport function performLLMInference(\n node: LLMNode,\n chatCtx: ChatContext,\n toolCtx: ToolContext,\n modelSettings: ModelSettings,\n controller: AbortController,\n model?: string,\n provider?: string,\n): [Task<void>, _LLMGenerationData] {\n const textStream = new IdentityTransform<string>();\n const toolCallStream = new IdentityTransform<FunctionCall>();\n\n const textWriter = textStream.writable.getWriter();\n const toolCallWriter = toolCallStream.writable.getWriter();\n const data = new _LLMGenerationData(textStream.readable, toolCallStream.readable);\n\n const _performLLMInferenceImpl = async (signal: AbortSignal, span: Span) => {\n span.setAttribute(\n traceTypes.ATTR_CHAT_CTX,\n JSON.stringify(chatCtx.toJSON({ excludeTimestamp: false })),\n );\n span.setAttribute(traceTypes.ATTR_FUNCTION_TOOLS, JSON.stringify(Object.keys(toolCtx)));\n\n if (model) {\n span.setAttribute(traceTypes.ATTR_GEN_AI_REQUEST_MODEL, model);\n }\n if (provider) {\n span.setAttribute(traceTypes.ATTR_GEN_AI_PROVIDER_NAME, provider);\n }\n\n let llmStreamReader: ReadableStreamDefaultReader<string | ChatChunk> | null = null;\n let llmStream: ReadableStream<string | ChatChunk> | null = null;\n const startTime = performance.now() / 1000; // Convert to seconds\n let firstTokenReceived = false;\n\n try {\n llmStream = await node(chatCtx, toolCtx, modelSettings);\n if (llmStream === null) {\n await textWriter.close();\n return;\n }\n\n const abortPromise = waitForAbort(signal);\n\n // TODO(brian): add support for dynamic tools\n\n llmStreamReader = llmStream.getReader();\n while (true) {\n if (signal.aborted) break;\n\n const result = await Promise.race([llmStreamReader.read(), abortPromise]);\n if (result === undefined) break;\n\n const { done, value: chunk } = result;\n if (done) break;\n\n if (!firstTokenReceived) {\n firstTokenReceived = true;\n data.ttft = performance.now() / 1000 - startTime;\n }\n\n if (typeof chunk === 'string') {\n data.generatedText += chunk;\n await textWriter.write(chunk);\n // TODO(shubhra): better way to check??\n } else {\n if (chunk.delta === undefined) {\n continue;\n }\n\n if (chunk.delta.toolCalls) {\n for (const tool of chunk.delta.toolCalls) {\n if (tool.type !== 'function_call') continue;\n\n const toolCall = FunctionCall.create({\n callId: `${data.id}/fnc_${data.generatedToolCalls.length}`,\n name: tool.name,\n args: tool.args,\n // Preserve thought signature for Gemini 3+ thinking mode\n thoughtSignature: tool.thoughtSignature,\n extra: tool.extra || {},\n });\n\n data.generatedToolCalls.push(toolCall);\n await toolCallWriter.write(toolCall);\n }\n }\n\n if (chunk.delta.content) {\n data.generatedText += chunk.delta.content;\n await textWriter.write(chunk.delta.content);\n }\n }\n\n // No need to check if chunk is of type other than ChatChunk or string like in\n // Python since chunk is defined in the type ChatChunk | string in TypeScript\n }\n\n span.setAttribute(traceTypes.ATTR_RESPONSE_TEXT, data.generatedText);\n if (data.ttft !== undefined) {\n span.setAttribute(traceTypes.ATTR_RESPONSE_TTFT, data.ttft);\n }\n } catch (error) {\n if (error instanceof DOMException && error.name === 'AbortError') {\n // Abort signal was triggered, handle gracefully\n return;\n }\n throw error;\n } finally {\n llmStreamReader?.releaseLock();\n await llmStream?.cancel();\n await textWriter.close();\n await toolCallWriter.close();\n }\n };\n\n // Capture the current context (agent_turn) to ensure llm_node is properly parented\n const currentContext = otelContext.active();\n\n const inferenceTask = async (signal: AbortSignal) =>\n tracer.startActiveSpan(async (span) => _performLLMInferenceImpl(signal, span), {\n name: 'llm_node',\n context: currentContext,\n });\n\n return [\n Task.from((controller) => inferenceTask(controller.signal), controller, 'performLLMInference'),\n data,\n ];\n}\n\nexport function performTTSInference(\n node: TTSNode,\n text: ReadableStream<string | TimedString>,\n modelSettings: ModelSettings,\n controller: AbortController,\n model?: string,\n provider?: string,\n): [Task<void>, _TTSGenerationData] {\n const audioStream = new IdentityTransform<AudioFrame>();\n const outputWriter = audioStream.writable.getWriter();\n const audioOutputStream = audioStream.readable;\n\n const timedTextsFut = new Future<ReadableStream<TimedString> | null>();\n const timedTextsStream = new IdentityTransform<TimedString>();\n const timedTextsWriter = timedTextsStream.writable.getWriter();\n\n // Transform stream to extract text from TimedString objects\n const textOnlyStream = new IdentityTransform<string>();\n const textOnlyWriter = textOnlyStream.writable.getWriter();\n (async () => {\n const reader = text.getReader();\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) {\n break;\n }\n const textValue = typeof value === 'string' ? value : value.text;\n await textOnlyWriter.write(textValue);\n }\n await textOnlyWriter.close();\n } catch (e) {\n await textOnlyWriter.abort(e as Error);\n } finally {\n reader.releaseLock();\n }\n })();\n\n let ttfb: number | undefined;\n\n const genData: _TTSGenerationData = {\n audioStream: audioOutputStream,\n timedTextsFut,\n ttfb: undefined,\n };\n\n const _performTTSInferenceImpl = async (signal: AbortSignal, span: Span) => {\n if (model) {\n span.setAttribute(traceTypes.ATTR_GEN_AI_REQUEST_MODEL, model);\n }\n if (provider) {\n span.setAttribute(traceTypes.ATTR_GEN_AI_PROVIDER_NAME, provider);\n }\n\n let ttsStreamReader: ReadableStreamDefaultReader<AudioFrame> | null = null;\n let ttsStream: ReadableStream<AudioFrame> | null = null;\n let pushedDuration = 0;\n const startTime = performance.now() / 1000; // Convert to seconds\n let firstByteReceived = false;\n\n try {\n ttsStream = await node(textOnlyStream.readable, modelSettings);\n if (ttsStream === null) {\n timedTextsFut.resolve(null);\n await outputWriter.close();\n await timedTextsWriter.close();\n return;\n }\n\n // This is critical: the future must be resolved with the channel/stream before the loop\n // so that agent_activity can start reading while we write\n if (!timedTextsFut.done) {\n timedTextsFut.resolve(timedTextsStream.readable);\n }\n\n ttsStreamReader = ttsStream.getReader();\n\n // In Python, perform_tts_inference has a while loop processing multiple input segments\n // (separated by FlushSentinel), with pushed_duration accumulating across segments.\n // JS currently only does single inference, so initialPushedDuration is always 0.\n // TODO: Add FlushSentinel + multi-segment loop\n const initialPushedDuration = pushedDuration;\n\n while (true) {\n if (signal.aborted) {\n break;\n }\n const { done, value: frame } = await ttsStreamReader.read();\n if (done) {\n break;\n }\n\n if (!firstByteReceived) {\n firstByteReceived = true;\n ttfb = performance.now() / 1000 - startTime;\n genData.ttfb = ttfb;\n span.setAttribute(traceTypes.ATTR_RESPONSE_TTFB, ttfb);\n }\n\n // Write the audio frame to the output stream\n await outputWriter.write(frame);\n\n const timedTranscripts = frame.userdata[USERDATA_TIMED_TRANSCRIPT] as\n | TimedString[]\n | undefined;\n if (timedTranscripts && timedTranscripts.length > 0) {\n for (const timedText of timedTranscripts) {\n // Uses the INITIAL value (from previous inferences), not the accumulated value\n const adjustedTimedText = createTimedString({\n text: timedText.text,\n startTime:\n timedText.startTime !== undefined\n ? timedText.startTime + initialPushedDuration\n : undefined,\n endTime:\n timedText.endTime !== undefined\n ? timedText.endTime + initialPushedDuration\n : undefined,\n confidence: timedText.confidence,\n startTimeOffset: timedText.startTimeOffset,\n });\n await timedTextsWriter.write(adjustedTimedText);\n }\n }\n\n const frameDuration = frame.samplesPerChannel / frame.sampleRate;\n pushedDuration += frameDuration;\n }\n } catch (error) {\n if (error instanceof DOMException && error.name === 'AbortError') {\n // Abort signal was triggered, handle gracefully\n return;\n }\n throw error;\n } finally {\n if (!timedTextsFut.done) {\n // Ensure downstream consumers don't hang on errors.\n timedTextsFut.resolve(null);\n }\n ttsStreamReader?.releaseLock();\n await ttsStream?.cancel();\n await outputWriter.close();\n await timedTextsWriter.close();\n }\n };\n\n // Capture the current context (agent_turn) to ensure tts_node is properly parented\n const currentContext = otelContext.active();\n\n const inferenceTask = async (signal: AbortSignal) =>\n tracer.startActiveSpan(async (span) => _performTTSInferenceImpl(signal, span), {\n name: 'tts_node',\n context: currentContext,\n });\n\n return [\n Task.from((controller) => inferenceTask(controller.signal), controller, 'performTTSInference'),\n genData,\n ];\n}\n\nexport interface _TextOut {\n text: string;\n firstTextFut: Future;\n}\n\nasync function forwardText(\n source: ReadableStream<string | TimedString>,\n out: _TextOut,\n signal: AbortSignal,\n textOutput: TextOutput | null,\n): Promise<void> {\n const reader = source.getReader();\n try {\n while (true) {\n if (signal.aborted) {\n break;\n }\n const { done, value: delta } = await reader.read();\n if (done) break;\n\n const deltaIsTimedString = isTimedString(delta);\n const textDelta = deltaIsTimedString ? delta.text : delta;\n\n out.text += textDelta;\n if (textOutput !== null) {\n // Pass TimedString to textOutput for synchronized transcription\n await textOutput.captureText(delta);\n }\n if (!out.firstTextFut.done) {\n out.firstTextFut.resolve();\n }\n }\n } finally {\n if (textOutput !== null) {\n textOutput.flush();\n }\n reader?.releaseLock();\n }\n}\n\nexport function performTextForwarding(\n source: ReadableStream<string | TimedString>,\n controller: AbortController,\n textOutput: TextOutput | null,\n): [Task<void>, _TextOut] {\n const out = {\n text: '',\n firstTextFut: new Future(),\n };\n return [\n Task.from(\n (controller) => forwardText(source, out, controller.signal, textOutput),\n controller,\n 'performTextForwarding',\n ),\n out,\n ];\n}\n\nexport interface _AudioOut {\n audio: Array<AudioFrame>;\n firstFrameFut: Future<number>;\n}\n\nasync function forwardAudio(\n ttsStream: ReadableStream<AudioFrame>,\n audioOutput: AudioOutput,\n out: _AudioOut,\n signal?: AbortSignal,\n): Promise<void> {\n const reader = ttsStream.getReader();\n let resampler: AudioResampler | null = null;\n\n const onPlaybackStarted = (ev: { createdAt: number }) => {\n if (!out.firstFrameFut.done) {\n out.firstFrameFut.resolve(ev.createdAt);\n }\n };\n\n try {\n audioOutput.on(AudioOutput.EVENT_PLAYBACK_STARTED, onPlaybackStarted);\n audioOutput.resume();\n\n while (true) {\n if (signal?.aborted) {\n break;\n }\n\n const { done, value: frame } = await reader.read();\n if (done) break;\n\n out.audio.push(frame);\n\n if (\n !out.firstFrameFut.done &&\n audioOutput.sampleRate &&\n audioOutput.sampleRate !== frame.sampleRate &&\n !resampler\n ) {\n resampler = new AudioResampler(frame.sampleRate, audioOutput.sampleRate, 1);\n }\n\n if (resampler) {\n for (const f of resampler.push(frame)) {\n await audioOutput.captureFrame(f);\n }\n } else {\n await audioOutput.captureFrame(frame);\n }\n }\n\n if (resampler) {\n for (const f of resampler.flush()) {\n await audioOutput.captureFrame(f);\n }\n }\n } finally {\n audioOutput.off(AudioOutput.EVENT_PLAYBACK_STARTED, onPlaybackStarted);\n\n if (!out.firstFrameFut.done) {\n out.firstFrameFut.reject(new Error('audio forwarding cancelled before playback started'));\n }\n\n reader?.releaseLock();\n audioOutput.flush();\n }\n}\n\nexport function performAudioForwarding(\n ttsStream: ReadableStream<AudioFrame>,\n audioOutput: AudioOutput,\n controller: AbortController,\n): [Task<void>, _AudioOut] {\n const out: _AudioOut = {\n audio: [],\n firstFrameFut: new Future<number>(),\n };\n\n return [\n Task.from(\n (controller) => forwardAudio(ttsStream, audioOutput, out, controller.signal),\n controller,\n 'performAudioForwarding',\n ),\n out,\n ];\n}\n\nexport function performToolExecutions({\n session,\n speechHandle,\n toolCtx,\n toolChoice,\n toolCallStream,\n onToolExecutionStarted = () => {},\n onToolExecutionCompleted = () => {},\n controller,\n}: {\n session: AgentSession;\n speechHandle: SpeechHandle;\n toolCtx: ToolContext;\n toolChoice?: ToolChoice;\n toolCallStream: ReadableStream<FunctionCall>;\n onToolExecutionStarted?: (toolCall: FunctionCall) => void;\n onToolExecutionCompleted?: (toolExecutionOutput: ToolExecutionOutput) => void;\n controller: AbortController;\n}): [Task<void>, ToolOutput] {\n const logger = log();\n const toolOutput: ToolOutput = {\n output: [],\n firstToolStartedFuture: new Future(),\n };\n\n const toolCompleted = (out: ToolExecutionOutput) => {\n onToolExecutionCompleted(out);\n toolOutput.output.push(out);\n };\n\n const executeToolsTask = async (controller: AbortController) => {\n const signal = controller.signal;\n const reader = toolCallStream.getReader();\n\n const tasks: Task<void>[] = [];\n while (!signal.aborted) {\n const { done, value: toolCall } = await reader.read();\n if (signal.aborted) break;\n if (done) break;\n\n if (toolChoice === 'none') {\n logger.error(\n {\n function: toolCall.name,\n speech_id: speechHandle.id,\n },\n \"received a tool call with toolChoice set to 'none', ignoring\",\n );\n continue;\n }\n\n // TODO(brian): assert other toolChoice values\n\n const tool = toolCtx[toolCall.name];\n if (!tool) {\n logger.warn(\n {\n function: toolCall.name,\n speech_id: speechHandle.id,\n },\n `unknown AI function ${toolCall.name}`,\n );\n continue;\n }\n\n if (!isFunctionTool(tool)) {\n logger.error(\n {\n function: toolCall.name,\n speech_id: speechHandle.id,\n },\n `unknown tool type: ${typeof tool}`,\n );\n continue;\n }\n\n let parsedArgs: object | undefined;\n\n // Ensure valid arguments\n try {\n const jsonArgs = JSON.parse(toolCall.args);\n\n if (isZodSchema(tool.parameters)) {\n const result = await parseZodSchema<object>(tool.parameters, jsonArgs);\n if (result.success) {\n parsedArgs = result.data;\n } else {\n throw result.error;\n }\n } else {\n parsedArgs = jsonArgs;\n }\n } catch (rawError) {\n const error = toError(rawError);\n logger.error(\n {\n function: toolCall.name,\n arguments: toolCall.args,\n speech_id: speechHandle.id,\n error: error.message,\n },\n `tried to call AI function ${toolCall.name} with invalid arguments`,\n );\n toolCompleted(\n createToolOutput({\n toolCall,\n exception: error,\n }),\n );\n continue;\n }\n\n if (!toolOutput.firstToolStartedFuture.done) {\n toolOutput.firstToolStartedFuture.resolve();\n }\n\n onToolExecutionStarted(toolCall);\n\n logger.info(\n {\n function: toolCall.name,\n arguments: parsedArgs,\n speech_id: speechHandle.id,\n },\n 'Executing LLM tool call',\n );\n\n const _tracableToolExecutionImpl = async (toolExecTask: Promise<unknown>, span: Span) => {\n span.setAttribute(traceTypes.ATTR_FUNCTION_TOOL_NAME, toolCall.name);\n span.setAttribute(traceTypes.ATTR_FUNCTION_TOOL_ARGS, toolCall.args);\n\n // await for task to complete, if task is aborted, set exception\n let toolOutput: ToolExecutionOutput | undefined;\n try {\n const { result, isAborted } = await waitUntilAborted(toolExecTask, signal);\n toolOutput = createToolOutput({\n toolCall,\n exception: isAborted ? new Error('tool call was aborted') : undefined,\n output: isAborted ? undefined : result,\n });\n\n if (toolOutput.toolCallOutput) {\n span.setAttribute(\n traceTypes.ATTR_FUNCTION_TOOL_OUTPUT,\n toolOutput.toolCallOutput.output,\n );\n span.setAttribute(\n traceTypes.ATTR_FUNCTION_TOOL_IS_ERROR,\n toolOutput.toolCallOutput.isError,\n );\n }\n } catch (rawError) {\n logger.error(\n {\n function: toolCall.name,\n speech_id: speechHandle.id,\n error: toError(rawError).message,\n },\n 'exception occurred while executing tool',\n );\n toolOutput = createToolOutput({\n toolCall,\n exception: toError(rawError),\n });\n\n if (toolOutput.toolCallOutput) {\n span.setAttribute(\n traceTypes.ATTR_FUNCTION_TOOL_OUTPUT,\n toolOutput.toolCallOutput.output,\n );\n span.setAttribute(traceTypes.ATTR_FUNCTION_TOOL_IS_ERROR, true);\n }\n } finally {\n if (!toolOutput) throw new Error('toolOutput is undefined');\n toolCompleted(toolOutput);\n }\n };\n\n const tracableToolExecution = (toolExecTask: Promise<unknown>) =>\n tracer.startActiveSpan(async (span) => _tracableToolExecutionImpl(toolExecTask, span), {\n name: 'function_tool',\n });\n\n const toolTask = Task.from(\n async () => {\n // Ensure this task is marked inline before user tool code executes.\n const currentTask = Task.current();\n if (currentTask) {\n _setActivityTaskInfo(currentTask, {\n speechHandle,\n functionCall: toolCall,\n inlineTask: true,\n });\n }\n\n const toolExecution = functionCallStorage.run({ functionCall: toolCall }, async () => {\n return await tool.execute(parsedArgs, {\n ctx: new RunContext(session, speechHandle, toolCall),\n toolCallId: toolCall.callId,\n abortSignal: signal,\n });\n });\n\n await tracableToolExecution(toolExecution);\n },\n controller,\n `performToolExecution:${toolCall.name}`,\n );\n\n _setActivityTaskInfo(toolTask, {\n speechHandle,\n functionCall: toolCall,\n inlineTask: true,\n });\n // wait, not cancelling all tool calling tasks\n tasks.push(toolTask);\n }\n\n await Promise.allSettled(tasks.map((task) => task.result));\n if (toolOutput.output.length > 0) {\n logger.debug(\n {\n speech_id: speechHandle.id,\n },\n 'tools execution completed',\n );\n }\n };\n\n return [Task.from(executeToolsTask, controller, 'performToolExecutions'), toolOutput];\n}\n\ntype Aborted<T> =\n | {\n result: T;\n isAborted: false;\n }\n | {\n result: undefined;\n isAborted: true;\n };\n\nasync function waitUntilAborted<T>(promise: Promise<T>, signal: AbortSignal): Promise<Aborted<T>> {\n const abortFut = new Future<Aborted<T>>();\n\n const resolveAbort = () => {\n if (!abortFut.done) {\n abortFut.resolve({ result: undefined, isAborted: true });\n }\n };\n\n signal.addEventListener('abort', resolveAbort);\n\n promise\n .then((r) => {\n if (!abortFut.done) {\n abortFut.resolve({ result: r, isAborted: false });\n }\n })\n .catch((e) => {\n if (!abortFut.done) {\n abortFut.reject(e);\n }\n })\n .finally(() => {\n signal.removeEventListener('abort', resolveAbort);\n });\n\n return await abortFut.await;\n}\n\nexport function removeInstructions(chatCtx: ChatContext) {\n // loop in case there are items with the same id (shouldn't happen!)\n while (true) {\n const idx = chatCtx.indexById(INSTRUCTIONS_MESSAGE_ID);\n if (idx !== undefined) {\n chatCtx.items.splice(idx, 1);\n } else {\n break;\n }\n }\n}\n"],"mappings":"AAIA,SAAS,sBAAsB;AAE/B,SAAS,WAAW,mBAAmB;AAEvC;AAAA,EAEE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP;AAAA,EAGE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,aAAa,sBAAsB;AAC5C,SAAS,WAAW;AACpB,SAAS,yBAAyB;AAClC,SAAS,YAAY,cAAc;AACnC,SAAS,iCAAiC;AAC1C,SAAS,QAAQ,MAAM,WAAW,SAAS,oBAAoB;AAC/D;AAAA,EAGE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP;AAAA,EACE;AAAA,EAKA;AAAA,EACA;AAAA,OACK;AACP,SAAS,kBAAkB;AAIpB,MAAM,mBAAmB;AAAA,EAM9B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