@alexkroman1/aai-cli 0.12.3 → 0.13.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-CgBw5Bcu.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 +17 -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-BNq5OnUJ.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 +22 -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-DJuwYZ6T.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-BH05zugt.mjs +251 -0
  57. package/dist/_studio-commands.d.ts +73 -0
  58. package/dist/_studio.d.ts +80 -0
  59. package/dist/_target-bundle.d.ts +139 -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-Bv-rd0SO.mjs +135 -0
  64. package/dist/_templates.d.ts +82 -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-B37oBfEv.mjs +592 -0
  80. package/dist/build.d.ts +146 -0
  81. package/dist/cli-workflow.d.ts +10 -0
  82. package/dist/cli.d.ts +1 -0
  83. package/dist/cli.mjs +1063 -198
  84. package/dist/client-bundler-D4SeZJ8E.mjs +240 -0
  85. package/dist/client-bundler.d.ts +32 -0
  86. package/dist/client-bundler.mjs +3 -0
  87. package/dist/console-D6OOjjeJ.mjs +443 -0
  88. package/dist/console.d.ts +70 -0
  89. package/dist/delete-Br0EOH0g.mjs +55 -0
  90. package/dist/delete.d.ts +25 -0
  91. package/dist/deploy-CLUH5cv2.mjs +97 -0
  92. package/dist/deploy.d.ts +25 -0
  93. package/dist/dev-ZVuyPLUk.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-x3FsKl2q.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-BfRq1HX9.mjs +80 -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 +140 -0
  109. package/dist/scaffold/agent-guide/PIPELINE-TUNING.md +235 -0
  110. package/dist/scaffold/agent-guide/PROVIDERS.md +143 -0
  111. package/dist/scaffold/agent-guide/TESTING-EVALS.md +158 -0
  112. package/dist/scaffold/agent-guide/TOOLS.md +628 -0
  113. package/dist/scaffold/agent-guide/UI.md +291 -0
  114. package/dist/scaffold/agent-guide/WORKFLOWS.md +801 -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-Db1UWLSZ.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-DAoJApzD.mjs +209 -0
  124. package/dist/studio.d.ts +55 -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 +254 -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 +513 -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 +647 -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 +332 -0
  326. package/dist/templates/medication-safety-agent/agent.ts +62 -0
  327. package/dist/templates/medication-safety-agent/fda.test.ts +130 -0
  328. package/dist/templates/medication-safety-agent/fda.ts +159 -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 +62 -0
  331. package/dist/templates/medication-safety-agent/tools/medication_lookup.ts +36 -0
  332. package/dist/templates/meeting-recap-agent/agent.eval.test.ts +446 -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 +341 -0
  376. package/dist/templates/research-handoff-agent/agent.test.ts +831 -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 +635 -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 +327 -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 +2032 -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 +222 -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 +181 -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 +484 -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,690 @@
