@voctiv/agent-runtime 0.2.1 → 0.4.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 (628) hide show
  1. package/README.md +45 -20
  2. package/dist/barge-in/barge-in-module.d.ts +0 -1
  3. package/dist/barge-in/barge-in-module.js +0 -1
  4. package/dist/barge-in/barge-in-service.d.ts +1 -1
  5. package/dist/barge-in/barge-in-service.js +33 -2
  6. package/dist/barge-in/barge-in-strategy.d.ts +11 -9
  7. package/dist/barge-in/barge-in-strategy.js +39 -23
  8. package/dist/barge-in/echo-cancellation.d.ts +0 -1
  9. package/dist/barge-in/echo-cancellation.js +0 -1
  10. package/dist/barge-in/echo.d.ts +0 -1
  11. package/dist/barge-in/echo.js +0 -1
  12. package/dist/barge-in/lexicon.d.ts +0 -1
  13. package/dist/barge-in/lexicon.js +8 -2
  14. package/dist/barge-in/speech-ledger.d.ts +0 -2
  15. package/dist/barge-in/speech-ledger.js +3 -4
  16. package/dist/barge-in/word-classifier.d.ts +0 -1
  17. package/dist/barge-in/word-classifier.js +0 -1
  18. package/dist/call/asr-usage.d.ts +53 -0
  19. package/dist/call/asr-usage.js +42 -0
  20. package/dist/call/async.d.ts +2 -0
  21. package/dist/call/async.js +14 -0
  22. package/dist/call/env.d.ts +88 -0
  23. package/dist/call/env.js +294 -0
  24. package/dist/call/extraction/core.d.ts +99 -0
  25. package/dist/call/extraction/core.js +259 -0
  26. package/dist/call/extraction/defaults.d.ts +10 -0
  27. package/dist/call/extraction/defaults.js +25 -0
  28. package/dist/call/extraction/index.d.ts +7 -0
  29. package/dist/call/extraction/index.js +24 -0
  30. package/dist/call/extraction/orchestrator.d.ts +144 -0
  31. package/dist/call/extraction/orchestrator.js +309 -0
  32. package/dist/call/failed-leg.d.ts +43 -0
  33. package/dist/call/failed-leg.js +77 -0
  34. package/dist/call/http.d.ts +94 -0
  35. package/dist/call/http.js +145 -0
  36. package/dist/call/ledger.d.ts +18 -0
  37. package/dist/call/ledger.js +80 -0
  38. package/dist/call/llm-tap.d.ts +7 -0
  39. package/dist/call/llm-tap.js +41 -0
  40. package/dist/call/logging.d.ts +16 -0
  41. package/dist/call/logging.js +92 -0
  42. package/dist/call/outbound.d.ts +144 -0
  43. package/dist/call/outbound.js +404 -0
  44. package/dist/call/output.d.ts +108 -0
  45. package/dist/call/output.js +77 -0
  46. package/dist/call/plan.d.ts +119 -0
  47. package/dist/call/plan.js +2 -0
  48. package/dist/call/recall.d.ts +115 -0
  49. package/dist/call/recall.js +312 -0
  50. package/dist/call/records.d.ts +9 -0
  51. package/dist/call/records.js +71 -0
  52. package/dist/call/report.d.ts +65 -0
  53. package/dist/call/report.js +263 -0
  54. package/dist/call/sanitize.d.ts +16 -0
  55. package/dist/call/sanitize.js +72 -0
  56. package/dist/call/sip.d.ts +111 -0
  57. package/dist/call/sip.js +212 -0
  58. package/dist/call/voicemail.d.ts +159 -0
  59. package/dist/call/voicemail.js +246 -0
  60. package/dist/core/call-disposables.d.ts +2 -2
  61. package/dist/core/call-disposables.js +8 -3
  62. package/dist/core/call-ended-budget.d.ts +11 -0
  63. package/dist/core/call-ended-budget.js +31 -0
  64. package/dist/core/container.d.ts +1 -3
  65. package/dist/core/container.js +9 -49
  66. package/dist/core/create-agent-script.d.ts +6 -1
  67. package/dist/core/create-agent-script.js +161 -28
  68. package/dist/core/decorators.d.ts +0 -1
  69. package/dist/core/decorators.js +0 -1
  70. package/dist/core/define-module.d.ts +0 -1
  71. package/dist/core/define-module.js +0 -1
  72. package/dist/core/dump-policy.d.ts +0 -1
  73. package/dist/core/dump-policy.js +0 -1
  74. package/dist/core/hooks.d.ts +15 -4
  75. package/dist/core/hooks.js +0 -1
  76. package/dist/core/media-bootstrap.d.ts +19 -4
  77. package/dist/core/media-bootstrap.js +53 -13
  78. package/dist/core/open-timeout.d.ts +12 -0
  79. package/dist/core/open-timeout.js +48 -0
  80. package/dist/core/provide-media.d.ts +0 -8
  81. package/dist/core/provide-media.js +1 -22
  82. package/dist/core/runtime-events.d.ts +28 -0
  83. package/dist/{llm/llm-module.js → core/runtime-events.js} +19 -16
  84. package/dist/core/tokens.d.ts +0 -10
  85. package/dist/core/tokens.js +0 -1
  86. package/dist/core/types.d.ts +0 -1
  87. package/dist/core/types.js +0 -1
  88. package/dist/core/version.d.ts +2 -3
  89. package/dist/core/version.js +2 -3
  90. package/dist/dialog/dialog-definition.d.ts +0 -5
  91. package/dist/dialog/dialog-definition.js +1 -6
  92. package/dist/dialog/dialog-ports.d.ts +3 -1
  93. package/dist/dialog/dialog-ports.js +10 -2
  94. package/dist/dialog/online-call-host.d.ts +26 -4
  95. package/dist/dialog/online-call-host.js +94 -12
  96. package/dist/dialog/online-call-module.d.ts +5 -11
  97. package/dist/dialog/online-call-module.js +4 -36
  98. package/dist/dialog/turn-metrics.d.ts +46 -0
  99. package/dist/dialog/turn-metrics.js +141 -0
  100. package/dist/dialog-events/active-media.d.ts +50 -2
  101. package/dist/dialog-events/active-media.js +146 -34
  102. package/dist/dialog-events/event-source.d.ts +0 -1
  103. package/dist/dialog-events/event-source.js +0 -1
  104. package/dist/dialog-events/virtual-finals-module.d.ts +0 -1
  105. package/dist/dialog-events/virtual-finals-module.js +0 -1
  106. package/dist/dialog-events/virtual-finals.d.ts +2 -1
  107. package/dist/dialog-events/virtual-finals.js +1 -1
  108. package/dist/index.d.ts +1 -4
  109. package/dist/index.js +8 -26
  110. package/dist/lifecycle/lifecycle.d.ts +25 -3
  111. package/dist/lifecycle/lifecycle.js +92 -14
  112. package/dist/result/result-store.d.ts +0 -1
  113. package/dist/result/result-store.js +0 -1
  114. package/dist/templates/authoring.d.ts +222 -0
  115. package/dist/templates/authoring.js +2 -0
  116. package/dist/templates/builder/agent.d.ts +34 -0
  117. package/dist/templates/builder/agent.js +87 -0
  118. package/dist/templates/builder/blocks.d.ts +54 -0
  119. package/dist/templates/builder/blocks.js +92 -0
  120. package/dist/templates/builder/data-check.d.ts +2 -0
  121. package/dist/templates/builder/data-check.js +61 -0
  122. package/dist/templates/builder/draft.d.ts +73 -0
  123. package/dist/templates/builder/draft.js +142 -0
  124. package/dist/templates/builder/index.d.ts +8 -0
  125. package/dist/templates/builder/index.js +55 -0
  126. package/dist/templates/builder/presets.d.ts +34 -0
  127. package/dist/templates/builder/presets.js +45 -0
  128. package/dist/templates/builder/spec-of.d.ts +13 -0
  129. package/dist/templates/builder/spec-of.js +18 -0
  130. package/dist/templates/builder/steps.d.ts +25 -0
  131. package/dist/templates/builder/steps.js +27 -0
  132. package/dist/templates/business/adapter.d.ts +12 -0
  133. package/dist/templates/business/adapter.js +980 -0
  134. package/dist/templates/business/agent-integrations.d.ts +24 -0
  135. package/dist/templates/business/agent-integrations.js +233 -0
  136. package/dist/templates/business/extraction-rules-transcript.d.ts +158 -0
  137. package/dist/templates/business/extraction-rules-transcript.js +405 -0
  138. package/dist/templates/business/extraction-rules.d.ts +107 -0
  139. package/dist/templates/business/extraction-rules.js +267 -0
  140. package/dist/templates/business/index.d.ts +6 -0
  141. package/dist/{result → templates/business}/index.js +8 -2
  142. package/dist/templates/business/input.d.ts +56 -0
  143. package/dist/templates/business/input.js +299 -0
  144. package/dist/templates/business/integration-data.d.ts +87 -0
  145. package/dist/templates/business/integration-data.js +312 -0
  146. package/dist/templates/business/integrations.d.ts +76 -0
  147. package/dist/templates/business/integrations.js +535 -0
  148. package/dist/templates/business/legs-policy.d.ts +43 -0
  149. package/dist/templates/business/legs-policy.js +268 -0
  150. package/dist/templates/business/report-label.d.ts +7 -0
  151. package/dist/templates/business/report-label.js +29 -0
  152. package/dist/templates/business/report.d.ts +67 -0
  153. package/dist/templates/business/report.js +284 -0
  154. package/dist/templates/business/result-catalog.d.ts +142 -0
  155. package/dist/templates/business/result-catalog.js +208 -0
  156. package/dist/templates/business/result-rules.d.ts +105 -0
  157. package/dist/templates/business/result-rules.js +167 -0
  158. package/dist/templates/business/results.d.ts +73 -0
  159. package/dist/templates/business/results.js +183 -0
  160. package/dist/templates/business/rule-env.d.ts +18 -0
  161. package/dist/templates/business/rule-env.js +38 -0
  162. package/dist/templates/business/sources.d.ts +76 -0
  163. package/dist/templates/business/sources.js +239 -0
  164. package/dist/templates/business/test-presets.d.ts +10 -0
  165. package/dist/templates/business/test-presets.js +68 -0
  166. package/dist/templates/catalog-match/block.d.ts +32 -0
  167. package/dist/templates/catalog-match/block.js +95 -0
  168. package/dist/templates/catalog-match/catalog.d.ts +77 -0
  169. package/dist/templates/catalog-match/catalog.js +222 -0
  170. package/dist/templates/catalog-match/recognizer.d.ts +44 -0
  171. package/dist/templates/catalog-match/recognizer.js +206 -0
  172. package/dist/templates/catalog-match/reconcile.d.ts +4 -0
  173. package/dist/templates/catalog-match/reconcile.js +39 -0
  174. package/dist/templates/catalog-match/request.d.ts +57 -0
  175. package/dist/templates/catalog-match/request.js +139 -0
  176. package/dist/templates/catalog-match/types.d.ts +197 -0
  177. package/dist/templates/catalog-match/types.js +2 -0
  178. package/dist/templates/catalog-match/verify.d.ts +76 -0
  179. package/dist/templates/catalog-match/verify.js +220 -0
  180. package/dist/templates/decision-model/index.d.ts +52 -0
  181. package/dist/templates/decision-model/index.js +68 -0
  182. package/dist/templates/engine/asr-picks.d.ts +11 -0
  183. package/dist/templates/engine/asr-picks.js +44 -0
  184. package/dist/templates/engine/call.d.ts +104 -0
  185. package/dist/templates/engine/call.js +322 -0
  186. package/dist/templates/engine/config.d.ts +447 -0
  187. package/dist/templates/engine/config.js +493 -0
  188. package/dist/templates/engine/define.d.ts +1 -0
  189. package/dist/templates/engine/define.js +9 -0
  190. package/dist/templates/engine/dialog.d.ts +253 -0
  191. package/dist/templates/engine/dialog.js +167 -0
  192. package/dist/templates/engine/echo-numbers.d.ts +7 -0
  193. package/dist/templates/engine/echo-numbers.js +19 -0
  194. package/dist/templates/engine/expand.d.ts +6 -0
  195. package/dist/templates/engine/expand.js +125 -0
  196. package/dist/templates/engine/filters.d.ts +81 -0
  197. package/dist/templates/engine/filters.js +654 -0
  198. package/dist/templates/engine/hook-state.d.ts +18 -0
  199. package/dist/templates/engine/hook-state.js +100 -0
  200. package/dist/templates/engine/hooks.d.ts +51 -0
  201. package/dist/templates/engine/hooks.js +310 -0
  202. package/dist/templates/engine/index.d.ts +13 -0
  203. package/dist/templates/engine/index.js +30 -0
  204. package/dist/templates/engine/language-vars.d.ts +6 -0
  205. package/dist/templates/engine/language-vars.js +40 -0
  206. package/dist/templates/engine/language.d.ts +32 -0
  207. package/dist/templates/engine/language.js +155 -0
  208. package/dist/templates/engine/lookup.d.ts +20 -0
  209. package/dist/templates/engine/lookup.js +52 -0
  210. package/dist/templates/engine/match.d.ts +48 -0
  211. package/dist/templates/engine/match.js +253 -0
  212. package/dist/templates/engine/media.d.ts +428 -0
  213. package/dist/templates/engine/media.js +1240 -0
  214. package/dist/templates/engine/script.d.ts +11 -0
  215. package/dist/templates/engine/script.js +69 -0
  216. package/dist/templates/engine/turns/actions.d.ts +5 -0
  217. package/dist/templates/engine/turns/actions.js +128 -0
  218. package/dist/templates/engine/turns/carry.d.ts +15 -0
  219. package/dist/templates/engine/turns/carry.js +74 -0
  220. package/dist/templates/engine/turns/choices-offers.d.ts +21 -0
  221. package/dist/templates/engine/turns/choices-offers.js +143 -0
  222. package/dist/templates/engine/turns/choices.d.ts +22 -0
  223. package/dist/templates/engine/turns/choices.js +141 -0
  224. package/dist/templates/engine/turns/closing-guard.d.ts +73 -0
  225. package/dist/templates/engine/turns/closing-guard.js +162 -0
  226. package/dist/templates/engine/turns/closing.d.ts +10 -0
  227. package/dist/templates/engine/turns/closing.js +82 -0
  228. package/dist/templates/engine/turns/compile-forms.d.ts +24 -0
  229. package/dist/templates/engine/turns/compile-forms.js +68 -0
  230. package/dist/templates/engine/turns/context.d.ts +96 -0
  231. package/dist/templates/engine/turns/context.js +158 -0
  232. package/dist/templates/engine/turns/events.d.ts +409 -0
  233. package/dist/templates/engine/turns/events.js +5 -0
  234. package/dist/templates/engine/turns/hook-forms.d.ts +62 -0
  235. package/dist/templates/engine/turns/hook-forms.js +79 -0
  236. package/dist/templates/engine/turns/ladders.d.ts +42 -0
  237. package/dist/templates/engine/turns/ladders.js +119 -0
  238. package/dist/templates/engine/turns/language.d.ts +8 -0
  239. package/dist/templates/engine/turns/language.js +121 -0
  240. package/dist/templates/engine/turns/notes-dates.d.ts +9 -0
  241. package/dist/templates/engine/turns/notes-dates.js +42 -0
  242. package/dist/templates/engine/turns/notes-detect.d.ts +13 -0
  243. package/dist/templates/engine/turns/notes-detect.js +36 -0
  244. package/dist/templates/engine/turns/notes.d.ts +27 -0
  245. package/dist/templates/engine/turns/notes.js +176 -0
  246. package/dist/templates/engine/turns/opening.d.ts +34 -0
  247. package/dist/templates/engine/turns/opening.js +306 -0
  248. package/dist/templates/engine/turns/overtalk.d.ts +21 -0
  249. package/dist/templates/engine/turns/overtalk.js +247 -0
  250. package/dist/templates/engine/turns/pending.d.ts +9 -0
  251. package/dist/templates/engine/turns/pending.js +88 -0
  252. package/dist/templates/engine/turns/reply-rules.d.ts +184 -0
  253. package/dist/templates/engine/turns/reply-rules.js +335 -0
  254. package/dist/templates/engine/turns/rules.d.ts +20 -0
  255. package/dist/templates/engine/turns/rules.js +144 -0
  256. package/dist/templates/engine/turns/silence.d.ts +7 -0
  257. package/dist/templates/engine/turns/silence.js +127 -0
  258. package/dist/templates/engine/turns/state-spec.d.ts +305 -0
  259. package/dist/templates/engine/turns/state-spec.js +2 -0
  260. package/dist/templates/engine/turns/state.d.ts +38 -0
  261. package/dist/templates/engine/turns/state.js +101 -0
  262. package/dist/templates/engine/turns/tracking.d.ts +50 -0
  263. package/dist/templates/engine/turns/tracking.js +184 -0
  264. package/dist/templates/engine/turns/transfer.d.ts +19 -0
  265. package/dist/templates/engine/turns/transfer.js +93 -0
  266. package/dist/templates/engine/turns/turn.d.ts +17 -0
  267. package/dist/templates/engine/turns/turn.js +363 -0
  268. package/dist/templates/engine/turns/voicemail.d.ts +8 -0
  269. package/dist/templates/engine/turns/voicemail.js +101 -0
  270. package/dist/templates/engine/variants.d.ts +36 -0
  271. package/dist/templates/engine/variants.js +159 -0
  272. package/dist/templates/engine/voice-dialog.d.ts +24 -0
  273. package/dist/templates/engine/voice-dialog.js +157 -0
  274. package/dist/templates/engine/voice.d.ts +174 -0
  275. package/dist/templates/engine/voice.js +1337 -0
  276. package/dist/templates/expr/caller-after.d.ts +20 -0
  277. package/dist/templates/expr/caller-after.js +53 -0
  278. package/dist/templates/expr/check.d.ts +19 -0
  279. package/dist/templates/expr/check.js +314 -0
  280. package/dist/templates/expr/compiled.d.ts +8 -0
  281. package/dist/templates/expr/compiled.js +8 -0
  282. package/dist/templates/expr/context.d.ts +28 -0
  283. package/dist/templates/expr/context.js +55 -0
  284. package/dist/templates/expr/day-table.d.ts +4 -0
  285. package/dist/templates/expr/day-table.js +80 -0
  286. package/dist/templates/expr/evaluate.d.ts +26 -0
  287. package/dist/templates/expr/evaluate.js +885 -0
  288. package/dist/templates/expr/facts.d.ts +7 -0
  289. package/dist/templates/expr/facts.js +81 -0
  290. package/dist/templates/expr/index.d.ts +4 -0
  291. package/dist/templates/expr/index.js +11 -0
  292. package/dist/templates/expr/line-tally.d.ts +64 -0
  293. package/dist/templates/expr/line-tally.js +88 -0
  294. package/dist/templates/expr/matchers-state.d.ts +23 -0
  295. package/dist/templates/expr/matchers-state.js +37 -0
  296. package/dist/templates/expr/matchers.d.ts +12 -0
  297. package/dist/templates/expr/matchers.js +99 -0
  298. package/dist/templates/expr/readers.d.ts +14 -0
  299. package/dist/templates/expr/readers.js +351 -0
  300. package/dist/templates/expr/slots.d.ts +14 -0
  301. package/dist/templates/expr/slots.js +678 -0
  302. package/dist/templates/expr/template.d.ts +12 -0
  303. package/dist/templates/expr/template.js +76 -0
  304. package/dist/templates/expr/test-call.d.ts +8 -0
  305. package/dist/templates/expr/test-call.js +32 -0
  306. package/dist/templates/expr/transcript.d.ts +36 -0
  307. package/dist/templates/expr/transcript.js +394 -0
  308. package/dist/templates/expr/types.d.ts +1011 -0
  309. package/dist/templates/expr/types.js +2 -0
  310. package/dist/templates/expr/values.d.ts +42 -0
  311. package/dist/templates/expr/values.js +166 -0
  312. package/dist/templates/expr/voice-ops.d.ts +26 -0
  313. package/dist/templates/expr/voice-ops.js +85 -0
  314. package/dist/templates/helpers/decision.d.ts +55 -0
  315. package/dist/templates/helpers/decision.js +83 -0
  316. package/dist/templates/helpers/fuzzy.d.ts +9 -0
  317. package/dist/templates/helpers/fuzzy.js +44 -0
  318. package/dist/templates/helpers/index.d.ts +6 -0
  319. package/dist/templates/helpers/index.js +35 -0
  320. package/dist/templates/index.d.ts +9 -0
  321. package/dist/templates/index.js +68 -0
  322. package/dist/templates/integration-forms.d.ts +252 -0
  323. package/dist/templates/integration-forms.js +2 -0
  324. package/dist/templates/knowledge/block.d.ts +44 -0
  325. package/dist/templates/knowledge/block.js +199 -0
  326. package/dist/templates/knowledge/dense.d.ts +87 -0
  327. package/dist/templates/knowledge/dense.js +158 -0
  328. package/dist/templates/knowledge/flow.d.ts +328 -0
  329. package/dist/templates/knowledge/flow.js +509 -0
  330. package/dist/templates/knowledge/retriever.d.ts +75 -0
  331. package/dist/templates/knowledge/retriever.js +204 -0
  332. package/dist/templates/knowledge/service.d.ts +77 -0
  333. package/dist/templates/knowledge/service.js +316 -0
  334. package/dist/templates/knowledge/text.d.ts +31 -0
  335. package/dist/templates/knowledge/text.js +66 -0
  336. package/dist/templates/knowledge/types.d.ts +120 -0
  337. package/dist/templates/knowledge/types.js +2 -0
  338. package/dist/templates/locale.d.ts +259 -0
  339. package/dist/templates/locale.js +4 -0
  340. package/dist/templates/locales/en-lexicons.d.ts +9 -0
  341. package/dist/templates/locales/en-lexicons.js +101 -0
  342. package/dist/templates/locales/en.d.ts +132 -0
  343. package/dist/templates/locales/en.js +261 -0
  344. package/dist/templates/locales/es.d.ts +65 -0
  345. package/dist/templates/locales/es.js +208 -0
  346. package/dist/templates/locales/hi.d.ts +47 -0
  347. package/dist/templates/locales/hi.js +235 -0
  348. package/dist/templates/locales/id.d.ts +43 -0
  349. package/dist/templates/locales/id.js +127 -0
  350. package/dist/templates/locales/index.d.ts +34 -0
  351. package/dist/templates/locales/index.js +112 -0
  352. package/dist/templates/locales/kk-lexicons.d.ts +22 -0
  353. package/dist/templates/locales/kk-lexicons.js +89 -0
  354. package/dist/templates/locales/kk.d.ts +140 -0
  355. package/dist/templates/locales/kk.js +306 -0
  356. package/dist/templates/locales/kn.d.ts +29 -0
  357. package/dist/templates/locales/kn.js +22 -0
  358. package/dist/templates/locales/listen-only.d.ts +15 -0
  359. package/dist/templates/locales/listen-only.js +27 -0
  360. package/dist/templates/locales/ms-lexicons.d.ts +13 -0
  361. package/dist/templates/locales/ms-lexicons.js +113 -0
  362. package/dist/templates/locales/ms.d.ts +76 -0
  363. package/dist/templates/locales/ms.js +179 -0
  364. package/dist/templates/locales/parse.d.ts +86 -0
  365. package/dist/templates/locales/parse.js +461 -0
  366. package/dist/templates/locales/ru-lexicons.d.ts +27 -0
  367. package/dist/templates/locales/ru-lexicons.js +127 -0
  368. package/dist/templates/locales/ru-stem.d.ts +2 -0
  369. package/dist/templates/locales/ru-stem.js +53 -0
  370. package/dist/templates/locales/ru.d.ts +143 -0
  371. package/dist/templates/locales/ru.js +387 -0
  372. package/dist/templates/locales/shared.d.ts +122 -0
  373. package/dist/templates/locales/shared.js +318 -0
  374. package/dist/templates/locales/ta.d.ts +29 -0
  375. package/dist/templates/locales/ta.js +22 -0
  376. package/dist/templates/locales/te.d.ts +29 -0
  377. package/dist/templates/locales/te.js +22 -0
  378. package/dist/templates/locales/tl-lexicons.d.ts +2 -0
  379. package/dist/templates/locales/tl-lexicons.js +230 -0
  380. package/dist/templates/locales/tl.d.ts +59 -0
  381. package/dist/templates/locales/tl.js +82 -0
  382. package/dist/templates/locales/vi.d.ts +59 -0
  383. package/dist/templates/locales/vi.js +160 -0
  384. package/dist/templates/locales/word-regex.d.ts +13 -0
  385. package/dist/templates/locales/word-regex.js +43 -0
  386. package/dist/templates/locales/words-kk.d.ts +2 -0
  387. package/dist/templates/locales/words-kk.js +23 -0
  388. package/dist/templates/locales/words-ru.d.ts +4 -0
  389. package/dist/templates/locales/words-ru.js +92 -0
  390. package/dist/templates/spec.d.ts +2856 -0
  391. package/dist/templates/spec.js +2 -0
  392. package/dist/testing/fake-channel.d.ts +0 -1
  393. package/dist/testing/fake-channel.js +0 -1
  394. package/dist/testing/index.d.ts +24 -1
  395. package/dist/testing/index.js +117 -2
  396. package/dist/voice/call-voice.d.ts +581 -0
  397. package/dist/voice/call-voice.js +1399 -0
  398. package/dist/voice/intent-interrupt.d.ts +32 -0
  399. package/dist/voice/intent-interrupt.js +91 -0
  400. package/dist/voice/self-echo.d.ts +28 -0
  401. package/dist/voice/self-echo.js +135 -0
  402. package/dist/voice/sentence-tag.d.ts +5 -0
  403. package/dist/voice/sentence-tag.js +42 -0
  404. package/dist/voice/speech-leak.d.ts +74 -0
  405. package/dist/voice/speech-leak.js +216 -0
  406. package/dist/voice/transfer.d.ts +90 -0
  407. package/dist/voice/transfer.js +331 -0
  408. package/dist/voice/turn-timing.d.ts +293 -0
  409. package/dist/voice/turn-timing.js +567 -0
  410. package/docs/README.md +3 -6
  411. package/docs/framework/README.md +6 -10
  412. package/docs/framework/architecture.md +2 -2
  413. package/docs/framework/container-and-di.md +1 -2
  414. package/docs/framework/invariants.md +6 -6
  415. package/docs/framework/package-layout.md +16 -23
  416. package/docs/framework/testing.md +8 -6
  417. package/package.json +10 -54
  418. package/skill/SKILL.md +213 -0
  419. package/skill/references/agent-file.md +230 -0
  420. package/skill/references/blocks.md +246 -0
  421. package/skill/references/builder.md +163 -0
  422. package/skill/references/business.md +659 -0
  423. package/skill/references/conversation.md +586 -0
  424. package/skill/references/core.md +89 -0
  425. package/skill/references/examples.md +73 -0
  426. package/skill/references/expressions.md +342 -0
  427. package/skill/references/format.md +114 -0
  428. package/skill/references/locales.md +149 -0
  429. package/skill/references/migration.md +133 -0
  430. package/skill/references/new-agent.md +81 -0
  431. package/skill/references/porting.md +109 -0
  432. package/templates/agent/README.md +50 -0
  433. package/templates/agent/package.json +24 -0
  434. package/templates/agent/src/agent.spec.ts +51 -0
  435. package/templates/agent/src/agent.ts +268 -0
  436. package/templates/agent/src/entities.ts +44 -0
  437. package/templates/agent/src/prompt.sqrl +21 -0
  438. package/templates/agent/src/variants/fixed-opening.ts +144 -0
  439. package/templates/agent/tsconfig.build.json +4 -0
  440. package/templates/agent/tsconfig.json +18 -0
  441. package/dist/asr/index.d.ts +0 -3
  442. package/dist/asr/index.d.ts.map +0 -1
  443. package/dist/asr/index.js +0 -6
  444. package/dist/asr/index.js.map +0 -1
  445. package/dist/barge-in/barge-in-module.d.ts.map +0 -1
  446. package/dist/barge-in/barge-in-module.js.map +0 -1
  447. package/dist/barge-in/barge-in-service.d.ts.map +0 -1
  448. package/dist/barge-in/barge-in-service.js.map +0 -1
  449. package/dist/barge-in/barge-in-strategy.d.ts.map +0 -1
  450. package/dist/barge-in/barge-in-strategy.js.map +0 -1
  451. package/dist/barge-in/echo-cancellation.d.ts.map +0 -1
  452. package/dist/barge-in/echo-cancellation.js.map +0 -1
  453. package/dist/barge-in/echo.d.ts.map +0 -1
  454. package/dist/barge-in/echo.js.map +0 -1
  455. package/dist/barge-in/index.d.ts +0 -13
  456. package/dist/barge-in/index.d.ts.map +0 -1
  457. package/dist/barge-in/index.js +0 -28
  458. package/dist/barge-in/index.js.map +0 -1
  459. package/dist/barge-in/lexicon.d.ts.map +0 -1
  460. package/dist/barge-in/lexicon.js.map +0 -1
  461. package/dist/barge-in/lexicons/en.d.ts +0 -2
  462. package/dist/barge-in/lexicons/en.d.ts.map +0 -1
  463. package/dist/barge-in/lexicons/en.js +0 -36
  464. package/dist/barge-in/lexicons/en.js.map +0 -1
  465. package/dist/barge-in/lexicons/id.d.ts +0 -2
  466. package/dist/barge-in/lexicons/id.d.ts.map +0 -1
  467. package/dist/barge-in/lexicons/id.js +0 -39
  468. package/dist/barge-in/lexicons/id.js.map +0 -1
  469. package/dist/barge-in/lexicons/index.d.ts +0 -10
  470. package/dist/barge-in/lexicons/index.d.ts.map +0 -1
  471. package/dist/barge-in/lexicons/index.js +0 -11
  472. package/dist/barge-in/lexicons/index.js.map +0 -1
  473. package/dist/barge-in/lexicons/ru.d.ts +0 -2
  474. package/dist/barge-in/lexicons/ru.d.ts.map +0 -1
  475. package/dist/barge-in/lexicons/ru.js +0 -39
  476. package/dist/barge-in/lexicons/ru.js.map +0 -1
  477. package/dist/barge-in/speech-ledger.d.ts.map +0 -1
  478. package/dist/barge-in/speech-ledger.js.map +0 -1
  479. package/dist/barge-in/word-classifier.d.ts.map +0 -1
  480. package/dist/barge-in/word-classifier.js.map +0 -1
  481. package/dist/bridge/bridge.d.ts +0 -28
  482. package/dist/bridge/bridge.d.ts.map +0 -1
  483. package/dist/bridge/bridge.js +0 -117
  484. package/dist/bridge/bridge.js.map +0 -1
  485. package/dist/bridge/index.d.ts +0 -3
  486. package/dist/bridge/index.d.ts.map +0 -1
  487. package/dist/bridge/index.js +0 -8
  488. package/dist/bridge/index.js.map +0 -1
  489. package/dist/core/call-disposables.d.ts.map +0 -1
  490. package/dist/core/call-disposables.js.map +0 -1
  491. package/dist/core/container.d.ts.map +0 -1
  492. package/dist/core/container.js.map +0 -1
  493. package/dist/core/create-agent-script.d.ts.map +0 -1
  494. package/dist/core/create-agent-script.js.map +0 -1
  495. package/dist/core/decorators.d.ts.map +0 -1
  496. package/dist/core/decorators.js.map +0 -1
  497. package/dist/core/define-module.d.ts.map +0 -1
  498. package/dist/core/define-module.js.map +0 -1
  499. package/dist/core/dump-policy.d.ts.map +0 -1
  500. package/dist/core/dump-policy.js.map +0 -1
  501. package/dist/core/hooks.d.ts.map +0 -1
  502. package/dist/core/hooks.js.map +0 -1
  503. package/dist/core/index.d.ts +0 -16
  504. package/dist/core/index.d.ts.map +0 -1
  505. package/dist/core/index.js +0 -36
  506. package/dist/core/index.js.map +0 -1
  507. package/dist/core/media-bootstrap.d.ts.map +0 -1
  508. package/dist/core/media-bootstrap.js.map +0 -1
  509. package/dist/core/provide-media.d.ts.map +0 -1
  510. package/dist/core/provide-media.js.map +0 -1
  511. package/dist/core/tokens.d.ts.map +0 -1
  512. package/dist/core/tokens.js.map +0 -1
  513. package/dist/core/types.d.ts.map +0 -1
  514. package/dist/core/types.js.map +0 -1
  515. package/dist/core/version.d.ts.map +0 -1
  516. package/dist/core/version.js.map +0 -1
  517. package/dist/dialog/basic-ports.d.ts +0 -54
  518. package/dist/dialog/basic-ports.d.ts.map +0 -1
  519. package/dist/dialog/basic-ports.js +0 -206
  520. package/dist/dialog/basic-ports.js.map +0 -1
  521. package/dist/dialog/define-dialog.d.ts +0 -21
  522. package/dist/dialog/define-dialog.d.ts.map +0 -1
  523. package/dist/dialog/define-dialog.js +0 -21
  524. package/dist/dialog/define-dialog.js.map +0 -1
  525. package/dist/dialog/dialog-definition.d.ts.map +0 -1
  526. package/dist/dialog/dialog-definition.js.map +0 -1
  527. package/dist/dialog/dialog-ports.d.ts.map +0 -1
  528. package/dist/dialog/dialog-ports.js.map +0 -1
  529. package/dist/dialog/index.d.ts +0 -7
  530. package/dist/dialog/index.d.ts.map +0 -1
  531. package/dist/dialog/index.js +0 -23
  532. package/dist/dialog/index.js.map +0 -1
  533. package/dist/dialog/online-call-host.d.ts.map +0 -1
  534. package/dist/dialog/online-call-host.js.map +0 -1
  535. package/dist/dialog/online-call-module.d.ts.map +0 -1
  536. package/dist/dialog/online-call-module.js.map +0 -1
  537. package/dist/dialog-events/active-media.d.ts.map +0 -1
  538. package/dist/dialog-events/active-media.js.map +0 -1
  539. package/dist/dialog-events/event-source.d.ts.map +0 -1
  540. package/dist/dialog-events/event-source.js.map +0 -1
  541. package/dist/dialog-events/index.d.ts +0 -8
  542. package/dist/dialog-events/index.d.ts.map +0 -1
  543. package/dist/dialog-events/index.js +0 -24
  544. package/dist/dialog-events/index.js.map +0 -1
  545. package/dist/dialog-events/max-listen-source.d.ts +0 -27
  546. package/dist/dialog-events/max-listen-source.d.ts.map +0 -1
  547. package/dist/dialog-events/max-listen-source.js +0 -98
  548. package/dist/dialog-events/max-listen-source.js.map +0 -1
  549. package/dist/dialog-events/overtalk-source.d.ts +0 -61
  550. package/dist/dialog-events/overtalk-source.d.ts.map +0 -1
  551. package/dist/dialog-events/overtalk-source.js +0 -232
  552. package/dist/dialog-events/overtalk-source.js.map +0 -1
  553. package/dist/dialog-events/silence-source.d.ts +0 -32
  554. package/dist/dialog-events/silence-source.d.ts.map +0 -1
  555. package/dist/dialog-events/silence-source.js +0 -128
  556. package/dist/dialog-events/silence-source.js.map +0 -1
  557. package/dist/dialog-events/virtual-finals-module.d.ts.map +0 -1
  558. package/dist/dialog-events/virtual-finals-module.js.map +0 -1
  559. package/dist/dialog-events/virtual-finals.d.ts.map +0 -1
  560. package/dist/dialog-events/virtual-finals.js.map +0 -1
  561. package/dist/dtmf/dtmf.d.ts +0 -27
  562. package/dist/dtmf/dtmf.d.ts.map +0 -1
  563. package/dist/dtmf/dtmf.js +0 -87
  564. package/dist/dtmf/dtmf.js.map +0 -1
  565. package/dist/dtmf/index.d.ts +0 -3
  566. package/dist/dtmf/index.d.ts.map +0 -1
  567. package/dist/dtmf/index.js +0 -8
  568. package/dist/dtmf/index.js.map +0 -1
  569. package/dist/index.d.ts.map +0 -1
  570. package/dist/index.js.map +0 -1
  571. package/dist/lifecycle/index.d.ts +0 -3
  572. package/dist/lifecycle/index.d.ts.map +0 -1
  573. package/dist/lifecycle/index.js +0 -9
  574. package/dist/lifecycle/index.js.map +0 -1
  575. package/dist/lifecycle/lifecycle.d.ts.map +0 -1
  576. package/dist/lifecycle/lifecycle.js.map +0 -1
  577. package/dist/llm/index.d.ts +0 -7
  578. package/dist/llm/index.d.ts.map +0 -1
  579. package/dist/llm/index.js +0 -18
  580. package/dist/llm/index.js.map +0 -1
  581. package/dist/llm/llm-markers-module.d.ts +0 -15
  582. package/dist/llm/llm-markers-module.d.ts.map +0 -1
  583. package/dist/llm/llm-markers-module.js +0 -48
  584. package/dist/llm/llm-markers-module.js.map +0 -1
  585. package/dist/llm/llm-markers.d.ts +0 -36
  586. package/dist/llm/llm-markers.d.ts.map +0 -1
  587. package/dist/llm/llm-markers.js +0 -210
  588. package/dist/llm/llm-markers.js.map +0 -1
  589. package/dist/llm/llm-module.d.ts +0 -20
  590. package/dist/llm/llm-module.d.ts.map +0 -1
  591. package/dist/llm/llm-module.js.map +0 -1
  592. package/dist/match/index.d.ts +0 -3
  593. package/dist/match/index.d.ts.map +0 -1
  594. package/dist/match/index.js +0 -10
  595. package/dist/match/index.js.map +0 -1
  596. package/dist/match/match.d.ts +0 -33
  597. package/dist/match/match.d.ts.map +0 -1
  598. package/dist/match/match.js +0 -85
  599. package/dist/match/match.js.map +0 -1
  600. package/dist/outbound/index.d.ts +0 -3
  601. package/dist/outbound/index.d.ts.map +0 -1
  602. package/dist/outbound/index.js +0 -8
  603. package/dist/outbound/index.js.map +0 -1
  604. package/dist/outbound/outbound.d.ts +0 -40
  605. package/dist/outbound/outbound.d.ts.map +0 -1
  606. package/dist/outbound/outbound.js +0 -84
  607. package/dist/outbound/outbound.js.map +0 -1
  608. package/dist/result/index.d.ts +0 -2
  609. package/dist/result/index.d.ts.map +0 -1
  610. package/dist/result/index.js.map +0 -1
  611. package/dist/result/result-store.d.ts.map +0 -1
  612. package/dist/result/result-store.js.map +0 -1
  613. package/dist/testing/fake-channel.d.ts.map +0 -1
  614. package/dist/testing/fake-channel.js.map +0 -1
  615. package/dist/testing/index.d.ts.map +0 -1
  616. package/dist/testing/index.js.map +0 -1
  617. package/docs/agents/README.md +0 -41
  618. package/docs/agents/barge-in.md +0 -67
  619. package/docs/agents/dialog.md +0 -98
  620. package/docs/agents/getting-started.md +0 -142
  621. package/docs/agents/imports.md +0 -40
  622. package/docs/agents/media-and-ports.md +0 -82
  623. package/docs/agents/modules.md +0 -83
  624. package/docs/agents/phases.md +0 -83
  625. package/docs/framework/extending.md +0 -59
  626. package/docs/framework/idn-parity.md +0 -18
  627. package/examples/minimal-agent/README.md +0 -7
  628. package/examples/minimal-agent/agent.ts +0 -94
