@alexkroman1/aai-cli 15.1.0 → 16.0.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 (362) hide show
  1. package/README.md +8 -5
  2. package/bin.mjs +12 -3
  3. package/dist/_build-target-55dJisQ-.mjs +649 -0
  4. package/dist/_build-target.d.ts +105 -108
  5. package/dist/_deno-output.d.ts +23 -0
  6. package/dist/_deno-target.d.ts +73 -0
  7. package/dist/{_init-Bsi3DZNJ.mjs → _init-BzQbV8Zh.mjs} +3 -1
  8. package/dist/_modal-app.d.ts +77 -0
  9. package/dist/_modal-output.d.ts +31 -0
  10. package/dist/_modal-target.d.ts +64 -0
  11. package/dist/_target-bundle.d.ts +27 -0
  12. package/dist/_target-drain.d.ts +44 -0
  13. package/dist/_target-output.d.ts +63 -0
  14. package/dist/{_templates-CIlJ3Vay.mjs → _templates-CuP74F8D.mjs} +94 -4
  15. package/dist/_templates.d.ts +14 -1
  16. package/dist/_vercel-output.d.ts +4 -19
  17. package/dist/_vercel-target.d.ts +169 -0
  18. package/dist/{test-D032V2cA.mjs → _vitest-runner-AVR9VtXh.mjs} +28 -68
  19. package/dist/_vitest-runner.d.ts +154 -0
  20. package/dist/build-ButI2IKc.mjs +689 -0
  21. package/dist/build.d.ts +11 -0
  22. package/dist/cli.mjs +12 -11
  23. package/dist/{dev-Bx9gYBHM.mjs → dev-kodAY23K.mjs} +7 -1
  24. package/dist/{eval-B3I7FqN9.mjs → eval-DvoSz7SZ.mjs} +1 -1
  25. package/dist/{init-CQbj3ycf.mjs → init-D363Ls5u.mjs} +2 -2
  26. package/dist/scaffold/CLAUDE.md +185 -35
  27. package/dist/scaffold/package.json +4 -4
  28. package/dist/start.mjs +3 -1
  29. package/dist/{studio-C_zuRC_z.mjs → studio-CtRBVVFR.mjs} +1 -1
  30. package/dist/templates/briefing-desk/agent.eval.test.ts +34 -6
  31. package/dist/templates/briefing-desk/agent.test.ts +347 -55
  32. package/dist/templates/briefing-desk/agent.ts +12 -0
  33. package/dist/templates/briefing-desk/shared.ts +220 -31
  34. package/dist/templates/briefing-desk/slack.ts +108 -0
  35. package/dist/templates/briefing-desk/system-prompt.md +12 -2
  36. package/dist/templates/briefing-desk/tools/briefing_so_far.ts +15 -7
  37. package/dist/templates/briefing-desk/tools/research_topic.ts +20 -28
  38. package/dist/templates/briefing-desk/tools/send_briefing.ts +77 -0
  39. package/dist/templates/briefing-desk/tools/verify_claim.ts +60 -14
  40. package/dist/templates/call-audit/agent.eval.test.ts +5 -0
  41. package/dist/templates/call-audit/agent.test.ts +6 -1
  42. package/dist/templates/call-audit/agent.ts +10 -23
  43. package/dist/templates/call-audit/client.tsx +30 -55
  44. package/dist/templates/call-audit/guards.test.ts +233 -0
  45. package/dist/templates/call-audit/workflows/audit.ts +95 -16
  46. package/dist/templates/call-audit/workflows/ingest.ts +107 -88
  47. package/dist/templates/call-audit/workflows/media.ts +98 -7
  48. package/dist/templates/call-audit/workflows/summarize.ts +35 -31
  49. package/dist/templates/call-audit/workflows/sync-api.ts +15 -6
  50. package/dist/templates/code-interpreter/agent.eval.test.ts +104 -56
  51. package/dist/templates/code-interpreter/agent.test.ts +44 -56
  52. package/dist/templates/code-interpreter/system-prompt.md +1 -1
  53. package/dist/templates/dispatch-center/agent.eval.test.ts +61 -24
  54. package/dist/templates/dispatch-center/agent.test.ts +253 -48
  55. package/dist/templates/dispatch-center/agent.ts +28 -1
  56. package/dist/templates/dispatch-center/client.tsx +126 -201
  57. package/dist/templates/dispatch-center/events.ts +48 -0
  58. package/dist/templates/dispatch-center/shared.ts +42 -1
  59. package/dist/templates/dispatch-center/tools/incident_create.ts +3 -2
  60. package/dist/templates/dispatch-center/tools/incident_escalate.ts +2 -1
  61. package/dist/templates/dispatch-center/tools/ops_dashboard.ts +35 -15
  62. package/dist/templates/dispatch-center/tools/ops_run_scenario.ts +3 -1
  63. package/dist/templates/dispatch-center/tools/resources_dispatch.ts +2 -2
  64. package/dist/templates/executive-assistant/agent.eval.test.ts +233 -0
  65. package/dist/templates/executive-assistant/agent.test.ts +672 -0
  66. package/dist/templates/executive-assistant/agent.ts +50 -0
  67. package/dist/templates/executive-assistant/calendar.test.ts +198 -0
  68. package/dist/templates/executive-assistant/client.tsx +195 -0
  69. package/dist/templates/executive-assistant/inbox.ts +233 -0
  70. package/dist/templates/executive-assistant/meeting.ts +138 -0
  71. package/dist/templates/executive-assistant/nodes.ts +152 -0
  72. package/dist/templates/executive-assistant/prompts.ts +331 -0
  73. package/dist/templates/executive-assistant/review.ts +425 -0
  74. package/dist/templates/executive-assistant/shared.ts +490 -0
  75. package/dist/templates/executive-assistant/system-prompt.md +15 -0
  76. package/dist/templates/executive-assistant/tools/accept.ts +10 -0
  77. package/dist/templates/executive-assistant/tools/ask_question.ts +30 -0
  78. package/dist/templates/executive-assistant/tools/draft_reply.ts +67 -0
  79. package/dist/templates/executive-assistant/tools/edit.ts +10 -0
  80. package/dist/templates/executive-assistant/tools/ignore.ts +10 -0
  81. package/dist/templates/executive-assistant/tools/inbox_status.ts +27 -0
  82. package/dist/templates/executive-assistant/tools/meeting_assistant.ts +52 -0
  83. package/dist/templates/executive-assistant/tools/new_email.ts +50 -0
  84. package/dist/templates/executive-assistant/tools/open_email.ts +165 -0
  85. package/dist/templates/executive-assistant/tools/respond.ts +10 -0
  86. package/dist/templates/executive-assistant/tools/review_memory.ts +22 -0
  87. package/dist/templates/executive-assistant/tools/send_calendar_invite.ts +68 -0
  88. package/dist/templates/executive-assistant/tools/triage_inbox.ts +75 -0
  89. package/dist/templates/health-assistant/agent.test.ts +134 -15
  90. package/dist/templates/health-assistant/agent.ts +8 -1
  91. package/dist/templates/health-assistant/fda.test.ts +130 -0
  92. package/dist/templates/health-assistant/fda.ts +75 -16
  93. package/dist/templates/health-assistant/system-prompt.md +9 -0
  94. package/dist/templates/health-assistant/tools/check_drug_interaction.ts +5 -2
  95. package/dist/templates/health-assistant/tools/medication_lookup.ts +16 -11
  96. package/dist/templates/hiring-desk/agent.eval.test.ts +242 -0
  97. package/dist/templates/hiring-desk/agent.test.ts +1021 -0
  98. package/dist/templates/hiring-desk/agent.ts +38 -0
  99. package/dist/templates/hiring-desk/client.tsx +154 -0
  100. package/dist/templates/hiring-desk/crews.ts +432 -0
  101. package/dist/templates/hiring-desk/leads.json +86 -0
  102. package/dist/templates/hiring-desk/screening-lock.test.ts +77 -0
  103. package/dist/templates/hiring-desk/screening-lock.ts +51 -0
  104. package/dist/templates/hiring-desk/shared.ts +480 -0
  105. package/dist/templates/hiring-desk/system-prompt.md +21 -0
  106. package/dist/templates/hiring-desk/tools/candidate_details.ts +49 -0
  107. package/dist/templates/hiring-desk/tools/proceed_to_emails.ts +127 -0
  108. package/dist/templates/hiring-desk/tools/read_email.ts +50 -0
  109. package/dist/templates/hiring-desk/tools/rescore_with_feedback.ts +140 -0
  110. package/dist/templates/hiring-desk/tools/screen_candidates.ts +128 -0
  111. package/dist/templates/hiring-desk/tools/screening_status.ts +51 -0
  112. package/dist/templates/hotel-desk/agent.eval.test.ts +177 -0
  113. package/dist/templates/hotel-desk/agent.test.ts +1128 -0
  114. package/dist/templates/hotel-desk/agent.ts +63 -0
  115. package/dist/templates/hotel-desk/booking.ts +159 -0
  116. package/dist/templates/hotel-desk/card.ts +92 -0
  117. package/dist/templates/hotel-desk/catalogs.ts +219 -0
  118. package/dist/templates/hotel-desk/client.tsx +137 -0
  119. package/dist/templates/hotel-desk/concierge.ts +99 -0
  120. package/dist/templates/hotel-desk/desk-seams.test.ts +334 -0
  121. package/dist/templates/hotel-desk/desk.ts +224 -0
  122. package/dist/templates/hotel-desk/disputes.ts +216 -0
  123. package/dist/templates/hotel-desk/events.ts +79 -0
  124. package/dist/templates/hotel-desk/hotel.ts +412 -0
  125. package/dist/templates/hotel-desk/policies.ts +209 -0
  126. package/dist/templates/hotel-desk/records.ts +384 -0
  127. package/dist/templates/hotel-desk/restaurant.ts +147 -0
  128. package/dist/templates/hotel-desk/seed.ts +955 -0
  129. package/dist/templates/hotel-desk/shared.ts +354 -0
  130. package/dist/templates/hotel-desk/system-prompt.md +76 -0
  131. package/dist/templates/hotel-desk/tools/abandon_booking.ts +30 -0
  132. package/dist/templates/hotel-desk/tools/add_to_waitlist.ts +41 -0
  133. package/dist/templates/hotel-desk/tools/book_airport_car.ts +57 -0
  134. package/dist/templates/hotel-desk/tools/book_business_center.ts +44 -0
  135. package/dist/templates/hotel-desk/tools/book_spa_appointment.ts +39 -0
  136. package/dist/templates/hotel-desk/tools/book_tour.ts +35 -0
  137. package/dist/templates/hotel-desk/tools/cancel_restaurant_reservation.ts +25 -0
  138. package/dist/templates/hotel-desk/tools/cancel_room_booking.ts +63 -0
  139. package/dist/templates/hotel-desk/tools/check_restaurant_availability.ts +24 -0
  140. package/dist/templates/hotel-desk/tools/check_room_availability.ts +40 -0
  141. package/dist/templates/hotel-desk/tools/choose_room.ts +93 -0
  142. package/dist/templates/hotel-desk/tools/confirm_booking.ts +153 -0
  143. package/dist/templates/hotel-desk/tools/dispatch_emergency.ts +61 -0
  144. package/dist/templates/hotel-desk/tools/dispute_charge.ts +90 -0
  145. package/dist/templates/hotel-desk/tools/flag_late_arrival.ts +26 -0
  146. package/dist/templates/hotel-desk/tools/lookup_booking.ts +48 -0
  147. package/dist/templates/hotel-desk/tools/lookup_guest_history.ts +28 -0
  148. package/dist/templates/hotel-desk/tools/lookup_invoice.ts +26 -0
  149. package/dist/templates/hotel-desk/tools/lookup_policy.ts +20 -0
  150. package/dist/templates/hotel-desk/tools/lookup_restaurant_reservation.ts +27 -0
  151. package/dist/templates/hotel-desk/tools/modify_restaurant_reservation.ts +75 -0
  152. package/dist/templates/hotel-desk/tools/order_flowers.ts +40 -0
  153. package/dist/templates/hotel-desk/tools/record_card.ts +46 -0
  154. package/dist/templates/hotel-desk/tools/record_followup.ts +50 -0
  155. package/dist/templates/hotel-desk/tools/record_group_inquiry.ts +44 -0
  156. package/dist/templates/hotel-desk/tools/record_guest_details.ts +71 -0
  157. package/dist/templates/hotel-desk/tools/reinstate_booking.ts +65 -0
  158. package/dist/templates/hotel-desk/tools/request_flight_reconfirmation.ts +54 -0
  159. package/dist/templates/hotel-desk/tools/resend_confirmation.ts +39 -0
  160. package/dist/templates/hotel-desk/tools/reserve_table.ts +87 -0
  161. package/dist/templates/hotel-desk/tools/resolve_room_conflict.ts +48 -0
  162. package/dist/templates/hotel-desk/tools/schedule_wakeup_call.ts +48 -0
  163. package/dist/templates/hotel-desk/tools/set_do_not_disturb.ts +28 -0
  164. package/dist/templates/hotel-desk/tools/set_extras.ts +51 -0
  165. package/dist/templates/hotel-desk/tools/set_stay.ts +97 -0
  166. package/dist/templates/hotel-desk/tools/start_booking_modification.ts +57 -0
  167. package/dist/templates/hotel-desk/tools/start_room_booking.ts +49 -0
  168. package/dist/templates/hotel-desk/tools/take_guest_message.ts +71 -0
  169. package/dist/templates/hotel-desk/tools/transfer_call.ts +47 -0
  170. package/dist/templates/hotel-desk/tools/update_card.ts +45 -0
  171. package/dist/templates/hotel-desk/tools/verify_booking.ts +95 -0
  172. package/dist/templates/infocom-adventure/agent.eval.test.ts +33 -1
  173. package/dist/templates/infocom-adventure/agent.test.ts +207 -52
  174. package/dist/templates/infocom-adventure/agent.ts +14 -3
  175. package/dist/templates/infocom-adventure/client.tsx +138 -176
  176. package/dist/templates/infocom-adventure/shared.ts +126 -6
  177. package/dist/templates/infocom-adventure/system-prompt.md +4 -4
  178. package/dist/templates/infocom-adventure/tools/game_state_drop.ts +20 -4
  179. package/dist/templates/infocom-adventure/tools/game_state_get.ts +6 -5
  180. package/dist/templates/infocom-adventure/tools/game_state_score.ts +9 -3
  181. package/dist/templates/link-digest/agent.eval.test.ts +8 -0
  182. package/dist/templates/link-digest/agent.test.ts +285 -29
  183. package/dist/templates/link-digest/agent.ts +9 -0
  184. package/dist/templates/link-digest/api-client.ts +144 -0
  185. package/dist/templates/link-digest/client.tsx +11 -30
  186. package/dist/templates/link-digest/workflows/digest.ts +72 -24
  187. package/dist/templates/night-owl/agent.eval.test.ts +55 -40
  188. package/dist/templates/night-owl/agent.test.ts +146 -12
  189. package/dist/templates/night-owl/client.tsx +50 -17
  190. package/dist/templates/night-owl/shared.ts +33 -2
  191. package/dist/templates/night-owl/system-prompt.md +3 -0
  192. package/dist/templates/night-owl/tools/recommend.ts +4 -1
  193. package/dist/templates/night-owl/tools/revisit.ts +49 -0
  194. package/dist/templates/pipeline-simple/agent.eval.test.ts +7 -6
  195. package/dist/templates/pipeline-simple/agent.test.ts +48 -91
  196. package/dist/templates/pipeline-simple/modes.test.ts +151 -0
  197. package/dist/templates/pipeline-simple/stages.test.ts +332 -0
  198. package/dist/templates/pizza-ordering/agent.test.ts +94 -38
  199. package/dist/templates/pizza-ordering/client.tsx +10 -5
  200. package/dist/templates/pizza-ordering/shared.ts +65 -6
  201. package/dist/templates/pizza-ordering/tools/add_pizza.ts +2 -7
  202. package/dist/templates/pizza-ordering/tools/place_order.ts +9 -6
  203. package/dist/templates/pizza-ordering/tools/remove_pizza.ts +6 -11
  204. package/dist/templates/pizza-ordering/tools/update_pizza.ts +8 -9
  205. package/dist/templates/pizza-ordering/tools/view_order.ts +2 -3
  206. package/dist/templates/plan-and-execute/agent.eval.test.ts +14 -6
  207. package/dist/templates/plan-and-execute/agent.test.ts +300 -113
  208. package/dist/templates/plan-and-execute/client.tsx +18 -7
  209. package/dist/templates/plan-and-execute/procedure.ts +162 -64
  210. package/dist/templates/plan-and-execute/prompts.ts +51 -15
  211. package/dist/templates/plan-and-execute/shared.ts +151 -45
  212. package/dist/templates/plan-and-execute/tools/plan_status.ts +15 -6
  213. package/dist/templates/plan-and-execute/tools/revise_plan.ts +2 -2
  214. package/dist/templates/plan-and-execute/tools/start_plan.ts +2 -2
  215. package/dist/templates/plan-and-execute/tools/work_next_step.ts +15 -13
  216. package/dist/templates/podcast-digest/agent.eval.test.ts +12 -7
  217. package/dist/templates/podcast-digest/agent.test.ts +126 -51
  218. package/dist/templates/podcast-digest/client.tsx +104 -68
  219. package/dist/templates/podcast-digest/workflows/digest.ts +71 -48
  220. package/dist/templates/podcast-digest/workflows/feeds.ts +5 -7
  221. package/dist/templates/podcast-digest/workflows/slack.ts +82 -17
  222. package/dist/templates/recap-workflow/agent.eval.test.ts +193 -209
  223. package/dist/templates/recap-workflow/agent.test.ts +207 -26
  224. package/dist/templates/recap-workflow/tools/recap_status.ts +2 -2
  225. package/dist/templates/recap-workflow/workflows/recap.ts +39 -28
  226. package/dist/templates/redline/agent.eval.test.ts +40 -3
  227. package/dist/templates/redline/agent.test.ts +216 -6
  228. package/dist/templates/redline/agent.ts +54 -34
  229. package/dist/templates/redline/client.tsx +82 -126
  230. package/dist/templates/redline/form.ts +74 -0
  231. package/dist/templates/redline/workflows/prompts.ts +3 -3
  232. package/dist/templates/redline/workflows/redline.ts +73 -4
  233. package/dist/templates/research-workflow/agent.eval.test.ts +152 -150
  234. package/dist/templates/research-workflow/agent.test.ts +436 -126
  235. package/dist/templates/research-workflow/agent.ts +20 -5
  236. package/dist/templates/research-workflow/tools/file_it_now.ts +11 -1
  237. package/dist/templates/research-workflow/tools/research_status.ts +39 -4
  238. package/dist/templates/research-workflow/workflows/filing.ts +164 -0
  239. package/dist/templates/research-workflow/workflows/notes.ts +69 -0
  240. package/dist/templates/research-workflow/workflows/prompts.ts +45 -31
  241. package/dist/templates/research-workflow/workflows/research.ts +227 -280
  242. package/dist/templates/research-workflow/workflows/review.ts +43 -0
  243. package/dist/templates/retail/address.ts +29 -35
  244. package/dist/templates/retail/agent.eval.test.ts +36 -16
  245. package/dist/templates/retail/agent.test.ts +104 -26
  246. package/dist/templates/retail/agent.ts +12 -0
  247. package/dist/templates/retail/cancel.ts +39 -42
  248. package/dist/templates/retail/client.tsx +111 -176
  249. package/dist/templates/retail/payment.ts +38 -43
  250. package/dist/templates/retail/pending.test.ts +16 -8
  251. package/dist/templates/retail/registry.test.ts +108 -49
  252. package/dist/templates/retail/resolve.test.ts +2 -63
  253. package/dist/templates/retail/resolve.ts +16 -56
  254. package/dist/templates/retail/returns.ts +53 -54
  255. package/dist/templates/retail/seed.test.ts +2 -1
  256. package/dist/templates/retail/shared.ts +58 -14
  257. package/dist/templates/retail/store.test.ts +40 -29
  258. package/dist/templates/retail/store.ts +60 -23
  259. package/dist/templates/retail/swap.ts +78 -81
  260. package/dist/templates/retail/tools/find_user_id_by_name_zip.ts +2 -1
  261. package/dist/templates/roadside-assist/agent.eval.test.ts +164 -0
  262. package/dist/templates/roadside-assist/agent.test.ts +617 -0
  263. package/dist/templates/roadside-assist/agent.ts +85 -0
  264. package/dist/templates/roadside-assist/call.ts +237 -0
  265. package/dist/templates/roadside-assist/events.ts +92 -0
  266. package/dist/templates/roadside-assist/shared.ts +334 -0
  267. package/dist/templates/roadside-assist/system-prompt.md +37 -0
  268. package/dist/templates/roadside-assist/tools/acknowledge_disclosure.ts +47 -0
  269. package/dist/templates/roadside-assist/tools/dispatch_truck.ts +148 -0
  270. package/dist/templates/roadside-assist/tools/job_status.ts +38 -0
  271. package/dist/templates/roadside-assist/tools/lookup_coverage.ts +72 -0
  272. package/dist/templates/roadside-assist/tools/report_location.ts +79 -0
  273. package/dist/templates/roadside-assist/tools/service_disclosure.ts +45 -0
  274. package/dist/templates/roadside-assist/yard.test.ts +158 -0
  275. package/dist/templates/roadside-assist/yard.ts +183 -0
  276. package/dist/templates/simple/agent.eval.test.ts +4 -1
  277. package/dist/templates/simple/agent.test.ts +54 -31
  278. package/dist/templates/solo-rpg/agent.eval.test.ts +19 -11
  279. package/dist/templates/solo-rpg/agent.test.ts +402 -175
  280. package/dist/templates/solo-rpg/agent.ts +14 -3
  281. package/dist/templates/solo-rpg/client.tsx +10 -10
  282. package/dist/templates/solo-rpg/shared.ts +198 -79
  283. package/dist/templates/solo-rpg/tools/action_roll.ts +7 -3
  284. package/dist/templates/solo-rpg/tools/burn_momentum.ts +16 -8
  285. package/dist/templates/solo-rpg/tools/oracle.ts +7 -7
  286. package/dist/templates/solo-rpg/tools/setup_character.ts +5 -5
  287. package/dist/templates/solo-rpg/tools/update_state.ts +29 -18
  288. package/dist/templates/spoken-summary/agent.test.ts +70 -15
  289. package/dist/templates/spoken-summary/agent.ts +25 -21
  290. package/dist/templates/spoken-summary/client.tsx +68 -88
  291. package/dist/templates/spoken-summary/workflows/summarize.ts +26 -8
  292. package/dist/templates/support-line/agent.test.ts +167 -36
  293. package/dist/templates/support-line/client.tsx +21 -9
  294. package/dist/templates/support-line/nodes.ts +74 -32
  295. package/dist/templates/support-line/procedure.ts +66 -21
  296. package/dist/templates/support-line/prompts.ts +9 -0
  297. package/dist/templates/support-line/shared.ts +55 -17
  298. package/dist/templates/support-line/tools/answer_question.ts +14 -14
  299. package/dist/templates/transcription-workflow/agent.test.ts +135 -13
  300. package/dist/templates/transcription-workflow/client.tsx +30 -23
  301. package/dist/templates/transcription-workflow/recover.test.ts +93 -12
  302. package/dist/templates/transcription-workflow/recover.ts +29 -5
  303. package/dist/templates/transcription-workflow/run-panel.tsx +40 -51
  304. package/dist/templates/transcription-workflow/workflows/normalize.ts +125 -24
  305. package/dist/templates/transcription-workflow/workflows/stream.ts +4 -1
  306. package/dist/templates/transcription-workflow/workflows/transcribe.ts +7 -5
  307. package/dist/templates/transcription-workflow/workflows/wav.ts +42 -117
  308. package/dist/templates/travel-concierge/agent.eval.test.ts +6 -4
  309. package/dist/templates/travel-concierge/agent.test.ts +209 -40
  310. package/dist/templates/travel-concierge/agent.ts +24 -4
  311. package/dist/templates/travel-concierge/call-events.ts +80 -0
  312. package/dist/templates/travel-concierge/client.tsx +3 -2
  313. package/dist/templates/travel-concierge/routing.ts +5 -7
  314. package/dist/templates/travel-concierge/shared.ts +202 -41
  315. package/dist/templates/travel-concierge/tools/book_car_rental.ts +2 -4
  316. package/dist/templates/travel-concierge/tools/book_excursion.ts +2 -4
  317. package/dist/templates/travel-concierge/tools/book_hotel.ts +2 -4
  318. package/dist/templates/travel-concierge/tools/cancel_ticket.ts +6 -4
  319. package/dist/templates/travel-concierge/tools/search_car_rentals.ts +3 -5
  320. package/dist/templates/travel-concierge/tools/search_excursions.ts +3 -5
  321. package/dist/templates/travel-concierge/tools/search_flights.ts +20 -9
  322. package/dist/templates/travel-concierge/tools/search_hotels.ts +3 -5
  323. package/dist/templates/travel-concierge/tools/update_ticket.ts +2 -4
  324. package/dist/templates/web-researcher/agent.eval.test.ts +3 -6
  325. package/dist/templates/web-researcher/agent.test.ts +102 -65
  326. package/dist/templates/web-researcher/agent.ts +93 -1
  327. package/dist/templates/web-researcher/system-prompt.md +7 -1
  328. package/dist/templates/word-wrangler/agent.eval.test.ts +157 -0
  329. package/dist/templates/word-wrangler/agent.test.ts +432 -0
  330. package/dist/templates/word-wrangler/agent.ts +35 -0
  331. package/dist/templates/word-wrangler/client.tsx +211 -0
  332. package/dist/templates/word-wrangler/game.ts +107 -0
  333. package/dist/templates/word-wrangler/guess.ts +63 -0
  334. package/dist/templates/word-wrangler/player.ts +68 -0
  335. package/dist/templates/word-wrangler/shared.ts +263 -0
  336. package/dist/templates/word-wrangler/system-prompt.md +15 -0
  337. package/dist/templates/word-wrangler/tools/final_score.ts +37 -0
  338. package/dist/templates/word-wrangler/tools/relay_description.ts +137 -0
  339. package/dist/templates/word-wrangler/tools/repeat_word.ts +19 -0
  340. package/dist/templates/word-wrangler/tools/skip_word.ts +31 -0
  341. package/dist/templates/word-wrangler/tools/start_game.ts +47 -0
  342. package/dist/templates/word-wrangler/words.ts +278 -0
  343. package/dist/test-Cllnx81G.mjs +83 -0
  344. package/dist/test.d.ts +9 -114
  345. package/package.json +5 -5
  346. package/dist/build-BhEaxBPu.mjs +0 -481
  347. package/dist/templates/embedded-assets/agent.eval.test.ts +0 -130
  348. package/dist/templates/embedded-assets/agent.test.ts +0 -79
  349. package/dist/templates/embedded-assets/agent.ts +0 -7
  350. package/dist/templates/embedded-assets/knowledge.json +0 -20
  351. package/dist/templates/embedded-assets/shared.ts +0 -17
  352. package/dist/templates/embedded-assets/system-prompt.md +0 -13
  353. package/dist/templates/embedded-assets/tools/list_topics.ts +0 -9
  354. package/dist/templates/embedded-assets/tools/search_knowledge.ts +0 -26
  355. package/dist/templates/math-buddy/agent.eval.test.ts +0 -128
  356. package/dist/templates/math-buddy/agent.test.ts +0 -126
  357. package/dist/templates/math-buddy/agent.ts +0 -15
  358. package/dist/templates/math-buddy/system-prompt.md +0 -12
  359. package/dist/templates/personal-finance/agent.eval.test.ts +0 -149
  360. package/dist/templates/personal-finance/agent.test.ts +0 -127
  361. package/dist/templates/personal-finance/agent.ts +0 -8
  362. package/dist/templates/personal-finance/system-prompt.md +0 -21
