@alexkroman1/aai-cli 0.12.3 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (591) hide show
  1. package/README.md +69 -0
  2. package/bin.mjs +58 -0
  3. package/dist/_agent-BopNO5Bq.mjs +152 -0
  4. package/dist/_agent.d.ts +83 -0
  5. package/dist/_api-client.d.ts +92 -0
  6. package/dist/_artifacts-BJOYGQPp.mjs +21 -0
  7. package/dist/_artifacts.d.ts +16 -0
  8. package/dist/_build-target-C08aM-Es.mjs +1119 -0
  9. package/dist/_build-target.d.ts +276 -0
  10. package/dist/_bundler-B6v31ROV.mjs +102 -0
  11. package/dist/_bundler.d.ts +60 -0
  12. package/dist/_cli-common.d.ts +173 -0
  13. package/dist/_client-plugins.d.ts +57 -0
  14. package/dist/_config-mq1I5Cva.mjs +263 -0
  15. package/dist/_config.d.ts +122 -0
  16. package/dist/_console-audio.d.ts +35 -0
  17. package/dist/_console-session.d.ts +70 -0
  18. package/dist/_default-html.d.ts +33 -0
  19. package/dist/_deno-output.d.ts +23 -0
  20. package/dist/_deno-target.d.ts +74 -0
  21. package/dist/_deploy.d.ts +22 -0
  22. package/dist/_dev-agent-env.d.ts +27 -0
  23. package/dist/_dev-env-D9Uy5wNt.mjs +89 -0
  24. package/dist/_dev-env.d.ts +77 -0
  25. package/dist/_dev-restart.d.ts +64 -0
  26. package/dist/_dev-server-GoEXEVpA.mjs +737 -0
  27. package/dist/_dev-server.d.ts +89 -0
  28. package/dist/_dev-session-ticket.d.ts +63 -0
  29. package/dist/_dev-source.d.ts +55 -0
  30. package/dist/_dev-tunnel.d.ts +90 -0
  31. package/dist/_dev-typecheck.d.ts +38 -0
  32. package/dist/_dev-vite-config.d.ts +100 -0
  33. package/dist/_dev-watch.d.ts +35 -0
  34. package/dist/_dotenv-file.d.ts +45 -0
  35. package/dist/_e2e-test-utils.d.ts +120 -0
  36. package/dist/_fault-mode.d.ts +194 -0
  37. package/dist/_help.d.ts +31 -0
  38. package/dist/_init.d.ts +66 -0
  39. package/dist/_mock-api.d.ts +22 -0
  40. package/dist/_mock-registry.d.ts +17 -0
  41. package/dist/_modal-app.d.ts +77 -0
  42. package/dist/_modal-output.d.ts +31 -0
  43. package/dist/_modal-target.d.ts +69 -0
  44. package/dist/_output-DBP9Op_d.mjs +120 -0
  45. package/dist/_output.d.ts +74 -0
  46. package/dist/_preflight-Bv6Ct4ss.mjs +149 -0
  47. package/dist/_preflight.d.ts +170 -0
  48. package/dist/_resource-commands.d.ts +54 -0
  49. package/dist/_run-code-deno-C0AtfHeH.mjs +268 -0
  50. package/dist/_run-code-deno.d.ts +130 -0
  51. package/dist/_server-common-CVXIeWrY.mjs +114 -0
  52. package/dist/_server-common.d.ts +75 -0
  53. package/dist/_slug-api-BnmTHtjd.mjs +68 -0
  54. package/dist/_slug-api.d.ts +61 -0
  55. package/dist/_stop-server.d.ts +17 -0
  56. package/dist/_studio-B5m4jBTD.mjs +256 -0
  57. package/dist/_studio-commands.d.ts +73 -0
  58. package/dist/_studio.d.ts +92 -0
  59. package/dist/_target-bundle.d.ts +141 -0
  60. package/dist/_target-drain.d.ts +44 -0
  61. package/dist/_target-entry.d.ts +81 -0
  62. package/dist/_target-output.d.ts +63 -0
  63. package/dist/_templates-BVMVsQh0.mjs +139 -0
  64. package/dist/_templates.d.ts +89 -0
  65. package/dist/_typecheck-gate-CcX2gLJZ.mjs +19 -0
  66. package/dist/_typecheck-gate.d.ts +11 -0
  67. package/dist/_ui-Coe0zwmm.mjs +102 -0
  68. package/dist/_ui.d.ts +90 -0
  69. package/dist/_utils-BVLdBvdT.mjs +186 -0
  70. package/dist/_utils.d.ts +126 -0
  71. package/dist/_vercel-output.d.ts +48 -0
  72. package/dist/_vercel-target.d.ts +169 -0
  73. package/dist/_vite-env-BiyJ0GQH.mjs +105 -0
  74. package/dist/_vite-env.d.ts +38 -0
  75. package/dist/_vitest-runner-CKI8_K1b.mjs +207 -0
  76. package/dist/_vitest-runner.d.ts +182 -0
  77. package/dist/_workflow-determinism-CLxFQ5ox.mjs +198 -0
  78. package/dist/_workflow-determinism.d.ts +118 -0
  79. package/dist/build-CKhanHVv.mjs +588 -0
  80. package/dist/build.d.ts +146 -0
  81. package/dist/cli-workflow.d.ts +17 -0
  82. package/dist/cli.d.ts +1 -0
  83. package/dist/cli.mjs +1092 -195
  84. package/dist/client-bundler-DZ_Zoznn.mjs +241 -0
  85. package/dist/client-bundler.d.ts +38 -0
  86. package/dist/client-bundler.mjs +3 -0
  87. package/dist/console-Dxq26Adz.mjs +447 -0
  88. package/dist/console.d.ts +70 -0
  89. package/dist/delete-DwXCHzTl.mjs +55 -0
  90. package/dist/delete.d.ts +26 -0
  91. package/dist/deploy-CbA8Ibiu.mjs +97 -0
  92. package/dist/deploy.d.ts +25 -0
  93. package/dist/dev-BWBDbUEb.mjs +274 -0
  94. package/dist/dev.d.ts +34 -0
  95. package/dist/eval-Dl8o91yC.mjs +74 -0
  96. package/dist/eval.d.ts +46 -0
  97. package/dist/init-CidslZZz.mjs +609 -0
  98. package/dist/init.d.ts +101 -0
  99. package/dist/login-oJdBWu2B.mjs +166 -0
  100. package/dist/login.d.ts +54 -0
  101. package/dist/logs-CnPK-Prw.mjs +102 -0
  102. package/dist/logs.d.ts +65 -0
  103. package/dist/project-config.d.ts +23 -0
  104. package/dist/project-config.mjs +3 -0
  105. package/dist/scaffold/.env.example +51 -0
  106. package/dist/scaffold/CLAUDE.md +390 -0
  107. package/dist/scaffold/agent-guide/AGENT-API.md +223 -0
  108. package/dist/scaffold/agent-guide/HOSTING.md +139 -0
  109. package/dist/scaffold/agent-guide/PIPELINE-TUNING.md +232 -0
  110. package/dist/scaffold/agent-guide/PROVIDERS.md +140 -0
  111. package/dist/scaffold/agent-guide/TESTING-EVALS.md +158 -0
  112. package/dist/scaffold/agent-guide/TOOLS.md +627 -0
  113. package/dist/scaffold/agent-guide/UI.md +292 -0
  114. package/dist/scaffold/agent-guide/WORKFLOWS.md +803 -0
  115. package/dist/scaffold/package.json +38 -0
  116. package/dist/scaffold/pnpm-workspace.yaml +45 -0
  117. package/dist/scaffold/tsconfig.json +3 -0
  118. package/dist/scaffold/vitest.config.ts +8 -0
  119. package/dist/secret-DPdPEet2.mjs +300 -0
  120. package/dist/secret.d.ts +70 -0
  121. package/dist/start.d.ts +112 -0
  122. package/dist/start.mjs +183 -0
  123. package/dist/studio-COjK25Rl.mjs +208 -0
  124. package/dist/studio.d.ts +56 -0
  125. package/dist/templates/applicant-screening-agent/agent.eval.test.ts +258 -0
  126. package/dist/templates/applicant-screening-agent/agent.test.ts +987 -0
  127. package/dist/templates/applicant-screening-agent/agent.ts +66 -0
  128. package/dist/templates/applicant-screening-agent/client.tsx +154 -0
  129. package/dist/templates/applicant-screening-agent/crews.ts +432 -0
  130. package/dist/templates/applicant-screening-agent/leads.json +86 -0
  131. package/dist/templates/applicant-screening-agent/screening-lock.test.ts +77 -0
  132. package/dist/templates/applicant-screening-agent/screening-lock.ts +51 -0
  133. package/dist/templates/applicant-screening-agent/shared.ts +483 -0
  134. package/dist/templates/applicant-screening-agent/system-prompt.md +21 -0
  135. package/dist/templates/applicant-screening-agent/tools/candidate_details.ts +49 -0
  136. package/dist/templates/applicant-screening-agent/tools/proceed_to_emails.ts +127 -0
  137. package/dist/templates/applicant-screening-agent/tools/read_email.ts +50 -0
  138. package/dist/templates/applicant-screening-agent/tools/rescore_with_feedback.ts +140 -0
  139. package/dist/templates/applicant-screening-agent/tools/screen_candidates.ts +128 -0
  140. package/dist/templates/applicant-screening-agent/tools/screening_status.ts +51 -0
  141. package/dist/templates/call-audit-workflow/agent.eval.test.ts +492 -0
  142. package/dist/templates/call-audit-workflow/agent.test.ts +1032 -0
  143. package/dist/templates/call-audit-workflow/agent.ts +161 -0
  144. package/dist/templates/call-audit-workflow/client.tsx +236 -0
  145. package/dist/templates/call-audit-workflow/guards.test.ts +233 -0
  146. package/dist/templates/call-audit-workflow/workflows/audit.ts +391 -0
  147. package/dist/templates/call-audit-workflow/workflows/ingest.ts +279 -0
  148. package/dist/templates/call-audit-workflow/workflows/media.ts +729 -0
  149. package/dist/templates/call-audit-workflow/workflows/summarize.ts +201 -0
  150. package/dist/templates/call-audit-workflow/workflows/sync-api.ts +54 -0
  151. package/dist/templates/code-interpreter-agent/agent.eval.test.ts +195 -0
  152. package/dist/templates/code-interpreter-agent/agent.test.ts +91 -0
  153. package/dist/templates/code-interpreter-agent/agent.ts +9 -0
  154. package/dist/templates/code-interpreter-agent/system-prompt.md +18 -0
  155. package/dist/templates/coding-agent/agent.eval.test.ts +135 -0
  156. package/dist/templates/coding-agent/agent.test.ts +109 -0
  157. package/dist/templates/coding-agent/agent.ts +45 -0
  158. package/dist/templates/coding-agent/chat.ts +63 -0
  159. package/dist/templates/coding-agent/shared.ts +46 -0
  160. package/dist/templates/coding-agent/system-prompt.md +32 -0
  161. package/dist/templates/coding-agent/tools/bash.ts +6 -0
  162. package/dist/templates/coding-agent/tools/delete_file.ts +6 -0
  163. package/dist/templates/coding-agent/tools/edit_file.ts +6 -0
  164. package/dist/templates/coding-agent/tools/glob.ts +6 -0
  165. package/dist/templates/coding-agent/tools/grep.ts +6 -0
  166. package/dist/templates/coding-agent/tools/list_files.ts +6 -0
  167. package/dist/templates/coding-agent/tools/read_file.ts +6 -0
  168. package/dist/templates/coding-agent/tools/todo_write.ts +6 -0
  169. package/dist/templates/coding-agent/tools/write_file.ts +6 -0
  170. package/dist/templates/custom-pipeline-agent/agent.eval.test.ts +79 -0
  171. package/dist/templates/custom-pipeline-agent/agent.test.ts +79 -0
  172. package/dist/templates/custom-pipeline-agent/agent.ts +13 -0
  173. package/dist/templates/custom-pipeline-agent/modes.test.ts +162 -0
  174. package/dist/templates/custom-pipeline-agent/stages.test.ts +330 -0
  175. package/dist/templates/document-redline-workflow/agent.eval.test.ts +251 -0
  176. package/dist/templates/document-redline-workflow/agent.test.ts +552 -0
  177. package/dist/templates/document-redline-workflow/agent.ts +112 -0
  178. package/dist/templates/document-redline-workflow/client.tsx +224 -0
  179. package/dist/templates/document-redline-workflow/form.ts +74 -0
  180. package/dist/templates/document-redline-workflow/workflows/prompts.ts +68 -0
  181. package/dist/templates/document-redline-workflow/workflows/redline.ts +317 -0
  182. package/dist/templates/emergency-dispatch-agent/agent.eval.test.ts +372 -0
  183. package/dist/templates/emergency-dispatch-agent/agent.test.ts +576 -0
  184. package/dist/templates/emergency-dispatch-agent/agent.ts +63 -0
  185. package/dist/templates/emergency-dispatch-agent/client.tsx +453 -0
  186. package/dist/templates/emergency-dispatch-agent/events.ts +48 -0
  187. package/dist/templates/emergency-dispatch-agent/guardrails.ts +105 -0
  188. package/dist/templates/emergency-dispatch-agent/shared.ts +768 -0
  189. package/dist/templates/emergency-dispatch-agent/system-prompt.md +42 -0
  190. package/dist/templates/emergency-dispatch-agent/tools/incident_add_note.ts +28 -0
  191. package/dist/templates/emergency-dispatch-agent/tools/incident_create.ts +95 -0
  192. package/dist/templates/emergency-dispatch-agent/tools/incident_escalate.ts +96 -0
  193. package/dist/templates/emergency-dispatch-agent/tools/incident_get.ts +40 -0
  194. package/dist/templates/emergency-dispatch-agent/tools/incident_triage.ts +90 -0
  195. package/dist/templates/emergency-dispatch-agent/tools/incident_update_status.ts +75 -0
  196. package/dist/templates/emergency-dispatch-agent/tools/ops_dashboard.ts +72 -0
  197. package/dist/templates/emergency-dispatch-agent/tools/ops_protocols.ts +27 -0
  198. package/dist/templates/emergency-dispatch-agent/tools/ops_run_scenario.ts +154 -0
  199. package/dist/templates/emergency-dispatch-agent/tools/resources_dispatch.ts +112 -0
  200. package/dist/templates/emergency-dispatch-agent/tools/resources_get_available.ts +34 -0
  201. package/dist/templates/emergency-dispatch-agent/tools/resources_update_status.ts +63 -0
  202. package/dist/templates/entertainment-picks-agent/agent.eval.test.ts +281 -0
  203. package/dist/templates/entertainment-picks-agent/agent.test.ts +260 -0
  204. package/dist/templates/entertainment-picks-agent/agent.ts +14 -0
  205. package/dist/templates/entertainment-picks-agent/client.tsx +169 -0
  206. package/dist/templates/entertainment-picks-agent/shared.ts +50 -0
  207. package/dist/templates/entertainment-picks-agent/system-prompt.md +19 -0
  208. package/dist/templates/entertainment-picks-agent/tools/recommend.ts +79 -0
  209. package/dist/templates/entertainment-picks-agent/tools/revisit.ts +56 -0
  210. package/dist/templates/executive-inbox-agent/agent.eval.test.ts +296 -0
  211. package/dist/templates/executive-inbox-agent/agent.test.ts +682 -0
  212. package/dist/templates/executive-inbox-agent/agent.ts +51 -0
  213. package/dist/templates/executive-inbox-agent/calendar.test.ts +203 -0
  214. package/dist/templates/executive-inbox-agent/client.tsx +195 -0
  215. package/dist/templates/executive-inbox-agent/inbox.ts +233 -0
  216. package/dist/templates/executive-inbox-agent/meeting.ts +138 -0
  217. package/dist/templates/executive-inbox-agent/nodes.ts +148 -0
  218. package/dist/templates/executive-inbox-agent/prompts.ts +333 -0
  219. package/dist/templates/executive-inbox-agent/review.ts +425 -0
  220. package/dist/templates/executive-inbox-agent/shared.ts +486 -0
  221. package/dist/templates/executive-inbox-agent/system-prompt.md +15 -0
  222. package/dist/templates/executive-inbox-agent/tools/accept.ts +10 -0
  223. package/dist/templates/executive-inbox-agent/tools/ask_question.ts +30 -0
  224. package/dist/templates/executive-inbox-agent/tools/draft_reply.ts +67 -0
  225. package/dist/templates/executive-inbox-agent/tools/edit.ts +10 -0
  226. package/dist/templates/executive-inbox-agent/tools/ignore.ts +10 -0
  227. package/dist/templates/executive-inbox-agent/tools/inbox_status.ts +27 -0
  228. package/dist/templates/executive-inbox-agent/tools/meeting_assistant.ts +52 -0
  229. package/dist/templates/executive-inbox-agent/tools/new_email.ts +50 -0
  230. package/dist/templates/executive-inbox-agent/tools/open_email.ts +157 -0
  231. package/dist/templates/executive-inbox-agent/tools/respond.ts +10 -0
  232. package/dist/templates/executive-inbox-agent/tools/review_memory.ts +22 -0
  233. package/dist/templates/executive-inbox-agent/tools/send_calendar_invite.ts +68 -0
  234. package/dist/templates/executive-inbox-agent/tools/triage_inbox.ts +75 -0
  235. package/dist/templates/front-desk-agent/agent.eval.test.ts +177 -0
  236. package/dist/templates/front-desk-agent/agent.test.ts +155 -0
  237. package/dist/templates/front-desk-agent/agent.ts +22 -0
  238. package/dist/templates/front-desk-agent/shared.ts +239 -0
  239. package/dist/templates/front-desk-agent/system-prompt.md +13 -0
  240. package/dist/templates/front-desk-agent/tools/verify_account.ts +41 -0
  241. package/dist/templates/home-assistant-agent/agent.eval.test.ts +176 -0
  242. package/dist/templates/home-assistant-agent/agent.test.ts +512 -0
  243. package/dist/templates/home-assistant-agent/agent.ts +37 -0
  244. package/dist/templates/home-assistant-agent/client.tsx +176 -0
  245. package/dist/templates/home-assistant-agent/ring.tsx +55 -0
  246. package/dist/templates/home-assistant-agent/shared.ts +130 -0
  247. package/dist/templates/home-assistant-agent/system-prompt.md +43 -0
  248. package/dist/templates/home-assistant-agent/tools/cancel_reminders.ts +16 -0
  249. package/dist/templates/home-assistant-agent/tools/deep_research.ts +55 -0
  250. package/dist/templates/home-assistant-agent/tools/remind_me.ts +53 -0
  251. package/dist/templates/home-assistant-agent/tools/stop.ts +25 -0
  252. package/dist/templates/home-assistant-agent/use-speaker.ts +98 -0
  253. package/dist/templates/home-assistant-agent/workflows/remind.ts +25 -0
  254. package/dist/templates/home-assistant-agent/workflows/research-prompts.ts +41 -0
  255. package/dist/templates/home-assistant-agent/workflows/research.ts +110 -0
  256. package/dist/templates/home-assistant-agent/workflows/text.ts +30 -0
  257. package/dist/templates/hotel-reception-agent/agent.eval.test.ts +241 -0
  258. package/dist/templates/hotel-reception-agent/agent.test.ts +1121 -0
  259. package/dist/templates/hotel-reception-agent/agent.ts +66 -0
  260. package/dist/templates/hotel-reception-agent/booking.ts +159 -0
  261. package/dist/templates/hotel-reception-agent/card.ts +92 -0
  262. package/dist/templates/hotel-reception-agent/catalogs.ts +219 -0
  263. package/dist/templates/hotel-reception-agent/client.tsx +150 -0
  264. package/dist/templates/hotel-reception-agent/concierge.ts +104 -0
  265. package/dist/templates/hotel-reception-agent/desk-seams.test.ts +339 -0
  266. package/dist/templates/hotel-reception-agent/desk.ts +220 -0
  267. package/dist/templates/hotel-reception-agent/disputes.ts +214 -0
  268. package/dist/templates/hotel-reception-agent/events.ts +80 -0
  269. package/dist/templates/hotel-reception-agent/hotel.ts +412 -0
  270. package/dist/templates/hotel-reception-agent/policies.ts +209 -0
  271. package/dist/templates/hotel-reception-agent/records.ts +384 -0
  272. package/dist/templates/hotel-reception-agent/restaurant.ts +147 -0
  273. package/dist/templates/hotel-reception-agent/seed.ts +955 -0
  274. package/dist/templates/hotel-reception-agent/session.ts +50 -0
  275. package/dist/templates/hotel-reception-agent/shared.ts +353 -0
  276. package/dist/templates/hotel-reception-agent/system-prompt.md +76 -0
  277. package/dist/templates/hotel-reception-agent/tools/abandon_booking.ts +31 -0
  278. package/dist/templates/hotel-reception-agent/tools/add_to_waitlist.ts +42 -0
  279. package/dist/templates/hotel-reception-agent/tools/book_airport_car.ts +58 -0
  280. package/dist/templates/hotel-reception-agent/tools/book_business_center.ts +44 -0
  281. package/dist/templates/hotel-reception-agent/tools/book_spa_appointment.ts +39 -0
  282. package/dist/templates/hotel-reception-agent/tools/book_tour.ts +35 -0
  283. package/dist/templates/hotel-reception-agent/tools/cancel_restaurant_reservation.ts +26 -0
  284. package/dist/templates/hotel-reception-agent/tools/cancel_room_booking.ts +64 -0
  285. package/dist/templates/hotel-reception-agent/tools/check_restaurant_availability.ts +24 -0
  286. package/dist/templates/hotel-reception-agent/tools/check_room_availability.ts +40 -0
  287. package/dist/templates/hotel-reception-agent/tools/choose_room.ts +93 -0
  288. package/dist/templates/hotel-reception-agent/tools/confirm_booking.ts +154 -0
  289. package/dist/templates/hotel-reception-agent/tools/dispatch_emergency.ts +62 -0
  290. package/dist/templates/hotel-reception-agent/tools/dispute_charge.ts +91 -0
  291. package/dist/templates/hotel-reception-agent/tools/flag_late_arrival.ts +27 -0
  292. package/dist/templates/hotel-reception-agent/tools/lookup_booking.ts +49 -0
  293. package/dist/templates/hotel-reception-agent/tools/lookup_guest_history.ts +28 -0
  294. package/dist/templates/hotel-reception-agent/tools/lookup_invoice.ts +27 -0
  295. package/dist/templates/hotel-reception-agent/tools/lookup_policy.ts +20 -0
  296. package/dist/templates/hotel-reception-agent/tools/lookup_restaurant_reservation.ts +27 -0
  297. package/dist/templates/hotel-reception-agent/tools/modify_restaurant_reservation.ts +75 -0
  298. package/dist/templates/hotel-reception-agent/tools/order_flowers.ts +40 -0
  299. package/dist/templates/hotel-reception-agent/tools/record_card.ts +46 -0
  300. package/dist/templates/hotel-reception-agent/tools/record_followup.ts +51 -0
  301. package/dist/templates/hotel-reception-agent/tools/record_group_inquiry.ts +45 -0
  302. package/dist/templates/hotel-reception-agent/tools/record_guest_details.ts +71 -0
  303. package/dist/templates/hotel-reception-agent/tools/reinstate_booking.ts +65 -0
  304. package/dist/templates/hotel-reception-agent/tools/request_flight_reconfirmation.ts +55 -0
  305. package/dist/templates/hotel-reception-agent/tools/resend_confirmation.ts +40 -0
  306. package/dist/templates/hotel-reception-agent/tools/reserve_table.ts +87 -0
  307. package/dist/templates/hotel-reception-agent/tools/resolve_room_conflict.ts +49 -0
  308. package/dist/templates/hotel-reception-agent/tools/schedule_wakeup_call.ts +49 -0
  309. package/dist/templates/hotel-reception-agent/tools/set_do_not_disturb.ts +29 -0
  310. package/dist/templates/hotel-reception-agent/tools/set_extras.ts +51 -0
  311. package/dist/templates/hotel-reception-agent/tools/set_stay.ts +98 -0
  312. package/dist/templates/hotel-reception-agent/tools/start_booking_modification.ts +58 -0
  313. package/dist/templates/hotel-reception-agent/tools/start_room_booking.ts +50 -0
  314. package/dist/templates/hotel-reception-agent/tools/take_guest_message.ts +72 -0
  315. package/dist/templates/hotel-reception-agent/tools/transfer_call.ts +48 -0
  316. package/dist/templates/hotel-reception-agent/tools/update_card.ts +46 -0
  317. package/dist/templates/hotel-reception-agent/tools/verify_booking.ts +96 -0
  318. package/dist/templates/link-digest-workflow/agent.eval.test.ts +231 -0
  319. package/dist/templates/link-digest-workflow/agent.test.ts +646 -0
  320. package/dist/templates/link-digest-workflow/agent.ts +100 -0
  321. package/dist/templates/link-digest-workflow/api-client.ts +144 -0
  322. package/dist/templates/link-digest-workflow/client.tsx +231 -0
  323. package/dist/templates/link-digest-workflow/workflows/digest.ts +334 -0
  324. package/dist/templates/medication-safety-agent/agent.eval.test.ts +182 -0
  325. package/dist/templates/medication-safety-agent/agent.test.ts +329 -0
  326. package/dist/templates/medication-safety-agent/agent.ts +62 -0
  327. package/dist/templates/medication-safety-agent/fda.test.ts +129 -0
  328. package/dist/templates/medication-safety-agent/fda.ts +166 -0
  329. package/dist/templates/medication-safety-agent/system-prompt.md +26 -0
  330. package/dist/templates/medication-safety-agent/tools/check_drug_interaction.ts +70 -0
  331. package/dist/templates/medication-safety-agent/tools/medication_lookup.ts +46 -0
  332. package/dist/templates/meeting-recap-agent/agent.eval.test.ts +459 -0
  333. package/dist/templates/meeting-recap-agent/agent.test.ts +1408 -0
  334. package/dist/templates/meeting-recap-agent/agent.ts +104 -0
  335. package/dist/templates/meeting-recap-agent/shared.ts +44 -0
  336. package/dist/templates/meeting-recap-agent/tools/cancel_recap.ts +23 -0
  337. package/dist/templates/meeting-recap-agent/tools/keep_transcript.ts +31 -0
  338. package/dist/templates/meeting-recap-agent/tools/recap_progress.ts +24 -0
  339. package/dist/templates/meeting-recap-agent/tools/recap_status.ts +45 -0
  340. package/dist/templates/meeting-recap-agent/tools/request_recap.ts +44 -0
  341. package/dist/templates/meeting-recap-agent/workflows/recap.ts +838 -0
  342. package/dist/templates/meeting-recap-agent/workflows/tokens.ts +47 -0
  343. package/dist/templates/pizza-ordering-agent/agent.eval.test.ts +228 -0
  344. package/dist/templates/pizza-ordering-agent/agent.test.ts +299 -0
  345. package/dist/templates/pizza-ordering-agent/agent.ts +24 -0
  346. package/dist/templates/pizza-ordering-agent/client.tsx +104 -0
  347. package/dist/templates/pizza-ordering-agent/shared.ts +225 -0
  348. package/dist/templates/pizza-ordering-agent/system-prompt.md +23 -0
  349. package/dist/templates/pizza-ordering-agent/tools/add_pizza.ts +27 -0
  350. package/dist/templates/pizza-ordering-agent/tools/place_order.ts +26 -0
  351. package/dist/templates/pizza-ordering-agent/tools/remove_pizza.ts +18 -0
  352. package/dist/templates/pizza-ordering-agent/tools/set_customer_name.ts +13 -0
  353. package/dist/templates/pizza-ordering-agent/tools/update_pizza.ts +28 -0
  354. package/dist/templates/pizza-ordering-agent/tools/view_order.ts +21 -0
  355. package/dist/templates/podcast-digest-workflow/agent.eval.test.ts +421 -0
  356. package/dist/templates/podcast-digest-workflow/agent.test.ts +1225 -0
  357. package/dist/templates/podcast-digest-workflow/agent.ts +143 -0
  358. package/dist/templates/podcast-digest-workflow/client.tsx +259 -0
  359. package/dist/templates/podcast-digest-workflow/workflows/digest.ts +499 -0
  360. package/dist/templates/podcast-digest-workflow/workflows/feeds.ts +575 -0
  361. package/dist/templates/podcast-digest-workflow/workflows/slack.ts +153 -0
  362. package/dist/templates/push-to-talk-agent/agent.eval.test.ts +78 -0
  363. package/dist/templates/push-to-talk-agent/agent.test.ts +63 -0
  364. package/dist/templates/push-to-talk-agent/agent.ts +22 -0
  365. package/dist/templates/push-to-talk-agent/client.tsx +124 -0
  366. package/dist/templates/push-to-talk-agent/shared.ts +28 -0
  367. package/dist/templates/push-to-talk-agent/system-prompt.md +11 -0
  368. package/dist/templates/push-to-talk-agent/tools/list_notes.ts +15 -0
  369. package/dist/templates/push-to-talk-agent/tools/save_note.ts +26 -0
  370. package/dist/templates/quickstart-agent/agent.eval.test.ts +148 -0
  371. package/dist/templates/quickstart-agent/agent.test.ts +96 -0
  372. package/dist/templates/quickstart-agent/agent.ts +25 -0
  373. package/dist/templates/quickstart-agent/system-prompt.md +8 -0
  374. package/dist/templates/quickstart-agent/tools/get_weather.ts +59 -0
  375. package/dist/templates/research-handoff-agent/agent.eval.test.ts +348 -0
  376. package/dist/templates/research-handoff-agent/agent.test.ts +818 -0
  377. package/dist/templates/research-handoff-agent/agent.ts +118 -0
  378. package/dist/templates/research-handoff-agent/shared.ts +41 -0
  379. package/dist/templates/research-handoff-agent/tools/file_it_now.ts +32 -0
  380. package/dist/templates/research-handoff-agent/tools/request_research.ts +33 -0
  381. package/dist/templates/research-handoff-agent/tools/research_progress.ts +23 -0
  382. package/dist/templates/research-handoff-agent/tools/research_status.ts +73 -0
  383. package/dist/templates/research-handoff-agent/workflows/filing.ts +164 -0
  384. package/dist/templates/research-handoff-agent/workflows/prompts.ts +46 -0
  385. package/dist/templates/research-handoff-agent/workflows/research.ts +100 -0
  386. package/dist/templates/research-handoff-agent/workflows/review.ts +43 -0
  387. package/dist/templates/research-planner-agent/agent.eval.test.ts +241 -0
  388. package/dist/templates/research-planner-agent/agent.test.ts +640 -0
  389. package/dist/templates/research-planner-agent/agent.ts +26 -0
  390. package/dist/templates/research-planner-agent/client.tsx +120 -0
  391. package/dist/templates/research-planner-agent/procedure.ts +287 -0
  392. package/dist/templates/research-planner-agent/prompts.ts +153 -0
  393. package/dist/templates/research-planner-agent/shared.ts +356 -0
  394. package/dist/templates/research-planner-agent/system-prompt.md +18 -0
  395. package/dist/templates/research-planner-agent/tools/plan_status.ts +41 -0
  396. package/dist/templates/research-planner-agent/tools/revise_plan.ts +71 -0
  397. package/dist/templates/research-planner-agent/tools/start_plan.ts +62 -0
  398. package/dist/templates/research-planner-agent/tools/work_next_step.ts +177 -0
  399. package/dist/templates/retail-orders-agent/address.ts +109 -0
  400. package/dist/templates/retail-orders-agent/agent.eval.test.ts +305 -0
  401. package/dist/templates/retail-orders-agent/agent.test.ts +1260 -0
  402. package/dist/templates/retail-orders-agent/agent.ts +103 -0
  403. package/dist/templates/retail-orders-agent/authenticate.ts +34 -0
  404. package/dist/templates/retail-orders-agent/cancel.ts +114 -0
  405. package/dist/templates/retail-orders-agent/client.tsx +579 -0
  406. package/dist/templates/retail-orders-agent/keyterms.ts +154 -0
  407. package/dist/templates/retail-orders-agent/payment.ts +103 -0
  408. package/dist/templates/retail-orders-agent/pending.test.ts +204 -0
  409. package/dist/templates/retail-orders-agent/pending.ts +137 -0
  410. package/dist/templates/retail-orders-agent/refund.ts +19 -0
  411. package/dist/templates/retail-orders-agent/registry.test.ts +446 -0
  412. package/dist/templates/retail-orders-agent/resolve.test.ts +100 -0
  413. package/dist/templates/retail-orders-agent/resolve.ts +114 -0
  414. package/dist/templates/retail-orders-agent/returns.ts +101 -0
  415. package/dist/templates/retail-orders-agent/seed.json +4260 -0
  416. package/dist/templates/retail-orders-agent/seed.test.ts +233 -0
  417. package/dist/templates/retail-orders-agent/shared.test.ts +240 -0
  418. package/dist/templates/retail-orders-agent/shared.ts +547 -0
  419. package/dist/templates/retail-orders-agent/store.test.ts +331 -0
  420. package/dist/templates/retail-orders-agent/store.ts +485 -0
  421. package/dist/templates/retail-orders-agent/swap.test.ts +189 -0
  422. package/dist/templates/retail-orders-agent/swap.ts +358 -0
  423. package/dist/templates/retail-orders-agent/system-prompt.md +152 -0
  424. package/dist/templates/retail-orders-agent/tools/cancel_change.ts +33 -0
  425. package/dist/templates/retail-orders-agent/tools/cancel_pending_order.ts +31 -0
  426. package/dist/templates/retail-orders-agent/tools/confirm_change.ts +42 -0
  427. package/dist/templates/retail-orders-agent/tools/exchange_delivered_order_items.ts +47 -0
  428. package/dist/templates/retail-orders-agent/tools/find_user_id_by_email.ts +31 -0
  429. package/dist/templates/retail-orders-agent/tools/find_user_id_by_name_zip.ts +36 -0
  430. package/dist/templates/retail-orders-agent/tools/get_item_details.ts +27 -0
  431. package/dist/templates/retail-orders-agent/tools/get_order_details.ts +37 -0
  432. package/dist/templates/retail-orders-agent/tools/get_product_details.ts +30 -0
  433. package/dist/templates/retail-orders-agent/tools/get_user_details.ts +37 -0
  434. package/dist/templates/retail-orders-agent/tools/list_all_product_types.ts +22 -0
  435. package/dist/templates/retail-orders-agent/tools/modify_pending_order_address.ts +27 -0
  436. package/dist/templates/retail-orders-agent/tools/modify_pending_order_items.ts +48 -0
  437. package/dist/templates/retail-orders-agent/tools/modify_pending_order_payment.ts +32 -0
  438. package/dist/templates/retail-orders-agent/tools/modify_user_address.ts +26 -0
  439. package/dist/templates/retail-orders-agent/tools/return_delivered_order_items.ts +37 -0
  440. package/dist/templates/retail-orders-agent/tools/transfer_to_human_agents.ts +28 -0
  441. package/dist/templates/roadside-assistance-agent/agent.eval.test.ts +283 -0
  442. package/dist/templates/roadside-assistance-agent/agent.test.ts +650 -0
  443. package/dist/templates/roadside-assistance-agent/agent.ts +89 -0
  444. package/dist/templates/roadside-assistance-agent/call.ts +232 -0
  445. package/dist/templates/roadside-assistance-agent/events.ts +92 -0
  446. package/dist/templates/roadside-assistance-agent/shared.ts +346 -0
  447. package/dist/templates/roadside-assistance-agent/system-prompt.md +37 -0
  448. package/dist/templates/roadside-assistance-agent/tools/acknowledge_disclosure.ts +61 -0
  449. package/dist/templates/roadside-assistance-agent/tools/dispatch_truck.ts +149 -0
  450. package/dist/templates/roadside-assistance-agent/tools/job_status.ts +38 -0
  451. package/dist/templates/roadside-assistance-agent/tools/lookup_coverage.ts +83 -0
  452. package/dist/templates/roadside-assistance-agent/tools/report_location.ts +79 -0
  453. package/dist/templates/roadside-assistance-agent/tools/service_disclosure.ts +51 -0
  454. package/dist/templates/roadside-assistance-agent/yard.test.ts +162 -0
  455. package/dist/templates/roadside-assistance-agent/yard.ts +183 -0
  456. package/dist/templates/spoken-summary-workflow/agent.eval.test.ts +354 -0
  457. package/dist/templates/spoken-summary-workflow/agent.test.ts +493 -0
  458. package/dist/templates/spoken-summary-workflow/agent.ts +164 -0
  459. package/dist/templates/spoken-summary-workflow/client.tsx +220 -0
  460. package/dist/templates/spoken-summary-workflow/workflows/summarize.ts +260 -0
  461. package/dist/templates/spoken-summary-workflow/workflows/transcribe.ts +137 -0
  462. package/dist/templates/tabletop-rpg-agent/agent.eval.test.ts +314 -0
  463. package/dist/templates/tabletop-rpg-agent/agent.test.ts +1000 -0
  464. package/dist/templates/tabletop-rpg-agent/agent.ts +58 -0
  465. package/dist/templates/tabletop-rpg-agent/client.tsx +814 -0
  466. package/dist/templates/tabletop-rpg-agent/shared.ts +1028 -0
  467. package/dist/templates/tabletop-rpg-agent/system-prompt.md +116 -0
  468. package/dist/templates/tabletop-rpg-agent/tools/action_roll.ts +119 -0
  469. package/dist/templates/tabletop-rpg-agent/tools/burn_momentum.ts +110 -0
  470. package/dist/templates/tabletop-rpg-agent/tools/check_state.ts +37 -0
  471. package/dist/templates/tabletop-rpg-agent/tools/oracle.ts +255 -0
  472. package/dist/templates/tabletop-rpg-agent/tools/setup_character.ts +228 -0
  473. package/dist/templates/tabletop-rpg-agent/tools/update_state.ts +194 -0
  474. package/dist/templates/technical-support-agent/agent.eval.test.ts +260 -0
  475. package/dist/templates/technical-support-agent/agent.test.ts +424 -0
  476. package/dist/templates/technical-support-agent/agent.ts +39 -0
  477. package/dist/templates/technical-support-agent/client.tsx +132 -0
  478. package/dist/templates/technical-support-agent/knowledge.json +65 -0
  479. package/dist/templates/technical-support-agent/knowledge.ts +165 -0
  480. package/dist/templates/technical-support-agent/nodes.ts +143 -0
  481. package/dist/templates/technical-support-agent/procedure.ts +453 -0
  482. package/dist/templates/technical-support-agent/prompts.ts +102 -0
  483. package/dist/templates/technical-support-agent/shared.ts +128 -0
  484. package/dist/templates/technical-support-agent/system-prompt.md +18 -0
  485. package/dist/templates/technical-support-agent/tools/answer_question.ts +134 -0
  486. package/dist/templates/technical-support-agent/tools/list_topics.ts +23 -0
  487. package/dist/templates/technical-support-agent/tools/log_ticket.ts +30 -0
  488. package/dist/templates/text-adventure-agent/agent.eval.test.ts +222 -0
  489. package/dist/templates/text-adventure-agent/agent.test.ts +429 -0
  490. package/dist/templates/text-adventure-agent/agent.ts +76 -0
  491. package/dist/templates/text-adventure-agent/client.tsx +359 -0
  492. package/dist/templates/text-adventure-agent/shared.ts +210 -0
  493. package/dist/templates/text-adventure-agent/system-prompt.md +50 -0
  494. package/dist/templates/text-adventure-agent/tools/game_state_drop.ts +29 -0
  495. package/dist/templates/text-adventure-agent/tools/game_state_flag.ts +13 -0
  496. package/dist/templates/text-adventure-agent/tools/game_state_get.ts +17 -0
  497. package/dist/templates/text-adventure-agent/tools/game_state_move.ts +15 -0
  498. package/dist/templates/text-adventure-agent/tools/game_state_restart.ts +13 -0
  499. package/dist/templates/text-adventure-agent/tools/game_state_score.ts +19 -0
  500. package/dist/templates/text-adventure-agent/tools/game_state_take.ts +13 -0
  501. package/dist/templates/topic-briefing-agent/agent.eval.test.ts +202 -0
  502. package/dist/templates/topic-briefing-agent/agent.test.ts +651 -0
  503. package/dist/templates/topic-briefing-agent/agent.ts +45 -0
  504. package/dist/templates/topic-briefing-agent/shared.ts +392 -0
  505. package/dist/templates/topic-briefing-agent/slack.ts +108 -0
  506. package/dist/templates/topic-briefing-agent/system-prompt.md +54 -0
  507. package/dist/templates/topic-briefing-agent/tools/briefing_so_far.ts +43 -0
  508. package/dist/templates/topic-briefing-agent/tools/research_topic.ts +80 -0
  509. package/dist/templates/topic-briefing-agent/tools/send_briefing.ts +115 -0
  510. package/dist/templates/topic-briefing-agent/tools/verify_claim.ts +123 -0
  511. package/dist/templates/transcription-workflow/agent.eval.test.ts +237 -0
  512. package/dist/templates/transcription-workflow/agent.test.ts +2033 -0
  513. package/dist/templates/transcription-workflow/agent.ts +188 -0
  514. package/dist/templates/transcription-workflow/client.tsx +511 -0
  515. package/dist/templates/transcription-workflow/recover.test.ts +219 -0
  516. package/dist/templates/transcription-workflow/recover.ts +154 -0
  517. package/dist/templates/transcription-workflow/run-panel.tsx +212 -0
  518. package/dist/templates/transcription-workflow/total-latency.tsx +170 -0
  519. package/dist/templates/transcription-workflow/workflows/batch.ts +189 -0
  520. package/dist/templates/transcription-workflow/workflows/downsample.ts +273 -0
  521. package/dist/templates/transcription-workflow/workflows/normalize.ts +385 -0
  522. package/dist/templates/transcription-workflow/workflows/stitch.ts +122 -0
  523. package/dist/templates/transcription-workflow/workflows/stream.ts +690 -0
  524. package/dist/templates/transcription-workflow/workflows/sync-api.ts +81 -0
  525. package/dist/templates/transcription-workflow/workflows/transcribe.ts +479 -0
  526. package/dist/templates/transcription-workflow/workflows/wav.ts +250 -0
  527. package/dist/templates/travel-concierge-agent/agent.eval.test.ts +300 -0
  528. package/dist/templates/travel-concierge-agent/agent.test.ts +601 -0
  529. package/dist/templates/travel-concierge-agent/agent.ts +62 -0
  530. package/dist/templates/travel-concierge-agent/call-events.ts +80 -0
  531. package/dist/templates/travel-concierge-agent/client.tsx +146 -0
  532. package/dist/templates/travel-concierge-agent/routing.ts +170 -0
  533. package/dist/templates/travel-concierge-agent/shared.ts +862 -0
  534. package/dist/templates/travel-concierge-agent/system-prompt.md +30 -0
  535. package/dist/templates/travel-concierge-agent/tools/book_car_rental.ts +21 -0
  536. package/dist/templates/travel-concierge-agent/tools/book_excursion.ts +19 -0
  537. package/dist/templates/travel-concierge-agent/tools/book_hotel.ts +21 -0
  538. package/dist/templates/travel-concierge-agent/tools/cancel_action.ts +9 -0
  539. package/dist/templates/travel-concierge-agent/tools/cancel_ticket.ts +21 -0
  540. package/dist/templates/travel-concierge-agent/tools/complete_or_escalate.ts +9 -0
  541. package/dist/templates/travel-concierge-agent/tools/confirm_action.ts +9 -0
  542. package/dist/templates/travel-concierge-agent/tools/lookup_booking.ts +36 -0
  543. package/dist/templates/travel-concierge-agent/tools/search_car_rentals.ts +36 -0
  544. package/dist/templates/travel-concierge-agent/tools/search_excursions.ts +40 -0
  545. package/dist/templates/travel-concierge-agent/tools/search_flights.ts +58 -0
  546. package/dist/templates/travel-concierge-agent/tools/search_hotels.ts +39 -0
  547. package/dist/templates/travel-concierge-agent/tools/to_car_rental_assistant.ts +11 -0
  548. package/dist/templates/travel-concierge-agent/tools/to_excursion_assistant.ts +11 -0
  549. package/dist/templates/travel-concierge-agent/tools/to_flight_assistant.ts +11 -0
  550. package/dist/templates/travel-concierge-agent/tools/to_hotel_assistant.ts +11 -0
  551. package/dist/templates/travel-concierge-agent/tools/update_ticket.ts +23 -0
  552. package/dist/templates/web-research-agent/agent.eval.test.ts +144 -0
  553. package/dist/templates/web-research-agent/agent.test.ts +182 -0
  554. package/dist/templates/web-research-agent/agent.ts +128 -0
  555. package/dist/templates/web-research-agent/system-prompt.md +33 -0
  556. package/dist/templates/word-game-agent/agent.eval.test.ts +222 -0
  557. package/dist/templates/word-game-agent/agent.test.ts +490 -0
  558. package/dist/templates/word-game-agent/agent.ts +55 -0
  559. package/dist/templates/word-game-agent/client.tsx +211 -0
  560. package/dist/templates/word-game-agent/game.ts +133 -0
  561. package/dist/templates/word-game-agent/guess.ts +63 -0
  562. package/dist/templates/word-game-agent/player.ts +67 -0
  563. package/dist/templates/word-game-agent/shared.ts +249 -0
  564. package/dist/templates/word-game-agent/system-prompt.md +15 -0
  565. package/dist/templates/word-game-agent/tools/final_score.ts +37 -0
  566. package/dist/templates/word-game-agent/tools/relay_description.ts +137 -0
  567. package/dist/templates/word-game-agent/tools/repeat_word.ts +19 -0
  568. package/dist/templates/word-game-agent/tools/skip_word.ts +31 -0
  569. package/dist/templates/word-game-agent/tools/start_game.ts +52 -0
  570. package/dist/templates/word-game-agent/words.ts +278 -0
  571. package/dist/test-XufelYGW.mjs +104 -0
  572. package/dist/test.d.ts +81 -0
  573. package/dist/typecheck.d.ts +44 -0
  574. package/dist/typecheck.mjs +185 -0
  575. package/dist/worker-bundler.d.ts +37 -0
  576. package/dist/worker-bundler.mjs +156 -0
  577. package/dist/workflow-CDUlTD5B.mjs +239 -0
  578. package/dist/workflow.d.ts +76 -0
  579. package/package.json +74 -28
  580. package/dist/_api-client-H4MFOr8j.mjs +0 -35
  581. package/dist/_bundler-DQtFVeww.mjs +0 -125
  582. package/dist/_discover-DzsMlg3G.mjs +0 -218
  583. package/dist/_init-CbMs9S2O.mjs +0 -56
  584. package/dist/_templates-BDkbj3TM.mjs +0 -72
  585. package/dist/_ui-DWGXImbO.mjs +0 -30
  586. package/dist/delete-CalIL6Pg.mjs +0 -34
  587. package/dist/deploy-CLs8gLHV.mjs +0 -53
  588. package/dist/dev-DEZKrw8v.mjs +0 -18
  589. package/dist/init-CNuntiij.mjs +0 -114
  590. package/dist/secret-xmLQ96Yz.mjs +0 -46
  591. package/dist/test-yqHGZPF3.mjs +0 -44
