@voctiv/agent-runtime 0.2.2 → 0.4.1

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 (632) hide show
  1. package/README.md +53 -20
  2. package/bin/voctiv-agent-check.js +98 -0
  3. package/dist/barge-in/barge-in-module.d.ts +0 -1
  4. package/dist/barge-in/barge-in-module.js +0 -1
  5. package/dist/barge-in/barge-in-service.d.ts +1 -1
  6. package/dist/barge-in/barge-in-service.js +33 -2
  7. package/dist/barge-in/barge-in-strategy.d.ts +11 -9
  8. package/dist/barge-in/barge-in-strategy.js +39 -23
  9. package/dist/barge-in/echo-cancellation.d.ts +0 -1
  10. package/dist/barge-in/echo-cancellation.js +0 -1
  11. package/dist/barge-in/echo.d.ts +0 -1
  12. package/dist/barge-in/echo.js +0 -1
  13. package/dist/barge-in/lexicon.d.ts +0 -1
  14. package/dist/barge-in/lexicon.js +0 -1
  15. package/dist/barge-in/speech-ledger.d.ts +0 -2
  16. package/dist/barge-in/speech-ledger.js +3 -4
  17. package/dist/barge-in/word-classifier.d.ts +0 -1
  18. package/dist/barge-in/word-classifier.js +0 -1
  19. package/dist/call/asr-usage.d.ts +53 -0
  20. package/dist/call/asr-usage.js +42 -0
  21. package/dist/call/async.d.ts +2 -0
  22. package/dist/call/async.js +14 -0
  23. package/dist/call/env.d.ts +88 -0
  24. package/dist/call/env.js +294 -0
  25. package/dist/call/extraction/core.d.ts +99 -0
  26. package/dist/call/extraction/core.js +259 -0
  27. package/dist/call/extraction/defaults.d.ts +10 -0
  28. package/dist/call/extraction/defaults.js +25 -0
  29. package/dist/call/extraction/index.d.ts +7 -0
  30. package/dist/call/extraction/index.js +24 -0
  31. package/dist/call/extraction/orchestrator.d.ts +144 -0
  32. package/dist/call/extraction/orchestrator.js +309 -0
  33. package/dist/call/failed-leg.d.ts +43 -0
  34. package/dist/call/failed-leg.js +77 -0
  35. package/dist/call/http.d.ts +94 -0
  36. package/dist/call/http.js +145 -0
  37. package/dist/call/ledger.d.ts +18 -0
  38. package/dist/call/ledger.js +80 -0
  39. package/dist/call/llm-tap.d.ts +7 -0
  40. package/dist/call/llm-tap.js +41 -0
  41. package/dist/call/logging.d.ts +16 -0
  42. package/dist/call/logging.js +92 -0
  43. package/dist/call/outbound.d.ts +144 -0
  44. package/dist/call/outbound.js +404 -0
  45. package/dist/call/output.d.ts +108 -0
  46. package/dist/call/output.js +77 -0
  47. package/dist/call/plan.d.ts +119 -0
  48. package/dist/call/plan.js +2 -0
  49. package/dist/call/recall.d.ts +115 -0
  50. package/dist/call/recall.js +312 -0
  51. package/dist/call/records.d.ts +9 -0
  52. package/dist/call/records.js +71 -0
  53. package/dist/call/report.d.ts +65 -0
  54. package/dist/call/report.js +263 -0
  55. package/dist/call/sanitize.d.ts +16 -0
  56. package/dist/call/sanitize.js +72 -0
  57. package/dist/call/sip.d.ts +111 -0
  58. package/dist/call/sip.js +212 -0
  59. package/dist/call/voicemail.d.ts +159 -0
  60. package/dist/call/voicemail.js +246 -0
  61. package/dist/core/call-disposables.d.ts +2 -2
  62. package/dist/core/call-disposables.js +8 -3
  63. package/dist/core/call-ended-budget.d.ts +11 -0
  64. package/dist/core/call-ended-budget.js +31 -0
  65. package/dist/core/container.d.ts +1 -3
  66. package/dist/core/container.js +9 -49
  67. package/dist/core/create-agent-script.d.ts +6 -1
  68. package/dist/core/create-agent-script.js +161 -28
  69. package/dist/core/decorators.d.ts +0 -1
  70. package/dist/core/decorators.js +0 -1
  71. package/dist/core/define-module.d.ts +0 -1
  72. package/dist/core/define-module.js +0 -1
  73. package/dist/core/dump-policy.d.ts +0 -1
  74. package/dist/core/dump-policy.js +0 -1
  75. package/dist/core/hooks.d.ts +15 -4
  76. package/dist/core/hooks.js +0 -1
  77. package/dist/core/media-bootstrap.d.ts +19 -4
  78. package/dist/core/media-bootstrap.js +53 -13
  79. package/dist/core/open-timeout.d.ts +12 -0
  80. package/dist/core/open-timeout.js +48 -0
  81. package/dist/core/provide-media.d.ts +0 -8
  82. package/dist/core/provide-media.js +1 -22
  83. package/dist/core/runtime-events.d.ts +28 -0
  84. package/dist/{llm/llm-module.js → core/runtime-events.js} +19 -16
  85. package/dist/core/tokens.d.ts +0 -10
  86. package/dist/core/tokens.js +0 -1
  87. package/dist/core/types.d.ts +0 -1
  88. package/dist/core/types.js +0 -1
  89. package/dist/core/version.d.ts +2 -3
  90. package/dist/core/version.js +2 -3
  91. package/dist/dialog/dialog-definition.d.ts +0 -5
  92. package/dist/dialog/dialog-definition.js +1 -6
  93. package/dist/dialog/dialog-ports.d.ts +3 -1
  94. package/dist/dialog/dialog-ports.js +10 -2
  95. package/dist/dialog/online-call-host.d.ts +26 -4
  96. package/dist/dialog/online-call-host.js +94 -12
  97. package/dist/dialog/online-call-module.d.ts +5 -11
  98. package/dist/dialog/online-call-module.js +4 -36
  99. package/dist/dialog/turn-metrics.d.ts +46 -0
  100. package/dist/dialog/turn-metrics.js +141 -0
  101. package/dist/dialog-events/active-media.d.ts +50 -2
  102. package/dist/dialog-events/active-media.js +146 -34
  103. package/dist/dialog-events/event-source.d.ts +0 -1
  104. package/dist/dialog-events/event-source.js +0 -1
  105. package/dist/dialog-events/virtual-finals-module.d.ts +0 -1
  106. package/dist/dialog-events/virtual-finals-module.js +0 -1
  107. package/dist/dialog-events/virtual-finals.d.ts +2 -1
  108. package/dist/dialog-events/virtual-finals.js +1 -1
  109. package/dist/index.d.ts +1 -4
  110. package/dist/index.js +8 -26
  111. package/dist/lifecycle/lifecycle.d.ts +25 -3
  112. package/dist/lifecycle/lifecycle.js +92 -14
  113. package/dist/result/result-store.d.ts +0 -1
  114. package/dist/result/result-store.js +0 -1
  115. package/dist/templates/authoring.d.ts +222 -0
  116. package/dist/templates/authoring.js +2 -0
  117. package/dist/templates/builder/agent.d.ts +34 -0
  118. package/dist/templates/builder/agent.js +87 -0
  119. package/dist/templates/builder/blocks.d.ts +54 -0
  120. package/dist/templates/builder/blocks.js +92 -0
  121. package/dist/templates/builder/data-check.d.ts +2 -0
  122. package/dist/templates/builder/data-check.js +61 -0
  123. package/dist/templates/builder/draft.d.ts +73 -0
  124. package/dist/templates/builder/draft.js +142 -0
  125. package/dist/templates/builder/index.d.ts +8 -0
  126. package/dist/templates/builder/index.js +55 -0
  127. package/dist/templates/builder/presets.d.ts +34 -0
  128. package/dist/templates/builder/presets.js +45 -0
  129. package/dist/templates/builder/spec-of.d.ts +13 -0
  130. package/dist/templates/builder/spec-of.js +18 -0
  131. package/dist/templates/builder/steps.d.ts +25 -0
  132. package/dist/templates/builder/steps.js +27 -0
  133. package/dist/templates/business/adapter.d.ts +12 -0
  134. package/dist/templates/business/adapter.js +980 -0
  135. package/dist/templates/business/agent-integrations.d.ts +24 -0
  136. package/dist/templates/business/agent-integrations.js +233 -0
  137. package/dist/templates/business/extraction-rules-transcript.d.ts +158 -0
  138. package/dist/templates/business/extraction-rules-transcript.js +405 -0
  139. package/dist/templates/business/extraction-rules.d.ts +107 -0
  140. package/dist/templates/business/extraction-rules.js +267 -0
  141. package/dist/templates/business/index.d.ts +6 -0
  142. package/dist/{result → templates/business}/index.js +8 -2
  143. package/dist/templates/business/input.d.ts +56 -0
  144. package/dist/templates/business/input.js +299 -0
  145. package/dist/templates/business/integration-data.d.ts +87 -0
  146. package/dist/templates/business/integration-data.js +312 -0
  147. package/dist/templates/business/integrations.d.ts +76 -0
  148. package/dist/templates/business/integrations.js +535 -0
  149. package/dist/templates/business/legs-policy.d.ts +43 -0
  150. package/dist/templates/business/legs-policy.js +268 -0
  151. package/dist/templates/business/report-label.d.ts +7 -0
  152. package/dist/templates/business/report-label.js +29 -0
  153. package/dist/templates/business/report.d.ts +67 -0
  154. package/dist/templates/business/report.js +284 -0
  155. package/dist/templates/business/result-catalog.d.ts +142 -0
  156. package/dist/templates/business/result-catalog.js +208 -0
  157. package/dist/templates/business/result-rules.d.ts +105 -0
  158. package/dist/templates/business/result-rules.js +167 -0
  159. package/dist/templates/business/results.d.ts +73 -0
  160. package/dist/templates/business/results.js +183 -0
  161. package/dist/templates/business/rule-env.d.ts +18 -0
  162. package/dist/templates/business/rule-env.js +38 -0
  163. package/dist/templates/business/sources.d.ts +76 -0
  164. package/dist/templates/business/sources.js +239 -0
  165. package/dist/templates/business/test-presets.d.ts +10 -0
  166. package/dist/templates/business/test-presets.js +68 -0
  167. package/dist/templates/catalog-match/block.d.ts +32 -0
  168. package/dist/templates/catalog-match/block.js +95 -0
  169. package/dist/templates/catalog-match/catalog.d.ts +77 -0
  170. package/dist/templates/catalog-match/catalog.js +222 -0
  171. package/dist/templates/catalog-match/recognizer.d.ts +44 -0
  172. package/dist/templates/catalog-match/recognizer.js +206 -0
  173. package/dist/templates/catalog-match/reconcile.d.ts +4 -0
  174. package/dist/templates/catalog-match/reconcile.js +39 -0
  175. package/dist/templates/catalog-match/request.d.ts +57 -0
  176. package/dist/templates/catalog-match/request.js +139 -0
  177. package/dist/templates/catalog-match/types.d.ts +197 -0
  178. package/dist/templates/catalog-match/types.js +2 -0
  179. package/dist/templates/catalog-match/verify.d.ts +76 -0
  180. package/dist/templates/catalog-match/verify.js +220 -0
  181. package/dist/templates/decision-model/index.d.ts +52 -0
  182. package/dist/templates/decision-model/index.js +68 -0
  183. package/dist/templates/engine/asr-picks.d.ts +11 -0
  184. package/dist/templates/engine/asr-picks.js +44 -0
  185. package/dist/templates/engine/call.d.ts +104 -0
  186. package/dist/templates/engine/call.js +322 -0
  187. package/dist/templates/engine/config.d.ts +447 -0
  188. package/dist/templates/engine/config.js +493 -0
  189. package/dist/templates/engine/define.d.ts +1 -0
  190. package/dist/templates/engine/define.js +9 -0
  191. package/dist/templates/engine/dialog.d.ts +253 -0
  192. package/dist/templates/engine/dialog.js +167 -0
  193. package/dist/templates/engine/echo-numbers.d.ts +7 -0
  194. package/dist/templates/engine/echo-numbers.js +19 -0
  195. package/dist/templates/engine/expand.d.ts +6 -0
  196. package/dist/templates/engine/expand.js +125 -0
  197. package/dist/templates/engine/filters.d.ts +81 -0
  198. package/dist/templates/engine/filters.js +654 -0
  199. package/dist/templates/engine/hook-state.d.ts +18 -0
  200. package/dist/templates/engine/hook-state.js +100 -0
  201. package/dist/templates/engine/hooks.d.ts +51 -0
  202. package/dist/templates/engine/hooks.js +310 -0
  203. package/dist/templates/engine/index.d.ts +13 -0
  204. package/dist/templates/engine/index.js +30 -0
  205. package/dist/templates/engine/language-vars.d.ts +6 -0
  206. package/dist/templates/engine/language-vars.js +40 -0
  207. package/dist/templates/engine/language.d.ts +32 -0
  208. package/dist/templates/engine/language.js +155 -0
  209. package/dist/templates/engine/lookup.d.ts +20 -0
  210. package/dist/templates/engine/lookup.js +52 -0
  211. package/dist/templates/engine/match.d.ts +48 -0
  212. package/dist/templates/engine/match.js +253 -0
  213. package/dist/templates/engine/media.d.ts +428 -0
  214. package/dist/templates/engine/media.js +1240 -0
  215. package/dist/templates/engine/script.d.ts +11 -0
  216. package/dist/templates/engine/script.js +69 -0
  217. package/dist/templates/engine/turns/actions.d.ts +5 -0
  218. package/dist/templates/engine/turns/actions.js +128 -0
  219. package/dist/templates/engine/turns/carry.d.ts +15 -0
  220. package/dist/templates/engine/turns/carry.js +74 -0
  221. package/dist/templates/engine/turns/choices-offers.d.ts +21 -0
  222. package/dist/templates/engine/turns/choices-offers.js +143 -0
  223. package/dist/templates/engine/turns/choices.d.ts +22 -0
  224. package/dist/templates/engine/turns/choices.js +141 -0
  225. package/dist/templates/engine/turns/closing-guard.d.ts +73 -0
  226. package/dist/templates/engine/turns/closing-guard.js +162 -0
  227. package/dist/templates/engine/turns/closing.d.ts +10 -0
  228. package/dist/templates/engine/turns/closing.js +82 -0
  229. package/dist/templates/engine/turns/compile-forms.d.ts +24 -0
  230. package/dist/templates/engine/turns/compile-forms.js +68 -0
  231. package/dist/templates/engine/turns/context.d.ts +96 -0
  232. package/dist/templates/engine/turns/context.js +158 -0
  233. package/dist/templates/engine/turns/events.d.ts +409 -0
  234. package/dist/templates/engine/turns/events.js +5 -0
  235. package/dist/templates/engine/turns/hook-forms.d.ts +62 -0
  236. package/dist/templates/engine/turns/hook-forms.js +79 -0
  237. package/dist/templates/engine/turns/ladders.d.ts +42 -0
  238. package/dist/templates/engine/turns/ladders.js +119 -0
  239. package/dist/templates/engine/turns/language.d.ts +8 -0
  240. package/dist/templates/engine/turns/language.js +121 -0
  241. package/dist/templates/engine/turns/notes-dates.d.ts +9 -0
  242. package/dist/templates/engine/turns/notes-dates.js +42 -0
  243. package/dist/templates/engine/turns/notes-detect.d.ts +13 -0
  244. package/dist/templates/engine/turns/notes-detect.js +36 -0
  245. package/dist/templates/engine/turns/notes.d.ts +27 -0
  246. package/dist/templates/engine/turns/notes.js +176 -0
  247. package/dist/templates/engine/turns/opening.d.ts +34 -0
  248. package/dist/templates/engine/turns/opening.js +306 -0
  249. package/dist/templates/engine/turns/overtalk.d.ts +21 -0
  250. package/dist/templates/engine/turns/overtalk.js +247 -0
  251. package/dist/templates/engine/turns/pending.d.ts +9 -0
  252. package/dist/templates/engine/turns/pending.js +88 -0
  253. package/dist/templates/engine/turns/reply-rules.d.ts +184 -0
  254. package/dist/templates/engine/turns/reply-rules.js +335 -0
  255. package/dist/templates/engine/turns/rules.d.ts +20 -0
  256. package/dist/templates/engine/turns/rules.js +144 -0
  257. package/dist/templates/engine/turns/silence.d.ts +7 -0
  258. package/dist/templates/engine/turns/silence.js +127 -0
  259. package/dist/templates/engine/turns/state-spec.d.ts +305 -0
  260. package/dist/templates/engine/turns/state-spec.js +2 -0
  261. package/dist/templates/engine/turns/state.d.ts +38 -0
  262. package/dist/templates/engine/turns/state.js +101 -0
  263. package/dist/templates/engine/turns/tracking.d.ts +50 -0
  264. package/dist/templates/engine/turns/tracking.js +184 -0
  265. package/dist/templates/engine/turns/transfer.d.ts +19 -0
  266. package/dist/templates/engine/turns/transfer.js +93 -0
  267. package/dist/templates/engine/turns/turn.d.ts +17 -0
  268. package/dist/templates/engine/turns/turn.js +363 -0
  269. package/dist/templates/engine/turns/voicemail.d.ts +8 -0
  270. package/dist/templates/engine/turns/voicemail.js +101 -0
  271. package/dist/templates/engine/variants.d.ts +36 -0
  272. package/dist/templates/engine/variants.js +159 -0
  273. package/dist/templates/engine/voice-dialog.d.ts +24 -0
  274. package/dist/templates/engine/voice-dialog.js +157 -0
  275. package/dist/templates/engine/voice.d.ts +174 -0
  276. package/dist/templates/engine/voice.js +1337 -0
  277. package/dist/templates/expr/caller-after.d.ts +20 -0
  278. package/dist/templates/expr/caller-after.js +53 -0
  279. package/dist/templates/expr/check.d.ts +19 -0
  280. package/dist/templates/expr/check.js +314 -0
  281. package/dist/templates/expr/compiled.d.ts +8 -0
  282. package/dist/templates/expr/compiled.js +8 -0
  283. package/dist/templates/expr/context.d.ts +28 -0
  284. package/dist/templates/expr/context.js +55 -0
  285. package/dist/templates/expr/day-table.d.ts +4 -0
  286. package/dist/templates/expr/day-table.js +80 -0
  287. package/dist/templates/expr/evaluate.d.ts +26 -0
  288. package/dist/templates/expr/evaluate.js +885 -0
  289. package/dist/templates/expr/facts.d.ts +7 -0
  290. package/dist/templates/expr/facts.js +81 -0
  291. package/dist/templates/expr/index.d.ts +4 -0
  292. package/dist/templates/expr/index.js +11 -0
  293. package/dist/templates/expr/line-tally.d.ts +64 -0
  294. package/dist/templates/expr/line-tally.js +88 -0
  295. package/dist/templates/expr/matchers-state.d.ts +23 -0
  296. package/dist/templates/expr/matchers-state.js +37 -0
  297. package/dist/templates/expr/matchers.d.ts +12 -0
  298. package/dist/templates/expr/matchers.js +99 -0
  299. package/dist/templates/expr/readers.d.ts +14 -0
  300. package/dist/templates/expr/readers.js +351 -0
  301. package/dist/templates/expr/slots.d.ts +14 -0
  302. package/dist/templates/expr/slots.js +678 -0
  303. package/dist/templates/expr/template.d.ts +12 -0
  304. package/dist/templates/expr/template.js +76 -0
  305. package/dist/templates/expr/test-call.d.ts +8 -0
  306. package/dist/templates/expr/test-call.js +32 -0
  307. package/dist/templates/expr/transcript.d.ts +36 -0
  308. package/dist/templates/expr/transcript.js +394 -0
  309. package/dist/templates/expr/types.d.ts +1011 -0
  310. package/dist/templates/expr/types.js +2 -0
  311. package/dist/templates/expr/values.d.ts +42 -0
  312. package/dist/templates/expr/values.js +166 -0
  313. package/dist/templates/expr/voice-ops.d.ts +26 -0
  314. package/dist/templates/expr/voice-ops.js +85 -0
  315. package/dist/templates/helpers/decision.d.ts +55 -0
  316. package/dist/templates/helpers/decision.js +83 -0
  317. package/dist/templates/helpers/fuzzy.d.ts +9 -0
  318. package/dist/templates/helpers/fuzzy.js +44 -0
  319. package/dist/templates/helpers/index.d.ts +6 -0
  320. package/dist/templates/helpers/index.js +35 -0
  321. package/dist/templates/index.d.ts +9 -0
  322. package/dist/templates/index.js +68 -0
  323. package/dist/templates/integration-forms.d.ts +252 -0
  324. package/dist/templates/integration-forms.js +2 -0
  325. package/dist/templates/knowledge/block.d.ts +44 -0
  326. package/dist/templates/knowledge/block.js +199 -0
  327. package/dist/templates/knowledge/dense.d.ts +87 -0
  328. package/dist/templates/knowledge/dense.js +158 -0
  329. package/dist/templates/knowledge/flow.d.ts +328 -0
  330. package/dist/templates/knowledge/flow.js +509 -0
  331. package/dist/templates/knowledge/retriever.d.ts +75 -0
  332. package/dist/templates/knowledge/retriever.js +204 -0
  333. package/dist/templates/knowledge/service.d.ts +77 -0
  334. package/dist/templates/knowledge/service.js +316 -0
  335. package/dist/templates/knowledge/text.d.ts +31 -0
  336. package/dist/templates/knowledge/text.js +66 -0
  337. package/dist/templates/knowledge/types.d.ts +120 -0
  338. package/dist/templates/knowledge/types.js +2 -0
  339. package/dist/templates/locale.d.ts +259 -0
  340. package/dist/templates/locale.js +4 -0
  341. package/dist/templates/locales/en-lexicons.d.ts +9 -0
  342. package/dist/templates/locales/en-lexicons.js +101 -0
  343. package/dist/templates/locales/en.d.ts +132 -0
  344. package/dist/templates/locales/en.js +261 -0
  345. package/dist/templates/locales/es.d.ts +65 -0
  346. package/dist/templates/locales/es.js +208 -0
  347. package/dist/templates/locales/hi.d.ts +47 -0
  348. package/dist/templates/locales/hi.js +235 -0
  349. package/dist/templates/locales/id.d.ts +43 -0
  350. package/dist/templates/locales/id.js +127 -0
  351. package/dist/templates/locales/index.d.ts +34 -0
  352. package/dist/templates/locales/index.js +112 -0
  353. package/dist/templates/locales/kk-lexicons.d.ts +22 -0
  354. package/dist/templates/locales/kk-lexicons.js +89 -0
  355. package/dist/templates/locales/kk.d.ts +140 -0
  356. package/dist/templates/locales/kk.js +306 -0
  357. package/dist/templates/locales/kn.d.ts +29 -0
  358. package/dist/templates/locales/kn.js +22 -0
  359. package/dist/templates/locales/listen-only.d.ts +15 -0
  360. package/dist/templates/locales/listen-only.js +27 -0
  361. package/dist/templates/locales/ms-lexicons.d.ts +13 -0
  362. package/dist/templates/locales/ms-lexicons.js +113 -0
  363. package/dist/templates/locales/ms.d.ts +76 -0
  364. package/dist/templates/locales/ms.js +179 -0
  365. package/dist/templates/locales/parse.d.ts +86 -0
  366. package/dist/templates/locales/parse.js +461 -0
  367. package/dist/templates/locales/ru-lexicons.d.ts +27 -0
  368. package/dist/templates/locales/ru-lexicons.js +127 -0
  369. package/dist/templates/locales/ru-stem.d.ts +2 -0
  370. package/dist/templates/locales/ru-stem.js +53 -0
  371. package/dist/templates/locales/ru.d.ts +143 -0
  372. package/dist/templates/locales/ru.js +387 -0
  373. package/dist/templates/locales/shared.d.ts +122 -0
  374. package/dist/templates/locales/shared.js +318 -0
  375. package/dist/templates/locales/ta.d.ts +29 -0
  376. package/dist/templates/locales/ta.js +22 -0
  377. package/dist/templates/locales/te.d.ts +29 -0
  378. package/dist/templates/locales/te.js +22 -0
  379. package/dist/templates/locales/tl-lexicons.d.ts +2 -0
  380. package/dist/templates/locales/tl-lexicons.js +230 -0
  381. package/dist/templates/locales/tl.d.ts +59 -0
  382. package/dist/templates/locales/tl.js +82 -0
  383. package/dist/templates/locales/vi.d.ts +59 -0
  384. package/dist/templates/locales/vi.js +160 -0
  385. package/dist/templates/locales/word-regex.d.ts +13 -0
  386. package/dist/templates/locales/word-regex.js +43 -0
  387. package/dist/templates/locales/words-kk.d.ts +2 -0
  388. package/dist/templates/locales/words-kk.js +23 -0
  389. package/dist/templates/locales/words-ru.d.ts +4 -0
  390. package/dist/templates/locales/words-ru.js +92 -0
  391. package/dist/templates/spec.d.ts +2856 -0
  392. package/dist/templates/spec.js +2 -0
  393. package/dist/testing/fake-channel.d.ts +0 -1
  394. package/dist/testing/fake-channel.js +0 -1
  395. package/dist/testing/index.d.ts +24 -1
  396. package/dist/testing/index.js +117 -2
  397. package/dist/voice/call-voice.d.ts +581 -0
  398. package/dist/voice/call-voice.js +1399 -0
  399. package/dist/voice/intent-interrupt.d.ts +32 -0
  400. package/dist/voice/intent-interrupt.js +91 -0
  401. package/dist/voice/self-echo.d.ts +28 -0
  402. package/dist/voice/self-echo.js +135 -0
  403. package/dist/voice/sentence-tag.d.ts +5 -0
  404. package/dist/voice/sentence-tag.js +42 -0
  405. package/dist/voice/speech-leak.d.ts +74 -0
  406. package/dist/voice/speech-leak.js +216 -0
  407. package/dist/voice/transfer.d.ts +90 -0
  408. package/dist/voice/transfer.js +331 -0
  409. package/dist/voice/turn-timing.d.ts +293 -0
  410. package/dist/voice/turn-timing.js +567 -0
  411. package/docs/README.md +3 -6
  412. package/docs/framework/README.md +6 -10
  413. package/docs/framework/architecture.md +2 -2
  414. package/docs/framework/container-and-di.md +1 -2
  415. package/docs/framework/invariants.md +6 -6
  416. package/docs/framework/package-layout.md +17 -23
  417. package/docs/framework/testing.md +8 -6
  418. package/package.json +22 -55
  419. package/skill/AGENTS.md +43 -0
  420. package/skill/AGENTS.recommend.md +27 -0
  421. package/skill/SKILL.md +100 -0
  422. package/skill/references/agent-file.md +230 -0
  423. package/skill/references/blocks.md +246 -0
  424. package/skill/references/builder.md +163 -0
  425. package/skill/references/business.md +659 -0
  426. package/skill/references/conversation.md +586 -0
  427. package/skill/references/core.md +89 -0
  428. package/skill/references/examples.md +73 -0
  429. package/skill/references/expressions.md +342 -0
  430. package/skill/references/format.md +114 -0
  431. package/skill/references/library-dev.md +84 -0
  432. package/skill/references/locales.md +149 -0
  433. package/skill/references/migration.md +133 -0
  434. package/skill/references/new-agent.md +170 -0
  435. package/skill/references/porting.md +165 -0
  436. package/templates/agent/README.md +55 -0
  437. package/templates/agent/package.json +24 -0
  438. package/templates/agent/src/agent.spec.ts +51 -0
  439. package/templates/agent/src/agent.ts +268 -0
  440. package/templates/agent/src/entities.ts +44 -0
  441. package/templates/agent/src/prompt.sqrl +21 -0
  442. package/templates/agent/src/variants/fixed-opening.ts +144 -0
  443. package/templates/agent/tsconfig.build.json +4 -0
  444. package/templates/agent/tsconfig.json +18 -0
  445. package/dist/asr/index.d.ts +0 -3
  446. package/dist/asr/index.d.ts.map +0 -1
  447. package/dist/asr/index.js +0 -6
  448. package/dist/asr/index.js.map +0 -1
  449. package/dist/barge-in/barge-in-module.d.ts.map +0 -1
  450. package/dist/barge-in/barge-in-module.js.map +0 -1
  451. package/dist/barge-in/barge-in-service.d.ts.map +0 -1
  452. package/dist/barge-in/barge-in-service.js.map +0 -1
  453. package/dist/barge-in/barge-in-strategy.d.ts.map +0 -1
  454. package/dist/barge-in/barge-in-strategy.js.map +0 -1
  455. package/dist/barge-in/echo-cancellation.d.ts.map +0 -1
  456. package/dist/barge-in/echo-cancellation.js.map +0 -1
  457. package/dist/barge-in/echo.d.ts.map +0 -1
  458. package/dist/barge-in/echo.js.map +0 -1
  459. package/dist/barge-in/index.d.ts +0 -13
  460. package/dist/barge-in/index.d.ts.map +0 -1
  461. package/dist/barge-in/index.js +0 -28
  462. package/dist/barge-in/index.js.map +0 -1
  463. package/dist/barge-in/lexicon.d.ts.map +0 -1
  464. package/dist/barge-in/lexicon.js.map +0 -1
  465. package/dist/barge-in/lexicons/en.d.ts +0 -2
  466. package/dist/barge-in/lexicons/en.d.ts.map +0 -1
  467. package/dist/barge-in/lexicons/en.js +0 -36
  468. package/dist/barge-in/lexicons/en.js.map +0 -1
  469. package/dist/barge-in/lexicons/id.d.ts +0 -2
  470. package/dist/barge-in/lexicons/id.d.ts.map +0 -1
  471. package/dist/barge-in/lexicons/id.js +0 -39
  472. package/dist/barge-in/lexicons/id.js.map +0 -1
  473. package/dist/barge-in/lexicons/index.d.ts +0 -10
  474. package/dist/barge-in/lexicons/index.d.ts.map +0 -1
  475. package/dist/barge-in/lexicons/index.js +0 -11
  476. package/dist/barge-in/lexicons/index.js.map +0 -1
  477. package/dist/barge-in/lexicons/ru.d.ts +0 -2
  478. package/dist/barge-in/lexicons/ru.d.ts.map +0 -1
  479. package/dist/barge-in/lexicons/ru.js +0 -39
  480. package/dist/barge-in/lexicons/ru.js.map +0 -1
  481. package/dist/barge-in/speech-ledger.d.ts.map +0 -1
  482. package/dist/barge-in/speech-ledger.js.map +0 -1
  483. package/dist/barge-in/word-classifier.d.ts.map +0 -1
  484. package/dist/barge-in/word-classifier.js.map +0 -1
  485. package/dist/bridge/bridge.d.ts +0 -28
  486. package/dist/bridge/bridge.d.ts.map +0 -1
  487. package/dist/bridge/bridge.js +0 -117
  488. package/dist/bridge/bridge.js.map +0 -1
  489. package/dist/bridge/index.d.ts +0 -3
  490. package/dist/bridge/index.d.ts.map +0 -1
  491. package/dist/bridge/index.js +0 -8
  492. package/dist/bridge/index.js.map +0 -1
  493. package/dist/core/call-disposables.d.ts.map +0 -1
  494. package/dist/core/call-disposables.js.map +0 -1
  495. package/dist/core/container.d.ts.map +0 -1
  496. package/dist/core/container.js.map +0 -1
  497. package/dist/core/create-agent-script.d.ts.map +0 -1
  498. package/dist/core/create-agent-script.js.map +0 -1
  499. package/dist/core/decorators.d.ts.map +0 -1
  500. package/dist/core/decorators.js.map +0 -1
  501. package/dist/core/define-module.d.ts.map +0 -1
  502. package/dist/core/define-module.js.map +0 -1
  503. package/dist/core/dump-policy.d.ts.map +0 -1
  504. package/dist/core/dump-policy.js.map +0 -1
  505. package/dist/core/hooks.d.ts.map +0 -1
  506. package/dist/core/hooks.js.map +0 -1
  507. package/dist/core/index.d.ts +0 -16
  508. package/dist/core/index.d.ts.map +0 -1
  509. package/dist/core/index.js +0 -36
  510. package/dist/core/index.js.map +0 -1
  511. package/dist/core/media-bootstrap.d.ts.map +0 -1
  512. package/dist/core/media-bootstrap.js.map +0 -1
  513. package/dist/core/provide-media.d.ts.map +0 -1
  514. package/dist/core/provide-media.js.map +0 -1
  515. package/dist/core/tokens.d.ts.map +0 -1
  516. package/dist/core/tokens.js.map +0 -1
  517. package/dist/core/types.d.ts.map +0 -1
  518. package/dist/core/types.js.map +0 -1
  519. package/dist/core/version.d.ts.map +0 -1
  520. package/dist/core/version.js.map +0 -1
  521. package/dist/dialog/basic-ports.d.ts +0 -54
  522. package/dist/dialog/basic-ports.d.ts.map +0 -1
  523. package/dist/dialog/basic-ports.js +0 -206
  524. package/dist/dialog/basic-ports.js.map +0 -1
  525. package/dist/dialog/define-dialog.d.ts +0 -21
  526. package/dist/dialog/define-dialog.d.ts.map +0 -1
  527. package/dist/dialog/define-dialog.js +0 -21
  528. package/dist/dialog/define-dialog.js.map +0 -1
  529. package/dist/dialog/dialog-definition.d.ts.map +0 -1
  530. package/dist/dialog/dialog-definition.js.map +0 -1
  531. package/dist/dialog/dialog-ports.d.ts.map +0 -1
  532. package/dist/dialog/dialog-ports.js.map +0 -1
  533. package/dist/dialog/index.d.ts +0 -7
  534. package/dist/dialog/index.d.ts.map +0 -1
  535. package/dist/dialog/index.js +0 -23
  536. package/dist/dialog/index.js.map +0 -1
  537. package/dist/dialog/online-call-host.d.ts.map +0 -1
  538. package/dist/dialog/online-call-host.js.map +0 -1
  539. package/dist/dialog/online-call-module.d.ts.map +0 -1
  540. package/dist/dialog/online-call-module.js.map +0 -1
  541. package/dist/dialog-events/active-media.d.ts.map +0 -1
  542. package/dist/dialog-events/active-media.js.map +0 -1
  543. package/dist/dialog-events/event-source.d.ts.map +0 -1
  544. package/dist/dialog-events/event-source.js.map +0 -1
  545. package/dist/dialog-events/index.d.ts +0 -8
  546. package/dist/dialog-events/index.d.ts.map +0 -1
  547. package/dist/dialog-events/index.js +0 -24
  548. package/dist/dialog-events/index.js.map +0 -1
  549. package/dist/dialog-events/max-listen-source.d.ts +0 -27
  550. package/dist/dialog-events/max-listen-source.d.ts.map +0 -1
  551. package/dist/dialog-events/max-listen-source.js +0 -98
  552. package/dist/dialog-events/max-listen-source.js.map +0 -1
  553. package/dist/dialog-events/overtalk-source.d.ts +0 -61
  554. package/dist/dialog-events/overtalk-source.d.ts.map +0 -1
  555. package/dist/dialog-events/overtalk-source.js +0 -232
  556. package/dist/dialog-events/overtalk-source.js.map +0 -1
  557. package/dist/dialog-events/silence-source.d.ts +0 -32
  558. package/dist/dialog-events/silence-source.d.ts.map +0 -1
  559. package/dist/dialog-events/silence-source.js +0 -128
  560. package/dist/dialog-events/silence-source.js.map +0 -1
  561. package/dist/dialog-events/virtual-finals-module.d.ts.map +0 -1
  562. package/dist/dialog-events/virtual-finals-module.js.map +0 -1
  563. package/dist/dialog-events/virtual-finals.d.ts.map +0 -1
  564. package/dist/dialog-events/virtual-finals.js.map +0 -1
  565. package/dist/dtmf/dtmf.d.ts +0 -27
  566. package/dist/dtmf/dtmf.d.ts.map +0 -1
  567. package/dist/dtmf/dtmf.js +0 -87
  568. package/dist/dtmf/dtmf.js.map +0 -1
  569. package/dist/dtmf/index.d.ts +0 -3
  570. package/dist/dtmf/index.d.ts.map +0 -1
  571. package/dist/dtmf/index.js +0 -8
  572. package/dist/dtmf/index.js.map +0 -1
  573. package/dist/index.d.ts.map +0 -1
  574. package/dist/index.js.map +0 -1
  575. package/dist/lifecycle/index.d.ts +0 -3
  576. package/dist/lifecycle/index.d.ts.map +0 -1
  577. package/dist/lifecycle/index.js +0 -9
  578. package/dist/lifecycle/index.js.map +0 -1
  579. package/dist/lifecycle/lifecycle.d.ts.map +0 -1
  580. package/dist/lifecycle/lifecycle.js.map +0 -1
  581. package/dist/llm/index.d.ts +0 -7
  582. package/dist/llm/index.d.ts.map +0 -1
  583. package/dist/llm/index.js +0 -18
  584. package/dist/llm/index.js.map +0 -1
  585. package/dist/llm/llm-markers-module.d.ts +0 -15
  586. package/dist/llm/llm-markers-module.d.ts.map +0 -1
  587. package/dist/llm/llm-markers-module.js +0 -48
  588. package/dist/llm/llm-markers-module.js.map +0 -1
  589. package/dist/llm/llm-markers.d.ts +0 -36
  590. package/dist/llm/llm-markers.d.ts.map +0 -1
  591. package/dist/llm/llm-markers.js +0 -210
  592. package/dist/llm/llm-markers.js.map +0 -1
  593. package/dist/llm/llm-module.d.ts +0 -20
  594. package/dist/llm/llm-module.d.ts.map +0 -1
  595. package/dist/llm/llm-module.js.map +0 -1
  596. package/dist/match/index.d.ts +0 -3
  597. package/dist/match/index.d.ts.map +0 -1
  598. package/dist/match/index.js +0 -10
  599. package/dist/match/index.js.map +0 -1
  600. package/dist/match/match.d.ts +0 -33
  601. package/dist/match/match.d.ts.map +0 -1
  602. package/dist/match/match.js +0 -85
  603. package/dist/match/match.js.map +0 -1
  604. package/dist/outbound/index.d.ts +0 -3
  605. package/dist/outbound/index.d.ts.map +0 -1
  606. package/dist/outbound/index.js +0 -8
  607. package/dist/outbound/index.js.map +0 -1
  608. package/dist/outbound/outbound.d.ts +0 -40
  609. package/dist/outbound/outbound.d.ts.map +0 -1
  610. package/dist/outbound/outbound.js +0 -84
  611. package/dist/outbound/outbound.js.map +0 -1
  612. package/dist/result/index.d.ts +0 -2
  613. package/dist/result/index.d.ts.map +0 -1
  614. package/dist/result/index.js.map +0 -1
  615. package/dist/result/result-store.d.ts.map +0 -1
  616. package/dist/result/result-store.js.map +0 -1
  617. package/dist/testing/fake-channel.d.ts.map +0 -1
  618. package/dist/testing/fake-channel.js.map +0 -1
  619. package/dist/testing/index.d.ts.map +0 -1
  620. package/dist/testing/index.js.map +0 -1
  621. package/docs/agents/README.md +0 -41
  622. package/docs/agents/barge-in.md +0 -67
  623. package/docs/agents/dialog.md +0 -98
  624. package/docs/agents/getting-started.md +0 -142
  625. package/docs/agents/imports.md +0 -40
  626. package/docs/agents/media-and-ports.md +0 -82
  627. package/docs/agents/modules.md +0 -83
  628. package/docs/agents/phases.md +0 -83
  629. package/docs/framework/extending.md +0 -59
  630. package/docs/framework/idn-parity.md +0 -18
  631. package/examples/minimal-agent/README.md +0 -7
  632. package/examples/minimal-agent/agent.ts +0 -94