@@ -52,7 +52,15 @@
52
52
  * not charged for the remaining seven.
53
53
  */
54
54
 
55
- import { type GenerateFn, omitUndefined, procedure } from "@alexkroman1/aai";
55
+ import {
56
+ DEFAULT_GUARDRAIL_MAX_RETRIES,
57
+ type GenerateFn,
58
+ type GuardrailVerdict,
59
+ omitUndefined,
60
+ type Procedure,
61
+ type ProcedureRunOptions,
62
+ procedure,
63
+ } from "@alexkroman1/aai";
56
64
  import { assign, fromPromise, setup } from "xstate";
57
65
  import {
58
66
  generateAnswer,
@@ -60,15 +68,22 @@ import {
60
68
  gradeGrounded,
61
69
  gradeUseful,
62
70
  transformQuery,
63
- type Verdict,
64
71
  } from "./nodes.ts";
65
72
  import type { AnswerTrace, Doc, GradedDoc, TraceStep } from "./shared.ts";
66
73
  import { retrieve } from "./shared.ts";
67
74
 
68
75
  /** Retrieve-and-answer attempts, i.e. one query rewrite. */
69
76
  export const MAX_ATTEMPTS = 2;
70
- /** Regenerations after a "not grounded" verdict, within one attempt. */
71
- export const MAX_REGENERATIONS = 1;
77
+ /**
78
+ * Regenerations after a "not grounded" verdict, within one attempt.
79
+ *
80
+ * The SDK's own number, not a coincidence: `DEFAULT_GUARDRAIL_MAX_RETRIES` is
81
+ * how many times `subagent({ guardrail })` re-asks after a verdict rejects an
82
+ * answer, and that is exactly what this counter bounds — the same judge, the
83
+ * same retry, one layer down. Taking it from the SDK is how the two stay one
84
+ * decision instead of two constants that drift.
85
+ */
86
+ export const MAX_REGENERATIONS = DEFAULT_GUARDRAIL_MAX_RETRIES;
72
87
 
73
88
  /**
74
89
  * What the machine carries: the trace it is building, plus the two counters the
@@ -80,9 +95,12 @@ export const MAX_REGENERATIONS = 1;
80
95
  */
81
96
  interface Ctx extends AnswerTrace {
82
97
  generate: GenerateFn;
83
- /** 1-based, bounded by {@link MAX_ATTEMPTS}. */
84
- attempt: number;
85
- /** Regenerations spent WITHIN this attempt; reset by `transform_query`. */
98
+ /**
99
+ * Regenerations spent WITHIN this attempt; reset by `transform_query`.
100
+ *
101
+ * There is no separate attempt counter: an attempt is a rewrite plus one, and
102
+ * `rewrites` (which the trace reports anyway) is the one place it is kept.
103
+ */
86
104
  regenerations: number;
87
105
  /** What this attempt's query retrieved, before grading. */
88
106
  retrieved: Doc[];
@@ -111,6 +129,24 @@ function noteFrom(node: string, detail: (context: Ctx) => string) {
111
129
  };
112
130
  }
113
131
 
132
+ /**
133
+ * The same again, for a grader's own words.
134
+ *
135
+ * A rejecting {@link GuardrailVerdict} IS the complaint, so the trace says what
136
+ * the grader objected to rather than a constant. It reads the DONE event, and
137
+ * the parameter is typed to the one field it needs — a done event is assignable
138
+ * to `{ output }`, so the narrowing xstate gives the transition survives.
139
+ */
140
+ function noteVerdict(node: string, prefix: string) {
141
+ return {
142
+ type: "note" as const,
143
+ params: ({ event }: { event: { output: GuardrailVerdict } }): NoteParams => ({
144
+ node,
145
+ detail: event.output === true ? prefix : `${prefix}: ${event.output}`,
146
+ }),
147
+ };
148
+ }
149
+
114
150
  interface NoteParams {
115
151
  node: string;
116
152
  detail: string;
@@ -132,11 +168,11 @@ const machine = setup({
132
168
  await generateAnswer(input.ctx.generate, input.ctx.question, input.ctx.relevant),
133
169
  ),
134
170
  gradeGrounded: fromPromise(
135
- async ({ input }: { input: { ctx: Ctx } }): Promise<Verdict> =>
171
+ async ({ input }: { input: { ctx: Ctx } }): Promise<GuardrailVerdict> =>
136
172
  await gradeGrounded(input.ctx.generate, input.ctx.relevant, input.ctx.answer ?? ""),
137
173
  ),
138
174
  gradeUseful: fromPromise(
139
- async ({ input }: { input: { ctx: Ctx } }): Promise<Verdict> =>
175
+ async ({ input }: { input: { ctx: Ctx } }): Promise<GuardrailVerdict> =>
140
176
  await gradeUseful(input.ctx.generate, input.ctx.question, input.ctx.answer ?? ""),
141
177
  ),
142
178
  transformQuery: fromPromise(
@@ -155,7 +191,7 @@ const machine = setup({
155
191
  guards: {
156
192
  /** Their `decide_to_generate`: is there anything to answer FROM? */
157
193
  hasRelevant: ({ context }) => context.relevant.length > 0,
158
- canRetry: ({ context }) => context.attempt < MAX_ATTEMPTS,
194
+ canRetry: ({ context }) => context.rewrites + 1 < MAX_ATTEMPTS,
159
195
  canRegenerate: ({ context }) => context.regenerations < MAX_REGENERATIONS,
160
196
  },
161
197
  // A grader's verdict is read INLINE (`event.output.pass`) rather than through
@@ -175,7 +211,6 @@ const machine = setup({
175
211
  grounded: null,
176
212
  useful: null,
177
213
  exhausted: false,
178
- attempt: 1,
179
214
  regenerations: 0,
180
215
  retrieved: [],
181
216
  relevant: [],
@@ -275,7 +310,7 @@ const machine = setup({
275
310
  input: ({ context }) => ({ ctx: context }),
276
311
  onDone: [
277
312
  {
278
- guard: ({ event }) => event.output.pass,
313
+ guard: ({ event }) => event.output === true,
279
314
  target: "gradeUseful",
280
315
  actions: [
281
316
  assign({ grounded: () => true }),
@@ -286,7 +321,7 @@ const machine = setup({
286
321
  guard: "canRegenerate",
287
322
  target: "generate",
288
323
  actions: [
289
- noteAt("grade_generation_v_documents", "not grounded"),
324
+ noteVerdict("grade_generation_v_documents", "not grounded"),
290
325
  assign({ regenerations: ({ context }) => context.regenerations + 1 }),
291
326
  ],
292
327
  },
@@ -294,7 +329,7 @@ const machine = setup({
294
329
  target: "ungrounded",
295
330
  actions: [
296
331
  assign({ grounded: () => false, answer: () => null, exhausted: () => true }),
297
- noteAt("grade_generation_v_documents", "still not grounded"),
332
+ noteVerdict("grade_generation_v_documents", "still not grounded"),
298
333
  ],
299
334
  },
300
335
  ],
@@ -312,7 +347,7 @@ const machine = setup({
312
347
  input: ({ context }) => ({ ctx: context }),
313
348
  onDone: [
314
349
  {
315
- guard: ({ event }) => event.output.pass,
350
+ guard: ({ event }) => event.output === true,
316
351
  target: "done",
317
352
  actions: [
318
353
  assign({ useful: () => true }),
@@ -324,14 +359,14 @@ const machine = setup({
324
359
  target: "transformQuery",
325
360
  actions: [
326
361
  assign({ useful: () => false }),
327
- noteAt("grade_generation_v_question", "not useful"),
362
+ noteVerdict("grade_generation_v_question", "not useful"),
328
363
  ],
329
364
  },
330
365
  {
331
366
  target: "exhausted",
332
367
  actions: [
333
368
  assign({ useful: () => false, exhausted: () => true }),
334
- noteAt("grade_generation_v_question", "not useful, and no attempts left"),
369
+ noteVerdict("grade_generation_v_question", "not useful, and no attempts left"),
335
370
  ],
336
371
  },
337
372
  ],
@@ -353,7 +388,6 @@ const machine = setup({
353
388
  assign({
354
389
  query: ({ event }) => event.output,
355
390
  rewrites: ({ context }) => context.rewrites + 1,
356
- attempt: ({ context }) => context.attempt + 1,
357
391
  regenerations: () => 0,
358
392
  answer: () => null,
359
393
  grounded: () => null,
@@ -382,7 +416,15 @@ const machine = setup({
382
416
  }),
383
417
  });
384
418
 
385
- const rag = procedure(machine);
419
+ /**
420
+ * The graph, ready to run.
421
+ *
422
+ * Annotated with the SDK's own `Procedure<M>` because that interface is what
423
+ * `procedure()` adds to a machine and the only reason this template reaches for
424
+ * it: `run(input, options)` awaits a final state and answers the machine's
425
+ * `output`, and `machine` is kept so a caller can still inspect what it drives.
426
+ */
427
+ const rag: Procedure<typeof machine> = procedure(machine);
386
428
 
387
429
  /**
388
430
  * Run the procedure for one caller question.
@@ -402,6 +444,9 @@ export async function runCorrectiveRag(
402
444
  ): Promise<AnswerTrace> {
403
445
  // `omitUndefined` rather than a conditional spread: `ProcedureRunOptions.signal`
404
446
  // is optional, and under `exactOptionalPropertyTypes` a present-and-undefined
405
- // key is not the same as an absent one.
406
- return await rag.run({ generate, question }, omitUndefined({ signal }));
447
+ // key is not the same as an absent one. The annotation is what makes that
448
+ // sentence checked rather than asserted — drop the `omitUndefined` and this
449
+ // line stops compiling.
450
+ const options: ProcedureRunOptions = omitUndefined({ signal });
451
+ return await rag.run({ generate, question }, options);
407
452
  }
@@ -40,6 +40,15 @@ export const binaryScore = z.object({
40
40
  reason: z.string().max(200).describe("One short sentence of justification"),
41
41
  });
42
42
 
43
+ /**
44
+ * What a grader call comes back with, as `nodes.ts` names it.
45
+ *
46
+ * Inferred from the schema rather than written out, so the two cannot drift —
47
+ * and exported because it is the type argument the schema overload of
48
+ * `ctx.generate` resolves to (`GenerateObjectResult<BinaryScore>`).
49
+ */
50
+ export type BinaryScore = z.infer<typeof binaryScore>;
51
+
43
52
  /** Their `retrieval_grader`: deliberately NOT a stringent test. */
44
53
  export const DOC_GRADER_SYSTEM = [
45
54
  "You are a grader assessing whether a retrieved support document is relevant",
@@ -17,7 +17,12 @@
17
17
  * "evening slowdown congestion peak time" and finds D10.
18
18
  */
19
19
 
20
- import { type DeepReadonly, pushCapped, sessionSlot } from "@alexkroman1/aai";
20
+ import {
21
+ type DeepReadonly,
22
+ type SlotCaps,
23
+ type StateProjection,
24
+ sessionSlot,
25
+ } from "@alexkroman1/aai";
21
26
  import knowledge from "./knowledge.json" with { type: "json" };
22
27
 
23
28
  export interface Doc {
@@ -92,13 +97,24 @@ function tokenize(text: string): string[] {
92
97
  .filter((word) => word.length > 2 && !STOPWORDS.has(word));
93
98
  }
94
99
 
95
- /** Term → how many documents contain it. Computed once at module load. */
100
+ /**
101
+ * Term → how many documents contain it, and per document, term → how often it
102
+ * occurs. Both computed once at module load, in the one pass that has to visit
103
+ * every token anyway.
104
+ *
105
+ * The per-document COUNTS are what scoring needs. Keeping the raw token list
106
+ * instead made `retrieve` walk it end to end once per query term, allocating a
107
+ * filtered array each time, to recover a number this loop already had.
108
+ */
96
109
  const DOC_FREQUENCY = new Map<string, number>();
97
- const DOC_TOKENS = new Map<string, string[]>();
110
+ const DOC_TERM_COUNTS = new Map<string, Map<string, number>>();
98
111
  for (const doc of DOCS) {
99
- const tokens = tokenize(`${doc.title} ${doc.topic} ${doc.text}`);
100
- DOC_TOKENS.set(doc.id, tokens);
101
- for (const term of new Set(tokens)) {
112
+ const counts = new Map<string, number>();
113
+ for (const token of tokenize(`${doc.title} ${doc.topic} ${doc.text}`)) {
114
+ counts.set(token, (counts.get(token) ?? 0) + 1);
115
+ }
116
+ DOC_TERM_COUNTS.set(doc.id, counts);
117
+ for (const term of counts.keys()) {
102
118
  DOC_FREQUENCY.set(term, (DOC_FREQUENCY.get(term) ?? 0) + 1);
103
119
  }
104
120
  }
@@ -123,10 +139,10 @@ export function retrieve(query: string, k: number = RETRIEVE_K): Retrieved[] {
123
139
  if (terms.size === 0) return [];
124
140
  const scored: Retrieved[] = [];
125
141
  for (const doc of DOCS) {
126
- const tokens = DOC_TOKENS.get(doc.id) ?? [];
142
+ const counts = DOC_TERM_COUNTS.get(doc.id);
127
143
  let score = 0;
128
144
  for (const term of terms) {
129
- const hits = tokens.filter((token) => token === term).length;
145
+ const hits = counts?.get(term) ?? 0;
130
146
  if (hits === 0) continue;
131
147
  const frequency = DOC_FREQUENCY.get(term) ?? 1;
132
148
  // Diminishing returns per repeat, so one long document cannot win on
@@ -192,13 +208,30 @@ export interface SupportState {
192
208
  ticketCounter: number;
193
209
  }
194
210
 
195
- export const MAX_ASKED = 20;
196
-
197
211
  export function emptySupportState(): SupportState {
198
212
  return { trace: null, asked: [], ticket: null, ticketCounter: 0 };
199
213
  }
200
214
 
201
- export const supportSlot = sessionSlot("support", emptySupportState);
215
+ /**
216
+ * How many of this call's questions the slot keeps.
217
+ *
218
+ * Exported because a spec reads it — the bound is declared once, here, and the
219
+ * test that the twenty-first question drops the first must not restate the
220
+ * number.
221
+ */
222
+ export const ASKED_CAP = 20;
223
+
224
+ /**
225
+ * The growth bound, named and TYPED.
226
+ *
227
+ * `SlotCaps<SupportState>` admits only the state's array-valued keys, so a cap
228
+ * on `ticketCounter` or a mistyped `askedd` is a compile error at the
229
+ * declaration rather than a bound that silently caps nothing. `asked` rides in
230
+ * every `syncState` frame, which is why it is the field that needs one.
231
+ */
232
+ const caps: SlotCaps<SupportState> = { asked: ASKED_CAP };
233
+
234
+ export const supportSlot = sessionSlot("support", emptySupportState, { caps });
202
235
 
203
236
  /**
204
237
  * The call as a READ hands it out: deep-frozen, and typed to say so.
@@ -211,10 +244,6 @@ export const supportSlot = sessionSlot("support", emptySupportState);
211
244
  */
212
245
  export type FrozenSupportState = DeepReadonly<SupportState>;
213
246
 
214
- export function recordQuestion(state: SupportState, question: string): void {
215
- pushCapped(state.asked, question, MAX_ASKED);
216
- }
217
-
218
247
  // ─── The projection ──────────────────────────────────────────────────────────
219
248
 
220
249
  export interface SupportView {
@@ -239,5 +268,14 @@ export function supportView(state: FrozenSupportState): SupportView {
239
268
  };
240
269
  }
241
270
 
242
- /** The projection BOTH ends use: `syncState` on the agent, `useAgentState` in the client. */
243
- export const supportProjection = supportSlot.projection(supportView);
271
+ /**
272
+ * The projection BOTH ends use: `syncState` on the agent, `useAgentState` in
273
+ * the client.
274
+ *
275
+ * Annotated with `StateProjection<SupportView>` because this export IS the
276
+ * contract between the two — it is the only thing `agent.ts` and `client.tsx`
277
+ * share, and naming what a projection is (a callable carrying the slot's `key`
278
+ * and `create`) is what tells a reader why passing it to `useAgentState`
279
+ * derives the pre-first-frame value for free.
280
+ */
281
+ export const supportProjection: StateProjection<SupportView> = supportSlot.projection(supportView);
@@ -1,17 +1,14 @@
1
1
  import { errorMessage, ProcedureNotFinishedError, tool, toolFailure } from "@alexkroman1/aai";
2
2
  import { z } from "zod";
3
3
  import { runCorrectiveRag } from "../procedure.ts";
4
- import { recordQuestion, supportSlot } from "../shared.ts";
4
+ import { supportSlot } from "../shared.ts";
5
5
 
6
6
  /**
7
- * How long the whole corrective loop may run before it gives up.
8
- *
9
- * Under the runtime's own per-tool deadline (`TOOL_EXECUTION_TIMEOUT_MS`, 30s)
10
- * with room for this tool's own bookkeeping, and written as a literal because
11
- * that constant is on `@alexkroman1/aai/internal` — a subpath a template may
12
- * not import. If the runtime's default ever moves, this is the number to move.
7
+ * Room left under the deadline for this tool's own bookkeeping: unwinding the
8
+ * graph, writing the trace to the slot, and composing the sentence the caller
9
+ * hears. Subtracted from `ctx.deadlineAt`, never from a copy of the deadline.
13
10
  */
14
- const LOOKUP_BUDGET_MS = 28_000;
11
+ const WRAP_UP_MS = 2000;
15
12
 
16
13
  /**
17
14
  * The whole graph, as one tool.
@@ -33,7 +30,8 @@ const LOOKUP_BUDGET_MS = 28_000;
33
30
  * really does exceed it: the model was handed
34
31
  * `{"error":"Tool \"answer_question\" timed out after 30000ms"}`, which tells
35
32
  * it nothing it can act on and reads to a caller as the line going dead.
36
- * `LOOKUP_BUDGET_MS` lands the overrun on the graph's OWN exit instead — the
33
+ * Budgeting under `ctx.deadlineAt` lands the overrun on the graph's OWN exit
34
+ * instead — the
37
35
  * same "offer to look again, or log a ticket" the design already has for an
38
36
  * interrupted run — so the slow path degrades into a sentence rather than into
39
37
  * an internal error. It does not make the loop faster; it makes running out
@@ -65,13 +63,15 @@ export default tool({
65
63
  try {
66
64
  // `ctx.signal` is what stops the graph on a barge-in: this loop is five
67
65
  // to nine model calls, and a caller who interrupts on the second should
68
- // not be charged for the rest. The budget rides alongside it — see the
69
- // module doc on `LOOKUP_BUDGET_MS` — and `AbortSignal.any` is what
70
- // combines the two without any unlink bookkeeping.
66
+ // not be charged for the rest. The budget rides alongside it and comes
67
+ // from `ctx.deadlineAt` — THIS call's deadline, so a host that gave this
68
+ // tool a different `timeoutMs` is followed rather than second-guessed —
69
+ // and `AbortSignal.any` combines the two with no unlink bookkeeping.
70
+ const budgetMs = Math.max(0, ctx.deadlineAt - Date.now() - WRAP_UP_MS);
71
71
  trace = await runCorrectiveRag(
72
72
  ctx.generate,
73
73
  args.question,
74
- AbortSignal.any([ctx.signal, AbortSignal.timeout(LOOKUP_BUDGET_MS)]),
74
+ AbortSignal.any([ctx.signal, AbortSignal.timeout(budgetMs)]),
75
75
  );
76
76
  } catch (err: unknown) {
77
77
  // An INTERRUPTED lookup is not a broken one, and the difference is worth
@@ -101,7 +101,7 @@ export default tool({
101
101
  // though the window could span a turn.
102
102
  supportSlot.update(ctx, (state) => {
103
103
  state.trace = trace;
104
- recordQuestion(state, args.question);
104
+ state.asked.push(args.question);
105
105
  });
106
106
 
107
107
  const sources = trace.docs.filter((doc) => doc.relevant).map((doc) => doc.title);
@@ -20,8 +20,8 @@
20
20
 
21
21
  import { readdir } from "node:fs/promises";
22
22
  import { tmpdir } from "node:os";
23
- import { stepReadUpload, type UploadRange } from "@alexkroman1/aai/step";
24
- import { FatalError, RetryableError } from "@alexkroman1/aai/step-errors";
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
25
  import { createWorkflowContext } from "@alexkroman1/aai/testing";
26
26
  import {
27
27
  installStubReporter,
@@ -40,7 +40,14 @@ import {
40
40
  NORMALIZED_SAMPLE_RATE,
41
41
  requestFormat,
42
42
  } from "./workflows/downsample.ts";
43
- import { cuttable, heavierThanNormalized, normalizeRecording } from "./workflows/normalize.ts";
43
+ import {
44
+ audioTrack,
45
+ cuttable,
46
+ encodeTargets,
47
+ heavierThanNormalized,
48
+ normalizeRecording,
49
+ requireWholeRecording,
50
+ } from "./workflows/normalize.ts";
44
51
  import { stitchChunks, stitchTranscript, TRANSCRIPT_STREAM } from "./workflows/stitch.ts";
45
52
  import {
46
53
  expectedSegments,
@@ -60,6 +67,7 @@ import {
60
67
  transcribeSegment,
61
68
  } from "./workflows/transcribe.ts";
62
69
  import {
70
+ assertCuttable,
63
71
  blockAlign,
64
72
  bytesPerSecond,
65
73
  MAX_BYTES_PER_SECOND,
@@ -102,7 +110,14 @@ function publishRecording(bytes: Uint8Array, name = "standup.wav") {
102
110
  /** 16 kHz mono 16-bit — one second of audio is 32,000 bytes. */
103
111
  const MONO_16K = { sampleRate: 16_000, channels: 1, bitsPerSample: 16 } as const;
104
112
 
105
- /** A canonical WAV header in front of `dataBytes` of (absent) samples. */
113
+ /**
114
+ * A canonical WAV header in front of `dataBytes` of (absent) samples.
115
+ *
116
+ * `WAV_HEADER_BYTES` (`@alexkroman1/aai/step`) is the length rather than a `44`
117
+ * typed here, because it is the same 44 the SDK's own `wavHeader` writes and
118
+ * `transcribeSegment` sends — this fixture and the code under test would
119
+ * otherwise agree by coincidence.
120
+ */
106
121
  function wavFile(
107
122
  fmt: { sampleRate: number; channels: number; bitsPerSample: number },
108
123
  dataBytes: number,
@@ -110,7 +125,7 @@ function wavFile(
110
125
  ): Uint8Array {
111
126
  const extra = overrides.extraChunk;
112
127
  const extraLength = extra === undefined ? 0 : 8 + extra.length + (extra.length % 2);
113
- const head = new Uint8Array(44 + extraLength);
128
+ const head = new Uint8Array(WAV_HEADER_BYTES + extraLength);
114
129
  const view = new DataView(head.buffer);
115
130
  const write = (at: number, text: string) => {
116
131
  for (let i = 0; i < text.length; i++) view.setUint8(at + i, text.charCodeAt(i));
@@ -291,17 +306,24 @@ describe("parseWav", () => {
291
306
  expect(() => parseWav(head, 44 + 320_000)).toThrow(/sample rate of 0/);
292
307
  });
293
308
 
294
- test("refuses a rate so high the overlap alone exceeds the request cap", () => {
309
+ test("assertCuttable refuses a rate so high the overlap alone exceeds the cap", () => {
295
310
  // The same hang from the other end: the overlap is subtracted from
296
311
  // MAX_SEGMENT_BYTES, so past MAX_BYTES_PER_SECOND the stride goes NEGATIVE
297
312
  // and the loop walks backwards. `sampleRate` is a uint32, so a header can
298
313
  // ask for this.
314
+ //
315
+ // The check is `assertCuttable`'s rather than `parseWav`'s now: the parse
316
+ // is the SDK's and answers whether this is READABLE WAV, where the cap is a
317
+ // property of the sync ENDPOINT this desk calls. Splitting them is what
318
+ // lets `cuttable` and `heavierThanNormalized` ask the two questions apart —
319
+ // a file that fails only the second is one downsampling repairs.
299
320
  const perSecond = MAX_BYTES_PER_SECOND + blockAlign(MONO_16K);
300
321
  const head = wavFile(
301
322
  { ...MONO_16K, sampleRate: Math.ceil(perSecond / blockAlign(MONO_16K)) },
302
323
  320_000,
303
324
  );
304
- expect(() => parseWav(head, 44 + 320_000)).toThrow(/bytes a second/);
325
+ expect(() => parseWav(head, 44 + 320_000)).not.toThrow();
326
+ expect(() => assertCuttable(parseWav(head, 44 + 320_000))).toThrow(/bytes a second/);
305
327
  });
306
328
 
307
329
  test("48 kHz 24-bit stereo — the realistic ceiling — is nowhere near the bound", () => {
@@ -787,14 +809,14 @@ describe("transcribeSegment", () => {
787
809
  expect(decoded).toContain("RIFF");
788
810
  // And the header is CONTIGUOUS with its samples, which is what the two-chunk
789
811
  // form (`[wavHeader(…), window]`) has to preserve and the only thing it could
790
- // plausibly lose: the part's payload is exactly the 44 bytes plus the window,
812
+ // plausibly lose: the part's payload is exactly the header plus the window,
791
813
  // with nothing between them and nothing appended. A body that grew or shrank
792
814
  // here is a file the endpoint decodes into confident nonsense rather than
793
815
  // refusing.
794
816
  const latin = new TextDecoder("latin1").decode(sent);
795
817
  const from = latin.indexOf("RIFF");
796
818
  const to = latin.lastIndexOf("\r\n--");
797
- expect(to - from).toBe(44 + (SEGMENT.end - SEGMENT.start));
819
+ expect(to - from).toBe(WAV_HEADER_BYTES + (SEGMENT.end - SEGMENT.start));
798
820
  });
799
821
 
800
822
  test("sends the DOWNSAMPLED window when the recording is heavier than 16 kHz mono", async () => {
@@ -828,7 +850,7 @@ describe("transcribeSegment", () => {
828
850
  // still declaring 48 kHz stereo is the one failure a byte count cannot see,
829
851
  // and it plays back at a third speed rather than failing.
830
852
  const at = new TextDecoder("latin1").decode(sent).indexOf("RIFF");
831
- const header = new DataView(sent.buffer, sent.byteOffset + at, 44);
853
+ const header = new DataView(sent.buffer, sent.byteOffset + at, WAV_HEADER_BYTES);
832
854
  expect(header.getUint16(22, true)).toBe(1);
833
855
  expect(header.getUint32(24, true)).toBe(16_000);
834
856
  expect(header.getUint32(40, true)).toBe(32_000);
@@ -938,11 +960,24 @@ describe("transcribeSegment", () => {
938
960
  expect(at).toBeLessThanOrEqual(30_000);
939
961
  });
940
962
 
941
- test("retries a rate limit that named no delay", async () => {
963
+ test("retries a rate limit that named no delay, after the class's own second", async () => {
964
+ // The OTHER half of the pair above, and the half `sync-api.ts`'s doc claims
965
+ // ("a bare `RetryableError` retries in ONE SECOND — that class's own
966
+ // default") while nothing pinned it. `DEFAULT_RETRY_DELAY_MS`
967
+ // (`@alexkroman1/aai/step-errors`) is that second, read from the SDK rather
968
+ // than typed here: a class that quietly changed its default would otherwise
969
+ // leave the sentence in the template's doc false with every test green.
942
970
  stubProvider({ status: 429, message: "slow down" });
943
- await expect(transcribeSegment(UPLOAD_ID, FORMAT, SEGMENT)).rejects.toBeInstanceOf(
944
- RetryableError,
971
+ const before = Date.now();
972
+ const failure = await transcribeSegment(UPLOAD_ID, FORMAT, SEGMENT).catch(
973
+ (err: unknown) => err,
945
974
  );
975
+ expect(failure).toBeInstanceOf(RetryableError);
976
+ const at = (failure as RetryableError).retryAfter.getTime();
977
+ expect(at).toBeGreaterThanOrEqual(before + DEFAULT_RETRY_DELAY_MS);
978
+ // Generous on the far side: the only thing between the two clock reads is
979
+ // the throw, so anything past a second of slack would be a different bug.
980
+ expect(at).toBeLessThanOrEqual(Date.now() + DEFAULT_RETRY_DELAY_MS);
946
981
  });
947
982
 
948
983
  test("fails FATALLY on a rejected request, naming what the endpoint said", async () => {
@@ -1466,6 +1501,93 @@ describe("normalizing the recording", () => {
1466
1501
  expect(reporter.lines.join(" ")).toContain("already linear-PCM WAV");
1467
1502
  });
1468
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
+
1469
1591
  // The ffmpeg VERDICT is no longer tested here, and its absence is the change
1470
1592
  // rather than a gap: `throwFfmpegStepError` on `@alexkroman1/aai/step-errors`
1471
1593
  // owns it now, with every arm pinned in `sdk/step-errors.test.ts` — a refused