1
+ // Copyright 2026 the AAI authors. MIT license.
2
+ /**
3
+ * The streaming desk: transcribe the recording WHILE it uploads.
4
+ *
5
+ * Read `transcribe.ts` first. This does the same three jobs — plan, transcribe,
6
+ * stitch — with the same two steps doing the middle and the end, and the only thing
7
+ * it changes is WHEN. That one change is the reason it exists:
8
+ *
9
+ * | | `transcribe` | `transcribeStream` |
10
+ * | --- | --- | --- |
11
+ * | the run starts | after the last byte is stored | before the first one is |
12
+ * | the client sends | `POST /workflows/uploads` | `PUT /workflows/uploads/<id>` |
13
+ * | who names the upload | the store | the CLIENT |
14
+ * | the body | plans once, fans out once | polls, fans out over what has arrived |
15
+ *
16
+ * ## The client names the upload, and that is the whole trick
17
+ *
18
+ * An ordinary upload cannot help here: `POST` answers with an id once the last byte
19
+ * is stored, so there is nothing to put in a run input until the upload is over. A
20
+ * STREAMED upload is named by its caller — `useWorkflowStream` mints an id, starts
21
+ * the run on it, and PUTs the file in one request — so the record exists from the
22
+ * first byte with `complete: false` and its `size` grows as bytes land.
23
+ *
24
+ * The reader needed almost nothing for this, which is why this flow is so close to
25
+ * the other one: `stepReadUpload` already clamped its window to what is stored (so a
26
+ * plan computed from a header could end one byte past the file), and that clamp is
27
+ * exactly "read what has arrived". So `transcribeSegment` below is `transcribe.ts`'s
28
+ * OWN step, unchanged, called on windows this body has checked are present.
29
+ *
30
+ * ## `complete`, never a stalled `size`
31
+ *
32
+ * The exit is the upload's `complete` flag. A `size` that has stopped growing means
33
+ * only that nothing arrived recently, which is what a slow link and a dead client
34
+ * both look like — so a body that took a stalled size for the end would return a
35
+ * transcript of most of a recording and report success. The stall is what
36
+ * {@link MAX_IDLE_POLLS} is for, and it FAILS the run rather than finishing it.
37
+ *
38
+ * ## A poll reads THREE numbers, and each answers a different question
39
+ *
40
+ * `size` is the CONTIGUOUS PREFIX, `stored` is every byte that has landed, and
41
+ * `ranges` is where those bytes are. They are one number only for a whole-file
42
+ * upload; under the browser's default fan-out they diverge completely, and reading
43
+ * the wrong one is two separate bugs:
44
+ *
45
+ * - **Readiness on the prefix alone made this flow a no-op.** The client sends
46
+ * `UPLOAD_PART_CONCURRENCY` windows of `UPLOAD_PART_BYTES` at once, so every part
47
+ * of any recording that fits in one round shares the uplink and they all finish
48
+ * together. The prefix cannot move until the FIRST part completes, which is
49
+ * within a second of the last. Measured on a deployed agent, a 27 MB recording at
50
+ * 0.9 MB/s: `size` was 0 at every poll for 45 seconds and then the whole file, so
51
+ * the run planned nothing, transcribed nothing, and did its entire fan-out after
52
+ * the upload — the classic flow, with extra steps. `segmentStored` reads `ranges`
53
+ * instead, and `stepReadUpload` clamps to the run a read starts in rather than to the
54
+ * prefix, so a window that has landed is a window this flow can work on.
55
+ * - **The stall test on the prefix would then FAIL a healthy upload.** A parts
56
+ * upload moving at full speed reports the same prefix at every poll, which is
57
+ * indistinguishable from a dead client — so past {@link MAX_IDLE_POLLS} the run
58
+ * abandons an upload that is still arriving. It reads `stored`, which grows with
59
+ * every window whatever order they land in.
60
+ *
61
+ * `size` keeps the two jobs only it can do: the header probe (which reads from byte
62
+ * zero) and the finished recording's duration.
63
+ *
64
+ * ## It really does overlap, and the granularity is a SEGMENT
65
+ *
66
+ * Watched directly — the same 10-minute recording at 2 MB/s, polling the upload's
67
+ * `size` and counting `Transcribed …` lines in the run's own log:
68
+ *
69
+ * ```text
70
+ * 1s 2 MB uploaded 0 segments transcribed
71
+ * 14s 26 MB 1 <- first one, at 24% of the file
72
+ * 23s 45 MB 2
73
+ * 32s 63 MB 3
74
+ * 41s 82 MB 4
75
+ * 48s 94 MB 5
76
+ * 54s 106 MB 6
77
+ * 55s ---- PUT returns ----
78
+ * 60s 109 MB 7 <- run completed
79
+ * ```
80
+ *
81
+ * **Six of seven segments were transcribed before the upload finished.** So the run
82
+ * does not wait for the file — and it does not start on the first CHUNK either, which
83
+ * is worth being exact about: a segment is the smallest thing the sync endpoint can
84
+ * decode, so the floor is "one segment has landed", not "some bytes have". Three
85
+ * granularities stack up to that:
86
+ *
87
+ * - a segment is `SEGMENT_SECONDS + SEGMENT_OVERLAP_SECONDS` of audio — ~17.6 MB at
88
+ * 48 kHz stereo, which is ~9s of a 2 MB/s uplink;
89
+ * - the store publishes bytes an `UPLOAD_PART_BYTES` window at a time (8 MiB), so the
90
+ * view a poll reads is up to a window stale. This paragraph said 1 MiB, naming
91
+ * `UPLOAD_CHUNK_BYTES`, which is the chunk a range READ is served in and not the
92
+ * unit a write publishes: `putWindows` cuts a body into `UPLOAD_PART_BYTES`
93
+ * windows so one byte layout serves every route an upload can arrive by;
94
+ * - the body sleeps {@link POLL_INTERVAL_MS} between polls when nothing is ready, cut
95
+ * short by the client's wake.
96
+ *
97
+ * 9s + one poll is the 14s above. Nothing here can go below a segment without a
98
+ * different provider API — which is what the third flow (`batch.ts`) is.
99
+ *
100
+ * ## What it actually saves, measured
101
+ *
102
+ * Run against a real dev server on a 10-minute 48 kHz stereo recording (115 MB, 7
103
+ * segments), with `curl --limit-rate` standing in for an uplink:
104
+ *
105
+ * | uplink | classic (upload + run) | streaming (upload + tail) | saved |
106
+ * | --- | --- | --- | --- |
107
+ * | loopback | 0.3 + 5.3 = 5.5s | 0.2 + 5.3 = 5.5s | 0s |
108
+ * | 8 MB/s | 13.8 + 4.2 = 18.0s | 13.9 + 3.2 = 17.1s | 0.9s |
109
+ * | 2 MB/s | 55.1 + 4.3 = 59.4s | 55.1 + 2.2 = 57.3s | 2.1s |
110
+ *
111
+ * Read the TAIL column, which is the whole mechanism: it shrinks as the uplink slows
112
+ * (5.3s -> 3.2s -> 2.2s) because more of the transcription has already happened
113
+ * behind the upload by the time the last byte lands. The floor is one segment.
114
+ *
115
+ * **So the saving is roughly ONE segment's latency, not a proportion of the file** —
116
+ * and the reason is structural rather than a tuning problem. Every segment but the
117
+ * last is transcribed during the upload, and the last one cannot start until its
118
+ * bytes land, so both flows end at `upload + one segment`. The transcription is the
119
+ * small term for any file this endpoint accepts: it runs 20-200x faster than
120
+ * realtime, so a recording long enough for the difference to matter is a recording
121
+ * whose upload dominates either way.
122
+ *
123
+ * Precisely: both flows are `upload + rounds x one segment`, streaming is always
124
+ * ONE round (only the last segment is left when the bytes land), and the classic
125
+ * flow is `ceil(segments / segmentConcurrency)`. So the saving is
126
+ * `(rounds - 1) x segment latency` and **it is ZERO whenever the classic fan-out
127
+ * fits in one round** — which is most files, because that width is 32:
128
+ *
129
+ * | recording | segments | classic rounds | saving |
130
+ * | --- | --- | --- | --- |
131
+ * | 12 min, 48 kHz stereo (130 MB) | 8 | 1 | none, by construction |
132
+ * | 60 min, 48 kHz stereo (660 MB) | 41 | 2 | one segment |
133
+ * | 6 h, 16 kHz mono (660 MB) | 241 | 8 | seven segments |
134
+ *
135
+ * It therefore grows with the SEGMENT COUNT, which is duration over bitrate — not
136
+ * with file size. The two 660 MB rows are the point: same bytes, same width, and
137
+ * the low-bitrate one has six times the segments and six times the benefit.
138
+ *
139
+ * This paragraph used to claim a 97-minute recording was "~65 segments in ~9
140
+ * rounds, and eight of those rounds happen behind the upload". The segment count
141
+ * was right and the rounds were not: at width 32 that is 3 rounds, so at most 2
142
+ * are hidden. It described a width of ~7, which is what `mapInBatches` and a
143
+ * smaller `BYTES_IN_FLIGHT` gave before either moved — and it overstated this
144
+ * flow's benefit about fourfold, which is exactly the expectation a reader brings
145
+ * to the mode picker and then finds unmet.
146
+ *
147
+ * What it always buys, at any length, is the thing a table cannot show: the page
148
+ * shows real progress — segment timings, arriving — while the bytes are still
149
+ * moving, instead of a bar and then a wait. The classic flow remains the simpler
150
+ * shape and is never slower, which is why the page offers both rather than replacing
151
+ * one with the other.
152
+ *
153
+ * ## A ROUND has to finish before the next poll
154
+ *
155
+ * Everything the body decides comes from a journaled poll, so the set of segments it
156
+ * fans out over is fixed for the length of that fan-out: one that becomes readable
157
+ * while a round is in flight waits for the round. That is a smaller wait than it was
158
+ * — `mapConcurrent` is a window over a cursor rather than sequential batches, so a
159
+ * round now ends when its LAST segment lands rather than at the sum of each batch's
160
+ * slowest — but it is not zero, and it is why the two flows converge on a fast
161
+ * uplink rather than the streaming one winning. On a slow uplink it costs nothing:
162
+ * segments arrive slower than they transcribe.
163
+ *
164
+ * Feeding new segments into a running fan-out would remove it and is deliberately
165
+ * not done: which items are in flight would then depend on when bytes arrived, and
166
+ * the DevKit correlates a journal entry to a step call by ISSUE ORDER. A round is
167
+ * what keeps that order a pure function of journaled values.
168
+ */
169
+
170
+ import type { WorkflowContext } from "@alexkroman1/aai";
171
+ import {
172
+ mapConcurrent,
173
+ stepReadUpload,
174
+ stepReport,
175
+ stepUploadInfo,
176
+ type UploadRange,
177
+ } from "@alexkroman1/aai/step";
178
+ import { throwFatalStepError } from "@alexkroman1/aai/step-errors";
179
+ import { formatDuration, omitUndefined, plural } from "@alexkroman1/aai/utils";
180
+ import {
181
+ fatalOnUnsupported,
182
+ mergeTranscript,
183
+ type SegmentTranscript,
184
+ segmentConcurrency,
185
+ transcribeSegment,
186
+ } from "./transcribe.ts";
187
+ import {
188
+ assertCuttable,
189
+ HEADER_PROBE_BYTES,
190
+ offsetToMs,
191
+ parseWav,
192
+ planSegments,
193
+ type Segment,
194
+ UnsupportedRecordingError,
195
+ type WavFormat,
196
+ } from "./wav.ts";
197
+
198
+ /**
199
+ * The LONGEST the body waits between polls, and its fallback when it cannot do
200
+ * better.
201
+ *
202
+ * It used to be the only interval, and on a slow uplink that is most of what this
203
+ * flow was still leaving on the table. A poll answers "has the next segment
204
+ * landed"; a flat interval answers it on average half an interval late, once per
205
+ * segment, for the whole upload — 20 segments of a 30-minute recording is ~50s of
206
+ * pure waiting added to a run whose entire point is to finish as the bytes arrive.
207
+ *
208
+ * So it is a CEILING now: {@link nextPollDelay} sleeps until the next segment
209
+ * should have landed, and falls back here when there is nothing to predict from.
210
+ */
211
+ const POLL_INTERVAL_MS = 5000;
212
+
213
+ /**
214
+ * The shortest the body will sleep.
215
+ *
216
+ * A poll is one cheap step (the body's own note above the `continue` says so), but
217
+ * it is not free — it is a journal write and, on the platform, a step execution —
218
+ * so a rate estimate that comes out near zero must not turn the loop into a spin.
219
+ *
220
+ * **The comparison that decides this number is the ROUND TRIP of the machinery
221
+ * that implements the sleep, not the latency of a segment's transcription.** It
222
+ * was 250ms on the second reading, which made it DEAD: `ctx.sleep`'s deadline is
223
+ * computed before its journal write is issued and tested after that write comes
224
+ * back, so on the platform — where one journal call was measured at ~558ms mean,
225
+ * p50 ranging 164-796ms — a 250ms sleep has already expired by the time its own
226
+ * write answers. It did not sleep at all, and the loop then polled as fast as the
227
+ * journal would let it. A floor under the round trip is not a floor.
228
+ *
229
+ * 1000ms is above every one of those readings and still an order of magnitude
230
+ * under a single segment's transcription, so nothing is waiting on it.
231
+ */
232
+ const MIN_POLL_INTERVAL_MS = 1000;
233
+
234
+ /**
235
+ * Consecutive polls with NO new bytes before the run gives up.
236
+ *
237
+ * An upload that died stays incomplete forever, so without a bound the run polls for
238
+ * as long as the world will replay it.
239
+ *
240
+ * **What one poll COSTS is a delivery, not an interval, and this doc said
241
+ * otherwise.** It read "at {@link POLL_INTERVAL_MS} this is five minutes of
242
+ * silence", which counts the sleep and nothing else. A poll that sleeps also
243
+ * suspends the run, so the wall clock between two polls is the sleep plus a
244
+ * queue round trip plus the next delivery's opening reads — measured on a
245
+ * deployed run at 11-40 seconds. Sixty of those is **20 to 40 minutes**, not
246
+ * five.
247
+ *
248
+ * That is longer than intended and is left as it is: what the bound has to
249
+ * outlast is a stall a live uplink really produces, and erring long costs an
250
+ * abandoned upload some idle deliveries where erring short fails a healthy
251
+ * recording. The number to write down is the honest one.
252
+ *
253
+ * It resets on every byte, so a slow upload is bounded by its own quietest gap
254
+ * rather than by its total length: a two-hour recording on a bad connection is fine
255
+ * as long as something arrives inside that window.
256
+ */
257
+ const MAX_IDLE_POLLS = 60;
258
+
259
+ /** What one poll of the upload found. */
260
+ export type UploadProgressView = {
261
+ /**
262
+ * The CONTIGUOUS PREFIX — how far the file can be read from byte zero.
263
+ *
264
+ * Not how much has arrived: see {@link UploadProgressView.stored}. It is what
265
+ * the header probe and the final duration are measured against, because both
266
+ * want a length rather than a coverage map.
267
+ */
268
+ size: number;
269
+ /** Whether that is all of them. The ONLY field an exit may be decided on. */
270
+ complete: boolean;
271
+ /**
272
+ * Total bytes landed, prefix and windows ahead of it alike.
273
+ *
274
+ * The one number a STALL may be judged on. `size` cannot be: a fan-out lands
275
+ * its windows out of order, so the prefix stays at zero through an upload that
276
+ * is moving at full speed and {@link MAX_IDLE_POLLS} would call it dead.
277
+ */
278
+ stored: number;
279
+ /**
280
+ * The windows that have landed, when the upload arrived as parts.
281
+ *
282
+ * Absent for a whole-file write, whose bytes are the prefix and nothing else.
283
+ * This is what makes a segment readable before the windows in front of it
284
+ * arrive — see the readiness test in the body.
285
+ */
286
+ ranges?: readonly UploadRange[];
287
+ /**
288
+ * When this view was taken, as the step that took it saw the clock.
289
+ *
290
+ * Journaled, which is the only reason the body may read a clock at all: the
291
+ * sleep below is derived from the RATE between the run's FIRST view and this
292
+ * one, and a value the body sampled itself would make that derivation diverge
293
+ * on a replay. Same rule
294
+ * as every other field here — see the body's own note on why its state is legal.
295
+ */
296
+ observedAt: number;
297
+ };
298
+
299
+ /** The cut, derived once from the header. */
300
+ export type StreamPlan = {
301
+ format: WavFormat;
302
+ segments: Segment[];
303
+ };
304
+
305
+ /**
306
+ * Transcribe a recording that is still uploading.
307
+ *
308
+ * The input is what `POST /workflows/runs` carries — see `agent.ts`. `recording` is
309
+ * an upload id exactly as in the classic flow; what differs is that the client chose
310
+ * it and the bytes are still on their way.
311
+ */
312
+ export async function transcribeStreamFlow(input: { recording: string }, ctx: WorkflowContext) {
313
+ // `ctx.now()`, not a step: the engine journals the read under its own key, so
314
+ // every walk of this line sees the instant the first one did.
315
+ const startedAt = await ctx.now();
316
+ let plan: StreamPlan | undefined;
317
+ // Body state, and legal because every value in it came out of a journaled step
318
+ // result — a replay rebuilds the identical sets in the identical order.
319
+ const done = new Set<number>();
320
+ const parts: SegmentTranscript[] = [];
321
+ let idlePolls = 0;
322
+ // The prefix at the last poll, which is what the final duration is measured
323
+ // from — and deliberately NOT what the stall test reads; see `lastStored`.
324
+ let lastSize = 0;
325
+ // Total bytes landed at the last poll. A fan-out lands its windows out of
326
+ // order, so this is the only number that distinguishes an upload that has
327
+ // stopped from one whose prefix has not caught up yet.
328
+ let lastStored = -1;
329
+ /**
330
+ * The FIRST poll, so {@link nextPollDelay} has a baseline to take an AVERAGE
331
+ * rate from. Body state for the same reason the rest is: it came out of a step.
332
+ *
333
+ * It used to be the PREVIOUS poll, and a two-sample difference is not a
334
+ * throughput here: the store publishes bytes an `UPLOAD_PART_BYTES` window at a
335
+ * time, so consecutive polls see either no change at all — which reads as a
336
+ * stall and gives back the flat ceiling — or one whole 8 MiB window, an
337
+ * instantaneous burst rate tens of times the real average that collapses the
338
+ * sleep to its floor. The distribution is bimodal and neither mode is the
339
+ * number the estimate wants. A baseline that never moves measures exactly what
340
+ * the arithmetic below claims to: bytes delivered per millisecond, over the
341
+ * upload so far.
342
+ */
343
+ let baseline: UploadProgressView | undefined;
344
+
345
+ for (;;) {
346
+ const at = await ctx.step("probeUpload", () => probeUpload(input.recording));
347
+ // Every poll, because this is only ever read at the END — the run breaks out
348
+ // on a `complete` view, whose prefix is the whole file. Updating it inside a
349
+ // branch is how it used to end up describing whichever poll last had work.
350
+ lastSize = at.size;
351
+ // HERE, not after the sleep below, and that placement is the whole bug the
352
+ // baseline replaced: the `continue` on a batch of ready segments skipped the
353
+ // old `previous = at`, so the next rate was computed against a view taken
354
+ // before the batch. Set once, before any branch can be taken.
355
+ baseline ??= at;
356
+
357
+ // The header has to be present before anything can be planned, and it is the
358
+ // first thing to arrive. `complete` also qualifies, for a recording shorter
359
+ // than the probe window.
360
+ if (!plan && (at.size >= HEADER_PROBE_BYTES || at.complete)) {
361
+ plan = await ctx.step("planStreamed", () => planStreamed(input.recording));
362
+ }
363
+
364
+ if (plan) {
365
+ // A segment is READY when its whole window is stored — except once the upload
366
+ // is complete, where `at.size` is the true total and the plan came from the
367
+ // header's DECLARED length: a recording that came up short leaves a final
368
+ // segment ending past the file, and `stepReadUpload` clamping is what makes that
369
+ // the right answer rather than an error.
370
+ const ready = plan.segments.filter(
371
+ (segment) =>
372
+ !done.has(segment.index) &&
373
+ (segmentStored(segment, at) || (at.complete && segment.start < at.size)),
374
+ );
375
+ if (ready.length > 0) {
376
+ idlePolls = 0;
377
+ lastStored = at.stored;
378
+ for (const segment of ready) done.add(segment.index);
379
+ // One step per segment, bounded, in an order a replay reproduces exactly —
380
+ // `ready` is derived from a journaled poll, and `mapConcurrent` issues its
381
+ // calls in list order. THE SAME STEP the classic flow uses, so a segment
382
+ // transcribed here reaches the page's live transcript identically.
383
+ parts.push(
384
+ ...(await mapConcurrent(
385
+ ready,
386
+ segmentConcurrency((plan as StreamPlan).format),
387
+ (segment) =>
388
+ // `maxAttempts: 6` was `transcribeSegment.maxRetries = 5`.
389
+ ctx.step(
390
+ "transcribeSegment",
391
+ () => transcribeSegment(input.recording, (plan as StreamPlan).format, segment),
392
+ { maxAttempts: 6 },
393
+ ),
394
+ )),
395
+ );
396
+ // Straight back to the top WITHOUT sleeping, and this line was measured
397
+ // rather than reasoned about. A batch takes seconds, so by the time it
398
+ // finishes the upload has moved on and the view above is stale — deciding
399
+ // anything on it means sleeping through news that has already arrived.
400
+ // Measured by deleting this one statement, 10-minute recording at 8 MB/s:
401
+ // the tail goes 3.2s -> 9.5s and the run 17.1s -> 23.4s. A poll is one cheap
402
+ // step; sleeping is only right when there was nothing to do.
403
+ continue;
404
+ }
405
+ }
406
+
407
+ // Nothing to work on, so this view is current and the exit can be trusted.
408
+ if (at.complete && plan && done.size >= expectedSegments(plan, at.size)) break;
409
+ // A stall, not an ending — see MAX_IDLE_POLLS. Judged on `stored` rather than
410
+ // on the prefix: under the browser's default fan-out the prefix does not move
411
+ // at all until the first window lands, so a run reading it would call a
412
+ // healthy upload abandoned five minutes in and fail.
413
+ if (at.stored === lastStored) idlePolls += 1;
414
+ else {
415
+ idlePolls = 0;
416
+ lastStored = at.stored;
417
+ }
418
+ if (idlePolls > MAX_IDLE_POLLS) abandon(input.recording, at);
419
+ // Sleep until the next segment should HAVE landed, rather than for a fixed
420
+ // interval — see `nextPollDelay`. Both arguments are journaled step results,
421
+ // so a replay computes the same delay from the same two samples.
422
+ await ctx.sleep("poll", nextPollDelay(at, baseline, plan, done));
423
+ }
424
+
425
+ const finished = plan;
426
+ if (!finished) abandon(input.recording, { size: 0, stored: 0 });
427
+ return await ctx.step("mergeTranscript", () =>
428
+ mergeTranscript(
429
+ input.recording,
430
+ offsetToMs(finished.format, Math.min(finished.format.dataEnd, lastSize)),
431
+ parts,
432
+ startedAt,
433
+ ),
434
+ );
435
+ }
436
+
437
+ /**
438
+ * How much of the upload is stored, and whether that is all of it.
439
+ *
440
+ * A step because it is I/O, which a body may not do — and because what the body does
441
+ * next is derived from its RESULT, so journaling it is what makes the run take the
442
+ * same branches on a replay. It narrates nothing: sixty "still uploading" lines
443
+ * would bury the ones that matter, and `transcribeSegment` is where the log comes
444
+ * from.
445
+ */
446
+ export async function probeUpload(id: string): Promise<UploadProgressView> {
447
+ const info = await stepUploadInfo(id);
448
+ return {
449
+ size: info.size,
450
+ complete: info.complete,
451
+ stored: storedBytes(info.size, info.ranges),
452
+ // Legal HERE and nowhere else in this flow: a step's internals are not
453
+ // replayed, only its result — which is what makes a step the place a clock
454
+ // belongs. See `sync-api.ts`'s `timed` for the same rule.
455
+ observedAt: Date.now(),
456
+ // `omitUndefined` rather than a spread, because a journaled step result is
457
+ // compared on replay and `{ ranges: undefined }` is not `{}` once it has been
458
+ // through JSON.
459
+ ...omitUndefined({ ranges: info.ranges }),
460
+ };
461
+ }
462
+
463
+ /**
464
+ * How long to wait before asking again — the time the NEXT segment still needs.
465
+ *
466
+ * The flat {@link POLL_INTERVAL_MS} this replaced is wrong in both directions on a
467
+ * slow uplink: too long when a segment is seconds away, and equally too long when
468
+ * it is a minute away, so the run discovers work late and then asks again pointlessly.
469
+ * The run's FIRST poll and its latest one give a byte RATE, the plan gives the byte
470
+ * offset the next un-transcribed segment needs, and the difference is a wait with a
471
+ * reason.
472
+ *
473
+ * **`baseline` is the first poll of the run and never moves**, so what this reads is
474
+ * the AVERAGE throughput rather than a first difference between two adjacent polls.
475
+ * That is not a refinement: bytes are published an `UPLOAD_PART_BYTES` window at a
476
+ * time, so a two-sample difference is 0 or one whole 8 MiB window and never the
477
+ * rate — see the body's own note where the baseline is set. The arithmetic below is
478
+ * unchanged, which is why it is the CALLER that had the bug.
479
+ *
480
+ * Every input is a journaled step result — both views, and a plan derived from one —
481
+ * so a replay computes the identical delay. That is the whole reason
482
+ * {@link UploadProgressView.observedAt} exists rather than the body reading a clock.
483
+ *
484
+ * It is deliberately an ESTIMATE with a floor and a ceiling rather than a promise.
485
+ * Undershooting costs one extra cheap poll; overshooting is bounded by
486
+ * {@link POLL_INTERVAL_MS}, so a rate that collapses mid-upload degrades to exactly
487
+ * the old behaviour instead of stalling. Note the estimate is only ever used to
488
+ * SLEEP: readiness is still decided by {@link segmentStored} against a real view, so
489
+ * a wrong guess here can waste a poll and can never transcribe a partial segment.
490
+ */
491
+ export function nextPollDelay(
492
+ at: UploadProgressView,
493
+ baseline: UploadProgressView | undefined,
494
+ plan: StreamPlan | undefined,
495
+ done: ReadonlySet<number>,
496
+ ): number {
497
+ // No baseline, or a clock that has not advanced past it: nothing to derive a
498
+ // rate from. The first sleep of every run takes this arm, the baseline BEING
499
+ // that poll.
500
+ const elapsedMs = baseline ? at.observedAt - baseline.observedAt : 0;
501
+ if (!baseline || elapsedMs <= 0) return POLL_INTERVAL_MS;
502
+ const bytesPerMs = (at.stored - baseline.stored) / elapsedMs;
503
+ // A stalled or shrinking upload has no arrival to predict. `MAX_IDLE_POLLS` is
504
+ // what ends that run; this only declines to guess about it.
505
+ if (bytesPerMs <= 0) return POLL_INTERVAL_MS;
506
+ // Before the header is read there is no plan, so what is being waited for is the
507
+ // probe window itself — small, and usually one part away. It is measured against
508
+ // the PREFIX because that is what the probe reads: from byte zero. Never against
509
+ // `stored`, which counts every window that has landed wherever it landed — the
510
+ // module doc's third section is about exactly that divergence, and under the
511
+ // browser's default fan-out `HEADER_PROBE_BYTES - stored` goes NEGATIVE before
512
+ // the header this arm is waiting for has arrived at all, collapsing the sleep to
513
+ // its floor. The RATE above is still `stored`'s, which is right: that one is a
514
+ // throughput, and throughput is what every window contributes to.
515
+ //
516
+ // The plan arm asks {@link segmentStored}'s own question instead of subtracting
517
+ // an offset, because that test does not read the prefix either. Measuring a
518
+ // segment against `size` saturates for the whole upload — 45 seconds of `size: 0`
519
+ // on the measured 27 MB recording — so every segment's sleep came back as the
520
+ // flat POLL_INTERVAL_MS this function exists to replace.
521
+ const remaining = plan ? bytesUntilNextSegment(plan, done, at) : HEADER_PROBE_BYTES - at.size;
522
+ // Every segment is already stored: the loop is waiting on `complete`, which is a
523
+ // flag the uploader sets rather than bytes to extrapolate.
524
+ if (remaining === undefined) return POLL_INTERVAL_MS;
525
+ // There is no `remaining <= 0` arm, and there used to be one returning the
526
+ // floor. It was UNREACHABLE from the body — `bytesUntilStored` answers 0 only
527
+ // when `segmentStored` does, which would have put the segment in `ready` and
528
+ // taken the `continue` above, and the no-plan arm is only taken while
529
+ // `at.size < HEADER_PROBE_BYTES` — and REDUNDANT besides: `Math.ceil` of a
530
+ // non-positive quotient is non-positive, so the `Math.max` below already
531
+ // answers the floor for it. Deleting it changes no answer for any input.
532
+ return Math.min(
533
+ POLL_INTERVAL_MS,
534
+ Math.max(MIN_POLL_INTERVAL_MS, Math.ceil(remaining / bytesPerMs)),
535
+ );
536
+ }
537
+
538
+ /**
539
+ * How many bytes away the NEAREST un-transcribed segment is from being readable.
540
+ *
541
+ * The nearest rather than the earliest, and that is the `ranges` arm's doing: a
542
+ * fan-out lands its windows out of order, so the next segment the loop can act on
543
+ * is whichever one is closest to covered — not the first one in the file. They are
544
+ * the same segment for a whole-file upload, where coverage is a prefix and the
545
+ * least distance belongs to the lowest `end`.
546
+ *
547
+ * `undefined` when there is nothing left to wait for.
548
+ */
549
+ function bytesUntilNextSegment(
550
+ plan: StreamPlan,
551
+ done: ReadonlySet<number>,
552
+ at: UploadProgressView,
553
+ ): number | undefined {
554
+ let nearest: number | undefined;
555
+ for (const segment of plan.segments) {
556
+ if (done.has(segment.index)) continue;
557
+ const missing = bytesUntilStored(segment, at);
558
+ if (nearest === undefined || missing < nearest) nearest = missing;
559
+ }
560
+ return nearest;
561
+ }
562
+
563
+ /**
564
+ * The bytes {@link segmentStored} still wants before it answers `true`.
565
+ *
566
+ * Derived from the same two readings that test uses, which is the whole point: a
567
+ * remainder taken from anything else predicts an arrival the readiness test will
568
+ * not agree with. Two ways for the window to be covered, so two candidates and the
569
+ * smaller wins — the PREFIX growing to `segment.end`, or the run that already
570
+ * holds `segment.start` growing to the same place. A run starting AFTER the
571
+ * segment does can never cover it alone (`rangesOf` merges the adjacent ones), so
572
+ * it is not a candidate at all and such a segment is left waiting on the prefix.
573
+ */
574
+ function bytesUntilStored(segment: Segment, at: UploadProgressView): number {
575
+ if (segmentStored(segment, at)) return 0;
576
+ let missing = segment.end - at.size;
577
+ for (const range of at.ranges ?? []) {
578
+ if (range.start > segment.start) continue;
579
+ missing = Math.min(missing, segment.end - range.end);
580
+ }
581
+ return missing;
582
+ }
583
+
584
+ /**
585
+ * How many bytes have landed in total, prefix and detached windows alike.
586
+ *
587
+ * `ranges` COVERS the prefix when it is present (it is every window the record
588
+ * holds, merged), so this is the larger of the two rather than their sum — adding
589
+ * them would double-count the prefix and make a stalled upload look like it was
590
+ * still growing, which is the one thing {@link MAX_IDLE_POLLS} must not be lied
591
+ * to about.
592
+ */
593
+ export function storedBytes(size: number, ranges: readonly UploadRange[] | undefined): number {
594
+ if (!ranges) return size;
595
+ return Math.max(
596
+ size,
597
+ ranges.reduce((total, range) => total + (range.end - range.start), 0),
598
+ );
599
+ }
600
+
601
+ /**
602
+ * Whether every byte of `segment` is stored, wherever in the file it landed.
603
+ *
604
+ * The prefix answers most of this — a whole-file upload has no windows and a
605
+ * finished one is covered end to end — and the `ranges` arm is what makes the
606
+ * streaming flow work against the browser's DEFAULT upload. That fan-out puts
607
+ * `UPLOAD_PART_CONCURRENCY` windows on the link at once, so they finish together
608
+ * and the prefix is zero until the last moment; measured on a deployed agent, a
609
+ * 27 MB recording at 0.9 MB/s reported `size: 0` for 45 of its 45 seconds. Read
610
+ * only the prefix and the run has nothing to do until the upload is over, which
611
+ * is the entire wait this flow exists to remove.
612
+ *
613
+ * A window has to be covered WHOLE by one run: `stepReadUpload` clamps to the run a
614
+ * read starts in, so a segment straddling a hole would come back short and be
615
+ * transcribed as a fragment. `rangesOf` merges adjacent windows, so a run really
616
+ * is a contiguous stretch and one containment test is the whole check.
617
+ */
618
+ export function segmentStored(segment: Segment, at: UploadProgressView): boolean {
619
+ if (segment.end <= at.size) return true;
620
+ return (at.ranges ?? []).some(
621
+ (range) => range.start <= segment.start && segment.end <= range.end,
622
+ );
623
+ }
624
+
625
+ /**
626
+ * Read the header and decide where to cut — from the DECLARED length.
627
+ *
628
+ * The one real difference from `splitRecording` next door, and it is a one-argument
629
+ * difference: that step passes the upload's own size, which for a file still
630
+ * arriving is only what has landed so far and would plan a fraction of the
631
+ * recording. `Number.POSITIVE_INFINITY` makes `parseWav` return the length the
632
+ * header DECLARES, which is known from the first 64 KB — so the whole plan exists
633
+ * before most of the audio does.
634
+ *
635
+ * A WAV declaring no length at all cannot be planned this way and is refused by
636
+ * name: there is nothing to compute a segment list from until the file has finished,
637
+ * which is what the classic flow is for.
638
+ */
639
+ export async function planStreamed(id: string): Promise<StreamPlan> {
640
+ const head = await stepReadUpload(id, { end: HEADER_PROBE_BYTES });
641
+ const format = fatalOnUnsupported(() =>
642
+ assertCuttable(parseWav(head.bytes, Number.POSITIVE_INFINITY)),
643
+ );
644
+ if (!Number.isFinite(format.dataEnd)) {
645
+ return throwFatalStepError(
646
+ new UnsupportedRecordingError(
647
+ "That WAV declares no data length, so its segments cannot be planned before it has " +
648
+ "finished uploading. Use the `transcribe` workflow, which stores the file first.",
649
+ ),
650
+ );
651
+ }
652
+ const segments = fatalOnUnsupported(() => planSegments(format));
653
+ await stepReport(
654
+ `Planned ${formatDuration(segments.at(-1)?.endMs ?? 0)} of audio as ` +
655
+ `${segments.length} ${plural(segments.length, "segment")} while it uploads.`,
656
+ );
657
+ return { format, segments };
658
+ }
659
+
660
+ /**
661
+ * How many segments a finished upload of `size` bytes really has.
662
+ *
663
+ * Not `plan.segments.length`: the plan came from the header's declared length, and a
664
+ * recording that came up short has segments that start past the end of the file.
665
+ * Counting those would leave the run waiting for audio nobody is going to send.
666
+ *
667
+ * Exported for its spec. It is the one piece of this flow's exit condition that is
668
+ * a pure function of journaled values, so it is the one a test can pin — and the
669
+ * failure it guards is a run that never ends rather than one that fails.
670
+ */
671
+ export function expectedSegments(plan: StreamPlan, size: number): number {
672
+ return plan.segments.filter((segment) => segment.start < size).length;
673
+ }
674
+
675
+ /**
676
+ * Give up on an upload that stopped arriving.
677
+ *
678
+ * A PLAIN throw, not `throwFatalStepError`: this is the BODY, and the
679
+ * fatal/retryable distinction belongs to a step — it is what tells the DevKit
680
+ * whether to run that step again. A body that throws fails the run, which is what
681
+ * should happen here, and dressing it up as a step error would suggest a retry
682
+ * policy with nothing to apply to.
683
+ */
684
+ function abandon(id: string, at: Pick<UploadProgressView, "size" | "stored">): never {
685
+ throw new Error(
686
+ `Gave up waiting for ${id}: ${at.stored} byte(s) stored, ${at.size} readable from the ` +
687
+ `start, and still incomplete. Nothing new arrived for ${MAX_IDLE_POLLS} polls — the ` +
688
+ "uploader stopped.",
689
+ );
690
+ }