@@ -0,0 +1,2856 @@
1
+ import type { LocaleCode } from './locale';
2
+ import type { Condition, DataExpr, Expr, MatcherAddition, NamedFacts, NamedMatchers, ReadSpec } from './expr/types';
3
+ import type { DecisionModelSpec } from './decision-model';
4
+ import type { StateMatcherAddition } from './expr/matchers-state';
5
+ import type { KnowledgeAnswerSpec } from './knowledge/types';
6
+ import type { CatalogMatchSpec } from './catalog-match/types';
7
+ import type { ReplyRuleSet } from './engine/turns/reply-rules';
8
+ import type { ClosingGuardReask } from './engine/turns/closing-guard';
9
+ import type { HoldExtendSpec, ReviewRules, ToolReplySpec } from './engine/turns/hook-forms';
10
+ import type { ExtractionRule } from './business/extraction-rules';
11
+ import type { ResultRule } from './business/result-rules';
12
+ import type { CatalogReportSource, ResultCatalog } from './business/result-catalog';
13
+ export type { ExtractionRule } from './business/extraction-rules';
14
+ export type { ResultRule } from './business/result-rules';
15
+ export type { CatalogAccept, CatalogColumns, CatalogEntry, CatalogItem, CatalogReportSource, CatalogValue, ResultCatalog } from './business/result-catalog';
16
+ import type { AfterLegPolicy, AskAgentSpec, BodySerialize, CallbackPolicy, HeaderValue, IntegrationCheck, IntegrationCooldown, IntegrationLog, IntegrationRead, RouteRule, StartAgentDialogSpec, TestPresets, TrunkPool } from './integration-forms';
17
+ import type { ChoicesSpec, LadderSpec, NoteEntry, TrackingSpec } from './engine/turns/state-spec';
18
+ /**
19
+ * Where a value comes from. Used by input fields, integration URLs/keys, recall budgets, switches.
20
+ * - `header`: `X-<name>` header (prefix added when absent): the dialer's header bag (`proto_additional`), then the
21
+ * INVITE's (any case, a list's first value); `order: 'inviteFirst'` the INVITE's first (the bag when it is missing or
22
+ * blank), `'invite'` only the INVITE's (default `'bagFirst'`);
23
+ * - `param`: dialog / campaign parameter;
24
+ * - `proto`: `proto_additional` of the dialog;
25
+ * - `entity`: CMS input entity of the dialog;
26
+ * - `global`: CMS global variable of the agent;
27
+ * - `storage`: CMS storage key (secrets);
28
+ * - `env`: process environment of the script host;
29
+ * - `dialogEnv`: a value kept in the dialog env under this key (e.g. by an earlier pass of the dialog);
30
+ * - `callRow`: a field of the platform's call row (a dotted path, e.g. `params.proto_additional.caller_id`);
31
+ * - `call`: a fact of this call (`msisdn`, `callUuid`, `dialogUuid`, `attempt`, `today`, `now`; `direction` of the leg
32
+ * as the platform's call row gives it, `in` / `out`; `trunkName` of the agent's trunk; `bulkUuid` of the campaign
33
+ * upload the dialog belongs to; `startedAt`: epoch ms of the dial on the platform's call row);
34
+ * - `platform`: value the platform/campaign supplies for this feature (recall budget, recall delay).
35
+ * An array is tried in order; the first non-empty value wins.
36
+ */
37
+ export type Source = {
38
+ readonly header: string;
39
+ readonly order?: 'bagFirst' | 'inviteFirst' | 'invite';
40
+ } | {
41
+ readonly param: string;
42
+ } | {
43
+ readonly proto: string;
44
+ } | {
45
+ readonly entity: string;
46
+ } | {
47
+ readonly global: string;
48
+ } | {
49
+ readonly storage: string;
50
+ } | {
51
+ readonly env: string;
52
+ } | {
53
+ readonly dialogEnv: string;
54
+ } | {
55
+ readonly callRow: string;
56
+ } | {
57
+ readonly call: 'msisdn' | 'callUuid' | 'dialogUuid' | 'agentUuid' | 'attempt' | 'today' | 'now' | 'direction' | 'trunkName' | 'bulkUuid' | 'startedAt';
58
+ } | {
59
+ readonly platform: true;
60
+ };
61
+ /**
62
+ * A value given literally, read from a source (or sources in order), with a default. With `map`, the raw value is
63
+ * looked up in the map (as is, then trimmed and lower-cased); a raw value the map does not list gives `default`.
64
+ */
65
+ export type Value<T> = T | {
66
+ readonly from: Source | readonly Source[];
67
+ readonly default?: T;
68
+ readonly map?: Readonly<Record<string, T>>;
69
+ };
70
+ /**
71
+ * A record of values given as an expression of the data language: `{ object }` (each value an expression), `{ merge }`
72
+ * or `{ cases }`. Any other object in a record slot is the record itself.
73
+ */
74
+ export type RecordExpr = Extract<DataExpr, {
75
+ readonly object: unknown;
76
+ } | {
77
+ readonly merge: unknown;
78
+ } | {
79
+ readonly cases: unknown;
80
+ }>;
81
+ /**
82
+ * Text the agent says or sends. A string may use `{name}` placeholders (call variables, plus `{attempt}`,
83
+ * `{language}` where the field says so). A per-language map picks by the active reply language. A function sees the
84
+ * call and the line being handled; returning `null` means «nothing to say».
85
+ */
86
+ export type Text = string | Partial<Record<LocaleCode, string>> | ((call: CallView, line?: string) => string | Partial<Record<LocaleCode, string>> | null)
87
+ /** An expression of the data language (`{ template }`, `{ cases }`, …): its value as text, `null` says nothing. */
88
+ | DataExpr;
89
+ /**
90
+ * What a line is matched against. `phrases` and `lexicon` are normalized (case, punctuation, spaces) and matched as
91
+ * whole words; `lexicon` names a list of the active locale pack(s) (e.g. `'yes'`, `'backchannel'`, `'voicemail'`) —
92
+ * its phrases, and its regular expressions (`LocalePack.patterns[name]`, tested on the line as it is); `in: 'all'`
93
+ * reads the lists of every call language, not only the reply language's (a caller may speak any of them); a name with
94
+ * a pack in front (`'hi:voicemail'`) reads that pack's list whatever the call's languages are (`in` is ignored) — the
95
+ * way to hear a language the agent does not reply in (token shapes take such names too).
96
+ * `tail` matches only the last `chars` characters (`words: true`: of the line with every non-letter turned into a
97
+ * space, lower case); `normalized` tests its matcher on the normalized line; `tokens` reads the line's shape (see
98
+ * {@link TokenShape}); `intent` asks the platform NLU.
99
+ */
100
+ export type Matcher = RegExp | {
101
+ readonly phrases: readonly string[] | Partial<Record<LocaleCode, readonly string[]>>;
102
+ } | {
103
+ readonly lexicon: string;
104
+ readonly in?: 'reply' | 'all';
105
+ }
106
+ /**
107
+ * Platform NLU intents (an asynchronous rule). `language`: the NLU language; `timeoutMs`: no answer by then is no
108
+ * match; `normalized`: the line is sent lower case without punctuation; `warmUp`: a request with this text at
109
+ * answer (its answer is ignored), so the first real one is not slow.
110
+ */
111
+ | {
112
+ readonly intent: string | readonly string[];
113
+ readonly minScore?: number;
114
+ readonly language?: string;
115
+ readonly timeoutMs?: number;
116
+ readonly normalized?: boolean;
117
+ readonly warmUp?: string;
118
+ } | {
119
+ readonly tail: Matcher;
120
+ readonly chars: number;
121
+ readonly words?: boolean;
122
+ } | {
123
+ readonly normalized: Matcher;
124
+ } | {
125
+ readonly tokens: TokenShape;
126
+ } | {
127
+ readonly any: readonly Matcher[];
128
+ } | {
129
+ readonly all: readonly Matcher[];
130
+ } | {
131
+ readonly not: Matcher;
132
+ }
133
+ /** Data-language matchers: `squeezed`, `words`, `mentions`, `normalizedEquals`, `lastAgentLine`, named `matcher`. */
134
+ | MatcherAddition
135
+ /** `spaced`, `contains` (see `expr/matchers-state`). */
136
+ | StateMatcherAddition | ((text: string, call: CallView) => boolean);
137
+ /**
138
+ * The shape of a short answer, word by word (lower case, split on non-letters; recognizer labels like `[ru]` dropped),
139
+ * from lexicons of every call language:
140
+ * - `has`: some word is in this lexicon (and nothing else is checked);
141
+ * - otherwise: words of `ignore` are dropped wherever they stand, leading words of `lead` are skipped, then at least
142
+ * `min` (default 1) words of `core` are read, and the rest of the line must be empty, or (with `rest`) the whole
143
+ * rest is one phrase of the lexicon `rest` (a string), or every rest word is in `rest.all` and some in `rest.some`.
144
+ */
145
+ export type TokenShape = {
146
+ readonly has: string;
147
+ } | {
148
+ readonly ignore?: string;
149
+ readonly lead?: string;
150
+ readonly core: string;
151
+ readonly min?: number;
152
+ readonly rest?: string | {
153
+ readonly all: string;
154
+ readonly some: string;
155
+ };
156
+ };
157
+ /** Milliseconds, or a function of the text (e.g. per-character floors). */
158
+ export type Ms = number | ((text: string) => number);
159
+ /** Read-only view of the call given to `Text` functions, matchers, rules and hooks. */
160
+ export interface CallView {
161
+ /** The call's variables: input fields, prompt variables, values set by rules (`set`). */
162
+ readonly vars: Readonly<Record<string, unknown>>;
163
+ /** Active reply language and whether it is still a provisional pick. */
164
+ readonly language: LocaleCode;
165
+ readonly languageProvisional: boolean;
166
+ readonly phase: 'opening' | 'conversation' | 'closing' | 'transfer';
167
+ /** The conversation in order. `heard` is false for an agent line the caller cut. */
168
+ readonly lines: readonly {
169
+ readonly who: 'agent' | 'caller';
170
+ readonly text: string;
171
+ readonly heard?: boolean;
172
+ readonly atMs: number;
173
+ /** An agent line's mixer alias (a fixed line's name; the LLM's replies `reply`), where the call knows it. */
174
+ readonly unit?: string;
175
+ }[];
176
+ readonly agentLines: readonly string[];
177
+ readonly callerLines: readonly string[];
178
+ /** Caller lines that reached the LLM / caller finals heard at all. */
179
+ readonly callerTurns: number;
180
+ readonly callerFinals: number;
181
+ readonly counters: Readonly<Record<string, number>>;
182
+ /** While a rule's actions run: how many times that rule has acted, this time included (what `{ nth }` reads). */
183
+ readonly ruleCount?: number;
184
+ /** Rule and detector flags; `closing.afterSilence`: the goodbye answered a silence turn. */
185
+ readonly flags: Readonly<Record<string, boolean>>;
186
+ readonly elapsedMs: number;
187
+ readonly attempt: number;
188
+ /** The previous attempt of this dialog (result, attempt), when there was one. */
189
+ readonly previous: {
190
+ readonly result: string;
191
+ readonly attempt: number;
192
+ } | null;
193
+ /** Values kept across attempts of the dialog (`remember` action). */
194
+ readonly memory: Readonly<Record<string, unknown>>;
195
+ /** After the call: extracted entities, the decided result label (before `labels.map`), who ended the call. */
196
+ readonly extracted?: Readonly<Record<string, unknown>>;
197
+ readonly result?: string;
198
+ /** Report fields of a row: the result before extraction and the extracted one (`null` on a row without them). */
199
+ readonly preResult?: string | null;
200
+ readonly extractedResult?: string | null;
201
+ readonly triggersCallback?: boolean | null;
202
+ /** Report fields of a row: the extraction request failed (`extraction.onFailure: 'keepResult'`; `null`: not known). */
203
+ readonly extractionFailed?: boolean | null;
204
+ /**
205
+ * The per-call state the agent's hooks keep (`HookApi.state`): during the call and after it. Agent code the reducer
206
+ * runs reads a copy as of the event (its writes go back to the hooks' state after the event).
207
+ */
208
+ readonly hookState?: Readonly<Record<string, unknown>>;
209
+ /** After the call: when it ended (epoch ms; before extraction and the row). */
210
+ readonly endedAtMs?: number;
211
+ /** Who ended the call: the agent (a goodbye, a close, a hangup action), the caller, or the call's time limit. */
212
+ readonly endedBy?: 'agent' | 'caller' | 'timeout' | 'error';
213
+ /** Voice variant picked for this call (`voice.tts.variants`). */
214
+ readonly voiceTag?: string;
215
+ /**
216
+ * After the call: how far the operator transfer got (`started` when the operator leg was being dialled, with its
217
+ * time; `completed` when it was bridged). Absent on a call that never started one.
218
+ */
219
+ readonly transfer?: {
220
+ readonly started: boolean;
221
+ readonly completed: boolean;
222
+ readonly startedAt: string;
223
+ };
224
+ /** At a goodbye: the reply that said it answered a silence turn. */
225
+ readonly afterSilence?: boolean;
226
+ /**
227
+ * After-call integrations: whether this pass booked the next leg (`null` when the redial is decided after them —
228
+ * set `platform.recall.beforeIntegrations`), and the campaign's redial budget (`null`: none given).
229
+ */
230
+ readonly recallScheduled?: boolean | null;
231
+ readonly budget?: number | null;
232
+ /** `voice.asrByReply`: the key the agent's replies last read as, and every change of it in order. */
233
+ readonly replyAsr?: string;
234
+ readonly replyAsrKeys?: readonly string[];
235
+ /**
236
+ * Report fields only: which row is built (`call`, `error`, `failedDial`, `failedLeg`, `cancelled`, `headless`) and its
237
+ * facts — the platform's service fields as the library would write them (`status`, `call_status`, `call_start_time`,
238
+ * `duration`, `call_uuid`, `call_transcript`…), the call and dialog UUIDs, the recognizer's seconds, the SIP code and
239
+ * phrase the script saw, the reply language at the end of the call (as the prompt names it; `null`: none) and whether
240
+ * it was still a provisional pick — for a row in the client's own layout.
241
+ */
242
+ readonly rowFacts?: {
243
+ readonly kind: 'call' | 'error' | 'failedDial' | 'cancelled' | 'failedLeg' | 'headless';
244
+ /** The leg was answered (`call`, `error`); false on a dial that never connected, a cancelled or headless pass. */
245
+ readonly connected: boolean;
246
+ readonly service: Readonly<Record<string, unknown>>;
247
+ readonly callUuid: string | null;
248
+ readonly dialogUuid: string | null;
249
+ readonly asrDurationSec: number | null;
250
+ readonly sipCode: number | null;
251
+ readonly sipPhrase: string | null;
252
+ readonly replyLanguage: string | null;
253
+ readonly replyLanguageProvisional: boolean;
254
+ };
255
+ /** After-call integrations: the decided result, the result before extraction, whether it asks for a callback, the entities. */
256
+ readonly outcome?: {
257
+ readonly result: string;
258
+ readonly preResult: string;
259
+ readonly triggersCallback: boolean;
260
+ readonly entities: Readonly<Record<string, unknown>>;
261
+ } | null;
262
+ }
263
+ /** The agent file as the engine runs it (data plus compiled functions and hooks). Agents write `AgentSpec` (./authoring). */
264
+ export interface EngineSpec<H = UntypedHooks> {
265
+ readonly id: AgentId;
266
+ /** Languages of the call, the first is the default. Each needs a recognizer in `voice.asr`. */
267
+ readonly languages: readonly LocaleCode[];
268
+ readonly platform: PlatformSpec<H>;
269
+ readonly voice: VoiceSpec;
270
+ /** Call variables: CMS input → formatted values for the prompt, texts and the report. */
271
+ readonly input: InputSpec<H>;
272
+ /**
273
+ * The LLM conversation's prompt; not needed when the opening ends the call (a last step `close`). Left out of an
274
+ * agent with a conversation: the agent has no LLM — rules (usually a hook rule on every caller line) and silence
275
+ * rungs answer with fixed lines; a line nothing answered is only written to the transcript.
276
+ */
277
+ readonly prompt?: PromptSpec;
278
+ /** What happens from answer until the LLM takes over. */
279
+ readonly opening: readonly OpeningStep<H>[];
280
+ readonly turn?: TurnSpec<H>;
281
+ readonly overtalk?: OvertalkSpec<H>;
282
+ /** Silence handling of the conversation; not needed when the opening ends the call. */
283
+ readonly silence?: SilenceSpec<H>;
284
+ readonly voicemail?: VoicemailSpec<H>;
285
+ /** Condition → actions, on caller lines, agent lines, tool calls. See `Rule` for order and accumulation. */
286
+ readonly rules?: readonly Rule<H>[];
287
+ /** Ongoing checks over the conversation (identity, consent): a question the agent asks, answers, limits. */
288
+ readonly gates?: readonly GateSpec[];
289
+ /** How the conversation ends; not needed when the opening ends the call. */
290
+ readonly closing?: ClosingSpec<H>;
291
+ readonly transfer?: TransferSpec<H>;
292
+ readonly extraction?: ExtractionSpec<H>;
293
+ readonly results: ResultsSpec<H>;
294
+ readonly report: ReportSpec;
295
+ readonly integrations?: readonly (Integration<H> | HookIntegration<H> | AgentIntegration)[];
296
+ /** The choice model (Workers AI) the blocks below ask, unless a block names its own. */
297
+ readonly decisionModel?: DecisionModelSpec;
298
+ /**
299
+ * Fixed answers from a knowledge base, no LLM: every caller line is planned by the library's planner (a whole-line
300
+ * pattern, an exact phrasing, or retrieval plus one decision request). The block adds its caller-line rule and its
301
+ * answer-phase start; silence rungs say `{ knowledge: 'silence' }` / `{ knowledge: 'unheard' }`; the row takes
302
+ * `{ knowledgeTrace }` fields; the result is rewritten at the call's end (`results.rewrite`).
303
+ */
304
+ readonly knowledgeAnswer?: KnowledgeAnswerSpec;
305
+ /**
306
+ * A name the caller says matched to a two-level list and picked by the decision model, and optionally checked with a
307
+ * client service step by step (`verify`). The block adds its caller-line rule; the row takes `{ catalogMatch: 'row' }`.
308
+ */
309
+ readonly catalogMatch?: CatalogMatchSpec;
310
+ /**
311
+ * Sticky per-call state read off the conversation: flags (lines, what the caller heard, a cut reply), stages, the
312
+ * question open now and how often each was asked — read in conditions as `{ flag }`, `{ stage }`, `{ openQuestion }`,
313
+ * `{ asked }`, `{ answers }`.
314
+ */
315
+ readonly tracking?: TrackingSpec;
316
+ /**
317
+ * Ladders by name: lines said once each by the `{ ladder }` action then a terminal action, or notes by stage and count
318
+ * read by a note's `{ ladder }` detector.
319
+ */
320
+ readonly ladders?: Readonly<Record<string, LadderSpec>>;
321
+ /** Option sets read off the words or the transcript (`{ choice }` expressions, note detectors). */
322
+ readonly choices?: ChoicesSpec;
323
+ /** The agent's hooks (also the second argument of `defineVoiceAgent`). */
324
+ readonly hooks?: AgentHooks;
325
+ /** Matchers by name, used anywhere a matcher goes as `{ matcher: name }`. */
326
+ readonly matchers?: NamedMatchers;
327
+ /**
328
+ * Facts of the call by name (`{ fact: name }` in conditions and expressions): a condition or a value, evaluated when
329
+ * read. A name of a built-in fact is refused.
330
+ */
331
+ readonly facts?: NamedFacts;
332
+ }
333
+ export interface AgentId {
334
+ readonly name: string;
335
+ /** CMS agent UUID (default when the dialog does not carry one). */
336
+ readonly uuid: string;
337
+ /** Agent version written to every report row. */
338
+ readonly version: string;
339
+ }
340
+ export interface PlatformSpec<H = UntypedHooks> {
341
+ /** `from_invite`: the script starts before the dial (failed legs reach the report). Default `on_answer`. */
342
+ readonly outboundMode?: 'on_answer' | 'from_invite';
343
+ /**
344
+ * Who follows the leg: the platform (default for `on_answer`: the row's service fields from its final status line,
345
+ * the attempt counted by the script, the row starting at the platform's call start) or the script itself (`script`,
346
+ * always so for `from_invite`: it latches the SIP status, sends "ready" at once, the row's start is when the script
347
+ * took the call and its service fields are what the script saw — `call_status` of its SIP view, `call_record` the CMS
348
+ * records page, the start time with milliseconds, the recognizer's seconds).
349
+ */
350
+ readonly followLeg?: 'platform' | 'script';
351
+ readonly ringingTimeoutMs?: number;
352
+ /** Hard limit of a connected call. */
353
+ readonly maxCallMs: number;
354
+ /** At `maxCallMs` the agent's line stops at once and the hangup follows this long after. Default 0: hang up at once. */
355
+ readonly maxCallGraceMs?: number;
356
+ /**
357
+ * The script schedules its outbound legs on the pre-call pass. `false` for inbound-only agents; a function decides
358
+ * per pass from the pass's variables (e.g. only over some trunks, only for a dialog of a campaign upload); an object
359
+ * schedules them with options. Default true.
360
+ */
361
+ readonly scheduleOutbound?: boolean | ((call: CallView) => boolean) | Exclude<Condition, boolean> | {
362
+ /** `priority` of the scheduled first leg. Default none. */
363
+ readonly priority?: number;
364
+ /**
365
+ * The first leg and the script's redials may dial the dialog's own number when the dialog params and row carry
366
+ * none (default true; `false`: no number in the params, no leg).
367
+ */
368
+ readonly msisdnFromDialog?: boolean;
369
+ /** Passes after a call (`after_call_failed` …) place no leg without logging it (default: logged). */
370
+ readonly quietAfterCall?: boolean;
371
+ };
372
+ /**
373
+ * Agent code on the pre-call pass, before the first leg is scheduled (`hook(call, null, api)`; awaited): e.g. it asks
374
+ * another CMS agent (`api.askAgent`) and keeps the answer for the call in the dialog env (`api.dialogEnv`), where
375
+ * input fields read it (`{ dialogEnv }`). Not run on the live pass or after a call. Default none.
376
+ */
377
+ readonly beforeCall?: HookRef<H, 'beforeCall'>;
378
+ /** Check before every dial (first and redials): an integration answering yes/no. `failOpen`: dial when it fails. */
379
+ readonly preDial?: {
380
+ readonly integration: string;
381
+ readonly failOpen: boolean;
382
+ };
383
+ /**
384
+ * A leg that never connected is reported on the `after_call_failed` pass (not in the live pass). The handler named on
385
+ * the legs for it: `legs.onFailedCall`.
386
+ */
387
+ readonly failedLegPass?: boolean | {
388
+ /**
389
+ * The row's `call_status` / `call_status_phrase`: `'host'` (the platform's `call_status` of the leg, then what a
390
+ * live pass of the leg handed over; default), `'liveRun'` (the other way round) or `'none'` (null).
391
+ */
392
+ readonly statusFrom?: 'host' | 'liveRun' | 'none';
393
+ };
394
+ /**
395
+ * How every leg the script places is placed — the first one, the redials of the failed-leg pass and of the `afterLeg`
396
+ * hook (`api.platform.redial`). Default: none of these.
397
+ */
398
+ readonly legs?: {
399
+ /**
400
+ * The number as the leg dials it, from the one the dialog carries (e.g. a trunk prefix, a national number with its
401
+ * country code; a number value is read as its text); the dialog and the row keep it as uploaded. Default: the text
402
+ * trimmed.
403
+ */
404
+ readonly dialNumber?: ((msisdn: string) => string) | DataExpr;
405
+ /**
406
+ * With `dialNumber`: a number value of the dialog's msisdn (not a text) is dialled as its text (default true);
407
+ * `false`: such a leg is not placed (`no msisdn`), as without `dialNumber`.
408
+ */
409
+ readonly numberMsisdn?: boolean;
410
+ /**
411
+ * The leg lines name the trunk the `trunkPool` picked: the first leg's line is `{ msisdn, entryPoint, selectedTrunk,
412
+ * trunkNumber, trunkId }` (`selectedTrunk`: the trunk's name, `trunkNumber`: its caller ID), the failed-leg redial
413
+ * lines (`failed_leg_redial_scheduled` / `_skipped`) carry `selectedTrunk`, `trunkNumber` after `callUuid` in place
414
+ * of the campaign's recall values and the handler. Default off.
415
+ */
416
+ readonly trunkLog?: boolean;
417
+ /** The trunk of the leg when the dialog params name none (before the dialog env's). */
418
+ readonly trunkId?: number;
419
+ /**
420
+ * SIP extras (headers: caller id…) every leg carries; the dialog params' own (`proto_additional`) go on top, or with
421
+ * `protoAdditionalOver` these win (a header named in both, in any case, is the agent's).
422
+ */
423
+ readonly protoAdditional?: Readonly<Record<string, string>>;
424
+ readonly protoAdditionalOver?: boolean;
425
+ /** The headless handler named on the leg for when it connected (its `after_call_success` pass runs `afterLeg`). */
426
+ readonly onSuccessCall?: string;
427
+ /**
428
+ * The headless handler named on the leg for a dial that never connected (the `failedLegPass` pass). Default
429
+ * `on_failed_call`; `null` names none (the platform's own continuation runs the pass, or — without `failedLegPass`
430
+ * — the leg nobody answered is reported by the live pass and the platform's own recall chain stays on).
431
+ */
432
+ readonly onFailedCall?: string | null;
433
+ /**
434
+ * A hook re-routing one leg, `hook(call, { msisdn })` → `{ msisdn, channel?, protoAdditional? }` or `null` (e.g.
435
+ * test numbers over a test trunk).
436
+ */
437
+ readonly route?: HookRef<H, 'route'>;
438
+ /** Re-routing rules as data (compiled to `route`; the first that holds; then `trunkPool`). */
439
+ readonly routeRules?: readonly RouteRule[];
440
+ /** Every leg over a trunk of the pool, picked at random (compiled to `route`). */
441
+ readonly trunkPool?: TrunkPool;
442
+ /** Callbacks at the time the caller named, booked after a connected call. */
443
+ readonly callbacks?: CallbackPolicy;
444
+ /**
445
+ * The `after_call_failed` pass of a leg redials the number itself: `'campaign'` (with `failedLegPass`, after the
446
+ * leg's row) by the campaign's contact rule a leg naming a handler gives up — at most `recallCount` redials,
447
+ * `recallDelay` seconds apart, counted in the dialog env (the row's `attempt` counts them too); `'atOnce'` the
448
+ * leg again at once (no budget, no delay). Default: a post-call pass never dials.
449
+ */
450
+ readonly redialFailed?: 'campaign' | 'atOnce';
451
+ };
452
+ /**
453
+ * Agent code on the headless passes after a leg: `after_call_success` (a connected leg named `legs.onSuccessCall`)
454
+ * and `after_call_failed` (with `failedLegPass`, after the leg's row) — `hook(call, { pass: 'success' | 'failed' },
455
+ * api)`. `api.platform.redial({ delaySec })` places the dialog's next leg as the first was placed (`true` when
456
+ * placed), `api.dialogEnv(key, value)` writes the dialog env (`call.memory`), `api.platform.setDialogResult(value)`
457
+ * writes the platform dialog's result. An agent that owns its redials (which results, how many, when) decides them
458
+ * there.
459
+ */
460
+ readonly afterLeg?: HookRef<H, 'afterLeg'> | AfterLegPolicy;
461
+ readonly recall?: RecallSpec;
462
+ /**
463
+ * CMS links (record, transcript, LLM log) in the row; a host may depend on a source (e.g. platform region).
464
+ * `host`: call log and record links; `llmHost`: LLM log link (default `host`); `dialogHost`: LLM dialog link (default
465
+ * `host`). A host read from a source is resolved after the call: the row is built with the `default` and its links
466
+ * are moved to the resolved host before the row is reported.
467
+ */
468
+ readonly links?: false | {
469
+ readonly host?: Value<string>;
470
+ readonly llmHost?: Value<string>;
471
+ readonly dialogHost?: Value<string>;
472
+ };
473
+ /**
474
+ * Write the conversation to a per-call LLM dialog (`callUuid`) instead of the CMS dialog (default true).
475
+ * `'answered'`: the same, but the row of a dial that never connected names the CMS dialog (no LLM dialog was opened).
476
+ */
477
+ readonly llmDialogPerCall?: boolean | 'answered';
478
+ /** Language and voice flag set on the CMS dialog at call start. */
479
+ readonly dialogLocale?: {
480
+ readonly language: string;
481
+ readonly voiceFlag?: string;
482
+ };
483
+ /**
484
+ * A pass that must not go on (the record is unusable): `when` reads the pass's variables and returns the result to
485
+ * end it with, or `null`. Every pass ends there: the pre-call pass dials nothing, a live leg is refused unanswered.
486
+ * The row is the input fields with that result (`report.fields`; extraction facts empty); with `report: true` the
487
+ * links are resolved and the after-call integrations run on it (their `when` sees the row).
488
+ */
489
+ readonly cancel?: {
490
+ readonly when: ((call: CallView) => string | null) | DataExpr;
491
+ readonly report?: boolean;
492
+ };
493
+ /**
494
+ * Written to the platform dialog's result (the legacy dialog store then shows the dialog completed): after a
495
+ * connected call ended, and on the failed-leg pass of a leg that booked no redial. Default: not written.
496
+ */
497
+ readonly dialogResult?: string;
498
+ /** When `dialogResult` is written after a connected call: as it ends (default) or once its row is built. */
499
+ readonly dialogResultAt?: 'callEnd' | 'row';
500
+ }
501
+ /** Redials the script books (never on a dialog the script did not dial). */
502
+ export interface RecallSpec {
503
+ /** Redials allowed after the first attempt. */
504
+ readonly budget: Value<number>;
505
+ /** Compare `attempt` with the budget: `>` (default) or `>=`. */
506
+ readonly budgetCheck?: '>' | '>=';
507
+ /**
508
+ * The script owns the redial chain alone: every leg it places (the first and each redial) carries
509
+ * `recallCount: 0, recallDelay: 0` so the platform's own recall chain stays off, a repeated pre-call pass of the
510
+ * dialog places no second first leg, and the row's `triggers_callback` is written false (the redial is booked
511
+ * already). Default false.
512
+ */
513
+ readonly platformRecallOff?: boolean;
514
+ /**
515
+ * Delay before a redial; from a source, or by result label (`default` for the rest; each entry a number or a source,
516
+ * e.g. `{ busy: 3600, default: { from: { platform: true } } }`).
517
+ */
518
+ readonly delaySec: Value<number> | Readonly<Record<string, Value<number>>>;
519
+ /** Dedup key of a redial: SIP call UUID (default) or the attempt number. */
520
+ readonly dedupBy?: 'callUuid' | 'attempt';
521
+ /** Book the redial before the after-call integrations run (default: after them). */
522
+ readonly beforeIntegrations?: boolean;
523
+ /**
524
+ * Count attempts by a ledger of the legs the script placed (dialog env `dial_legs_scheduled`, `dial_leg_due_at`,
525
+ * `dial_attempts`) instead of by call UUID: every live pass counts one attempt; a failed-dial report counts only
526
+ * while a placed leg is uncounted and due (a repeated report writes no row and books nothing); no redial is booked
527
+ * while a placed leg is uncounted, nor on a dialog the script placed no leg on. Default false.
528
+ */
529
+ readonly legLedger?: boolean;
530
+ /** Entry point of the redialed leg (default `on_recall`). */
531
+ readonly entryPoint?: string;
532
+ }
533
+ export interface VoiceSpec {
534
+ /** One recognizer per language of `languages`; `undecided` runs while the language is not picked yet. */
535
+ readonly asr: Readonly<Partial<Record<LocaleCode | 'undecided', AsrSpec>>>;
536
+ readonly tts: TtsSpec;
537
+ /** Vendor VAD settings, passed through in the vendor's units (often frames, not ms). */
538
+ readonly vad: Readonly<Record<string, unknown>>;
539
+ readonly endOfTurn?: EndOfTurnSpec;
540
+ /**
541
+ * Drop finals whose peak VAD is below this (noise); a matcher can exempt lines. `over`: the peak of the speech
542
+ * segment the final closes (`segment`, default), or of everything heard since the previous final as well (`line`:
543
+ * a long answer spanning several segments keeps its louder start).
544
+ */
545
+ readonly minPeakVad?: number | {
546
+ readonly value: number;
547
+ readonly except?: Matcher;
548
+ readonly over?: 'segment' | 'line';
549
+ };
550
+ /** ASR finals rewritten before anything reads them. */
551
+ readonly corrections?: readonly {
552
+ readonly match: RegExp;
553
+ readonly replace: string;
554
+ }[];
555
+ /**
556
+ * Self-echo of the agent on the caller's line (an echoing line): a caller final that reproduces a run of one of the
557
+ * agent's last `lookback` spoken lines (at least `minEchoTokens` caller words covering `minAgentCoverage` of the
558
+ * line's distinct words, gaps up to `maxGapTokens`; or, shorter, a whole non-final sentence of the last line of at
559
+ * least `sentenceEchoMinTokens` words and nothing else) is dropped, or cut to the caller's own words around it,
560
+ * before anything (voicemail detection, the conversation) reads it. Words compare lower case without punctuation,
561
+ * one edit apart from 4 letters; `expandToken` turns a caller word (a number in digits) into the words the agent
562
+ * spoke. Off when absent.
563
+ */
564
+ readonly selfEcho?: {
565
+ readonly minEchoTokens: number;
566
+ readonly minAgentCoverage: number;
567
+ readonly maxGapTokens: number;
568
+ readonly lookback: number;
569
+ readonly sentenceEchoMinTokens: number;
570
+ readonly expandToken?: (word: string) => readonly string[] | null;
571
+ /**
572
+ * A caller word that is a number in figures (up to 9 digits, after one of `prefixes`, e.g. a currency letter;
573
+ * with an ordinal suffix of the pack when `ordinals`) is the pack's number words of the agent's first language
574
+ * (its ordinal words with a suffix) — `expandToken` as data. `true`: no prefixes, ordinals on.
575
+ */
576
+ readonly expandNumbers?: boolean | {
577
+ readonly prefixes?: readonly string[];
578
+ readonly ordinals?: boolean;
579
+ };
580
+ };
581
+ /** Lines dropped as fillers/echo before anything reads them. */
582
+ readonly dropLine?: Matcher;
583
+ /**
584
+ * A line `dropLine` dropped as a filler that matches this (a bare «uh-huh») is the caller's answer after all when
585
+ * nothing of the agent plays and the line is not held. Default none.
586
+ */
587
+ readonly dropLineAnswer?: RegExp;
588
+ /**
589
+ * Caller finals the conversation does not answer — speech over the greeting (or another opening line), lines
590
+ * dropped within `overtalk.guardMs` — still go to the transcript as caller lines, as heard. Default false: only
591
+ * lines that became (part of) a turn are written.
592
+ */
593
+ readonly transcriptHeard?: boolean;
594
+ /**
595
+ * Caller finals that are not the caller (e.g. an advert the line plays): ignored (logged) after the voicemail
596
+ * detectors read them — no turn, no transcript line.
597
+ */
598
+ readonly ignoreLine?: Matcher;
599
+ /** Ambient bed: a file / URL, or a CMS record (looked up under the dialog's voice flag); `volume` of its queue. */
600
+ readonly ambient?: {
601
+ readonly url?: Value<string>;
602
+ readonly record?: string;
603
+ readonly volume: number;
604
+ };
605
+ /** CMS record flag of the agent's clips (`play` records), when it is not the dialog's voice flag. */
606
+ readonly recordFlag?: string;
607
+ /**
608
+ * A reply that streamed nothing after `afterMs` (and nothing plays) gets one clip picked at random from `urls`
609
+ * (`{voice}`: the voice variant's tag) ahead of it, on the agent queue (alias `filler`).
610
+ */
611
+ readonly filler?: {
612
+ readonly urls: readonly string[];
613
+ readonly afterMs: number;
614
+ };
615
+ /** Clips played from a file or record (not TTS) are written to the platform's call transcript as agent lines. */
616
+ readonly clipTranscript?: boolean;
617
+ /**
618
+ * The recognizer follows the agent's replies: `detect` reads a reply as it streams and names the `voice.asr` key the
619
+ * caller will answer in (e.g. by its script), or `null`. The recognizer is re-created for that key when it differs;
620
+ * once the call left `noReturnTo` it never goes back to it (a brand name in a reply is not a switch). The keys
621
+ * detected reach texts and the row as `call.replyAsr` / `call.replyAsrKeys`.
622
+ */
623
+ readonly asrByReply?: AsrByReply;
624
+ /** Queues and volumes of the mixer when the defaults do not fit. */
625
+ readonly mixer?: Readonly<Record<string, number>>;
626
+ }
627
+ /**
628
+ * `voice.asrByReply`: how a streaming reply names the recognizer key the caller will answer in — a function
629
+ * (`detect`), or by the reply's script (`byScript`, data). `noReturnTo`: once the call left this key it never goes back.
630
+ */
631
+ export type AsrByReply = {
632
+ readonly detect: (textSoFar: string) => string | null;
633
+ readonly byScript?: undefined;
634
+ readonly noReturnTo?: string;
635
+ } | {
636
+ readonly byScript: ReplyScriptRule;
637
+ readonly detect?: undefined;
638
+ readonly noReturnTo?: string;
639
+ };
640
+ /**
641
+ * A Unicode script name as `\p{Script=…}` reads it (`Latin`, `Cyrillic`, `Devanagari`, `Tamil`, `Telugu`, `Kannada`,
642
+ * `Arabic`, `Han`, …).
643
+ */
644
+ export type UnicodeScript = 'Latin' | 'Cyrillic' | 'Devanagari' | 'Tamil' | 'Telugu' | 'Kannada' | 'Bengali' | 'Gujarati' | 'Gurmukhi' | 'Malayalam' | 'Oriya' | 'Arabic' | 'Thai' | 'Han' | 'Hangul' | 'Hiragana' | 'Katakana' | 'Greek' | (string & {});
645
+ /**
646
+ * The script of a text read by counting letters of each listed script: the script with the most letters wins (a tie:
647
+ * the one listed first); no winner when the text has none of them, when the winner has fewer than `minLetters`
648
+ * letters, or holds less than `minShare` of the letters of all listed scripts.
649
+ */
650
+ export interface ScriptRule {
651
+ /** Key → script; keys are what the rule names (a recognizer key, a language). Order breaks ties. */
652
+ readonly scripts: Readonly<Record<string, UnicodeScript>>;
653
+ /** Default 1. */
654
+ readonly minLetters?: number;
655
+ /** 0..1, default 0. */
656
+ readonly minShare?: number;
657
+ }
658
+ /** `voice.asrByReply.byScript`: the reply's script names the recognizer key; only keys of `switchTo` move it. */
659
+ export interface ReplyScriptRule extends ScriptRule {
660
+ /** Keys a reply may switch to (default: every key of `scripts`). A winner outside it leaves the recognizer alone. */
661
+ readonly switchTo?: readonly string[];
662
+ }
663
+ /**
664
+ * A recognizer picked per call from its variables (`voice.asr.<lang>.picks`, the first that applies): `when` holds
665
+ * and the call falls in the `share` (both when both are given). A pick without `name` keeps the agent's key.
666
+ */
667
+ export interface AsrPick {
668
+ readonly when?: Condition;
669
+ /**
670
+ * A share of calls in percent (`from`, clamped to 0..100; empty or not a number: `default`, else 0): a call is in it
671
+ * when FNV-1a 32 of `seed` (e.g. `{ template: '{call_uuid}#asr' }`) as a fraction of 2^32, times 100, is below it.
672
+ */
673
+ readonly share?: {
674
+ readonly from: Expr;
675
+ readonly default?: number;
676
+ readonly seed: Expr;
677
+ };
678
+ readonly name?: string;
679
+ readonly data?: AsrVendorSettings;
680
+ }
681
+ export interface AsrSpec {
682
+ readonly vendor?: Value<string>;
683
+ /** Recognizer key (absent: the platform's default key of the agent). */
684
+ readonly name?: string;
685
+ /** A recognizer picked per call from its variables (e.g. a share of calls on another vendor): its key and settings. */
686
+ readonly pick?: (call: CallView) => {
687
+ readonly name?: string;
688
+ readonly data?: AsrVendorSettings;
689
+ } | null;
690
+ /** The same as data: the first pick that applies (`pick` wins when both are given). */
691
+ readonly picks?: readonly AsrPick[];
692
+ /** Vendor language code (may differ from the locale code). */
693
+ readonly language: string;
694
+ /** Settings the recognizer's vendor reads (sent as they are). */
695
+ readonly data?: AsrVendorSettings;
696
+ }
697
+ /** Settings of a recognizer's vendor, sent to it as they are (the keys are the vendor's own). */
698
+ export interface AsrVendorSettings {
699
+ /** The vendor's recognition model (e.g. `nova-3`). */
700
+ readonly model?: string;
701
+ /** Words and phrases the recognizer favours (brand names). */
702
+ readonly phrase_list?: readonly string[];
703
+ /** VAIS: the enhanced model, the server (`host:port`) and the request timeout (ms). */
704
+ readonly vais_use_enhanced?: boolean;
705
+ readonly vais_endpoint?: string;
706
+ readonly vais_timeout?: number;
707
+ }
708
+ export interface EndOfTurnSpec {
709
+ readonly smartTurn?: Readonly<Record<string, unknown>>;
710
+ readonly finalizeDebounceMs?: number;
711
+ readonly quietWindowMs?: number;
712
+ /** While a partial matches (digits or a date being dictated), wait for the vendor's final, no early final. */
713
+ readonly holdOn?: Matcher;
714
+ /** One caller line is cut after this long. */
715
+ readonly maxUtteranceMs?: number;
716
+ /**
717
+ * The vendor's own final of an utterance an early (virtual) final already answered — it comes within `quietWindowMs`
718
+ * and is no turn — replaces that line's text in the call transcript (the recognizer's better wording), while the line
719
+ * is still the caller's last one. Default false: the transcript keeps the early final's text.
720
+ */
721
+ readonly vendorFinalInTranscript?: boolean;
722
+ }
723
+ /** Settings of the TTS vendor (ElevenLabs), sent to it as they are (the keys are the vendor's own). */
724
+ export interface TtsVendorSettings {
725
+ readonly voice_settings_stability?: number;
726
+ readonly voice_settings_similarity_boost?: number;
727
+ /** Speaking rate (1: the voice's own). */
728
+ readonly voice_settings_speed?: number;
729
+ /** Language of the synthesis (ISO 639-1, e.g. `vi`). */
730
+ readonly language_code?: string;
731
+ /** Audio format of the vendor's answer (e.g. `pcm_16000`). */
732
+ readonly output_format?: string;
733
+ /** The platform's cache of synthesized lines, keyed by `flag`. */
734
+ readonly cache?: {
735
+ readonly flag: string;
736
+ };
737
+ }
738
+ /** A fact of the call's language state a prompt variable reads (`prompt.callVars`). */
739
+ export type LanguageCallVar = 'languageName' | 'languageProvisional' | 'language';
740
+ /** How `voice.tts.variants` are picked without a call variable naming one. */
741
+ export type VariantPickMode = 'modulo' | 'range' | 'random';
742
+ /** The agent's voice: the engine's fields; the vendor's settings ({@link TtsVendorSettings}) go to the vendor. */
743
+ export interface TtsSpec extends TtsVendorSettings {
744
+ readonly vendor?: string;
745
+ readonly name?: string;
746
+ readonly voiceId: Value<string>;
747
+ readonly model?: Value<string>;
748
+ /** How the reply text is cut for synthesis (the SDK's `ttsStrategy`): by sentence, streamed as it comes, or whole. */
749
+ readonly strategy?: 'sentence' | 'streaming' | 'full';
750
+ /**
751
+ * Keep one TTS session for the call; `openTimeoutMs`: give up on the session after this long (default 10 s): the call
752
+ * goes on without it, as when it fails to open; one that opens later is closed.
753
+ */
754
+ readonly session?: boolean | {
755
+ readonly openTimeoutMs: number;
756
+ };
757
+ /**
758
+ * Voice variants picked per call (A/B): by a stable hash of the call UUID, weighted. The tag goes to the report
759
+ * and selects the matching recorded clips (`{voice}` in record names/URLs).
760
+ */
761
+ readonly variants?: readonly {
762
+ readonly tag: string;
763
+ readonly voiceId: string;
764
+ readonly model?: string;
765
+ readonly weight?: number;
766
+ readonly session?: boolean;
767
+ /** The TTS chunking of this variant's plays (default the voice's `strategy`). */
768
+ readonly strategy?: 'sentence' | 'streaming' | 'full';
769
+ /** Vendor settings of this voice (e.g. its speed), over the `tts` ones. */
770
+ readonly settings?: TtsVendorSettings;
771
+ /**
772
+ * Values that travel with this voice (a persona's name, pronouns): the call variable `variantVar` is
773
+ * `{ tag, ...vars }` of the call's variant, set before the input fields (they read `{ var: 'voice.name' }`).
774
+ */
775
+ readonly vars?: Readonly<Record<string, unknown>>;
776
+ }[];
777
+ /**
778
+ * How a variant is picked: `modulo` (default: FNV-1a of the call UUID modulo the total weight), `range` (the hash as
779
+ * a fraction of 2^32 scaled to the total weight — a variant of weight 1 in 100 takes the lowest 1 % of hashes),
780
+ * `random` (weighted, by the random source when the call variables are built; kept in `variantVar`), or `{ by }`:
781
+ * the tag the expression gives from the call variables (`otherwise` when it names no variant; default `modulo`).
782
+ */
783
+ readonly variantPick?: VariantPickMode | {
784
+ readonly by: Expr;
785
+ readonly otherwise?: VariantPickMode;
786
+ };
787
+ /** The call variable that holds `{ tag, ...vars }` of the call's variant (default `voice`); see `variants[].vars`. */
788
+ readonly variantVar?: string;
789
+ /**
790
+ * The variant of a call from its input variables (e.g. a persona the input picked, or a call variable holding the
791
+ * tag): the tag of one of `variants`. A tag that names none (or `null`) falls back to the hash pick.
792
+ */
793
+ readonly variantBy?: ((vars: Readonly<Record<string, unknown>>) => string | null | undefined) | DataExpr;
794
+ /**
795
+ * Respelling for the voice only (numbers, brands); transcript keeps the written text. `keepCase`: a match starting
796
+ * with a lower-case letter gets `say` with a lower-case first letter.
797
+ */
798
+ readonly respell?: readonly {
799
+ readonly match: RegExp | string;
800
+ readonly say: string;
801
+ readonly keepCase?: boolean;
802
+ }[];
803
+ /**
804
+ * How a streamed reply is respelled: each chunk as it comes (`chunk`, default), or up to its last space with the rest
805
+ * held for the next chunk (`word`: a word split across chunks is still respelled).
806
+ */
807
+ readonly respellBy?: 'chunk' | 'word';
808
+ /** What `respell` applies to: every spoken line (`all`, default) or only the conversation's LLM replies (`replies`: not the greeting, not fixed lines or clips). */
809
+ readonly respellScope?: 'all' | 'replies';
810
+ /**
811
+ * Fixed lines put into the TTS cache when the call starts (before the opening's first line, on the call's TTS
812
+ * session; nothing without one): said later, they start without the synthesis delay.
813
+ */
814
+ readonly presay?: readonly string[] | ((call: CallView) => readonly string[]) | DataExpr;
815
+ /**
816
+ * A delivery tag the TTS vendor reads (e.g. a style tag in brackets) put in front of every sentence of every spoken
817
+ * line (each sentence is synthesized alone, so each needs it); the transcript keeps the text without it. A sentence
818
+ * ends at `.`, `!`, `?` or `…` followed by a space (a closing `...` stays with the sentence before it).
819
+ */
820
+ readonly sentenceTag?: string;
821
+ }
822
+ export interface InputSpec<H = UntypedHooks> {
823
+ /** Call variables. A field reads its sources and formats the value; `group` builds a nested object. */
824
+ readonly fields: Readonly<Record<string, FieldSpec | {
825
+ readonly group: Readonly<Record<string, FieldSpec>>;
826
+ }>>;
827
+ /** Time zone for dates, `today`, time of day. */
828
+ readonly timeZone: string;
829
+ /**
830
+ * `{ header }` also reads the dialer's header bag from the dialog env under this key (e.g. `proto_additional`),
831
+ * when the dialog parameters and the call row carry none; the INVITE headers still come last. Default: not read.
832
+ */
833
+ readonly headerBagEnvKey?: string;
834
+ /**
835
+ * Values written to the dialog env, read back by later passes with `{ dialogEnv }` sources / `call.memory`: `value`
836
+ * from the call's variables (`undefined` leaves the key); skipped when `unless` holds for the value already there
837
+ * (e.g. a date kept since the dialog's first call). `on`: the passes that write it — `'call'` (default: when the call
838
+ * is set up, on the live pass and on the failed-leg pass of a leg that never connected; not the pre-call pass) or
839
+ * `'everyPass'` (every pass of the dialog once its variables are read: the pre-call pass, the live call, the passes
840
+ * after a leg; e.g. a client callback URL the after-call pass needs when its own dialog params lack it).
841
+ */
842
+ readonly dialogEnv?: readonly {
843
+ readonly key: string;
844
+ readonly value: ((call: CallView) => unknown) | DataExpr;
845
+ /** As a condition: the current value is `{ self: true }`. */
846
+ readonly unless?: ((current: unknown) => boolean) | Condition;
847
+ readonly on?: 'call' | 'everyPass';
848
+ }[];
849
+ /** Fields that must be present; a missing one is logged. */
850
+ readonly required?: {
851
+ readonly fields: readonly string[];
852
+ readonly onMissing: 'log';
853
+ };
854
+ /**
855
+ * The call's data from a client service, read at answer on a live call while the opening's first clip plays:
856
+ * `hook(call, undefined, api)` (`call.vars`: the input fields; `api.http`, `api.storage`) returns the value of the
857
+ * field `field`, and the call's variables are built again with it (every field computed from it follows: the prompt,
858
+ * texts, step conditions, the row). LLM requests wait for it: an eager greeting is requested once it is in, its
859
+ * step's `when` reading the new variables; the row of a call that ended first waits for it too. `result`: the call's
860
+ * result from then on (e.g. a record the client says must not be talked to), unless the call is closing already. A
861
+ * hook that throws leaves the variables as they were (logged `input_lookup_failed`). Default: none.
862
+ */
863
+ readonly lookup?: {
864
+ /** The hook, or an integration of `phase: 'lookup'` whose `value` is the field's value (`{ integration: id }`). */
865
+ readonly hook?: HookName<H, 'lookup'>;
866
+ readonly integration?: string;
867
+ readonly field: string;
868
+ readonly result?: ((vars: Readonly<Record<string, unknown>>) => string | null | undefined) | DataExpr;
869
+ };
870
+ /** Test values: switched on by a source, used only when the real value is empty. */
871
+ readonly testData?: {
872
+ readonly enabledBy: Source;
873
+ /**
874
+ * Field → value; a function also gets the value that switched test data on (e.g. a preset name) and the call facts.
875
+ * One of `values` / `presets`.
876
+ */
877
+ readonly values?: Readonly<Record<string, unknown>> | ((call: CallView, enabled: unknown, facts?: CallFacts, sourced?: Readonly<Record<string, unknown>>) => Readonly<Record<string, unknown>>);
878
+ /** QA records as data: presets picked by the switch's value (compiled to `values`). */
879
+ readonly presets?: TestPresets;
880
+ readonly onlyWhenEmpty?: boolean;
881
+ /** No test values at all when any of these fields has a value from its sources (a real customer record). */
882
+ readonly unlessAnyOf?: readonly string[];
883
+ };
884
+ }
885
+ /** Facts of the call every computed field sees: the day and the wall clock in `input.timeZone`. */
886
+ export interface CallFacts {
887
+ readonly today: {
888
+ readonly year: number;
889
+ readonly month: number;
890
+ readonly day: number;
891
+ };
892
+ readonly now: Date;
893
+ readonly hour: number;
894
+ readonly minute: number;
895
+ readonly timeZone: string;
896
+ }
897
+ export interface FieldSpec {
898
+ /**
899
+ * Sources in order, or a value computed from the fields declared before this one (fields are evaluated in
900
+ * declaration order) and the call facts.
901
+ */
902
+ readonly from?: Source | readonly Source[] | ((vars: Readonly<Record<string, unknown>>, facts: CallFacts) => unknown) | DataExpr;
903
+ /** Used when no source gives a value, and when the formatted value is empty. A function sees the vars so far. */
904
+ readonly default?: unknown | ((vars: Readonly<Record<string, unknown>>, facts: CallFacts) => unknown);
905
+ /**
906
+ * Locale formatter: how the value is read out — `amount` (`currency`), `date` (`style`, or `pattern` with the tokens
907
+ * `YYYY MM M DD D MMMM MMM dddd ddd`; a string value is parsed as a calendar date), `number`, `digits`, `name`,
908
+ * `text`, `count` (`forms`), `timeOfDayGreeting` / `timeOfDay` (of the call hour when the field has no `from`),
909
+ * `relativeDay`. Other keys are passed to the pack's formatter as options; `locale` formats with another bundled
910
+ * pack (e.g. English month abbreviations in a machine date).
911
+ */
912
+ readonly format?: string | {
913
+ readonly kind: string;
914
+ readonly locale?: LocaleCode;
915
+ readonly [k: string]: unknown;
916
+ };
917
+ /** Also expose to the prompt (default true); `omitEmpty` drops the key when there is no value. */
918
+ readonly prompt?: boolean | 'omitEmpty';
919
+ /** `uri`: a string read from an `X-*` header (`header` / `proto` source) is URI-decoded (a malformed one is kept). */
920
+ readonly decode?: 'uri';
921
+ /**
922
+ * A reader applied to the value the sources (or `from`) gave, before `default` and `format` (`'msisdn'`,
923
+ * `{ kind: 'date', orders: ['mdy'] }`, `{ kind: 'amount', separators: 'lastIsDecimal' }` …; see the data language).
924
+ * An empty read value takes `default`.
925
+ */
926
+ readonly read?: ReadSpec;
927
+ /**
928
+ * Readers run on each source's value in turn (in order) before the first value that is not empty is taken (e.g. line
929
+ * breaks stripped, then URI-decoded: a source that is empty once cleaned gives way to the next). `read` still runs on
930
+ * the value taken.
931
+ */
932
+ readonly readEach?: ReadSpec | readonly ReadSpec[];
933
+ /**
934
+ * A secret of the call (a one-time code): the field, and the dialog parameters / headers it reads, are written as
935
+ * `[redacted]` in the integration-context log line. Default false.
936
+ */
937
+ readonly secret?: boolean;
938
+ }
939
+ export interface PromptSpec {
940
+ /** System instruction template, rendered by the platform with the call's variables. */
941
+ readonly template: string;
942
+ readonly engine?: 'squirrelly' | 'jinja';
943
+ /** Extra variables only the prompt sees; a function is evaluated before every LLM request. */
944
+ readonly vars?: Readonly<Record<string, unknown>> | ((call: CallView) => Readonly<Record<string, unknown>>) | RecordExpr;
945
+ /**
946
+ * Variable sets picked by the call (scenario variants): the first `when` that holds is added to the prompt's
947
+ * variables (after the input fields and `vars`), at every LLM request. `vars` may be computed from the call.
948
+ */
949
+ readonly variants?: readonly {
950
+ readonly when: ((call: CallView) => boolean) | Condition;
951
+ readonly vars: Readonly<Record<string, unknown>> | ((call: CallView) => Readonly<Record<string, unknown>>) | RecordExpr;
952
+ }[];
953
+ /**
954
+ * First message to the LLM after a fixed opening: what was already said. Placeholders (also `call.vars` of a text
955
+ * function): `{said_1}`, `{said_2}`… (opening lines spoken, in order), `{callerLine}` (the turn's text, marks
956
+ * included), `{firstReply}` (the caller's answer to the opening, lines joined with ` | `; empty when none),
957
+ * `{language}` (reply language as `languageNames` names it), `{askedLanguage}` (language of the opening question),
958
+ * `{provisional}`.
959
+ */
960
+ readonly handoff?: Text;
961
+ /**
962
+ * How the prompt names the call languages in markers and reasons (`{language}`, `reply_language=…`); default the
963
+ * locale code.
964
+ */
965
+ readonly languageNames?: Partial<Record<LocaleCode, string>>;
966
+ /**
967
+ * Prompt variables of every LLM request read from the call's language state: name → fact (`languageName`: the reply
968
+ * language as `languageNames` names it; `languageProvisional`: whether it is still a provisional pick; `language`:
969
+ * its locale code). They come first, `vars` and `variants` after (a key they set wins, in its place). `true`: the usual
970
+ * set `{ reply_language: 'languageName', reply_language_provisional: 'languageProvisional', opening_language:
971
+ * 'languageName' }`. Absent or `false`: none.
972
+ */
973
+ readonly callVars?: Readonly<Record<string, LanguageCallVar>> | boolean;
974
+ /** Text the LLM gets for a silence turn; placeholders `{attempt}`, `{heardSpeech}`. */
975
+ readonly silenceSignal: Text;
976
+ /** Text the LLM gets after an LLM/connection error (absent: the error only ends the turn). */
977
+ readonly errorSignal?: string;
978
+ /**
979
+ * Lines the agent spoke without the LLM (fixed replies, silence probes, re-asks; not closing lines) reach the LLM in
980
+ * front of the caller's next line, each as `mark` with `{line}` filled, joined by spaces.
981
+ */
982
+ readonly systemNotes?: {
983
+ readonly mark: string;
984
+ };
985
+ /** Keep one LLM stream open for the call. */
986
+ readonly persistentStream?: boolean;
987
+ /**
988
+ * LLM requests whose text is one of the agent's own signals (an LLM greeting's `signal`, `silenceSignal`, a silence
989
+ * rung's `llm` text) go with `hidden: true` (the platform keeps them out of the visible dialog). Default false: no
990
+ * `hidden` option is sent.
991
+ */
992
+ readonly hiddenSignals?: boolean;
993
+ }
994
+ /** Something played: a CMS record (by name, may use `{voice}`) or URL, or TTS of `text` when there is no record. */
995
+ export interface PlaySpec {
996
+ readonly record?: string;
997
+ readonly url?: string;
998
+ /** Text of the clip: written to the transcript; spoken by TTS when the record is missing. */
999
+ readonly text: Text;
1000
+ /** Wait this long after the clip before going on. */
1001
+ readonly tailMs?: number;
1002
+ /** Wait this long before the clip starts (speech heard meanwhile counts as speech over it). Default 0. */
1003
+ readonly delayMs?: number;
1004
+ /** The clip counts as playing at least this long from the moment it is played (before `tailMs`). */
1005
+ readonly minPlayMs?: number;
1006
+ /** The caller can cut the clip (default false: clips of the opening and re-prompts play to the end). */
1007
+ readonly bargeIn?: boolean;
1008
+ /** Queue alias of the clip (default: the record name, else `play-<n>`). */
1009
+ readonly alias?: string;
1010
+ /**
1011
+ * The clip has played when the agent queue says its item finished, not when the platform's play call returns (a
1012
+ * clip the caller hung up on is then not in the transcript).
1013
+ */
1014
+ readonly waitFinished?: boolean;
1015
+ /**
1016
+ * A sequence of CMS records read from the call (e.g. one clip per digit of a code), played one after another in
1017
+ * place of `record`; `gapMs` of pause between two of them (not after the last). `text` as a function gets each
1018
+ * record's name as its line. An empty list plays nothing. Only on an opening `play` step. As data: an expression
1019
+ * giving the list (its empty items dropped), e.g. one record per character of a variable:
1020
+ * `{ each: { list: { var: 'otp' }, split: '' }, to: { template: 'digit_{item}' } }`.
1021
+ */
1022
+ readonly records?: ((call: CallView) => readonly string[]) | DataExpr;
1023
+ readonly gapMs?: number;
1024
+ /**
1025
+ * Every record `records` may name: looked up once at answer with the other clips (the lookups, and their log lines,
1026
+ * then do not follow the call's sequence). Without it each record is looked up when first played.
1027
+ */
1028
+ readonly recordSet?: readonly string[];
1029
+ }
1030
+ /**
1031
+ * The opening is a list of steps run in order. A step waits for what it needs (playback end, caller line, silence)
1032
+ * and moves on, or ends the call through its actions. When the list ends the LLM takes over (`prompt.handoff`).
1033
+ */
1034
+ export type OpeningStep<H = UntypedHooks> = OpeningStepKind<H> & {
1035
+ /**
1036
+ * The step runs only on a call where this holds (read when the step's turn comes); otherwise it is skipped. E.g. a
1037
+ * call the caller placed skips the liveness clip meant for a call the agent placed.
1038
+ */
1039
+ readonly when?: ((call: CallView) => boolean) | Condition;
1040
+ };
1041
+ export type OpeningStepKind<H = UntypedHooks> = ({
1042
+ readonly step: 'play';
1043
+ } & PlaySpec)
1044
+ /** `text` as a list: said part by part (see the `say` action). */
1045
+ | {
1046
+ readonly step: 'say';
1047
+ readonly text: Text | readonly Text[];
1048
+ readonly alias?: string;
1049
+ readonly bargeIn?: boolean;
1050
+ }
1051
+ /** The LLM says the greeting (requested while earlier steps play). `fallback` when it is late or empty. */
1052
+ | {
1053
+ readonly step: 'llmGreeting';
1054
+ readonly signal: string;
1055
+ readonly waitMs: number;
1056
+ readonly eager?: boolean;
1057
+ /**
1058
+ * Said instead when the greeting streamed no text (its stream failed, or `firstTokenMs` passed with nothing): a
1059
+ * clip (record / URL / TTS of its text) or a text (said by TTS with the reply voice) that counts as playing at least
1060
+ * its text's `turn.drainFloor` from the moment it is played (and a clip's `minPlayMs`).
1061
+ */
1062
+ readonly fallback?: PlaySpec | Text;
1063
+ /** The greeting's stream ends empty when its first chunk has not come this long after it was requested. */
1064
+ readonly firstTokenMs?: number;
1065
+ /**
1066
+ * The caller can cut the greeting this long after it started playing (default: never). A cut greeting ends the
1067
+ * opening at once: speech heard before the cut is dropped, the line that cut it is the first turn.
1068
+ */
1069
+ readonly bargeInAfterMs?: number;
1070
+ }
1071
+ /**
1072
+ * Wait for the caller.
1073
+ * - `silence`: ladder before any caller line; its rungs may `play` re-prompts, `next` (go on regardless) or close;
1074
+ * - `speechOverPrevious`: what speech over the previous step means;
1075
+ * - `answer`: whether the caller's line goes to the LLM (default), only to the transcript, or nowhere;
1076
+ * - `voiceWithoutTextMs`: VAD heard the caller but no final came: the step is answered (with nothing) this long
1077
+ * after the voice ends, at the latest `voiceWithoutTextMaxMs` (default the same) after it first started; counted
1078
+ * from the first voice of the opening (also over the clip before the step), until the opening's LLM greeting
1079
+ * starts; a clip still playing (or its tail) defers it in 200 ms steps;
1080
+ * - `transcriptLine`: written to the transcript as a caller line each time a rung of `silence` fires (e.g.
1081
+ * `[silence]`);
1082
+ * - `toLlmWhen`: an answer that matches goes to the LLM as the first turn whatever `answer` says, and the rest of
1083
+ * the opening is skipped (an LLM greeting still to come is not played; its eager request, still in the LLM's
1084
+ * history, is waited for first, at most the greeting's `waitMs`). For answers that carry the caller's intent.
1085
+ */
1086
+ | {
1087
+ readonly step: 'listen';
1088
+ readonly silence?: readonly SilenceRung[];
1089
+ readonly speechOverPrevious?: 'answer' | 'drop' | {
1090
+ readonly keepIfWithinMs: number;
1091
+ };
1092
+ readonly answer?: 'toLlm' | 'transcriptOnly' | 'discard';
1093
+ readonly voiceWithoutTextMs?: number;
1094
+ readonly voiceWithoutTextMaxMs?: number;
1095
+ readonly transcriptLine?: string;
1096
+ readonly toLlmWhen?: Matcher;
1097
+ /**
1098
+ * The window does not start over when the caller speaks: when it runs out while they speak, it fires when the
1099
+ * speech ends (checked every `pollMs`), at most `maxMs` after it ran out.
1100
+ */
1101
+ readonly holdWhileSpeaking?: {
1102
+ readonly pollMs: number;
1103
+ readonly maxMs: number;
1104
+ };
1105
+ }
1106
+ /**
1107
+ * Pick the reply language among `languages`. The library runs the evidence ladder from the locale packs
1108
+ * (`LocalePack.evidence`): strong/weak markers, explicit requests, neutral lines. A pick may stay provisional and be
1109
+ * revised on later lines; `askedIn` reads a plain «yes» to a question asked in that language as consent to it;
1110
+ * `fallback` switches one way after N lines plainly in that language.
1111
+ */
1112
+ | {
1113
+ readonly step: 'language';
1114
+ /** The language(s) the opening question may be asked in whose plain «yes» settles it (one or a list). */
1115
+ readonly askedIn?: LocaleCode | readonly LocaleCode[];
1116
+ /** What counts as a plain «yes» to that question. Default: every word of the line is in a `yes` lexicon. */
1117
+ readonly plainYes?: Matcher;
1118
+ /**
1119
+ * The opening asked a question whose short answer names the language (e.g. «may I go on in X?»): the opening
1120
+ * answer (or the speech before the question) matching an entry picks its language for good, before the
1121
+ * evidence ladder (reason `opening_answer:<language>`). First match wins. Default none.
1122
+ */
1123
+ readonly answers?: readonly {
1124
+ readonly match: Matcher;
1125
+ readonly language: LocaleCode;
1126
+ }[];
1127
+ readonly provisional?: boolean;
1128
+ readonly fallback?: {
1129
+ readonly to: LocaleCode;
1130
+ readonly afterLines: number;
1131
+ readonly resetOnOther?: boolean;
1132
+ };
1133
+ /** The caller can ask for a language at any time of the call (default true). */
1134
+ readonly honourRequests?: boolean;
1135
+ /** Words that carry no language evidence besides the packs' own (brand and product names). */
1136
+ readonly neutral?: readonly string[];
1137
+ /** Words of the packs' neutral lists this agent reads as evidence (another campaign's product words). */
1138
+ readonly notNeutral?: readonly string[];
1139
+ /** Strong markers of a language besides its pack's (words of the agent's campaign); each tests one word. */
1140
+ readonly strong?: Partial<Record<LocaleCode, readonly RegExp[]>>;
1141
+ /**
1142
+ * Marker in front of the next LLM turn after the pick changed or settled in the conversation; placeholders
1143
+ * `{language}` (as `prompt.languageNames` names it) and `{reason}`.
1144
+ */
1145
+ readonly changeMark?: string;
1146
+ /**
1147
+ * When the recognizer follows a settled pick: at the caller's next turn (`nextTurn`, default) or as soon as the
1148
+ * opening ends (`openingEnd`: right after its last line went out; a provisional pick still waits).
1149
+ */
1150
+ readonly asrSwitch?: 'nextTurn' | 'openingEnd';
1151
+ }
1152
+ /** Run a gate's question now (see `gates`); `alias` names the line in the mixer and the transcript. */
1153
+ | {
1154
+ readonly step: 'gate';
1155
+ readonly gate: string;
1156
+ readonly alias?: string;
1157
+ readonly bargeIn?: boolean;
1158
+ } | {
1159
+ readonly step: 'hook';
1160
+ readonly name: HookName<H, 'step'>;
1161
+ }
1162
+ /**
1163
+ * End the call: say `text` (uninterruptible; nothing by default), then hang up `graceMs` after it played out
1164
+ * (default `closing.hangupGraceMs`) with `result`. An opening that ends this way is the whole call: `prompt`,
1165
+ * `silence` and `closing` may be left out, and `voice.asr` may be empty (no recognizer is started).
1166
+ */
1167
+ /**
1168
+ * Ends the call: its line (if any), then the hangup. The last step, or an earlier one with `when` (the call ends
1169
+ * there when it holds). `alias`: the line's mixer alias (default the step's key).
1170
+ */
1171
+ | {
1172
+ readonly step: 'close';
1173
+ readonly result: string | ((call: CallView) => string) | DataExpr;
1174
+ readonly text?: Text | null;
1175
+ readonly graceMs?: number;
1176
+ readonly reason?: string;
1177
+ readonly alias?: string;
1178
+ };
1179
+ /**
1180
+ * A question the call must settle (who is on the line, consent). The gate notices when the agent asks it (fixed text
1181
+ * or an LLM line matching `asked`), reads the next caller line with `answers`, marks the LLM's next turn, and closes
1182
+ * after `maxAsks` unanswered asks. Rules and texts can test the gate's flag `<id>.passed`.
1183
+ */
1184
+ export interface GateSpec {
1185
+ readonly id: string;
1186
+ /** Fixed question (used by the opening step) — and/or how to recognize the question in agent lines. */
1187
+ readonly question?: Text;
1188
+ readonly asked?: Matcher;
1189
+ /** Answer classes → matcher (locale lexicons usually). First match wins; no match is `other`. */
1190
+ readonly answers: Readonly<Record<string, Matcher>>;
1191
+ /** What each answer class does; `passed: true` sets `<id>.passed`; `mark` goes in front of the LLM's next turn. */
1192
+ readonly on: Readonly<Record<string, {
1193
+ readonly passed?: boolean;
1194
+ readonly mark?: string;
1195
+ }>>;
1196
+ /**
1197
+ * A passing answer the caller did not hear the reply to (their next line came before that reply played out) is
1198
+ * taken back unless the next line passes too; the LLM gets this marker in front of that line.
1199
+ */
1200
+ readonly unheardMark?: string;
1201
+ /** An agent line matching this passes the gate (the agent went past the question, e.g. it named the debt). */
1202
+ readonly passedBy?: Matcher;
1203
+ /**
1204
+ * Which agent line an answer answers: the last one, skipping lines matching `skip` («please repeat»); a line matching
1205
+ * `reask.match` («can you hear me?») still lets the classes in `reask.answers` answer the question before it.
1206
+ * An answer passes only when every caller line since the agent's last line is of a passing class.
1207
+ */
1208
+ readonly skip?: Matcher;
1209
+ readonly reask?: {
1210
+ readonly match: Matcher;
1211
+ readonly answers: readonly string[];
1212
+ };
1213
+ /** After `maxAsks` questions (agent lines matching `asked`) a line of no class runs `onExhausted`. */
1214
+ readonly maxAsks: number;
1215
+ readonly onExhausted: Action | readonly Action[];
1216
+ }
1217
+ export interface TurnSpec<H = UntypedHooks> {
1218
+ /** Filters on the reply text before TTS, in order. */
1219
+ readonly filters?: readonly ReplyFilterSpec<H>[];
1220
+ /**
1221
+ * Empty LLM replies: what counts as empty, retry mode, how many in a row before `onExhausted`, fixed probes.
1222
+ * `errorEvent`: the LLM's error event name — a reply carrying it is not asked again, and when the limit is reached
1223
+ * after such a reply the result is `erroredResult` (instead of the `onExhausted` one).
1224
+ */
1225
+ readonly emptyReply?: {
1226
+ readonly retry: 'ellipsis' | 'same' | 'none';
1227
+ readonly max: number;
1228
+ /**
1229
+ * Fixed lines said, one per exhaustion, before `onExhausted` runs (the count starts over after each; a reply with
1230
+ * text resets the ladder). `alias` names the line (default `llm_unavailable_probe_<n>`).
1231
+ */
1232
+ readonly probes?: readonly (Text | {
1233
+ readonly text: Text;
1234
+ readonly alias?: string;
1235
+ })[];
1236
+ readonly onExhausted: Action<H> | readonly Action<H>[];
1237
+ readonly errorEvent?: string;
1238
+ readonly erroredResult?: string;
1239
+ };
1240
+ /**
1241
+ * A reply whose playback ended before its LLM stream did (cut by the stop of the turn before it) is asked again
1242
+ * with the same text up to this many times, not counted as empty.
1243
+ */
1244
+ readonly abortedRetries?: number;
1245
+ /**
1246
+ * Agent code told what the caller heard of each LLM reply of the conversation (not the greeting, not a goodbye):
1247
+ * `hook(call, { text, heard }, api)` — `heard: true` when the reply played to the end, `false` when it was cut by
1248
+ * the caller, superseded before it played, or asked again (`abortedRetries`). Called before the next request goes
1249
+ * out; what the hook keeps in `api.state` the prompt variables and filters read as `call.hookState` (in the reducer: a
1250
+ * snapshot taken before each event).
1251
+ */
1252
+ readonly replyPlayed?: HookRef<H, 'replyPlayed'>;
1253
+ /** Wait at least (floor) / at most (ceiling) this long for the reply to finish playing. */
1254
+ readonly drainFloor?: DrainFloorSpec;
1255
+ readonly drainCeiling?: {
1256
+ readonly msPerChar: number;
1257
+ readonly minMs: number;
1258
+ };
1259
+ /**
1260
+ * When a line counts as played out after its floor: when the agent queue runs dry (default), or (`queueIdle`) once
1261
+ * the queue's first clip started (within `startAllowanceMs`, else at once), nothing more was queued for 500 ms and at
1262
+ * least 45 ms per spoken character passed since that start; a closing line waits the drain ceiling of its text then.
1263
+ */
1264
+ readonly playedOut?: {
1265
+ readonly by: 'queueEmpty';
1266
+ } | {
1267
+ readonly by: 'queueIdle';
1268
+ readonly startAllowanceMs: number;
1269
+ };
1270
+ /** «Hello?» while the LLM is still thinking: hold it up to `maxMs` instead of starting a new turn. */
1271
+ readonly holdLivenessPrompt?: {
1272
+ readonly match: Matcher;
1273
+ readonly maxMs: number;
1274
+ };
1275
+ /**
1276
+ * A cap on the call's length in agent lines: once `count` lines played out (the opening's fixed lines included), `do`
1277
+ * runs at that drain (e.g. a hangup with its result). Default none.
1278
+ */
1279
+ readonly maxLines?: {
1280
+ readonly count: number;
1281
+ readonly do: Action<H> | readonly Action<H>[];
1282
+ };
1283
+ /**
1284
+ * A caller line split by the recognizer: speech heard over the reply within `windowMs` of the caller's previous
1285
+ * line (and not part of it) continues that line — when it is answered, the two go to the LLM as one and the
1286
+ * transcript's last caller line is rewritten (when it is still the last line). (A reply cut because the caller went
1287
+ * on speaking is `turn.carryOn`.)
1288
+ */
1289
+ readonly continuation?: {
1290
+ readonly windowMs: number;
1291
+ };
1292
+ /**
1293
+ * A caller who was only pausing takes the reply back. Speech that starts while the reply to their line is not on the
1294
+ * line yet (or within `startGraceMs` of its first audio) and brings words of its own (not the answered line again,
1295
+ * not a `voice.dropLine` filler) stops the reply as soon as those words come (a partial or the final), at most
1296
+ * `maxPlayedMs` into its audio; no turn starts then. The caller's next line goes to the LLM behind `mark` (`{line}`:
1297
+ * the line the stopped reply answered), so the whole line is answered once; when a silence window runs out first,
1298
+ * the LLM is asked with `lapsedMark` (say the stopped reply again). Default none.
1299
+ */
1300
+ readonly carryOn?: {
1301
+ readonly startGraceMs: number;
1302
+ readonly maxPlayedMs: number;
1303
+ readonly mark: string;
1304
+ readonly lapsedMark: string;
1305
+ };
1306
+ /**
1307
+ * A caller line said while the reply to their previous line is still in the making (nothing of it plays yet)
1308
+ * supersedes it: `'replace'` (default) asks the LLM with the new line alone; `'join'` asks with the previous line's
1309
+ * request text and the new line joined (the caller paused mid-sentence): one caller turn. The transcript keeps both
1310
+ * lines.
1311
+ */
1312
+ readonly supersede?: 'replace' | 'join';
1313
+ /** A line whose synthesis has not settled after this long counts as played (stuck TTS). Default 30 000. */
1314
+ readonly sayTimeoutMs?: number;
1315
+ /**
1316
+ * Agent code that judges a reply before any of it is spoken (`hook`). It is asked at the start of every LLM turn but
1317
+ * the greeting with `{ stage: 'start', request, trigger, regenerated, silence }` (`request`: the text sent to the LLM;
1318
+ * `trigger`: the caller's words the turn answers; `regenerated`: why this turn is a regeneration, or `null`) and
1319
+ * returns `null` (the reply is spoken as it comes) or `{ holdChars }`: the reply is held until its first sentence
1320
+ * ended and `holdChars` more characters came (or the stream ended). Each time the held text grows it is asked
1321
+ * `{ stage: 'held', held, final, request, trigger, regenerated }` (`final`: the hold is over) and returns `null` (keep
1322
+ * holding; spoken when the hold is over), `'release'` (spoken now), `{ regenerate: text }` (nothing of the reply is
1323
+ * spoken; the LLM is asked again with `text` when its stream ended — the regeneration keeps the turn's trigger and
1324
+ * carries the reason `review`), or `{ then: actions }` (nothing is spoken; the actions run when the stream ended).
1325
+ * As data: `{ start, held }` rules ({@link ReviewRules}).
1326
+ */
1327
+ readonly review?: HookRef<H, 'review'> | ReviewRules;
1328
+ /**
1329
+ * Rules on the streaming reply as data ({@link ReplyRuleSet}): sentence rules with counters (drop / cut / replace and
1330
+ * close), the unclear-reply ladder, a sentence inserted after the first one, a reply played as a recorded clip,
1331
+ * stray-script letters. Each set is one reply filter, run in order where `{ filter: 'replyRules' }` stands in
1332
+ * `filters` (first when not listed).
1333
+ */
1334
+ readonly replyRules?: readonly ReplyRuleSet[];
1335
+ /**
1336
+ * A reply with no words that started no transfer, on a turn that is not itself a regeneration (not the greeting), is
1337
+ * asked again once with this text (a text function sees the call and the caller's line) instead of handing the turn
1338
+ * back. `null` from the function: not asked again.
1339
+ */
1340
+ readonly regenerateEmpty?: {
1341
+ readonly signal: Text;
1342
+ };
1343
+ }
1344
+ /**
1345
+ * Hold a line at least `max(minMs, msPerChar × spoken chars)` counted `from` the turn start, the first chunk
1346
+ * (`spokenChunk`: likewise, but a reply nothing of which reached TTS counts from now), or the first audio of the turn (`playbackStart`: credited only with what already played; none played: from now), before the
1347
+ * agent queue's drain is waited for. `staticFrom`: how a fixed line counts (default `from`).
1348
+ */
1349
+ export interface DrainFloorSpec {
1350
+ readonly msPerChar: number;
1351
+ readonly minMs: number;
1352
+ readonly from: 'turnStart' | 'firstChunk' | 'playbackStart' | 'spokenChunk';
1353
+ readonly staticFrom?: 'turnStart' | 'firstChunk' | 'playbackStart' | 'spokenChunk';
1354
+ }
1355
+ export type ReplyFilterSpec<H = UntypedHooks> =
1356
+ /**
1357
+ * Stop the reply after a marker (goodbye, end of turn): at once (`at: 'match'`, default), or when the next chunk comes
1358
+ * (`'nextChunk'`: the stream ends there, or at its own end).
1359
+ */
1360
+ {
1361
+ readonly filter: 'cutAfter';
1362
+ readonly match: Matcher;
1363
+ readonly at?: 'match' | 'nextChunk';
1364
+ }
1365
+ /** Remove labels / tags (`snake_case:`, `<tag>`). */
1366
+ | {
1367
+ readonly filter: 'strip';
1368
+ readonly match: RegExp;
1369
+ }
1370
+ /**
1371
+ * A reply that is only a label is replaced by that label's line. `lines` lists them, or a hook names the line of a
1372
+ * label (`null`: the reply says nothing); with a hook any `snake_case` word alone is a label. With `lines`:
1373
+ * `match: 'snakeCase'` reads any `snake_case` word alone (any case, trailing `.…,:;!?` allowed) as a label, looked up
1374
+ * lower case (default `'exact'`: the reply trimmed is a listed label); `unknown: 'drop'`: a label not listed says
1375
+ * nothing (default `'keep'`: the reply as it is); `greeting: false`: not on the greeting turn. The hook form is
1376
+ * `{ match: 'snakeCase', unknown: 'drop', greeting: false }`.
1377
+ */
1378
+ | {
1379
+ readonly filter: 'labels';
1380
+ readonly lines: Readonly<Record<string, Text>> | HookRef<H, 'label'>;
1381
+ readonly match?: 'exact' | 'snakeCase';
1382
+ readonly unknown?: 'keep' | 'drop';
1383
+ readonly greeting?: boolean;
1384
+ }
1385
+ /** Where `closing.guard` reads the reply among the filters (default: first). */
1386
+ | {
1387
+ readonly filter: 'closingGuard';
1388
+ }
1389
+ /** Where `turn.replyRules` run among the filters (default: first). */
1390
+ | {
1391
+ readonly filter: 'replyRules';
1392
+ }
1393
+ /**
1394
+ * Drop sentences mostly in another script than the reply language (reasoning leaks); `allow` keeps listed words (a
1395
+ * function: the words of this call, e.g. its names). A sentence is dropped when its Latin letters are more than half of
1396
+ * its Latin and Cyrillic letters.
1397
+ */
1398
+ | {
1399
+ readonly filter: 'scriptLeak';
1400
+ readonly allow?: readonly string[] | ((call: CallView) => readonly string[]) | DataExpr;
1401
+ /**
1402
+ * A reply all of whose sentences were dropped is asked again with this note in front of its request (a new line
1403
+ * between); once, until a reply with words comes. Default: not asked again (an empty reply).
1404
+ */
1405
+ readonly retry?: string;
1406
+ } | {
1407
+ readonly filter: 'replace';
1408
+ readonly match: RegExp;
1409
+ readonly with: string | ((m: string) => string);
1410
+ }
1411
+ /**
1412
+ * Figures in the reply as words of the reply language (its pack's `format.text`), written into the reply itself — the
1413
+ * transcript and the extractor read the words.
1414
+ * `languages`: only replies in these (default every call language). A figure the stream split («1» + «999») is held
1415
+ * until the next chunk settles it.
1416
+ */
1417
+ | {
1418
+ readonly filter: 'numbersAsWords';
1419
+ readonly languages?: readonly LocaleCode[];
1420
+ }
1421
+ /** Insert a line after a chunk that matches (e.g. a disclosure after the introduction); `once` per call (default). */
1422
+ | {
1423
+ readonly filter: 'insertAfter';
1424
+ readonly match: Matcher;
1425
+ readonly text: Text;
1426
+ readonly once?: boolean;
1427
+ }
1428
+ /**
1429
+ * Cut the stream at word boundaries only. `space`: the space between two words ends the piece sent (`end`,
1430
+ * default) or starts the word held back (`start`: a piece never ends in a space).
1431
+ */
1432
+ | {
1433
+ readonly filter: 'wholeWords';
1434
+ readonly space?: 'end' | 'start';
1435
+ }
1436
+ /** Text sent to the LLM for a caller line (notes, parsed dates): applied to the request, not the reply. */
1437
+ /**
1438
+ * `perRequest`: the note is made from the caller's own words for every request — a reply asked again after it was cut
1439
+ * (`abortedRetries`) is annotated anew (it sees what changed meanwhile), and the echo check of speech over the reply
1440
+ * compares with the words, not the note.
1441
+ */
1442
+ | {
1443
+ readonly filter: 'annotateCaller';
1444
+ readonly with: Text;
1445
+ readonly perRequest?: boolean;
1446
+ }
1447
+ /**
1448
+ * Notes as data (`NoteEntry`): made in order on the caller's words, each with its condition, detector (day words, a
1449
+ * note ladder's rung, a choice) and place (in front, before the words, after). See `skill/references/blocks.md`.
1450
+ */
1451
+ | {
1452
+ readonly filter: 'annotateCaller';
1453
+ readonly notes: readonly NoteEntry[];
1454
+ readonly perRequest?: boolean;
1455
+ } | {
1456
+ readonly filter: 'hook';
1457
+ readonly name: HookName<H, 'replyText'>;
1458
+ }
1459
+ /**
1460
+ * The reply passes through the agent's hook as a stream (client rules on its wording that need more than one chunk:
1461
+ * hold the first sentence, drop or add a sentence, stop the reply). `hook(call, { chunk, at, turn }, api)` is asked once
1462
+ * when the reply starts (`at: 'start'`, `chunk: ''`), for every chunk (`'chunk'`) and once when its stream ended
1463
+ * (`'end'`, `chunk: ''`: pass on what was held); it returns the text to pass on now ({@link ReplyChunkAnswer}). A reply
1464
+ * cut or superseded before its stream ended gets no `end`. `api.state` is the call's hook state.
1465
+ */
1466
+ | {
1467
+ readonly filter: 'stream';
1468
+ readonly hook: HookName<H, 'replyChunk'>;
1469
+ }
1470
+ /**
1471
+ * The reply reaches TTS one sentence at a time (a sentence ends at a `.`/`!`/`?`/`।`/`…` followed by a space; the
1472
+ * rest at the reply's end), each judged by the agent's hook (client rules on its own wording):
1473
+ * `hook(call, { sentence, index, tag, silence }, api)` returns the sentence to speak (changed or not), `''` / `null`
1474
+ * to drop it, `{ cut: true }` to drop it and the rest of the reply, or `{ replace, alias?, close? }` to drop the reply
1475
+ * and say `replace` instead once it ended (`close: { result, reason? }` ends the call after it). `tag` is `bootstrap`
1476
+ * for the LLM greeting; `silence` marks a reply to a silence turn; `api.state` is kept for the whole call.
1477
+ */
1478
+ | {
1479
+ readonly filter: 'sentences';
1480
+ readonly hook: HookName<H, 'sentence'>;
1481
+ }
1482
+ /**
1483
+ * The reply is passed on one sentence at a time and stops at the first sentence matching `match` (e.g. the model's
1484
+ * own reasoning): nothing of it or after it is spoken. When nothing at all was spoken and the turn started no
1485
+ * transfer, it is asked again once with `regenerate` (not on a regeneration, not on the greeting).
1486
+ */
1487
+ | {
1488
+ readonly filter: 'cutAtSentence';
1489
+ readonly match: Matcher;
1490
+ readonly regenerate?: Text;
1491
+ };
1492
+ /** What a `sentences` filter hook returns for one sentence. */
1493
+ export type SentenceVerdict = string | null | {
1494
+ readonly cut: true;
1495
+ } | {
1496
+ readonly replace: string;
1497
+ readonly alias?: string;
1498
+ readonly close?: {
1499
+ readonly result: string;
1500
+ readonly reason?: string;
1501
+ };
1502
+ };
1503
+ /** What a `stream` reply filter hook reads: a chunk of the reply (or its start / end) and the turn it answers. */
1504
+ export interface ReplyChunkInput {
1505
+ readonly chunk: string;
1506
+ readonly at: 'start' | 'chunk' | 'end';
1507
+ /**
1508
+ * The reply's turn: `seq` its number (per-reply state in `api.state` is kept by it), `tag` (`bootstrap`: the LLM
1509
+ * greeting), `silence` (it answers a silence turn), `trigger` (the caller's words it answers).
1510
+ */
1511
+ readonly turn: {
1512
+ readonly seq: number;
1513
+ readonly tag: string;
1514
+ readonly silence: boolean;
1515
+ readonly trigger: string;
1516
+ };
1517
+ }
1518
+ /**
1519
+ * What a `stream` reply filter hook returns: the text to pass on now (`''` / `null`: nothing yet), or
1520
+ * `{ text?, then?, vars?, clip? }` — `text` passed on now; `then`: nothing more of the reply is spoken (its stream is
1521
+ * still read) and these actions run when it ended (as `turn.review`'s `then`); `vars`: call variables set when the reply
1522
+ * ended as the current turn having said something (the last `vars` given for the reply count; texts and prompt
1523
+ * variables read them as `call.vars`); `clip`: nothing more of the reply is synthesized, the clip `play` plays now in
1524
+ * its place and the reply counts as said as `line` (e.g. a reply that is the words of a recorded clip).
1525
+ */
1526
+ export type ReplyChunkAnswer<H = UntypedHooks> = string | null | undefined | {
1527
+ readonly text?: string;
1528
+ readonly then?: Action<H> | readonly Action<H>[];
1529
+ readonly vars?: Readonly<Record<string, unknown>>;
1530
+ readonly clip?: {
1531
+ readonly play: PlaySpec;
1532
+ readonly line: string;
1533
+ };
1534
+ };
1535
+ export interface OvertalkSpec<H = UntypedHooks> {
1536
+ /** Speech in the first ms of a reply does not interrupt it; `dropEcho` drops a final repeating the trigger line. */
1537
+ readonly guardMs: number;
1538
+ /**
1539
+ * A caller line heard over the agent's reply to a silence turn (the re-engagement the ladder asked for): buffered like
1540
+ * any speech over the agent (default), or answered at once (`answer`).
1541
+ */
1542
+ readonly overSilenceTurn?: 'buffer' | 'answer';
1543
+ /** Within `guardMs` a line matching this is dropped too (a bare call: «hello?»); other lines are buffered. */
1544
+ readonly guardDrop?: Matcher;
1545
+ /** A line heard within this long after a turn started, before any of it played, is speech over the agent too. */
1546
+ readonly pendingMs?: number;
1547
+ readonly dropEcho?: boolean;
1548
+ /**
1549
+ * What interrupts a reply: partial length, confirm time, VAD, and/or words (`match`, usually a locale lexicon).
1550
+ * Absent: speech over the agent never cuts a reply (it is buffered as below).
1551
+ */
1552
+ readonly interrupt?: {
1553
+ readonly minChars: number;
1554
+ readonly confirmMs: number;
1555
+ readonly minVad: number;
1556
+ readonly match?: Matcher;
1557
+ readonly byLength?: boolean;
1558
+ readonly requireText?: boolean;
1559
+ /**
1560
+ * The platform NLU reads the caller's partials while the agent speaks (`minChars` or longer, one request at a
1561
+ * time, at most one per `throttleMs`) and one of `intents` stops the agent (once per reply, whatever the VAD).
1562
+ */
1563
+ readonly intents?: {
1564
+ readonly intents: readonly string[];
1565
+ readonly minChars: number;
1566
+ readonly throttleMs: number;
1567
+ };
1568
+ /** The caller's speech stops the agent also while nothing of it plays yet (the reply still in the making is dropped). */
1569
+ readonly whileSilent?: boolean;
1570
+ /** What `minChars` counts in a partial: every character (default) or only letters and digits. */
1571
+ readonly minCharsOf?: 'chars' | 'letters';
1572
+ };
1573
+ /**
1574
+ * Agent code asked for the caller's line that follows a reply they cut (`hook(call, { heardMs })`, `heardMs`: how long
1575
+ * the reply had played when it was cut): a mark it returns goes in front of the line's LLM request (the turn's
1576
+ * trigger stays the line).
1577
+ */
1578
+ readonly cutMark?: HookRef<H, 'cutMark'> | DataExpr;
1579
+ /** Speech that did not interrupt is buffered and answered after the reply. */
1580
+ readonly buffer?: {
1581
+ readonly replayAfterGapMs: number;
1582
+ /** The gap counts from the agent queue running dry (`drained`, default) or from when the line was heard (`heard`). */
1583
+ readonly gapFrom?: 'drained' | 'heard';
1584
+ /**
1585
+ * Wait while the caller is still speaking before replaying (poll, max). `extend`: past `maxMs` agent code is asked
1586
+ * at each poll while the caller still speaks (`{ heardMs, msSinceLastPartial }`: how long the replay has been held,
1587
+ * how long ago the caller's last partial with text came — `null`: none yet) and `true` keeps waiting. As data
1588
+ * ({@link HoldExtendSpec}): while a partial came within `whilePartialWithinMs`, up to `maxHeldMs` held.
1589
+ */
1590
+ readonly holdWhileSpeaking?: {
1591
+ readonly pollMs: number;
1592
+ readonly maxMs: number;
1593
+ readonly extend?: HookRef<H, 'replayHold'> | HoldExtendSpec;
1594
+ };
1595
+ /**
1596
+ * Join buffered pieces into one line (a piece the buffer already holds is skipped); a piece heard more than
1597
+ * `windowMs` after the one before it, or one that would make the line longer than `maxChars`, replaces it;
1598
+ * `supersede`: a piece that holds the whole buffer replaces it.
1599
+ */
1600
+ readonly merge?: {
1601
+ readonly windowMs?: number;
1602
+ readonly maxChars?: number;
1603
+ readonly supersede?: boolean;
1604
+ };
1605
+ /** A line heard `leadMs` or more before the reply drained is replayed after `replayAfterGapMs` instead. */
1606
+ readonly earlyFragment?: {
1607
+ readonly leadMs: number;
1608
+ readonly replayAfterGapMs: number;
1609
+ };
1610
+ /**
1611
+ * A buffered line that predates the reply's question is replayed `replayAfterGapMs` after the drain (from the
1612
+ * drain, whatever `gapFrom` says): the reply's own question gets its answer first (a caller line meanwhile joins
1613
+ * the buffer). Which lines: `speechBeforeReply` — its speech began before the reply played (the rest of the
1614
+ * caller's previous line, not an answer to the reply); `heardBeforeDrain` — heard more than `olderThanMs` before
1615
+ * the reply drained, when that reply ended on a question (`?`). Default: like any buffered line.
1616
+ */
1617
+ readonly predating?: {
1618
+ readonly by: 'speechBeforeReply';
1619
+ readonly replayAfterGapMs: number;
1620
+ } | {
1621
+ readonly by: 'heardBeforeDrain';
1622
+ readonly olderThanMs: number;
1623
+ readonly replayAfterGapMs: number;
1624
+ };
1625
+ /**
1626
+ * Backchannels («yes», «uh-huh») over the agent are held: a buffered line that `match`es (default the locale lexicon
1627
+ * `backchannel`) waits `holdMs` after the drain instead of the replay gap; a caller line in that time replaces it (it
1628
+ * is dropped, not joined); otherwise it goes to the LLM with `marker` (`markerAt`: in front of the caller's words,
1629
+ * default, or after them; the transcript and the echo check keep the words alone). A buffered line is otherwise put
1630
+ * in front of the caller's next line heard before its replay (one turn).
1631
+ */
1632
+ readonly backchannel?: {
1633
+ readonly match?: Matcher;
1634
+ readonly holdMs: number;
1635
+ readonly marker: string;
1636
+ readonly markerAt?: 'before' | 'after';
1637
+ };
1638
+ /**
1639
+ * A silence window that runs out while a line is buffered: `true` (default) answers the buffered line at once;
1640
+ * `false` leaves it to its replay (armed again from then: the replay gap), and no silence rung runs.
1641
+ */
1642
+ readonly answerOnSilence?: boolean;
1643
+ /**
1644
+ * Without `merge` a new line replaces the buffered one, except here: a line that is no answer (`reverse.keep`) does
1645
+ * not replace a buffered answer, and a line of at most `interjectionMaxChars` characters (normalized) that is no
1646
+ * answer does not replace a longer one — unless the buffered line was heard before the sentence now playing and
1647
+ * `reverse.beforeLastSentence` will drop it. Default: the last line wins.
1648
+ */
1649
+ readonly keep?: {
1650
+ readonly interjectionMaxChars: number;
1651
+ };
1652
+ };
1653
+ /**
1654
+ * Speech the caller began before the reply started playing (at most `graceMs` after its start) is the rest of the
1655
+ * line the reply answers, not an answer to the reply's question: it is appended to that caller line in the
1656
+ * transcript (the extractor reads it) and to the line the echo check compares with, and is neither buffered nor
1657
+ * replayed. Not for a silence turn, a line already contained in the trigger line, or speech of unknown start.
1658
+ */
1659
+ readonly startedBeforeReply?: {
1660
+ readonly graceMs: number;
1661
+ };
1662
+ /**
1663
+ * Reverse guard: a buffered line said early in the reply is dropped when the reply already covered it — heard more
1664
+ * than `tailMs` before the drain (with `minTurnMs` alone: only on a reply that played at least that long), or (with
1665
+ * `positionRatio` and `minTurnMs`) in the first part of a long reply.
1666
+ */
1667
+ readonly reverse?: {
1668
+ readonly tailMs?: number;
1669
+ readonly positionRatio?: number;
1670
+ readonly minTurnMs?: number;
1671
+ readonly backchannelMaxChars?: number;
1672
+ /** Lines never dropped (answers, contact attempts). */
1673
+ readonly keep?: Matcher;
1674
+ /**
1675
+ * `'answerAtDrain'`: a line heard once the last part of a fixed line started playing (a line said in parts, see
1676
+ * the `say` action; a line of one part: the whole line) is never dropped and is answered as soon as the line
1677
+ * drained, without the replay gap (speech over the closing question of a long answer is its answer). Not for LLM
1678
+ * replies. Default: no exception.
1679
+ */
1680
+ readonly lastPart?: 'answerAtDrain';
1681
+ /**
1682
+ * A buffered line heard within this long of the reply's first audio (the caller began before the reply did, so it
1683
+ * cannot answer the reply's question) is dropped at the drain unless it matches `keep`. Default off.
1684
+ */
1685
+ readonly preReplyMs?: number;
1686
+ /**
1687
+ * A buffered line heard before the reply's last sentence (its last agent-queue item) started playing is dropped at
1688
+ * the drain, whatever it says: the question is the reply's last sentence. Lines within `preReplyMs` are left to
1689
+ * that rule. Default false.
1690
+ */
1691
+ readonly beforeLastSentence?: boolean;
1692
+ /**
1693
+ * None of the drops above (nor `tailMs`) applies to the reply of a silence turn: speech over it is the answer it
1694
+ * asked for. Default false.
1695
+ */
1696
+ readonly exceptSilenceTurn?: boolean;
1697
+ };
1698
+ }
1699
+ /**
1700
+ * One rung of a silence ladder: `afterMs` of silence counted from the end of the agent's last line (each rung starts
1701
+ * a new count). `when` skips the rung when false. The last rung usually closes the call.
1702
+ */
1703
+ export interface SilenceRung<H = UntypedHooks> {
1704
+ readonly afterMs: number;
1705
+ /** False: the rung is skipped (the next one acts now), or `otherwise` acts in its place. */
1706
+ readonly when?: ((call: CallView) => boolean) | Condition;
1707
+ readonly do: Action<H> | readonly Action<H>[];
1708
+ readonly otherwise?: Action<H> | readonly Action<H>[];
1709
+ /** Name of the rung in `silence.voidMark` (`{action}`). */
1710
+ readonly name?: string;
1711
+ }
1712
+ export interface SilenceSpec<H = UntypedHooks> {
1713
+ /** Ladder in the conversation. Rung action default: an LLM turn with `prompt.silenceSignal`. */
1714
+ readonly ladder: readonly SilenceRung<H>[];
1715
+ /** Ladder while the line is held (`hold` action). */
1716
+ readonly held?: {
1717
+ readonly rungs: readonly SilenceRung<H>[];
1718
+ };
1719
+ /** Window after a line the filters dropped (noise) — usually longer. */
1720
+ readonly afterDroppedLineMs?: number;
1721
+ /** Caller spoke (VAD) but ASR gave nothing: treat as a turn after `afterMs`; the first `excused` do not count. */
1722
+ readonly speechWithoutText?: {
1723
+ readonly afterMs: number;
1724
+ readonly excused?: number;
1725
+ readonly do?: Action<H> | readonly Action<H>[];
1726
+ /** Speech shorter than this (VAD start to end) is noise, not words the line lost. Default 0. */
1727
+ readonly minSpeechMs?: number;
1728
+ /** Written to the transcript as the caller's line each time it fires (e.g. `[inaudible]`). */
1729
+ readonly transcriptLine?: string;
1730
+ };
1731
+ /** No audio at all on the line. */
1732
+ readonly deadAudio?: {
1733
+ readonly ms: number;
1734
+ readonly do: Action<H> | readonly Action<H>[];
1735
+ };
1736
+ /**
1737
+ * The longest wait after an agent line for a caller line, however often speech starts and stops on the line: past it
1738
+ * the next pause (after the speech-without-text window) is a silence turn and new speech no longer puts it off.
1739
+ */
1740
+ readonly maxAwaitMs?: number;
1741
+ /** Nothing progresses (no caller line, no agent line) for this long. */
1742
+ readonly noProgress?: {
1743
+ readonly ms: number;
1744
+ readonly do: Action<H> | readonly Action<H>[];
1745
+ /** Actions while the opening is on (default `do`). */
1746
+ readonly inOpening?: Action<H> | readonly Action<H>[];
1747
+ };
1748
+ /**
1749
+ * No-words backstop: a silence turn of the ladder when no recognised word (a partial with text) came within N ms of
1750
+ * the end of the agent's line, whatever VAD says (line noise VAD reads as speech holds the ordinary window off);
1751
+ * every partial with text starts the wait over. Off when absent.
1752
+ */
1753
+ readonly noWordsMs?: number;
1754
+ /** The window while the caller has not said a line yet in the call (default: the rung's `afterMs`). */
1755
+ readonly beforeFirstLineMs?: number;
1756
+ /**
1757
+ * A silence turn whose reply the caller cut before hearing any of it is voided: the caller's line goes to the LLM
1758
+ * with this marker in front (placeholder `{action}`: the rung's `name`).
1759
+ */
1760
+ readonly voidMark?: string;
1761
+ /** Speech that never ends (no end of speech, no text) is disbelieved after this long. Default `endOfTurn.maxUtteranceMs`. */
1762
+ readonly speechLatchMaxMs?: number;
1763
+ }
1764
+ export interface VoicemailSpec<H = UntypedHooks> {
1765
+ readonly detectors: readonly VoicemailDetector[];
1766
+ /**
1767
+ * When detection acts: until the first caller line that reached the LLM (default — answers to liveness checks
1768
+ * during the opening do not count), or the whole call.
1769
+ */
1770
+ readonly scope?: 'beforeFirstTurn' | 'wholeCall';
1771
+ /** Default: hang up with result `voicemail`. */
1772
+ readonly then?: Action<H> | readonly Action<H>[];
1773
+ /** A line a detector caught on a partial is written to the platform's call transcript as a caller line. */
1774
+ readonly transcriptLine?: boolean;
1775
+ /** Detection runs only on a call where this holds (e.g. not on a call the caller placed). Default: every call. */
1776
+ readonly when?: ((call: CallView) => boolean) | Condition;
1777
+ }
1778
+ export type VoicemailDetector =
1779
+ /** Platform NLU on partials/finals; `fallback` phrases are checked only when the NLU did not answer. */
1780
+ {
1781
+ readonly by: 'nlu';
1782
+ readonly intents: readonly string[];
1783
+ readonly minChars?: number;
1784
+ readonly throttleMs?: number;
1785
+ readonly onPartials?: boolean;
1786
+ readonly fallback?: Matcher;
1787
+ /**
1788
+ * `'throttle'` (default): a partial is checked at most every `throttleMs`, a final at once, and the conversation
1789
+ * reads the final without waiting (a late hit hangs up mid-turn). `'debounce'`: a partial is checked `throttleMs`
1790
+ * after the last one (each partial, and the caller's next speech start, restarts the wait; one request at a
1791
+ * time), and every final waits for its own NLU answer before the conversation reads it (a hit is never a turn;
1792
+ * `fallback` is not read).
1793
+ */
1794
+ readonly timing?: 'throttle' | 'debounce';
1795
+ /**
1796
+ * `fallback` read on every final before the NLU (a match is voicemail at once, without a request; a final that
1797
+ * comes while a request is in flight is not queued, and the NLU's failure reads no fallback). Default false: the
1798
+ * fallback is read only when the NLU did not answer.
1799
+ */
1800
+ readonly fallbackFirst?: boolean;
1801
+ }
1802
+ /**
1803
+ * Phrases (locale lexicon `voicemail` + agent's own); `firstFinals` is recorded, not applied (limit with `when`); `transcript`: the
1804
+ * line goes to the transcript as a caller line; `when`: the detector reads a line only while this holds (e.g. only
1805
+ * in the opening: `{ fact: 'phase', eq: 'opening' }`; only before a line flag: `{ not: { flag: 'loanNamed' } }`).
1806
+ */
1807
+ | {
1808
+ readonly by: 'phrases';
1809
+ readonly match: Matcher;
1810
+ readonly firstFinals?: number;
1811
+ readonly transcript?: boolean;
1812
+ readonly when?: Condition | ((call: CallView) => boolean);
1813
+ }
1814
+ /** Same long line repeated. */
1815
+ | {
1816
+ readonly by: 'loop';
1817
+ readonly minChars: number;
1818
+ readonly repeats: number;
1819
+ }
1820
+ /** A menu cycling: the same long line recurring within a window of lines. */
1821
+ | {
1822
+ readonly by: 'menu';
1823
+ readonly minChars: number;
1824
+ readonly windowLines: number;
1825
+ readonly recurrences: number;
1826
+ }
1827
+ /**
1828
+ * The caller's first speech run starts within `startWithinMs` of answer and lasts `ms` or more (pauses up to
1829
+ * `mergeGapMs` do not end it): a likely machine. It sets the flag `voicemail.monologue` (read as `call.flags`).
1830
+ */
1831
+ | {
1832
+ readonly by: 'monologue';
1833
+ readonly ms: number;
1834
+ readonly startWithinMs?: number;
1835
+ readonly mergeGapMs?: number;
1836
+ };
1837
+ /**
1838
+ * Rules are checked in order on each event. By default the first rule that matches acts and the rest are skipped;
1839
+ * `continue: true` lets later rules act too (accumulating marks or flags). A caller-line rule is evaluated before the
1840
+ * LLM turn starts — async matchers (NLU) and hooks delay the turn; `whileWaiting` says a filler if that takes long.
1841
+ */
1842
+ export interface Rule<H = UntypedHooks> {
1843
+ readonly id: string;
1844
+ readonly on: 'callerLine' | 'callerPartial' | 'agentLine' | 'agentLineHeard' | 'agentLineCut' | 'toolCall';
1845
+ /** What the line must match; absent: every line (a rule with a `when` condition). */
1846
+ readonly match?: Matcher;
1847
+ /**
1848
+ * The phase, the limit and the hold (`{ phase, max, held }`), or a condition (`Condition`; its `line` is the line):
1849
+ * read when the rule's turn comes, after the rules before it acted (a `count` before it is seen). A condition rule acts
1850
+ * in the conversation.
1851
+ */
1852
+ readonly when?: RuleWhen | Condition | ((call: CallView, line: string) => boolean);
1853
+ readonly then: Action<H> | readonly Action<H>[];
1854
+ readonly continue?: boolean;
1855
+ readonly whileWaiting?: {
1856
+ readonly afterMs: number;
1857
+ readonly say: Text;
1858
+ };
1859
+ }
1860
+ /** The phase, limit and hold of a rule. */
1861
+ export interface RuleWhen {
1862
+ readonly phase?: CallView['phase'] | readonly CallView['phase'][];
1863
+ /** The rule acts at most this many times in the call. */
1864
+ readonly max?: number;
1865
+ /** The line is held (`hold` action) / not held. */
1866
+ readonly held?: boolean;
1867
+ }
1868
+ /** What rules, steps, ladders, gates and detectors can do. */
1869
+ export type Action<H = UntypedHooks> =
1870
+ /**
1871
+ * Say fixed text instead of the LLM reply. A list is said part by part: each part its own clip on the agent queue,
1872
+ * synthesized when the one before it is (the line is the parts joined with a space). `speechOver: 'answer'`: speech
1873
+ * heard while it plays (past `overtalk.guardMs`' echo check) is the answer at once — a caller turn, the line stops
1874
+ * (a re-prompt); default: buffered like speech over any line.
1875
+ */
1876
+ {
1877
+ readonly say: Text | readonly Text[];
1878
+ readonly alias?: string;
1879
+ readonly speechOver?: 'buffer' | 'answer';
1880
+ } | {
1881
+ readonly play: PlaySpec;
1882
+ }
1883
+ /** Give the LLM this line instead of the caller's text. */
1884
+ | {
1885
+ readonly llm: Text;
1886
+ }
1887
+ /** Prefix the next LLM turn with a marker. */
1888
+ | {
1889
+ readonly mark: string;
1890
+ }
1891
+ /** Hold the line (`true`: the `silence.held` ladder runs) or release it (`false`). */
1892
+ | {
1893
+ readonly hold: boolean;
1894
+ }
1895
+ /** Go on with the next opening step (from an opening silence rung). */
1896
+ | {
1897
+ readonly next: true;
1898
+ }
1899
+ /**
1900
+ * Close: say text (optional; `alias` names it in the mixer; a list is said part by part, see `say`), hang up, set the
1901
+ * result. `result`, `reason` and `alias` may be functions of the call (one close action that says different lines on
1902
+ * different calls).
1903
+ */
1904
+ | {
1905
+ readonly close: Text | readonly Text[] | null;
1906
+ readonly result: string | ((call: CallView) => string) | DataExpr;
1907
+ readonly reason?: string | ((call: CallView) => string) | DataExpr;
1908
+ readonly alias?: string | ((call: CallView) => string) | DataExpr;
1909
+ }
1910
+ /**
1911
+ * Hang up now without a phrase (after `closing.hangupGraceMs`, or `graceMs`; `0`: at once, a line in flight is not
1912
+ * said). No `result`: the result stays as it is.
1913
+ */
1914
+ | {
1915
+ readonly hangup: string;
1916
+ readonly result?: string;
1917
+ readonly graceMs?: number;
1918
+ } | {
1919
+ readonly transfer: true;
1920
+ } | {
1921
+ readonly flag: string;
1922
+ readonly value?: boolean;
1923
+ }
1924
+ /** A call variable; `value` as written, or an expression of the call and the line (a literal object with an operator key: `{ quote }`). */
1925
+ | {
1926
+ readonly set: string;
1927
+ readonly value: unknown;
1928
+ }
1929
+ /** The next line of a line ladder (`AgentSpec.ladders`), or its terminal action once every line was said. */
1930
+ | {
1931
+ readonly ladder: string;
1932
+ }
1933
+ /** One more (`by`) on a counter, read as `{ counter: name }`; `log`: an event with the caller's line and the count. */
1934
+ | {
1935
+ readonly count: string;
1936
+ readonly by?: number;
1937
+ readonly log?: string;
1938
+ }
1939
+ /**
1940
+ * Log an event: `data` is its fields, each a value or an expression of the call (`{ fact: 'line' }` is the caller's
1941
+ * line the rule handles), e.g. `{ log: 'guard_close', data: { reason: 'refused', userText: { fact: 'line' } } }`.
1942
+ */
1943
+ | {
1944
+ readonly log: string;
1945
+ readonly data?: Readonly<Record<string, unknown>> | ((call: CallView, line: string | undefined) => Readonly<Record<string, unknown>>);
1946
+ }
1947
+ /** Agent code returns the actions (the one action of its list; see {@link HookKinds} `action`). */
1948
+ | {
1949
+ readonly hook: HookName<H, 'action'>;
1950
+ }
1951
+ /** The `knowledgeAnswer` planner's turn: a silence turn, or speech without words (silence rungs only). */
1952
+ | {
1953
+ readonly knowledge: 'silence' | 'unheard';
1954
+ }
1955
+ /**
1956
+ * Actions chosen by the call, as data: the `then` of the first case whose `when` holds (`otherwise` when none; no
1957
+ * actions when none and no `otherwise`). Run like a hook action: the one action of its list, not in the opening.
1958
+ */
1959
+ | ActionChoice<H>;
1960
+ /** Actions chosen by conditions (the data form of «rules at a hook place»). */
1961
+ export interface ActionChoice<H = UntypedHooks> {
1962
+ readonly choose: readonly {
1963
+ readonly when: Condition;
1964
+ readonly then: Action<H> | readonly Action<H>[];
1965
+ }[];
1966
+ readonly otherwise?: Action<H> | readonly Action<H>[];
1967
+ }
1968
+ export interface ClosingSpec<H = UntypedHooks> {
1969
+ /** A reply matching this (usually `{ tail, chars }`) is a goodbye: the call hangs up after it is spoken. */
1970
+ readonly goodbye: Matcher;
1971
+ readonly goodbyeResult?: string;
1972
+ /**
1973
+ * The caller was still finishing their answer when an LLM goodbye started: cancel the hangup (the goodbye is cut) and
1974
+ * take the words as a new turn. Once per call, for a final heard while the goodbye plays (or buffered over it while
1975
+ * it streamed) whose speech started no later than `startWithinMs` after the goodbye's first audio (speech segments
1976
+ * less than `runGapMs` apart are one run, default 0), unless it matches `ignore` (thanks / yes / bye), repeats the
1977
+ * line the goodbye answered or only echoes the goodbye's words. `marker` goes with the words to the LLM (`markerAt`:
1978
+ * in front, default, or after; not in the transcript); the result goes back to `default`.
1979
+ */
1980
+ readonly reopenOnSpeech?: {
1981
+ readonly startWithinMs: number;
1982
+ readonly runGapMs?: number;
1983
+ readonly ignore?: Matcher;
1984
+ readonly marker?: string;
1985
+ readonly markerAt?: 'before' | 'after';
1986
+ };
1987
+ /** Pause after the last line before the hangup. */
1988
+ readonly hangupGraceMs?: number;
1989
+ /**
1990
+ * A goodbye reply stays a reply until its `drainFloor` passed: the caller can still cut it and a line of theirs takes
1991
+ * the call over (the goodbye does not hang up). The hangup (and the goodbye result) starts after the floor.
1992
+ */
1993
+ readonly openUntilFloor?: boolean;
1994
+ /**
1995
+ * Wait at least this long for a goodbye (a reply ending the call, a closing line) to play out before the hangup
1996
+ * (same shape as `turn.drainFloor`). Default none: the agent queue's own drain.
1997
+ */
1998
+ readonly drainFloor?: DrainFloorSpec;
1999
+ /**
2000
+ * A goodbye with no letter or digit (a bare `…`: nothing is played, so no end of playback will come): `hangupNow`
2001
+ * hangs up at once (no `hangupGraceMs`); `wait` (default) waits for the drain like any goodbye.
2002
+ */
2003
+ readonly emptyGoodbye?: 'hangupNow' | 'wait';
2004
+ /**
2005
+ * Guard on lines that end the call too early: the opening of a reply is held back (up to `holdChars`, or a shorter
2006
+ * line's whole length) while it can still be one of `closings`; a reply that becomes one is judged before any of it
2007
+ * is spoken. `openings` are held to their first question mark, then judged. A judged line is replaced by a fixed line
2008
+ * (spoken instead, `alias`; a replacement that is a goodbye closes the call) —
2009
+ * what the `hook` returns (`null`: the line is spoken as it is). `leading` is cut from the
2010
+ * held opening before it is matched (e.g. a prompt label in front).
2011
+ */
2012
+ readonly guard?: {
2013
+ readonly closings: readonly string[] | ((call: CallView) => readonly string[]) | DataExpr;
2014
+ readonly openings?: readonly string[] | ((call: CallView) => readonly string[]) | DataExpr;
2015
+ readonly holdChars?: number;
2016
+ readonly leading?: RegExp;
2017
+ /**
2018
+ * The fixed line instead of a judged one: a hook, an `Expr` (its `line` and `input` are the judged line; empty:
2019
+ * spoken as it is), or the re-ask plan `{ reask }` ({@link ClosingGuardReask}).
2020
+ */
2021
+ readonly replace: HookRef<H, 'closingGuard'> | DataExpr | {
2022
+ readonly reask: ClosingGuardReask;
2023
+ };
2024
+ readonly alias?: string;
2025
+ };
2026
+ }
2027
+ export interface TransferSpec<H = UntypedHooks> {
2028
+ /** Started by an LLM tool call with this name (see `requireRequest`), and/or by the rule action `transfer`. */
2029
+ readonly toolName?: string;
2030
+ /** A reply matching this is the transfer line itself (the LLM said it, with or without the tool). */
2031
+ readonly spoken?: Matcher;
2032
+ /**
2033
+ * `bridge`: the platform bridge to `target.did` on `target.channel` with `headers`. `dialAndWhisper`: dial
2034
+ * `target.msisdn`, hold the customer until a person answers (`humanDetect`), `whisper` to them,
2035
+ * then bridge.
2036
+ */
2037
+ readonly mode: 'bridge' | 'dialAndWhisper';
2038
+ /** A `did` given as a function reads the call (e.g. a call variable read from the CMS at the start). */
2039
+ readonly target: {
2040
+ readonly did?: Value<string> | ((call: CallView) => string) | DataExpr;
2041
+ readonly msisdn?: Value<string>;
2042
+ readonly channel?: string;
2043
+ };
2044
+ /**
2045
+ * Said before the transfer. Absent: the LLM's reply is the transfer line. `when: 'replyEmpty'`: only when the reply
2046
+ * that started it said no words (no letter or digit); `'replyBlank'`: only when it said nothing at all (a «…» counts as
2047
+ * said). It is said in the reply language. `alias` names it in the mixer (default `transfer`).
2048
+ */
2049
+ readonly text?: {
2050
+ readonly say: Text;
2051
+ readonly when?: 'always' | 'replyEmpty' | 'replyBlank';
2052
+ readonly alias?: string;
2053
+ /** The line goes to the transcript; with `phraseFloor` it counts as playing at least its floor from its start. */
2054
+ readonly transcript?: boolean;
2055
+ /** `say` gave nothing: this clip plays instead; it counts as playing `playMs`; `text` goes to the transcript. */
2056
+ readonly clip?: PlaySpec & {
2057
+ readonly playMs: number;
2058
+ };
2059
+ };
2060
+ /**
2061
+ * The transfer line plays out before the dial: at least `max(minMs, msPerChar × chars)` from `from` (same shape as
2062
+ * `turn.drainFloor`), then the agent queue's drain. Default none: the queue's drain only. `graceMs`: pause after it.
2063
+ */
2064
+ readonly phraseFloor?: {
2065
+ readonly msPerChar: number;
2066
+ readonly minMs: number;
2067
+ readonly from: 'turnStart' | 'firstChunk' | 'playbackStart';
2068
+ };
2069
+ readonly graceMs?: number;
2070
+ /**
2071
+ * Bridge: how long the operator leg may ring, from the moment it is placed (default 30 000; 0: no limit). When it
2072
+ * runs out the operator leg is hung up and the transfer fails as `no_answer` (`onFailure`).
2073
+ */
2074
+ readonly answerTimeoutMs?: number;
2075
+ /** Dial-and-whisper: recognizer on the operator leg and lines that mean «still in the queue». */
2076
+ readonly humanDetect?: {
2077
+ readonly asr: AsrSpec;
2078
+ readonly queue: Matcher;
2079
+ readonly holdTimeoutMs: number;
2080
+ };
2081
+ readonly whisper?: Text;
2082
+ /**
2083
+ * Once the transfer started the call clock and the silence windows stop and caller lines are not read;
2084
+ * `skipExtraction` (default true): the row is the transfer's result, no extraction.
2085
+ */
2086
+ readonly whileBridged?: {
2087
+ readonly skipExtraction?: boolean;
2088
+ };
2089
+ /**
2090
+ * The transfer did not connect and the customer is on the line (outcome `not_configured`, `dial_failed`,
2091
+ * `no_answer`, `rejected`, `operator_gone`; `timeout` for `dialAndWhisper`): say `say` (by reply language; `alias`
2092
+ * in the mixer), then `close` (hang up after it), `continue` (back to the conversation) or `log` (default: nothing
2093
+ * more — the customer stays on the line until they hang up or the call's time limit ends it). The library never
2094
+ * hangs the customer up on its own before the operator answered. Either way the call is reported as not
2095
+ * transferred (`results.notAnswered`).
2096
+ */
2097
+ readonly onFailure?: {
2098
+ readonly say?: Text;
2099
+ readonly then: 'continue' | 'close' | 'log';
2100
+ readonly alias?: string;
2101
+ };
2102
+ /**
2103
+ * Result labels: `connected` (bridged; for `bridge` the result while the transfer runs), `notAnswered` (it did not
2104
+ * connect with the customer on the line), `customerDropped` (the customer left before it connected; for
2105
+ * `dialAndWhisper` the result while the transfer runs). `notAnswered` / `customerDropped` absent: the call keeps the
2106
+ * result it had before the transfer started. A call whose transfer did not connect is reported like any other
2107
+ * (extraction runs; `whileBridged.skipExtraction` is only for a connected one).
2108
+ */
2109
+ readonly results?: {
2110
+ readonly connected: string;
2111
+ readonly notAnswered?: string;
2112
+ readonly customerDropped?: string;
2113
+ };
2114
+ /** `X-*` headers of the operator leg. */
2115
+ readonly headers?: ((call: CallView) => Readonly<Record<string, string>>) | DataExpr;
2116
+ /** Entities of the row of a call whose extraction the transfer skipped. */
2117
+ readonly entities?: Readonly<Record<string, unknown>> | ((call: CallView) => Readonly<Record<string, unknown>>) | RecordExpr;
2118
+ /**
2119
+ * Entities still extracted from a call whose extraction the transfer skipped (`whileBridged.skipExtraction`): only
2120
+ * those of this list that imply no result. They go to the row in front of `entities`; a failed extraction is logged
2121
+ * and leaves them out.
2122
+ */
2123
+ readonly extract?: readonly string[];
2124
+ /**
2125
+ * The LLM's tool call counts only when the caller's last `lookbackTurns` lines (joined) match `match` (a function
2126
+ * matcher also sees the call: e.g. the agent's last line was the transfer offer). Otherwise the reply is cut at the
2127
+ * tool call and, when it said nothing, asked once more with `refusedSignal`.
2128
+ */
2129
+ readonly requireRequest?: {
2130
+ readonly match: Matcher;
2131
+ readonly lookbackTurns: number;
2132
+ readonly refusedSignal: string;
2133
+ };
2134
+ /**
2135
+ * Agent code asked when the tool latched on a reply that said no words (`hook(call, line)`, `line`: the caller's line
2136
+ * the turn answers): `null` lets the transfer go on; a text refuses it — nothing more of the reply is spoken and the
2137
+ * LLM is asked again with the text (once: a tool call on that regeneration goes through).
2138
+ */
2139
+ readonly veto?: HookRef<H, 'transferVeto'> | DataExpr;
2140
+ /**
2141
+ * Agent code that reads a reply on which the LLM called the transfer's tool (client rules on how the model words a
2142
+ * transfer). While the reply streams it is asked before each chunk (`{ text, next, goodbye }`, `text`: the reply so
2143
+ * far, `next`: the chunk coming): `'over'` ends the reply there (the tool call stands). When the reply ended it is
2144
+ * asked once more (`next: null`; `goodbye`: the reply ends on the goodbye marker): `'drop'` drops the tool call (the
2145
+ * reply is no transfer). Anything else: as it is.
2146
+ */
2147
+ readonly toolReply?: HookRef<H, 'toolReply'> | ToolReplySpec;
2148
+ }
2149
+ export interface ExtractionEntity {
2150
+ readonly name: string;
2151
+ readonly description: Text;
2152
+ readonly schema: Readonly<Record<string, unknown>>;
2153
+ readonly implies?: string;
2154
+ readonly priority?: number;
2155
+ /** Extract it only on calls where this holds (otherwise it is not asked for and not in the row). */
2156
+ readonly when?: ((call: CallView) => boolean) | Condition;
2157
+ }
2158
+ /**
2159
+ * `extraction.catalog` as data: the entities of the first case whose `when` holds on the call, else `else` (default
2160
+ * `ExtractionSpec.entities`).
2161
+ */
2162
+ export interface ExtractionCatalogCases {
2163
+ readonly cases: readonly {
2164
+ readonly when: Condition;
2165
+ readonly value: readonly ExtractionEntity[];
2166
+ }[];
2167
+ readonly else?: readonly ExtractionEntity[];
2168
+ }
2169
+ export interface ExtractionSpec<H = UntypedHooks> {
2170
+ /** Entities extracted from the transcript after the call; `implies` + `priority` map them to a result. */
2171
+ readonly entities: readonly ExtractionEntity[];
2172
+ /**
2173
+ * The entities of this call when they depend on it (e.g. one catalog per scenario of the call): the request and the
2174
+ * row's entity columns use them. `entities` still lists every entity any call can have (their results).
2175
+ */
2176
+ readonly catalog?: ((call: CallView) => readonly ExtractionEntity[]) | ExtractionCatalogCases;
2177
+ /**
2178
+ * `platform`: the CMS agent's extraction model. Own model: provider, endpoint, key from a source (never literal);
2179
+ * `fallback` is asked again when the first model picks a result listed in `recheckOn`.
2180
+ */
2181
+ readonly model: 'platform' | (ExtractionModel & {
2182
+ readonly fallback?: ExtractionModel;
2183
+ readonly recheckOn?: readonly string[];
2184
+ });
2185
+ readonly prompt?: Text;
2186
+ /** Variables for `{placeholders}` in descriptions and prompt. */
2187
+ readonly vars?: ((call: CallView) => Readonly<Record<string, unknown>>) | DataExpr;
2188
+ readonly summary?: {
2189
+ readonly language: LocaleCode | 'en';
2190
+ readonly schema?: Readonly<Record<string, unknown>>;
2191
+ };
2192
+ /** Fix values after extraction (`"null"` → null, clamp dates); a hook for client business rules. */
2193
+ /**
2194
+ * The extraction request is retried: `max` more requests after one fails (an error, or `attemptTimeoutMs` passed),
2195
+ * the n-th after `backoffFactor ** n` seconds. Default: one request, no timeout of its own.
2196
+ */
2197
+ readonly retry?: {
2198
+ readonly max: number;
2199
+ readonly backoffFactor?: number;
2200
+ readonly attemptTimeoutMs?: number;
2201
+ };
2202
+ /**
2203
+ * A request that failed (after its retries): `'failureResult'` (default) makes the pre-result `extract request
2204
+ * failure`; `'keepResult'` keeps the call's own pre-result and decides the result from it (no entities), and the
2205
+ * row's fact `extractionFailed` says whether it failed; `'keepDecided'` keeps it only when the call decided it itself
2206
+ * (a fixed close's result; not `goodbye`, `default` or a technical one), else the failure result.
2207
+ */
2208
+ readonly onFailure?: 'failureResult' | 'keepResult' | 'keepDecided';
2209
+ /**
2210
+ * The request names the LLM dialog the conversation was written to also when that is the CMS dialog
2211
+ * (`platform.llmDialogPerCall: false`). Default: named only with a per-call dialog.
2212
+ */
2213
+ readonly namesDialog?: boolean;
2214
+ /**
2215
+ * Key order of the extraction request (`dialogUuid`, `prompt`, `call_summary`, entity names…); keys not listed
2216
+ * follow in their usual order. Default: the usual order.
2217
+ */
2218
+ readonly requestOrder?: readonly string[];
2219
+ readonly normalize?: readonly {
2220
+ readonly entity: string;
2221
+ readonly fix: ((v: unknown, call: CallView) => unknown) | DataExpr;
2222
+ }[] | HookRef<H, 'normalize'>;
2223
+ /**
2224
+ * Ordered entity fixes as data, after `normalize` and before the result is picked from the entities (null words,
2225
+ * trims, allow-lists, patterns, coercion, conditional sets and clears). See `ExtractionRule`.
2226
+ */
2227
+ readonly rules?: readonly ExtractionRule[];
2228
+ }
2229
+ /**
2230
+ * An own extraction model. Sent to the platform as `{ apiKey, baseUrl, provider, ...settings, deploymentName }`;
2231
+ * `settings` carries the vendor's other fields as they are (`modelName`, `apiVersion`, `kwargs`…). A key that
2232
+ * resolves to nothing falls back to the platform model (logged).
2233
+ */
2234
+ export interface ExtractionModel {
2235
+ readonly provider: string;
2236
+ readonly endpoint: Value<string>;
2237
+ readonly deployment?: string;
2238
+ readonly key: Source;
2239
+ readonly settings?: Readonly<Record<string, unknown>>;
2240
+ /** Field order of the object sent (names of the fields above as sent: `apiKey`, `baseUrl`…); the rest follow. */
2241
+ readonly fieldOrder?: readonly string[];
2242
+ }
2243
+ export interface ResultsSpec<H = UntypedHooks> {
2244
+ /**
2245
+ * Result labels and what each means. Merged over the library's base table (`silence`, `voicemail`, `goodbye`…);
2246
+ * the key `'*'` applies to every label, listed or not (its fields under the label's own).
2247
+ */
2248
+ readonly table: Readonly<Record<string, ResultMeaning>>;
2249
+ /** Result from what happened in the call (never spoke → `silence`), at the goodbye / end of silence / call end. */
2250
+ readonly fromFacts?: readonly {
2251
+ readonly at: 'goodbye' | 'silenceLimit' | 'callEnd';
2252
+ readonly when: ((call: CallView) => boolean) | Condition;
2253
+ readonly result: string;
2254
+ }[];
2255
+ /**
2256
+ * Final say on the result after extraction (client rules, result trees). The hook gets
2257
+ * `{ result, preResult, extractedResult, entities, extractionSkipped, triggersCallback }` and returns a label (its
2258
+ * `recall` from `table` decides the redial), nothing to keep the result, or
2259
+ * `{ result?, recall?, entities?, extractedResult? }`: `recall` is the redial as the hook says (e.g.
2260
+ * `recall: input.triggersCallback` keeps the one decided before the hook — a report wording of the decided result);
2261
+ * `entities` replace the entities the row shows when the client's rules rewrite them (a promise recovered from the
2262
+ * transcript, a date gate); `extractedResult` restates the extracted result (e.g. a promise the rules demoted;
2263
+ * otherwise `extracted_result` stays the extractor's own pick). `call.endedBy` says who hung up.
2264
+ */
2265
+ readonly decide?: HookRef<H, 'decide'>;
2266
+ /**
2267
+ * Ordered rules after extraction (before `decide`): each that holds changes the result, the entities and the redial
2268
+ * (first match ends the list unless `stop: false`). See `ResultRule`.
2269
+ */
2270
+ readonly rules?: readonly ResultRule[];
2271
+ /** Where `rules` apply: the decision (default) or only the row's `result` field (`'report'`). */
2272
+ readonly rulesOn?: 'decide' | 'report';
2273
+ /** The client's label sheet: result / token → label(s) and columns. See `ResultCatalog`. */
2274
+ readonly catalog?: ResultCatalog;
2275
+ /**
2276
+ * How long the result stays `greeting drop`: until the opening is over (default), or until the caller's first line
2277
+ * that reaches the LLM (answers to the opening's liveness check do not count).
2278
+ */
2279
+ readonly greetingDropUntil?: 'openingEnd' | 'callerTurn';
2280
+ /** Labels renamed in the report's `result` field. */
2281
+ readonly labels?: {
2282
+ readonly map: Readonly<Record<string, string>>;
2283
+ };
2284
+ /**
2285
+ * Values kept for the next attempts of the dialog (`call.memory`, stored under `key` in the dialog env), written
2286
+ * after the row is built and before the redial is booked. `value` returning `undefined` leaves the key as it is.
2287
+ */
2288
+ readonly remember?: readonly {
2289
+ readonly key: string;
2290
+ readonly value: ((row: Readonly<Record<string, unknown>>, call: CallView) => unknown) | DataExpr;
2291
+ }[];
2292
+ }
2293
+ export interface ResultMeaning {
2294
+ /** Book a redial (uses `platform.recall`). Rows with `recall` are not final. */
2295
+ readonly recall?: boolean;
2296
+ /** Skip extraction for this result (technical results). */
2297
+ readonly extract?: boolean;
2298
+ /** A result set during the call wins over the extracted one. */
2299
+ readonly outranksExtraction?: boolean;
2300
+ /**
2301
+ * With `extract: false`: extraction still runs when `when` holds, and the result the entities pick after
2302
+ * `extraction.normalize` and `extraction.rules` replaces this one only when it is in `only`; otherwise (and when the
2303
+ * request failed) the call keeps this result as if extraction was skipped: no extracted result, no entities.
2304
+ */
2305
+ readonly extractWhen?: {
2306
+ readonly when: Condition;
2307
+ readonly only: readonly string[];
2308
+ };
2309
+ }
2310
+ export interface ReportSpec {
2311
+ /**
2312
+ * Row fields → source, in row order. `entity: '*'` spreads all entities (null when not extracted; first in the row of
2313
+ * a failed dial, so named fields win), `fact: 'service'` spreads the platform's service fields (status, attempt,
2314
+ * duration, start time, SIP status, transcript, ids, CMS links; appended at the end when not listed). In a row whose
2315
+ * extraction threw (and the row of a leg that never connected on the engine's call media) extraction facts and
2316
+ * entities are not written. A function field that returns `undefined` writes nothing. `asrDurationSec` is whole
2317
+ * seconds.
2318
+ */
2319
+ readonly fields: Readonly<Record<string, ReportSource>>;
2320
+ /**
2321
+ * `call_start_time`: ISO to the second (default), with ms, `DD-MM-YYYY HH:MM:SS` in the script host's local time, or
2322
+ * `iso-offset`: ISO 8601 wall clock of `input.timeZone` to the second, with its UTC offset (`2026-09-08T15:10:12+08:00`).
2323
+ */
2324
+ readonly startTimeFormat?: 'iso' | 'iso-ms' | 'iso-offset' | 'dd-mm-yyyy hh:mm:ss' | 'called_date';
2325
+ /**
2326
+ * The service block (`{ fact: 'service' }`) where agents differ; the defaults keep the library's block. `false`: the
2327
+ * platform's service fields are not appended when `fact: 'service'` is not listed (default: appended).
2328
+ */
2329
+ readonly service?: false | {
2330
+ /** `call_record`: the CMS player link (default) or the CMS records page. */
2331
+ readonly recordLink?: 'player' | 'records';
2332
+ /**
2333
+ * `call_status` of a connected call: `'200 OK'` once answered or the final SIP response (default); `'signals'`: the
2334
+ * last SIP signal the leg's script saw (code and phrase, or its state when it carried no code), else the platform's
2335
+ * call status, null when there is neither.
2336
+ */
2337
+ readonly callStatus?: 'answer' | 'signals';
2338
+ /**
2339
+ * Where a connected call's service fields come from: `'script'` — as the script saw the leg (the SIP code and
2340
+ * phrase it saw, null when none; the answer as the start, with ms; the records link; the recognizer's seconds), as
2341
+ * a `from_invite` agent writes them, also for an `on_answer` agent. Default: by `platform.outboundMode`.
2342
+ */
2343
+ readonly source?: 'script' | 'mode';
2344
+ /** `call_start_time` of a dial that never connected: the attempt's start (default) or null. */
2345
+ readonly failedDialStartTime?: 'attempt' | 'none';
2346
+ };
2347
+ /** A failed dial's null entities: first in the row (default; named fields win) or where `{ entity: '*' }` stands. */
2348
+ readonly failedDialEntities?: 'first' | 'inPlace';
2349
+ /** Row of a failed dial: written once per dialog, once per leg (a pass repeated for the same leg writes none), or on every attempt. */
2350
+ readonly failedDialRow?: 'once' | 'oncePerLeg' | 'everyAttempt';
2351
+ /** `triggers_callback` (`fact: 'triggersCallback'`) of a failed dial's row. Default true. */
2352
+ readonly failedDialCallback?: boolean;
2353
+ /**
2354
+ * A pass with no call returns a row too. `'fields'`: every pass with no call (the pre-call pass, an
2355
+ * `after_call_failed` pass that reports nothing else) returns the `var`, `value` and function fields and `result`
2356
+ * (`undefined`). `'failedDial'`: the pre-call pass (it schedules the first leg) writes the row of a call not made yet,
2357
+ * built like a failed dial's (no result, every entity null; `call.preResult` null). Default: no row.
2358
+ */
2359
+ readonly headlessRow?: 'fields' | 'failedDial';
2360
+ /**
2361
+ * With `platform.outboundMode: 'from_invite'` and no `platform.failedLegPass`: the live pass of a leg nobody
2362
+ * answered writes its row (like a failed leg's: `result` `undefined`, no extraction facts or entities; service fields
2363
+ * `status` `-ERR`, `call_status`, `call_status_phrase`, `attempt`, `call_start_time`, `call_uuid`). Default: no row.
2364
+ */
2365
+ readonly unansweredLegRow?: boolean;
2366
+ }
2367
+ export type ReportSource =
2368
+ /** Several fields at once, in the order of the returned object (nothing when it returns `undefined`). */
2369
+ {
2370
+ readonly spread: ((row: Readonly<Record<string, unknown>>, call: CallView) => Readonly<Record<string, unknown>> | undefined) | DataExpr;
2371
+ } | {
2372
+ readonly var: string;
2373
+ } | {
2374
+ readonly entity: string;
2375
+ }
2376
+ /** A fact; `omit`: with `fact: 'service'`, the platform's service fields left out of the row (older row layouts). */
2377
+ | {
2378
+ readonly fact: ReportFact;
2379
+ readonly omit?: readonly string[];
2380
+ } | {
2381
+ readonly value: unknown;
2382
+ }
2383
+ /**
2384
+ * The `knowledgeAnswer` decision trace (`decision_*` / `qna_*` fields): `'call'` in a call's row, `'notConnected'`
2385
+ * (every field `null`) in the row of a dial that never connected.
2386
+ */
2387
+ | {
2388
+ readonly knowledgeTrace: 'call' | 'notConnected';
2389
+ }
2390
+ /**
2391
+ * The `catalogMatch` fields of a call's row (nothing on a failed dial): with `entities: 'all'` every extraction entity
2392
+ * first (`null` when not extracted), then the levels as the list spells them, the reconcile keys and the check's keys.
2393
+ */
2394
+ | {
2395
+ readonly catalogMatch: 'row';
2396
+ readonly entities?: 'all';
2397
+ }
2398
+ /** A field of `results.catalog` (its columns spread, its label, one column). */
2399
+ | CatalogReportSource
2400
+ /**
2401
+ * Every entity as these `extraction.rules` would leave them, for the row only (the decision keeps the entities as
2402
+ * they are): spread in a connected call's row (nothing in other rows); `pick`: only these keys.
2403
+ */
2404
+ | {
2405
+ readonly entities: '*';
2406
+ readonly view: readonly ExtractionRule[];
2407
+ readonly pick?: readonly string[];
2408
+ } | ((row: Readonly<Record<string, unknown>>, call: CallView) => unknown)
2409
+ /** An expression of the data language (other than the forms above); `{ omit: true }` writes nothing. */
2410
+ | DataExpr;
2411
+ export type ReportFact = 'result' | 'preResult' | 'extractedResult' | 'status' | 'triggersCallback' | 'extractionSkipped' | 'attempt' | 'durationSec' | 'asrDurationSec' | 'sipCode' | 'sipPhrase' | 'callUuid' | 'dialogUuid' | 'llmDialogUuid' | 'transcript' | 'summary' | 'startTime' | 'recordUrl' | 'transcriptUrl' | 'llmLogUrl' | 'voiceTag' | 'endedBy' | 'language' | 'agentVersion' | 'service' | 'extractionFailed';
2412
+ /** An HTTP call: before a dial (yes/no), during the call (from hooks), or after the call (CRM, client report, SMS). */
2413
+ export interface Integration<H = UntypedHooks> {
2414
+ readonly id: string;
2415
+ /**
2416
+ * `lookup`: the request of `input.lookup` (`{ integration }`), its `value` the field's value. `dialogEnd`: run by
2417
+ * the after-leg policy when the dialog ends (`platform.afterLeg.on*.onDone`) or by a hook (`api.integration`).
2418
+ */
2419
+ readonly phase: 'preDial' | 'inCall' | 'afterCall' | 'lookup' | 'dialogEnd';
2420
+ readonly kind?: 'http';
2421
+ /** After the call: which rows. Facts include `attempt`, `budget`, `recallScheduled`. */
2422
+ readonly when?: 'answered' | 'failedDial' | 'always' | ((row: Readonly<Record<string, unknown>>, call: CallView) => boolean) | Exclude<Condition, boolean>;
2423
+ readonly enabledBy?: {
2424
+ readonly from: Source;
2425
+ readonly equals?: unknown;
2426
+ };
2427
+ readonly method: 'POST' | 'PUT' | 'GET';
2428
+ /** `{name}` placeholders: `dialogUuid`, `callUuid`, `msisdn` and call variables (URI-encoded); or a text expression. */
2429
+ readonly url: Value<string> | DataExpr;
2430
+ /** Appended to the resolved `url` with its trailing slashes removed (a base URL from a source + a fixed path). */
2431
+ readonly path?: string;
2432
+ /**
2433
+ * A header that resolves to nothing (a key not configured) skips the request; it is logged. A value may be an
2434
+ * expression, `{ basic: [user, password] }` or `{ bearer: token }`.
2435
+ */
2436
+ readonly headers?: Readonly<Record<string, HeaderValue>>;
2437
+ /** Query parameters (expressions; an empty one is left out), appended to the URL. */
2438
+ readonly query?: Readonly<Record<string, DataExpr | string | number | boolean>>;
2439
+ /** Values read before the checks that ask for them, as locals of every expression of the integration (e.g. CMS storage keys). */
2440
+ readonly inputs?: Readonly<Record<string, Value<unknown>>>;
2441
+ /** Reasons not to send, in order (see {@link IntegrationCheck}). */
2442
+ readonly skipWhen?: readonly IntegrationCheck[];
2443
+ readonly cooldown?: IntegrationCooldown;
2444
+ /** How a data body is put on the wire (default JSON as it is). */
2445
+ readonly serialize?: BodySerialize;
2446
+ readonly read?: IntegrationRead;
2447
+ /**
2448
+ * After the call: row fields from the outcome (expressions; locals as for `log`, plus `ok`). `onSkip` / `onFail`:
2449
+ * the fields of a skipped / failed request instead.
2450
+ */
2451
+ readonly rowFields?: Readonly<Record<string, DataExpr | string | number | boolean | null>>;
2452
+ readonly onSkip?: Readonly<Record<string, DataExpr | string | number | boolean | null>>;
2453
+ readonly onFail?: Readonly<Record<string, DataExpr | string | number | boolean | null>>;
2454
+ /** `phase: 'lookup'`: the field's value from the outcome (locals as for `log`, plus `outcome`: `sent`, `skipped`, `failed`). */
2455
+ readonly value?: DataExpr;
2456
+ readonly log?: IntegrationLog;
2457
+ /** Request body (sent as JSON); a hook gets the row as its input. */
2458
+ readonly body?: ((row: Readonly<Record<string, unknown>>, call: CallView) => unknown) | HookRef<H, 'body'> | DataExpr;
2459
+ /**
2460
+ * `preDial`: how the answer (the parsed JSON body) reads as yes/no; `null` = no usable answer (treated as a failure,
2461
+ * see `platform.preDial.failOpen`). The call view carries `memory` (values kept across attempts).
2462
+ */
2463
+ readonly answer?: ((response: unknown, call: CallView) => boolean | null) | DataExpr;
2464
+ readonly requestId?: 'callUuid' | 'dialogUuid';
2465
+ readonly timeoutMs?: number;
2466
+ readonly retries?: number;
2467
+ readonly retryOn?: '5xx' | 'any';
2468
+ /**
2469
+ * Retries (`retries`, `retryOn`): a POST is repeated only when it certainly did not arrive (connection refused, DNS)
2470
+ * or on a 5xx other than 504, unless the request carries an `Idempotency-Key` header (then also after a timeout).
2471
+ * GET and PUT are retried as configured.
2472
+ */
2473
+ /**
2474
+ * Write the outcome into a row field: a field name gets the response status (`null` when skipped, `'failed'` when
2475
+ * there was no answer); `{ field, value }` gets what `value` returns for the outcome (`applied: false` on a row the
2476
+ * integration does not apply to; `undefined` writes nothing).
2477
+ */
2478
+ readonly writeBack?: string | {
2479
+ readonly field: string;
2480
+ readonly value: ((outcome: IntegrationResult, row: Readonly<Record<string, unknown>>, call: CallView) => unknown) | DataExpr;
2481
+ };
2482
+ }
2483
+ /** What an after-call integration came to, for `writeBack`. */
2484
+ export interface IntegrationResult {
2485
+ /** The row was one the integration applies to (`when`). */
2486
+ readonly applied: boolean;
2487
+ /** Why it was not sent (switched off, a header or URL that resolved to nothing…); `null` when it was sent. */
2488
+ readonly skipped: string | null;
2489
+ /** HTTP status of the answer; `null` when not sent or not answered. */
2490
+ readonly status: number | null;
2491
+ /** The request's error (timeout, network); `null` when answered. */
2492
+ readonly error: string | null;
2493
+ }
2494
+ /**
2495
+ * An after-call (or in-call) step whose requests the agent's hook makes: a client protocol of several requests (a
2496
+ * login, then the call), with a cooldown of its own. `hook(call, row, api)` uses `api.http`, `api.storage`,
2497
+ * `api.agentEnv`; it is bounded by `timeoutMs` (default 30 000) and never fails the call. After the call, an object it
2498
+ * returns adds its fields to the row (nothing: the row stays). `when` and `enabledBy` as for {@link Integration}.
2499
+ * `phase: 'answer'`: run once when a live call is answered, before the recognizer and the voice are set up, beside
2500
+ * them (nothing waits for it): what a call's hooks need ready early (credentials from `api.storage`, a warm
2501
+ * connection, per-call state in `api.state` — the same object the call's other hooks get); its input is `{}`.
2502
+ */
2503
+ export interface HookIntegration<H = UntypedHooks> {
2504
+ readonly id: string;
2505
+ /** `beforeCall`: run on the pre-call pass (after `platform.beforeCall`), before the first leg is placed. */
2506
+ readonly phase: 'answer' | 'inCall' | 'afterCall' | 'beforeCall' | 'dialogEnd';
2507
+ readonly when?: Integration['when'];
2508
+ readonly enabledBy?: Integration['enabledBy'];
2509
+ readonly run: HookRef<H, 'integration'>;
2510
+ readonly timeoutMs?: number;
2511
+ }
2512
+ /**
2513
+ * A request kind of its own, as data (compiled to a hook step): `startAgentDialog` starts a dialog of another CMS agent
2514
+ * for the customer; `askAgent` asks another CMS LLM agent before the call and keeps the answers in the dialog env.
2515
+ * `when`, `enabledBy`, `inputs`, `skipWhen`, `cooldown`, `timeoutMs`, `log` as for {@link Integration}.
2516
+ */
2517
+ export type AgentIntegration = AgentIntegrationBase & ({
2518
+ readonly kind: 'startAgentDialog';
2519
+ readonly startAgentDialog: StartAgentDialogSpec;
2520
+ } | {
2521
+ readonly kind: 'askAgent';
2522
+ readonly ask: AskAgentSpec;
2523
+ });
2524
+ export interface AgentIntegrationBase {
2525
+ readonly id: string;
2526
+ readonly phase: 'beforeCall' | 'inCall' | 'afterCall' | 'dialogEnd';
2527
+ readonly when?: Integration['when'];
2528
+ readonly enabledBy?: Integration['enabledBy'];
2529
+ readonly inputs?: Integration['inputs'];
2530
+ readonly skipWhen?: Integration['skipWhen'];
2531
+ readonly cooldown?: IntegrationCooldown;
2532
+ readonly timeoutMs?: number;
2533
+ readonly requestId?: 'callUuid' | 'dialogUuid';
2534
+ readonly log?: IntegrationLog;
2535
+ }
2536
+ /**
2537
+ * What a hook may use: call integrations by id, log. Hooks never drive media or the LLM stream directly. A hook run
2538
+ * during the call (a rule's `hook` action) also gets the call's identity, CMS storage (secrets, settings) and a
2539
+ * per-call `state` object it keeps between its runs (the same object for every hook of the call).
2540
+ */
2541
+ export interface HookApi {
2542
+ readonly integration: (id: string, input?: unknown) => Promise<unknown>;
2543
+ readonly log: (message: string, data?: Readonly<Record<string, unknown>>) => void;
2544
+ readonly callUuid?: string;
2545
+ readonly dialogUuid?: string;
2546
+ readonly storage?: (...names: string[]) => Promise<Readonly<Record<string, string | undefined>>>;
2547
+ readonly state?: Record<string, unknown>;
2548
+ /** Direction of the leg as the platform stamped it (`in`: the customer called), lower case; undefined: unknown. */
2549
+ readonly direction?: string;
2550
+ /** The leg's INVITE SIP headers as they came (`input.lookup` on a live call); undefined: none / not given. */
2551
+ readonly sipHeaders?: Readonly<Record<string, unknown>>;
2552
+ /** One HTTP request through the library (timeout, correlation id, one log line); never rejects on a status. */
2553
+ readonly http?: (url: string, opts: HookHttpOptions) => Promise<{
2554
+ readonly status: number;
2555
+ readonly text: string;
2556
+ }>;
2557
+ /**
2558
+ * The agent's own key-value store, shared by its dialogs (a cooldown per customer): `agentEnv(key)` reads,
2559
+ * `agentEnv(key, value, { expire })` writes (`expire` in days).
2560
+ */
2561
+ readonly agentEnv?: (key: string, value?: unknown, opts?: {
2562
+ readonly expire?: number;
2563
+ }) => Promise<unknown>;
2564
+ /**
2565
+ * One question to another CMS LLM agent: a dialog with it is created (`name`), `text` is asked, the answer returned
2566
+ * (`hidden`: the question is not shown in that dialog). Rejects when the LLM does.
2567
+ */
2568
+ readonly askAgent?: (text: string, opts: {
2569
+ readonly agentUuid: string;
2570
+ readonly name?: string;
2571
+ readonly hidden?: boolean;
2572
+ }) => Promise<string>;
2573
+ /** The dialog env: `dialogEnv(key)` reads a value, `dialogEnv(key, value)` writes it (kept for later passes). */
2574
+ readonly dialogEnv?: (key: string, value?: unknown) => unknown;
2575
+ /**
2576
+ * The platform's legs, for an agent that places its own (`platform.scheduleOutbound: false`; hooks of
2577
+ * `platform.beforeCall` and after-call integrations): the pass's phase and the campaign's redial budget and delay,
2578
+ * where the dialog's leg goes (its number, entry point, the library's routing — trunk, pool, upload, headers), and
2579
+ * `call` (absent where the platform cannot place calls) / `setDialogResult`.
2580
+ */
2581
+ readonly platform?: {
2582
+ readonly phase: string;
2583
+ /** The platform's attempt count of this leg (0 on the first). */
2584
+ readonly attempt?: number;
2585
+ readonly recallCount?: number;
2586
+ readonly recallDelaySec?: number;
2587
+ /** The leg's own number. */
2588
+ readonly msisdn?: string;
2589
+ readonly dialogMsisdn: () => string;
2590
+ readonly entryPoint: () => string;
2591
+ readonly routing: () => Readonly<Record<string, unknown>>;
2592
+ readonly call?: (msisdn: string, options: Readonly<Record<string, unknown>>) => Promise<unknown>;
2593
+ readonly setDialogResult: (value: string) => void;
2594
+ /** `platform.afterLeg` only: place the dialog's next leg in `delaySec`, as the first was placed (`true` when placed). */
2595
+ readonly redial?: (opts: {
2596
+ readonly delaySec: number;
2597
+ }) => Promise<boolean>;
2598
+ };
2599
+ }
2600
+ /** An HTTP request of a hook (`HookApi.http`). */
2601
+ export interface HookHttpOptions {
2602
+ readonly method?: string;
2603
+ readonly headers?: Readonly<Record<string, string>>;
2604
+ /** Sent as it is (JSON text, form text). */
2605
+ readonly body?: string;
2606
+ readonly timeoutMs?: number;
2607
+ /** Correlation id of the request (`X-Request-Id`). */
2608
+ readonly requestId?: string;
2609
+ /** Name of the request in the log line. */
2610
+ readonly event?: string;
2611
+ }
2612
+ /** A report row as hooks and integrations read it. */
2613
+ export type Row = Readonly<Record<string, unknown>>;
2614
+ /** What a hook of a list of actions returns: the actions to run (one or a list; nothing: none). */
2615
+ export type HookActions = Action | readonly Action[] | null | undefined;
2616
+ /** `turn.review` asks at the start of a turn (`stage: 'start'`) and on the held text (`stage: 'held'`). */
2617
+ export type ReviewInput = {
2618
+ readonly stage: 'start';
2619
+ readonly request: string;
2620
+ readonly trigger: string;
2621
+ readonly regenerated: string | null;
2622
+ readonly silence: boolean;
2623
+ } | {
2624
+ readonly stage: 'held';
2625
+ readonly held: string;
2626
+ readonly final: boolean;
2627
+ readonly request: string;
2628
+ readonly trigger: string;
2629
+ readonly regenerated: string | null;
2630
+ };
2631
+ /**
2632
+ * What `turn.review` answers: at the start `null` or `{ holdChars }`; on the held text `null` (keep holding),
2633
+ * `'release'`, `{ regenerate }` or `{ then }`.
2634
+ */
2635
+ export type ReviewAnswer = null | undefined | 'release' | {
2636
+ readonly holdChars: number;
2637
+ } | {
2638
+ readonly regenerate: string;
2639
+ } | {
2640
+ readonly then: readonly Action[];
2641
+ };
2642
+ /** What `results.decide` reads: the decision so far. */
2643
+ export interface DecideInput {
2644
+ readonly result: string;
2645
+ readonly preResult: string;
2646
+ readonly extractedResult: string | null;
2647
+ readonly entities: Readonly<Record<string, unknown>>;
2648
+ readonly extractionSkipped: boolean;
2649
+ readonly triggersCallback: boolean;
2650
+ }
2651
+ /** What `results.decide` answers: a label, nothing (the result stays), or parts of the decision. */
2652
+ export type DecideAnswer = string | null | undefined | {
2653
+ readonly result?: string;
2654
+ readonly recall?: boolean;
2655
+ readonly entities?: Readonly<Record<string, unknown>>;
2656
+ readonly extractedResult?: string | null;
2657
+ };
2658
+ /** Where `platform.legs.route` sends one leg (`null`: as it is). */
2659
+ export interface HookLegRoute {
2660
+ readonly msisdn: string;
2661
+ readonly channel?: string;
2662
+ /** The leg over this trunk id (the routing's channel dropped). */
2663
+ readonly trunkId?: number;
2664
+ readonly protoAdditional?: Readonly<Record<string, string>>;
2665
+ }
2666
+ /**
2667
+ * Every kind of hook by where the agent file names it: what it gets as `input` and what it returns (`result`).
2668
+ * `async: true`: it may return a promise (the engine waits for it); otherwise it answers at once.
2669
+ * - `action`: a `{ hook }` action — of a caller-line rule (`input`: the caller's line; the turn waits for the
2670
+ * answer, `whileWaiting` says a filler), of another rule, a silence rung, `voicemail.then`… (`input`: the line
2671
+ * being handled, or `''`). Returns the actions to run (validated: an unknown action or one needing a block the
2672
+ * agent file lacks is logged `hook_result_invalid` and dropped; a `hook` action in the answer is not run);
2673
+ * - `step`: an opening `{ step: 'hook' }` (`input`: `''`), returns actions like `action`;
2674
+ * - `replyPlayed`: `turn.replyPlayed` (`{ text, heard }`), nothing to return;
2675
+ * - `review`: `turn.review` ({@link ReviewInput} → {@link ReviewAnswer});
2676
+ * - `replyText`: a `{ filter: 'hook' }` reply filter (a chunk of the reply → the chunk to pass on);
2677
+ * - `replyChunk`: a `{ filter: 'stream' }` reply filter ({@link ReplyChunkInput} → {@link ReplyChunkAnswer});
2678
+ * - `sentence`: a `sentences` reply filter (`{ sentence, index, tag, silence }` → {@link SentenceVerdict});
2679
+ * - `label`: a `labels` reply filter with a hook (the label → its line, or `null`);
2680
+ * - `cutMark`: `overtalk.cutMark` (`{ heardMs }` → a mark or `null`);
2681
+ * - `replayHold`: `overtalk.buffer.holdWhileSpeaking.extend` (`{ heldMs, msSinceLastPartial }` → `true`: keep waiting);
2682
+ * - `closingGuard`: `closing.guard.replace` (the held line → the fixed line instead, or `null`);
2683
+ * - `transferVeto`: `transfer.veto` (the caller's line → a refusal text, or `null`);
2684
+ * - `toolReply`: `transfer.toolReply` (`{ text, next, goodbye }` → `'over'` / `'drop'` / `null`);
2685
+ * - `lookup`: `input.lookup` (`undefined` → the value of the field);
2686
+ * - `decide`: `results.decide` ({@link DecideInput} → {@link DecideAnswer});
2687
+ * - `normalize`: `extraction.normalize` (the entities → the entities);
2688
+ * - `body`: an integration's `body` (the row → the request body);
2689
+ * - `integration`: a hook integration's `run` (the row, `{}` at answer → fields added to the row, or nothing);
2690
+ * - `beforeCall`: `platform.beforeCall` (`null`), `afterLeg`: `platform.afterLeg` (`{ pass, recall }`);
2691
+ * - `route`: `platform.legs.route` (`{ msisdn }` → {@link HookLegRoute} or `null`).
2692
+ * A hook named in the agent file but missing in `hooks` fails `defineVoiceAgent`.
2693
+ */
2694
+ export interface HookKinds {
2695
+ readonly action: {
2696
+ readonly input: string;
2697
+ readonly result: HookActions;
2698
+ readonly async: true;
2699
+ };
2700
+ readonly step: {
2701
+ readonly input: string;
2702
+ readonly result: HookActions;
2703
+ readonly async: true;
2704
+ };
2705
+ readonly replyPlayed: {
2706
+ readonly input: {
2707
+ readonly text: string;
2708
+ readonly heard: boolean;
2709
+ };
2710
+ readonly result: void;
2711
+ readonly async: true;
2712
+ };
2713
+ readonly review: {
2714
+ readonly input: ReviewInput;
2715
+ readonly result: ReviewAnswer;
2716
+ readonly async: false;
2717
+ };
2718
+ readonly replyText: {
2719
+ readonly input: string;
2720
+ readonly result: string | null | undefined;
2721
+ readonly async: false;
2722
+ };
2723
+ readonly replyChunk: {
2724
+ readonly input: ReplyChunkInput;
2725
+ readonly result: ReplyChunkAnswer;
2726
+ readonly async: false;
2727
+ };
2728
+ readonly sentence: {
2729
+ readonly input: {
2730
+ readonly sentence: string;
2731
+ readonly index: number;
2732
+ readonly tag: string;
2733
+ readonly silence: boolean;
2734
+ };
2735
+ readonly result: SentenceVerdict | undefined;
2736
+ readonly async: false;
2737
+ };
2738
+ readonly label: {
2739
+ readonly input: string;
2740
+ readonly result: string | null | undefined;
2741
+ readonly async: false;
2742
+ };
2743
+ readonly cutMark: {
2744
+ readonly input: {
2745
+ readonly heardMs: number;
2746
+ };
2747
+ readonly result: string | null | undefined;
2748
+ readonly async: false;
2749
+ };
2750
+ readonly replayHold: {
2751
+ readonly input: {
2752
+ readonly heldMs: number;
2753
+ readonly msSinceLastPartial: number | null;
2754
+ };
2755
+ readonly result: boolean | null | undefined;
2756
+ readonly async: false;
2757
+ };
2758
+ readonly closingGuard: {
2759
+ readonly input: string;
2760
+ readonly result: string | null | undefined;
2761
+ readonly async: false;
2762
+ };
2763
+ readonly transferVeto: {
2764
+ readonly input: string;
2765
+ readonly result: string | null | undefined;
2766
+ readonly async: false;
2767
+ };
2768
+ readonly toolReply: {
2769
+ readonly input: {
2770
+ readonly text: string;
2771
+ readonly next: string | null;
2772
+ readonly goodbye: boolean;
2773
+ };
2774
+ readonly result: 'over' | 'drop' | null | undefined;
2775
+ readonly async: false;
2776
+ };
2777
+ readonly lookup: {
2778
+ readonly input: undefined;
2779
+ readonly result: unknown;
2780
+ readonly async: true;
2781
+ };
2782
+ readonly decide: {
2783
+ readonly input: DecideInput;
2784
+ readonly result: DecideAnswer;
2785
+ readonly async: true;
2786
+ };
2787
+ readonly normalize: {
2788
+ readonly input: Readonly<Record<string, unknown>>;
2789
+ readonly result: Readonly<Record<string, unknown>> | null | undefined;
2790
+ readonly async: true;
2791
+ };
2792
+ readonly body: {
2793
+ readonly input: Row;
2794
+ readonly result: unknown;
2795
+ readonly async: true;
2796
+ };
2797
+ readonly integration: {
2798
+ readonly input: Row;
2799
+ readonly result: Readonly<Record<string, unknown>> | null | undefined | void;
2800
+ readonly async: true;
2801
+ };
2802
+ readonly beforeCall: {
2803
+ readonly input: null;
2804
+ readonly result: void;
2805
+ readonly async: true;
2806
+ };
2807
+ readonly afterLeg: {
2808
+ readonly input: {
2809
+ readonly pass: 'success' | 'failed';
2810
+ readonly recall: {
2811
+ readonly count: Readonly<Record<string, number>>;
2812
+ readonly delaySec: Readonly<Record<string, number>>;
2813
+ };
2814
+ };
2815
+ readonly result: void;
2816
+ readonly async: true;
2817
+ };
2818
+ readonly route: {
2819
+ readonly input: {
2820
+ readonly msisdn: string;
2821
+ };
2822
+ readonly result: HookLegRoute | null | undefined;
2823
+ readonly async: false;
2824
+ };
2825
+ }
2826
+ export type HookKind = keyof HookKinds;
2827
+ /** What a hook of a kind returns (a promise of it where the kind may answer later). */
2828
+ export type HookResult<K extends HookKind> = HookKinds[K]['async'] extends true ? HookKinds[K]['result'] | Promise<HookKinds[K]['result']> : HookKinds[K]['result'];
2829
+ /** A hook of one kind: e.g. `const fixedReply: Hook<'action'> = (call, line) => [{ say: '…' }]`. */
2830
+ export type Hook<K extends HookKind> = (call: CallView, input: HookKinds[K]['input'], api: HookApi) => HookResult<K>;
2831
+ /** Any hook (the type of a value of `hooks` before it is checked against where the agent file names it). */
2832
+ export type AnyHook = (call: CallView, input: unknown, api: HookApi) => unknown;
2833
+ /**
2834
+ * Agent code referenced by name from the agent file. Declare it with `satisfies AgentHooks` and type the agent file
2835
+ * `AgentSpec<typeof hooks>`: every name the file references is then checked against the hooks of the kind that place
2836
+ * expects ({@link HookKinds}) — a name that is missing, or whose hook returns the wrong thing, does not compile.
2837
+ */
2838
+ export interface AgentHooks {
2839
+ readonly [name: string]: AnyHook;
2840
+ }
2841
+ /**
2842
+ * The names of `H` usable as a hook of kind `K`: its hooks whose type fits {@link Hook}`<K>`. With the plain
2843
+ * {@link AgentHooks} (no names known) any string.
2844
+ */
2845
+ export type HookName<H, K extends HookKind> = {
2846
+ [N in keyof H & string]: string extends N ? string : H[N] extends Hook<K> ? N : never;
2847
+ }[keyof H & string];
2848
+ /**
2849
+ * The hooks of an agent file typed without them (`AgentSpec`): every hook name is a string. `any` so that an agent file
2850
+ * typed with its hooks (`AgentSpec<typeof hooks>`) is still an `AgentSpec` everywhere the library takes one.
2851
+ */
2852
+ export type UntypedHooks = any;
2853
+ /** A reference to a hook of kind `K` in the agent file. */
2854
+ export interface HookRef<H, K extends HookKind> {
2855
+ readonly hook: HookName<H, K>;
2856
+ }