@@ -0,0 +1,2033 @@
1
+ // Copyright 2026 the AAI authors. MIT license.
2
+ /**
3
+ * Specs for the transcription desk's declaration, its WAV arithmetic, and its
4
+ * steps.
5
+ *
6
+ * A step is an ordinary exported async function, so its retries, its
7
+ * `FatalError` guards, its HTTP handling and its merge are all testable
8
+ * directly. **And one of the three bodies IS driven**, on the real replay
9
+ * engine — `transcribeBatch`, in the last block, which is the flow that reaches
10
+ * no ffmpeg. The other two normalize the recording first and this repo's test
11
+ * environment has no ffmpeg, so their durability stays `aai-cli`'s
12
+ * `dev-workflow.scenario.test.ts`'s. Saying which of the three is covered is
13
+ * the point: a body test dressed up as a durability test would be the worse
14
+ * failure, and so would a durable one that implied it covered all three.
15
+ *
16
+ * The WAV half is worth its own section because it is where a silent bug lives:
17
+ * a cut that lands mid-frame, or an off-by-one in the chunk walk, produces audio
18
+ * the decoder happily transcribes into confident nonsense.
19
+ */
20
+
21
+ import { readdir } from "node:fs/promises";
22
+ import { tmpdir } from "node:os";
23
+ import { stepReadUpload, type UploadRange, WAV_HEADER_BYTES } from "@alexkroman1/aai/step";
24
+ import { DEFAULT_RETRY_DELAY_MS, FatalError, RetryableError } from "@alexkroman1/aai/step-errors";
25
+ import { createWorkflowContext, runWorkflow } from "@alexkroman1/aai-runtime/testing";
26
+ import {
27
+ installStubReporter,
28
+ installStubStepFetch,
29
+ installStubTranscribe,
30
+ installStubUploads,
31
+ } from "@alexkroman1/aai-runtime/testing/vitest";
32
+ import { beforeEach, describe, expect, test, vi } from "vitest";
33
+ import { z } from "zod";
34
+ import agentDef, { transcribe, transcribeBatch, transcribeStream } from "./agent.ts";
35
+ import { createJob, pollTranscript, uploadToProvider } from "./workflows/batch.ts";
36
+ import {
37
+ downsampleSegment,
38
+ NORMALIZED_CHANNELS,
39
+ NORMALIZED_SAMPLE_RATE,
40
+ requestFormat,
41
+ } from "./workflows/downsample.ts";
42
+ import {
43
+ audioTrack,
44
+ cuttable,
45
+ encodeTargets,
46
+ heavierThanNormalized,
47
+ normalizeRecording,
48
+ requireWholeRecording,
49
+ } from "./workflows/normalize.ts";
50
+ import { stitchChunks, stitchTranscript, TRANSCRIPT_STREAM } from "./workflows/stitch.ts";
51
+ import {
52
+ expectedSegments,
53
+ nextPollDelay,
54
+ planStreamed,
55
+ probeUpload,
56
+ type StreamPlan,
57
+ segmentStored,
58
+ storedBytes,
59
+ type UploadProgressView,
60
+ } from "./workflows/stream.ts";
61
+ import {
62
+ mergeTranscript,
63
+ splitRecording,
64
+ type Transcript,
65
+ transcribeFlow,
66
+ transcribeSegment,
67
+ } from "./workflows/transcribe.ts";
68
+ import {
69
+ assertCuttable,
70
+ blockAlign,
71
+ bytesPerSecond,
72
+ MAX_BYTES_PER_SECOND,
73
+ MAX_SEGMENT_BYTES,
74
+ MAX_SEGMENT_SECONDS,
75
+ parseWav,
76
+ planSegments,
77
+ SEGMENT_SECONDS,
78
+ UnsupportedRecordingError,
79
+ type WavFormat,
80
+ } from "./workflows/wav.ts";
81
+
82
+ /** The id every spec below uploads under. */
83
+ const UPLOAD_ID = "upl_test";
84
+
85
+ /**
86
+ * A fixed run-start epoch, so `elapsedMs` is assertable at all.
87
+ *
88
+ * The body reads it with `ctx.now()`, which the engine journals; a spec supplies
89
+ * the value directly, which is the point of threading it as an argument rather
90
+ * than reading a clock inside the merge — the duration is then a function of
91
+ * journaled values and not of how long the test took.
92
+ */
93
+ const STARTED_AT = 1_000_000;
94
+
95
+ /**
96
+ * Publish one in-memory upload, the way `createServerForRuntime` publishes a real store.
97
+ *
98
+ * This is the seam that makes a step testable at all: `stepReadUpload` reads a
99
+ * process-wide slot rather than dialling anything, so a spec supplies its own
100
+ * bytes with no server, no database and no HTTP.
101
+ */
102
+ function publishRecording(bytes: Uint8Array, name = "standup.wav") {
103
+ // `installStubUploads` rather than `stubUploads`: the fake registers its own
104
+ // `onTestFinished`, which is what replaced the three hand-kept restore
105
+ // registries this file used to carry.
106
+ installStubUploads({ [UPLOAD_ID]: { bytes, name, type: "audio/wav" } });
107
+ }
108
+
109
+ /** 16 kHz mono 16-bit — one second of audio is 32,000 bytes. */
110
+ const MONO_16K = { sampleRate: 16_000, channels: 1, bitsPerSample: 16 } as const;
111
+
112
+ /**
113
+ * A canonical WAV header in front of `dataBytes` of (absent) samples.
114
+ *
115
+ * `WAV_HEADER_BYTES` (`@alexkroman1/aai/step`) is the length rather than a `44`
116
+ * typed here, because it is the same 44 the SDK's own `wavHeader` writes and
117
+ * `transcribeSegment` sends — this fixture and the code under test would
118
+ * otherwise agree by coincidence.
119
+ */
120
+ function wavFile(
121
+ fmt: { sampleRate: number; channels: number; bitsPerSample: number },
122
+ dataBytes: number,
123
+ overrides: { declaredDataSize?: number; extraChunk?: string } = {},
124
+ ): Uint8Array {
125
+ const extra = overrides.extraChunk;
126
+ const extraLength = extra === undefined ? 0 : 8 + extra.length + (extra.length % 2);
127
+ const head = new Uint8Array(WAV_HEADER_BYTES + extraLength);
128
+ const view = new DataView(head.buffer);
129
+ const write = (at: number, text: string) => {
130
+ for (let i = 0; i < text.length; i++) view.setUint8(at + i, text.charCodeAt(i));
131
+ };
132
+
133
+ write(0, "RIFF");
134
+ view.setUint32(4, 36 + extraLength + dataBytes, true);
135
+ write(8, "WAVEfmt ");
136
+ view.setUint32(16, 16, true);
137
+ view.setUint16(20, 1, true);
138
+ view.setUint16(22, fmt.channels, true);
139
+ view.setUint32(24, fmt.sampleRate, true);
140
+ view.setUint32(28, (fmt.channels * fmt.bitsPerSample * fmt.sampleRate) / 8, true);
141
+ view.setUint16(32, (fmt.channels * fmt.bitsPerSample) / 8, true);
142
+ view.setUint16(34, fmt.bitsPerSample, true);
143
+
144
+ // An odd-length chunk before `data`, which is what the walk's padding rule is
145
+ // for — a recorder's `LIST`/`bext` block sits exactly here.
146
+ let at = 36;
147
+ if (extra !== undefined) {
148
+ write(at, "LIST");
149
+ view.setUint32(at + 4, extra.length, true);
150
+ write(at + 8, extra);
151
+ at += extraLength;
152
+ }
153
+ write(at, "data");
154
+ view.setUint32(at + 4, overrides.declaredDataSize ?? dataBytes, true);
155
+ return head;
156
+ }
157
+
158
+ describe("the agent declares its three workflows", () => {
159
+ test("under the names the REST route resolves them by", () => {
160
+ // The page starts a run by these strings, so a rename is a runtime 400 rather
161
+ // than a compile error — which is what makes pinning them worth a test.
162
+ // `arrayContaining` rather than an exact key list: a fourth desk of your own
163
+ // is an invited edit and must not redden a test you did not write. These
164
+ // three NAMES stay pinned, deliberately — the page starts a run by each
165
+ // string, so renaming one is a runtime 400 rather than a compile error, and
166
+ // this is the only thing that says so. Rename here and in `client.tsx`
167
+ // together.
168
+ expect(Object.keys(agentDef.workflows ?? {})).toEqual(
169
+ expect.arrayContaining(["transcribe", "transcribeStream", "transcribeBatch"]),
170
+ );
171
+ expect(agentDef.workflows?.transcribe).toBe(transcribe);
172
+ expect(agentDef.workflows?.transcribeStream).toBe(transcribeStream);
173
+ expect(agentDef.workflows?.transcribeBatch).toBe(transcribeBatch);
174
+ });
175
+
176
+ test("all three take `recording` as an UPLOAD, which is what makes one picker serve them", () => {
177
+ // There is no second kind of declaration: `recording` carries an upload id in
178
+ // every flow, and the streaming one differs only in that the CLIENT chose the id
179
+ // and PUT the file to it. A divergence here would mean the form had to ask a
180
+ // person how the bytes should travel.
181
+ for (const wf of [transcribe, transcribeStream, transcribeBatch]) {
182
+ expect(wf.uploads).toEqual(["recording"]);
183
+ }
184
+ });
185
+
186
+ test("with no tools, because the interface is the page and the API", () => {
187
+ // A PIN, deliberately, and the one assertion in this file you are expected
188
+ // to edit rather than satisfy. `workflowApp()` declares no session, so a
189
+ // tool has no conversation to be called from — a name appearing here means
190
+ // the voice path crept back in and the tool will never run. If you want a
191
+ // voice agent that STARTS a workflow, `research-handoff-agent` is that template,
192
+ // and this line is what tells you you are on the wrong one.
193
+ expect(Object.keys(agentDef.tools ?? {})).toEqual([]);
194
+ });
195
+
196
+ test("declaring the key its steps read, so a deploy checks for it", () => {
197
+ // Without this a missing credential is discovered by the first run, minutes
198
+ // after the deploy reported success.
199
+ expect(agentDef.requiredEnv).toContain("ASSEMBLYAI_API_KEY");
200
+ });
201
+ });
202
+
203
+ describe("the input schema", () => {
204
+ test("accepts what the page's form collects, with no mapping in between", async () => {
205
+ const result = await transcribe.input?.["~standard"].validate({
206
+ recording: "upl_9f3c1d",
207
+ });
208
+ expect(result?.issues).toBeUndefined();
209
+ });
210
+
211
+ test("takes the recording alone — there is nothing else to ask for", async () => {
212
+ const result = await transcribe.input?.["~standard"].validate({
213
+ recording: "upl_9f3c1d",
214
+ });
215
+ // Re-tested rather than trusted: a Standard Schema result is a union, so
216
+ // this is what makes `value` reachable without a cast.
217
+ expect(result?.issues).toBeUndefined();
218
+ if (result?.issues) expect.fail("expected the submission to validate");
219
+ expect(result?.value).toMatchObject({ recording: "upl_9f3c1d" });
220
+ });
221
+
222
+ test("rejects a submission with no recording at the call site rather than in a step", async () => {
223
+ // A 400 on the POST, with the run never created, instead of a failed run
224
+ // discovered a minute later.
225
+ const result = await transcribe.input?.["~standard"].validate({});
226
+ expect(result?.issues).toBeDefined();
227
+ });
228
+
229
+ test("declares the recording as an upload, which is what makes the form take a file", () => {
230
+ // Without this the page renders a text box asking for an id no person has —
231
+ // the property is a plain string in the schema, deliberately, because an
232
+ // upload id is what the run receives.
233
+ expect(transcribe.uploads).toEqual(["recording"]);
234
+ });
235
+
236
+ test("describes the recording, which is what labels it on the page", async () => {
237
+ // `<WorkflowFields>` renders a control per scalar property and uses each
238
+ // `.describe()` as its hint, so a missing description is a bare field.
239
+ // Narrowed rather than cast: `input` is a Standard Schema, and only a
240
+ // `ZodObject` has the `shape` this reads.
241
+ const schema = transcribe.input;
242
+ if (!(schema instanceof z.ZodObject)) expect.fail("expected a zod object schema");
243
+ expect(schema.shape.recording?.description).toBeTruthy();
244
+ });
245
+ });
246
+
247
+ describe("parseWav", () => {
248
+ test("reads the format and where the samples start", () => {
249
+ const head = wavFile(MONO_16K, 320_000);
250
+ expect(parseWav(head, 44 + 320_000)).toEqual({
251
+ ...MONO_16K,
252
+ dataStart: 44,
253
+ dataEnd: 44 + 320_000,
254
+ });
255
+ });
256
+
257
+ test("walks past a chunk in front of the samples, padding included", () => {
258
+ // A `LIST` of odd length: the padding byte is not counted by the chunk's
259
+ // own length field, which is the off-by-one that lands `dataStart` inside
260
+ // the audio and makes every segment one byte out of frame.
261
+ const head = wavFile(MONO_16K, 320_000, { extraChunk: "INFOxyz" });
262
+ expect(parseWav(head, head.length + 320_000).dataStart).toBe(head.length);
263
+ });
264
+
265
+ test("caps a declared length at what was actually served", () => {
266
+ // A truncated download declares more than it holds; reading past the end
267
+ // would make the last segment a range the server answers 416 for.
268
+ const head = wavFile(MONO_16K, 320_000);
269
+ expect(parseWav(head, 44 + 100_000).dataEnd).toBe(44 + 100_000);
270
+ });
271
+
272
+ test("treats an unknown declared length as 'to the end of the file'", () => {
273
+ // What a streaming encoder writes — the length was not known when the
274
+ // header went out.
275
+ const head = wavFile(MONO_16K, 320_000, { declaredDataSize: 0xff_ff_ff_ff });
276
+ expect(parseWav(head, 44 + 320_000).dataEnd).toBe(44 + 320_000);
277
+ });
278
+
279
+ test("refuses a file that is not a WAV, naming the fix", () => {
280
+ const notWav = new Uint8Array(64).fill(0x66);
281
+ expect(() => parseWav(notWav, 64)).toThrow(UnsupportedRecordingError);
282
+ expect(() => parseWav(notWav, 64)).toThrow(/ffmpeg/);
283
+ });
284
+
285
+ test("refuses a WAV that is not linear PCM", () => {
286
+ // Cutting a compressed payload by arithmetic produces noise, and noise
287
+ // transcribes into confident nonsense rather than failing.
288
+ const head = wavFile(MONO_16K, 320_000);
289
+ new DataView(head.buffer).setUint16(20, 0xff_fe, true);
290
+ expect(() => parseWav(head, 44 + 320_000)).toThrow(/linear PCM/);
291
+ });
292
+
293
+ // The two rates below are why the guard is in `parseWav` and not in
294
+ // `planSegments`: both make that loop spin on pure CPU with no `await` in it,
295
+ // so neither `AbortSignal.timeout` nor a step's retry budget can interrupt
296
+ // one — and this is the workflow app that takes an arbitrary uploaded file
297
+ // over a public form.
298
+
299
+ test("refuses a WAV declaring a sample rate of 0, which would hang the cut", () => {
300
+ // `bytesPerSecond` is 0, so `stride` is 0, so `start += stride` never
301
+ // advances and the loop pushes a Segment per iteration until it runs out of
302
+ // memory.
303
+ const head = wavFile({ ...MONO_16K, sampleRate: 0 }, 320_000);
304
+ expect(() => parseWav(head, 44 + 320_000)).toThrow(UnsupportedRecordingError);
305
+ expect(() => parseWav(head, 44 + 320_000)).toThrow(/sample rate of 0/);
306
+ });
307
+
308
+ test("assertCuttable refuses a rate so high the overlap alone exceeds the cap", () => {
309
+ // The same hang from the other end: the overlap is subtracted from
310
+ // MAX_SEGMENT_BYTES, so past MAX_BYTES_PER_SECOND the stride goes NEGATIVE
311
+ // and the loop walks backwards. `sampleRate` is a uint32, so a header can
312
+ // ask for this.
313
+ //
314
+ // The check is `assertCuttable`'s rather than `parseWav`'s now: the parse
315
+ // is the SDK's and answers whether this is READABLE WAV, where the cap is a
316
+ // property of the sync ENDPOINT this desk calls. Splitting them is what
317
+ // lets `cuttable` and `heavierThanNormalized` ask the two questions apart —
318
+ // a file that fails only the second is one downsampling repairs.
319
+ const perSecond = MAX_BYTES_PER_SECOND + blockAlign(MONO_16K);
320
+ const head = wavFile(
321
+ { ...MONO_16K, sampleRate: Math.ceil(perSecond / blockAlign(MONO_16K)) },
322
+ 320_000,
323
+ );
324
+ expect(() => parseWav(head, 44 + 320_000)).not.toThrow();
325
+ expect(() => assertCuttable(parseWav(head, 44 + 320_000))).toThrow(/bytes a second/);
326
+ });
327
+
328
+ test("48 kHz 24-bit stereo — the realistic ceiling — is nowhere near the bound", () => {
329
+ // The guard has to refuse the pathological headers without refusing any
330
+ // recording a person would actually upload.
331
+ const studio = { sampleRate: 48_000, channels: 2, bitsPerSample: 24 };
332
+ expect(bytesPerSecond(studio)).toBeLessThan(MAX_BYTES_PER_SECOND);
333
+ const head = wavFile(studio, 4_000_000);
334
+ expect(parseWav(head, 44 + 4_000_000).sampleRate).toBe(48_000);
335
+ });
336
+ });
337
+
338
+ describe("planSegments decides the fan-out's width", () => {
339
+ /** A format covering `seconds` of 16 kHz mono audio. */
340
+ function format(seconds: number): WavFormat {
341
+ const bytes = seconds * MONO_16K.sampleRate * blockAlign(MONO_16K);
342
+ return { ...MONO_16K, dataStart: 44, dataEnd: 44 + bytes };
343
+ }
344
+
345
+ test("covers the whole recording", () => {
346
+ const segments = planSegments(format(600));
347
+ expect(segments[0]?.start).toBe(44);
348
+ expect(segments.at(-1)?.end).toBe(format(600).dataEnd);
349
+ });
350
+
351
+ test("keeps every segment inside the endpoint's limit", () => {
352
+ // The cap the whole template exists to work around — one segment over it is
353
+ // a 413 rather than a shorter transcript.
354
+ for (const segment of planSegments(format(3600))) {
355
+ expect(segment.endMs - segment.startMs).toBeLessThanOrEqual(MAX_SEGMENT_SECONDS * 1000);
356
+ }
357
+ });
358
+
359
+ test("overlaps each segment with the one before it", () => {
360
+ // The overlap is what stops a cut mid-word being heard as half a word by
361
+ // both sides; `stitchTranscript` removes the duplicate.
362
+ const segments = planSegments(format(600));
363
+ expect(segments.length).toBeGreaterThan(1);
364
+ for (const [at, segment] of segments.entries()) {
365
+ if (at === 0) continue;
366
+ expect(segment.startMs).toBeLessThan(segments[at - 1]?.endMs ?? 0);
367
+ }
368
+ });
369
+
370
+ test("cuts only on frame boundaries", () => {
371
+ // A cut mid-sample shifts every following byte into the wrong channel and
372
+ // the wrong half of a 16-bit word — audible as noise, never as an error.
373
+ const stereo = { sampleRate: 44_100, channels: 2, bitsPerSample: 16 };
374
+ const frame = blockAlign(stereo);
375
+ const segments = planSegments({
376
+ ...stereo,
377
+ dataStart: 44,
378
+ dataEnd: 44 + 600 * stereo.sampleRate * frame,
379
+ });
380
+ for (const segment of segments) {
381
+ expect((segment.start - 44) % frame).toBe(0);
382
+ expect((segment.end - 44) % frame).toBe(0);
383
+ }
384
+ });
385
+
386
+ test("keeps every segment inside the endpoint's byte cap too", () => {
387
+ // The cap that binds on high-rate audio rather than long audio: 96 kHz
388
+ // stereo 24-bit reaches 40 MB in ~73 seconds, well inside the 120-second
389
+ // one. The overlap counts toward it, which is why the stride subtracts it.
390
+ const hiFi = { sampleRate: 96_000, channels: 2, bitsPerSample: 24 };
391
+ const perSecond = hiFi.sampleRate * blockAlign(hiFi);
392
+ const segments = planSegments({
393
+ ...hiFi,
394
+ dataStart: 44,
395
+ dataEnd: 44 + 600 * perSecond,
396
+ });
397
+ expect(segments.length).toBeGreaterThan(1);
398
+ for (const segment of segments) {
399
+ expect(segment.end - segment.start).toBeLessThanOrEqual(MAX_SEGMENT_BYTES);
400
+ }
401
+ });
402
+
403
+ test("emits one segment for a recording shorter than the stride", () => {
404
+ expect(planSegments(format(SEGMENT_SECONDS - 1))).toHaveLength(1);
405
+ });
406
+
407
+ test("emits no trailing empty segment when the audio divides evenly", () => {
408
+ // The case a loop with the wrong bound fans one extra step out over
409
+ // nothing, which the endpoint answers 400 for.
410
+ const segments = planSegments(format(SEGMENT_SECONDS * 3));
411
+ expect(segments.at(-1)?.end).toBeGreaterThan(segments.at(-1)?.start ?? 0);
412
+ expect(segments).toHaveLength(3);
413
+ });
414
+
415
+ test("refuses a recording shorter than the endpoint's floor", () => {
416
+ expect(() => planSegments(format(0.01))).toThrow(UnsupportedRecordingError);
417
+ });
418
+ });
419
+
420
+ describe("stitchTranscript", () => {
421
+ test("removes the words the overlap made duplicates", () => {
422
+ expect(
423
+ stitchTranscript(["we should ship it on Friday", "ship it on Friday if the tests pass"]),
424
+ ).toBe("we should ship it on Friday if the tests pass");
425
+ });
426
+
427
+ test("matches a seam the two passes punctuated differently", () => {
428
+ // The common case, not an edge one: one segment ends a sentence where the
429
+ // other is mid-clause, so a raw compare finds no seam at all.
430
+ expect(stitchTranscript(["that is all for today.", "Today we ship."])).toBe(
431
+ "that is all for today. we ship.",
432
+ );
433
+ });
434
+
435
+ test("keeps both sides when there is no seam", () => {
436
+ expect(stitchTranscript(["alpha beta", "gamma delta"])).toBe("alpha beta gamma delta");
437
+ });
438
+
439
+ test("prefers the longest seam over an accidental short one", () => {
440
+ // A repeated "the" is not evidence of anything; taking it would delete
441
+ // speech, which is the one failure worse than a repeated phrase.
442
+ expect(stitchTranscript(["the plan is the same", "the same next week"])).toBe(
443
+ "the plan is the same next week",
444
+ );
445
+ });
446
+
447
+ test("skips a segment that transcribed to nothing", () => {
448
+ // A segment of silence, which a long recording legitimately contains.
449
+ expect(stitchTranscript(["alpha", " ", "beta"])).toBe("alpha beta");
450
+ });
451
+ });
452
+
453
+ describe("stitchChunks — what the PAGE renders while a run is going", () => {
454
+ const chunk = (index: number, text: string) => ({
455
+ index,
456
+ startMs: index * 1000,
457
+ endMs: (index + 1) * 1000,
458
+ text,
459
+ });
460
+
461
+ test("orders by index, because chunks arrive as the segments settle", () => {
462
+ // The one thing a live reader definitely does not have is arrival order: the
463
+ // segments are transcribed concurrently, so chunk 2 routinely precedes 1.
464
+ expect(stitchChunks([chunk(2, "gamma"), chunk(0, "alpha"), chunk(1, "beta")])).toBe(
465
+ "alpha beta gamma",
466
+ );
467
+ });
468
+
469
+ test("stitches the seams the same way the finished run does", () => {
470
+ // The whole reason the page imports the run's own function: a live
471
+ // transcript that de-duplicated differently would read as the model having
472
+ // changed its mind between the last poll and the result.
473
+ const parts = ["we should ship it on Friday", "ship it on Friday if the tests pass"];
474
+ expect(stitchChunks(parts.map((text, index) => chunk(index, text)))).toBe(
475
+ stitchTranscript(parts),
476
+ );
477
+ });
478
+
479
+ test("keeps both pieces around a HOLE rather than seaming across it", () => {
480
+ // A partial list is the ordinary case here, and two pieces that were never
481
+ // adjacent share no overlap — so the live text reads with a jump in it until
482
+ // the missing segment lands, instead of quietly losing a sentence.
483
+ expect(stitchChunks([chunk(0, "alpha beta"), chunk(2, "epsilon zeta")])).toBe(
484
+ "alpha beta epsilon zeta",
485
+ );
486
+ });
487
+
488
+ test("does not mutate the caller's list, which is React state", () => {
489
+ const chunks = [chunk(1, "beta"), chunk(0, "alpha")];
490
+ stitchChunks(chunks);
491
+ expect(chunks.map((one) => one.index)).toEqual([1, 0]);
492
+ });
493
+
494
+ test("renders nothing out of nothing", () => {
495
+ expect(stitchChunks([])).toBe("");
496
+ });
497
+ });
498
+
499
+ describe("splitRecording", () => {
500
+ test("plans the segments and reports the duration", async () => {
501
+ const seconds = 200;
502
+ const bytes = seconds * MONO_16K.sampleRate * blockAlign(MONO_16K);
503
+ publishRecording(concat(wavFile(MONO_16K, bytes), new Uint8Array(bytes)));
504
+
505
+ const plan = await splitRecording(UPLOAD_ID);
506
+ expect(plan.format.sampleRate).toBe(MONO_16K.sampleRate);
507
+ expect(plan.segments.length).toBeGreaterThan(1);
508
+ expect(plan.durationMs).toBe(seconds * 1000);
509
+ });
510
+
511
+ test("reads a recording shorter than the header probe", async () => {
512
+ // The window is CLAMPED to the file rather than refused, which is what lets
513
+ // a step ask for 64 KB of a 12 KB recording without knowing its size first.
514
+ const bytes = 8000;
515
+ publishRecording(concat(wavFile(MONO_16K, bytes), new Uint8Array(bytes)));
516
+ const plan = await splitRecording(UPLOAD_ID);
517
+ expect(plan.format.dataStart).toBe(44);
518
+ });
519
+
520
+ test("fails FATALLY on an id that names no upload", async () => {
521
+ publishRecording(new Uint8Array(0));
522
+ // A missing upload does not appear on the fourth attempt.
523
+ await expect(splitRecording("upl_gone")).rejects.toThrow(/No upload with id/);
524
+ });
525
+
526
+ test("fails FATALLY on a recording it cannot cut", async () => {
527
+ // Compressed audio has no frame boundary an offset can find; the run says
528
+ // so by name instead of transcribing nonsense.
529
+ publishRecording(new Uint8Array([0x49, 0x44, 0x33, 0x04, 0, 0, 0, 0, 0, 0]));
530
+ await expect(splitRecording(UPLOAD_ID)).rejects.toThrow();
531
+ });
532
+ });
533
+
534
+ /**
535
+ * A sine, as interleaved little-endian 16-bit PCM with every channel identical.
536
+ *
537
+ * A TONE rather than noise or a ramp, because what a resampler can get wrong is
538
+ * frequency: decimating without a low-pass folds anything above the new Nyquist
539
+ * back into the speech band at full strength, and that is invisible to any
540
+ * assertion about lengths or formats.
541
+ */
542
+ function sineFrames(opts: {
543
+ hz: number;
544
+ sampleRate: number;
545
+ channels: number;
546
+ frames: number;
547
+ amplitude?: number;
548
+ }): Uint8Array {
549
+ const amplitude = opts.amplitude ?? 10_000;
550
+ const out = new Uint8Array(opts.frames * opts.channels * 2);
551
+ const view = new DataView(out.buffer);
552
+ for (let f = 0; f < opts.frames; f++) {
553
+ const value = Math.round(amplitude * Math.sin((2 * Math.PI * opts.hz * f) / opts.sampleRate));
554
+ for (let c = 0; c < opts.channels; c++) view.setInt16((f * opts.channels + c) * 2, value, true);
555
+ }
556
+ return out;
557
+ }
558
+
559
+ /** How loud 16-bit mono PCM is, in one number. */
560
+ function rms(bytes: Uint8Array): number {
561
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
562
+ let total = 0;
563
+ for (let at = 0; at < bytes.length; at += 2) total += view.getInt16(at, true) ** 2;
564
+ return Math.sqrt(total / (bytes.length / 2));
565
+ }
566
+
567
+ /** How FAST a tone is, without an FFT: a sine crosses zero twice per cycle. */
568
+ function zeroCrossings(bytes: Uint8Array): number {
569
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
570
+ let crossings = 0;
571
+ let previous = view.getInt16(0, true);
572
+ for (let at = 2; at < bytes.length; at += 2) {
573
+ const value = view.getInt16(at, true);
574
+ if (previous < 0 !== value < 0) crossings += 1;
575
+ previous = value;
576
+ }
577
+ return crossings;
578
+ }
579
+
580
+ describe("downsampleSegment — what actually goes on the wire", () => {
581
+ const STEREO_48K = { sampleRate: 48_000, channels: 2, bitsPerSample: 16 } as const;
582
+
583
+ test("passes already-normalized audio through UNTOUCHED, same array", () => {
584
+ // Identity rather than a copy, which is what the classic flow relies on:
585
+ // `normalizeRecording` has already converted the whole file, so this must cost
586
+ // nothing at all there — not a re-encode, not even an allocation.
587
+ const bytes = sineFrames({ hz: 440, sampleRate: 16_000, channels: 1, frames: 4000 });
588
+ const light = downsampleSegment(bytes, MONO_16K);
589
+
590
+ expect(light.bytes).toBe(bytes);
591
+ expect(light.format).toBe(MONO_16K);
592
+ });
593
+
594
+ test("cuts 48 kHz stereo to a SIXTH of the bytes, at 16 kHz mono", () => {
595
+ // The whole reason this exists: a 92-second segment is 17.66 MB at the source
596
+ // format and 2.94 MB here, against an endpoint that deadlines a request at 30
597
+ // seconds of wall clock INCLUDING the upload.
598
+ const bytes = sineFrames({ hz: 440, sampleRate: 48_000, channels: 2, frames: 48_000 });
599
+ const light = downsampleSegment(bytes, STEREO_48K);
600
+
601
+ expect(light.format).toEqual({ sampleRate: 16_000, channels: 1, bitsPerSample: 16 });
602
+ expect(light.bytes.length).toBe(32_000);
603
+ expect(light.bytes.length * 6).toBe(bytes.length);
604
+ });
605
+
606
+ test("the TONE survives — same pitch, same loudness", () => {
607
+ // The assertion the byte counts cannot make, and it is stated as an
608
+ // EQUIVALENCE rather than a constant: resampling a 440 Hz tone recorded at
609
+ // 48 kHz should give back what recording the same tone at 16 kHz would have
610
+ // given. 440 Hz is far below the new 8 kHz Nyquist, so the box filter costs
611
+ // it about 0.1%.
612
+ const bytes = sineFrames({ hz: 440, sampleRate: 48_000, channels: 2, frames: 12_000 });
613
+ const light = downsampleSegment(bytes, STEREO_48K);
614
+ const reference = sineFrames({ hz: 440, sampleRate: 16_000, channels: 1, frames: 4000 });
615
+
616
+ expect(zeroCrossings(light.bytes)).toBe(zeroCrossings(reference));
617
+ expect(rms(light.bytes)).toBeCloseTo(rms(reference), -2);
618
+ });
619
+
620
+ test("ATTENUATES a tone above the new Nyquist instead of folding it back", () => {
621
+ // The test that tells a box filter from plain decimation, and the reason the
622
+ // averaging is not a wasted pass. Taking every third sample of a 20 kHz tone
623
+ // at 48 kHz reproduces it at 4 kHz — in the middle of speech — at FULL
624
+ // amplitude. Averaging leaves about a quarter of it.
625
+ const bytes = sineFrames({ hz: 20_000, sampleRate: 48_000, channels: 2, frames: 12_000 });
626
+ const light = downsampleSegment(bytes, STEREO_48K);
627
+
628
+ const before = rms(bytes);
629
+ // Bounded on BOTH sides: an upper bound alone is satisfied by a resampler
630
+ // that returns silence, which would pass while destroying every transcript.
631
+ expect(rms(light.bytes)).toBeLessThan(before * 0.4);
632
+ expect(rms(light.bytes)).toBeGreaterThan(before * 0.1);
633
+ });
634
+
635
+ test("downmixes by AVERAGING the channels, not by dropping one", () => {
636
+ // A stereo call with one party per channel is exactly the file where dropping
637
+ // a channel loses a speaker outright. Left is +8000, right is -8000, so an
638
+ // average is silence and a dropped channel is a loud tone.
639
+ const bytes = new Uint8Array(4 * 2 * 2);
640
+ const view = new DataView(bytes.buffer);
641
+ for (let f = 0; f < 4; f++) {
642
+ view.setInt16(f * 4, 8000, true);
643
+ view.setInt16(f * 4 + 2, -8000, true);
644
+ }
645
+ const light = downsampleSegment(bytes, { sampleRate: 16_000, channels: 2, bitsPerSample: 16 });
646
+
647
+ expect(light.format).toEqual({ sampleRate: 16_000, channels: 1, bitsPerSample: 16 });
648
+ expect([...light.bytes]).toEqual([0, 0, 0, 0, 0, 0, 0, 0]);
649
+ });
650
+
651
+ test("never UPSAMPLES — 8 kHz stereo comes back at 8 kHz, mono", () => {
652
+ // The rate is a floor to come DOWN to, never a target to reach: resampling a
653
+ // narrowband recording up would invent bytes to pay the deadline with.
654
+ const bytes = sineFrames({ hz: 300, sampleRate: 8000, channels: 2, frames: 800 });
655
+ const light = downsampleSegment(bytes, { sampleRate: 8000, channels: 2, bitsPerSample: 16 });
656
+
657
+ expect(light.format).toEqual({ sampleRate: 8000, channels: 1, bitsPerSample: 16 });
658
+ expect(light.bytes.length).toBe(1600);
659
+ });
660
+
661
+ test("reads 8-bit samples as UNSIGNED, which is RIFF's one asymmetry", () => {
662
+ // Read as signed, a silent 8-bit recording (every byte 128) decodes as a
663
+ // constant -128 — full-scale DC, which transcribes as nothing but is the
664
+ // shape of the bug. 128 is silence; 255 is the positive peak.
665
+ const silent = downsampleSegment(new Uint8Array([128, 128, 128, 128]), {
666
+ sampleRate: 48_000,
667
+ channels: 2,
668
+ bitsPerSample: 8,
669
+ });
670
+ expect([...silent.bytes]).toEqual([0, 0]);
671
+
672
+ const loud = downsampleSegment(new Uint8Array([255, 255]), {
673
+ sampleRate: 16_000,
674
+ channels: 2,
675
+ bitsPerSample: 8,
676
+ });
677
+ expect(new DataView(loud.bytes.buffer).getInt16(0, true)).toBe(32_512);
678
+ });
679
+
680
+ test("sign-extends 24-bit samples", () => {
681
+ // The depth with no `DataView` accessor, so the sign extension is hand-written
682
+ // and is the one thing to get wrong: -1 is `ff ff ff`, which read unsigned is
683
+ // +8388607 rather than a whisker below zero.
684
+ const bytes = new Uint8Array([0xff, 0xff, 0xff, 0x00, 0x00, 0x40]);
685
+ const light = downsampleSegment(bytes, {
686
+ sampleRate: 16_000,
687
+ channels: 2,
688
+ bitsPerSample: 24,
689
+ });
690
+
691
+ // -1 and +4194304 on the 24-bit scale are -1/256 and +16384 on the 16-bit
692
+ // one; their average rounds to 8192.
693
+ expect(new DataView(light.bytes.buffer).getInt16(0, true)).toBe(8192);
694
+ });
695
+
696
+ test("REFUSES a bit depth it cannot read, terminally", () => {
697
+ // `parseWav` admits any multiple of 8, so this is reachable from a real file.
698
+ // Terminal because it answers the same way on every attempt — a retry would
699
+ // spend the step's whole budget arriving back here.
700
+ expect(() =>
701
+ downsampleSegment(new Uint8Array(16), {
702
+ sampleRate: 48_000,
703
+ channels: 2,
704
+ bitsPerSample: 64,
705
+ }),
706
+ ).toThrow(UnsupportedRecordingError);
707
+ });
708
+
709
+ test("REFUSES a depth it cannot read on the LIGHT path too, where nothing resamples", () => {
710
+ // The classification used to hang off the resampler, so it only ever ran when
711
+ // there was resampling to do — and a recording already at 16 kHz mono takes
712
+ // the identity path, where `requestFormat` hands its own argument back. Both
713
+ // depths below reach that path from a real file, `parseWav` admitting any
714
+ // multiple of 8, and each fails a different way once past here: 12 bits is a
715
+ // `RangeError` out of `encodeWav`, which is UNCLASSIFIED and therefore
716
+ // retried six times against a file that can never work, and 64 bits passes
717
+ // the header check and goes on the wire MISLABELLED — the worse of the two,
718
+ // because it comes back as a transcript rather than as an error.
719
+ for (const bitsPerSample of [12, 64]) {
720
+ expect(() => downsampleSegment(new Uint8Array(16), { ...MONO_16K, bitsPerSample })).toThrow(
721
+ UnsupportedRecordingError,
722
+ );
723
+ }
724
+ });
725
+
726
+ test("REFUSES a window with no whole frame rather than sending silence", () => {
727
+ // Reachable from the streaming flow, whose reads are CLAMPED to what has
728
+ // arrived: a segment whose window comes back short of one frame used to
729
+ // divide by a zero-wide averaging window, and `setInt16` turns the resulting
730
+ // `NaN` into a 0 — so the desk sent a two-byte WAV of silence and reported a
731
+ // transcript of it. A retry re-reads the same clamped window, so this is
732
+ // terminal like every other answer this module gives twice.
733
+ expect(() => downsampleSegment(new Uint8Array(2), STEREO_48K)).toThrow(
734
+ UnsupportedRecordingError,
735
+ );
736
+ // And on the light path, where there is no averaging to divide by zero and an
737
+ // empty request is just as useless.
738
+ expect(() => downsampleSegment(new Uint8Array(0), MONO_16K)).toThrow(UnsupportedRecordingError);
739
+ });
740
+
741
+ test("requestFormat is what the fan-out's WIDTH is priced from", () => {
742
+ // The two must not drift: `segmentConcurrency` divides a byte budget by a
743
+ // segment's cost, and that budget is bytes UPLOADING. Pricing the source
744
+ // format would make the width six times too cautious on exactly the
745
+ // recordings this change is for.
746
+ const sent = downsampleSegment(
747
+ sineFrames({ hz: 440, sampleRate: 48_000, channels: 2, frames: 48_000 }),
748
+ STEREO_48K,
749
+ );
750
+ expect(requestFormat(STEREO_48K)).toEqual(sent.format);
751
+ expect(requestFormat(MONO_16K)).toBe(MONO_16K);
752
+ expect(bytesPerSecond(requestFormat(STEREO_48K))).toBe(
753
+ NORMALIZED_SAMPLE_RATE * NORMALIZED_CHANNELS * 2,
754
+ );
755
+ });
756
+ });
757
+
758
+ describe("transcribeSegment", () => {
759
+ const FORMAT: WavFormat = { ...MONO_16K, dataStart: 44, dataEnd: 44 + 320_000 };
760
+ const SEGMENT = { index: 0, start: 44, end: 44 + 32_000, startMs: 0, endMs: 1000 };
761
+
762
+ beforeEach(() => {
763
+ // `stepEnv` falls back to the process env when no host has published one,
764
+ // which is exactly the case a spec is: there is no agent env in this
765
+ // process. `unstubEnvs` clears it before the next test.
766
+ vi.stubEnv("ASSEMBLYAI_API_KEY", "sk-test");
767
+ });
768
+
769
+ /**
770
+ * Publishes the recording and answers the sync endpoint.
771
+ *
772
+ * `installStubTranscribe` routes AssemblyAI's four legs off the SDK's own
773
+ * endpoint constants, so this file no longer re-types the wire — and it fills a
774
+ * published `stepFetch` rather than `vi.stubGlobal("fetch", …)`, because the
775
+ * step calls `stepFetch`, which reaches a published slot rather than the global
776
+ * (see `sdk/step-fetch.ts` for why it has to: HTTP/1.1, so a batch of segments
777
+ * gets a socket each instead of N streams on one connection). Stubbing the
778
+ * global still passes, because an unpublished slot falls back to it, and would
779
+ * be asserting against a path production does not take.
780
+ *
781
+ * A refusal is staged as a STATUS, which is what makes the classification specs
782
+ * below a test of the SDK's reading of it rather than of an error a fake minted.
783
+ */
784
+ function stubProvider(failure?: { status: number; message: string; retryAfterSeconds?: number }) {
785
+ publishRecording(new Uint8Array(FORMAT.dataEnd));
786
+ return installStubTranscribe({
787
+ text: "hello there",
788
+ failure: failure === undefined ? undefined : { leg: "sync", ...failure },
789
+ }).calls;
790
+ }
791
+
792
+ test("sends the segment as a WAV named after its index", async () => {
793
+ // What the SYNC endpoint's request looks like — the URL, the raw-key auth, the
794
+ // multipart envelope — is the SDK's contract and `sdk/step-transcribe*.test.ts`
795
+ // owns it. What is left here is this template's: it re-attaches a header to a
796
+ // window it read, and it names the part after the segment.
797
+ const calls = stubProvider();
798
+ const result = await transcribeSegment(UPLOAD_ID, FORMAT, SEGMENT);
799
+
800
+ expect(result).toEqual({ index: 0, text: "hello there" });
801
+ const sent = calls.find((call) => call.leg === "sync")?.body;
802
+ // Narrowed by a failing assertion rather than a cast: `expect.fail` returns
803
+ // `never`, and a body that is not bytes is a finding rather than a type error.
804
+ if (!(sent instanceof Uint8Array)) return expect.fail("the sync leg carries bytes");
805
+ const decoded = new TextDecoder().decode(sent);
806
+ expect(decoded).toContain('name="audio"; filename="segment-0.wav"');
807
+ // The WAV really rides in the part, header and all.
808
+ expect(decoded).toContain("RIFF");
809
+ // And the header is CONTIGUOUS with its samples, which is what the two-chunk
810
+ // form (`[wavHeader(…), window]`) has to preserve and the only thing it could
811
+ // plausibly lose: the part's payload is exactly the header plus the window,
812
+ // with nothing between them and nothing appended. A body that grew or shrank
813
+ // here is a file the endpoint decodes into confident nonsense rather than
814
+ // refusing.
815
+ const latin = new TextDecoder("latin1").decode(sent);
816
+ const from = latin.indexOf("RIFF");
817
+ const to = latin.lastIndexOf("\r\n--");
818
+ expect(to - from).toBe(WAV_HEADER_BYTES + (SEGMENT.end - SEGMENT.start));
819
+ });
820
+
821
+ test("sends the DOWNSAMPLED window when the recording is heavier than 16 kHz mono", async () => {
822
+ // The end-to-end half of `downsampleSegment`'s own specs: that the lighter
823
+ // bytes reach the WIRE, which is the only place the endpoint's 30-second
824
+ // budget is spent. One second of 48 kHz stereo is 192,000 bytes and leaves
825
+ // here as 32,000.
826
+ const stereo: WavFormat = {
827
+ sampleRate: 48_000,
828
+ channels: 2,
829
+ bitsPerSample: 16,
830
+ dataStart: 44,
831
+ dataEnd: 44 + 192_000,
832
+ };
833
+ publishRecording(new Uint8Array(stereo.dataEnd));
834
+ const calls = installStubTranscribe({ text: "hello there" }).calls;
835
+
836
+ await transcribeSegment(UPLOAD_ID, stereo, {
837
+ index: 0,
838
+ start: 44,
839
+ end: 44 + 192_000,
840
+ startMs: 0,
841
+ endMs: 1000,
842
+ });
843
+
844
+ const sent = calls.find((call) => call.leg === "sync")?.body;
845
+ if (!(sent instanceof Uint8Array)) return expect.fail("the sync leg carries bytes");
846
+ expect(sent.length).toBeLessThan(40_000);
847
+
848
+ // And the HEADER agrees with the samples under it. A body that shrank while
849
+ // still declaring 48 kHz stereo is the one failure a byte count cannot see,
850
+ // and it plays back at a third speed rather than failing.
851
+ const at = new TextDecoder("latin1").decode(sent).indexOf("RIFF");
852
+ const header = new DataView(sent.buffer, sent.byteOffset + at, WAV_HEADER_BYTES);
853
+ expect(header.getUint16(22, true)).toBe(1);
854
+ expect(header.getUint32(24, true)).toBe(16_000);
855
+ expect(header.getUint32(40, true)).toBe(32_000);
856
+ });
857
+
858
+ test("a depth it can CUT but not RESAMPLE fails the step FATALLY, not six times", async () => {
859
+ // `downsampleSegment`'s own spec asserts it throws; this asserts the
860
+ // CLASSIFICATION, which is the half that decides what the run does with it.
861
+ // `parseWav` admits any bit depth whose block align is positive, so a 48 kHz
862
+ // stereo 64-bit recording plans fine and only fails here — and it answers the
863
+ // same way on every attempt, so a plain throw would re-read this window out of
864
+ // the upload store six times to arrive back at the identical error. Only the
865
+ // STREAMING flow can get here: the classic one converts a heavy recording
866
+ // whole before any segment is cut.
867
+ const wide: WavFormat = {
868
+ sampleRate: 48_000,
869
+ channels: 2,
870
+ bitsPerSample: 64,
871
+ dataStart: 44,
872
+ dataEnd: 44 + 96_000,
873
+ };
874
+ publishRecording(new Uint8Array(wide.dataEnd));
875
+ installStubTranscribe({ text: "never reached" });
876
+
877
+ await expect(
878
+ transcribeSegment(UPLOAD_ID, wide, {
879
+ index: 0,
880
+ start: 44,
881
+ end: 44 + 96_000,
882
+ startMs: 0,
883
+ endMs: 1000,
884
+ }),
885
+ ).rejects.toBeInstanceOf(FatalError);
886
+ });
887
+
888
+ test("and fails fatally on the LIGHT path, which resamples nothing", async () => {
889
+ // The same classification one arm over, and the arm the case above cannot
890
+ // reach: a recording already at 16 kHz mono is passed through untouched, so
891
+ // nothing here ever asked what its samples were until it was too late to say
892
+ // so. 12 bits reached `encodeWav`, which refuses a depth that is not a
893
+ // multiple of 8 with a plain `RangeError` — retryable, so six attempts
894
+ // against a file no attempt can fix.
895
+ const narrow: WavFormat = {
896
+ sampleRate: 16_000,
897
+ channels: 1,
898
+ bitsPerSample: 12,
899
+ dataStart: 44,
900
+ dataEnd: 44 + 24_000,
901
+ };
902
+ publishRecording(new Uint8Array(narrow.dataEnd));
903
+ installStubTranscribe({ text: "never reached" });
904
+
905
+ await expect(
906
+ transcribeSegment(UPLOAD_ID, narrow, {
907
+ index: 0,
908
+ start: 44,
909
+ end: 44 + 24_000,
910
+ startMs: 0,
911
+ endMs: 1000,
912
+ }),
913
+ ).rejects.toBeInstanceOf(FatalError);
914
+ });
915
+
916
+ test("EMITS the segment's words as it lands, into the transcript stream", async () => {
917
+ // What makes the run's answer streamable rather than only its narration: the
918
+ // page stitches whatever has arrived, so the transcript renders growing
919
+ // instead of appearing when the last segment does. The reporter is the SDK's
920
+ // published slot, which is the same seam `stepReport()` goes through.
921
+ const reported = installStubReporter();
922
+ stubProvider();
923
+
924
+ await transcribeSegment(UPLOAD_ID, FORMAT, SEGMENT);
925
+
926
+ // The timestamps ride along for the READER — a partial transcript has holes
927
+ // in it, and "0:00–0:01" is what explains a jump.
928
+ expect(reported.emitted).toEqual([
929
+ {
930
+ namespace: TRANSCRIPT_STREAM,
931
+ chunk: { index: 0, startMs: 0, endMs: 1000, text: "hello there" },
932
+ },
933
+ ]);
934
+ // And the narration is still its own stream: lines a page prints verbatim
935
+ // cannot share a channel with objects.
936
+ expect(reported.lines.some((line) => line.startsWith("Transcribing"))).toBe(true);
937
+ });
938
+
939
+ test("fails FATALLY with no API key rather than retrying five times", async () => {
940
+ vi.stubEnv("ASSEMBLYAI_API_KEY", "");
941
+ stubProvider();
942
+ await expect(transcribeSegment(UPLOAD_ID, FORMAT, SEGMENT)).rejects.toThrow(
943
+ /ASSEMBLYAI_API_KEY/,
944
+ );
945
+ });
946
+
947
+ test("retries a rate limit, honouring the delay the endpoint asked for", async () => {
948
+ // `RetryableError` carrying `retryAfter` is the difference between draining
949
+ // the 429s and re-collecting them `SEGMENT_CONCURRENCY` at a time on a
950
+ // backoff the server did not choose.
951
+ stubProvider({ status: 429, message: "slow down", retryAfterSeconds: 30 });
952
+ const failure = await transcribeSegment(UPLOAD_ID, FORMAT, SEGMENT).catch(
953
+ (err: unknown) => err,
954
+ );
955
+ expect(failure).toBeInstanceOf(RetryableError);
956
+ expect(String(failure)).toMatch(/HTTP 429 — slow down/);
957
+ const at = (failure as RetryableError).retryAfter.getTime() - Date.now();
958
+ expect(at).toBeGreaterThan(25_000);
959
+ expect(at).toBeLessThanOrEqual(30_000);
960
+ });
961
+
962
+ test("retries a rate limit that named no delay, after the class's own second", async () => {
963
+ // The OTHER half of the pair above, and the half `sync-api.ts`'s doc claims
964
+ // ("a bare `RetryableError` retries in ONE SECOND — that class's own
965
+ // default") while nothing pinned it. `DEFAULT_RETRY_DELAY_MS`
966
+ // (`@alexkroman1/aai/step-errors`) is that second, read from the SDK rather
967
+ // than typed here: a class that quietly changed its default would otherwise
968
+ // leave the sentence in the template's doc false with every test green.
969
+ stubProvider({ status: 429, message: "slow down" });
970
+ const before = Date.now();
971
+ const failure = await transcribeSegment(UPLOAD_ID, FORMAT, SEGMENT).catch(
972
+ (err: unknown) => err,
973
+ );
974
+ expect(failure).toBeInstanceOf(RetryableError);
975
+ const at = (failure as RetryableError).retryAfter.getTime();
976
+ expect(at).toBeGreaterThanOrEqual(before + DEFAULT_RETRY_DELAY_MS);
977
+ // Generous on the far side: the only thing between the two clock reads is
978
+ // the throw, so anything past a second of slack would be a different bug.
979
+ expect(at).toBeLessThanOrEqual(Date.now() + DEFAULT_RETRY_DELAY_MS);
980
+ });
981
+
982
+ test("fails FATALLY on a rejected request, naming what the endpoint said", async () => {
983
+ stubProvider({ status: 400, message: "too short" });
984
+ await expect(transcribeSegment(UPLOAD_ID, FORMAT, SEGMENT)).rejects.toThrow(
985
+ /HTTP 400 — too short/,
986
+ );
987
+ });
988
+
989
+ test("is raised on both of the classic flow's I/O steps, and on nothing else", async () => {
990
+ // The policy is an argument to `ctx.step` now, so it is observable only at
991
+ // the CALL — which is exactly the kind of thing a property on the function
992
+ // could not have said differently, `transcribeSegment` being called from two
993
+ // flows. `runSteps: false` with a skeleton of results: no provider, no
994
+ // ffmpeg, no bytes.
995
+ //
996
+ // `transcribeStreamFlow`'s own `transcribeSegment` call carries the same
997
+ // budget and is asserted with that flow, not here — this drives only
998
+ // `transcribeFlow`.
999
+ const ctx = createWorkflowContext({
1000
+ runSteps: false,
1001
+ results: {
1002
+ normalizeRecording: { recording: UPLOAD_ID, converted: false },
1003
+ splitRecording: { format: FORMAT, segments: [SEGMENT], durationMs: 1000 },
1004
+ transcribeSegment: { index: 0, text: "hello" },
1005
+ // The real `Transcript` shape rather than `{ text }` — the body returns
1006
+ // this straight out as the run's output, so a fixture the system cannot
1007
+ // produce is the shape a reader copies.
1008
+ mergeTranscript: {
1009
+ source: "call.wav",
1010
+ segments: 1,
1011
+ durationMs: 1000,
1012
+ elapsedMs: 10,
1013
+ words: 1,
1014
+ transcript: "hello",
1015
+ } satisfies Transcript,
1016
+ },
1017
+ });
1018
+ await transcribeFlow({ recording: UPLOAD_ID }, ctx);
1019
+
1020
+ const segments = ctx.steps.filter((step) => step.name === "transcribeSegment");
1021
+ expect(segments.length).toBeGreaterThan(0);
1022
+ // The EXACT budget, not `toBeGreaterThan(3)`: the value is a literal at the
1023
+ // call site, so a typo'd `maxAttempts: 4` is what this should catch.
1024
+ for (const step of segments) expect(step.maxAttempts).toBe(6);
1025
+ // The OTHER raised step, whose assertion the migration dropped along with
1026
+ // the `normalizeRecording.maxRetries` property it used to read.
1027
+ const budgets = new Map(ctx.steps.map((step) => [step.name, step.maxAttempts]));
1028
+ expect(budgets.get("normalizeRecording")).toBe(6);
1029
+ // And the two that take the default, which is the other half of the claim.
1030
+ // Asserted as PRESENT-with-no-budget rather than as `get(…) === undefined`,
1031
+ // which a step the body never reached at all would also satisfy.
1032
+ for (const name of ["mergeTranscript", "splitRecording"]) {
1033
+ expect(budgets.has(name)).toBe(true);
1034
+ expect(budgets.get(name)).toBeUndefined();
1035
+ }
1036
+ });
1037
+ });
1038
+
1039
+ describe("mergeTranscript", () => {
1040
+ test("stitches the segments in index order, whatever order they arrive in", async () => {
1041
+ publishRecording(new Uint8Array(1));
1042
+ const merged = await mergeTranscript(
1043
+ UPLOAD_ID,
1044
+ 12_000,
1045
+ [
1046
+ { index: 1, text: "on Friday if the tests pass" },
1047
+ { index: 0, text: "we ship on Friday" },
1048
+ ],
1049
+ STARTED_AT,
1050
+ );
1051
+ expect(merged.transcript).toBe("we ship on Friday if the tests pass");
1052
+ expect(merged.words).toBe(8);
1053
+ expect(merged).toMatchObject({ segments: 2, durationMs: 12_000 });
1054
+ });
1055
+
1056
+ test("names the FILE it transcribed, not the id the run carried", async () => {
1057
+ publishRecording(new Uint8Array(1), "standup.wav");
1058
+ const merged = await mergeTranscript(UPLOAD_ID, 1000, [{ index: 0, text: "hi" }], STARTED_AT);
1059
+ expect(merged.source).toBe("standup.wav");
1060
+ });
1061
+ });
1062
+
1063
+ /** Two byte arrays end to end. */
1064
+ function concat(a: Uint8Array, b: Uint8Array): Uint8Array {
1065
+ const out = new Uint8Array(a.length + b.length);
1066
+ out.set(a);
1067
+ out.set(b, a.length);
1068
+ return out;
1069
+ }
1070
+
1071
+ /**
1072
+ * The STREAMING flow's own steps.
1073
+ *
1074
+ * Same honest line as the classic half above: the steps are driven directly and the
1075
+ * body is not, because a step is an ordinary exported async function. Almost
1076
+ * nothing here is new — the transcribing and the merging are
1077
+ * `transcribe.ts`'s own steps, called unchanged — so what is worth asserting is the
1078
+ * two things this flow adds: reading how far the upload has got, and planning from a
1079
+ * header while most of the file is still missing.
1080
+ */
1081
+ describe("the streaming flow", () => {
1082
+ const FORMAT: WavFormat = { ...MONO_16K, dataStart: 44, dataEnd: 44 + 320_000 };
1083
+
1084
+ /** Publish a partially-arrived upload: `stored` bytes of a `declared`-byte file. */
1085
+ function publishPartial(stored: number, declared: number, complete = false) {
1086
+ const bytes = new Uint8Array(44 + stored);
1087
+ bytes.set(wavFile(MONO_16K, declared), 0);
1088
+ installStubUploads({
1089
+ [UPLOAD_ID]: { bytes, name: "standup.wav", type: "audio/wav", complete },
1090
+ });
1091
+ }
1092
+
1093
+ test("probeUpload reports what has ARRIVED and whether that is all", async () => {
1094
+ publishPartial(1000, 320_000);
1095
+ // The poll the body runs. `complete` is separate from `size` because a size that
1096
+ // stopped growing is not a claim that the file is finished.
1097
+ // `stored` equals `size` here and only here: a whole-file upload's bytes ARE
1098
+ // its prefix, and the store publishes no windows for one.
1099
+ await expect(probeUpload(UPLOAD_ID)).resolves.toEqual({
1100
+ size: 44 + 1000,
1101
+ complete: false,
1102
+ stored: 44 + 1000,
1103
+ // A real clock, which is the point of it: `nextPollDelay` derives a rate from
1104
+ // two of these, so the step has to stamp when it looked rather than the body
1105
+ // guessing. Matched loosely because the VALUE is the wall clock.
1106
+ observedAt: expect.any(Number),
1107
+ });
1108
+ });
1109
+
1110
+ /**
1111
+ * A poll of a parts upload: `landed` windows of a `declared`-byte file.
1112
+ *
1113
+ * Built by hand rather than through `stubUploads`, which models an upload as one
1114
+ * contiguous buffer and so cannot express a HOLE — which is the entire state under
1115
+ * test. These two functions are pure over a poll's result, so a literal is the
1116
+ * whole fixture.
1117
+ */
1118
+ function poll(landed: readonly [number, number][], declared: number): UploadProgressView {
1119
+ const ranges = landed.map(([start, end]) => ({ start, end }));
1120
+ const prefix = ranges.find((range) => range.start === 0)?.end ?? 0;
1121
+ return {
1122
+ size: prefix,
1123
+ complete: prefix >= declared,
1124
+ stored: storedBytes(prefix, ranges),
1125
+ ranges,
1126
+ // Fixed rather than `Date.now()`: these fixtures feed pure functions, and a
1127
+ // real clock would make `nextPollDelay`'s arithmetic depend on how long the
1128
+ // suite took to get here.
1129
+ observedAt: 0,
1130
+ };
1131
+ }
1132
+
1133
+ test("segmentStored reads a landed window the PREFIX cannot see", () => {
1134
+ // The state the browser's default fan-out produces and the reason this flow
1135
+ // was a no-op against it: eight windows go up at once, share the uplink, and
1136
+ // finish together — so nothing starts at byte zero until the very end. Measured
1137
+ // on a deployed agent, a 27 MB recording at 0.9 MB/s reported `size: 0` at every
1138
+ // poll for 45 seconds and then the whole file.
1139
+ const at = poll([[8000, 24_000]], 32_000);
1140
+ expect(at.size).toBe(0);
1141
+ expect(segmentStored({ index: 1, start: 8000, end: 16_000, startMs: 0, endMs: 0 }, at)).toBe(
1142
+ true,
1143
+ );
1144
+ // And the prefix arm still answers on its own, which is what keeps a whole-file
1145
+ // upload (no windows at all) behaving exactly as it did.
1146
+ expect(segmentStored({ index: 0, start: 0, end: 4000, startMs: 0, endMs: 0 }, at)).toBe(false);
1147
+ });
1148
+
1149
+ test("segmentStored refuses a window that STRADDLES a hole", () => {
1150
+ // A run is contiguous, so containment in one is the whole test — and it has to
1151
+ // be, because `stepReadUpload` clamps to the run a read starts in. A segment
1152
+ // spanning two runs would come back short and be transcribed as a fragment,
1153
+ // which is a wrong transcript rather than a failed one.
1154
+ const at = poll(
1155
+ [
1156
+ [0, 8000],
1157
+ [16_000, 24_000],
1158
+ ],
1159
+ 32_000,
1160
+ );
1161
+ expect(segmentStored({ index: 1, start: 4000, end: 20_000, startMs: 0, endMs: 0 }, at)).toBe(
1162
+ false,
1163
+ );
1164
+ expect(segmentStored({ index: 2, start: 16_000, end: 24_000, startMs: 0, endMs: 0 }, at)).toBe(
1165
+ true,
1166
+ );
1167
+ });
1168
+
1169
+ test("storedBytes counts the WINDOWS, so a moving upload never reads as stalled", () => {
1170
+ // The other half of the fix. Judge a stall on the prefix and a parts upload
1171
+ // running at full speed reports the same number at every poll — so the run
1172
+ // abandons it after MAX_IDLE_POLLS with the bytes still arriving.
1173
+ const first = poll([[8000, 16_000]], 32_000);
1174
+ const later = poll(
1175
+ [
1176
+ [8000, 16_000],
1177
+ [24_000, 32_000],
1178
+ ],
1179
+ 32_000,
1180
+ );
1181
+ expect(first.size).toBe(later.size);
1182
+ expect(later.stored).toBeGreaterThan(first.stored);
1183
+ });
1184
+
1185
+ test("storedBytes does not double-count the prefix", () => {
1186
+ // `ranges` COVERS the prefix rather than sitting beside it, so summing the two
1187
+ // would report a growing total for an upload that had stopped.
1188
+ expect(storedBytes(8000, [{ start: 0, end: 8000 }])).toBe(8000);
1189
+ // And an upload with no windows at all is its prefix.
1190
+ expect(storedBytes(8000, undefined)).toBe(8000);
1191
+ });
1192
+
1193
+ test("probeUpload reports complete once it is", async () => {
1194
+ publishPartial(320_000, 320_000, true);
1195
+ await expect(probeUpload(UPLOAD_ID)).resolves.toMatchObject({ complete: true });
1196
+ });
1197
+
1198
+ test("planStreamed plans the WHOLE recording from a header that arrived alone", async () => {
1199
+ // The one real difference from `splitRecording`: only 1000 bytes of audio are
1200
+ // stored, and the plan still covers the 320,000 the header declares. Planning
1201
+ // from what has arrived would fan out over a fraction of the recording and report
1202
+ // success — which is the failure this argument exists to prevent.
1203
+ publishPartial(1000, 320_000);
1204
+ const plan = await planStreamed(UPLOAD_ID);
1205
+ expect(plan.format.dataEnd).toBe(44 + 320_000);
1206
+ expect(plan.segments.at(-1)?.end).toBe(44 + 320_000);
1207
+ expect(plan.segments.length).toBe(planSegments(FORMAT).length);
1208
+ });
1209
+
1210
+ test("planStreamed refuses a WAV that declares no length, naming the other flow", async () => {
1211
+ // `0` means "unknown", and there is nothing to compute a segment list from until
1212
+ // the file has finished — which is exactly what `transcribe` is for.
1213
+ const bytes = new Uint8Array(44 + 100);
1214
+ bytes.set(wavFile(MONO_16K, 100, { declaredDataSize: 0 }), 0);
1215
+ installStubUploads({ [UPLOAD_ID]: { bytes, complete: false } });
1216
+ await expect(planStreamed(UPLOAD_ID)).rejects.toThrow(/declares no data length/);
1217
+ });
1218
+
1219
+ test("planStreamed refuses a file that is not a WAV, terminally", async () => {
1220
+ installStubUploads({ [UPLOAD_ID]: { bytes: new Uint8Array(2000), complete: false } });
1221
+ // Fatal, not retryable: three more attempts read the same bytes.
1222
+ await expect(planStreamed(UPLOAD_ID)).rejects.toBeInstanceOf(FatalError);
1223
+ });
1224
+
1225
+ test("a segment reads SHORT rather than failing when its bytes have not landed", async () => {
1226
+ // The property the whole flow rests on, and it predates streaming: `stepReadUpload`
1227
+ // clamps its window to what is stored. So a body that asks slightly early gets
1228
+ // what exists — which is why the body checks `end <= size` and can trust the
1229
+ // clamp for the final segment of a file that came up short.
1230
+ publishPartial(1000, 320_000);
1231
+ const slice = await stepReadUpload(UPLOAD_ID, { start: 44, end: 44 + 320_000 });
1232
+ expect(slice.bytes.length).toBe(1000);
1233
+ expect(slice.end).toBe(44 + 1000);
1234
+ });
1235
+ });
1236
+
1237
+ /**
1238
+ * The ASYNC flow's steps.
1239
+ *
1240
+ * Driven against a stubbed `stepFetch`, like the sync flow's — and note what that
1241
+ * makes assertable: the three calls this flow makes are the whole of it, so the
1242
+ * assertions are about the CONTRACT with the provider (an id survives, a failed job
1243
+ * is terminal, the file is streamed rather than buffered) rather than about
1244
+ * arithmetic this flow does not do.
1245
+ */
1246
+ describe("the async flow", () => {
1247
+ beforeEach(() => {
1248
+ vi.stubEnv("ASSEMBLYAI_API_KEY", "sk-test");
1249
+ });
1250
+
1251
+ /**
1252
+ * Answer the async API, recording what was sent.
1253
+ *
1254
+ * `installStubTranscribe` routes the three legs off the SDK's own endpoint
1255
+ * constants — so a spec cannot pass because the fake and the step agree on a
1256
+ * typo — and it restores itself when the test ends.
1257
+ */
1258
+ function stubBatch(options: Parameters<typeof installStubTranscribe>[0] = {}) {
1259
+ return installStubTranscribe({ audioUrl: "https://cdn.example/abc", ...options }).calls;
1260
+ }
1261
+
1262
+ test("uploadToProvider streams the file and answers with the provider's URL", async () => {
1263
+ publishRecording(new Uint8Array(5000), "standup.wav");
1264
+ const calls = stubBatch();
1265
+ await expect(uploadToProvider(UPLOAD_ID)).resolves.toEqual({
1266
+ audioUrl: "https://cdn.example/abc",
1267
+ });
1268
+ expect(calls.map((one) => one.url)).toEqual(["https://api.assemblyai.com/v2/upload"]);
1269
+ });
1270
+
1271
+ test("the file is STREAMED, so a step never holds a whole recording", async () => {
1272
+ publishRecording(new Uint8Array(5000), "standup.wav");
1273
+ const calls = stubBatch();
1274
+ await uploadToProvider(UPLOAD_ID);
1275
+ // The fake drains a streaming body into bytes, so what this asserts is that
1276
+ // every byte went out — the streaming is what keeps a gigabyte off the heap, and
1277
+ // the bytes arriving intact is what says the windowing is right.
1278
+ const sent = calls[0]?.body;
1279
+ expect(sent).toBeInstanceOf(Uint8Array);
1280
+ expect(sent instanceof Uint8Array ? sent.length : -1).toBe(5000);
1281
+ });
1282
+
1283
+ test("the upload is a SEPARATE step, so a failed submit does not re-send the file", async () => {
1284
+ // Found by running it: as one step, a 400 on the create call retried the whole
1285
+ // thing five times and re-uploaded 24 MB on each attempt. The split is what makes
1286
+ // a retry of the cheap half cost the cheap half.
1287
+ publishRecording(new Uint8Array(5000));
1288
+ const calls = stubBatch({ failure: { leg: "submit", status: 400, message: "bad field" } });
1289
+ await expect(createJob("https://cdn.example/abc")).rejects.toBeInstanceOf(FatalError);
1290
+ // One call, and it is not the upload.
1291
+ expect(calls).toHaveLength(1);
1292
+ expect(calls[0]?.url).toBe("https://api.assemblyai.com/v2/transcript");
1293
+ });
1294
+
1295
+ test("createJob asks for `speech_models`, plural — the singular field is a 400", async () => {
1296
+ publishRecording(new Uint8Array(10));
1297
+ const calls = stubBatch({ jobIdPrefix: "tr_" });
1298
+ await expect(createJob("https://cdn.example/abc")).resolves.toEqual({ id: "tr_1" });
1299
+ const sent = JSON.parse(String(calls[0]?.body)) as Record<string, unknown>;
1300
+ // The async API deprecated `speech_model` and answers 400 for any current model
1301
+ // name passed to it — which is how the first live run of this flow failed. The
1302
+ // STREAMING API still uses the singular field, so neither is "the" spelling.
1303
+ expect(sent).toMatchObject({ speech_models: ["universal-3-5-pro"] });
1304
+ expect(sent.speech_model).toBeUndefined();
1305
+ });
1306
+
1307
+ test("a job the provider gave up on is TERMINAL, not polled forever", async () => {
1308
+ publishRecording(new Uint8Array(10));
1309
+ stubBatch({ jobError: "audio too quiet" });
1310
+ // The provider has decided; no number of polls changes it, so this must not come
1311
+ // back as "not done yet".
1312
+ await expect(pollTranscript(UPLOAD_ID, "tr_1", STARTED_AT)).rejects.toBeInstanceOf(FatalError);
1313
+ });
1314
+
1315
+ test("pollTranscript answers `done` on completed and not before", async () => {
1316
+ publishRecording(new Uint8Array(10));
1317
+ stubBatch({ pendingPolls: 1 });
1318
+ await expect(pollTranscript(UPLOAD_ID, "tr_1", STARTED_AT)).resolves.toEqual({ done: false });
1319
+ });
1320
+
1321
+ test("an unknown status is NOT done, so a new one cannot end a run early", async () => {
1322
+ publishRecording(new Uint8Array(10));
1323
+ // Raw rather than `stubTranscribe`: a body with no status at all is not a
1324
+ // shape the fake can stage, and it is the whole point of this spec.
1325
+ installStubStepFetch(() => ({ body: {} }));
1326
+ await expect(pollTranscript(UPLOAD_ID, "tr_1", STARTED_AT)).resolves.toMatchObject({
1327
+ done: false,
1328
+ });
1329
+ });
1330
+
1331
+ test("a completed poll carries the transcript — ONE request, not two", async () => {
1332
+ publishRecording(new Uint8Array(10), "standup.wav");
1333
+ // It used to poll for a status and then fetch the identical URL again for the
1334
+ // text the poll already had in its hand.
1335
+ const calls = stubBatch({ text: " hello there ", durationSec: 12.5 });
1336
+ await expect(pollTranscript(UPLOAD_ID, "tr_1", STARTED_AT)).resolves.toMatchObject({
1337
+ done: true,
1338
+ transcript: {
1339
+ source: "standup.wav",
1340
+ // Not a fudge: the async API transcribed the recording in one piece, which is
1341
+ // the difference this flow is here to show.
1342
+ segments: 1,
1343
+ durationMs: 12_500,
1344
+ words: 2,
1345
+ transcript: "hello there",
1346
+ },
1347
+ });
1348
+ expect(calls).toHaveLength(1);
1349
+ });
1350
+
1351
+ test("a rate limit is RETRYABLE, so a busy minute does not fail the run", async () => {
1352
+ publishRecording(new Uint8Array(10));
1353
+ stubBatch({ failure: { leg: "poll", status: 429, message: "slow down" } });
1354
+ await expect(pollTranscript(UPLOAD_ID, "tr_1", STARTED_AT)).rejects.toBeInstanceOf(
1355
+ RetryableError,
1356
+ );
1357
+ });
1358
+
1359
+ test("all three flows report the same SHAPE, which is what lets one page render any", async () => {
1360
+ publishRecording(new Uint8Array(10), "standup.wav");
1361
+ stubBatch({ text: "hi", durationSec: 1 });
1362
+ const progress = await pollTranscript(UPLOAD_ID, "tr_1", STARTED_AT);
1363
+ if (!progress.done) return expect.fail("the stub reports a completed job");
1364
+ const batched = progress.transcript;
1365
+ // One key set, so the page's summary line renders every flow's output. A field on
1366
+ // one flow and not the others is a panel that shows it for some runs and not
1367
+ // others, with nothing saying why.
1368
+ expect(Object.keys(batched).sort()).toEqual([
1369
+ "durationMs",
1370
+ "elapsedMs",
1371
+ "segments",
1372
+ "source",
1373
+ "transcript",
1374
+ "words",
1375
+ ]);
1376
+ // And the wall clock really is measured from what it was handed.
1377
+ expect(batched.elapsedMs).toBeGreaterThan(0);
1378
+ });
1379
+ });
1380
+
1381
+ describe("normalizing the recording", () => {
1382
+ /**
1383
+ * The CONVERSION is not driven here, and the reason is the tier rather than the
1384
+ * code: it spawns ffmpeg and writes a temp file, neither of which a unit test
1385
+ * may do. What is reachable is everything that DECIDES — whether a file needs
1386
+ * converting at all, and how a conversion's failure is classified — and those
1387
+ * are the two places a mistake is silent. A file wrongly passed through fails
1388
+ * later in `splitRecording` with a message about a header; a `timeout`
1389
+ * classified as fatal is a run that gives up on work that would have finished.
1390
+ */
1391
+ // Point the toolchain at nothing, so this block really is what its doc says:
1392
+ // a unit test that spawns no binary. Without it a developer with ffmpeg
1393
+ // installed runs a different test from CI, which has none — and the one
1394
+ // assertion below that reaches `normalizeRecording` is about a reporter line
1395
+ // emitted BEFORE the spawn. `unstubEnvs` is in the agent test preset, so
1396
+ // there is no teardown.
1397
+ beforeEach(() => {
1398
+ vi.stubEnv("AAI_FFMPEG_PATH", "/nonexistent/ffmpeg");
1399
+ vi.stubEnv("AAI_FFPROBE_PATH", "/nonexistent/ffprobe");
1400
+ });
1401
+
1402
+ test("a canonical WAV is cuttable, so the desk converts nothing", () => {
1403
+ expect(cuttable(wavFile(MONO_16K, 32_000), 44 + 32_000)).toBe(true);
1404
+ });
1405
+
1406
+ test("an extra chunk before the samples is still cuttable", () => {
1407
+ // The `LIST`-chunk case, which is the reason the probe window is 64 KB rather
1408
+ // than 44 bytes: a file the walk CAN read must not be re-encoded.
1409
+ const head = wavFile(MONO_16K, 32_000, { extraChunk: "recorder" });
1410
+ expect(cuttable(head, head.length + 32_000)).toBe(true);
1411
+ });
1412
+
1413
+ test("an m4a is not, which is what puts ffmpeg in the path", () => {
1414
+ // An MPEG-4 `ftyp` box — what a phone recording really starts with.
1415
+ const m4a = new Uint8Array([
1416
+ 0, 0, 0, 0x20, 0x66, 0x74, 0x79, 0x70, 0x4d, 0x34, 0x41, 0x20, 0, 0, 0, 0,
1417
+ ]);
1418
+ expect(cuttable(m4a, 4_000_000)).toBe(false);
1419
+ });
1420
+
1421
+ test("a WAV whose encoding is not linear PCM is not", () => {
1422
+ // The case an `ffprobe`-based check gets WRONG, which is why the check is
1423
+ // `parseWav` itself: this file reports a PCM codec to ffprobe and is refused
1424
+ // by the parser, so a probe would pass it through and the cut would fail.
1425
+ const extensible = wavFile(MONO_16K, 32_000);
1426
+ new DataView(extensible.buffer).setUint16(20, 0xff_fe, true);
1427
+ expect(cuttable(extensible, 44 + 32_000)).toBe(false);
1428
+ });
1429
+
1430
+ test("a WAV too dense to cut is not, and downsampling is what repairs it", () => {
1431
+ // Past `MAX_BYTES_PER_SECOND`, so `parseWav` refuses it — and a conversion to
1432
+ // 16 kHz mono makes it cuttable, which is a fix the desk gets for free from
1433
+ // asking the parser rather than asking about the codec.
1434
+ const dense = wavFile({ sampleRate: 4_000_000, channels: 8, bitsPerSample: 32 }, 32_000);
1435
+ expect(cuttable(dense, 44 + 32_000)).toBe(false);
1436
+ });
1437
+
1438
+ test("48 kHz stereo is cuttable and still too heavy to cut as it is", () => {
1439
+ // The file that broke a real run. It parses, it cuts, and every 92-second
1440
+ // segment of it is 17.7 MB against 2.94 MB normalized — six times the upload
1441
+ // per request, against a sync endpoint that deadlines at 30s. `cuttable`
1442
+ // cannot see that, which is the whole reason there are two predicates.
1443
+ const heavy = wavFile({ sampleRate: 48_000, channels: 2, bitsPerSample: 16 }, 32_000);
1444
+ expect(cuttable(heavy, 44 + 32_000)).toBe(true);
1445
+ expect(heavierThanNormalized(heavy, 44 + 32_000)).toBe(true);
1446
+ });
1447
+
1448
+ test.each([
1449
+ ["a higher rate alone", { sampleRate: 44_100, channels: 1, bitsPerSample: 16 }],
1450
+ ["more channels alone", { sampleRate: 16_000, channels: 2, bitsPerSample: 16 }],
1451
+ ])("%s is enough to convert", (_label, fmt) => {
1452
+ // Either axis on its own, because the segment cost is their PRODUCT — a file
1453
+ // that is only wide or only fast still costs a multiple of the target.
1454
+ expect(heavierThanNormalized(wavFile(fmt, 32_000), 44 + 32_000)).toBe(true);
1455
+ });
1456
+
1457
+ test("the normalize target itself is not heavier than itself", () => {
1458
+ // The predicate has to be false at the fixed point or the fast path is dead
1459
+ // and every recording pays an ffmpeg pass that produces its own input.
1460
+ const target = {
1461
+ sampleRate: NORMALIZED_SAMPLE_RATE,
1462
+ channels: NORMALIZED_CHANNELS,
1463
+ bitsPerSample: 16,
1464
+ };
1465
+ expect(heavierThanNormalized(wavFile(target, 32_000), 44 + 32_000)).toBe(false);
1466
+ });
1467
+
1468
+ test("a rate BELOW the target is left alone rather than upsampled", () => {
1469
+ // 8 kHz telephony audio. Converting it would invent no information and cost a
1470
+ // full pass over the recording, so the comparison is `>` and not `!==`.
1471
+ const narrow = wavFile({ sampleRate: 8000, channels: 1, bitsPerSample: 16 }, 32_000);
1472
+ expect(heavierThanNormalized(narrow, 44 + 32_000)).toBe(false);
1473
+ });
1474
+
1475
+ test("a heavy WAV is CONVERTED, and the line says why rather than lying", async () => {
1476
+ // The report used to read "not a WAV we can cut" on every conversion, which
1477
+ // for this file contradicts the thing the caller uploaded. The conversion
1478
+ // itself is out of tier (it spawns ffmpeg), so what is asserted is that the
1479
+ // fast path was declined and the reason given is the weight.
1480
+ publishRecording(
1481
+ wavFile({ sampleRate: 48_000, channels: 2, bitsPerSample: 16 }, 32_000),
1482
+ "workshop.wav",
1483
+ );
1484
+ const reporter = installStubReporter();
1485
+ await normalizeRecording(UPLOAD_ID).catch(() => undefined);
1486
+ const said = reporter.lines.join(" ");
1487
+ expect(said).not.toContain("already linear-PCM WAV");
1488
+ expect(said).toContain("heavier per second than 16 kHz mono");
1489
+ });
1490
+
1491
+ test("an already-cuttable recording keeps the id it came in under", async () => {
1492
+ // The property that matters: no second upload, so the fan-out reads the file
1493
+ // the caller stored. A step that copied it would double the storage every run
1494
+ // pays for and would still report success.
1495
+ publishRecording(wavFile(MONO_16K, 32_000), "standup.wav");
1496
+ const reporter = installStubReporter();
1497
+ await expect(normalizeRecording(UPLOAD_ID)).resolves.toEqual({
1498
+ recording: UPLOAD_ID,
1499
+ converted: false,
1500
+ });
1501
+ expect(reporter.lines.join(" ")).toContain("already linear-PCM WAV");
1502
+ });
1503
+
1504
+ test("a recording still arriving is refused, naming the flow that CAN take it", async () => {
1505
+ // `complete: false` is what an upload looks like while its bytes are on the
1506
+ // way, which is the state the STREAMING flow exists for and the one this
1507
+ // flow cannot serve: it cuts the whole file. `stepRequireCompleteUpload`
1508
+ // already refuses (its `UploadIncompleteError` carries `retryable = false`),
1509
+ // so what is asserted here is the desk's own SENTENCE — the mirror of
1510
+ // `planStreamed` refusing a length-less WAV and naming `transcribe`.
1511
+ installStubUploads({
1512
+ [UPLOAD_ID]: {
1513
+ bytes: wavFile(MONO_16K, 32_000),
1514
+ name: "standup.wav",
1515
+ type: "audio/wav",
1516
+ complete: false,
1517
+ },
1518
+ });
1519
+ const failure = await requireWholeRecording(UPLOAD_ID).catch((err: unknown) => err);
1520
+ // Fatal, not retryable: three more attempts find the same partial file, and
1521
+ // the remedy is a different workflow rather than a wait.
1522
+ expect(failure).toBeInstanceOf(FatalError);
1523
+ expect(String(failure)).toMatch(/still uploading/);
1524
+ expect(String(failure)).toMatch(/transcribeStream/);
1525
+ });
1526
+
1527
+ test("a complete recording passes through with its record intact", async () => {
1528
+ publishRecording(wavFile(MONO_16K, 32_000), "standup.wav");
1529
+ await expect(requireWholeRecording(UPLOAD_ID)).resolves.toMatchObject({
1530
+ id: UPLOAD_ID,
1531
+ name: "standup.wav",
1532
+ complete: true,
1533
+ });
1534
+ });
1535
+
1536
+ test("a failure that is not an incomplete upload is re-raised UNCHANGED", async () => {
1537
+ // The half a `catch` gets wrong: dressing every failure up as "still
1538
+ // uploading" would answer a missing id with advice about a flow that would
1539
+ // fail the same way.
1540
+ publishRecording(wavFile(MONO_16K, 32_000));
1541
+ await expect(requireWholeRecording("upl_gone")).rejects.toThrow(/No upload with id/);
1542
+ });
1543
+
1544
+ test("audioTrack refuses a file with no audio in it, terminally", () => {
1545
+ // A screen recording with the microphone off: real video, nothing to
1546
+ // transcribe. Without this the desk copies the whole file to disk and lets
1547
+ // ffmpeg refuse it, which is a true message about an argv rather than about
1548
+ // the file the person chose.
1549
+ const silent = { streams: [{ index: 0, kind: "video", codec: "h264" }], raw: null };
1550
+ expect(() => audioTrack(silent)).toThrow(FatalError);
1551
+ expect(() => audioTrack(silent)).toThrow(/no audio track/);
1552
+ });
1553
+
1554
+ test("audioTrack answers the stream ffmpeg will read", () => {
1555
+ const audio = { index: 1, kind: "audio", codec: "aac", sampleRate: 44_100, channels: 2 };
1556
+ expect(audioTrack({ streams: [{ index: 0, kind: "video" }, audio], audio, raw: null })).toBe(
1557
+ audio,
1558
+ );
1559
+ });
1560
+
1561
+ test("encodeTargets caps the rate at the normalize target", () => {
1562
+ expect(encodeTargets({ sampleRate: 48_000 })).toEqual({
1563
+ sampleRate: NORMALIZED_SAMPLE_RATE,
1564
+ channels: NORMALIZED_CHANNELS,
1565
+ });
1566
+ });
1567
+
1568
+ test("encodeTargets never UPSAMPLES — 8 kHz telephony is re-encoded at 8 kHz", () => {
1569
+ // The bug this function exists for: a fixed `sampleRate: 16000` doubled the
1570
+ // bytes of every request made from a phone recording, for information the
1571
+ // source does not contain, against an endpoint whose budget is wall clock.
1572
+ expect(encodeTargets({ sampleRate: 8000 }).sampleRate).toBe(8000);
1573
+ });
1574
+
1575
+ test("encodeTargets falls back to the ceiling when ffprobe named no rate", () => {
1576
+ expect(encodeTargets({}).sampleRate).toBe(NORMALIZED_SAMPLE_RATE);
1577
+ });
1578
+
1579
+ test("encodeTargets agrees with requestFormat, which prices the same audio", () => {
1580
+ // The two are one decision — what a request should be encoded at — asked of
1581
+ // a whole file here and of one segment there. They disagreed for exactly the
1582
+ // sub-16 kHz sources, which is the case a fan-out cannot see because the
1583
+ // conversion happens first.
1584
+ for (const sampleRate of [8000, 16_000, 44_100, 48_000]) {
1585
+ expect(encodeTargets({ sampleRate }).sampleRate).toBe(
1586
+ requestFormat({ sampleRate, channels: 1, bitsPerSample: 16 }).sampleRate,
1587
+ );
1588
+ }
1589
+ });
1590
+
1591
+ // The ffmpeg VERDICT is no longer tested here, and its absence is the change
1592
+ // rather than a gap: `throwFfmpegStepError` on `@alexkroman1/aai/step-errors`
1593
+ // owns it now, with every arm pinned in `sdk/step-errors.test.ts` — a refused
1594
+ // file, a missing binary, a timeout rethrown UNCHANGED so its `argv` survives,
1595
+ // and a cause that is not an ffmpeg failure at all. What stays above is what is
1596
+ // still this desk's: WHICH files it decides to convert.
1597
+ });
1598
+
1599
+ describe("expectedSegments", () => {
1600
+ /** A plan over 16 kHz mono, cut into three 90-second segments. */
1601
+ const PLAN = {
1602
+ format: { ...MONO_16K, dataStart: 44, dataEnd: 44 + 270 * 32_000 },
1603
+ segments: [0, 1, 2].map((index) => ({
1604
+ index,
1605
+ start: 44 + index * 90 * 32_000,
1606
+ end: 44 + (index + 1) * 90 * 32_000,
1607
+ startMs: index * 90_000,
1608
+ endMs: (index + 1) * 90_000,
1609
+ })),
1610
+ };
1611
+
1612
+ test("counts every segment once the whole recording has arrived", () => {
1613
+ expect(expectedSegments(PLAN, PLAN.format.dataEnd)).toBe(3);
1614
+ });
1615
+
1616
+ test("ignores segments that start past the end of a SHORT upload", () => {
1617
+ // The failure this guards is a run that never ENDS rather than one that fails:
1618
+ // the plan came from the header's declared length, so a recording that came up
1619
+ // short has segments beginning past the last byte, and waiting for them is
1620
+ // waiting for audio nobody is going to send.
1621
+ expect(expectedSegments(PLAN, 44 + 100 * 32_000)).toBe(2);
1622
+ expect(expectedSegments(PLAN, 44 + 1)).toBe(1);
1623
+ });
1624
+
1625
+ test("an upload with nothing in it expects no segments at all", () => {
1626
+ expect(expectedSegments(PLAN, 0)).toBe(0);
1627
+ });
1628
+ });
1629
+
1630
+ describe("the conversion, up to the spawn", () => {
1631
+ /**
1632
+ * Reaches the point where ffmpeg would run and stops there, DETERMINISTICALLY.
1633
+ *
1634
+ * `AAI_FFPROBE_PATH` names the binary the SDK resolves, so pointing it at a path
1635
+ * that does not exist produces `kind: "missing-binary"` on every machine — one
1636
+ * where ffmpeg is installed, one where it is not, and CI's Linux leg alike. A
1637
+ * test that instead relied on ffmpeg being ABSENT would pass on a laptop and
1638
+ * behave differently in CI.
1639
+ *
1640
+ * What it covers is the whole step up to the subprocess: reading the header,
1641
+ * deciding the file needs converting, and materializing it to a temp file. Plus
1642
+ * the behaviour a developer actually meets — `aai dev` with no ffmpeg is the one
1643
+ * place dev/prod parity is partial, and it must fail FATALLY with an installable
1644
+ * remedy rather than burn five attempts on a binary that will not appear.
1645
+ */
1646
+ test("materializes the recording, then fails fatally with no ffprobe", async () => {
1647
+ vi.stubEnv("AAI_FFPROBE_PATH", "/nonexistent/aai-test/ffprobe");
1648
+ vi.stubEnv("AAI_FFMPEG_PATH", "/nonexistent/aai-test/ffmpeg");
1649
+ // An m4a `ftyp` box, so `cuttable` says no and the conversion path is taken.
1650
+ publishRecording(
1651
+ new Uint8Array([0, 0, 0, 0x20, 0x66, 0x74, 0x79, 0x70, 0x4d, 0x34, 0x41, 0x20]),
1652
+ "standup.m4a",
1653
+ );
1654
+ const reporter = installStubReporter();
1655
+ // Fatal, not retryable: four more attempts find the same missing binary, and
1656
+ // the message already carries the install instructions.
1657
+ await expect(normalizeRecording(UPLOAD_ID)).rejects.toThrow(/ffprobe/);
1658
+ await expect(normalizeRecording(UPLOAD_ID)).rejects.toBeInstanceOf(FatalError);
1659
+ // It got as far as deciding the file needs converting — the failure is the
1660
+ // binary, not the input.
1661
+ expect(reporter.lines.join(" ")).toContain("standup.m4a");
1662
+ });
1663
+
1664
+ test("leaves no temp directory behind when the conversion fails", async () => {
1665
+ // The `finally`, on the path that matters: a guest's disk is small, and a step
1666
+ // that leaked a directory per failed run would fill it.
1667
+ vi.stubEnv("AAI_FFPROBE_PATH", "/nonexistent/aai-test/ffprobe");
1668
+ const leaked = (names: string[]) => names.filter((n) => n.startsWith("aai-normalize-"));
1669
+ const before = leaked(await readdir(tmpdir()));
1670
+ publishRecording(new Uint8Array([0, 0, 0, 0x20, 0x66, 0x74, 0x79, 0x70]), "standup.m4a");
1671
+ installStubReporter();
1672
+ await expect(normalizeRecording(UPLOAD_ID)).rejects.toBeInstanceOf(FatalError);
1673
+ expect(leaked(await readdir(tmpdir()))).toEqual(before);
1674
+ });
1675
+ });
1676
+
1677
+ /**
1678
+ * The adaptive poll delay.
1679
+ *
1680
+ * `POLL_INTERVAL_MS` used to be the only interval, and on a slow uplink that meant
1681
+ * discovering every segment on average half an interval late — once per segment,
1682
+ * for the whole upload. `nextPollDelay` sleeps until the next segment should have
1683
+ * landed instead. It is pure over two journaled polls, which is what makes it both
1684
+ * replay-safe and testable without a clock.
1685
+ */
1686
+ describe("nextPollDelay", () => {
1687
+ /**
1688
+ * A poll: `stored` bytes at `observedAt` ms, prefix and total agreeing.
1689
+ *
1690
+ * Which is the WHOLE-FILE upload — the two numbers only agree there. The parts
1691
+ * fan-out is `detached` below, and it is a separate helper rather than an
1692
+ * optional argument so a case that means them to diverge has to say so.
1693
+ */
1694
+ const view = (stored: number, observedAt: number): UploadProgressView => ({
1695
+ size: stored,
1696
+ complete: false,
1697
+ stored,
1698
+ observedAt,
1699
+ });
1700
+ /** A poll under the parts fan-out: `stored` bytes landed, `size` readable. */
1701
+ const detached = (stored: number, size: number, observedAt: number): UploadProgressView => ({
1702
+ size,
1703
+ complete: false,
1704
+ stored,
1705
+ observedAt,
1706
+ });
1707
+ /**
1708
+ * A plan whose segments end at the given byte offsets.
1709
+ *
1710
+ * Both halves are REAL values rather than casts: `nextPollDelay` only reads
1711
+ * `segments`, but a `{} as never` format would stop reporting the moment the
1712
+ * function grew a second reader — which is the whole argument against the
1713
+ * cast. 16 kHz mono is what `normalizeRecording` produces.
1714
+ */
1715
+ const planAt = (...ends: number[]): StreamPlan => ({
1716
+ format: {
1717
+ sampleRate: 16_000,
1718
+ channels: 1,
1719
+ bitsPerSample: 16,
1720
+ dataStart: 44,
1721
+ dataEnd: 44 + Math.max(0, ...ends),
1722
+ },
1723
+ segments: ends.map((end, index) => ({ index, start: 0, end, startMs: 0, endMs: 0 })),
1724
+ });
1725
+
1726
+ test("falls back to the ceiling with no previous sample to take a rate from", () => {
1727
+ // The first sleep of every run: one point is not a rate.
1728
+ expect(nextPollDelay(view(1000, 5000), undefined, planAt(50_000), new Set())).toBe(5000);
1729
+ });
1730
+
1731
+ test("falls back to the ceiling for a STALLED upload rather than guessing", () => {
1732
+ // Nothing arrived between the two samples, so there is no arrival to
1733
+ // extrapolate. MAX_IDLE_POLLS is what ends such a run; this only declines to
1734
+ // predict it, and must not divide by zero doing so.
1735
+ expect(nextPollDelay(view(1000, 2000), view(1000, 1000), planAt(50_000), new Set())).toBe(5000);
1736
+ });
1737
+
1738
+ test("waits the time the next segment still needs, at the observed rate", () => {
1739
+ // 10_000 bytes over 1000ms is 10 bytes/ms; the next segment needs 10_000 more.
1740
+ const delay = nextPollDelay(view(20_000, 2000), view(10_000, 1000), planAt(30_000), new Set());
1741
+ expect(delay).toBe(1000);
1742
+ });
1743
+
1744
+ test("targets the EARLIEST unfinished segment, not the furthest", () => {
1745
+ // Segments land as they arrive, so what the loop can act on next is the first
1746
+ // one it has not done — waiting for the last would sleep through the rest.
1747
+ const done = new Set([0]);
1748
+ const delay = nextPollDelay(
1749
+ view(10_000, 2000),
1750
+ view(0, 1000),
1751
+ planAt(5000, 20_000, 90_000),
1752
+ done,
1753
+ );
1754
+ // 10 bytes/ms, 10_000 more needed to reach segment 1's end at 20_000.
1755
+ expect(delay).toBe(1000);
1756
+ });
1757
+
1758
+ test("clamps to the ceiling so a collapsing rate degrades to the old behaviour", () => {
1759
+ // 1 byte/ms against 10 MB outstanding is hours; the ceiling is what stops this
1760
+ // becoming a stall no MAX_IDLE_POLLS can see.
1761
+ const delay = nextPollDelay(view(1000, 2000), view(0, 1000), planAt(10_000_000), new Set());
1762
+ expect(delay).toBe(5000);
1763
+ });
1764
+
1765
+ test("clamps to the floor rather than spinning when the bytes are already there", () => {
1766
+ // A remainder of zero, which the `Math.max` below the estimate answers with the
1767
+ // floor — there is no arm of its own for it, and the one that used to be there
1768
+ // was unreachable from the body anyway (a stored segment goes in `ready` and
1769
+ // the loop `continue`s past the sleep). What the floor is FOR is that the body
1770
+ // must not poll faster than the round trip its own sleep costs, which is why it
1771
+ // is 1000ms and not the 250ms that could not sleep at all.
1772
+ const delay = nextPollDelay(view(60_000, 2000), view(10_000, 1000), planAt(30_000), new Set());
1773
+ expect(delay).toBe(1000);
1774
+ });
1775
+
1776
+ test("waits for the HEADER window before there is a plan to aim at", () => {
1777
+ // No plan yet, so what is being waited for is the probe window itself.
1778
+ const delay = nextPollDelay(view(0, 2000), view(0, 1000), undefined, new Set());
1779
+ // Rate is zero here, so this takes the stalled arm — the point is that a missing
1780
+ // plan is not a crash.
1781
+ expect(delay).toBe(5000);
1782
+ });
1783
+
1784
+ test("returns the ceiling once every segment is done", () => {
1785
+ // Nothing left to extrapolate toward: the loop is waiting on the `complete`
1786
+ // flag, which is set by the uploader rather than reached by bytes.
1787
+ const delay = nextPollDelay(
1788
+ view(50_000, 2000),
1789
+ view(40_000, 1000),
1790
+ planAt(30_000),
1791
+ new Set([0]),
1792
+ );
1793
+ expect(delay).toBe(5000);
1794
+ });
1795
+
1796
+ test("measures the wait against the PREFIX, not against every window that landed", () => {
1797
+ // The parts fan-out is the DEFAULT, and there `stored` and `size` diverge
1798
+ // completely (the module doc measured `size` at 0 for 45 seconds while the
1799
+ // whole file arrived). Both targets here are byte OFFSETS, so subtracting a
1800
+ // total that counts detached windows reads segment 1 as already reached and
1801
+ // collapses the sleep to its 250ms floor — 20x the polling on the path this
1802
+ // flow is normally on. 60_000 bytes have landed somewhere; only 4_000 of them
1803
+ // are readable from the start, so the segment ending at 30_000 needs 26_000
1804
+ // more at the observed 10 bytes/ms.
1805
+ const delay = nextPollDelay(
1806
+ detached(60_000, 4000, 2000),
1807
+ detached(50_000, 0, 1000),
1808
+ planAt(30_000),
1809
+ new Set(),
1810
+ );
1811
+ expect(delay).toBe(2600);
1812
+ });
1813
+
1814
+ test("waits for the HEADER window against the prefix too", () => {
1815
+ // Same trap one step earlier, and this is the arm that really runs first: the
1816
+ // body plans when `at.size >= HEADER_PROBE_BYTES`, so a delay derived from
1817
+ // `stored` is answering a different question than the one the loop asks. A
1818
+ // megabyte has landed in later windows and the header has not arrived.
1819
+ // 50 bytes/ms against the whole 64 KiB probe window is 1311ms; measured
1820
+ // against `stored` the remainder is negative and the answer is the floor.
1821
+ //
1822
+ // The rate is half what this case used to carry, and deliberately: at 100
1823
+ // bytes/ms the answer is 656ms, which is UNDER `MIN_POLL_INTERVAL_MS` and
1824
+ // therefore the same 1000 a broken remainder would give — the case would
1825
+ // still pass while measuring nothing. Every case below keeps its answer
1826
+ // clear of both bounds for that reason.
1827
+ const delay = nextPollDelay(
1828
+ detached(100_000, 0, 3000),
1829
+ detached(0, 0, 1000),
1830
+ undefined,
1831
+ new Set(),
1832
+ );
1833
+ expect(delay).toBe(1311);
1834
+ });
1835
+
1836
+ /**
1837
+ * One 8 MiB upload window, the unit the store publishes a write in.
1838
+ *
1839
+ * The fan-out's real shape, and the one `size` cannot see: the prefix does not
1840
+ * move until the FIRST window lands, so a poll under it reads `size: 0` with
1841
+ * megabytes stored.
1842
+ */
1843
+ const PART_BYTES = 8 * 1024 * 1024;
1844
+
1845
+ /**
1846
+ * A poll of a parts upload whose PREFIX has not moved at all.
1847
+ *
1848
+ * The measured shape from the module doc — a 27 MB recording at 0.9 MB/s
1849
+ * reported `size: 0` for 45 of its 45 seconds while the windows landed. `size`
1850
+ * is fixed at 0 here for exactly that reason: a helper that let it drift would
1851
+ * let a case pass on the prefix arm, which is the hole these two cases exist
1852
+ * to close.
1853
+ */
1854
+ const landed = (ranges: readonly UploadRange[], observedAt: number): UploadProgressView => ({
1855
+ size: 0,
1856
+ complete: false,
1857
+ stored: storedBytes(0, ranges),
1858
+ ranges,
1859
+ observedAt,
1860
+ });
1861
+
1862
+ /** A plan whose segments are the given `[start, end)` windows. */
1863
+ const planOver = (...windows: readonly (readonly [number, number])[]): StreamPlan => ({
1864
+ format: {
1865
+ sampleRate: 48_000,
1866
+ channels: 2,
1867
+ bitsPerSample: 16,
1868
+ dataStart: 44,
1869
+ dataEnd: 44 + Math.max(0, ...windows.map(([, end]) => end)),
1870
+ },
1871
+ segments: windows.map(([start, end], index) => ({ index, start, end, startMs: 0, endMs: 0 })),
1872
+ });
1873
+
1874
+ test("measures a segment against the RANGES its readiness is decided on", () => {
1875
+ // The other half of the prefix rule above, and the one that decides this
1876
+ // flow's whole cadence: `segmentStored` reads `ranges`, so the work still
1877
+ // outstanding is what that test needs and not what the prefix is short by.
1878
+ // Under the fan-out the prefix stays at 0 for the length of the upload, so a
1879
+ // remainder measured against it is the WHOLE segment at every poll — which
1880
+ // saturates the ceiling and gives back the flat 5000ms interval this
1881
+ // function replaced, once per segment, for the entire recording.
1882
+ //
1883
+ // Two 8 MiB windows have landed contiguously from byte zero, at ~466
1884
+ // bytes/ms; the segment ends 866,384 bytes past them.
1885
+ const delay = nextPollDelay(
1886
+ landed([{ start: 0, end: 2 * PART_BYTES }], 19_000),
1887
+ landed([{ start: 0, end: PART_BYTES }], 1000),
1888
+ planOver([0, 17_643_600]),
1889
+ new Set(),
1890
+ );
1891
+ expect(delay).toBe(1860);
1892
+ });
1893
+
1894
+ test("wakes for the segment CLOSEST to ready, which need not be the earliest", () => {
1895
+ // Windows land out of order — that is the premise the `ranges` arm rests on
1896
+ // — so the next segment the loop can act on is not always the first one it
1897
+ // has not done. Segment 0 has nothing covering its start and needs the whole
1898
+ // 20 MB prefix; segment 1 sits inside a window that is 500,000 bytes short.
1899
+ const delay = nextPollDelay(
1900
+ landed([{ start: 16_000_000, end: 35_500_000 }], 19_000),
1901
+ landed([{ start: 16_000_000, end: 27_111_608 }], 1000),
1902
+ planOver([0, 20_000_000], [16_000_000, 36_000_000]),
1903
+ new Set(),
1904
+ );
1905
+ // 466 bytes/ms against the 500,000 still missing from segment 1's window.
1906
+ expect(delay).toBe(1073);
1907
+ });
1908
+
1909
+ test("falls back to the prefix for a window that does not cover the segment's START", () => {
1910
+ // A run has to cover a segment WHOLE to make it readable, so a window landing
1911
+ // in the middle of one moves nothing: what remains is the prefix's own
1912
+ // distance, which here is a ceiling's worth of waiting.
1913
+ const delay = nextPollDelay(
1914
+ landed([{ start: 8_000_000, end: 16_000_000 }], 10_000),
1915
+ landed([{ start: 8_000_000, end: 12_000_000 }], 1000),
1916
+ planOver([0, 17_643_600]),
1917
+ new Set(),
1918
+ );
1919
+ expect(delay).toBe(5000);
1920
+ });
1921
+ });
1922
+
1923
+ /**
1924
+ * `transcribeBatch`, on the real replay engine.
1925
+ *
1926
+ * The batch flow is the one of this desk's three that reaches no ffmpeg — it
1927
+ * uploads, submits and polls — so it is the one a unit spec can drive end to
1928
+ * end. `transcribe` and `transcribeStream` both normalize the recording first,
1929
+ * and this repo's test environment has no ffmpeg (the `normalizeRecording` specs
1930
+ * above assert the FatalError that produces). Their durability is
1931
+ * `aai-cli`'s `dev-workflow.scenario.test.ts`'s to cover; what is asserted here
1932
+ * is the half that is honestly reachable, which is better than a body test
1933
+ * dressed up as a durability test.
1934
+ *
1935
+ * Two claims, and the second is the one no other tier can make:
1936
+ *
1937
+ * - **The recording is uploaded ONCE**, however many times the body is walked.
1938
+ * That is why the upload is a step of its own with a raised attempt budget.
1939
+ * - **`ctx.now()` is JOURNALED**, so `startedAt` — which the poll step subtracts
1940
+ * to report `elapsedMs` — is the instant the run really began and not the
1941
+ * instant the latest walk began. A body that read `Date.now()` there would
1942
+ * report a shrinking elapsed on every resume, which is `guard-invariants`
1943
+ * rule 30 and the whole reason the affordance exists.
1944
+ */
1945
+ describe("the batch run is DURABLE", () => {
1946
+ const INPUT = { recording: UPLOAD_ID };
1947
+
1948
+ beforeEach(() => {
1949
+ installStubUploads({
1950
+ [UPLOAD_ID]: { bytes: new Uint8Array(4096), name: "standup.wav", type: "audio/wav" },
1951
+ });
1952
+ installStubReporter();
1953
+ vi.stubEnv("ASSEMBLYAI_API_KEY", "test-key");
1954
+ });
1955
+
1956
+ test("parks on the poll cadence with the upload already journaled", async () => {
1957
+ const provider = installStubTranscribe({ pendingPolls: 1, text: "We shipped it." });
1958
+ const started = Date.now();
1959
+ const run = await runWorkflow(transcribeBatch, INPUT, { name: "transcribeBatch" });
1960
+
1961
+ expect(run.status).toBe("running");
1962
+ expect(run.wakeAt).toBeGreaterThan(started);
1963
+ expect(run.steps.map((step) => step.key)).toEqual([
1964
+ "createJob#0",
1965
+ "pollTranscript#0",
1966
+ "uploadToProvider#0",
1967
+ ]);
1968
+ // The clock the body read alongside the upload is journaled too, in its own
1969
+ // reserved key space — `run.reads`, not `run.steps`.
1970
+ expect(run.reads.map((read) => read.key)).toEqual(["now!0"]);
1971
+ expect(provider.calls.filter((call) => call.leg === "upload")).toHaveLength(1);
1972
+ });
1973
+
1974
+ test("resumes past the poll without moving the recording again", async () => {
1975
+ const provider = installStubTranscribe({ pendingPolls: 1, text: "We shipped it." });
1976
+ const run = await runWorkflow(transcribeBatch, INPUT, { name: "transcribeBatch" });
1977
+ await run.advanceSleep();
1978
+
1979
+ expect(run.status).toBe("completed");
1980
+ expect(run.output).toMatchObject({
1981
+ transcript: "We shipped it.",
1982
+ // ONE, which is the difference this flow exists to show against the two
1983
+ // that segment.
1984
+ segments: 1,
1985
+ source: "standup.wav",
1986
+ });
1987
+ expect(run.deliveries).toBe(2);
1988
+ // The whole recording crossed the wire once, on the first walk.
1989
+ expect(provider.calls.filter((call) => call.leg === "upload")).toHaveLength(1);
1990
+ expect(provider.calls.filter((call) => call.leg === "submit")).toHaveLength(1);
1991
+ });
1992
+
1993
+ test("reports the elapsed from the run's OWN start, not the resuming walk's", async () => {
1994
+ // The affordance's claim. `ctx.now()` is journaled under its own key, so the
1995
+ // second walk re-reads the first walk's instant — and `elapsedMs`, which the
1996
+ // poll step computes as `Date.now() - startedAt`, therefore counts the whole
1997
+ // run rather than the delivery it finished on.
1998
+ const provider = installStubTranscribe({ pendingPolls: 1, text: "We shipped it." });
1999
+ const run = await runWorkflow(transcribeBatch, INPUT, { name: "transcribeBatch" });
2000
+ await run.advanceSleep();
2001
+
2002
+ expect(run.status).toBe("completed");
2003
+ // A journaled clock cannot go backwards across a resume, and a re-read one
2004
+ // routinely would — the second walk starts later than the first.
2005
+ expect(run.output?.elapsedMs).toBeGreaterThanOrEqual(0);
2006
+ expect(provider.calls.filter((call) => call.leg === "poll")).toHaveLength(2);
2007
+ });
2008
+
2009
+ test("a worker that dies before the job is created re-uploads, because nothing settled", async () => {
2010
+ // The other side of exactly-once, and the honest one: a step whose entry was
2011
+ // never written IS re-run, because the journal is what makes a step skippable
2012
+ // and a crashed one left none.
2013
+ const provider = installStubTranscribe({ text: "We shipped it." });
2014
+ const run = await runWorkflow(transcribeBatch, INPUT, {
2015
+ name: "transcribeBatch",
2016
+ crashAt: "createJob",
2017
+ });
2018
+
2019
+ expect(run.crashed).toBe(true);
2020
+ expect(run.steps.map((step) => step.name)).toEqual(["uploadToProvider"]);
2021
+ // The clock the body read in the same `Promise.all` survived the crash with
2022
+ // it, which is what makes the resumed run's elapsed the WHOLE run's.
2023
+ expect(run.reads.map((read) => read.key)).toEqual(["now!0"]);
2024
+ expect(provider.calls.filter((call) => call.leg === "submit")).toHaveLength(0);
2025
+
2026
+ await run.restart();
2027
+ expect(run.status).toBe("completed");
2028
+ // The upload SURVIVED — it settled before the crash — and only the job
2029
+ // creation was re-issued.
2030
+ expect(provider.calls.filter((call) => call.leg === "upload")).toHaveLength(1);
2031
+ expect(provider.calls.filter((call) => call.leg === "submit")).toHaveLength(1);
2032
+ });
2033
+ });