@@ -0,0 +1,1399 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.applyAsrCorrections = exports.CallVoice = exports.spokenLength = exports.DEFAULT_GOODBYE_FLOOR = exports.DEFAULT_REPLY_FLOOR = exports.VOICE_ASR = void 0;
4
+ // The media side of a voice call, shared by every conversation that drives it through events and effects: one
5
+ // recognizer per conversation language on the runtime's ActiveMedia (barge-in and virtual finals come from the runtime
6
+ // modules), the turn-timing watchdog (silence windows), agent turns (an LLM stream or a fixed phrase → TTS,
7
+ // supersession by sequence number, drain floors and ceilings, the say() watchdog, a retry on an empty reply) and the
8
+ // hangup. It holds only media facts; every decision is the conversation's, which gets them as a snapshot on each
9
+ // event. A conversation part adds its own kinds of turns and reply sources by extending it.
10
+ const self_echo_1 = require("./self-echo");
11
+ const rxjs_1 = require("rxjs");
12
+ const lifecycle_1 = require("../lifecycle/lifecycle");
13
+ const speech_leak_1 = require("./speech-leak");
14
+ const turn_timing_1 = require("./turn-timing");
15
+ const open_timeout_1 = require("../core/open-timeout");
16
+ /** Token of the call's recognizer (barge-in binding and ActiveMedia). */
17
+ exports.VOICE_ASR = 'asr:fixed';
18
+ /** Result label of a call whose LLM said nothing twice in a row (`hangupOnSecondEmptyReply`). */
19
+ const LLM_FAILURE = 'llm failure';
20
+ /** Result label of a reply that ended on the goodbye marker. */
21
+ const GOODBYE = 'goodbye';
22
+ /** Default drain floors: TTS pace lower bounds (ms per spoken character) and the minimum, counted as `from` says. */
23
+ exports.DEFAULT_REPLY_FLOOR = { msPerChar: 45, minMs: 1_200, from: 'turnStart' };
24
+ exports.DEFAULT_GOODBYE_FLOOR = { msPerChar: 55, minMs: 1_200, from: 'firstChunk' };
25
+ /** A turn with no floor waits this long for its first audio before it counts as played (nothing will play). */
26
+ const NO_FLOOR_START_ALLOWANCE_MS = 3_000;
27
+ function spokenLength(text) {
28
+ return text.replace(/\[[^\]]*\]/g, '').trim().length;
29
+ }
30
+ exports.spokenLength = spokenLength;
31
+ /**
32
+ * The call's media. Extend it with the conversation's own reply source ({@link replyStream}) and, when needed, its
33
+ * own turns; run it from the conversation's ports, read its {@link events$} in the conversation's event source.
34
+ */
35
+ class CallVoice {
36
+ get callEnding() {
37
+ return this.ending;
38
+ }
39
+ constructor(channel, logger, am, call, lifecycle) {
40
+ this.channel = channel;
41
+ this.logger = logger;
42
+ this.am = am;
43
+ this.call = call;
44
+ this.lifecycle = lifecycle;
45
+ this.events = new rxjs_1.Subject();
46
+ this.events$ = this.events.asObservable();
47
+ // media facts
48
+ this.turnSeq = 0;
49
+ /** Per-call scratch of the agent's reply filter. */
50
+ this.filterState = {};
51
+ this.agentSpeaking = false;
52
+ this.playbackStartedAtMs = 0;
53
+ /** When the last turn's first audio started (not cleared by the drain) and when the current turn started. */
54
+ this.lastPlaybackStartedAtMs = 0;
55
+ this.turnStartedAtMs = 0;
56
+ /** Start of the current turn's latest agent-queue item (0 since the turn began). */
57
+ this.lastItemStartedAtMs = 0;
58
+ this.agentTurnInterrupted = false;
59
+ /** How long the current turn had played when the caller cut it (`undefined`: not cut). */
60
+ this.cutHeardMs = undefined;
61
+ this.lastTurnTriggerText = null;
62
+ this.closingPhraseActive = false;
63
+ this.greetingOnWire = false;
64
+ this.userSpeaking = false;
65
+ this.userSpeechStartedAt = 0;
66
+ /** The hangup has started; it was sent; bumped by `cancelHangup` (a goodbye drain in flight then does not hang up). */
67
+ this.ending = false;
68
+ this.hangupSent = false;
69
+ /** A hangup waits for its line to play out (`hangupAfterPlayback` in progress). */
70
+ this.hangupWaiting = false;
71
+ /** The last turn whose DRAINED was emitted. */
72
+ this.drainedSeq = -1;
73
+ this.hangupGeneration = 0;
74
+ /** The caller's current run of speech began / their last segment ended (`reopenOnSpeech`). */
75
+ this.speechRunStartedAt = 0;
76
+ /** When the caller's last partial with words came. */
77
+ this.lastPartialAtMs = 0;
78
+ this.lastSpeechEndAt = 0;
79
+ this.terminated = false;
80
+ this.terminatedP = new Promise((resolve) => { this.terminatedResolve = resolve; });
81
+ this.asrDisposed = false;
82
+ this.queueEventsObserved = false;
83
+ /** When the first audio item of the current turn started (null: none yet). */
84
+ this.turnFirstItemStartedAt = null;
85
+ this.itemStarted = new rxjs_1.Subject();
86
+ /** When the last part of the current fixed line started playing (0: not yet). */
87
+ this.lastPartStartedAtMs = 0;
88
+ this.pending = 0;
89
+ this.tts = null;
90
+ this.sayWatchdogs = new Set();
91
+ this.emptyReplyRetried = false;
92
+ /** `emptyReply`: empty replies in a row, and re-asks of replies cut before their stream ended. */
93
+ this.emptyStreak = 0;
94
+ this.abortedRetries = 0;
95
+ /** Probes said since the last reply with text (`emptyReply.probes`). */
96
+ this.probesUsed = 0;
97
+ /** When the LLM turn in flight was requested while nothing of it streamed yet (0: none). */
98
+ this.llmWaitingSince = 0;
99
+ this.replayTimer = null;
100
+ // recognizer
101
+ this.asr = null;
102
+ this.asrSubs = [];
103
+ this.activeSession = null;
104
+ this.requestedSession = null;
105
+ /** The language key the open recognizer session was started with (null: none open). */
106
+ this.activeKey = null;
107
+ this.startSeq = 0;
108
+ this.noAudioTimer = null;
109
+ this.deadAudioTimer = null;
110
+ this.audioEvidence = false;
111
+ this.subs = [];
112
+ /** The agent's last spoken lines, most recent first (`selfEcho`). */
113
+ this.spokenLines = [];
114
+ /** Finals the self-echo check dropped or cut this call. */
115
+ this.echoResults = 0;
116
+ this.voiceAnswerOn = false;
117
+ this.voiceStartedAt = null;
118
+ this.voiceAnswerTimer = null;
119
+ this.finalGate = null;
120
+ this.finalChain = Promise.resolve();
121
+ /** The vendor's final of an utterance a virtual final answered goes to the transcript (set by a conversation part). */
122
+ this.vendorFinalInTranscript = false;
123
+ /** The last final handed to the conversation. */
124
+ this.lastFinalText = null;
125
+ /** The watch of the current fixed line's last part (one at a time). */
126
+ this.lastPartWatch = null;
127
+ }
128
+ /** Speech start and partials reach the conversation only when it reads them. */
129
+ get speechEvents() {
130
+ return false;
131
+ }
132
+ snapshot() {
133
+ const now = Date.now();
134
+ return {
135
+ now,
136
+ agentSpeaking: this.agentSpeaking,
137
+ agentTurnInterrupted: this.agentTurnInterrupted,
138
+ playbackStartedAt: this.playbackStartedAtMs !== 0 ? this.playbackStartedAtMs : now,
139
+ lastTurnTriggerText: this.lastTurnTriggerText,
140
+ closingPhraseActive: this.closingPhraseActive,
141
+ callEnding: this.callEnding,
142
+ terminated: this.terminated,
143
+ userSpeaking: this.userSpeaking,
144
+ userSpeechStartedAt: 0,
145
+ turnSeq: this.turnSeq,
146
+ llmWaitingSince: this.llmWaitingSince,
147
+ turnStartedAt: this.turnStartedAtMs,
148
+ lastPlaybackStartedAt: this.lastPlaybackStartedAtMs,
149
+ lastItemStartedAt: this.lastItemStartedAtMs,
150
+ speechRunStartedAt: this.speechRunStartedAt,
151
+ hangupSent: this.hangupSent,
152
+ ...(this.cutHeardMs !== undefined ? { cutHeardMs: this.cutHeardMs } : {}),
153
+ ...(this.lastPartialAtMs !== 0 ? { lastPartialAt: this.lastPartialAtMs } : {}),
154
+ ...(this.lastPartStartedAtMs ? { lastPartStartedAt: this.lastPartStartedAtMs } : {}),
155
+ };
156
+ }
157
+ emit(e) {
158
+ if (this.terminated && e.type !== 'SPOKEN' && e.type !== 'RESULT')
159
+ return;
160
+ if (e.type === 'SPOKEN' && this.agent.selfEcho) {
161
+ const text = e.text;
162
+ if (text)
163
+ this.spokenLines = [text, ...this.spokenLines].slice(0, Math.max(1, this.agent.selfEcho.lookback));
164
+ }
165
+ this.events.next(e);
166
+ }
167
+ /** A caller final without the agent's own words in it (`null`: nothing of the caller's is left). */
168
+ withoutSelfEcho(text) {
169
+ const cfg = this.agent.selfEcho;
170
+ if (!cfg)
171
+ return text;
172
+ const echo = (0, self_echo_1.detectSelfEcho)(text, this.spokenLines, cfg);
173
+ if (echo == null)
174
+ return text;
175
+ this.echoResults += 1;
176
+ this.logger.log(echo.residue ? 'asr_echo_stripped' : 'asr_result_skipped_echo', {
177
+ userText: text, residue: echo.residue, echoTokens: echo.echoTokens, echoSpan: echo.echoSpan, totalTokens: echo.totalTokens,
178
+ agentCoverage: Number(echo.agentCoverage.toFixed(2)), agentText: echo.agentText, echoResults: this.echoResults,
179
+ });
180
+ return echo.residue || null;
181
+ }
182
+ // ── call start ────────────────────────────────────────────────────────────────
183
+ async onOnlineCall() {
184
+ const { channel, agent, logger } = this;
185
+ logger.log('started', {
186
+ agentUuid: this.call.agentUuid,
187
+ callUuid: this.call.callUuid,
188
+ dialogUuid: this.call.context.dialogUuid,
189
+ version: agent.logicVersion,
190
+ });
191
+ this.watchTermination();
192
+ // Mixer queues and the ambient bed.
193
+ const ttsQueue = channel.audio.queue(agent.queues.tts);
194
+ channel.audio.queue(agent.queues.ambient).volume = agent.queues.ambientVolume;
195
+ this.subs.push(ttsQueue.itemStarted$.subscribe(() => {
196
+ if (!this.agentSpeaking || this.playbackStartedAtMs === 0)
197
+ this.lastPlaybackStartedAtMs = Date.now();
198
+ this.agentSpeaking = true;
199
+ if (this.playbackStartedAtMs === 0)
200
+ this.playbackStartedAtMs = Date.now();
201
+ this.pending += 1;
202
+ this.queueEventsObserved = true;
203
+ if (this.turnFirstItemStartedAt == null)
204
+ this.turnFirstItemStartedAt = Date.now();
205
+ this.lastItemStartedAtMs = Date.now();
206
+ this.itemStarted.next();
207
+ }), ttsQueue.itemFinished$.subscribe(() => {
208
+ this.pending = Math.max(0, this.pending - 1);
209
+ }));
210
+ this.watchQueue(ttsQueue);
211
+ this.startBackground();
212
+ const ttsReady = this.openTtsSession();
213
+ this.timing = new turn_timing_1.TurnTimingController(logger, agent.turnTiming, {
214
+ onSilenceTimeout: (timeout) => this.emit({ type: 'SILENCE', timeout, m: this.snapshot() }),
215
+ onMaxListenTimeout: () => this.finalize(),
216
+ onNoProgress: () => this.emit({ type: 'NO_PROGRESS', m: this.snapshot() }),
217
+ });
218
+ this.am.setBargeInBlocker(() => this.callEnding || this.greetingOnWire || this.closingPhraseActive);
219
+ this.subs.push(this.am.bargeIn$.subscribe((ev) => {
220
+ if (ev.phase !== 'stop')
221
+ return;
222
+ this.agentTurnInterrupted = true;
223
+ this.cutHeardMs = this.agentSpeaking && this.playbackStartedAtMs !== 0 ? Date.now() - this.playbackStartedAtMs : null;
224
+ this.turnCut(this.turnSeq);
225
+ }), this.am.finals$().subscribe((raw) => this.onFinal(raw)), this.am.dropped$.subscribe(({ text, reason }) => this.onDropped(text, reason)), this.am.suppressedFinals$.subscribe((raw) => this.onSuppressedFinal(raw)));
226
+ // ONE recognizer, up before the first word (the opening is talked over most of the time).
227
+ await this.startEngine(this.setup().defaultLanguage, true).catch((err) => {
228
+ this.asrStartFailed(err);
229
+ });
230
+ await ttsReady;
231
+ }
232
+ /** More watchers on the agent queue (a conversation part's own drain). */
233
+ watchQueue(_ttsQueue) {
234
+ /* none */
235
+ }
236
+ /** The ambient bed. */
237
+ startBackground() {
238
+ const { agent, logger } = this;
239
+ void this.channel.audio.play(agent.audio.ambientLoopUrl, agent.play.ambient).catch((err) => {
240
+ logger.log('ambient play error', { err: String(err) });
241
+ });
242
+ }
243
+ /** The caller's speech started / ended (VAD). */
244
+ speechStarted() {
245
+ /* none */
246
+ }
247
+ speechEnded() {
248
+ /* none */
249
+ }
250
+ /** The conversation turns the voice-without-text answer on / off, or asks it again shortly (a clip still plays). */
251
+ voiceAnswerOp(op) {
252
+ if (op === 'retry') {
253
+ if (!this.voiceAnswerOn)
254
+ return;
255
+ this.clearVoiceAnswer();
256
+ this.voiceAnswerTimer = setTimeout(() => this.fireVoiceAnswer(), 200);
257
+ return;
258
+ }
259
+ this.voiceAnswerOn = op === 'on';
260
+ this.clearVoiceAnswer();
261
+ if (op === 'on')
262
+ this.voiceStartedAt = null;
263
+ }
264
+ armVoiceAnswer(edge) {
265
+ const cfg = this.agent.voiceAnswer;
266
+ if (!cfg || !this.voiceAnswerOn)
267
+ return;
268
+ const now = Date.now();
269
+ if (edge === 'start' && this.voiceStartedAt == null)
270
+ this.voiceStartedAt = now;
271
+ if (this.voiceStartedAt == null)
272
+ return;
273
+ this.clearVoiceAnswer();
274
+ const capAt = this.voiceStartedAt + cfg.maxMs;
275
+ const fireAt = this.userSpeaking ? capAt : Math.min(now + cfg.settleMs, capAt);
276
+ this.voiceAnswerTimer = setTimeout(() => this.fireVoiceAnswer(), Math.max(0, fireAt - now));
277
+ }
278
+ fireVoiceAnswer() {
279
+ this.voiceAnswerTimer = null;
280
+ if (!this.voiceAnswerOn || this.terminated || this.callEnding)
281
+ return;
282
+ this.logger.log('opening_voice_answer', {
283
+ msSinceVoiceStart: this.voiceStartedAt == null ? null : Date.now() - this.voiceStartedAt,
284
+ userSpeaking: this.userSpeaking,
285
+ });
286
+ this.emit({ type: 'VOICE_ANSWER', m: this.snapshot() });
287
+ }
288
+ clearVoiceAnswer() {
289
+ if (this.voiceAnswerTimer != null)
290
+ clearTimeout(this.voiceAnswerTimer);
291
+ this.voiceAnswerTimer = null;
292
+ }
293
+ /** A recognizer picked for this call (its key and settings), in place of the language's own; `null`: none. */
294
+ asrPick(_language) {
295
+ return null;
296
+ }
297
+ /** The recognizer could not be created. */
298
+ asrStartFailed(err) {
299
+ this.logger.log('asr_start_failed', { err: String(err) });
300
+ }
301
+ async openTtsSession() {
302
+ if (!this.agent.ttsSession)
303
+ return;
304
+ const start = Date.now();
305
+ const timeoutMs = this.agent.ttsSessionOpenTimeoutMs ?? open_timeout_1.DEFAULT_MEDIA_OPEN_TIMEOUT_MS;
306
+ try {
307
+ const tts = await (0, open_timeout_1.withOpenTimeout)(this.channel.createTts(this.agent.ttsSession), 'tts', timeoutMs, (late) => {
308
+ this.logger.log('tts_session_closed_late', { id: late.id });
309
+ late.destroy();
310
+ });
311
+ if (this.terminated) {
312
+ // Opened after the teardown: nothing will close it later.
313
+ this.logger.log('tts_session_closed_late', { id: tts.id });
314
+ try {
315
+ tts.destroy();
316
+ }
317
+ catch { /* best effort */ }
318
+ return;
319
+ }
320
+ this.tts = tts;
321
+ this.subs.push(this.tts.error$.subscribe((err) => this.logger.warn('tts_session_error', { message: err?.message })));
322
+ this.logger.log('perf', { event: 'tts_session_created', ms: Date.now() - start, id: this.tts.id });
323
+ }
324
+ catch (err) {
325
+ this.tts = null;
326
+ this.logger.log('tts_session_create_failed', { err: String(err) });
327
+ }
328
+ }
329
+ watchTermination() {
330
+ const fire = (source) => {
331
+ if (this.terminated)
332
+ return;
333
+ this.logger.log('terminated', { source });
334
+ this.terminated = true;
335
+ this.terminatedResolve();
336
+ this.teardown();
337
+ };
338
+ this.subs.push(this.channel.events.terminated$.subscribe(() => fire('terminated$')));
339
+ try {
340
+ this.subs.push(this.channel.sip.state$.subscribe((s) => { if (s === 'terminated')
341
+ fire('sip_state'); }));
342
+ }
343
+ catch {
344
+ /* no SIP layer */
345
+ }
346
+ }
347
+ teardown() {
348
+ this.clearReplay();
349
+ this.clearVoiceAnswer();
350
+ this.voiceAnswerOn = false;
351
+ for (const t of this.sayWatchdogs)
352
+ clearTimeout(t);
353
+ this.sayWatchdogs.clear();
354
+ try {
355
+ this.channel.audio.stop(this.agent.queues.ambient);
356
+ }
357
+ catch { /* ignore */ }
358
+ this.timing?.dispose();
359
+ this.clearEngine();
360
+ try {
361
+ this.tts?.destroy();
362
+ }
363
+ catch { /* best effort */ }
364
+ this.tts = null;
365
+ if (!this.callEnding)
366
+ this.logger.log('terminated without goodbye', { signal: this.agent.connectionErrorSignal });
367
+ }
368
+ onCallDestroy() {
369
+ if (!this.terminated) {
370
+ this.terminated = true;
371
+ this.terminatedResolve();
372
+ this.teardown();
373
+ }
374
+ for (const s of this.subs)
375
+ s.unsubscribe();
376
+ this.subs.length = 0;
377
+ this.lastPartWatch?.unsubscribe();
378
+ this.am.setBargeInBlocker(null);
379
+ // itemStarted is left open: a wait still racing it must time out, not fail empty.
380
+ this.events.complete();
381
+ }
382
+ // ── recognizer ───────────────────────────────────────────────────────────────
383
+ languageConfig(language) {
384
+ const { languages, defaultLanguage } = this.agent.asr;
385
+ return languages[language] ?? languages[defaultLanguage];
386
+ }
387
+ /** The language key for the next session: the detection row while the language is provisional. */
388
+ sessionLanguage(language, provisional) {
389
+ const { detectionLanguage, languages, defaultLanguage } = this.agent.asr;
390
+ if (provisional && detectionLanguage != null && languages[detectionLanguage])
391
+ return detectionLanguage;
392
+ return languages[language] ? language : defaultLanguage;
393
+ }
394
+ /** Re-point the recognizer at a settled language; free when that session is already up or connecting. */
395
+ async switchTo(language) {
396
+ if (this.terminated || this.callEnding || this.startSeq === 0)
397
+ return;
398
+ const cfg = this.languageConfig(language);
399
+ const wanted = `${cfg.name}|${cfg.language}`;
400
+ if (this.requestedSession === wanted)
401
+ return;
402
+ this.logger.log('asr switch', { from: this.activeSession, to: wanted, language });
403
+ await this.startEngine(language, false);
404
+ }
405
+ finalize() {
406
+ try {
407
+ this.asr?.finalize();
408
+ }
409
+ catch { /* harmless */ }
410
+ }
411
+ clearEngine() {
412
+ for (const t of [this.noAudioTimer, this.deadAudioTimer])
413
+ if (t != null)
414
+ clearTimeout(t);
415
+ this.noAudioTimer = null;
416
+ this.deadAudioTimer = null;
417
+ for (const s of this.asrSubs)
418
+ s.unsubscribe();
419
+ this.asrSubs = [];
420
+ if (this.asr) {
421
+ const closed = this.activeSession;
422
+ try {
423
+ this.asr.destroy();
424
+ }
425
+ catch { /* already destroyed */ }
426
+ this.asr = null;
427
+ const sessionMs = this.call.usage.sessionClosed();
428
+ const total = this.call.usage.snapshot();
429
+ this.logger.log('asr_session_closed', { session: closed, sessionMs, totalMs: total.activeMs, sessions: total.sessions });
430
+ }
431
+ this.activeSession = null;
432
+ this.activeKey = null;
433
+ }
434
+ async startEngine(language, opening) {
435
+ if (this.terminated)
436
+ return;
437
+ // A call without a recognizer (an agent that only plays).
438
+ if (Object.keys(this.agent.asr.languages).length === 0)
439
+ return;
440
+ const seq = ++this.startSeq;
441
+ const key = opening ? this.sessionLanguage(language, true) : language;
442
+ const pick = this.asrPick(key);
443
+ const base = this.languageConfig(key);
444
+ const cfg = pick?.name != null ? { ...base, name: pick.name } : base;
445
+ const sessionKey = `${cfg.name}|${cfg.language}`;
446
+ // A switch closes the working session first (two live sessions would dispatch every line twice).
447
+ const previous = opening ? null : this.activeKey;
448
+ this.clearEngine();
449
+ this.requestedSession = sessionKey;
450
+ this.logger.log('asr creating', { language: key, asrName: cfg.name, asrLanguage: cfg.language });
451
+ const a = this.agent.asr;
452
+ let handle;
453
+ try {
454
+ const data = pick?.data ?? a.data;
455
+ handle = await (0, open_timeout_1.withOpenTimeout)(this.channel.createAsr({
456
+ // No key: the platform's default recognizer of the agent.
457
+ ...(cfg.name ? { name: cfg.name } : {}),
458
+ language: cfg.language,
459
+ ...(a.vendor ? { vendor: a.vendor } : {}),
460
+ ...(data ? { data } : {}),
461
+ vad: a.vad,
462
+ smartTurn: a.smartTurn,
463
+ }), 'asr', a.openTimeoutMs ?? open_timeout_1.DEFAULT_MEDIA_OPEN_TIMEOUT_MS, (late) => {
464
+ this.logger.log('asr_session_closed_late', { session: sessionKey });
465
+ late.destroy();
466
+ });
467
+ }
468
+ catch (err) {
469
+ if (seq === this.startSeq)
470
+ this.requestedSession = null;
471
+ // A failed switch must not leave the call deaf: the previous language's session is opened again, once.
472
+ if (previous != null && seq === this.startSeq && !this.terminated) {
473
+ this.logger.log('asr_switch_failed_reopen', { from: sessionKey, language: previous, err: String(err) });
474
+ await this.startEngine(previous, false).catch((reopenErr) => {
475
+ this.logger.log('asr_switch_reopen_failed', { language: previous, err: String(reopenErr) });
476
+ });
477
+ }
478
+ throw err;
479
+ }
480
+ if (this.terminated || seq !== this.startSeq) {
481
+ try {
482
+ handle.destroy();
483
+ }
484
+ catch { /* ignore */ }
485
+ return;
486
+ }
487
+ this.asr = handle;
488
+ this.activeSession = sessionKey;
489
+ this.activeKey = key;
490
+ this.call.usage.sessionOpened();
491
+ this.wire(handle, cfg.language);
492
+ // The runtime takes the session from here: virtual finals, result filters, barge-in.
493
+ this.am.setAsr(handle, exports.VOICE_ASR);
494
+ this.logger.log('asr ready', { language: key, asrLanguage: cfg.language });
495
+ }
496
+ wire(asr, lang) {
497
+ const { logger } = this;
498
+ const cfg = this.agent.asr;
499
+ this.audioEvidence = false;
500
+ let vadSamples = 0;
501
+ this.noAudioTimer = setTimeout(() => {
502
+ this.noAudioTimer = null;
503
+ if (!this.terminated && vadSamples === 0)
504
+ logger.log('asr_no_audio', { asr: lang, afterMs: cfg.noAudioWarnMs });
505
+ }, cfg.noAudioWarnMs);
506
+ if (cfg.deadAudioMs != null && cfg.deadAudioMs > 0) {
507
+ this.deadAudioTimer = setTimeout(() => {
508
+ this.deadAudioTimer = null;
509
+ if (this.terminated || this.audioEvidence)
510
+ return;
511
+ logger.log('asr_audio_path_dead', { asr: lang, afterMs: cfg.deadAudioMs });
512
+ this.emit({ type: 'AUDIO_DEAD', m: this.snapshot() });
513
+ }, cfg.deadAudioMs);
514
+ }
515
+ this.asrSubs.push(asr.vadProbability$.subscribe(() => {
516
+ vadSamples += 1;
517
+ this.audioEvidence = true;
518
+ }), asr.speechStart$.subscribe(() => {
519
+ this.audioEvidence = true;
520
+ if (this.terminated)
521
+ return;
522
+ const run = this.agent.reopenOnSpeech;
523
+ if (run && (this.speechRunStartedAt === 0 || Date.now() - this.lastSpeechEndAt > run.runGapMs))
524
+ this.speechRunStartedAt = Date.now();
525
+ this.userSpeaking = true;
526
+ this.userSpeechStartedAt = Date.now();
527
+ this.timing.onUserSpeechStart();
528
+ this.speechStarted();
529
+ this.armVoiceAnswer('start');
530
+ if (this.speechEvents)
531
+ this.emit({ type: 'SPEECH_START', m: this.snapshot() });
532
+ }), asr.speechEnd$.subscribe(() => {
533
+ if (!this.terminated) {
534
+ this.userSpeaking = false;
535
+ this.lastSpeechEndAt = Date.now();
536
+ this.timing.onUserSpeechEnd();
537
+ this.speechEnded();
538
+ this.armVoiceAnswer('end');
539
+ }
540
+ // Finalize on every VAD end: the vendor then returns its final sooner.
541
+ try {
542
+ asr.finalize();
543
+ }
544
+ catch { /* harmless */ }
545
+ }), asr.result$.subscribe(() => {
546
+ this.audioEvidence = true;
547
+ }), asr.partial$.subscribe((p) => {
548
+ if (!this.terminated && (p.text?.trim() ?? '') !== '')
549
+ this.lastPartialAtMs = Date.now();
550
+ if (!this.terminated)
551
+ this.partialHeard(p.text ?? '');
552
+ }));
553
+ if (this.speechEvents || this.agent.turnTiming.maxNoWordsMs != null) {
554
+ this.asrSubs.push(asr.partial$.subscribe((p) => {
555
+ const text = p.text?.trim() ?? '';
556
+ if (!text || this.terminated)
557
+ return;
558
+ this.timing.onUserWords();
559
+ if (this.speechEvents)
560
+ this.emit({ type: 'PARTIAL', text, isFinal: p.isFinal === true, m: this.snapshot() });
561
+ }));
562
+ }
563
+ }
564
+ /**
565
+ * A final of a session that is already closed (the switch destroyed it, the next one is still connecting): the
566
+ * closed session's virtual-final timer is gone with it, so nothing of it reaches the conversation. The runtime keeps
567
+ * the closed handle's virtual finals until the next handle is set; they are dropped here.
568
+ */
569
+ fromClosedSession(text, kind) {
570
+ if (this.asr != null || this.startSeq === 0)
571
+ return false;
572
+ this.logger.log('asr_final_of_closed_session_dropped', { text, kind });
573
+ return true;
574
+ }
575
+ onFinal(raw) {
576
+ if (this.fromClosedSession(raw, 'final'))
577
+ return;
578
+ this.audioEvidence = true;
579
+ if (this.terminated || this.asrDisposed)
580
+ return;
581
+ if (this.finalsIgnored(raw))
582
+ return;
583
+ const corrected = applyAsrCorrections(raw, this.agent.asr.resultCorrections);
584
+ if (corrected !== raw.trim())
585
+ this.logger.log('asr_result_corrected', { from: raw, to: corrected });
586
+ if (!corrected)
587
+ return;
588
+ const text = this.withoutSelfEcho(corrected);
589
+ if (text == null)
590
+ return;
591
+ this.logger.log('asr dispatch', { text, len: text.length });
592
+ const gate = this.finalGate;
593
+ if (!gate) {
594
+ this.emitFinal(text);
595
+ return;
596
+ }
597
+ // Held: the gate answers first (in order of the finals); a final it takes is not the conversation's.
598
+ this.finalChain = this.finalChain.then(async () => {
599
+ let taken = false;
600
+ try {
601
+ taken = await gate(text);
602
+ }
603
+ catch (err) {
604
+ this.logger.log('asr_final_gate_failed', { err: String(err) });
605
+ }
606
+ if (!taken && !this.terminated)
607
+ this.emitFinal(text);
608
+ });
609
+ }
610
+ /** Every caller final waits for `gate` before the conversation reads it; `true` from the gate drops it. */
611
+ setFinalGate(gate) {
612
+ this.finalGate = gate;
613
+ }
614
+ /** The vendor's final swallowed after a virtual final: its wording, for the transcript line of that final. */
615
+ onSuppressedFinal(raw) {
616
+ if (!this.vendorFinalInTranscript || this.terminated || this.asrDisposed || this.lastFinalText == null)
617
+ return;
618
+ const text = applyAsrCorrections(raw, this.agent.asr.resultCorrections);
619
+ if (!text)
620
+ return;
621
+ this.logger.log('asr_vendor_final_after_virtual', { text, virtual: this.lastFinalText });
622
+ this.emit({ type: 'FINAL_REWORDED', text, virtual: this.lastFinalText });
623
+ }
624
+ /** A caller final to the conversation; it ends the utterance speech start began. */
625
+ emitFinal(text) {
626
+ this.lastFinalText = text;
627
+ const userSpeechStartedAt = this.userSpeechStartedAt;
628
+ this.userSpeechStartedAt = 0;
629
+ this.emit({ type: 'FINAL', text, m: { ...this.snapshot(), userSpeechStartedAt } });
630
+ }
631
+ onDropped(text, reason) {
632
+ if (this.fromClosedSession(text, `dropped_${reason}`))
633
+ return;
634
+ this.audioEvidence = true;
635
+ if (this.terminated || this.asrDisposed)
636
+ return;
637
+ this.userSpeaking = false;
638
+ if (this.rescueDropped(text, reason))
639
+ return;
640
+ this.userSpeechStartedAt = 0;
641
+ this.timing.noteDroppedLine();
642
+ this.timing.onUserUtteranceDropped();
643
+ this.logger.log('asr_result_dropped', { text, reason });
644
+ this.emit({ type: 'DROPPED', text, reason, m: this.snapshot() });
645
+ }
646
+ /** Caller finals are not read now (the call was handed over); true: dropped. */
647
+ finalsIgnored(_text) {
648
+ return false;
649
+ }
650
+ /** A dropped final the conversation part takes as a final after all (true: handled). */
651
+ rescueDropped(_text, _reason) {
652
+ return false;
653
+ }
654
+ // ── timing and replay (effects of the conversation) ──────────────────────────
655
+ timingOp(op, value) {
656
+ if (!this.timing || this.terminated)
657
+ return;
658
+ if (op === 'playbackEnd')
659
+ this.timing.onAgentPlaybackEnd();
660
+ else if (op === 'realResult') {
661
+ this.userSpeaking = false;
662
+ this.timing.onRealUserResult();
663
+ }
664
+ else if (op === 'refund')
665
+ this.timing.refundSilenceTurn();
666
+ else if (op === 'openingEnd')
667
+ this.timing.endOpening();
668
+ else
669
+ this.timing.setAwaitingHandover(value === true);
670
+ }
671
+ armReplay(ms) {
672
+ this.clearReplay();
673
+ this.replayTimer = setTimeout(() => {
674
+ this.replayTimer = null;
675
+ this.emit({ type: 'REPLAY_DUE', m: this.snapshot() });
676
+ }, ms);
677
+ }
678
+ clearReplay() {
679
+ if (this.replayTimer != null)
680
+ clearTimeout(this.replayTimer);
681
+ this.replayTimer = null;
682
+ }
683
+ // ── agent turns ──────────────────────────────────────────────────────────────
684
+ clearAgentSpeaking() {
685
+ this.agentSpeaking = false;
686
+ this.playbackStartedAtMs = 0;
687
+ }
688
+ stopTts() {
689
+ this.channel.audio.stop(this.agent.queues.tts);
690
+ this.pending = 0;
691
+ this.turnFirstItemStartedAt = null;
692
+ }
693
+ /** Text the reply filters still held when turn `seq`'s playback ended (a cut reply); default none. */
694
+ heldBack(_seq) {
695
+ return '';
696
+ }
697
+ /** A partial of the caller's speech (every one, as the recognizer sends it). */
698
+ partialHeard(_text) {
699
+ /* none */
700
+ }
701
+ /**
702
+ * Stop the agent's line now on a decision made outside the barge-in strategy (an interruption intent): as a barge-in
703
+ * would, unless the line may not be cut (closing, a protected line, the call ending).
704
+ */
705
+ forceCut(reason, data) {
706
+ if (this.callEnding || this.terminated || this.greetingOnWire || this.closingPhraseActive)
707
+ return;
708
+ try {
709
+ this.stopTts();
710
+ }
711
+ catch { /* closed */ }
712
+ this.agentTurnInterrupted = true;
713
+ this.cutHeardMs = this.agentSpeaking && this.playbackStartedAtMs !== 0 ? Date.now() - this.playbackStartedAtMs : null;
714
+ this.logger.log('barge_in_stop', { reason, ...data });
715
+ this.turnCut(this.turnSeq);
716
+ }
717
+ /** The caller cut turn `seq` (barge-in). */
718
+ turnCut(_seq) {
719
+ /* none */
720
+ }
721
+ /** A new agent turn; `stop: false` lets what the agent queue still plays go on (the turn queues behind it). */
722
+ beginTurn(stop = true) {
723
+ const seq = ++this.turnSeq;
724
+ this.lastPartStartedAtMs = 0;
725
+ this.turnStartedAtMs = Date.now();
726
+ this.lastItemStartedAtMs = 0;
727
+ this.agentTurnInterrupted = false;
728
+ this.cutHeardMs = undefined;
729
+ this.clearAgentSpeaking();
730
+ if (stop)
731
+ this.stopTts();
732
+ this.timing.onAgentTurnStart();
733
+ return seq;
734
+ }
735
+ /** Fixed lines into the TTS cache on the call's TTS session (nothing without one). */
736
+ presay(texts) {
737
+ const tts = this.tts;
738
+ if (tts == null) {
739
+ this.logger.log('presay_skipped', { reason: 'no tts session' });
740
+ return;
741
+ }
742
+ const { ttsVendor, name, ttsConfig, ttsStrategy } = this.agent.play.llm;
743
+ for (const text of texts) {
744
+ void this.channel.audio.presay(text, { ttsVendor, name, ttsConfig, ttsStrategy, tts })
745
+ .catch((err) => this.logger.log('presay_error', { text, err: String(err) }));
746
+ }
747
+ }
748
+ /** A turn whose line comes later (agent code is deciding it): the agent stops, the silence windows wait. */
749
+ startPendingTurn() {
750
+ if (this.terminated)
751
+ return;
752
+ this.beginTurn();
753
+ }
754
+ /** A reply taken back (the caller carried on): superseded and stopped, no new turn. */
755
+ cutReply() {
756
+ if (this.terminated)
757
+ return;
758
+ this.turnSeq += 1;
759
+ this.clearAgentSpeaking();
760
+ this.agentTurnInterrupted = false;
761
+ this.stopTts();
762
+ }
763
+ isCurrent(seq) {
764
+ return seq === this.turnSeq;
765
+ }
766
+ drained(seq) {
767
+ if (this.isCurrent(seq))
768
+ this.clearAgentSpeaking();
769
+ if (this.callEnding || this.terminated || !this.isCurrent(seq))
770
+ return;
771
+ this.drainedSeq = seq;
772
+ this.emit({ type: 'DRAINED', m: this.snapshot() });
773
+ }
774
+ /**
775
+ * The end of turn `seq` threw (a hook, a wait that failed). The call must not wait for a DRAINED that never comes:
776
+ * the turn counts as drained, or, when the call is ending and no hangup is on its way, it is hung up after playback.
777
+ */
778
+ turnEndFailed(event, seq, err, data, release, hangupReason) {
779
+ this.logger.log(event, { ...data, err: String(err) });
780
+ try {
781
+ release?.();
782
+ }
783
+ catch { /* ignore */ }
784
+ if (this.isCurrent(seq))
785
+ this.clearAgentSpeaking();
786
+ if (this.terminated)
787
+ return;
788
+ if (hangupReason != null && !this.ending) {
789
+ this.hangupAfterPlayback(hangupReason, this.drainSafely()).catch((e) => this.logger.log('hangup_failed', { reason: hangupReason, err: String(e) }));
790
+ return;
791
+ }
792
+ if (this.ending) {
793
+ if (!this.hangupSent && !this.hangupWaiting) {
794
+ this.hangupStalled(hangupReason ?? 'turn_end_failed').catch((e) => this.logger.log('hangup_failed', { reason: event, err: String(e) }));
795
+ }
796
+ return;
797
+ }
798
+ if (this.callEnding || !this.isCurrent(seq) || this.drainedSeq === seq)
799
+ return;
800
+ this.drainedSeq = seq;
801
+ this.emit({ type: 'DRAINED', m: this.snapshot() });
802
+ }
803
+ /** The agent queue's drain under the lifecycle's timeout; never fails. */
804
+ drainSafely() {
805
+ return Promise.resolve()
806
+ .then(() => this.awaitTtsQueueDrain(this.agent.lifecycle.ttsDrainTimeoutMs))
807
+ .catch(() => undefined);
808
+ }
809
+ /** The call is ending but the hangup that was to end it failed on its way: it is sent after playback. */
810
+ async hangupStalled(reason) {
811
+ const generation = this.hangupGeneration;
812
+ await this.drainSafely();
813
+ if (this.terminated || this.hangupSent || this.hangupWaiting || !this.ending || generation !== this.hangupGeneration)
814
+ return;
815
+ this.hangupSent = true;
816
+ await this.lifecycle.hangup(reason, { strategy: lifecycle_1.HangupStrategy.immediate({ rtpTailMs: 0 }) });
817
+ }
818
+ armSayWatchdog(onFire) {
819
+ const w = setTimeout(() => {
820
+ this.sayWatchdogs.delete(w);
821
+ onFire();
822
+ }, this.agent.lifecycle.sayTimeoutMs);
823
+ this.sayWatchdogs.add(w);
824
+ return w;
825
+ }
826
+ settleWatchdog(w) {
827
+ clearTimeout(w);
828
+ this.sayWatchdogs.delete(w);
829
+ }
830
+ /** The turn's LLM payload: the call's, with the reply language (or the conversation's own variables). */
831
+ turnPayload(language) {
832
+ const base = this.setup().llmPayload;
833
+ return language.payload
834
+ ? { ...base, ...language.payload }
835
+ : { ...base, reply_language: language.replyLanguage, reply_language_provisional: language.provisional, opening_language: language.replyLanguage };
836
+ }
837
+ /** Play options of an LLM turn by its tag. */
838
+ llmPlay(tag) {
839
+ return tag === 'bootstrap' ? this.agent.play.greeting : this.agent.play.llm;
840
+ }
841
+ runLlmTurn(turn, tag, language, opts = {}) {
842
+ if (this.terminated)
843
+ return;
844
+ const { agent, logger } = this;
845
+ if (!opts.keepTrigger)
846
+ this.lastTurnTriggerText = opts.trigger ?? (typeof turn === 'string' ? turn : turn.heard);
847
+ const seq = this.beginTurn();
848
+ const turnStart = Date.now();
849
+ this.llmWaitingSince = turnStart;
850
+ let aggregated = '';
851
+ let firstChunkAt = turnStart;
852
+ let streamEnded = false;
853
+ const payload = this.turnPayload(language);
854
+ const reply$ = this.replyStream(turn, seq, payload, tag).pipe((0, rxjs_1.tap)({ complete: () => { streamEnded = true; } }));
855
+ this.replyRequested(seq, tag);
856
+ const filter = this.call.voice.replyFilter?.({
857
+ seq,
858
+ text: this.lastTurnTriggerText, language: language.replyLanguage, id: tag, silence: this.lastTurnTriggerText === agent.silenceEllipsis,
859
+ request: typeof turn === 'string' ? turn : turn.heard, regenerated: opts.regenerated ?? null,
860
+ agentLines: language.lines?.agent ?? [], callerLines: language.lines?.caller ?? [], state: this.filterState, llmPayload: {},
861
+ channel: this.channel, logger, agent,
862
+ });
863
+ const spoken$ = filter?.stream ? filter.stream(reply$) : reply$;
864
+ const { respell } = this.call.voice;
865
+ const { speechFilter } = this.setup();
866
+ const leakFilter = speechFilter ? new speech_leak_1.SpeechLeakFilter(speechFilter) : null;
867
+ const current$ = spoken$.pipe((0, rxjs_1.takeWhile)((chunk) => this.isCurrent(seq) && !this.replyCut(seq, tag, aggregated, chunk)));
868
+ const aggregated$ = (leakFilter ? current$.pipe((0, speech_leak_1.filterSpeechLeaks)(leakFilter)) : current$).pipe((0, rxjs_1.tap)((chunk) => {
869
+ if (aggregated.length === 0) {
870
+ this.agentSpeaking = true;
871
+ firstChunkAt = Date.now();
872
+ if (this.isCurrent(seq))
873
+ this.llmWaitingSince = 0;
874
+ this.replyStarted(seq);
875
+ }
876
+ aggregated += chunk;
877
+ if (this.isCurrent(seq))
878
+ this.replyProgress(aggregated);
879
+ }));
880
+ const play = this.llmPlay(tag);
881
+ const text$ = respell ? respell.reply(aggregated$, tag) : aggregated$;
882
+ const unit = play.alias ?? tag;
883
+ let settled = false;
884
+ const watchdog = this.armSayWatchdog(() => {
885
+ if (settled)
886
+ return;
887
+ settled = true;
888
+ if (!this.isCurrent(seq))
889
+ return;
890
+ logger.log('perf', { event: 'agent_reply_say_timeout', tag, replyLen: aggregated.length });
891
+ if (aggregated.length > 0)
892
+ this.emit({ type: 'SPOKEN', text: aggregated, unit });
893
+ this.clearAgentSpeaking();
894
+ if (this.callEnding || this.terminated)
895
+ return;
896
+ this.emit({ type: 'DRAINED', m: this.snapshot() });
897
+ });
898
+ const blocks = this.replyBlocksBargeIn(tag);
899
+ if (blocks != null)
900
+ this.greetingOnWire = blocks;
901
+ const unblock = () => {
902
+ if (blocks && this.isCurrent(seq))
903
+ this.greetingOnWire = false;
904
+ };
905
+ void this.channel.audio.say(text$, { ...play, tts: this.tts ?? undefined }).then(async () => {
906
+ this.settleWatchdog(watchdog);
907
+ if (settled)
908
+ return;
909
+ settled = true;
910
+ try {
911
+ if (!this.isCurrent(seq)) {
912
+ logger.log('perf', { event: 'agent_reply_superseded', tag, replyLen: aggregated.length });
913
+ this.replyPlayed(aggregated, false, tag);
914
+ // A superseded reply that streamed text: the LLM answers.
915
+ if (aggregated.trim().length > 0)
916
+ this.resetEmptyCounts();
917
+ return;
918
+ }
919
+ this.llmWaitingSince = 0;
920
+ // A reply cut while filters held part of it: that part counts as said (the transcript reads the LLM's text).
921
+ aggregated += this.heldBack(seq);
922
+ const suppressed = leakFilter?.suppressed ?? [];
923
+ if (suppressed.length > 0) {
924
+ aggregated = aggregated.trim();
925
+ logger.log('llm_reply_leak_suppressed', { tag, suppressed, spokenLen: aggregated.length });
926
+ }
927
+ const end = { turn, tag, language, aggregated, suppressed, turnStart, firstChunkAt, seq, opts };
928
+ if (this.replyRetried(end))
929
+ return;
930
+ if (agent.emptyReply && tag !== 'bootstrap') {
931
+ if (this.emptyPolicy(end, streamEnded, opts))
932
+ return;
933
+ }
934
+ else if (agent.emptyReply) {
935
+ // The greeting: an empty one counts toward the limit; it is not asked again.
936
+ if (aggregated.trim().length === 0)
937
+ this.emptyStreak += 1;
938
+ else
939
+ this.resetEmptyCounts();
940
+ }
941
+ else if (aggregated.trim().length === 0) {
942
+ if (!this.emptyReplyRetried && (agent.emptyReplyRetries ?? 1) > 0 && !this.callEnding && !this.terminated) {
943
+ this.emptyReplyRetried = true;
944
+ logger.log('agent_reply_empty_retry', { tag });
945
+ this.emptyReplyAskedAgain(seq);
946
+ this.runLlmTurn(agent.silenceEllipsis, tag, language);
947
+ return;
948
+ }
949
+ if (agent.hangupOnSecondEmptyReply === true) {
950
+ if (!this.callEnding && !this.terminated) {
951
+ logger.log('agent_reply_empty_twice, hanging up', { tag });
952
+ this.clearAgentSpeaking();
953
+ this.emit({ type: 'RESULT', result: LLM_FAILURE });
954
+ await this.hangupAfterPlayback('llm_failure', Promise.resolve());
955
+ }
956
+ return;
957
+ }
958
+ }
959
+ else {
960
+ this.emptyReplyRetried = false;
961
+ }
962
+ const isTransfer = this.isTransferReply(aggregated);
963
+ const isGoodbye = !isTransfer && agent.conversation.endsWithGoodbyeMarker(aggregated);
964
+ const msAfterTurnStart = Date.now() - turnStart;
965
+ this.emit({ type: 'SPOKEN', text: aggregated, unit });
966
+ logger.log('perf', {
967
+ event: 'agent_reply_say_done', tag, msAfterTurnStart, isGoodbye, replyLen: aggregated.length,
968
+ ...this.replyDoneLogFields(isTransfer),
969
+ });
970
+ if (isTransfer && this.transferReply(end))
971
+ return;
972
+ if (isGoodbye && agent.goodbyeOpenUntilFloor) {
973
+ // The goodbye is a reply until its floor passed: a line of the caller's meanwhile takes the call over.
974
+ const floor = this.goodbyeFloor;
975
+ const ceilingMs = this.drainCeilingFor(aggregated);
976
+ let floorMs = 0;
977
+ if (floor) {
978
+ const since = floor.from === 'turnStart' ? turnStart : floor.from === 'firstChunk' ? firstChunkAt : (this.turnFirstItemStartedAt ?? Date.now());
979
+ floorMs = Math.max(0, Math.min(Math.max(spokenLength(aggregated) * floor.msPerChar, floor.minMs), ceilingMs) - (Date.now() - since));
980
+ if (floorMs > 0)
981
+ await delay(floorMs);
982
+ }
983
+ if (!this.isCurrent(seq)) {
984
+ logger.log('perf', { event: 'goodbye_superseded', tag, msAfterTurnStart: Date.now() - turnStart });
985
+ return;
986
+ }
987
+ if (this.callEnding || this.terminated)
988
+ return;
989
+ this.emit({ type: 'RESULT', result: GOODBYE });
990
+ await this.hangupAfterPlayback('goodbye_reply', this.awaitTtsQueueDrain(Math.max(0, ceilingMs - floorMs)), this.closeCeilingFor(aggregated));
991
+ return;
992
+ }
993
+ if (isGoodbye) {
994
+ this.emit({ type: 'RESULT', result: GOODBYE });
995
+ if (agent.emptyGoodbyeHangsUpNow && !/[\p{L}\p{N}]/u.test(aggregated)) {
996
+ await this.hangupAfterPlayback('goodbye_reply_empty', Promise.resolve(), undefined, 0);
997
+ return;
998
+ }
999
+ const hangup = this.hangupAfterPlayback('goodbye_reply', this.awaitPlayedOut(aggregated, this.goodbyeFloor, { turnStart, firstChunkAt }, seq), this.closeCeilingFor(aggregated));
1000
+ // From here caller finals reach a closing call: speech buffered over the goodbye gets its look now.
1001
+ if (agent.reopenOnSpeech)
1002
+ this.emit({ type: 'GOODBYE_STARTED', m: this.snapshot() });
1003
+ await hangup;
1004
+ return;
1005
+ }
1006
+ await this.awaitPlayedOut(aggregated, this.replyFloor, { turnStart, firstChunkAt }, seq);
1007
+ unblock();
1008
+ // Heard: played to the end, still the current turn, not cut by the caller.
1009
+ this.replyPlayed(aggregated, this.isCurrent(seq) && !this.agentTurnInterrupted, tag);
1010
+ this.drained(seq);
1011
+ }
1012
+ catch (err) {
1013
+ this.turnEndFailed('agent_reply_end_failed', seq, err, { tag }, unblock);
1014
+ }
1015
+ }, (err) => {
1016
+ this.settleWatchdog(watchdog);
1017
+ const superseded = !this.isCurrent(seq);
1018
+ logger.log('perf', { event: 'agent_reply_say_error', tag, superseded, err: String(err) });
1019
+ if (settled)
1020
+ return;
1021
+ settled = true;
1022
+ unblock();
1023
+ if (!superseded)
1024
+ this.clearAgentSpeaking();
1025
+ if (superseded || this.callEnding || this.terminated)
1026
+ return;
1027
+ this.emit({ type: 'DRAINED', m: this.snapshot() });
1028
+ });
1029
+ }
1030
+ /**
1031
+ * What the caller heard of an LLM reply (not a goodbye): `heard` when it played to the end as the current turn and
1032
+ * nobody cut it; not heard when superseded, cut, or asked again before its stream ended.
1033
+ */
1034
+ replyPlayed(_text, _heard, _tag) {
1035
+ /* none */
1036
+ }
1037
+ /** The reply language (and prompt variables) a reply cut before its stream ended is asked again with. */
1038
+ abortedRetryLanguage(language) {
1039
+ return language;
1040
+ }
1041
+ /** The text a reply cut before its stream ended is asked again with (default: the text it was asked with). */
1042
+ abortedRetryText(text, _opts) {
1043
+ return text;
1044
+ }
1045
+ /** An LLM turn was requested (its reply has not streamed yet). */
1046
+ /** The reply of the current turn so far (every chunk). */
1047
+ replyProgress(_textSoFar) {
1048
+ /* nothing by default */
1049
+ }
1050
+ replyRequested(_seq, _tag) {
1051
+ /* none */
1052
+ }
1053
+ /** The first chunk of turn `seq` streamed. */
1054
+ replyStarted(_seq) {
1055
+ /* none */
1056
+ }
1057
+ /** Whether a reply of this tag plays out whole (barge-in off until it drains); undefined: as it is. */
1058
+ replyBlocksBargeIn(_tag) {
1059
+ return undefined;
1060
+ }
1061
+ /** A reply the conversation part asks again (true: a new turn was started). */
1062
+ replyRetried(_end) {
1063
+ return false;
1064
+ }
1065
+ /** The reply stream of turn `seq` stops here (nothing more of it is spoken), given what was said so far. */
1066
+ replyCut(_seq, _tag, _soFar, _next) {
1067
+ return false;
1068
+ }
1069
+ /** An empty reply of turn `seq` is asked again (what the reply carried, e.g. its tool call, may go to the retry). */
1070
+ emptyReplyAskedAgain(_seq) { }
1071
+ /** An empty reply that is not counted (its tool call was refused). */
1072
+ replyExempt(_seq) {
1073
+ return false;
1074
+ }
1075
+ /** The turn's LLM stream carried the error event. */
1076
+ replyErrored(_seq) {
1077
+ return false;
1078
+ }
1079
+ /** The text the turn sent to the LLM (what `retry: 'same'` sends again). */
1080
+ sentText(turn, _seq) {
1081
+ return typeof turn === 'string' ? turn : turn.heard;
1082
+ }
1083
+ /** A reply with text (or one the conversation replaced): the empty counts and the probe ladder start over. */
1084
+ resetEmptyCounts() {
1085
+ this.emptyStreak = 0;
1086
+ this.abortedRetries = 0;
1087
+ this.probesUsed = 0;
1088
+ }
1089
+ /** `emptyReply`: an empty reply asked again or counted (true: handled — a new turn, or the limit reached). */
1090
+ emptyPolicy(end, streamEnded, opts) {
1091
+ const policy = this.agent.emptyReply;
1092
+ const { aggregated, tag, turnStart, language, seq, turn } = end;
1093
+ const { logger } = this;
1094
+ if (aggregated.trim().length > 0) {
1095
+ this.resetEmptyCounts();
1096
+ return false;
1097
+ }
1098
+ if (this.callEnding || this.terminated || this.replyExempt(seq))
1099
+ return false;
1100
+ const errored = this.replyErrored(seq);
1101
+ const again = (text, lang = language) => this.runLlmTurn(text, tag, lang, {
1102
+ keepTrigger: opts.keepTrigger, refusedRetry: opts.refusedRetry,
1103
+ ...(opts.trigger != null ? { trigger: opts.trigger } : {}), ...(opts.retryText != null ? { retryText: opts.retryText } : {}),
1104
+ });
1105
+ if (!streamEnded && !errored && this.abortedRetries < policy.abortedRetries) {
1106
+ // The playback ended before the stream did (cut by the previous turn's stop): asked again, not counted.
1107
+ this.abortedRetries += 1;
1108
+ logger.log('agent_reply_aborted_before_stream_end', { tag, abortedTurnRetries: this.abortedRetries, msAfterTurnStart: Date.now() - turnStart });
1109
+ this.replyPlayed(aggregated, false, tag);
1110
+ again(this.abortedRetryText(opts.retryText ?? this.sentText(turn, seq), opts), this.abortedRetryLanguage(language));
1111
+ return true;
1112
+ }
1113
+ this.emptyStreak += 1;
1114
+ if (this.emptyStreak >= policy.max) {
1115
+ if (this.probesUsed < (policy.probes ?? 0)) {
1116
+ // A probe line first: the count starts over, the ladder moves one rung.
1117
+ this.probesUsed += 1;
1118
+ this.emptyStreak = 0;
1119
+ logger.log('llm_unavailable_probe', { tag, probe: this.probesUsed, llmErrored: errored, msAfterTurnStart: Date.now() - turnStart });
1120
+ this.emit({ type: 'EMPTY_EXHAUSTED', errored, probe: this.probesUsed, m: this.snapshot() });
1121
+ return true;
1122
+ }
1123
+ logger.log('llm_unavailable_hangup', { tag, emptyLlmStreak: this.emptyStreak, llmErrored: errored, msAfterTurnStart: Date.now() - turnStart });
1124
+ this.emit({ type: 'EMPTY_EXHAUSTED', errored, m: this.snapshot() });
1125
+ return true;
1126
+ }
1127
+ if (!errored && policy.retry !== 'none') {
1128
+ logger.log('agent_reply_empty_retry', { tag, msAfterTurnStart: Date.now() - turnStart });
1129
+ this.emptyReplyAskedAgain(seq);
1130
+ again(policy.retry === 'same' ? opts.retryText ?? this.sentText(turn, seq) : this.agent.silenceEllipsis);
1131
+ return true;
1132
+ }
1133
+ return false;
1134
+ }
1135
+ /** A reply that hands the call over (the conversation part's transfer). */
1136
+ isTransferReply(_text) {
1137
+ return false;
1138
+ }
1139
+ replyDoneLogFields(_isTransfer) {
1140
+ return {};
1141
+ }
1142
+ /** The transfer the reply asked for (true: it took the call over). */
1143
+ transferReply(_end) {
1144
+ return false;
1145
+ }
1146
+ /** Ceiling of the wait before a closing hangup (undefined: the lifecycle's drain timeout). */
1147
+ closeCeilingFor(_text) {
1148
+ return undefined;
1149
+ }
1150
+ runStaticTurn(text, alias, opts = {}) {
1151
+ if (this.terminated)
1152
+ return;
1153
+ const { logger } = this;
1154
+ const { hangupReason } = opts;
1155
+ const seq = this.beginTurn();
1156
+ this.llmWaitingSince = 0;
1157
+ if (hangupReason != null)
1158
+ this.closingPhraseActive = true;
1159
+ this.greetingOnWire = opts.blocksBargeIn === true;
1160
+ this.agentSpeaking = true;
1161
+ const turnStart = Date.now();
1162
+ let settled = false;
1163
+ const done = () => {
1164
+ if (this.isCurrent(seq))
1165
+ this.greetingOnWire = false;
1166
+ };
1167
+ const closeCeilingMs = this.closeCeilingFor(text);
1168
+ const watchdog = this.armSayWatchdog(() => {
1169
+ if (settled)
1170
+ return;
1171
+ settled = true;
1172
+ if (!this.isCurrent(seq))
1173
+ return;
1174
+ logger.log('perf', { event: 'static_turn_say_timeout', alias });
1175
+ this.emit({ type: 'SPOKEN', text, unit: alias });
1176
+ this.clearAgentSpeaking();
1177
+ done();
1178
+ if (hangupReason != null) {
1179
+ void this.hangupAfterPlayback(hangupReason, Promise.resolve(), closeCeilingMs);
1180
+ return;
1181
+ }
1182
+ if (this.callEnding || this.terminated)
1183
+ return;
1184
+ this.emit({ type: 'DRAINED', m: this.snapshot() });
1185
+ });
1186
+ const said = opts.parts?.length
1187
+ ? this.sayParts(opts.parts, alias, seq)
1188
+ : this.sayWhole(text, alias, seq);
1189
+ void said.then(async (saidText) => {
1190
+ this.settleWatchdog(watchdog);
1191
+ if (settled)
1192
+ return;
1193
+ settled = true;
1194
+ try {
1195
+ if (!this.isCurrent(seq)) {
1196
+ logger.log('perf', { event: 'static_turn_superseded', alias });
1197
+ return;
1198
+ }
1199
+ this.emit({ type: 'SPOKEN', text: saidText, unit: alias });
1200
+ const at = { turnStart, firstChunkAt: turnStart };
1201
+ if (hangupReason != null) {
1202
+ await this.hangupAfterPlayback(hangupReason, this.awaitPlayedOut(text, staticFloor(this.goodbyeFloor), at, seq), closeCeilingMs);
1203
+ return;
1204
+ }
1205
+ await this.awaitPlayedOut(text, staticFloor(this.replyFloor), at, seq);
1206
+ done();
1207
+ this.drained(seq);
1208
+ }
1209
+ catch (err) {
1210
+ this.turnEndFailed('static_turn_end_failed', seq, err, { alias }, done, hangupReason);
1211
+ }
1212
+ }, (err) => {
1213
+ this.settleWatchdog(watchdog);
1214
+ const superseded = !this.isCurrent(seq);
1215
+ logger.log('perf', { event: 'static_turn_say_error', alias, superseded, err: String(err) });
1216
+ if (settled)
1217
+ return;
1218
+ settled = true;
1219
+ if (!superseded)
1220
+ this.clearAgentSpeaking();
1221
+ done();
1222
+ if (hangupReason != null) {
1223
+ void this.hangupAfterPlayback(hangupReason, Promise.resolve(), closeCeilingMs);
1224
+ return;
1225
+ }
1226
+ if (superseded || this.callEnding || this.terminated)
1227
+ return;
1228
+ this.emit({ type: 'DRAINED', m: this.snapshot() });
1229
+ });
1230
+ }
1231
+ /** A fixed line said at once; the moment its first audio starts is the start of its last (only) part. */
1232
+ async sayWhole(text, alias, seq) {
1233
+ this.watchLastPart(alias, seq);
1234
+ const spoken = this.call.voice.respell?.phrase(text) ?? text;
1235
+ await this.channel.audio.say(spoken, { ...this.agent.play.llm, alias, tts: this.tts ?? undefined });
1236
+ return text;
1237
+ }
1238
+ /** A fixed line said part by part, each once the one before it is synthesized; a cut turn stops the rest. */
1239
+ async sayParts(parts, alias, seq) {
1240
+ const last = parts.length - 1;
1241
+ const said = [];
1242
+ for (const [i, part] of parts.entries()) {
1243
+ if (!this.isCurrent(seq) || this.agentTurnInterrupted || this.terminated)
1244
+ break;
1245
+ const partAlias = `${alias}-${i}`;
1246
+ if (i === last)
1247
+ this.watchLastPart(partAlias, seq);
1248
+ const spoken = this.call.voice.respell?.phrase(part) ?? part;
1249
+ try {
1250
+ await this.channel.audio.say(spoken, { ...this.agent.play.llm, alias: partAlias, tts: this.tts ?? undefined });
1251
+ // A part the hangup cut off before it was handed over is not said.
1252
+ if (this.terminated)
1253
+ break;
1254
+ said.push(part);
1255
+ }
1256
+ catch (err) {
1257
+ if (i === last && !said.length)
1258
+ throw err;
1259
+ this.logger.log('static_part_say_error', { alias: partAlias, err: String(err) });
1260
+ }
1261
+ }
1262
+ return said.join(' ');
1263
+ }
1264
+ /** Note when the first audio of a line's last part starts (`<alias>` or one of its items `<alias>-<n>`). */
1265
+ watchLastPart(alias, seq) {
1266
+ this.lastPartWatch?.unsubscribe();
1267
+ const q = this.channel.audio.queue(this.agent.queues.tts);
1268
+ const sub = q.itemStarted$.subscribe((a) => {
1269
+ if (a !== alias && !a.startsWith(`${alias}-`))
1270
+ return;
1271
+ sub.unsubscribe();
1272
+ if (this.isCurrent(seq))
1273
+ this.lastPartStartedAtMs = Date.now();
1274
+ });
1275
+ this.lastPartWatch = sub;
1276
+ }
1277
+ // ── drain ────────────────────────────────────────────────────────────────────
1278
+ get replyFloor() {
1279
+ const f = this.agent.replyFloor;
1280
+ return f === undefined ? exports.DEFAULT_REPLY_FLOOR : f;
1281
+ }
1282
+ get goodbyeFloor() {
1283
+ const f = this.agent.goodbyeFloor;
1284
+ if (f !== undefined)
1285
+ return f;
1286
+ return this.agent.farewellDrain === 'reply' ? this.replyFloor : exports.DEFAULT_GOODBYE_FLOOR;
1287
+ }
1288
+ drainCeilingFor(text) {
1289
+ const { ttsDrainTimeoutMs, ttsDrainMsPerChar } = this.agent.lifecycle;
1290
+ return Math.max(ttsDrainTimeoutMs, text.length * ttsDrainMsPerChar);
1291
+ }
1292
+ awaitTtsQueueDrain(ceilingMs) {
1293
+ if (this.pending === 0)
1294
+ return Promise.resolve();
1295
+ const q = this.channel.audio.queue(this.agent.queues.tts);
1296
+ // A source that completes without a value (a channel closed after the hangup) ends the wait, not fails it.
1297
+ return (0, rxjs_1.firstValueFrom)((0, rxjs_1.race)(q.queueEmpty$, this.channel.events.terminated$, (0, rxjs_1.timer)(ceilingMs)), { defaultValue: undefined }).then(() => undefined);
1298
+ }
1299
+ /**
1300
+ * The line had time to play out: its floor (counted as the floor says), then the agent queue's drain, all under
1301
+ * the ceiling. Without a floor: the queue's own drain (a line that has not started playing yet is waited for).
1302
+ */
1303
+ async awaitPlayedOut(text, floor, at, seq) {
1304
+ const ceilingMs = this.drainCeilingFor(text);
1305
+ if (floor == null) {
1306
+ await this.awaitQueueDrained(text, ceilingMs, seq);
1307
+ return;
1308
+ }
1309
+ // `playbackStart`: credited with what already played; nothing played yet counts from now.
1310
+ // `spokenChunk`: the first chunk that reached TTS; a reply nothing of which was spoken counts from now.
1311
+ const since = floor.from === 'turnStart' ? at.turnStart
1312
+ : floor.from === 'firstChunk' ? at.firstChunkAt
1313
+ : floor.from === 'spokenChunk' ? (spokenLength(text) > 0 ? at.firstChunkAt : Date.now())
1314
+ : (this.turnFirstItemStartedAt ?? Date.now());
1315
+ const floorMs = Math.max(0, Math.min(Math.max(spokenLength(text) * floor.msPerChar, floor.minMs), ceilingMs) - (Date.now() - since));
1316
+ if (floorMs > 0)
1317
+ await delay(floorMs);
1318
+ await this.awaitAfterFloor(text, Math.max(0, ceilingMs - floorMs), seq);
1319
+ }
1320
+ /** The wait after the floor: the agent queue's drain. */
1321
+ async awaitAfterFloor(_text, ceilingMs, _seq) {
1322
+ await this.awaitTtsQueueDrain(ceilingMs);
1323
+ }
1324
+ /** No floor: the line played out when the agent queue ran dry (an empty line: at once). */
1325
+ async awaitQueueDrained(text, ceilingMs, seq) {
1326
+ if (!spokenLength(text) || !this.isCurrent(seq))
1327
+ return;
1328
+ const q = this.channel.audio.queue(this.agent.queues.tts);
1329
+ const deadline = Date.now() + ceilingMs;
1330
+ if (this.pending === 0 && this.turnFirstItemStartedAt == null) {
1331
+ const started = await (0, rxjs_1.firstValueFrom)((0, rxjs_1.race)(this.itemStarted.pipe((0, rxjs_1.map)(() => true)), this.channel.events.terminated$.pipe((0, rxjs_1.map)(() => false)), (0, rxjs_1.timer)(Math.min(NO_FLOOR_START_ALLOWANCE_MS, ceilingMs)).pipe((0, rxjs_1.map)(() => false))), { defaultValue: false });
1332
+ if (!started)
1333
+ return;
1334
+ }
1335
+ if (this.pending === 0)
1336
+ return;
1337
+ await (0, rxjs_1.firstValueFrom)((0, rxjs_1.race)(q.queueEmpty$, this.channel.events.terminated$, (0, rxjs_1.timer)(Math.max(0, deadline - Date.now()))), { defaultValue: undefined });
1338
+ }
1339
+ // ── hangup ───────────────────────────────────────────────────────────────────
1340
+ async hangupAfterPlayback(reason, drained, ceilingMs, tailMs = this.agent.lifecycle.rtpTailGraceMs) {
1341
+ if (this.ending)
1342
+ return;
1343
+ this.ending = true;
1344
+ const generation = this.hangupGeneration;
1345
+ this.am.setCallEnding(true);
1346
+ this.logger.log('goodbye detected, draining TTS queue before hangup', { reason, ...(ceilingMs != null ? { ceilingMs } : {}) });
1347
+ this.hangupWaiting = true;
1348
+ try {
1349
+ await Promise.race([drained, delay(ceilingMs ?? this.agent.lifecycle.ttsDrainTimeoutMs)]);
1350
+ if (this.terminated || generation !== this.hangupGeneration)
1351
+ return;
1352
+ // The RTP tail is waited here, not by the runtime's strategy: a leg that terminates within it is not hung up
1353
+ // again (the runtime's tail does not look).
1354
+ if (tailMs > 0)
1355
+ await delay(tailMs);
1356
+ if (this.terminated || generation !== this.hangupGeneration)
1357
+ return;
1358
+ }
1359
+ finally {
1360
+ this.hangupWaiting = false;
1361
+ }
1362
+ this.hangupSent = true;
1363
+ await this.lifecycle.hangup(reason, { strategy: lifecycle_1.HangupStrategy.immediate({ rtpTailMs: 0 }) });
1364
+ }
1365
+ /**
1366
+ * Undo a hangup that waits for its line to play out, so the conversation goes on (the caller was still talking).
1367
+ * `false`, changing nothing, when no hangup waits or it was already sent.
1368
+ */
1369
+ cancelHangup(reason) {
1370
+ if (!this.ending || this.terminated || this.hangupSent)
1371
+ return false;
1372
+ this.ending = false;
1373
+ this.hangupGeneration += 1;
1374
+ this.am.setCallEnding(false);
1375
+ this.logger.log('hangup cancelled', { reason });
1376
+ return true;
1377
+ }
1378
+ }
1379
+ exports.CallVoice = CallVoice;
1380
+ /** ASR finals rewritten before anything reads them (first matching correction). */
1381
+ function applyAsrCorrections(text, corrections = []) {
1382
+ const t = text.trim();
1383
+ if (!t)
1384
+ return t;
1385
+ for (const { pattern, replacement } of corrections) {
1386
+ const next = t.replace(pattern, replacement).trim();
1387
+ if (next !== t)
1388
+ return next;
1389
+ }
1390
+ return t;
1391
+ }
1392
+ exports.applyAsrCorrections = applyAsrCorrections;
1393
+ /** The floor of a fixed line: counted as `staticFrom` says. */
1394
+ function staticFloor(f) {
1395
+ return f && f.staticFrom != null ? { ...f, from: f.staticFrom } : f;
1396
+ }
1397
+ function delay(ms) {
1398
+ return new Promise((resolve) => setTimeout(resolve, ms));
1399
+ }